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_BAO_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);
40 CRM_Utils_Hook
::pre('create', 'LineItem', $id, $params);
43 // unset entity table and entity id in $params
44 // we never update the entity table and entity id during update mode
46 $entity_id = $params['entity_id'] ??
NULL;
47 $entity_table = $params['entity_table'] ??
NULL;
48 unset($params['entity_id'], $params['entity_table']);
51 if (!isset($params['unit_price'])) {
52 $params['unit_price'] = 0;
55 if (isset($params['financial_type_id'], $params['line_total'])) {
56 $params['tax_amount'] = self
::getTaxAmountForLineItem($params);
59 $lineItemBAO = new CRM_Price_BAO_LineItem();
60 $lineItemBAO->copyValues($params);
62 $return = $lineItemBAO->save();
63 if ($lineItemBAO->entity_table
=== 'civicrm_membership' && $lineItemBAO->contribution_id
&& $lineItemBAO->entity_id
) {
64 $membershipPaymentParams = [
65 'membership_id' => $lineItemBAO->entity_id
,
66 'contribution_id' => $lineItemBAO->contribution_id
,
68 if (!civicrm_api3('MembershipPayment', 'getcount', $membershipPaymentParams)) {
69 // If we are creating the membership payment row from the line item then we
70 // should have correct line item & membership payment should not need to fix.
71 $membershipPaymentParams['isSkipLineItem'] = TRUE;
72 civicrm_api3('MembershipPayment', 'create', $membershipPaymentParams);
77 // CRM-21281: Restore entity reference in case the post hook needs it
78 $lineItemBAO->entity_id
= $entity_id;
79 $lineItemBAO->entity_table
= $entity_table;
80 CRM_Utils_Hook
::post('edit', 'LineItem', $id, $lineItemBAO);
83 CRM_Utils_Hook
::post('create', 'LineItem', $lineItemBAO->id
, $lineItemBAO);
90 * Retrieve DB object based on input parameters.
92 * It also stores all the retrieved values in the default array.
94 * @param array $params
95 * (reference ) an assoc array of name/value pairs.
96 * @param array $defaults
97 * (reference ) an assoc array to hold the flattened values.
99 * @return CRM_Price_BAO_LineItem
101 public static function retrieve(&$params = [], &$defaults = []) {
102 $lineItem = new CRM_Price_BAO_LineItem();
103 $lineItem->copyValues($params);
104 if ($lineItem->find(TRUE)) {
105 CRM_Core_DAO
::storeValues($lineItem, $defaults);
112 * @param int $contributionId
114 * @return null|string
116 public static function getLineTotal($contributionId) {
117 $sqlLineItemTotal = "SELECT SUM(li.line_total + COALESCE(li.tax_amount,0))
118 FROM civicrm_line_item li
119 WHERE li.contribution_id = %1";
120 $params = [1 => [$contributionId, 'Integer']];
121 $lineItemTotal = CRM_Core_DAO
::singleValueQuery($sqlLineItemTotal, $params);
122 return $lineItemTotal;
126 * Wrapper for line item retrieval when contribution ID is known.
127 * @param int $contributionID
131 public static function getLineItemsByContributionID($contributionID) {
132 return self
::getLineItems($contributionID, 'contribution', NULL, TRUE, TRUE);
136 * Given a participant id/contribution id,
137 * return contribution/fee line items
139 * @param int $entityId
140 * participant/contribution id.
141 * @param string $entity
142 * participant/contribution.
144 * @param bool $isQuick
145 * @param bool $isQtyZero
146 * @param bool $relatedEntity
149 * Array of line items
151 public static function getLineItems($entityId, $entity = 'participant', $isQuick = FALSE, $isQtyZero = TRUE, $relatedEntity = FALSE) {
152 $whereClause = $fromClause = NULL;
162 pf.label as field_title,
165 pfv.membership_type_id,
166 pfv.membership_num_terms,
168 li.participant_count,
169 li.price_field_value_id,
170 li.financial_type_id,
174 $condition = "li.entity_id = civicrm_%2.id AND li.entity_table = 'civicrm_%2'";
175 if ($relatedEntity) {
176 $condition = 'li.contribution_id = civicrm_%2.id ';
181 LEFT JOIN civicrm_line_item li ON ({$condition})
182 LEFT JOIN civicrm_price_field_value pfv ON (pfv.id = li.price_field_value_id)
183 LEFT JOIN civicrm_price_field pf ON (pf.id = li.price_field_id )";
184 $whereClause = " WHERE civicrm_%2.id = %1";
185 $orderByClause = " ORDER BY pf.weight, pfv.weight";
188 $fromClause .= " LEFT JOIN civicrm_price_set cps on cps.id = pf.price_set_id ";
189 $whereClause .= " and cps.is_quick_config = 0";
193 $whereClause .= " and li.qty != 0";
198 if (!$entityId ||
!$entity ||
!$fromClause) {
203 1 => [$entityId, 'Integer'],
204 2 => [$entity, 'Text'],
207 $getTaxDetails = FALSE;
208 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
209 $invoicing = $invoiceSettings['invoicing'] ??
NULL;
211 $dao = CRM_Core_DAO
::executeQuery("$selectClause $fromClause $whereClause $orderByClause", $params);
212 while ($dao->fetch()) {
216 $lineItems[$dao->id
] = [
217 'qty' => (float) $dao->qty
,
218 'label' => $dao->label
,
219 'unit_price' => $dao->unit_price
,
220 'line_total' => $dao->line_total
,
221 'price_field_id' => $dao->price_field_id
,
222 'participant_count' => $dao->participant_count
,
223 'price_field_value_id' => $dao->price_field_value_id
,
224 'field_title' => $dao->field_title
,
225 'html_type' => $dao->html_type
,
226 'description' => $dao->description
,
227 'entity_id' => $dao->entity_id
,
228 'entity_table' => $dao->entity_table
,
229 'contribution_id' => $dao->contribution_id
,
230 'financial_type_id' => $dao->financial_type_id
,
231 'financial_type' => CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'financial_type_id', $dao->financial_type_id
),
232 'membership_type_id' => $dao->membership_type_id
,
233 'membership_num_terms' => $dao->membership_num_terms
,
234 'tax_amount' => (float) $dao->tax_amount
,
235 'price_set_id' => $dao->price_set_id
,
237 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
238 if (isset($lineItems[$dao->id
]['financial_type_id']) && array_key_exists($lineItems[$dao->id
]['financial_type_id'], $taxRates)) {
239 // Cast to float so trailing zero decimals are removed for display.
240 $lineItems[$dao->id
]['tax_rate'] = (float) $taxRates[$lineItems[$dao->id
]['financial_type_id']];
243 // There is no Tax Rate associated with this Financial Type
244 $lineItems[$dao->id
]['tax_rate'] = FALSE;
246 $lineItems[$dao->id
]['subTotal'] = $lineItems[$dao->id
]['qty'] * $lineItems[$dao->id
]['unit_price'];
247 if ($lineItems[$dao->id
]['tax_amount'] != '') {
248 $getTaxDetails = TRUE;
252 // @todo - this is an inappropriate place to be doing form level assignments.
253 $taxTerm = Civi
::settings()->get('tax_term');
254 $smarty = CRM_Core_Smarty
::singleton();
255 $smarty->assign('taxTerm', $taxTerm);
256 $smarty->assign('getTaxDetails', $getTaxDetails);
262 * This method will create the lineItem array required for
263 * processAmount method
266 * Price set field id.
267 * @param array $params
268 * Reference to form values.
269 * @param array $fields
270 * Array of fields belonging to the price set used for particular event
271 * @param array $values
272 * Reference to the values array(.
275 * @param string $amount_override
276 * Amount override must be in format 1000.00 - ie no thousand separator & if
277 * a decimal point is used it should be a decimal
279 * @todo - this parameter is only used for partial payments. It's unclear why a partial
280 * payment would change the line item price.
282 public static function format($fid, $params, $fields, &$values, $amount_override = NULL) {
283 if (empty($params["price_{$fid}"])) {
287 //lets first check in fun parameter,
288 //since user might modified w/ hooks.
290 if (array_key_exists('options', $fields)) {
291 $options = $fields['options'];
294 CRM_Price_BAO_PriceFieldValue
::getValues($fid, $options, 'weight', TRUE);
296 $fieldTitle = $fields['label'] ??
NULL;
298 $fieldTitle = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'label');
301 foreach ($params["price_{$fid}"] as $oid => $qty) {
302 $price = $amount_override === NULL ?
$options[$oid]['amount'] : $amount_override;
304 $participantsPerField = CRM_Utils_Array
::value('count', $options[$oid], 0);
307 'price_field_id' => $fid,
308 'price_field_value_id' => $oid,
309 'label' => $options[$oid]['label'] ??
NULL,
310 'field_title' => $fieldTitle,
311 'description' => $options[$oid]['description'] ??
NULL,
313 'unit_price' => $price,
314 'line_total' => $qty * $price,
315 'participant_count' => $qty * $participantsPerField,
316 'max_value' => $options[$oid]['max_value'] ??
NULL,
317 'membership_type_id' => $options[$oid]['membership_type_id'] ??
NULL,
318 'membership_num_terms' => $options[$oid]['membership_num_terms'] ??
NULL,
319 'auto_renew' => $options[$oid]['auto_renew'] ??
NULL,
320 'html_type' => $fields['html_type'],
321 'financial_type_id' => $options[$oid]['financial_type_id'] ??
NULL,
322 'tax_amount' => CRM_Utils_Array
::value('tax_amount', $options[$oid], 0),
323 'non_deductible_amount' => $options[$oid]['non_deductible_amount'] ??
NULL,
326 if ($values[$oid]['membership_type_id'] && empty($values[$oid]['auto_renew'])) {
327 $values[$oid]['auto_renew'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $values[$oid]['membership_type_id'], 'auto_renew');
333 * Delete line items for given entity.
335 * @param int $entityId
336 * @param int $entityTable
340 public static function deleteLineItems($entityId, $entityTable) {
341 if (!$entityId ||
!$entityTable) {
345 if ($entityId && !is_array($entityId)) {
346 $entityId = [$entityId];
350 foreach ($entityId as $id) {
351 CRM_Utils_Hook
::pre('delete', 'LineItem', $id, $params);
354 $query = "DELETE FROM civicrm_line_item where entity_id IN ('" . implode("','", $entityId) . "') AND entity_table = '$entityTable'";
355 $dao = CRM_Core_DAO
::executeQuery($query);
360 * Process price set and line items.
362 * @param int $entityId
363 * @param array $lineItems
365 * @param object $contributionDetails
366 * @param string $entityTable
369 * @param bool $update
371 * @throws \CRM_Core_Exception
372 * @throws \CiviCRM_API3_Exception
374 public static function processPriceSet($entityId, $lineItems, $contributionDetails = NULL, $entityTable = 'civicrm_contribution', $update = FALSE) {
375 if (!$entityId ||
!is_array($lineItems)
376 || CRM_Utils_System
::isNull($lineItems)
381 foreach ($lineItems as $priceSetId => &$values) {
386 foreach ($values as &$line) {
387 if (empty($line['entity_table'])) {
388 $line['entity_table'] = $entityTable;
390 if (empty($line['entity_id'])) {
391 $line['entity_id'] = $entityId;
393 if (!empty($line['membership_type_id'])) {
394 $line['entity_table'] = 'civicrm_membership';
396 if (!empty($contributionDetails->id
)) {
397 $line['contribution_id'] = $contributionDetails->id
;
398 if ($line['entity_table'] === 'civicrm_contribution') {
399 $line['entity_id'] = $contributionDetails->id
;
403 // if financial type is not set and if price field value is NOT NULL
404 // get financial type id of price field value
405 if (!empty($line['price_field_value_id']) && empty($line['financial_type_id'])) {
406 $line['financial_type_id'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $line['price_field_value_id'], 'financial_type_id');
408 $createdLineItem = CRM_Price_BAO_LineItem
::create($line);
409 if (!$update && $contributionDetails) {
410 $financialItem = CRM_Financial_BAO_FinancialItem
::add($createdLineItem, $contributionDetails);
411 $line['financial_item_id'] = $financialItem->id
;
412 if (!empty($line['tax_amount'])) {
413 CRM_Financial_BAO_FinancialItem
::add($createdLineItem, $contributionDetails, TRUE);
418 if (!$update && $contributionDetails) {
419 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn($lineItems, $contributionDetails);
424 * @param int $entityId
425 * @param string $entityTable
427 * @param array $otherParams
429 public static function syncLineItems($entityId, $entityTable, $amount, $otherParams = NULL) {
430 if (!$entityId || CRM_Utils_System
::isNull($amount)) {
434 $from = " civicrm_line_item li
435 LEFT JOIN civicrm_price_field pf ON pf.id = li.price_field_id
436 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id ";
438 $set = " li.unit_price = %3,
439 li.line_total = %3 ";
441 $where = " li.entity_id = %1 AND
442 li.entity_table = %2 ";
445 1 => [$entityId, 'Integer'],
446 2 => [$entityTable, 'String'],
447 3 => [$amount, 'Float'],
450 if ($entityTable == 'civicrm_contribution') {
451 $entityName = 'default_contribution_amount';
452 $where .= " AND ps.name = %4 ";
453 $params[4] = [$entityName, 'String'];
455 elseif ($entityTable == 'civicrm_participant') {
457 LEFT JOIN civicrm_price_set_entity cpse ON cpse.price_set_id = ps.id
458 LEFT JOIN civicrm_price_field_value cpfv ON cpfv.price_field_id = pf.id and cpfv.label = %4 ";
459 $set .= " ,li.label = %4,
460 li.price_field_value_id = cpfv.id ";
461 $where .= " AND cpse.entity_table = 'civicrm_event' AND cpse.entity_id = %5 ";
462 $amount = empty($amount) ?
0 : $amount;
464 4 => [$otherParams['fee_label'], 'String'],
465 5 => [$otherParams['event_id'], 'String'],
475 CRM_Core_DAO
::executeQuery($query, $params);
479 * Build line items array.
481 * @param array $params
484 * @param string $entityId
487 * @param string $entityTable
490 * @param bool $isRelatedID
492 public static function getLineItemArray(&$params, $entityId = NULL, $entityTable = 'contribution', $isRelatedID = FALSE) {
494 $priceSetDetails = CRM_Price_BAO_PriceSet
::getDefaultPriceSet($entityTable);
495 $totalAmount = $params['total_amount'] ??
0;
496 $financialType = $params['financial_type_id'] ??
NULL;
497 foreach ($priceSetDetails as $values) {
498 if ($entityTable === 'membership') {
499 if ($isRelatedID != $values['membership_type_id']) {
503 $totalAmount = $values['amount'];
505 $financialType = $values['financial_type_id'];
508 'price_field_id' => $values['priceFieldID'],
509 'price_field_value_id' => $values['priceFieldValueID'],
510 'label' => $values['label'],
512 'unit_price' => $totalAmount,
513 'line_total' => $totalAmount,
514 'financial_type_id' => $financialType,
515 'membership_type_id' => $values['membership_type_id'],
517 $lineItem['tax_amount'] = self
::getTaxAmountForLineItem($lineItem);
518 $params['line_item'][$values['setID']][$values['priceFieldID']] = $lineItem;
524 $totalEntityId = count($entityId);
525 if ($entityTable == 'contribution') {
528 foreach ($entityId as $id) {
529 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($id, $entityTable, FALSE, TRUE, $isRelatedID);
530 foreach ($lineItems as $key => $values) {
531 if (!$setID && $values['price_field_id']) {
532 $setID = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $values['price_field_id'], 'price_set_id');
533 $params['is_quick_config'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $setID, 'is_quick_config');
535 if (!empty($params['is_quick_config']) && array_key_exists('total_amount', $params)
536 && $totalEntityId == 1 && count($lineItems) == 1
538 $values['line_total'] = $values['unit_price'] = $params['total_amount'];
540 $values['id'] = $key;
541 $params['line_item'][$setID][$key] = $values;
548 * Build the line items for the submitted price field.
550 * This is when first building them - not an update where an entityId is already present
551 * as this is intended as a subfunction of that. Ideally getLineItemArray would call this
552 * (resolving to the same format regardless of what type of price set is being used first).
554 * @param array $priceParams
555 * These are per the way the form processes them - ie
556 * ['price_1' => 1, 'price_2' => 8]
557 * This would mean price field id 1, option 1 (or 1 unit if using is_enter_qty).
558 * @param float|null $overrideAmount
559 * Optional override of the amount.
561 * @param int|null $financialTypeID
562 * Financial type ID is the type should be overridden.
565 * Line items formatted for processing. These will look like
566 * [4] => ['price_field_id' => 4, 'price_field_value_id' => x, 'label....qty...unit_price...line_total...financial_type_id]
567 * [5] => ['price_field_id' => 5, 'price_field_value_id' => x, 'label....qty...unit_price...line_total...financial_type_id]
570 public static function buildLineItemsForSubmittedPriceField($priceParams, $overrideAmount = NULL, $financialTypeID = NULL) {
572 foreach ($priceParams as $key => $value) {
573 $priceField = self
::getPriceFieldMetaData($key);
575 if ($priceField['html_type'] === 'Text') {
576 $valueSpec = reset($priceField['values']);
579 $valueSpec = $priceField['values'][$value];
581 $qty = $priceField['is_enter_qty'] ?
$value : 1;
582 $lineItems[$priceField['id']] = [
583 'price_field_id' => $priceField['id'],
584 'price_field_value_id' => $valueSpec['id'],
585 'label' => $valueSpec['label'],
587 'unit_price' => $overrideAmount ?
: $valueSpec['amount'],
588 'line_total' => $qty * ($overrideAmount ?
: $valueSpec['amount']),
589 'financial_type_id' => $financialTypeID ?
: $valueSpec['financial_type_id'],
590 'membership_type_id' => $valueSpec['membership_type_id'],
591 'price_set_id' => $priceField['price_set_id'],
598 * Function to update related contribution of a entity and
599 * add/update/cancel financial records
601 * @param array $params
602 * @param int $entityID
604 * @param int $contributionId
606 * @param array $lineItems
608 * @throws \CiviCRM_API3_Exception
610 public static function changeFeeSelections(
618 $entityTable = "civicrm_" . $entity;
620 CRM_Price_BAO_PriceSet
::processAmount($feeBlock,
621 $params, $newLineItems
623 // initialize empty Lineitem instance to call protected helper functions
624 $lineItemObj = new CRM_Price_BAO_LineItem();
626 // fetch submitted LineItems from input params and feeBlock information
627 $submittedLineItems = $lineItemObj->getSubmittedLineItems($params, $feeBlock);
629 $requiredChanges = $lineItemObj->getLineItemsToAlter($submittedLineItems, $entityID, $entity);
631 // get financial information that need to be recorded on basis on submitted price field value IDs
632 if (!empty($requiredChanges['line_items_to_cancel']) ||
!empty($requiredChanges['line_items_to_update'])) {
633 // @todo - this IF is to get this through PR merge but I suspect that it should not
634 // be necessary & is masking something else.
635 $financialItemsArray = $lineItemObj->getAdjustedFinancialItemsToRecord(
639 array_keys($requiredChanges['line_items_to_cancel']),
640 $requiredChanges['line_items_to_update']
644 // update line item with changed line total and other information
645 $totalParticipant = $participantCount = 0;
647 if (!empty($requiredChanges['line_items_to_update'])) {
648 foreach ($requiredChanges['line_items_to_update'] as $priceFieldValueID => $value) {
649 $amountLevel[] = $value['label'] . ' - ' . (float) $value['qty'];
650 if ($entity == 'participant' && isset($value['participant_count'])) {
651 $totalParticipant +
= $value['participant_count'];
656 foreach (array_merge($requiredChanges['line_items_to_resurrect'], $requiredChanges['line_items_to_cancel'], $requiredChanges['line_items_to_update']) as $lineItemToAlter) {
657 // Must use BAO rather than api because a bad line it in the api which we want to avoid.
658 CRM_Price_BAO_LineItem
::create($lineItemToAlter);
661 $lineItemObj->addLineItemOnChangeFeeSelection($requiredChanges['line_items_to_add'], $entityID, $entityTable, $contributionId);
664 if ($entity == 'participant') {
665 $count = count(CRM_Event_BAO_Participant
::getParticipantIds($contributionId));
668 $count = CRM_Utils_Array
::value('count', civicrm_api3('MembershipPayment', 'getcount', ['contribution_id' => $contributionId]));
671 $updatedAmount = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
674 $updatedAmount = CRM_Utils_Array
::value('amount', $params, CRM_Utils_Array
::value('total_amount', $params));
676 if (strlen($params['tax_amount']) != 0) {
677 $taxAmount = $params['tax_amount'];
682 $displayParticipantCount = '';
683 if ($totalParticipant > 0) {
684 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
686 $updateAmountLevel = NULL;
687 if (!empty($amountLevel)) {
688 $updateAmountLevel = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amountLevel) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
690 $trxn = $lineItemObj->_recordAdjustedAmt($updatedAmount, $contributionId, $taxAmount, $updateAmountLevel);
691 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_DAO_Contribution', 'contribution_status_id', CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'contribution_status_id'));
693 if (!empty($financialItemsArray)) {
694 foreach ($financialItemsArray as $updateFinancialItemInfoValues) {
695 $newFinancialItem = CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues);
696 // record reverse transaction only if Contribution is Completed because for pending refund or
697 // partially paid we are already recording the surplus owed or refund amount
698 if (!empty($updateFinancialItemInfoValues['financialTrxn']) && ($contributionStatus == 'Completed')) {
699 $updateFinancialItemInfoValues = array_merge($updateFinancialItemInfoValues['financialTrxn'], [
700 'entity_id' => $newFinancialItem->id
,
701 'entity_table' => 'civicrm_financial_item',
703 $reverseTrxn = CRM_Core_BAO_FinancialTrxn
::create($updateFinancialItemInfoValues);
704 // record reverse entity financial trxn linked to membership's related contribution
705 civicrm_api3('EntityFinancialTrxn', 'create', [
706 'entity_table' => "civicrm_contribution",
707 'entity_id' => $contributionId,
708 'financial_trxn_id' => $reverseTrxn->id
,
709 'amount' => $reverseTrxn->total_amount
,
711 unset($updateFinancialItemInfoValues['financialTrxn']);
713 elseif ($trxn && $newFinancialItem->amount
!= 0) {
714 civicrm_api3('EntityFinancialTrxn', 'create', [
715 'entity_id' => $newFinancialItem->id
,
716 'entity_table' => 'civicrm_financial_item',
717 'financial_trxn_id' => $trxn->id
,
718 'amount' => $newFinancialItem->amount
,
724 $lineItemObj->addFinancialItemsOnLineItemsChange(array_merge($requiredChanges['line_items_to_add'], $requiredChanges['line_items_to_resurrect']), $entityID, $entityTable, $contributionId, $trxn->id ??
NULL);
726 // update participant fee_amount column
727 $lineItemObj->updateEntityRecordOnChangeFeeSelection($params, $entityID, $entity);
731 * Function to retrieve financial items that need to be recorded as result of changed fee
733 * @param int $entityID
734 * @param string $entityTable
735 * @param int $contributionID
736 * @param array $priceFieldValueIDsToCancel
737 * @param array $lineItemsToUpdate
740 * List of formatted reverse Financial Items to be recorded
742 protected function getAdjustedFinancialItemsToRecord($entityID, $entityTable, $contributionID, $priceFieldValueIDsToCancel, $lineItemsToUpdate) {
743 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, str_replace('civicrm_', '', $entityTable));
745 $financialItemsArray = [];
746 $financialItemResult = $this->getNonCancelledFinancialItems($entityID, $entityTable);
747 foreach ($financialItemResult as $updateFinancialItemInfoValues) {
748 $updateFinancialItemInfoValues['transaction_date'] = date('YmdHis');
750 // the below params are not needed as we are creating new financial item
751 $previousFinancialItemID = $updateFinancialItemInfoValues['id'];
752 $totalFinancialAmount = $this->checkFinancialItemTotalAmountByLineItemID($updateFinancialItemInfoValues['entity_id']);
753 unset($updateFinancialItemInfoValues['id']);
754 unset($updateFinancialItemInfoValues['created_date']);
755 $previousLineItem = $previousLineItems[$updateFinancialItemInfoValues['entity_id']];
757 // if not submitted and difference is not 0 make it negative
758 if ((empty($lineItemsToUpdate) ||
(in_array($updateFinancialItemInfoValues['price_field_value_id'], $priceFieldValueIDsToCancel) &&
759 $totalFinancialAmount == $updateFinancialItemInfoValues['amount'])
760 ) && $updateFinancialItemInfoValues['amount'] > 0
763 // INSERT negative financial_items
764 $updateFinancialItemInfoValues['amount'] = -$updateFinancialItemInfoValues['amount'];
765 // reverse the related financial trxn too
766 $updateFinancialItemInfoValues['financialTrxn'] = $this->getRelatedCancelFinancialTrxn($previousFinancialItemID);
767 if ($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']) {
768 $updateFinancialItemInfoValues['tax']['amount'] = -($previousLineItem['tax_amount']);
769 $updateFinancialItemInfoValues['tax']['description'] = $this->getSalesTaxTerm();
771 // INSERT negative financial_items for tax amount
772 $financialItemsArray[$updateFinancialItemInfoValues['entity_id']] = $updateFinancialItemInfoValues;
774 // INSERT a financial item to record surplus/lesser amount when a text price fee is changed
776 !empty($lineItemsToUpdate)
777 && isset($lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']])
778 && $lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']]['html_type'] == 'Text'
779 && $updateFinancialItemInfoValues['amount'] > 0
781 $amountChangeOnTextLineItem = $lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']]['line_total'] - $totalFinancialAmount;
782 if ($amountChangeOnTextLineItem !== (float) 0) {
783 // calculate the amount difference, considered as financial item amount
784 $updateFinancialItemInfoValues['amount'] = $amountChangeOnTextLineItem;
785 if ($previousLineItem['tax_amount']
786 && $previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount'] !== 0.00) {
787 $updateFinancialItemInfoValues['tax']['amount'] = $lineItemsToUpdate[$updateFinancialItemInfoValues['entity_id']]['tax_amount'] - $previousLineItem['tax_amount'];
788 $updateFinancialItemInfoValues['tax']['description'] = $this->getSalesTaxTerm();
790 $financialItemsArray[$updateFinancialItemInfoValues['entity_id']] = $updateFinancialItemInfoValues;
795 return $financialItemsArray;
799 * Helper function to return sum of financial item's amount related to a line-item
800 * @param array $lineItemID
802 * @return float $financialItem
804 protected function checkFinancialItemTotalAmountByLineItemID($lineItemID) {
805 return CRM_Core_DAO
::singleValueQuery("
807 FROM civicrm_financial_item
808 WHERE entity_table = 'civicrm_line_item' AND entity_id = {$lineItemID}
813 * Helper function to retrieve submitted line items from form values $inputParams and used $feeBlock
815 * @param array $inputParams
816 * @param array $feeBlock
819 * List of submitted line items
821 protected function getSubmittedLineItems($inputParams, $feeBlock) {
822 $submittedLineItems = [];
823 foreach ($feeBlock as $id => $values) {
824 CRM_Price_BAO_LineItem
::format($id, $inputParams, $values, $submittedLineItems);
827 return $submittedLineItems;
831 * Helper function to retrieve line items that need to be altered.
833 * We iterate through the previous line items for the given entity to determine
834 * what alterations to line items need to be made to reflect the new line items.
836 * There are 4 possible changes required - per the keys in the return array.
838 * @param array $submittedLineItems
839 * @param int $entityID
840 * @param string $entity
843 * Array of line items to alter with the following keys
844 * - line_items_to_add. If the line items required are new radio options that
845 * have not previously been set then we should add line items for them
846 * - line_items_to_update. If we have already been an active option and a change has
847 * happened then it should be in this array.
848 * - line_items_to_cancel. Line items currently selected but not selected in the new selection.
849 * These need to be zero'd out.
850 * - line_items_to_resurrect. Line items previously selected and then deselected. These need to be
851 * re-enabled rather than a new one added.
853 protected function getLineItemsToAlter($submittedLineItems, $entityID, $entity) {
854 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, $entity);
856 $lineItemsToAdd = $submittedLineItems;
857 $lineItemsToUpdate = [];
858 $submittedPriceFieldValueIDs = array_keys($submittedLineItems);
859 $lineItemsToCancel = $lineItemsToResurrect = [];
861 foreach ($previousLineItems as $id => $previousLineItem) {
862 if (in_array($previousLineItem['price_field_value_id'], $submittedPriceFieldValueIDs)) {
863 $submittedLineItem = $submittedLineItems[$previousLineItem['price_field_value_id']];
864 if (CRM_Utils_Array
::value('html_type', $lineItemsToAdd[$previousLineItem['price_field_value_id']]) == 'Text') {
865 // If a 'Text' price field was updated by changing qty value, then we are not adding new line-item but updating the existing one,
866 // 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
867 // exception here by adding financial item for updated line-item and will reverse any previous financial item entries.
868 $lineItemsToUpdate[$previousLineItem['price_field_value_id']] = array_merge($submittedLineItem, ['id' => $id]);
869 unset($lineItemsToAdd[$previousLineItem['price_field_value_id']]);
872 $submittedLineItem = $submittedLineItems[$previousLineItem['price_field_value_id']];
873 // for updating the line items i.e. use-case - once deselect-option selecting again
874 if (($previousLineItem['line_total'] != $submittedLineItem['line_total'])
876 // This would be a $0 line item - but why it should be catered to
877 // other than when the above condition is unclear.
878 $submittedLineItem['line_total'] == 0 && $submittedLineItem['qty'] == 1
881 $previousLineItem['qty'] != $submittedLineItem['qty']
884 $lineItemsToUpdate[$previousLineItem['price_field_value_id']] = $submittedLineItem;
885 $lineItemsToUpdate[$previousLineItem['price_field_value_id']]['id'] = $id;
886 // Format is actually '0.00'
887 if ($previousLineItem['line_total'] == 0) {
888 $lineItemsToAdd[$previousLineItem['price_field_value_id']]['id'] = $id;
889 $lineItemsToResurrect[] = $lineItemsToAdd[$previousLineItem['price_field_value_id']];
892 // If there was previously a submitted line item for the same option value then there is
893 // either no change or a qty adjustment. In either case we are not doing an add + reversal.
894 unset($lineItemsToAdd[$previousLineItem['price_field_value_id']]);
895 unset($lineItemsToCancel[$previousLineItem['price_field_value_id']]);
899 if (!$this->isCancelled($previousLineItem)) {
900 $cancelParams = ['qty' => 0, 'line_total' => 0, 'tax_amount' => 0, 'participant_count' => 0, 'non_deductible_amount' => 0, 'id' => $id];
901 $lineItemsToCancel[$previousLineItem['price_field_value_id']] = array_merge($previousLineItem, $cancelParams);
908 'line_items_to_add' => $lineItemsToAdd,
909 'line_items_to_update' => $lineItemsToUpdate,
910 'line_items_to_cancel' => $lineItemsToCancel,
911 'line_items_to_resurrect' => $lineItemsToResurrect,
916 * Check if a line item has already been cancelled.
918 * @param array $lineItem
922 protected function isCancelled($lineItem) {
923 if ($lineItem['qty'] == 0 && $lineItem['line_total'] == 0) {
929 * Add line Items as result of fee change.
931 * @param array $lineItemsToAdd
932 * @param int $entityID
933 * @param string $entityTable
934 * @param int $contributionID
936 protected function addLineItemOnChangeFeeSelection(
942 // if there is no line item to add, do not proceed
943 if (empty($lineItemsToAdd)) {
947 $changedFinancialTypeID = NULL;
948 $updatedContribution = new CRM_Contribute_BAO_Contribution();
949 $updatedContribution->id
= (int) $contributionID;
950 // insert financial items
951 foreach ($lineItemsToAdd as $priceFieldValueID => $lineParams) {
952 $lineParams = array_merge($lineParams, [
953 'entity_table' => $entityTable,
954 'entity_id' => $entityID,
955 'contribution_id' => $contributionID,
957 if (!array_key_exists('skip', $lineParams)) {
958 self
::create($lineParams);
962 if ($changedFinancialTypeID) {
963 $updatedContribution->financial_type_id
= $changedFinancialTypeID;
964 $updatedContribution->save();
969 * Add financial transactions when an array of line items is changed.
971 * @param array $lineItemsToAdd
972 * @param int $entityID
973 * @param string $entityTable
974 * @param int $contributionID
975 * @param bool $trxnID
976 * Is there a change to the total balance requiring additional transactions to be created.
978 protected function addFinancialItemsOnLineItemsChange($lineItemsToAdd, $entityID, $entityTable, $contributionID, $trxnID) {
979 $updatedContribution = new CRM_Contribute_BAO_Contribution();
980 $updatedContribution->id
= $contributionID;
981 $updatedContribution->find(TRUE);
982 $trxnArray = $trxnID ?
['id' => $trxnID] : NULL;
984 foreach ($lineItemsToAdd as $priceFieldValueID => $lineParams) {
985 $lineParams = array_merge($lineParams, [
986 'entity_table' => $entityTable,
987 'entity_id' => $entityID,
988 'contribution_id' => $contributionID,
990 $lineObj = CRM_Price_BAO_LineItem
::retrieve($lineParams);
991 // insert financial items
992 // ensure entity_financial_trxn table has a linking of it.
993 CRM_Financial_BAO_FinancialItem
::add($lineObj, $updatedContribution, NULL, $trxnArray);
994 if (isset($lineObj->tax_amount
) && (float) $lineObj->tax_amount
!== 0.00) {
995 CRM_Financial_BAO_FinancialItem
::add($lineObj, $updatedContribution, TRUE, $trxnArray);
1001 * Helper function to update entity record on change fee selection
1003 * @param array $inputParams
1004 * @param int $entityID
1005 * @param string $entity
1008 protected function updateEntityRecordOnChangeFeeSelection($inputParams, $entityID, $entity) {
1009 $entityTable = "civicrm_{$entity}";
1011 if ($entity == 'participant') {
1012 $partUpdateFeeAmt = ['id' => $entityID];
1013 $getUpdatedLineItems = "SELECT *
1014 FROM civicrm_line_item
1015 WHERE (entity_table = '{$entityTable}' AND entity_id = {$entityID} AND qty > 0)";
1016 $getUpdatedLineItemsDAO = CRM_Core_DAO
::executeQuery($getUpdatedLineItems);
1018 while ($getUpdatedLineItemsDAO->fetch()) {
1019 $line[$getUpdatedLineItemsDAO->price_field_value_id
] = $getUpdatedLineItemsDAO->label
. ' - ' . (float) $getUpdatedLineItemsDAO->qty
;
1022 $partUpdateFeeAmt['fee_level'] = implode(', ', $line);
1023 $partUpdateFeeAmt['fee_amount'] = $inputParams['amount'];
1024 CRM_Event_BAO_Participant
::add($partUpdateFeeAmt);
1027 CRM_Event_BAO_Participant
::addActivityForSelection($entityID, 'Change Registration');
1032 * Get the metadata for a price field.
1034 * @param string|int $key
1035 * Price field id. Either as an integer or as 'price_4' where 4 is the id
1038 * Metadata for the price field with a values key for option values.
1040 protected static function getPriceFieldMetaData($key) {
1041 $priceFieldID = str_replace('price_', '', $key);
1042 if (!isset(Civi
::$statics[__CLASS__
]['price_fields'][$priceFieldID])) {
1043 $values = civicrm_api3('PriceFieldValue', 'get', [
1044 'price_field_id' => $priceFieldID,
1048 'financial_type_id',
1049 'membership_type_id',
1052 'price_field_id.price_set_id',
1053 'price_field_id.html_type',
1057 $firstValue = reset($values['values']);
1058 $values = $values['values'];
1059 foreach ($values as $index => $value) {
1060 // Let's be nice to calling functions & ensure membership_type_id is set
1061 // so they don't have to handle notices on it. Handle one place not many.
1062 if (!isset($value['membership_type_id'])) {
1063 $values[$index]['membership_type_id'] = NULL;
1067 Civi
::$statics[__CLASS__
]['price_fields'][$priceFieldID] = [
1068 'price_set_id' => $firstValue['price_field_id.price_set_id'],
1069 'id' => $firstValue['price_field_id'],
1070 'html_type' => $firstValue['price_field_id.html_type'],
1071 'is_enter_qty' => !empty($firstValue['is_enter_qty']),
1072 'values' => $values,
1075 return Civi
::$statics[__CLASS__
]['price_fields'][$priceFieldID];
1079 * Get the tax rate for the given line item.
1081 * @param array $params
1085 protected static function getTaxAmountForLineItem(array $params): float {
1086 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
1087 $taxRate = $taxRates[$params['financial_type_id']] ??
0;
1088 return ($taxRate / 100) * $params['line_total'];
1092 * Helper function to retrieve financial trxn parameters to reverse
1093 * for given financial item identified by $financialItemID
1095 * @param int $financialItemID
1097 * @return array $financialTrxn
1100 protected function _getRelatedCancelFinancialTrxn($financialItemID) {
1102 $financialTrxn = civicrm_api3('EntityFinancialTrxn', 'getsingle', [
1103 'entity_table' => 'civicrm_financial_item',
1104 'entity_id' => $financialItemID,
1106 'sort' => 'id DESC',
1109 'api.FinancialTrxn.getsingle' => [
1110 'id' => "\$value.financial_trxn_id",
1114 catch (CiviCRM_API3_Exception
$e) {
1118 $financialTrxn = array_merge($financialTrxn['api.FinancialTrxn.getsingle'], [
1119 'trxn_date' => date('YmdHis'),
1120 'total_amount' => -$financialTrxn['api.FinancialTrxn.getsingle']['total_amount'],
1121 'net_amount' => -$financialTrxn['api.FinancialTrxn.getsingle']['net_amount'],
1122 'entity_table' => 'civicrm_financial_item',
1123 'entity_id' => $financialItemID,
1125 unset($financialTrxn['id']);
1127 return $financialTrxn;
1131 * Record adjusted amount.
1133 * @param int $updatedAmount
1134 * @param int $contributionId
1135 * @param int $taxAmount
1136 * @param bool $updateAmountLevel
1138 * @return bool|\CRM_Core_BAO_FinancialTrxn
1140 protected function _recordAdjustedAmt($updatedAmount, $contributionId, $taxAmount = NULL, $updateAmountLevel = NULL) {
1141 $paidAmount = (float) CRM_Core_BAO_FinancialTrxn
::getTotalPayments($contributionId);
1142 $balanceAmt = $updatedAmount - $paidAmount;
1144 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1145 $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
1146 $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
1147 $completedStatusId = array_search('Completed', $contributionStatuses);
1149 $updatedContributionDAO = new CRM_Contribute_BAO_Contribution();
1150 $adjustedTrxn = FALSE;
1152 if ($paidAmount === 0.0) {
1153 //skip updating the contribution status if no payment is made
1154 $updatedContributionDAO->cancel_date
= 'null';
1155 $updatedContributionDAO->cancel_reason
= NULL;
1158 $updatedContributionDAO->contribution_status_id
= $balanceAmt > 0 ?
$partiallyPaidStatusId : $pendingRefundStatusId;
1161 // update contribution status and total amount without trigger financial code
1162 // as this is handled in current BAO function used for change selection
1163 $updatedContributionDAO->id
= $contributionId;
1165 $updatedContributionDAO->total_amount
= $updatedContributionDAO->net_amount
= $updatedAmount;
1166 $updatedContributionDAO->fee_amount
= 0;
1167 $updatedContributionDAO->tax_amount
= $taxAmount;
1168 if (!empty($updateAmountLevel)) {
1169 $updatedContributionDAO->amount_level
= $updateAmountLevel;
1171 $updatedContributionDAO->save();
1172 // adjusted amount financial_trxn creation
1173 $updatedContribution = CRM_Contribute_BAO_Contribution
::getValues(
1174 ['id' => $contributionId]
1176 $toFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($updatedContribution->financial_type_id
, 'Accounts Receivable Account is');
1177 $adjustedTrxnValues = [
1178 'from_financial_account_id' => NULL,
1179 'to_financial_account_id' => $toFinancialAccount,
1180 'total_amount' => $balanceAmt,
1181 'net_amount' => $balanceAmt,
1182 'status_id' => $completedStatusId,
1183 'payment_instrument_id' => $updatedContribution->payment_instrument_id
,
1184 'contribution_id' => $updatedContribution->id
,
1185 'trxn_date' => date('YmdHis'),
1186 'currency' => $updatedContribution->currency
,
1188 $adjustedTrxn = CRM_Core_BAO_FinancialTrxn
::create($adjustedTrxnValues);
1190 // CRM-17151: Update the contribution status to completed if balance is zero,
1191 // because due to sucessive fee change will leave the related contribution status incorrect
1193 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'contribution_status_id', $completedStatusId);
1196 return $adjustedTrxn;
1200 * Get Financial items, culling out any that have already been reversed.
1202 * @param int $entityID
1203 * @param string $entityTable
1206 * Array of financial items that have not be reversed.
1208 protected function getNonCancelledFinancialItems($entityID, $entityTable) {
1209 // gathering necessary info to record negative (deselected) financial_item
1210 $updateFinancialItem = "
1211 SELECT fi.*, price_field_value_id, financial_type_id, tax_amount
1212 FROM civicrm_financial_item fi LEFT JOIN civicrm_line_item li ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1213 WHERE (li.entity_table = '{$entityTable}' AND li.entity_id = {$entityID})
1214 GROUP BY li.entity_table, li.entity_id, price_field_value_id, fi.id
1216 $updateFinancialItemInfoDAO = CRM_Core_DAO
::executeQuery($updateFinancialItem);
1218 $financialItemResult = $updateFinancialItemInfoDAO->fetchAll();
1220 foreach ($financialItemResult as $index => $financialItem) {
1221 $items[$financialItem['price_field_value_id']][$index] = $financialItem['amount'];
1223 if (!empty($items[$financialItem['price_field_value_id']])) {
1224 foreach ($items[$financialItem['price_field_value_id']] as $existingItemID => $existingAmount) {
1225 if ($financialItem['amount'] +
$existingAmount == 0) {
1226 // Filter both rows as they cancel each other out.
1227 unset($financialItemResult[$index]);
1228 unset($financialItemResult[$existingItemID]);
1229 unset($items['price_field_value_id'][$existingItemID]);
1230 unset($items[$financialItem['price_field_value_id']][$index]);
1237 return $financialItemResult;
1241 * Get the string used to describe the sales tax (eg. VAT, GST).
1245 protected function getSalesTaxTerm() {
1246 return CRM_Contribute_BAO_Contribution
::checkContributeSettings('tax_term');
1250 * Whitelist of possible values for the entity_table field
1254 public static function entityTables(): array {
1256 'civicrm_contribution' => ts('Contribution'),
1257 'civicrm_participant' => ts('Participant'),
1258 'civicrm_membership' => ts('Membership'),