Merge pull request #4651 from jitendrapurohit/CRM-15559
[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 *
c490a46a 53 * @return CRM_Price_DAO_LineItem object
6a488035
TO
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 }
c206647d 65
22fe049d
PN
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 *
c490a46a 96 * @return CRM_Price_BAO_LineItem object
6a488035
TO
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 110 /**
100fef9d 111 * @param int $entityId
ffd93213
EM
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
34a100a7 126 /**
100fef9d
CW
127 * Wrapper for line item retrieval when contribution ID is known
128 * @param int $contributionID
34a100a7
EM
129 *
130 * @return array
131 */
132 static function getLineItemsByContributionID($contributionID) {
133 return self::getLineItems($contributionID,'contribution', NULL, TRUE, TRUE, " WHERE contribution_id = " . (int) $contributionID);
134 }
135
6a488035
TO
136 /**
137 * Given a participant id/contribution id,
138 * return contribution/fee line items
139 *
140 * @param $entityId int participant/contribution id
141 * @param $entity string participant/contribution.
142 *
dd244018
EM
143 * @param null $isQuick
144 * @param bool $isQtyZero
0d6f29cd 145 * @param bool $relatedEntity
dd244018 146 *
34a100a7
EM
147 * @param string $overrideWhereClause e.g "WHERE contribution id = 7 " per the getLineItemsByContributionID wrapper.
148 * this function precedes the convenience of the contribution id but since it does quite a bit more than just a db retrieval we need to be able to use it even
149 * when we don't want it's entity-id magix
150 *
6a488035
TO
151 * @return array of line items
152 */
34a100a7
EM
153 static function getLineItems($entityId, $entity = 'participant', $isQuick = NULL , $isQtyZero = TRUE, $relatedEntity = FALSE, $overrideWhereClause = '') {
154 $whereClause = $fromClause = NULL;
6a488035
TO
155 $selectClause = "
156 SELECT li.id,
157 li.label,
a7886853 158 li.contribution_id,
6a488035
TO
159 li.qty,
160 li.unit_price,
161 li.line_total,
34a100a7
EM
162 li.entity_table,
163 li.entity_id,
6a488035
TO
164 pf.label as field_title,
165 pf.html_type,
166 pfv.membership_type_id,
9c09f5b7 167 pfv.membership_num_terms,
6a488035
TO
168 li.price_field_id,
169 li.participant_count,
170 li.price_field_value_id,
bf45dbe8 171 li.financial_type_id,
9849720e 172 li.tax_amount,
6a488035
TO
173 pfv.description";
174
0d6f29cd 175 $condition = "li.entity_id = %2.id AND li.entity_table = 'civicrm_%2'";
176 if ($relatedEntity) {
177 $condition = "li.contribution_id = %2.id ";
178 }
179
6a488035
TO
180 $fromClause = "
181 FROM civicrm_%2 as %2
0d6f29cd 182 LEFT JOIN civicrm_line_item li ON ({$condition})
6a488035
TO
183 LEFT JOIN civicrm_price_field_value pfv ON ( pfv.id = li.price_field_value_id )
184 LEFT JOIN civicrm_price_field pf ON (pf.id = li.price_field_id )";
185 $whereClause = "
186 WHERE %2.id = %1";
187
e68f41a5
DG
188 $orderByClause = " ORDER BY pf.weight, pfv.weight";
189
6a488035
TO
190 if ($isQuick) {
191 $fromClause .= " LEFT JOIN civicrm_price_set cps on cps.id = pf.price_set_id ";
192 $whereClause .= " and cps.is_quick_config = 0";
193 }
d5397f2f
PJ
194
195 if (!$isQtyZero) {
196 $whereClause .= " and li.qty != 0";
197 }
198
6a488035
TO
199 $lineItems = array();
200
201 if (!$entityId || !$entity || !$fromClause) {
202 return $lineItems;
203 }
204
205 $params = array(
206 1 => array($entityId, 'Integer'),
207 2 => array($entity, 'Text'),
208 );
209
2feea3d1 210 $getTaxDetails = FALSE;
03b412ae
PB
211 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME,'contribution_invoice_settings');
212 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
34a100a7
EM
213 if ($overrideWhereClause) {
214 $whereClause = $overrideWhereClause;
215 }
216
e68f41a5 217 $dao = CRM_Core_DAO::executeQuery("$selectClause $fromClause $whereClause $orderByClause", $params);
6a488035
TO
218 while ($dao->fetch()) {
219 if (!$dao->id) {
220 continue;
221 }
222 $lineItems[$dao->id] = array(
223 'qty' => $dao->qty,
224 'label' => $dao->label,
225 'unit_price' => $dao->unit_price,
226 'line_total' => $dao->line_total,
227 'price_field_id' => $dao->price_field_id,
228 'participant_count' => $dao->participant_count,
229 'price_field_value_id' => $dao->price_field_value_id,
230 'field_title' => $dao->field_title,
231 'html_type' => $dao->html_type,
232 'description' => $dao->description,
34a100a7
EM
233 // the entity id seems prone to randomness but not sure if it has a reason - so if we are overriding the Where clause we assume
234 // we also JUST WANT TO KNOW the the entity_id in the DB
235 'entity_id' => empty($overrideWhereClause) ? $entityId : $dao->entity_id,
236 'entity_table' => $dao->entity_table,
a7886853 237 'contribution_id' => $dao->contribution_id,
bf45dbe8 238 'financial_type_id' => $dao->financial_type_id,
6a488035 239 'membership_type_id' => $dao->membership_type_id,
9c09f5b7 240 'membership_num_terms' => $dao->membership_num_terms,
9849720e 241 'tax_amount' => $dao->tax_amount,
6a488035 242 );
9849720e
RK
243 $lineItems[$dao->id]['tax_rate'] = CRM_Price_BAO_LineItem::calculateTaxRate($lineItems[$dao->id]);
244 $lineItems[$dao->id]['subTotal'] = $lineItems[$dao->id]['qty'] * $lineItems[$dao->id]['unit_price'];
2feea3d1
PB
245 if ($lineItems[$dao->id]['tax_amount'] != '') {
246 $getTaxDetails = TRUE;
247 }
6a488035 248 }
03b412ae
PB
249 if ($invoicing) {
250 $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
251 $smarty = CRM_Core_Smarty::singleton();
252 $smarty->assign('taxTerm', $taxTerm);
253 $smarty->assign('getTaxDetails', $getTaxDetails);
254 }
6a488035
TO
255 return $lineItems;
256 }
257
258 /**
259 * This method will create the lineItem array required for
260 * processAmount method
261 *
262 * @param int $fid price set field id
c206647d
EM
263 * @param array $params reference to form values
264 * @param array $fields reference to array of fields belonging
6a488035 265 * to the price set used for particular event
c206647d 266 * @param array $values reference to the values array(
6a488035
TO
267 this is
268 * lineItem array)
269 *
270 * @return void
271 * @access static
272 */
273 static function format($fid, &$params, &$fields, &$values) {
274 if (empty($params["price_{$fid}"])) {
275 return;
276 }
277
278 $optionIDs = implode(',', array_keys($params["price_{$fid}"]));
279
280 //lets first check in fun parameter,
281 //since user might modified w/ hooks.
282 $options = array();
283 if (array_key_exists('options', $fields)) {
284 $options = $fields['options'];
285 }
286 else {
9da8dc8c 287 CRM_Price_BAO_PriceFieldValue::getValues($fid, $options, 'weight', TRUE);
6a488035
TO
288 }
289 $fieldTitle = CRM_Utils_Array::value('label', $fields);
290 if (!$fieldTitle) {
9da8dc8c 291 $fieldTitle = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'label');
6a488035
TO
292 }
293
294 foreach ($params["price_{$fid}"] as $oid => $qty) {
295 $price = $options[$oid]['amount'];
296
297 // lets clean the price in case it is not yet cleant
298 // CRM-10974
299 $price = CRM_Utils_Rule::cleanMoney($price);
300
301 $participantsPerField = CRM_Utils_Array::value('count', $options[$oid], 0);
302
303 $values[$oid] = array(
304 'price_field_id' => $fid,
305 'price_field_value_id' => $oid,
306 'label' => CRM_Utils_Array::value('label', $options[$oid]),
307 'field_title' => $fieldTitle,
308 'description' => CRM_Utils_Array::value('description', $options[$oid]),
309 'qty' => $qty,
310 'unit_price' => $price,
311 'line_total' => $qty * $price,
312 'participant_count' => $qty * $participantsPerField,
313 'max_value' => CRM_Utils_Array::value('max_value', $options[$oid]),
314 'membership_type_id' => CRM_Utils_Array::value('membership_type_id', $options[$oid]),
315 'membership_num_terms' => CRM_Utils_Array::value('membership_num_terms', $options[$oid]),
316 'auto_renew' => CRM_Utils_Array::value('auto_renew', $options[$oid]),
317 'html_type' => $fields['html_type'],
bf45dbe8 318 'financial_type_id' => CRM_Utils_Array::value('financial_type_id', $options[$oid]),
5a18a545 319 'tax_amount' => CRM_Utils_Array::value('tax_amount', $options[$oid]),
6a488035 320 );
cdeb4bdf 321
e03317f1 322 if ($values[$oid]['membership_type_id'] && empty($values[$oid]['auto_renew'])) {
421dfaa6 323 $values[$oid]['auto_renew'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $values[$oid]['membership_type_id'], 'auto_renew');
6a488035
TO
324 }
325 }
326 }
327
328 /**
329 * Delete line items for given entity.
330 *
331 * @param int $entityId
332 * @param int $entityTable
333 *
77b97be7 334 * @return bool
6a488035
TO
335 * @access public
336 * @static
337 */
421dfaa6 338 public static function deleteLineItems($entityId, $entityTable) {
6a488035 339 if (!$entityId || !$entityTable) {
9330406e 340 return FALSE;
6a488035
TO
341 }
342
343 if ($entityId && !is_array($entityId)) {
344 $entityId = array($entityId);
345 }
346
de1c25e1 347 $query = "DELETE FROM civicrm_line_item where entity_id IN ('" . implode("','", $entityId) . "') AND entity_table = '$entityTable'";
6a488035 348 $dao = CRM_Core_DAO::executeQuery($query);
9330406e 349 return TRUE;
6a488035
TO
350 }
351
352 /**
100fef9d 353 * Process price set and line items.
dd244018 354 *
100fef9d 355 * @param int $entityId
6a488035
TO
356 * @param array $lineItem line item array
357 * @param object $contributionDetails
6a488035
TO
358 * @param string $entityTable entity table
359 *
dd244018
EM
360 * @param bool $update
361 *
6a488035
TO
362 * @access public
363 * @return void
364 * @static
365 */
366 static function processPriceSet($entityId, $lineItem, $contributionDetails = NULL, $entityTable = 'civicrm_contribution', $update = FALSE) {
367 if (!$entityId || !is_array($lineItem)
368 || CRM_Utils_system::isNull($lineItem)
369 ) {
370 return;
371 }
421dfaa6 372
6a488035
TO
373 foreach ($lineItem as $priceSetId => $values) {
374 if (!$priceSetId) {
375 continue;
376 }
377
378 foreach ($values as $line) {
379 $line['entity_table'] = $entityTable;
34a100a7
EM
380 if (empty($line['entity_id'])) {
381 $line['entity_id'] = $entityId;
382 }
8aa7457a 383 if(!empty($line['membership_type_id'])) {
79ebec7b 384 $line['entity_table'] = 'civicrm_membership';
8aa7457a 385 }
79ebec7b
PN
386 if (!empty($contributionDetails->id)) {
387 $line['contribution_id'] = $contributionDetails->id;
388 if ($line['entity_table'] == 'civicrm_contribution') {
389 $line['entity_id'] = $contributionDetails->id;
7d3f62f6 390 }
a7886853 391 }
c206647d 392
6a488035
TO
393 // if financial type is not set and if price field value is NOT NULL
394 // get financial type id of price field value
8cc574cf 395 if (!empty($line['price_field_value_id']) && empty($line['financial_type_id'])) {
9da8dc8c 396 $line['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $line['price_field_value_id'], 'financial_type_id');
6a488035
TO
397 }
398 $lineItems = CRM_Price_BAO_LineItem::create($line);
399 if (!$update && $contributionDetails) {
400 CRM_Financial_BAO_FinancialItem::add($lineItems, $contributionDetails);
c40e1ff4 401 if (isset($line['tax_amount'])) {
0b7bd9dd 402 CRM_Financial_BAO_FinancialItem::add($lineItems, $contributionDetails, TRUE);
403 }
6a488035
TO
404 }
405 }
406 }
421dfaa6 407 }
6a488035 408
ffd93213 409 /**
100fef9d 410 * @param int $entityId
ffd93213
EM
411 * @param string $entityTable
412 * @param $amount
100fef9d 413 * @param array $otherParams
ffd93213 414 */
6a488035
TO
415 public static function syncLineItems($entityId, $entityTable = 'civicrm_contribution', $amount, $otherParams = NULL) {
416 if (!$entityId || CRM_Utils_System::isNull($amount))
417 return;
418
419 $from = " civicrm_line_item li
420 LEFT JOIN civicrm_price_field pf ON pf.id = li.price_field_id
421 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id ";
422
421dfaa6 423 $set = " li.unit_price = %3,
6a488035
TO
424 li.line_total = %3 ";
425
421dfaa6 426 $where = " li.entity_id = %1 AND
6a488035
TO
427 li.entity_table = %2 ";
428
429 $params = array(
430 1 => array($entityId, 'Integer'),
431 2 => array($entityTable, 'String'),
432 3 => array($amount, 'Float'),
433 );
434
435 if ($entityTable == 'civicrm_contribution') {
436 $entityName = 'default_contribution_amount';
437 $where .= " AND ps.name = %4 ";
421dfaa6 438 $params[4] = array($entityName, 'String');
439 }
6a488035
TO
440 elseif ($entityTable == 'civicrm_participant') {
441 $from .= "
442 LEFT JOIN civicrm_price_set_entity cpse ON cpse.price_set_id = ps.id
443 LEFT JOIN civicrm_price_field_value cpfv ON cpfv.price_field_id = pf.id and cpfv.label = %4 ";
444 $set .= " ,li.label = %4,
445 li.price_field_value_id = cpfv.id ";
446 $where .= " AND cpse.entity_table = 'civicrm_event' AND cpse.entity_id = %5 ";
447 $amount = empty($amount) ? 0: $amount;
448 $params += array(
449 4 => array($otherParams['fee_label'], 'String'),
450 5 => array($otherParams['event_id'], 'String'),
451 );
452 }
453
421dfaa6 454 $query = "
6a488035
TO
455 UPDATE $from
456 SET $set
421dfaa6 457 WHERE $where
6a488035
TO
458 ";
459
460 CRM_Core_DAO::executeQuery($query, $params);
461 }
462
463 /**
100fef9d 464 * Build line items array.
62c4420e 465 * @param array $params form values
6a488035
TO
466 *
467 * @param string $entityId entity id
468 *
469 * @param string $entityTable entity Table
470 *
471 * @access public
472 * @return void
473 * @static
474 */
79ebec7b 475 static function getLineItemArray(&$params, $entityId = NULL, $entityTable = 'contribution', $isRelatedID = FALSE) {
421dfaa6 476
6a488035 477 if (!$entityId) {
82cc6775
PN
478 $priceSetDetails = CRM_Price_BAO_PriceSet::getDefaultPriceSet($entityTable);
479 $totalAmount = CRM_Utils_Array::value('total_amount', $params);
480 $financialType = CRM_Utils_Array::value('financial_type_id', $params);
6a488035 481 foreach ($priceSetDetails as $values) {
c206647d 482 if ($entityTable == 'membership') {
82cc6775
PN
483 if ($isRelatedID != $values['membership_type_id']) {
484 continue;
485 }
486 if (!$totalAmount) {
487 $totalAmount = $values['amount'];
488 }
489 $financialType = $values['financial_type_id'];
490 }
6a488035
TO
491 $params['line_item'][$values['setID']][$values['priceFieldID']] = array(
492 'price_field_id' => $values['priceFieldID'],
493 'price_field_value_id' => $values['priceFieldValueID'],
494 'label' => $values['label'],
495 'qty' => 1,
82cc6775
PN
496 'unit_price' => $totalAmount,
497 'line_total' => $totalAmount,
498 'financial_type_id' => $financialType,
499 'membership_type_id' => $values['membership_type_id']
6a488035 500 );
82cc6775 501 break;
6a488035 502 }
421dfaa6 503 }
6a488035
TO
504 else {
505 $setID = NULL;
464bb009
PN
506 $totalEntityId = count($entityId);
507 foreach ($entityId as $id) {
79ebec7b 508 $lineItems = CRM_Price_BAO_LineItem::getLineItems($id, $entityTable, NULL, TRUE, $isRelatedID);
464bb009 509 foreach ($lineItems as $key => $values) {
32cb2feb 510 if (!$setID && $values['price_field_id']) {
9da8dc8c 511 $setID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $values['price_field_id'], 'price_set_id');
512 $params['is_quick_config'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $setID, 'is_quick_config');
464bb009 513 }
a7488080 514 if (!empty($params['is_quick_config']) && array_key_exists('total_amount', $params)
464bb009
PN
515 && $totalEntityId == 1) {
516 $values['line_total'] = $values['unit_price'] = $params['total_amount'];
517 }
518 $values['id'] = $key;
519 $params['line_item'][$setID][$key] = $values;
6a488035 520 }
6a488035
TO
521 }
522 }
523 }
9849720e
RK
524
525 /**
2826a42e
RK
526 * Calculate tax rate in percentage
527 *
528 * @param $lineItemId an assoc array of lineItem
529 *
530 * @return tax rate
531 *
532 * @access public
533 * @static
9849720e
RK
534 */
535 public static function calculateTaxRate($lineItemId) {
536 if ($lineItemId['html_type'] == 'Text') {
e9a531f7 537 $tax = $lineItemId['tax_amount']/($lineItemId['unit_price'] * $lineItemId['qty'])*100;
9849720e
RK
538 }
539 else {
e9a531f7 540 $tax = ($lineItemId['tax_amount']/$lineItemId['unit_price']) * 100;
9849720e
RK
541 }
542 return $tax;
543 }
6a488035 544}