Merge remote branch 'canonical/master' into merge-20140827
[civicrm-core.git] / CRM / Price / BAO / LineItem.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
06b69b18 4 | CiviCRM version 4.5 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26*/
27
28/**
29 *
30 * @package CRM
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35
36/**
37 *
38 * @package CRM
39 * @author Marshal Newrock <marshal@idealso.com>
40 * $Id$
41 */
42
43/**
44 * Business objects for Line Items generated by monetary transactions
45 */
46class CRM_Price_BAO_LineItem extends CRM_Price_DAO_LineItem {
47
48 /**
49 * Creates a new entry in the database.
50 *
51 * @param array $params (reference) an assoc array of name/value pairs
52 *
53 * @return object CRM_Price_DAO_LineItem object
54 * @access public
55 * @static
56 */
57 static function create(&$params) {
22fe049d
PN
58 $id = CRM_Utils_Array::value('id', $params);
59 if ($id) {
60 CRM_Utils_Hook::pre('edit', 'LineItem', $id, $params);
61 }
62 else {
63 CRM_Utils_Hook::pre('create', 'LineItem', $params['entity_id'], $params);
64 }
65
66 // unset entity table and entity id in $params
67 // we never update the entity table and entity id during update mode
68 if ($id) {
69 unset($params['entity_id'], $params['entity_table']);
70 }
421dfaa6 71
6a488035
TO
72 $lineItemBAO = new CRM_Price_BAO_LineItem();
73 $lineItemBAO->copyValues($params);
74
75 $return = $lineItemBAO->save();
76
22fe049d
PN
77 if ($id) {
78 CRM_Utils_Hook::post('edit', 'LineItem', $id, $params);
79 }
80 else {
81 CRM_Utils_Hook::post('create', 'LineItem', $params['entity_id'], $params);
82 }
6a488035
TO
83
84 return $return;
85 }
86
87 /**
88 * Takes a bunch of params that are needed to match certain criteria and
89 * retrieves the relevant objects. Typically, the valid params are only
90 * price_field_id. This is the inverse function of create. It also
91 * stores all of the retrieved values in the default array.
92 *
93 * @param array $params (reference ) an assoc array of name/value pairs
94 * @param array $defaults (reference ) an assoc array to hold the flattened values
95 *
96 * @return object CRM_Price_BAO_LineItem object
97 * @access public
98 * @static
99 */
100 static function retrieve(&$params, &$defaults) {
101 $lineItem = new CRM_Price_BAO_LineItem();
102 $lineItem->copyValues($params);
103 if ($lineItem->find(TRUE)) {
104 CRM_Core_DAO::storeValues($lineItem, $defaults);
105 return $lineItem;
106 }
107 return NULL;
108 }
109
ffd93213
EM
110 /**
111 * @param $entityId
112 * @param $entityTable
113 *
114 * @return null|string
115 */
bc2eeabb 116 static function getLineTotal($entityId, $entityTable) {
5a18a545 117 $sqlLineItemTotal = "SELECT SUM(li.line_total + COALESCE(li.tax_amount,0))
bc2eeabb 118FROM civicrm_line_item li
ae53df5f
PJ
119WHERE li.entity_table = '{$entityTable}'
120AND li.entity_id = {$entityId}
121";
bc2eeabb
PJ
122 $lineItemTotal = CRM_Core_DAO::singleValueQuery($sqlLineItemTotal);
123 return $lineItemTotal;
124 }
125
6a488035
TO
126 /**
127 * Given a participant id/contribution id,
128 * return contribution/fee line items
129 *
130 * @param $entityId int participant/contribution id
131 * @param $entity string participant/contribution.
132 *
dd244018
EM
133 * @param null $isQuick
134 * @param bool $isQtyZero
0d6f29cd 135 * @param bool $relatedEntity
dd244018 136 *
6a488035
TO
137 * @return array of line items
138 */
0d6f29cd 139 static function getLineItems($entityId, $entity = 'participant', $isQuick = NULL , $isQtyZero = TRUE, $relatedEntity = FALSE) {
6a488035
TO
140 $selectClause = $whereClause = $fromClause = NULL;
141 $selectClause = "
142 SELECT li.id,
143 li.label,
a7886853 144 li.contribution_id,
6a488035
TO
145 li.qty,
146 li.unit_price,
147 li.line_total,
148 pf.label as field_title,
149 pf.html_type,
150 pfv.membership_type_id,
9c09f5b7 151 pfv.membership_num_terms,
6a488035
TO
152 li.price_field_id,
153 li.participant_count,
154 li.price_field_value_id,
bf45dbe8 155 li.financial_type_id,
9849720e 156 li.tax_amount,
6a488035
TO
157 pfv.description";
158
0d6f29cd 159 $condition = "li.entity_id = %2.id AND li.entity_table = 'civicrm_%2'";
160 if ($relatedEntity) {
161 $condition = "li.contribution_id = %2.id ";
162 }
163
6a488035
TO
164 $fromClause = "
165 FROM civicrm_%2 as %2
0d6f29cd 166 LEFT JOIN civicrm_line_item li ON ({$condition})
6a488035
TO
167 LEFT JOIN civicrm_price_field_value pfv ON ( pfv.id = li.price_field_value_id )
168 LEFT JOIN civicrm_price_field pf ON (pf.id = li.price_field_id )";
169 $whereClause = "
170 WHERE %2.id = %1";
171
e68f41a5
DG
172 $orderByClause = " ORDER BY pf.weight, pfv.weight";
173
6a488035
TO
174 if ($isQuick) {
175 $fromClause .= " LEFT JOIN civicrm_price_set cps on cps.id = pf.price_set_id ";
176 $whereClause .= " and cps.is_quick_config = 0";
177 }
d5397f2f
PJ
178
179 if (!$isQtyZero) {
180 $whereClause .= " and li.qty != 0";
181 }
182
6a488035
TO
183 $lineItems = array();
184
185 if (!$entityId || !$entity || !$fromClause) {
186 return $lineItems;
187 }
188
189 $params = array(
190 1 => array($entityId, 'Integer'),
191 2 => array($entity, 'Text'),
192 );
193
2feea3d1 194 $getTaxDetails = FALSE;
03b412ae
PB
195 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME,'contribution_invoice_settings');
196 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
e68f41a5 197 $dao = CRM_Core_DAO::executeQuery("$selectClause $fromClause $whereClause $orderByClause", $params);
6a488035
TO
198 while ($dao->fetch()) {
199 if (!$dao->id) {
200 continue;
201 }
202 $lineItems[$dao->id] = array(
203 'qty' => $dao->qty,
204 'label' => $dao->label,
205 'unit_price' => $dao->unit_price,
206 'line_total' => $dao->line_total,
207 'price_field_id' => $dao->price_field_id,
208 'participant_count' => $dao->participant_count,
209 'price_field_value_id' => $dao->price_field_value_id,
210 'field_title' => $dao->field_title,
211 'html_type' => $dao->html_type,
212 'description' => $dao->description,
213 'entity_id' => $entityId,
a7886853 214 'contribution_id' => $dao->contribution_id,
bf45dbe8 215 'financial_type_id' => $dao->financial_type_id,
6a488035 216 'membership_type_id' => $dao->membership_type_id,
9c09f5b7 217 'membership_num_terms' => $dao->membership_num_terms,
9849720e 218 'tax_amount' => $dao->tax_amount,
6a488035 219 );
9849720e
RK
220 $lineItems[$dao->id]['tax_rate'] = CRM_Price_BAO_LineItem::calculateTaxRate($lineItems[$dao->id]);
221 $lineItems[$dao->id]['subTotal'] = $lineItems[$dao->id]['qty'] * $lineItems[$dao->id]['unit_price'];
2feea3d1
PB
222 if ($lineItems[$dao->id]['tax_amount'] != '') {
223 $getTaxDetails = TRUE;
224 }
6a488035 225 }
03b412ae
PB
226 if ($invoicing) {
227 $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
228 $smarty = CRM_Core_Smarty::singleton();
229 $smarty->assign('taxTerm', $taxTerm);
230 $smarty->assign('getTaxDetails', $getTaxDetails);
231 }
6a488035
TO
232 return $lineItems;
233 }
234
235 /**
236 * This method will create the lineItem array required for
237 * processAmount method
238 *
239 * @param int $fid price set field id
240 * @param array $params referance to form values
241 * @param array $fields referance to array of fields belonging
242 * to the price set used for particular event
243 * @param array $values referance to the values array(
244 this is
245 * lineItem array)
246 *
247 * @return void
248 * @access static
249 */
250 static function format($fid, &$params, &$fields, &$values) {
251 if (empty($params["price_{$fid}"])) {
252 return;
253 }
254
255 $optionIDs = implode(',', array_keys($params["price_{$fid}"]));
256
257 //lets first check in fun parameter,
258 //since user might modified w/ hooks.
259 $options = array();
260 if (array_key_exists('options', $fields)) {
261 $options = $fields['options'];
262 }
263 else {
9da8dc8c 264 CRM_Price_BAO_PriceFieldValue::getValues($fid, $options, 'weight', TRUE);
6a488035
TO
265 }
266 $fieldTitle = CRM_Utils_Array::value('label', $fields);
267 if (!$fieldTitle) {
9da8dc8c 268 $fieldTitle = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'label');
6a488035
TO
269 }
270
271 foreach ($params["price_{$fid}"] as $oid => $qty) {
272 $price = $options[$oid]['amount'];
273
274 // lets clean the price in case it is not yet cleant
275 // CRM-10974
276 $price = CRM_Utils_Rule::cleanMoney($price);
277
278 $participantsPerField = CRM_Utils_Array::value('count', $options[$oid], 0);
279
280 $values[$oid] = array(
281 'price_field_id' => $fid,
282 'price_field_value_id' => $oid,
283 'label' => CRM_Utils_Array::value('label', $options[$oid]),
284 'field_title' => $fieldTitle,
285 'description' => CRM_Utils_Array::value('description', $options[$oid]),
286 'qty' => $qty,
287 'unit_price' => $price,
288 'line_total' => $qty * $price,
289 'participant_count' => $qty * $participantsPerField,
290 'max_value' => CRM_Utils_Array::value('max_value', $options[$oid]),
291 'membership_type_id' => CRM_Utils_Array::value('membership_type_id', $options[$oid]),
292 'membership_num_terms' => CRM_Utils_Array::value('membership_num_terms', $options[$oid]),
293 'auto_renew' => CRM_Utils_Array::value('auto_renew', $options[$oid]),
294 'html_type' => $fields['html_type'],
bf45dbe8 295 'financial_type_id' => CRM_Utils_Array::value('financial_type_id', $options[$oid]),
5a18a545 296 'tax_amount' => CRM_Utils_Array::value('tax_amount', $options[$oid]),
6a488035 297 );
cdeb4bdf 298
e03317f1 299 if ($values[$oid]['membership_type_id'] && empty($values[$oid]['auto_renew'])) {
421dfaa6 300 $values[$oid]['auto_renew'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $values[$oid]['membership_type_id'], 'auto_renew');
6a488035
TO
301 }
302 }
303 }
304
305 /**
306 * Delete line items for given entity.
307 *
308 * @param int $entityId
309 * @param int $entityTable
310 *
77b97be7 311 * @return bool
6a488035
TO
312 * @access public
313 * @static
314 */
421dfaa6 315 public static function deleteLineItems($entityId, $entityTable) {
6a488035 316 if (!$entityId || !$entityTable) {
9330406e 317 return FALSE;
6a488035
TO
318 }
319
320 if ($entityId && !is_array($entityId)) {
321 $entityId = array($entityId);
322 }
323
de1c25e1 324 $query = "DELETE FROM civicrm_line_item where entity_id IN ('" . implode("','", $entityId) . "') AND entity_table = '$entityTable'";
6a488035 325 $dao = CRM_Core_DAO::executeQuery($query);
9330406e 326 return TRUE;
6a488035
TO
327 }
328
329 /**
330 * Function to process price set and line items.
dd244018
EM
331 *
332 * @param $entityId
6a488035
TO
333 * @param array $lineItem line item array
334 * @param object $contributionDetails
6a488035
TO
335 * @param string $entityTable entity table
336 *
dd244018
EM
337 * @param bool $update
338 *
339 * @internal param int $contributionId contribution id
340 * @internal param \decimal $initAmount amount
6a488035
TO
341 * @access public
342 * @return void
343 * @static
344 */
345 static function processPriceSet($entityId, $lineItem, $contributionDetails = NULL, $entityTable = 'civicrm_contribution', $update = FALSE) {
346 if (!$entityId || !is_array($lineItem)
347 || CRM_Utils_system::isNull($lineItem)
348 ) {
349 return;
350 }
421dfaa6 351
6a488035
TO
352 foreach ($lineItem as $priceSetId => $values) {
353 if (!$priceSetId) {
354 continue;
355 }
356
357 foreach ($values as $line) {
358 $line['entity_table'] = $entityTable;
359 $line['entity_id'] = $entityId;
8aa7457a
EM
360 if(!empty($line['membership_type_id'])) {
361 $entityTable == 'civicrm_membership';
362 $line['contribution_id'] = $contributionDetails->id;
363 }
a7886853
E
364 if ($entityTable == 'civicrm_contribution') {
365 $line['contribution_id'] = $entityId;
366 }
367 else {
7d3f62f6
C
368 if (!empty($contributionDetails->id)) {
369 $line['contribution_id'] = $contributionDetails->id;
370 }
a7886853 371 }
6a488035
TO
372 // if financial type is not set and if price field value is NOT NULL
373 // get financial type id of price field value
8cc574cf 374 if (!empty($line['price_field_value_id']) && empty($line['financial_type_id'])) {
9da8dc8c 375 $line['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $line['price_field_value_id'], 'financial_type_id');
6a488035
TO
376 }
377 $lineItems = CRM_Price_BAO_LineItem::create($line);
378 if (!$update && $contributionDetails) {
379 CRM_Financial_BAO_FinancialItem::add($lineItems, $contributionDetails);
c40e1ff4 380 if (isset($line['tax_amount'])) {
0b7bd9dd 381 CRM_Financial_BAO_FinancialItem::add($lineItems, $contributionDetails, TRUE);
382 }
6a488035
TO
383 }
384 }
385 }
421dfaa6 386 }
6a488035 387
ffd93213
EM
388 /**
389 * @param $entityId
390 * @param string $entityTable
391 * @param $amount
392 * @param null $otherParams
393 */
6a488035
TO
394 public static function syncLineItems($entityId, $entityTable = 'civicrm_contribution', $amount, $otherParams = NULL) {
395 if (!$entityId || CRM_Utils_System::isNull($amount))
396 return;
397
398 $from = " civicrm_line_item li
399 LEFT JOIN civicrm_price_field pf ON pf.id = li.price_field_id
400 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id ";
401
421dfaa6 402 $set = " li.unit_price = %3,
6a488035
TO
403 li.line_total = %3 ";
404
421dfaa6 405 $where = " li.entity_id = %1 AND
6a488035
TO
406 li.entity_table = %2 ";
407
408 $params = array(
409 1 => array($entityId, 'Integer'),
410 2 => array($entityTable, 'String'),
411 3 => array($amount, 'Float'),
412 );
413
414 if ($entityTable == 'civicrm_contribution') {
415 $entityName = 'default_contribution_amount';
416 $where .= " AND ps.name = %4 ";
421dfaa6 417 $params[4] = array($entityName, 'String');
418 }
6a488035
TO
419 elseif ($entityTable == 'civicrm_participant') {
420 $from .= "
421 LEFT JOIN civicrm_price_set_entity cpse ON cpse.price_set_id = ps.id
422 LEFT JOIN civicrm_price_field_value cpfv ON cpfv.price_field_id = pf.id and cpfv.label = %4 ";
423 $set .= " ,li.label = %4,
424 li.price_field_value_id = cpfv.id ";
425 $where .= " AND cpse.entity_table = 'civicrm_event' AND cpse.entity_id = %5 ";
426 $amount = empty($amount) ? 0: $amount;
427 $params += array(
428 4 => array($otherParams['fee_label'], 'String'),
429 5 => array($otherParams['event_id'], 'String'),
430 );
431 }
432
421dfaa6 433 $query = "
6a488035
TO
434 UPDATE $from
435 SET $set
421dfaa6 436 WHERE $where
6a488035
TO
437 ";
438
439 CRM_Core_DAO::executeQuery($query, $params);
440 }
441
442 /**
443 * Function to build line items array.
62c4420e 444 * @param array $params form values
6a488035
TO
445 *
446 * @param string $entityId entity id
447 *
448 * @param string $entityTable entity Table
449 *
450 * @access public
451 * @return void
452 * @static
453 */
454 static function getLineItemArray(&$params, $entityId = NULL, $entityTable = 'contribution') {
421dfaa6 455
6a488035 456 if (!$entityId) {
9da8dc8c 457 $priceSetDetails = CRM_Price_BAO_PriceSet::getDefaultPriceSet();
6a488035
TO
458 foreach ($priceSetDetails as $values) {
459 $params['line_item'][$values['setID']][$values['priceFieldID']] = array(
460 'price_field_id' => $values['priceFieldID'],
461 'price_field_value_id' => $values['priceFieldValueID'],
462 'label' => $values['label'],
463 'qty' => 1,
464 'unit_price' => $params['total_amount'],
465 'line_total' => $params['total_amount'],
466 'financial_type_id' => $params['financial_type_id']
467 );
468 }
421dfaa6 469 }
6a488035
TO
470 else {
471 $setID = NULL;
464bb009
PN
472 $totalEntityId = count($entityId);
473 foreach ($entityId as $id) {
474 $lineItems = CRM_Price_BAO_LineItem::getLineItems($id, $entityTable);
475 foreach ($lineItems as $key => $values) {
32cb2feb 476 if (!$setID && $values['price_field_id']) {
9da8dc8c 477 $setID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $values['price_field_id'], 'price_set_id');
478 $params['is_quick_config'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $setID, 'is_quick_config');
464bb009 479 }
a7488080 480 if (!empty($params['is_quick_config']) && array_key_exists('total_amount', $params)
464bb009
PN
481 && $totalEntityId == 1) {
482 $values['line_total'] = $values['unit_price'] = $params['total_amount'];
483 }
484 $values['id'] = $key;
485 $params['line_item'][$setID][$key] = $values;
6a488035 486 }
6a488035
TO
487 }
488 }
489 }
9849720e
RK
490
491 /**
2826a42e
RK
492 * Calculate tax rate in percentage
493 *
494 * @param $lineItemId an assoc array of lineItem
495 *
496 * @return tax rate
497 *
498 * @access public
499 * @static
9849720e
RK
500 */
501 public static function calculateTaxRate($lineItemId) {
502 if ($lineItemId['html_type'] == 'Text') {
e9a531f7 503 $tax = $lineItemId['tax_amount']/($lineItemId['unit_price'] * $lineItemId['qty'])*100;
9849720e
RK
504 }
505 else {
e9a531f7 506 $tax = ($lineItemId['tax_amount']/$lineItemId['unit_price']) * 100;
9849720e
RK
507 }
508 return $tax;
509 }
6a488035 510}