Merge pull request #9554 from colemanw/CRM-19769
[civicrm-core.git] / CRM / Price / BAO / LineItem.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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
31 * @copyright CiviCRM LLC (c) 2004-2016
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 */
46 class CRM_Price_BAO_LineItem extends CRM_Price_DAO_LineItem {
47
48 /**
49 * Creates a new entry in the database.
50 *
51 * @param array $params
52 * (reference) an assoc array of name/value pairs.
53 *
54 * @return \CRM_Price_DAO_LineItem
55 *
56 * @throws \CiviCRM_API3_Exception
57 * @throws \Exception
58 */
59 public static function create(&$params) {
60 $id = CRM_Utils_Array::value('id', $params);
61 if ($id) {
62 CRM_Utils_Hook::pre('edit', 'LineItem', $id, $params);
63 $op = CRM_Core_Action::UPDATE;
64 }
65 else {
66 CRM_Utils_Hook::pre('create', 'LineItem', $params['entity_id'], $params);
67 $op = CRM_Core_Action::ADD;
68 }
69
70 // unset entity table and entity id in $params
71 // we never update the entity table and entity id during update mode
72 if ($id) {
73 unset($params['entity_id'], $params['entity_table']);
74 }
75 else {
76 if (!isset($params['unit_price'])) {
77 $params['unit_price'] = 0;
78 }
79 }
80 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus() && CRM_Utils_Array::value('check_permissions', $params)) {
81 if (empty($params['financial_type_id'])) {
82 throw new Exception('Mandatory key(s) missing from params array: financial_type_id');
83 }
84 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($types, $op);
85 if (!in_array($params['financial_type_id'], array_keys($types))) {
86 throw new Exception('You do not have permission to create this line item');
87 }
88 }
89
90 $lineItemBAO = new CRM_Price_BAO_LineItem();
91 $lineItemBAO->copyValues($params);
92
93 $return = $lineItemBAO->save();
94 if ($lineItemBAO->entity_table == 'civicrm_membership' && $lineItemBAO->contribution_id && $lineItemBAO->entity_id) {
95 $membershipPaymentParams = array(
96 'membership_id' => $lineItemBAO->entity_id,
97 'contribution_id' => $lineItemBAO->contribution_id,
98 );
99 if (!civicrm_api3('MembershipPayment', 'getcount', $membershipPaymentParams)) {
100 civicrm_api3('MembershipPayment', 'create', $membershipPaymentParams);
101 }
102 }
103
104 if ($id) {
105 CRM_Utils_Hook::post('edit', 'LineItem', $id, $lineItemBAO);
106 }
107 else {
108 CRM_Utils_Hook::post('create', 'LineItem', $lineItemBAO->id, $lineItemBAO);
109 }
110
111 return $return;
112 }
113
114 /**
115 * Retrieve DB object based on input parameters.
116 *
117 * It also stores all the retrieved values in the default array.
118 *
119 * @param array $params
120 * (reference ) an assoc array of name/value pairs.
121 * @param array $defaults
122 * (reference ) an assoc array to hold the flattened values.
123 *
124 * @return CRM_Price_BAO_LineItem
125 */
126 public static function retrieve(&$params, &$defaults) {
127 $lineItem = new CRM_Price_BAO_LineItem();
128 $lineItem->copyValues($params);
129 if ($lineItem->find(TRUE)) {
130 CRM_Core_DAO::storeValues($lineItem, $defaults);
131 return $lineItem;
132 }
133 return NULL;
134 }
135
136 /**
137 * Modifies $params array for filtering financial types.
138 *
139 * @param array $params
140 * (reference ) an assoc array of name/value pairs.
141 *
142 */
143 public static function getAPILineItemParams(&$params) {
144 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($types);
145 if ($types && empty($params['financial_type_id'])) {
146 $params['financial_type_id'] = array('IN' => array_keys($types));
147 }
148 elseif ($types) {
149 if (is_array($params['financial_type_id'])) {
150 $invalidFts = array_diff($params['financial_type_id'], array_keys($types));
151 }
152 elseif (!in_array($params['financial_type_id'], array_keys($types))) {
153 $invalidFts = $params['financial_type_id'];
154 }
155 if ($invalidFts) {
156 $params['financial_type_id'] = array('NOT IN' => $invalidFts);
157 }
158 }
159 else {
160 $params['financial_type_id'] = 0;
161 }
162 }
163
164 /**
165 * @param int $contributionId
166 *
167 * @return null|string
168 */
169 public static function getLineTotal($contributionId) {
170 $sqlLineItemTotal = "SELECT SUM(li.line_total + COALESCE(li.tax_amount,0))
171 FROM civicrm_line_item li
172 WHERE li.contribution_id = %1";
173 $params = array(1 => array($contributionId, 'Integer'));
174 $lineItemTotal = CRM_Core_DAO::singleValueQuery($sqlLineItemTotal, $params);
175 return $lineItemTotal;
176 }
177
178 /**
179 * Wrapper for line item retrieval when contribution ID is known.
180 * @param int $contributionID
181 *
182 * @return array
183 */
184 public static function getLineItemsByContributionID($contributionID) {
185 return self::getLineItems($contributionID, 'contribution', NULL, TRUE, TRUE, " WHERE contribution_id = " . (int) $contributionID);
186 }
187
188 /**
189 * Given a participant id/contribution id,
190 * return contribution/fee line items
191 *
192 * @param int $entityId
193 * participant/contribution id.
194 * @param string $entity
195 * participant/contribution.
196 *
197 * @param bool $isQuick
198 * @param bool $isQtyZero
199 * @param bool $relatedEntity
200 *
201 * @param bool $invoice
202 * @return array
203 * Array of line items
204 */
205 public static function getLineItems($entityId, $entity = 'participant', $isQuick = FALSE, $isQtyZero = TRUE, $relatedEntity = FALSE, $invoice = FALSE) {
206 $whereClause = $fromClause = NULL;
207 $selectClause = "
208 SELECT li.id,
209 li.label,
210 li.contribution_id,
211 li.qty,
212 li.unit_price,
213 li.line_total,
214 li.entity_table,
215 li.entity_id,
216 pf.label as field_title,
217 pf.html_type,
218 pf.price_set_id,
219 pfv.membership_type_id,
220 pfv.membership_num_terms,
221 li.price_field_id,
222 li.participant_count,
223 li.price_field_value_id,
224 li.financial_type_id,
225 li.tax_amount,
226 pfv.description";
227
228 $condition = "li.entity_id = %2.id AND li.entity_table = 'civicrm_%2'";
229 if ($relatedEntity) {
230 $condition = "li.contribution_id = %2.id ";
231 }
232
233 $fromClause = "
234 FROM civicrm_%2 as %2
235 LEFT JOIN civicrm_line_item li ON ({$condition})
236 LEFT JOIN civicrm_price_field_value pfv ON ( pfv.id = li.price_field_value_id )
237 LEFT JOIN civicrm_price_field pf ON (pf.id = li.price_field_id )";
238 $whereClause = "
239 WHERE %2.id = %1";
240
241 // CRM-16250 get additional participant's fee selection details only for invoice PDF (if any)
242 if ($entity == 'participant' && $invoice) {
243 $additionalParticipantIDs = CRM_Event_BAO_Participant::getAdditionalParticipantIds($entityId);
244 if (!empty($additionalParticipantIDs)) {
245 $whereClause = "WHERE %2.id IN (%1, " . implode(', ', $additionalParticipantIDs) . ")";
246 }
247 }
248
249 $orderByClause = " ORDER BY pf.weight, pfv.weight";
250
251 if ($isQuick) {
252 $fromClause .= " LEFT JOIN civicrm_price_set cps on cps.id = pf.price_set_id ";
253 $whereClause .= " and cps.is_quick_config = 0";
254 }
255
256 if (!$isQtyZero) {
257 $whereClause .= " and li.qty != 0";
258 }
259
260 $lineItems = array();
261
262 if (!$entityId || !$entity || !$fromClause) {
263 return $lineItems;
264 }
265
266 $params = array(
267 1 => array($entityId, 'Integer'),
268 2 => array($entity, 'Text'),
269 );
270
271 $getTaxDetails = FALSE;
272 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
273 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
274
275 $dao = CRM_Core_DAO::executeQuery("$selectClause $fromClause $whereClause $orderByClause", $params);
276 while ($dao->fetch()) {
277 if (!$dao->id) {
278 continue;
279 }
280 $lineItems[$dao->id] = array(
281 'qty' => (float) $dao->qty,
282 'label' => $dao->label,
283 'unit_price' => $dao->unit_price,
284 'line_total' => $dao->line_total,
285 'price_field_id' => $dao->price_field_id,
286 'participant_count' => $dao->participant_count,
287 'price_field_value_id' => $dao->price_field_value_id,
288 'field_title' => $dao->field_title,
289 'html_type' => $dao->html_type,
290 'description' => $dao->description,
291 'entity_id' => $dao->entity_id,
292 'entity_table' => $dao->entity_table,
293 'contribution_id' => $dao->contribution_id,
294 'financial_type_id' => $dao->financial_type_id,
295 'financial_type' => CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_Contribution', 'financial_type_id', $dao->financial_type_id),
296 'membership_type_id' => $dao->membership_type_id,
297 'membership_num_terms' => $dao->membership_num_terms,
298 'tax_amount' => $dao->tax_amount,
299 'price_set_id' => $dao->price_set_id,
300 );
301 $lineItems[$dao->id]['tax_rate'] = CRM_Price_BAO_LineItem::calculateTaxRate($lineItems[$dao->id]);
302 $lineItems[$dao->id]['subTotal'] = $lineItems[$dao->id]['qty'] * $lineItems[$dao->id]['unit_price'];
303 if ($lineItems[$dao->id]['tax_amount'] != '') {
304 $getTaxDetails = TRUE;
305 }
306 }
307 if ($invoicing) {
308 $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
309 $smarty = CRM_Core_Smarty::singleton();
310 $smarty->assign('taxTerm', $taxTerm);
311 $smarty->assign('getTaxDetails', $getTaxDetails);
312 }
313 return $lineItems;
314 }
315
316 /**
317 * This method will create the lineItem array required for
318 * processAmount method
319 *
320 * @param int $fid
321 * Price set field id.
322 * @param array $params
323 * Reference to form values.
324 * @param array $fields
325 * Array of fields belonging to the price set used for particular event
326 * @param array $values
327 * Reference to the values array(.
328 * this is
329 * lineItem array)
330 * @param string $amount_override
331 */
332 public static function format($fid, $params, $fields, &$values, $amount_override = NULL) {
333 if (empty($params["price_{$fid}"])) {
334 return;
335 }
336
337 //lets first check in fun parameter,
338 //since user might modified w/ hooks.
339 $options = array();
340 if (array_key_exists('options', $fields)) {
341 $options = $fields['options'];
342 }
343 else {
344 CRM_Price_BAO_PriceFieldValue::getValues($fid, $options, 'weight', TRUE);
345 }
346 $fieldTitle = CRM_Utils_Array::value('label', $fields);
347 if (!$fieldTitle) {
348 $fieldTitle = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'label');
349 }
350
351 foreach ($params["price_{$fid}"] as $oid => $qty) {
352 $price = $amount_override === NULL ? $options[$oid]['amount'] : $amount_override;
353
354 // lets clean the price in case it is not yet cleant
355 // CRM-10974
356 $price = CRM_Utils_Rule::cleanMoney($price);
357
358 $participantsPerField = CRM_Utils_Array::value('count', $options[$oid], 0);
359
360 $values[$oid] = array(
361 'price_field_id' => $fid,
362 'price_field_value_id' => $oid,
363 'label' => CRM_Utils_Array::value('label', $options[$oid]),
364 'field_title' => $fieldTitle,
365 'description' => CRM_Utils_Array::value('description', $options[$oid]),
366 'qty' => $qty,
367 'unit_price' => $price,
368 'line_total' => $qty * $price,
369 'participant_count' => $qty * $participantsPerField,
370 'max_value' => CRM_Utils_Array::value('max_value', $options[$oid]),
371 'membership_type_id' => CRM_Utils_Array::value('membership_type_id', $options[$oid]),
372 'membership_num_terms' => CRM_Utils_Array::value('membership_num_terms', $options[$oid]),
373 'auto_renew' => CRM_Utils_Array::value('auto_renew', $options[$oid]),
374 'html_type' => $fields['html_type'],
375 'financial_type_id' => CRM_Utils_Array::value('financial_type_id', $options[$oid]),
376 'tax_amount' => CRM_Utils_Array::value('tax_amount', $options[$oid]),
377 'non_deductible_amount' => CRM_Utils_Array::value('non_deductible_amount', $options[$oid]),
378 );
379
380 if ($values[$oid]['membership_type_id'] && empty($values[$oid]['auto_renew'])) {
381 $values[$oid]['auto_renew'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $values[$oid]['membership_type_id'], 'auto_renew');
382 }
383 }
384 }
385
386 /**
387 * Delete line items for given entity.
388 *
389 * @param int $entityId
390 * @param int $entityTable
391 *
392 * @return bool
393 */
394 public static function deleteLineItems($entityId, $entityTable) {
395 if (!$entityId || !$entityTable) {
396 return FALSE;
397 }
398
399 if ($entityId && !is_array($entityId)) {
400 $entityId = array($entityId);
401 }
402
403 $query = "DELETE FROM civicrm_line_item where entity_id IN ('" . implode("','", $entityId) . "') AND entity_table = '$entityTable'";
404 $dao = CRM_Core_DAO::executeQuery($query);
405 return TRUE;
406 }
407
408 /**
409 * Process price set and line items.
410 *
411 * @param int $entityId
412 * @param array $lineItem
413 * Line item array.
414 * @param object $contributionDetails
415 * @param string $entityTable
416 * Entity table.
417 *
418 * @param bool $update
419 *
420 * @return void
421 */
422 public static function processPriceSet($entityId, $lineItem, $contributionDetails = NULL, $entityTable = 'civicrm_contribution', $update = FALSE) {
423 if (!$entityId || !is_array($lineItem)
424 || CRM_Utils_system::isNull($lineItem)
425 ) {
426 return;
427 }
428
429 foreach ($lineItem as $priceSetId => &$values) {
430 if (!$priceSetId) {
431 continue;
432 }
433
434 foreach ($values as &$line) {
435 if (empty($line['entity_table'])) {
436 $line['entity_table'] = $entityTable;
437 }
438 if (empty($line['entity_id'])) {
439 $line['entity_id'] = $entityId;
440 }
441 if (!empty($line['membership_type_id'])) {
442 $line['entity_table'] = 'civicrm_membership';
443 }
444 if (!empty($contributionDetails->id)) {
445 $line['contribution_id'] = $contributionDetails->id;
446 if ($line['entity_table'] == 'civicrm_contribution') {
447 $line['entity_id'] = $contributionDetails->id;
448 }
449 // CRM-19094: entity_table is set to civicrm_membership then ensure
450 // the entityId is set to membership ID not contribution by default
451 elseif ($line['entity_table'] == 'civicrm_membership' && !empty($line['entity_id']) && $line['entity_id'] == $contributionDetails->id) {
452 $membershipId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', 'contribution_id', $line['entity_id'], 'membership_id');
453 $line['entity_id'] = $membershipId ? $membershipId : $line['entity_id'];
454 }
455 }
456
457 // if financial type is not set and if price field value is NOT NULL
458 // get financial type id of price field value
459 if (!empty($line['price_field_value_id']) && empty($line['financial_type_id'])) {
460 $line['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $line['price_field_value_id'], 'financial_type_id');
461 }
462 $lineItems = CRM_Price_BAO_LineItem::create($line);
463 if (!$update && $contributionDetails) {
464 $financialItem = CRM_Financial_BAO_FinancialItem::add($lineItems, $contributionDetails);
465 $line['financial_item_id'] = $financialItem->id;
466 if (!empty($line['tax_amount'])) {
467 CRM_Financial_BAO_FinancialItem::add($lineItems, $contributionDetails, TRUE);
468 }
469 }
470 }
471 }
472 if (!$update && $contributionDetails) {
473 CRM_Core_BAO_FinancialTrxn::createDeferredTrxn($lineItem, $contributionDetails);
474 }
475 }
476
477 /**
478 * @param int $entityId
479 * @param string $entityTable
480 * @param $amount
481 * @param array $otherParams
482 */
483 public static function syncLineItems($entityId, $entityTable = 'civicrm_contribution', $amount, $otherParams = NULL) {
484 if (!$entityId || CRM_Utils_System::isNull($amount)) {
485 return;
486 }
487
488 $from = " civicrm_line_item li
489 LEFT JOIN civicrm_price_field pf ON pf.id = li.price_field_id
490 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id ";
491
492 $set = " li.unit_price = %3,
493 li.line_total = %3 ";
494
495 $where = " li.entity_id = %1 AND
496 li.entity_table = %2 ";
497
498 $params = array(
499 1 => array($entityId, 'Integer'),
500 2 => array($entityTable, 'String'),
501 3 => array($amount, 'Float'),
502 );
503
504 if ($entityTable == 'civicrm_contribution') {
505 $entityName = 'default_contribution_amount';
506 $where .= " AND ps.name = %4 ";
507 $params[4] = array($entityName, 'String');
508 }
509 elseif ($entityTable == 'civicrm_participant') {
510 $from .= "
511 LEFT JOIN civicrm_price_set_entity cpse ON cpse.price_set_id = ps.id
512 LEFT JOIN civicrm_price_field_value cpfv ON cpfv.price_field_id = pf.id and cpfv.label = %4 ";
513 $set .= " ,li.label = %4,
514 li.price_field_value_id = cpfv.id ";
515 $where .= " AND cpse.entity_table = 'civicrm_event' AND cpse.entity_id = %5 ";
516 $amount = empty($amount) ? 0 : $amount;
517 $params += array(
518 4 => array($otherParams['fee_label'], 'String'),
519 5 => array($otherParams['event_id'], 'String'),
520 );
521 }
522
523 $query = "
524 UPDATE $from
525 SET $set
526 WHERE $where
527 ";
528
529 CRM_Core_DAO::executeQuery($query, $params);
530 }
531
532 /**
533 * Build line items array.
534 *
535 * @param array $params
536 * Form values.
537 *
538 * @param string $entityId
539 * Entity id.
540 *
541 * @param string $entityTable
542 * Entity Table.
543 *
544 * @param bool $isRelatedID
545 */
546 public static function getLineItemArray(&$params, $entityId = NULL, $entityTable = 'contribution', $isRelatedID = FALSE) {
547
548 if (!$entityId) {
549 $priceSetDetails = CRM_Price_BAO_PriceSet::getDefaultPriceSet($entityTable);
550 $totalAmount = CRM_Utils_Array::value('total_amount', $params);
551 $financialType = CRM_Utils_Array::value('financial_type_id', $params);
552 foreach ($priceSetDetails as $values) {
553 if ($entityTable == 'membership') {
554 if ($isRelatedID != $values['membership_type_id']) {
555 continue;
556 }
557 if (!$totalAmount) {
558 $totalAmount = $values['amount'];
559 }
560 $financialType = $values['financial_type_id'];
561 }
562 $params['line_item'][$values['setID']][$values['priceFieldID']] = array(
563 'price_field_id' => $values['priceFieldID'],
564 'price_field_value_id' => $values['priceFieldValueID'],
565 'label' => $values['label'],
566 'qty' => 1,
567 'unit_price' => $totalAmount,
568 'line_total' => $totalAmount,
569 'financial_type_id' => $financialType,
570 'membership_type_id' => $values['membership_type_id'],
571 );
572 break;
573 }
574 }
575 else {
576 $setID = NULL;
577 $totalEntityId = count($entityId);
578 if ($entityTable == 'contribution') {
579 $isRelatedID = TRUE;
580 }
581 foreach ($entityId as $id) {
582 $lineItems = CRM_Price_BAO_LineItem::getLineItems($id, $entityTable, FALSE, TRUE, $isRelatedID);
583 foreach ($lineItems as $key => $values) {
584 if (!$setID && $values['price_field_id']) {
585 $setID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $values['price_field_id'], 'price_set_id');
586 $params['is_quick_config'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $setID, 'is_quick_config');
587 }
588 if (!empty($params['is_quick_config']) && array_key_exists('total_amount', $params)
589 && $totalEntityId == 1
590 ) {
591 $values['line_total'] = $values['unit_price'] = $params['total_amount'];
592 }
593 $values['id'] = $key;
594 $params['line_item'][$setID][$key] = $values;
595 }
596 }
597 }
598 }
599
600 /**
601 * Calculate tax rate in percentage.
602 *
603 * @param array $lineItemId
604 * An assoc array of lineItem.
605 *
606 * @return int|void
607 * tax rate
608 */
609 public static function calculateTaxRate($lineItemId) {
610 if ($lineItemId['unit_price'] == 0 || $lineItemId['qty'] == 0) {
611 return FALSE;
612 }
613 if ($lineItemId['html_type'] == 'Text') {
614 $tax = round($lineItemId['tax_amount'] / ($lineItemId['unit_price'] * $lineItemId['qty']) * 100, 2);
615 }
616 else {
617 $tax = round(($lineItemId['tax_amount'] / $lineItemId['unit_price']) * 100, 2);
618 }
619 return $tax;
620 }
621
622 }