3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * Business objects for Line Items generated by monetary transactions
21 class CRM_Price_BAO_LineItem
extends CRM_Price_DAO_LineItem
{
24 * Creates a new entry in the database.
26 * @param array $params
27 * (reference) an assoc array of name/value pairs.
29 * @return \CRM_Price_DAO_LineItem
31 * @throws \CiviCRM_API3_Exception
34 public static function create(&$params) {
35 $id = $params['id'] ??
NULL;
37 CRM_Utils_Hook
::pre('edit', 'LineItem', $id, $params);
38 $op = CRM_Core_Action
::UPDATE
;
41 CRM_Utils_Hook
::pre('create', 'LineItem', $params['entity_id'], $params);
42 $op = CRM_Core_Action
::ADD
;
45 // unset entity table and entity id in $params
46 // we never update the entity table and entity id during update mode
48 $entity_id = $params['entity_id'] ??
NULL;
49 $entity_table = $params['entity_table'] ??
NULL;
50 unset($params['entity_id'], $params['entity_table']);
53 if (!isset($params['unit_price'])) {
54 $params['unit_price'] = 0;
57 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus() && !empty($params['check_permissions'])) {
58 if (empty($params['financial_type_id'])) {
59 throw new Exception('Mandatory key(s) missing from params array: financial_type_id');
61 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($types, $op);
62 if (!in_array($params['financial_type_id'], array_keys($types))) {
63 throw new Exception('You do not have permission to create this line item');
67 $lineItemBAO = new CRM_Price_BAO_LineItem();
68 $lineItemBAO->copyValues($params);
70 $return = $lineItemBAO->save();
71 if ($lineItemBAO->entity_table
== 'civicrm_membership' && $lineItemBAO->contribution_id
&& $lineItemBAO->entity_id
) {
72 $membershipPaymentParams = [
73 'membership_id' => $lineItemBAO->entity_id
,
74 'contribution_id' => $lineItemBAO->contribution_id
,
76 if (!civicrm_api3('MembershipPayment', 'getcount', $membershipPaymentParams)) {
77 // If we are creating the membership payment row from the line item then we
78 // should have correct line item & membership payment should not need to fix.
79 $membershipPaymentParams['isSkipLineItem'] = TRUE;
80 civicrm_api3('MembershipPayment', 'create', $membershipPaymentParams);
85 // CRM-21281: Restore entity reference in case the post hook needs it
86 $lineItemBAO->entity_id
= $entity_id;
87 $lineItemBAO->entity_table
= $entity_table;
88 CRM_Utils_Hook
::post('edit', 'LineItem', $id, $lineItemBAO);
91 CRM_Utils_Hook
::post('create', 'LineItem', $lineItemBAO->id
, $lineItemBAO);
98 * Retrieve DB object based on input parameters.
100 * It also stores all the retrieved values in the default array.
102 * @param array $params
103 * (reference ) an assoc array of name/value pairs.
104 * @param array $defaults
105 * (reference ) an assoc array to hold the flattened values.
107 * @return CRM_Price_BAO_LineItem
109 public static function retrieve(&$params = [], &$defaults = []) {
110 $lineItem = new CRM_Price_BAO_LineItem();
111 $lineItem->copyValues($params);
112 if ($lineItem->find(TRUE)) {
113 CRM_Core_DAO
::storeValues($lineItem, $defaults);
120 * Modifies $params array for filtering financial types.
122 * @param array $params
123 * (reference ) an assoc array of name/value pairs.
126 public static function getAPILineItemParams(&$params) {
127 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($types);
128 if ($types && empty($params['financial_type_id'])) {
129 $params['financial_type_id'] = ['IN' => array_keys($types)];
132 if (is_array($params['financial_type_id'])) {
133 $invalidFts = array_diff($params['financial_type_id'], array_keys($types));
135 elseif (!in_array($params['financial_type_id'], array_keys($types))) {
136 $invalidFts = $params['financial_type_id'];
139 $params['financial_type_id'] = ['NOT IN' => $invalidFts];
143 $params['financial_type_id'] = 0;
148 * @param int $contributionId
150 * @return null|string
152 public static function getLineTotal($contributionId) {
153 $sqlLineItemTotal = "SELECT SUM(li.line_total + COALESCE(li.tax_amount,0))
154 FROM civicrm_line_item li
155 WHERE li.contribution_id = %1";
156 $params = [1 => [$contributionId, 'Integer']];
157 $lineItemTotal = CRM_Core_DAO
::singleValueQuery($sqlLineItemTotal, $params);
158 return $lineItemTotal;
162 * Wrapper for line item retrieval when contribution ID is known.
163 * @param int $contributionID
167 public static function getLineItemsByContributionID($contributionID) {
168 return self
::getLineItems($contributionID, 'contribution', NULL, TRUE, TRUE);
172 * Given a participant id/contribution id,
173 * return contribution/fee line items
175 * @param int $entityId
176 * participant/contribution id.
177 * @param string $entity
178 * participant/contribution.
180 * @param bool $isQuick
181 * @param bool $isQtyZero
182 * @param bool $relatedEntity
185 * Array of line items
187 public static function getLineItems($entityId, $entity = 'participant', $isQuick = FALSE, $isQtyZero = TRUE, $relatedEntity = FALSE) {
188 $whereClause = $fromClause = NULL;
198 pf.label as field_title,
201 pfv.membership_type_id,
202 pfv.membership_num_terms,
204 li.participant_count,
205 li.price_field_value_id,
206 li.financial_type_id,
210 $condition = "li.entity_id = civicrm_%2.id AND li.entity_table = 'civicrm_%2'";
211 if ($relatedEntity) {
212 $condition = 'li.contribution_id = civicrm_%2.id ';
217 LEFT JOIN civicrm_line_item li ON ({$condition})
218 LEFT JOIN civicrm_price_field_value pfv ON (pfv.id = li.price_field_value_id)
219 LEFT JOIN civicrm_price_field pf ON (pf.id = li.price_field_id )";
220 $whereClause = " WHERE civicrm_%2.id = %1";
221 $orderByClause = " ORDER BY pf.weight, pfv.weight";
224 $fromClause .= " LEFT JOIN civicrm_price_set cps on cps.id = pf.price_set_id ";
225 $whereClause .= " and cps.is_quick_config = 0";
229 $whereClause .= " and li.qty != 0";
234 if (!$entityId ||
!$entity ||
!$fromClause) {
239 1 => [$entityId, 'Integer'],
240 2 => [$entity, 'Text'],
243 $getTaxDetails = FALSE;
244 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
245 $invoicing = $invoiceSettings['invoicing'] ??
NULL;
247 $dao = CRM_Core_DAO
::executeQuery("$selectClause $fromClause $whereClause $orderByClause", $params);
248 while ($dao->fetch()) {
252 $lineItems[$dao->id
] = [
253 'qty' => (float) $dao->qty
,
254 'label' => $dao->label
,
255 'unit_price' => $dao->unit_price
,
256 'line_total' => $dao->line_total
,
257 'price_field_id' => $dao->price_field_id
,
258 'participant_count' => $dao->participant_count
,
259 'price_field_value_id' => $dao->price_field_value_id
,
260 'field_title' => $dao->field_title
,
261 'html_type' => $dao->html_type
,
262 'description' => $dao->description
,
263 'entity_id' => $dao->entity_id
,
264 'entity_table' => $dao->entity_table
,
265 'contribution_id' => $dao->contribution_id
,
266 'financial_type_id' => $dao->financial_type_id
,
267 'financial_type' => CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'financial_type_id', $dao->financial_type_id
),
268 'membership_type_id' => $dao->membership_type_id
,
269 'membership_num_terms' => $dao->membership_num_terms
,
270 'tax_amount' => (float) $dao->tax_amount
,
271 'price_set_id' => $dao->price_set_id
,
273 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
274 if (isset($lineItems[$dao->id
]['financial_type_id']) && array_key_exists($lineItems[$dao->id
]['financial_type_id'], $taxRates)) {
275 // Cast to float so trailing zero decimals are removed for display.
276 $lineItems[$dao->id
]['tax_rate'] = (float) $taxRates[$lineItems[$dao->id
]['financial_type_id']];
279 // There is no Tax Rate associated with this Financial Type
280 $lineItems[$dao->id
]['tax_rate'] = FALSE;
282 $lineItems[$dao->id
]['subTotal'] = $lineItems[$dao->id
]['qty'] * $lineItems[$dao->id
]['unit_price'];
283 if ($lineItems[$dao->id
]['tax_amount'] != '') {
284 $getTaxDetails = TRUE;
288 // @todo - this is an inappropriate place to be doing form level assignments.
289 $taxTerm = Civi
::settings()->get('tax_term');
290 $smarty = CRM_Core_Smarty
::singleton();
291 $smarty->assign('taxTerm', $taxTerm);
292 $smarty->assign('getTaxDetails', $getTaxDetails);
298 * This method will create the lineItem array required for
299 * processAmount method
302 * Price set field id.
303 * @param array $params
304 * Reference to form values.
305 * @param array $fields
306 * Array of fields belonging to the price set used for particular event
307 * @param array $values
308 * Reference to the values array(.
311 * @param string $amount_override
312 * Amount override must be in format 1000.00 - ie no thousand separator & if
313 * a decimal point is used it should be a decimal
315 * @todo - this parameter is only used for partial payments. It's unclear why a partial
316 * payment would change the line item price.
318 public static function format($fid, $params, $fields, &$values, $amount_override = NULL) {
319 if (empty($params["price_{$fid}"])) {
323 //lets first check in fun parameter,
324 //since user might modified w/ hooks.
326 if (array_key_exists('options', $fields)) {
327 $options = $fields['options'];
330 CRM_Price_BAO_PriceFieldValue
::getValues($fid, $options, 'weight', TRUE);
332 $fieldTitle = $fields['label'] ??
NULL;
334 $fieldTitle = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'label');
337 foreach ($params["price_{$fid}"] as $oid => $qty) {
338 $price = $amount_override === NULL ?
$options[$oid]['amount'] : $amount_override;
340 $participantsPerField = CRM_Utils_Array
::value('count', $options[$oid], 0);
343 'price_field_id' => $fid,
344 'price_field_value_id' => $oid,
345 'label' => $options[$oid]['label'] ??
NULL,
346 'field_title' => $fieldTitle,
347 'description' => $options[$oid]['description'] ??
NULL,
349 'unit_price' => $price,
350 'line_total' => $qty * $price,
351 'participant_count' => $qty * $participantsPerField,
352 'max_value' => $options[$oid]['max_value'] ??
NULL,
353 'membership_type_id' => $options[$oid]['membership_type_id'] ??
NULL,
354 'membership_num_terms' => $options[$oid]['membership_num_terms'] ??
NULL,
355 'auto_renew' => $options[$oid]['auto_renew'] ??
NULL,
356 'html_type' => $fields['html_type'],
357 'financial_type_id' => $options[$oid]['financial_type_id'] ??
NULL,
358 'tax_amount' => CRM_Utils_Array
::value('tax_amount', $options[$oid], 0),
359 'non_deductible_amount' => $options[$oid]['non_deductible_amount'] ??
NULL,
362 if ($values[$oid]['membership_type_id'] && empty($values[$oid]['auto_renew'])) {
363 $values[$oid]['auto_renew'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $values[$oid]['membership_type_id'], 'auto_renew');
369 * Delete line items for given entity.
371 * @param int $entityId
372 * @param int $entityTable
376 public static function deleteLineItems($entityId, $entityTable) {
377 if (!$entityId ||
!$entityTable) {
381 if ($entityId && !is_array($entityId)) {
382 $entityId = [$entityId];
385 $query = "DELETE FROM civicrm_line_item where entity_id IN ('" . implode("','", $entityId) . "') AND entity_table = '$entityTable'";
386 $dao = CRM_Core_DAO
::executeQuery($query);
391 * Process price set and line items.
393 * @param int $entityId
394 * @param array $lineItems
396 * @param object $contributionDetails
397 * @param string $entityTable
400 * @param bool $update
402 * @throws \CRM_Core_Exception
403 * @throws \CiviCRM_API3_Exception
405 public static function processPriceSet($entityId, $lineItems, $contributionDetails = NULL, $entityTable = 'civicrm_contribution', $update = FALSE) {
406 if (!$entityId ||
!is_array($lineItems)
407 || CRM_Utils_System
::isNull($lineItems)
412 foreach ($lineItems as $priceSetId => &$values) {
417 foreach ($values as &$line) {
418 if (empty($line['entity_table'])) {
419 $line['entity_table'] = $entityTable;
421 if (empty($line['entity_id'])) {
422 $line['entity_id'] = $entityId;
424 if (!empty($line['membership_type_id'])) {
425 $line['entity_table'] = 'civicrm_membership';
427 if (!empty($contributionDetails->id
)) {
428 $line['contribution_id'] = $contributionDetails->id
;
429 if ($line['entity_table'] == 'civicrm_contribution') {
430 $line['entity_id'] = $contributionDetails->id
;
432 // CRM-19094: entity_table is set to civicrm_membership then ensure
433 // the entityId is set to membership ID not contribution by default
434 elseif ($line['entity_table'] == 'civicrm_membership' && !empty($line['entity_id']) && $line['entity_id'] == $contributionDetails->id
) {
435 $membershipId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $contributionDetails->id
, 'membership_id', 'contribution_id');
436 if ($membershipId && (int) $membershipId !== (int) $line['entity_id']) {
437 $line['entity_id'] = $membershipId;
438 Civi
::log()->warning('Per https://lab.civicrm.org/dev/core/issues/15 this data fix should not be required. Please log a ticket at https://lab.civicrm.org/dev/core with steps to get this.', ['civi.tag' => 'deprecated']);
443 // if financial type is not set and if price field value is NOT NULL
444 // get financial type id of price field value
445 if (!empty($line['price_field_value_id']) && empty($line['financial_type_id'])) {
446 $line['financial_type_id'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $line['price_field_value_id'], 'financial_type_id');
448 $createdLineItem = CRM_Price_BAO_LineItem
::create($line);
449 if (!$update && $contributionDetails) {
450 $financialItem = CRM_Financial_BAO_FinancialItem
::add($createdLineItem, $contributionDetails);
451 $line['financial_item_id'] = $financialItem->id
;
452 if (!empty($line['tax_amount'])) {
453 CRM_Financial_BAO_FinancialItem
::add($createdLineItem, $contributionDetails, TRUE);
458 if (!$update && $contributionDetails) {
459 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn($lineItems, $contributionDetails);
464 * @param int $entityId
465 * @param string $entityTable
467 * @param array $otherParams
469 public static function syncLineItems($entityId, $entityTable = 'civicrm_contribution', $amount, $otherParams = NULL) {
470 if (!$entityId || CRM_Utils_System
::isNull($amount)) {
474 $from = " civicrm_line_item li
475 LEFT JOIN civicrm_price_field pf ON pf.id = li.price_field_id
476 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id ";
478 $set = " li.unit_price = %3,
479 li.line_total = %3 ";
481 $where = " li.entity_id = %1 AND
482 li.entity_table = %2 ";
485 1 => [$entityId, 'Integer'],
486 2 => [$entityTable, 'String'],
487 3 => [$amount, 'Float'],
490 if ($entityTable == 'civicrm_contribution') {
491 $entityName = 'default_contribution_amount';
492 $where .= " AND ps.name = %4 ";
493 $params[4] = [$entityName, 'String'];
495 elseif ($entityTable == 'civicrm_participant') {
497 LEFT JOIN civicrm_price_set_entity cpse ON cpse.price_set_id = ps.id
498 LEFT JOIN civicrm_price_field_value cpfv ON cpfv.price_field_id = pf.id and cpfv.label = %4 ";
499 $set .= " ,li.label = %4,
500 li.price_field_value_id = cpfv.id ";
501 $where .= " AND cpse.entity_table = 'civicrm_event' AND cpse.entity_id = %5 ";
502 $amount = empty($amount) ?
0 : $amount;
504 4 => [$otherParams['fee_label'], 'String'],
505 5 => [$otherParams['event_id'], 'String'],
515 CRM_Core_DAO
::executeQuery($query, $params);
519 * Build line items array.
521 * @param array $params
524 * @param string $entityId
527 * @param string $entityTable
530 * @param bool $isRelatedID
532 public static function getLineItemArray(&$params, $entityId = NULL, $entityTable = 'contribution', $isRelatedID = FALSE) {
534 $priceSetDetails = CRM_Price_BAO_PriceSet
::getDefaultPriceSet($entityTable);
535 $totalAmount = CRM_Utils_Array
::value('partial_payment_total', $params, CRM_Utils_Array
::value('total_amount', $params));
536 $financialType = $params['financial_type_id'] ??
NULL;
537 foreach ($priceSetDetails as $values) {
538 if ($entityTable == 'membership') {
539 if ($isRelatedID != $values['membership_type_id']) {
543 $totalAmount = $values['amount'];
545 $financialType = $values['financial_type_id'];
547 $params['line_item'][$values['setID']][$values['priceFieldID']] = [
548 'price_field_id' => $values['priceFieldID'],
549 'price_field_value_id' => $values['priceFieldValueID'],
550 'label' => $values['label'],
552 'unit_price' => $totalAmount,
553 'line_total' => $totalAmount,
554 'financial_type_id' => $financialType,
555 'membership_type_id' => $values['membership_type_id'],
562 $totalEntityId = count($entityId);
563 if ($entityTable == 'contribution') {
566 foreach ($entityId as $id) {
567 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($id, $entityTable, FALSE, TRUE, $isRelatedID);
568 foreach ($lineItems as $key => $values) {
569 if (!$setID && $values['price_field_id']) {
570 $setID = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $values['price_field_id'], 'price_set_id');
571 $params['is_quick_config'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $setID, 'is_quick_config');
573 if (!empty($params['is_quick_config']) && array_key_exists('total_amount', $params)
574 && $totalEntityId == 1
576 $values['line_total'] = $values['unit_price'] = $params['total_amount'];
578 $values['id'] = $key;
579 $params['line_item'][$setID][$key] = $values;
586 * Build the line items for the submitted price field.
588 * This is when first building them - not an update where an entityId is already present
589 * as this is intended as a subfunction of that. Ideally getLineItemArray would call this
590 * (resolving to the same format regardless of what type of price set is being used first).
592 * @param array $priceParams
593 * These are per the way the form processes them - ie
594 * ['price_1' => 1, 'price_2' => 8]
595 * This would mean price field id 1, option 1 (or 1 unit if using is_enter_qty).
596 * @param float|null $overrideAmount
597 * Optional override of the amount.
599 * @param int|null $financialTypeID
600 * Financial type ID is the type should be overridden.
603 * Line items formatted for processing. These will look like
604 * [4] => ['price_field_id' => 4, 'price_field_value_id' => x, 'label....qty...unit_price...line_total...financial_type_id]
605 * [5] => ['price_field_id' => 5, 'price_field_value_id' => x, 'label....qty...unit_price...line_total...financial_type_id]
608 public static function buildLineItemsForSubmittedPriceField($priceParams, $overrideAmount = NULL, $financialTypeID = NULL) {
610 foreach ($priceParams as $key => $value) {
611 $priceField = self
::getPriceFieldMetaData($key);
613 if ($priceField['html_type'] === 'Text') {
614 $valueSpec = reset($priceField['values']);
617 $valueSpec = $priceField['values'][$value];
619 $qty = $priceField['is_enter_qty'] ?
$value : 1;
620 $lineItems[$priceField['id']] = [
621 'price_field_id' => $priceField['id'],
622 'price_field_value_id' => $valueSpec['id'],
623 'label' => $valueSpec['label'],
625 'unit_price' => $overrideAmount ?
: $valueSpec['amount'],
626 'line_total' => $qty * ($overrideAmount ?
: $valueSpec['amount']),
627 'financial_type_id' => $financialTypeID ?
: $valueSpec['financial_type_id'],
628 'membership_type_id' => $valueSpec['membership_type_id'],
629 'price_set_id' => $priceField['price_set_id'],
636 * Function to update related contribution of a entity and
637 * add/update/cancel financial records
639 * @param array $params
640 * @param int $entityID
642 * @param int $contributionId
644 * @param array $lineItems
646 * @throws \CiviCRM_API3_Exception
648 public static function changeFeeSelections(
656 $entityTable = "civicrm_" . $entity;
657 CRM_Price_BAO_PriceSet
::processAmount($feeBlock,
660 // initialize empty Lineitem instance to call protected helper functions
661 $lineItemObj = new CRM_Price_BAO_LineItem();
663 // fetch submitted LineItems from input params and feeBlock information
664 $submittedLineItems = $lineItemObj->getSubmittedLineItems($params, $feeBlock);
666 $requiredChanges = $lineItemObj->getLineItemsToAlter($submittedLineItems, $entityID, $entity);
668 // get financial information that need to be recorded on basis on submitted price field value IDs
669 if (!empty($requiredChanges['line_items_to_cancel']) ||
!empty($requiredChanges['line_items_to_update'])) {
670 // @todo - this IF is to get this through PR merge but I suspect that it should not
671 // be necessary & is masking something else.
672 $financialItemsArray = $lineItemObj->getAdjustedFinancialItemsToRecord(
676 array_keys($requiredChanges['line_items_to_cancel']),
677 $requiredChanges['line_items_to_update']
681 // update line item with changed line total and other information
682 $totalParticipant = $participantCount = 0;
684 if (!empty($requiredChanges['line_items_to_update'])) {
685 foreach ($requiredChanges['line_items_to_update'] as $priceFieldValueID => $value) {
686 $amountLevel[] = $value['label'] . ' - ' . (float) $value['qty'];
687 if ($entity == 'participant' && isset($value['participant_count'])) {
688 $totalParticipant +
= $value['participant_count'];
693 foreach (array_merge($requiredChanges['line_items_to_resurrect'], $requiredChanges['line_items_to_cancel'], $requiredChanges['line_items_to_update']) as $lineItemToAlter) {
694 // Must use BAO rather than api because a bad line it in the api which we want to avoid.
695 CRM_Price_BAO_LineItem
::create($lineItemToAlter);
698 $lineItemObj->addLineItemOnChangeFeeSelection($requiredChanges['line_items_to_add'], $entityID, $entityTable, $contributionId);
701 if ($entity == 'participant') {
702 $count = count(CRM_Event_BAO_Participant
::getParticipantIds($contributionId));
705 $count = CRM_Utils_Array
::value('count', civicrm_api3('MembershipPayment', 'getcount', ['contribution_id' => $contributionId]));
708 $updatedAmount = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
711 $updatedAmount = CRM_Utils_Array
::value('amount', $params, CRM_Utils_Array
::value('total_amount', $params));
713 if (strlen($params['tax_amount']) != 0) {
714 $taxAmount = $params['tax_amount'];
719 $displayParticipantCount = '';
720 if ($totalParticipant > 0) {
721 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
723 $updateAmountLevel = NULL;
724 if (!empty($amountLevel)) {
725 $updateAmountLevel = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amountLevel) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
727 $trxn = $lineItemObj->_recordAdjustedAmt($updatedAmount, $contributionId, $taxAmount, $updateAmountLevel);
728 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_DAO_Contribution', 'contribution_status_id', CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'contribution_status_id'));
730 if (!empty($financialItemsArray)) {
731 foreach ($financialItemsArray as $updateFinancialItemInfoValues) {
732 $newFinancialItem = CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues);
733 // record reverse transaction only if Contribution is Completed because for pending refund or
734 // partially paid we are already recording the surplus owed or refund amount
735 if (!empty($updateFinancialItemInfoValues['financialTrxn']) && ($contributionStatus == 'Completed')) {
736 $updateFinancialItemInfoValues = array_merge($updateFinancialItemInfoValues['financialTrxn'], [
737 'entity_id' => $newFinancialItem->id
,
738 'entity_table' => 'civicrm_financial_item',
740 $reverseTrxn = CRM_Core_BAO_FinancialTrxn
::create($updateFinancialItemInfoValues);
741 // record reverse entity financial trxn linked to membership's related contribution
742 civicrm_api3('EntityFinancialTrxn', 'create', [
743 'entity_table' => "civicrm_contribution",
744 'entity_id' => $contributionId,
745 'financial_trxn_id' => $reverseTrxn->id
,
746 'amount' => $reverseTrxn->total_amount
,
748 unset($updateFinancialItemInfoValues['financialTrxn']);
750 elseif ($trxn && $newFinancialItem->amount
!= 0) {
751 civicrm_api3('EntityFinancialTrxn', 'create', [
752 'entity_id' => $newFinancialItem->id
,
753 'entity_table' => 'civicrm_financial_item',
754 'financial_trxn_id' => $trxn->id
,
755 'amount' => $newFinancialItem->amount
,
761 $lineItemObj->addFinancialItemsOnLineItemsChange(array_merge($requiredChanges['line_items_to_add'], $requiredChanges['line_items_to_resurrect']), $entityID, $entityTable, $contributionId, $trxn->id ??
NULL);
763 // update participant fee_amount column
764 $lineItemObj->updateEntityRecordOnChangeFeeSelection($params, $entityID, $entity);
768 * Function to retrieve financial items that need to be recorded as result of changed fee
770 * @param int $entityID
771 * @param string $entityTable
772 * @param int $contributionID
773 * @param array $priceFieldValueIDsToCancel
774 * @param array $lineItemsToUpdate
777 * List of formatted reverse Financial Items to be recorded
779 protected function getAdjustedFinancialItemsToRecord($entityID, $entityTable, $contributionID, $priceFieldValueIDsToCancel, $lineItemsToUpdate) {
780 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, str_replace('civicrm_', '', $entityTable));
782 $financialItemsArray = [];
783 $financialItemResult = $this->getNonCancelledFinancialItems($entityID, $entityTable);
784 foreach ($financialItemResult as $updateFinancialItemInfoValues) {
785 $updateFinancialItemInfoValues['transaction_date'] = date('YmdHis');
787 // the below params are not needed as we are creating new financial item
788 $previousFinancialItemID = $updateFinancialItemInfoValues['id'];
789 $totalFinancialAmount = $this->checkFinancialItemTotalAmountByLineItemID($updateFinancialItemInfoValues['entity_id']);
790 unset($updateFinancialItemInfoValues['id']);
791 unset($updateFinancialItemInfoValues['created_date']);
792 $previousLineItem = $previousLineItems[$updateFinancialItemInfoValues['entity_id']];
794 // if not submitted and difference is not 0 make it negative
795 if ((empty($lineItemsToUpdate) ||
(in_array($updateFinancialItemInfoValues['price_field_value_id'], $priceFieldValueIDsToCancel) &&
796 $totalFinancialAmount == $updateFinancialItemInfoValues['amount'])
797 ) && $updateFinancialItemInfoValues['amount'] > 0
800 // INSERT negative financial_items
801 $updateFinancialItemInfoValues['amount'] = -$updateFinancialItemInfoValues['amount'];
802 // reverse the related financial trxn too
803 $updateFinancialItemInfoValues['financialTrxn'] = $this->getRelatedCancelFinancialTrxn($previousFinancialItemID);
804 if ($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']) {
805 $updateFinancialItemInfoValues['tax']['amount'] = -($previousLineItem['tax_amount']);
806 $updateFinancialItemInfoValues['tax']['description'] = $this->getSalesTaxTerm();
808 // INSERT negative financial_items for tax amount
809 $financialItemsArray[$updateFinancialItemInfoValues['entity_id']] = $updateFinancialItemInfoValues;
811 // INSERT a financial item to record surplus/lesser amount when a text price fee is changed
813 !empty($lineItemsToUpdate)
814 && isset($lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']])
815 && $lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']]['html_type'] == 'Text'
816 && $updateFinancialItemInfoValues['amount'] > 0
818 $amountChangeOnTextLineItem = $lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']]['line_total'] - $totalFinancialAmount;
819 if ($amountChangeOnTextLineItem !== (float) 0) {
820 // calculate the amount difference, considered as financial item amount
821 $updateFinancialItemInfoValues['amount'] = $amountChangeOnTextLineItem;
822 if ($previousLineItem['tax_amount']
823 && $previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount'] !== 0.00) {
824 $updateFinancialItemInfoValues['tax']['amount'] = $lineItemsToUpdate[$updateFinancialItemInfoValues['entity_id']]['tax_amount'] - $previousLineItem['tax_amount'];
825 $updateFinancialItemInfoValues['tax']['description'] = $this->getSalesTaxTerm();
827 $financialItemsArray[$updateFinancialItemInfoValues['entity_id']] = $updateFinancialItemInfoValues;
832 return $financialItemsArray;
836 * Helper function to return sum of financial item's amount related to a line-item
837 * @param array $lineItemID
839 * @return float $financialItem
841 protected function checkFinancialItemTotalAmountByLineItemID($lineItemID) {
842 return CRM_Core_DAO
::singleValueQuery("
844 FROM civicrm_financial_item
845 WHERE entity_table = 'civicrm_line_item' AND entity_id = {$lineItemID}
850 * Helper function to retrieve submitted line items from form values $inputParams and used $feeBlock
852 * @param array $inputParams
853 * @param array $feeBlock
856 * List of submitted line items
858 protected function getSubmittedLineItems($inputParams, $feeBlock) {
859 $submittedLineItems = [];
860 foreach ($feeBlock as $id => $values) {
861 CRM_Price_BAO_LineItem
::format($id, $inputParams, $values, $submittedLineItems);
864 return $submittedLineItems;
868 * Helper function to retrieve line items that need to be altered.
870 * We iterate through the previous line items for the given entity to determine
871 * what alterations to line items need to be made to reflect the new line items.
873 * There are 4 possible changes required - per the keys in the return array.
875 * @param array $submittedLineItems
876 * @param int $entityID
877 * @param string $entity
880 * Array of line items to alter with the following keys
881 * - line_items_to_add. If the line items required are new radio options that
882 * have not previously been set then we should add line items for them
883 * - line_items_to_update. If we have already been an active option and a change has
884 * happened then it should be in this array.
885 * - line_items_to_cancel. Line items currently selected but not selected in the new selection.
886 * These need to be zero'd out.
887 * - line_items_to_resurrect. Line items previously selected and then deselected. These need to be
888 * re-enabled rather than a new one added.
890 protected function getLineItemsToAlter($submittedLineItems, $entityID, $entity) {
891 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, $entity);
893 $lineItemsToAdd = $submittedLineItems;
894 $lineItemsToUpdate = [];
895 $submittedPriceFieldValueIDs = array_keys($submittedLineItems);
896 $lineItemsToCancel = $lineItemsToResurrect = [];
898 foreach ($previousLineItems as $id => $previousLineItem) {
899 if (in_array($previousLineItem['price_field_value_id'], $submittedPriceFieldValueIDs)) {
900 $submittedLineItem = $submittedLineItems[$previousLineItem['price_field_value_id']];
901 if (CRM_Utils_Array
::value('html_type', $lineItemsToAdd[$previousLineItem['price_field_value_id']]) == 'Text') {
902 // If a 'Text' price field was updated by changing qty value, then we are not adding new line-item but updating the existing one,
903 // because unlike other kind of price-field, it's related price-field-value-id isn't changed and thats why we need to make an
904 // exception here by adding financial item for updated line-item and will reverse any previous financial item entries.
905 $lineItemsToUpdate[$previousLineItem['price_field_value_id']] = array_merge($submittedLineItem, ['id' => $id]);
906 unset($lineItemsToAdd[$previousLineItem['price_field_value_id']]);
909 $submittedLineItem = $submittedLineItems[$previousLineItem['price_field_value_id']];
910 // for updating the line items i.e. use-case - once deselect-option selecting again
911 if (($previousLineItem['line_total'] != $submittedLineItem['line_total'])
913 // This would be a $0 line item - but why it should be catered to
914 // other than when the above condition is unclear.
915 $submittedLineItem['line_total'] == 0 && $submittedLineItem['qty'] == 1
918 $previousLineItem['qty'] != $submittedLineItem['qty']
921 $lineItemsToUpdate[$previousLineItem['price_field_value_id']] = $submittedLineItem;
922 $lineItemsToUpdate[$previousLineItem['price_field_value_id']]['id'] = $id;
923 // Format is actually '0.00'
924 if ($previousLineItem['line_total'] == 0) {
925 $lineItemsToAdd[$previousLineItem['price_field_value_id']]['id'] = $id;
926 $lineItemsToResurrect[] = $lineItemsToAdd[$previousLineItem['price_field_value_id']];
929 // If there was previously a submitted line item for the same option value then there is
930 // either no change or a qty adjustment. In either case we are not doing an add + reversal.
931 unset($lineItemsToAdd[$previousLineItem['price_field_value_id']]);
932 unset($lineItemsToCancel[$previousLineItem['price_field_value_id']]);
936 if (!$this->isCancelled($previousLineItem)) {
937 $cancelParams = ['qty' => 0, 'line_total' => 0, 'tax_amount' => 0, 'participant_count' => 0, 'non_deductible_amount' => 0, 'id' => $id];
938 $lineItemsToCancel[$previousLineItem['price_field_value_id']] = array_merge($previousLineItem, $cancelParams);
945 'line_items_to_add' => $lineItemsToAdd,
946 'line_items_to_update' => $lineItemsToUpdate,
947 'line_items_to_cancel' => $lineItemsToCancel,
948 'line_items_to_resurrect' => $lineItemsToResurrect,
953 * Check if a line item has already been cancelled.
955 * @param array $lineItem
959 protected function isCancelled($lineItem) {
960 if ($lineItem['qty'] == 0 && $lineItem['line_total'] == 0) {
966 * Add line Items as result of fee change.
968 * @param array $lineItemsToAdd
969 * @param int $entityID
970 * @param string $entityTable
971 * @param int $contributionID
973 protected function addLineItemOnChangeFeeSelection(
979 // if there is no line item to add, do not proceed
980 if (empty($lineItemsToAdd)) {
984 $changedFinancialTypeID = NULL;
985 $updatedContribution = new CRM_Contribute_BAO_Contribution();
986 $updatedContribution->id
= (int) $contributionID;
987 // insert financial items
988 foreach ($lineItemsToAdd as $priceFieldValueID => $lineParams) {
989 $lineParams = array_merge($lineParams, [
990 'entity_table' => $entityTable,
991 'entity_id' => $entityID,
992 'contribution_id' => $contributionID,
994 if (!array_key_exists('skip', $lineParams)) {
995 self
::create($lineParams);
999 if ($changedFinancialTypeID) {
1000 $updatedContribution->financial_type_id
= $changedFinancialTypeID;
1001 $updatedContribution->save();
1006 * Add financial transactions when an array of line items is changed.
1008 * @param array $lineItemsToAdd
1009 * @param int $entityID
1010 * @param string $entityTable
1011 * @param int $contributionID
1012 * @param bool $trxnID
1013 * Is there a change to the total balance requiring additional transactions to be created.
1015 protected function addFinancialItemsOnLineItemsChange($lineItemsToAdd, $entityID, $entityTable, $contributionID, $trxnID) {
1016 $updatedContribution = new CRM_Contribute_BAO_Contribution();
1017 $updatedContribution->id
= $contributionID;
1018 $updatedContribution->find(TRUE);
1019 $trxnArray = $trxnID ?
['id' => $trxnID] : NULL;
1021 foreach ($lineItemsToAdd as $priceFieldValueID => $lineParams) {
1022 $lineParams = array_merge($lineParams, [
1023 'entity_table' => $entityTable,
1024 'entity_id' => $entityID,
1025 'contribution_id' => $contributionID,
1027 $lineObj = CRM_Price_BAO_LineItem
::retrieve($lineParams);
1028 // insert financial items
1029 // ensure entity_financial_trxn table has a linking of it.
1030 CRM_Financial_BAO_FinancialItem
::add($lineObj, $updatedContribution, NULL, $trxnArray);
1031 if (isset($lineObj->tax_amount
) && (float) $lineObj->tax_amount
!== 0.00) {
1032 CRM_Financial_BAO_FinancialItem
::add($lineObj, $updatedContribution, TRUE, $trxnArray);
1038 * Helper function to update entity record on change fee selection
1040 * @param array $inputParams
1041 * @param int $entityID
1042 * @param string $entity
1045 protected function updateEntityRecordOnChangeFeeSelection($inputParams, $entityID, $entity) {
1046 $entityTable = "civicrm_{$entity}";
1048 if ($entity == 'participant') {
1049 $partUpdateFeeAmt = ['id' => $entityID];
1050 $getUpdatedLineItems = "SELECT *
1051 FROM civicrm_line_item
1052 WHERE (entity_table = '{$entityTable}' AND entity_id = {$entityID} AND qty > 0)";
1053 $getUpdatedLineItemsDAO = CRM_Core_DAO
::executeQuery($getUpdatedLineItems);
1055 while ($getUpdatedLineItemsDAO->fetch()) {
1056 $line[$getUpdatedLineItemsDAO->price_field_value_id
] = $getUpdatedLineItemsDAO->label
. ' - ' . (float) $getUpdatedLineItemsDAO->qty
;
1059 $partUpdateFeeAmt['fee_level'] = implode(', ', $line);
1060 $partUpdateFeeAmt['fee_amount'] = $inputParams['amount'];
1061 CRM_Event_BAO_Participant
::add($partUpdateFeeAmt);
1064 CRM_Event_BAO_Participant
::addActivityForSelection($entityID, 'Change Registration');
1069 * Get the metadata for a price field.
1071 * @param string|int $key
1072 * Price field id. Either as an integer or as 'price_4' where 4 is the id
1075 * Metadata for the price field with a values key for option values.
1077 protected static function getPriceFieldMetaData($key) {
1078 $priceFieldID = str_replace('price_', '', $key);
1079 if (!isset(Civi
::$statics[__CLASS__
]['price_fields'][$priceFieldID])) {
1080 $values = civicrm_api3('PriceFieldValue', 'get', [
1081 'price_field_id' => $priceFieldID,
1085 'financial_type_id',
1086 'membership_type_id',
1089 'price_field_id.price_set_id',
1090 'price_field_id.html_type',
1094 $firstValue = reset($values['values']);
1095 $values = $values['values'];
1096 foreach ($values as $index => $value) {
1097 // Let's be nice to calling functions & ensure membership_type_id is set
1098 // so they don't have to handle notices on it. Handle one place not many.
1099 if (!isset($value['membership_type_id'])) {
1100 $values[$index]['membership_type_id'] = NULL;
1104 Civi
::$statics[__CLASS__
]['price_fields'][$priceFieldID] = [
1105 'price_set_id' => $firstValue['price_field_id.price_set_id'],
1106 'id' => $firstValue['price_field_id'],
1107 'html_type' => $firstValue['price_field_id.html_type'],
1108 'is_enter_qty' => !empty($firstValue['is_enter_qty']),
1109 'values' => $values,
1112 return Civi
::$statics[__CLASS__
]['price_fields'][$priceFieldID];
1116 * Helper function to retrieve financial trxn parameters to reverse
1117 * for given financial item identified by $financialItemID
1119 * @param int $financialItemID
1121 * @return array $financialTrxn
1124 protected function _getRelatedCancelFinancialTrxn($financialItemID) {
1126 $financialTrxn = civicrm_api3('EntityFinancialTrxn', 'getsingle', [
1127 'entity_table' => 'civicrm_financial_item',
1128 'entity_id' => $financialItemID,
1130 'sort' => 'id DESC',
1133 'api.FinancialTrxn.getsingle' => [
1134 'id' => "\$value.financial_trxn_id",
1138 catch (CiviCRM_API3_Exception
$e) {
1142 $financialTrxn = array_merge($financialTrxn['api.FinancialTrxn.getsingle'], [
1143 'trxn_date' => date('YmdHis'),
1144 'total_amount' => -$financialTrxn['api.FinancialTrxn.getsingle']['total_amount'],
1145 'net_amount' => -$financialTrxn['api.FinancialTrxn.getsingle']['net_amount'],
1146 'entity_table' => 'civicrm_financial_item',
1147 'entity_id' => $financialItemID,
1149 unset($financialTrxn['id']);
1151 return $financialTrxn;
1155 * Record adjusted amount.
1157 * @param int $updatedAmount
1158 * @param int $contributionId
1159 * @param int $taxAmount
1160 * @param bool $updateAmountLevel
1162 * @return bool|\CRM_Core_BAO_FinancialTrxn
1164 protected function _recordAdjustedAmt($updatedAmount, $contributionId, $taxAmount = NULL, $updateAmountLevel = NULL) {
1165 $paidAmount = (float) CRM_Core_BAO_FinancialTrxn
::getTotalPayments($contributionId);
1166 $balanceAmt = $updatedAmount - $paidAmount;
1168 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1169 $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
1170 $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
1171 $completedStatusId = array_search('Completed', $contributionStatuses);
1173 $updatedContributionDAO = new CRM_Contribute_BAO_Contribution();
1174 $adjustedTrxn = FALSE;
1176 if ($paidAmount === 0.0) {
1177 //skip updating the contribution status if no payment is made
1178 $updatedContributionDAO->cancel_date
= 'null';
1179 $updatedContributionDAO->cancel_reason
= NULL;
1182 $updatedContributionDAO->contribution_status_id
= $balanceAmt > 0 ?
$partiallyPaidStatusId : $pendingRefundStatusId;
1185 // update contribution status and total amount without trigger financial code
1186 // as this is handled in current BAO function used for change selection
1187 $updatedContributionDAO->id
= $contributionId;
1189 $updatedContributionDAO->total_amount
= $updatedContributionDAO->net_amount
= $updatedAmount;
1190 $updatedContributionDAO->fee_amount
= 0;
1191 $updatedContributionDAO->tax_amount
= $taxAmount;
1192 if (!empty($updateAmountLevel)) {
1193 $updatedContributionDAO->amount_level
= $updateAmountLevel;
1195 $updatedContributionDAO->save();
1196 // adjusted amount financial_trxn creation
1197 $updatedContribution = CRM_Contribute_BAO_Contribution
::getValues(
1198 ['id' => $contributionId]
1200 $toFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($updatedContribution->financial_type_id
, 'Accounts Receivable Account is');
1201 $adjustedTrxnValues = [
1202 'from_financial_account_id' => NULL,
1203 'to_financial_account_id' => $toFinancialAccount,
1204 'total_amount' => $balanceAmt,
1205 'net_amount' => $balanceAmt,
1206 'status_id' => $completedStatusId,
1207 'payment_instrument_id' => $updatedContribution->payment_instrument_id
,
1208 'contribution_id' => $updatedContribution->id
,
1209 'trxn_date' => date('YmdHis'),
1210 'currency' => $updatedContribution->currency
,
1212 $adjustedTrxn = CRM_Core_BAO_FinancialTrxn
::create($adjustedTrxnValues);
1214 // CRM-17151: Update the contribution status to completed if balance is zero,
1215 // because due to sucessive fee change will leave the related contribution status incorrect
1217 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'contribution_status_id', $completedStatusId);
1220 return $adjustedTrxn;
1224 * Get Financial items, culling out any that have already been reversed.
1226 * @param int $entityID
1227 * @param string $entityTable
1230 * Array of financial items that have not be reversed.
1232 protected function getNonCancelledFinancialItems($entityID, $entityTable) {
1233 // gathering necessary info to record negative (deselected) financial_item
1234 $updateFinancialItem = "
1235 SELECT fi.*, price_field_value_id, financial_type_id, tax_amount
1236 FROM civicrm_financial_item fi LEFT JOIN civicrm_line_item li ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1237 WHERE (li.entity_table = '{$entityTable}' AND li.entity_id = {$entityID})
1238 GROUP BY li.entity_table, li.entity_id, price_field_value_id, fi.id
1240 $updateFinancialItemInfoDAO = CRM_Core_DAO
::executeQuery($updateFinancialItem);
1242 $financialItemResult = $updateFinancialItemInfoDAO->fetchAll();
1244 foreach ($financialItemResult as $index => $financialItem) {
1245 $items[$financialItem['price_field_value_id']][$index] = $financialItem['amount'];
1247 if (!empty($items[$financialItem['price_field_value_id']])) {
1248 foreach ($items[$financialItem['price_field_value_id']] as $existingItemID => $existingAmount) {
1249 if ($financialItem['amount'] +
$existingAmount == 0) {
1250 // Filter both rows as they cancel each other out.
1251 unset($financialItemResult[$index]);
1252 unset($financialItemResult[$existingItemID]);
1253 unset($items['price_field_value_id'][$existingItemID]);
1254 unset($items[$financialItem['price_field_value_id']][$index]);
1261 return $financialItemResult;
1265 * Get the string used to describe the sales tax (eg. VAT, GST).
1269 protected function getSalesTaxTerm() {
1270 return CRM_Contribute_BAO_Contribution
::checkContributeSettings('tax_term');