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);
75 if ($lineItemBAO->entity_table
=== 'civicrm_participant' && $lineItemBAO->contribution_id
&& $lineItemBAO->entity_id
) {
76 $participantPaymentParams = [
77 'participant_id' => $lineItemBAO->entity_id
,
78 'contribution_id' => $lineItemBAO->contribution_id
,
80 if (!civicrm_api3('ParticipantPayment', 'getcount', $participantPaymentParams)) {
81 civicrm_api3('ParticipantPayment', 'create', $participantPaymentParams);
86 // CRM-21281: Restore entity reference in case the post hook needs it
87 $lineItemBAO->entity_id
= $entity_id;
88 $lineItemBAO->entity_table
= $entity_table;
89 CRM_Utils_Hook
::post('edit', 'LineItem', $id, $lineItemBAO);
92 CRM_Utils_Hook
::post('create', 'LineItem', $lineItemBAO->id
, $lineItemBAO);
99 * Retrieve DB object based on input parameters.
101 * It also stores all the retrieved values in the default array.
103 * @param array $params
104 * (reference ) an assoc array of name/value pairs.
105 * @param array $defaults
106 * (reference ) an assoc array to hold the flattened values.
108 * @return CRM_Price_BAO_LineItem
110 public static function retrieve(&$params = [], &$defaults = []) {
111 $lineItem = new CRM_Price_BAO_LineItem();
112 $lineItem->copyValues($params);
113 if ($lineItem->find(TRUE)) {
114 CRM_Core_DAO
::storeValues($lineItem, $defaults);
121 * @param int $contributionId
123 * @return null|string
125 public static function getLineTotal($contributionId) {
126 $sqlLineItemTotal = "SELECT SUM(li.line_total + COALESCE(li.tax_amount,0))
127 FROM civicrm_line_item li
128 WHERE li.contribution_id = %1";
129 $params = [1 => [$contributionId, 'Integer']];
130 $lineItemTotal = CRM_Core_DAO
::singleValueQuery($sqlLineItemTotal, $params);
131 return $lineItemTotal;
135 * Wrapper for line item retrieval when contribution ID is known.
136 * @param int $contributionID
140 public static function getLineItemsByContributionID($contributionID) {
141 return self
::getLineItems($contributionID, 'contribution', NULL, TRUE, TRUE);
145 * Given a participant id/contribution id,
146 * return contribution/fee line items
148 * @param int $entityId
149 * participant/contribution id.
150 * @param string $entity
151 * participant/contribution.
153 * @param bool $isQuick
154 * @param bool $isQtyZero
155 * @param bool $relatedEntity
158 * Array of line items
160 public static function getLineItems($entityId, $entity = 'participant', $isQuick = FALSE, $isQtyZero = TRUE, $relatedEntity = FALSE) {
161 $whereClause = $fromClause = NULL;
171 pf.label as field_title,
174 pfv.membership_type_id,
175 pfv.membership_num_terms,
177 li.participant_count,
178 li.price_field_value_id,
179 li.financial_type_id,
183 $condition = "li.entity_id = civicrm_%2.id AND li.entity_table = 'civicrm_%2'";
184 if ($relatedEntity) {
185 $condition = 'li.contribution_id = civicrm_%2.id ';
190 LEFT JOIN civicrm_line_item li ON ({$condition})
191 LEFT JOIN civicrm_price_field_value pfv ON (pfv.id = li.price_field_value_id)
192 LEFT JOIN civicrm_price_field pf ON (pf.id = li.price_field_id )";
193 $whereClause = " WHERE civicrm_%2.id = %1";
194 $orderByClause = " ORDER BY pf.weight, pfv.weight";
197 $fromClause .= " LEFT JOIN civicrm_price_set cps on cps.id = pf.price_set_id ";
198 $whereClause .= " and cps.is_quick_config = 0";
202 $whereClause .= " and li.qty != 0";
207 if (!$entityId ||
!$entity ||
!$fromClause) {
212 1 => [$entityId, 'Integer'],
213 2 => [$entity, 'Text'],
216 $getTaxDetails = FALSE;
217 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
218 $invoicing = $invoiceSettings['invoicing'] ??
NULL;
220 $dao = CRM_Core_DAO
::executeQuery("$selectClause $fromClause $whereClause $orderByClause", $params);
221 while ($dao->fetch()) {
225 $lineItems[$dao->id
] = [
226 'qty' => (float) $dao->qty
,
227 'label' => $dao->label
,
228 'unit_price' => $dao->unit_price
,
229 'line_total' => $dao->line_total
,
230 'price_field_id' => $dao->price_field_id
,
231 'participant_count' => $dao->participant_count
,
232 'price_field_value_id' => $dao->price_field_value_id
,
233 'field_title' => $dao->field_title
,
234 'html_type' => $dao->html_type
,
235 'description' => $dao->description
,
236 'entity_id' => $dao->entity_id
,
237 'entity_table' => $dao->entity_table
,
238 'contribution_id' => $dao->contribution_id
,
239 'financial_type_id' => $dao->financial_type_id
,
240 'financial_type' => CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'financial_type_id', $dao->financial_type_id
),
241 'membership_type_id' => $dao->membership_type_id
,
242 'membership_num_terms' => $dao->membership_num_terms
,
243 'tax_amount' => (float) $dao->tax_amount
,
244 'price_set_id' => $dao->price_set_id
,
246 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
247 if (isset($lineItems[$dao->id
]['financial_type_id']) && array_key_exists($lineItems[$dao->id
]['financial_type_id'], $taxRates)) {
248 // Cast to float so trailing zero decimals are removed for display.
249 $lineItems[$dao->id
]['tax_rate'] = (float) $taxRates[$lineItems[$dao->id
]['financial_type_id']];
252 // There is no Tax Rate associated with this Financial Type
253 $lineItems[$dao->id
]['tax_rate'] = FALSE;
255 $lineItems[$dao->id
]['subTotal'] = $lineItems[$dao->id
]['qty'] * $lineItems[$dao->id
]['unit_price'];
256 if ($lineItems[$dao->id
]['tax_amount'] != '') {
257 $getTaxDetails = TRUE;
261 // @todo - this is an inappropriate place to be doing form level assignments.
262 $taxTerm = Civi
::settings()->get('tax_term');
263 $smarty = CRM_Core_Smarty
::singleton();
264 $smarty->assign('taxTerm', $taxTerm);
265 $smarty->assign('getTaxDetails', $getTaxDetails);
271 * This method will create the lineItem array required for
272 * processAmount method
275 * Price set field id.
276 * @param array $params
277 * Reference to form values.
278 * @param array $fields
279 * Array of fields belonging to the price set used for particular event
280 * @param array $values
281 * Reference to the values array(.
284 * @param string $amount_override
285 * Amount override must be in format 1000.00 - ie no thousand separator & if
286 * a decimal point is used it should be a decimal
288 * @todo - this parameter is only used for partial payments. It's unclear why a partial
289 * payment would change the line item price.
291 public static function format($fid, $params, $fields, &$values, $amount_override = NULL) {
292 if (empty($params["price_{$fid}"])) {
296 //lets first check in fun parameter,
297 //since user might modified w/ hooks.
299 if (array_key_exists('options', $fields)) {
300 $options = $fields['options'];
303 CRM_Price_BAO_PriceFieldValue
::getValues($fid, $options, 'weight', TRUE);
305 $fieldTitle = $fields['label'] ??
NULL;
307 $fieldTitle = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'label');
310 foreach ($params["price_{$fid}"] as $oid => $qty) {
311 $price = $amount_override === NULL ?
$options[$oid]['amount'] : $amount_override;
313 $participantsPerField = CRM_Utils_Array
::value('count', $options[$oid], 0);
316 'price_field_id' => $fid,
317 'price_field_value_id' => $oid,
318 'label' => $options[$oid]['label'] ??
NULL,
319 'field_title' => $fieldTitle,
320 'description' => $options[$oid]['description'] ??
NULL,
322 'unit_price' => $price,
323 'line_total' => $qty * $price,
324 'participant_count' => $qty * $participantsPerField,
325 'max_value' => $options[$oid]['max_value'] ??
NULL,
326 'membership_type_id' => $options[$oid]['membership_type_id'] ??
NULL,
327 'membership_num_terms' => $options[$oid]['membership_num_terms'] ??
NULL,
328 'auto_renew' => $options[$oid]['auto_renew'] ??
NULL,
329 'html_type' => $fields['html_type'],
330 'financial_type_id' => $options[$oid]['financial_type_id'] ??
NULL,
331 'tax_amount' => CRM_Utils_Array
::value('tax_amount', $options[$oid], 0),
332 'non_deductible_amount' => $options[$oid]['non_deductible_amount'] ??
NULL,
335 if ($values[$oid]['membership_type_id'] && empty($values[$oid]['auto_renew'])) {
336 $values[$oid]['auto_renew'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $values[$oid]['membership_type_id'], 'auto_renew');
342 * Delete line items for given entity.
344 * @param int $entityId
345 * @param int $entityTable
349 public static function deleteLineItems($entityId, $entityTable) {
350 if (!$entityId ||
!$entityTable) {
354 if ($entityId && !is_array($entityId)) {
355 $entityId = [$entityId];
359 foreach ($entityId as $id) {
360 CRM_Utils_Hook
::pre('delete', 'LineItem', $id, $params);
363 $query = "DELETE FROM civicrm_line_item where entity_id IN ('" . implode("','", $entityId) . "') AND entity_table = '$entityTable'";
364 $dao = CRM_Core_DAO
::executeQuery($query);
369 * Process price set and line items.
371 * @param int $entityId
372 * @param array $lineItems
374 * @param object $contributionDetails
375 * @param string $entityTable
378 * @param bool $update
380 * @throws \CRM_Core_Exception
381 * @throws \CiviCRM_API3_Exception
383 public static function processPriceSet($entityId, $lineItems, $contributionDetails = NULL, $entityTable = 'civicrm_contribution', $update = FALSE) {
384 if (!$entityId ||
!is_array($lineItems)
385 || CRM_Utils_System
::isNull($lineItems)
390 foreach ($lineItems as $priceSetId => &$values) {
395 foreach ($values as &$line) {
396 if (empty($line['entity_table'])) {
397 $line['entity_table'] = $entityTable;
399 if (empty($line['entity_id'])) {
400 $line['entity_id'] = $entityId;
402 if (!empty($line['membership_type_id'])) {
403 $line['entity_table'] = 'civicrm_membership';
405 if (!empty($contributionDetails->id
)) {
406 $line['contribution_id'] = $contributionDetails->id
;
407 if ($line['entity_table'] === 'civicrm_contribution') {
408 $line['entity_id'] = $contributionDetails->id
;
412 // if financial type is not set and if price field value is NOT NULL
413 // get financial type id of price field value
414 if (!empty($line['price_field_value_id']) && empty($line['financial_type_id'])) {
415 $line['financial_type_id'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $line['price_field_value_id'], 'financial_type_id');
417 $createdLineItem = CRM_Price_BAO_LineItem
::create($line);
418 if (!$update && $contributionDetails) {
419 $financialItem = CRM_Financial_BAO_FinancialItem
::add($createdLineItem, $contributionDetails);
420 $line['financial_item_id'] = $financialItem->id
;
421 if (!empty($line['tax_amount'])) {
422 CRM_Financial_BAO_FinancialItem
::add($createdLineItem, $contributionDetails, TRUE);
427 if (!$update && $contributionDetails) {
428 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn($lineItems, $contributionDetails);
433 * @param int $entityId
434 * @param string $entityTable
436 * @param array $otherParams
438 public static function syncLineItems($entityId, $entityTable, $amount, $otherParams = NULL) {
439 if (!$entityId || CRM_Utils_System
::isNull($amount)) {
443 $from = " civicrm_line_item li
444 LEFT JOIN civicrm_price_field pf ON pf.id = li.price_field_id
445 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id ";
447 $set = " li.unit_price = %3,
448 li.line_total = %3 ";
450 $where = " li.entity_id = %1 AND
451 li.entity_table = %2 ";
454 1 => [$entityId, 'Integer'],
455 2 => [$entityTable, 'String'],
456 3 => [$amount, 'Float'],
459 if ($entityTable == 'civicrm_contribution') {
460 $entityName = 'default_contribution_amount';
461 $where .= " AND ps.name = %4 ";
462 $params[4] = [$entityName, 'String'];
464 elseif ($entityTable == 'civicrm_participant') {
466 LEFT JOIN civicrm_price_set_entity cpse ON cpse.price_set_id = ps.id
467 LEFT JOIN civicrm_price_field_value cpfv ON cpfv.price_field_id = pf.id and cpfv.label = %4 ";
468 $set .= " ,li.label = %4,
469 li.price_field_value_id = cpfv.id ";
470 $where .= " AND cpse.entity_table = 'civicrm_event' AND cpse.entity_id = %5 ";
471 $amount = empty($amount) ?
0 : $amount;
473 4 => [$otherParams['fee_label'], 'String'],
474 5 => [$otherParams['event_id'], 'String'],
484 CRM_Core_DAO
::executeQuery($query, $params);
488 * Build line items array.
490 * @param array $params
493 * @param string $entityId
496 * @param string $entityTable
499 * @param bool $isRelatedID
501 public static function getLineItemArray(&$params, $entityId = NULL, $entityTable = 'contribution', $isRelatedID = FALSE) {
503 $priceSetDetails = CRM_Price_BAO_PriceSet
::getDefaultPriceSet($entityTable);
504 $totalAmount = $params['total_amount'] ??
0;
505 $financialType = $params['financial_type_id'] ??
NULL;
506 foreach ($priceSetDetails as $values) {
507 if ($entityTable === 'membership') {
508 if ($isRelatedID != $values['membership_type_id']) {
512 $totalAmount = $values['amount'];
514 $financialType = $values['financial_type_id'];
517 'price_field_id' => $values['priceFieldID'],
518 'price_field_value_id' => $values['priceFieldValueID'],
519 'label' => $values['label'],
521 'unit_price' => $totalAmount,
522 'line_total' => $totalAmount,
523 'financial_type_id' => $financialType,
524 'membership_type_id' => $values['membership_type_id'],
526 $lineItem['tax_amount'] = self
::getTaxAmountForLineItem($lineItem);
527 $params['line_item'][$values['setID']][$values['priceFieldID']] = $lineItem;
533 $totalEntityId = count($entityId);
534 if ($entityTable == 'contribution') {
537 foreach ($entityId as $id) {
538 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($id, $entityTable, FALSE, TRUE, $isRelatedID);
539 foreach ($lineItems as $key => $values) {
540 if (!$setID && $values['price_field_id']) {
541 $setID = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $values['price_field_id'], 'price_set_id');
542 $params['is_quick_config'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $setID, 'is_quick_config');
544 if (!empty($params['is_quick_config']) && array_key_exists('total_amount', $params)
545 && $totalEntityId == 1 && count($lineItems) == 1
547 $values['line_total'] = $values['unit_price'] = $params['total_amount'];
549 $values['id'] = $key;
550 $params['line_item'][$setID][$key] = $values;
557 * Build the line items for the submitted price field.
559 * This is when first building them - not an update where an entityId is already present
560 * as this is intended as a subfunction of that. Ideally getLineItemArray would call this
561 * (resolving to the same format regardless of what type of price set is being used first).
563 * @param array $priceParams
564 * These are per the way the form processes them - ie
565 * ['price_1' => 1, 'price_2' => 8]
566 * This would mean price field id 1, option 1 (or 1 unit if using is_enter_qty).
567 * @param float|null $overrideAmount
568 * Optional override of the amount.
570 * @param int|null $financialTypeID
571 * Financial type ID is the type should be overridden.
574 * Line items formatted for processing. These will look like
575 * [4] => ['price_field_id' => 4, 'price_field_value_id' => x, 'label....qty...unit_price...line_total...financial_type_id]
576 * [5] => ['price_field_id' => 5, 'price_field_value_id' => x, 'label....qty...unit_price...line_total...financial_type_id]
579 public static function buildLineItemsForSubmittedPriceField($priceParams, $overrideAmount = NULL, $financialTypeID = NULL) {
581 foreach ($priceParams as $key => $value) {
582 $priceField = self
::getPriceFieldMetaData($key);
584 if ($priceField['html_type'] === 'Text') {
585 $valueSpec = reset($priceField['values']);
588 $valueSpec = $priceField['values'][$value];
590 $qty = $priceField['is_enter_qty'] ?
$value : 1;
591 $lineItems[$priceField['id']] = [
592 'price_field_id' => $priceField['id'],
593 'price_field_value_id' => $valueSpec['id'],
594 'label' => $valueSpec['label'],
596 'unit_price' => $overrideAmount ?
: $valueSpec['amount'],
597 'line_total' => $qty * ($overrideAmount ?
: $valueSpec['amount']),
598 'financial_type_id' => $financialTypeID ?
: $valueSpec['financial_type_id'],
599 'membership_type_id' => $valueSpec['membership_type_id'],
600 'price_set_id' => $priceField['price_set_id'],
607 * Function to update related contribution of a entity and
608 * add/update/cancel financial records
610 * @param array $params
611 * @param int $entityID
613 * @param int $contributionId
615 * @param array $lineItems
617 * @throws \CiviCRM_API3_Exception
619 public static function changeFeeSelections(
627 $entityTable = "civicrm_" . $entity;
629 CRM_Price_BAO_PriceSet
::processAmount($feeBlock,
630 $params, $newLineItems
632 // initialize empty Lineitem instance to call protected helper functions
633 $lineItemObj = new CRM_Price_BAO_LineItem();
635 // fetch submitted LineItems from input params and feeBlock information
636 $submittedLineItems = $lineItemObj->getSubmittedLineItems($params, $feeBlock);
638 $requiredChanges = $lineItemObj->getLineItemsToAlter($submittedLineItems, $entityID, $entity);
640 // get financial information that need to be recorded on basis on submitted price field value IDs
641 if (!empty($requiredChanges['line_items_to_cancel']) ||
!empty($requiredChanges['line_items_to_update'])) {
642 // @todo - this IF is to get this through PR merge but I suspect that it should not
643 // be necessary & is masking something else.
644 $financialItemsArray = $lineItemObj->getAdjustedFinancialItemsToRecord(
648 array_keys($requiredChanges['line_items_to_cancel']),
649 $requiredChanges['line_items_to_update']
653 // update line item with changed line total and other information
654 $totalParticipant = $participantCount = 0;
656 if (!empty($requiredChanges['line_items_to_update'])) {
657 foreach ($requiredChanges['line_items_to_update'] as $priceFieldValueID => $value) {
658 $amountLevel[] = $value['label'] . ' - ' . (float) $value['qty'];
659 if ($entity == 'participant' && isset($value['participant_count'])) {
660 $totalParticipant +
= $value['participant_count'];
665 foreach (array_merge($requiredChanges['line_items_to_resurrect'], $requiredChanges['line_items_to_cancel'], $requiredChanges['line_items_to_update']) as $lineItemToAlter) {
666 // Must use BAO rather than api because a bad line it in the api which we want to avoid.
667 CRM_Price_BAO_LineItem
::create($lineItemToAlter);
670 $lineItemObj->addLineItemOnChangeFeeSelection($requiredChanges['line_items_to_add'], $entityID, $entityTable, $contributionId);
673 if ($entity == 'participant') {
674 $count = count(CRM_Event_BAO_Participant
::getParticipantIds($contributionId));
677 $count = CRM_Utils_Array
::value('count', civicrm_api3('MembershipPayment', 'getcount', ['contribution_id' => $contributionId]));
680 $updatedAmount = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
683 $updatedAmount = CRM_Utils_Array
::value('amount', $params, CRM_Utils_Array
::value('total_amount', $params));
685 if (strlen($params['tax_amount']) != 0) {
686 $taxAmount = $params['tax_amount'];
691 $displayParticipantCount = '';
692 if ($totalParticipant > 0) {
693 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
695 $updateAmountLevel = NULL;
696 if (!empty($amountLevel)) {
697 $updateAmountLevel = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amountLevel) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
699 $trxn = $lineItemObj->_recordAdjustedAmt($updatedAmount, $contributionId, $taxAmount, $updateAmountLevel);
700 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_DAO_Contribution', 'contribution_status_id', CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'contribution_status_id'));
702 if (!empty($financialItemsArray)) {
703 foreach ($financialItemsArray as $updateFinancialItemInfoValues) {
704 $newFinancialItem = CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues);
705 // record reverse transaction only if Contribution is Completed because for pending refund or
706 // partially paid we are already recording the surplus owed or refund amount
707 if (!empty($updateFinancialItemInfoValues['financialTrxn']) && ($contributionStatus == 'Completed')) {
708 $updateFinancialItemInfoValues = array_merge($updateFinancialItemInfoValues['financialTrxn'], [
709 'entity_id' => $newFinancialItem->id
,
710 'entity_table' => 'civicrm_financial_item',
712 $reverseTrxn = CRM_Core_BAO_FinancialTrxn
::create($updateFinancialItemInfoValues);
713 // record reverse entity financial trxn linked to membership's related contribution
714 civicrm_api3('EntityFinancialTrxn', 'create', [
715 'entity_table' => "civicrm_contribution",
716 'entity_id' => $contributionId,
717 'financial_trxn_id' => $reverseTrxn->id
,
718 'amount' => $reverseTrxn->total_amount
,
720 unset($updateFinancialItemInfoValues['financialTrxn']);
722 elseif ($trxn && $newFinancialItem->amount
!= 0) {
723 civicrm_api3('EntityFinancialTrxn', 'create', [
724 'entity_id' => $newFinancialItem->id
,
725 'entity_table' => 'civicrm_financial_item',
726 'financial_trxn_id' => $trxn->id
,
727 'amount' => $newFinancialItem->amount
,
733 $lineItemObj->addFinancialItemsOnLineItemsChange(array_merge($requiredChanges['line_items_to_add'], $requiredChanges['line_items_to_resurrect']), $entityID, $entityTable, $contributionId, $trxn->id ??
NULL);
735 // update participant fee_amount column
736 $lineItemObj->updateEntityRecordOnChangeFeeSelection($params, $entityID, $entity);
740 * Function to retrieve financial items that need to be recorded as result of changed fee
742 * @param int $entityID
743 * @param string $entityTable
744 * @param int $contributionID
745 * @param array $priceFieldValueIDsToCancel
746 * @param array $lineItemsToUpdate
749 * List of formatted reverse Financial Items to be recorded
751 protected function getAdjustedFinancialItemsToRecord($entityID, $entityTable, $contributionID, $priceFieldValueIDsToCancel, $lineItemsToUpdate) {
752 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, str_replace('civicrm_', '', $entityTable));
754 $financialItemsArray = [];
755 $financialItemResult = $this->getNonCancelledFinancialItems($entityID, $entityTable);
756 foreach ($financialItemResult as $updateFinancialItemInfoValues) {
757 $updateFinancialItemInfoValues['transaction_date'] = date('YmdHis');
759 // the below params are not needed as we are creating new financial item
760 $previousFinancialItemID = $updateFinancialItemInfoValues['id'];
761 $totalFinancialAmount = $this->checkFinancialItemTotalAmountByLineItemID($updateFinancialItemInfoValues['entity_id']);
762 unset($updateFinancialItemInfoValues['id']);
763 unset($updateFinancialItemInfoValues['created_date']);
764 $previousLineItem = $previousLineItems[$updateFinancialItemInfoValues['entity_id']];
766 // if not submitted and difference is not 0 make it negative
767 if ((empty($lineItemsToUpdate) ||
(in_array($updateFinancialItemInfoValues['price_field_value_id'], $priceFieldValueIDsToCancel) &&
768 $totalFinancialAmount == $updateFinancialItemInfoValues['amount'])
769 ) && $updateFinancialItemInfoValues['amount'] > 0
772 // INSERT negative financial_items
773 $updateFinancialItemInfoValues['amount'] = -$updateFinancialItemInfoValues['amount'];
774 // reverse the related financial trxn too
775 $updateFinancialItemInfoValues['financialTrxn'] = $this->getRelatedCancelFinancialTrxn($previousFinancialItemID);
776 if ($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']) {
777 $updateFinancialItemInfoValues['tax']['amount'] = -($previousLineItem['tax_amount']);
778 $updateFinancialItemInfoValues['tax']['description'] = $this->getSalesTaxTerm();
780 // INSERT negative financial_items for tax amount
781 $financialItemsArray[$updateFinancialItemInfoValues['entity_id']] = $updateFinancialItemInfoValues;
783 // INSERT a financial item to record surplus/lesser amount when a text price fee is changed
785 !empty($lineItemsToUpdate)
786 && isset($lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']])
787 && $lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']]['html_type'] == 'Text'
788 && $updateFinancialItemInfoValues['amount'] > 0
790 $amountChangeOnTextLineItem = $lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']]['line_total'] - $totalFinancialAmount;
791 if ($amountChangeOnTextLineItem !== (float) 0) {
792 // calculate the amount difference, considered as financial item amount
793 $updateFinancialItemInfoValues['amount'] = $amountChangeOnTextLineItem;
794 if ($previousLineItem['tax_amount']
795 && $previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount'] !== 0.00) {
796 $updateFinancialItemInfoValues['tax']['amount'] = $lineItemsToUpdate[$updateFinancialItemInfoValues['entity_id']]['tax_amount'] - $previousLineItem['tax_amount'];
797 $updateFinancialItemInfoValues['tax']['description'] = $this->getSalesTaxTerm();
799 $financialItemsArray[$updateFinancialItemInfoValues['entity_id']] = $updateFinancialItemInfoValues;
804 return $financialItemsArray;
808 * Helper function to return sum of financial item's amount related to a line-item
809 * @param array $lineItemID
811 * @return float $financialItem
813 protected function checkFinancialItemTotalAmountByLineItemID($lineItemID) {
814 return CRM_Core_DAO
::singleValueQuery("
816 FROM civicrm_financial_item
817 WHERE entity_table = 'civicrm_line_item' AND entity_id = {$lineItemID}
822 * Helper function to retrieve submitted line items from form values $inputParams and used $feeBlock
824 * @param array $inputParams
825 * @param array $feeBlock
828 * List of submitted line items
830 protected function getSubmittedLineItems($inputParams, $feeBlock) {
831 $submittedLineItems = [];
832 foreach ($feeBlock as $id => $values) {
833 CRM_Price_BAO_LineItem
::format($id, $inputParams, $values, $submittedLineItems);
836 return $submittedLineItems;
840 * Helper function to retrieve line items that need to be altered.
842 * We iterate through the previous line items for the given entity to determine
843 * what alterations to line items need to be made to reflect the new line items.
845 * There are 4 possible changes required - per the keys in the return array.
847 * @param array $submittedLineItems
848 * @param int $entityID
849 * @param string $entity
852 * Array of line items to alter with the following keys
853 * - line_items_to_add. If the line items required are new radio options that
854 * have not previously been set then we should add line items for them
855 * - line_items_to_update. If we have already been an active option and a change has
856 * happened then it should be in this array.
857 * - line_items_to_cancel. Line items currently selected but not selected in the new selection.
858 * These need to be zero'd out.
859 * - line_items_to_resurrect. Line items previously selected and then deselected. These need to be
860 * re-enabled rather than a new one added.
862 protected function getLineItemsToAlter($submittedLineItems, $entityID, $entity) {
863 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, $entity);
865 $lineItemsToAdd = $submittedLineItems;
866 $lineItemsToUpdate = [];
867 $submittedPriceFieldValueIDs = array_keys($submittedLineItems);
868 $lineItemsToCancel = $lineItemsToResurrect = [];
870 foreach ($previousLineItems as $id => $previousLineItem) {
871 if (in_array($previousLineItem['price_field_value_id'], $submittedPriceFieldValueIDs)) {
872 $submittedLineItem = $submittedLineItems[$previousLineItem['price_field_value_id']];
873 if (CRM_Utils_Array
::value('html_type', $lineItemsToAdd[$previousLineItem['price_field_value_id']]) == 'Text') {
874 // If a 'Text' price field was updated by changing qty value, then we are not adding new line-item but updating the existing one,
875 // 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
876 // exception here by adding financial item for updated line-item and will reverse any previous financial item entries.
877 $lineItemsToUpdate[$previousLineItem['price_field_value_id']] = array_merge($submittedLineItem, ['id' => $id]);
878 unset($lineItemsToAdd[$previousLineItem['price_field_value_id']]);
881 $submittedLineItem = $submittedLineItems[$previousLineItem['price_field_value_id']];
882 // for updating the line items i.e. use-case - once deselect-option selecting again
883 if (($previousLineItem['line_total'] != $submittedLineItem['line_total'])
885 // This would be a $0 line item - but why it should be catered to
886 // other than when the above condition is unclear.
887 $submittedLineItem['line_total'] == 0 && $submittedLineItem['qty'] == 1
890 $previousLineItem['qty'] != $submittedLineItem['qty']
893 $lineItemsToUpdate[$previousLineItem['price_field_value_id']] = $submittedLineItem;
894 $lineItemsToUpdate[$previousLineItem['price_field_value_id']]['id'] = $id;
895 // Format is actually '0.00'
896 if ($previousLineItem['line_total'] == 0) {
897 $lineItemsToAdd[$previousLineItem['price_field_value_id']]['id'] = $id;
898 $lineItemsToResurrect[] = $lineItemsToAdd[$previousLineItem['price_field_value_id']];
901 // If there was previously a submitted line item for the same option value then there is
902 // either no change or a qty adjustment. In either case we are not doing an add + reversal.
903 unset($lineItemsToAdd[$previousLineItem['price_field_value_id']]);
904 unset($lineItemsToCancel[$previousLineItem['price_field_value_id']]);
908 if (!$this->isCancelled($previousLineItem)) {
909 $cancelParams = ['qty' => 0, 'line_total' => 0, 'tax_amount' => 0, 'participant_count' => 0, 'non_deductible_amount' => 0, 'id' => $id];
910 $lineItemsToCancel[$previousLineItem['price_field_value_id']] = array_merge($previousLineItem, $cancelParams);
917 'line_items_to_add' => $lineItemsToAdd,
918 'line_items_to_update' => $lineItemsToUpdate,
919 'line_items_to_cancel' => $lineItemsToCancel,
920 'line_items_to_resurrect' => $lineItemsToResurrect,
925 * Check if a line item has already been cancelled.
927 * @param array $lineItem
931 protected function isCancelled($lineItem) {
932 if ($lineItem['qty'] == 0 && $lineItem['line_total'] == 0) {
938 * Add line Items as result of fee change.
940 * @param array $lineItemsToAdd
941 * @param int $entityID
942 * @param string $entityTable
943 * @param int $contributionID
945 protected function addLineItemOnChangeFeeSelection(
951 // if there is no line item to add, do not proceed
952 if (empty($lineItemsToAdd)) {
956 $changedFinancialTypeID = NULL;
957 $updatedContribution = new CRM_Contribute_BAO_Contribution();
958 $updatedContribution->id
= (int) $contributionID;
959 // insert financial items
960 foreach ($lineItemsToAdd as $priceFieldValueID => $lineParams) {
961 $lineParams = array_merge($lineParams, [
962 'entity_table' => $entityTable,
963 'entity_id' => $entityID,
964 'contribution_id' => $contributionID,
966 if (!array_key_exists('skip', $lineParams)) {
967 self
::create($lineParams);
971 if ($changedFinancialTypeID) {
972 $updatedContribution->financial_type_id
= $changedFinancialTypeID;
973 $updatedContribution->save();
978 * Add financial transactions when an array of line items is changed.
980 * @param array $lineItemsToAdd
981 * @param int $entityID
982 * @param string $entityTable
983 * @param int $contributionID
984 * @param bool $trxnID
985 * Is there a change to the total balance requiring additional transactions to be created.
987 protected function addFinancialItemsOnLineItemsChange($lineItemsToAdd, $entityID, $entityTable, $contributionID, $trxnID) {
988 $updatedContribution = new CRM_Contribute_BAO_Contribution();
989 $updatedContribution->id
= $contributionID;
990 $updatedContribution->find(TRUE);
991 $trxnArray = $trxnID ?
['id' => $trxnID] : NULL;
993 foreach ($lineItemsToAdd as $priceFieldValueID => $lineParams) {
994 $lineParams = array_merge($lineParams, [
995 'entity_table' => $entityTable,
996 'entity_id' => $entityID,
997 'contribution_id' => $contributionID,
999 $lineObj = CRM_Price_BAO_LineItem
::retrieve($lineParams);
1000 // insert financial items
1001 // ensure entity_financial_trxn table has a linking of it.
1002 CRM_Financial_BAO_FinancialItem
::add($lineObj, $updatedContribution, NULL, $trxnArray);
1003 if (isset($lineObj->tax_amount
) && (float) $lineObj->tax_amount
!== 0.00) {
1004 CRM_Financial_BAO_FinancialItem
::add($lineObj, $updatedContribution, TRUE, $trxnArray);
1010 * Helper function to update entity record on change fee selection
1012 * @param array $inputParams
1013 * @param int $entityID
1014 * @param string $entity
1017 protected function updateEntityRecordOnChangeFeeSelection($inputParams, $entityID, $entity) {
1018 $entityTable = "civicrm_{$entity}";
1020 if ($entity == 'participant') {
1021 $partUpdateFeeAmt = ['id' => $entityID];
1022 $getUpdatedLineItems = "SELECT *
1023 FROM civicrm_line_item
1024 WHERE (entity_table = '{$entityTable}' AND entity_id = {$entityID} AND qty > 0)";
1025 $getUpdatedLineItemsDAO = CRM_Core_DAO
::executeQuery($getUpdatedLineItems);
1027 while ($getUpdatedLineItemsDAO->fetch()) {
1028 $line[$getUpdatedLineItemsDAO->price_field_value_id
] = $getUpdatedLineItemsDAO->label
. ' - ' . (float) $getUpdatedLineItemsDAO->qty
;
1031 $partUpdateFeeAmt['fee_level'] = implode(', ', $line);
1032 $partUpdateFeeAmt['fee_amount'] = $inputParams['amount'];
1033 CRM_Event_BAO_Participant
::add($partUpdateFeeAmt);
1036 CRM_Event_BAO_Participant
::addActivityForSelection($entityID, 'Change Registration');
1041 * Get the metadata for a price field.
1043 * @param string|int $key
1044 * Price field id. Either as an integer or as 'price_4' where 4 is the id
1047 * Metadata for the price field with a values key for option values.
1049 protected static function getPriceFieldMetaData($key) {
1050 $priceFieldID = str_replace('price_', '', $key);
1051 if (!isset(Civi
::$statics[__CLASS__
]['price_fields'][$priceFieldID])) {
1052 $values = civicrm_api3('PriceFieldValue', 'get', [
1053 'price_field_id' => $priceFieldID,
1057 'financial_type_id',
1058 'membership_type_id',
1061 'price_field_id.price_set_id',
1062 'price_field_id.html_type',
1066 $firstValue = reset($values['values']);
1067 $values = $values['values'];
1068 foreach ($values as $index => $value) {
1069 // Let's be nice to calling functions & ensure membership_type_id is set
1070 // so they don't have to handle notices on it. Handle one place not many.
1071 if (!isset($value['membership_type_id'])) {
1072 $values[$index]['membership_type_id'] = NULL;
1076 Civi
::$statics[__CLASS__
]['price_fields'][$priceFieldID] = [
1077 'price_set_id' => $firstValue['price_field_id.price_set_id'],
1078 'id' => $firstValue['price_field_id'],
1079 'html_type' => $firstValue['price_field_id.html_type'],
1080 'is_enter_qty' => !empty($firstValue['is_enter_qty']),
1081 'values' => $values,
1084 return Civi
::$statics[__CLASS__
]['price_fields'][$priceFieldID];
1088 * Get the tax rate for the given line item.
1090 * @param array $params
1094 protected static function getTaxAmountForLineItem(array $params): float {
1095 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
1096 $taxRate = $taxRates[$params['financial_type_id']] ??
0;
1097 return ($taxRate / 100) * $params['line_total'];
1101 * Helper function to retrieve financial trxn parameters to reverse
1102 * for given financial item identified by $financialItemID
1104 * @param int $financialItemID
1106 * @return array $financialTrxn
1109 protected function _getRelatedCancelFinancialTrxn($financialItemID) {
1111 $financialTrxn = civicrm_api3('EntityFinancialTrxn', 'getsingle', [
1112 'entity_table' => 'civicrm_financial_item',
1113 'entity_id' => $financialItemID,
1115 'sort' => 'id DESC',
1118 'api.FinancialTrxn.getsingle' => [
1119 'id' => "\$value.financial_trxn_id",
1123 catch (CiviCRM_API3_Exception
$e) {
1127 $financialTrxn = array_merge($financialTrxn['api.FinancialTrxn.getsingle'], [
1128 'trxn_date' => date('YmdHis'),
1129 'total_amount' => -$financialTrxn['api.FinancialTrxn.getsingle']['total_amount'],
1130 'net_amount' => -$financialTrxn['api.FinancialTrxn.getsingle']['net_amount'],
1131 'entity_table' => 'civicrm_financial_item',
1132 'entity_id' => $financialItemID,
1134 unset($financialTrxn['id']);
1136 return $financialTrxn;
1140 * Record adjusted amount.
1142 * @param int $updatedAmount
1143 * @param int $contributionId
1144 * @param int $taxAmount
1145 * @param bool $updateAmountLevel
1147 * @return bool|\CRM_Core_BAO_FinancialTrxn
1149 protected function _recordAdjustedAmt($updatedAmount, $contributionId, $taxAmount = NULL, $updateAmountLevel = NULL) {
1150 $paidAmount = (float) CRM_Core_BAO_FinancialTrxn
::getTotalPayments($contributionId);
1151 $balanceAmt = $updatedAmount - $paidAmount;
1153 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1154 $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
1155 $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
1156 $completedStatusId = array_search('Completed', $contributionStatuses);
1158 $updatedContributionDAO = new CRM_Contribute_BAO_Contribution();
1159 $adjustedTrxn = FALSE;
1161 if ($paidAmount === 0.0) {
1162 //skip updating the contribution status if no payment is made
1163 $updatedContributionDAO->cancel_date
= 'null';
1164 $updatedContributionDAO->cancel_reason
= NULL;
1167 $updatedContributionDAO->contribution_status_id
= $balanceAmt > 0 ?
$partiallyPaidStatusId : $pendingRefundStatusId;
1170 // update contribution status and total amount without trigger financial code
1171 // as this is handled in current BAO function used for change selection
1172 $updatedContributionDAO->id
= $contributionId;
1174 $updatedContributionDAO->total_amount
= $updatedContributionDAO->net_amount
= $updatedAmount;
1175 $updatedContributionDAO->fee_amount
= 0;
1176 $updatedContributionDAO->tax_amount
= $taxAmount;
1177 if (!empty($updateAmountLevel)) {
1178 $updatedContributionDAO->amount_level
= $updateAmountLevel;
1180 $updatedContributionDAO->save();
1181 // adjusted amount financial_trxn creation
1182 $updatedContribution = CRM_Contribute_BAO_Contribution
::getValues(
1183 ['id' => $contributionId]
1185 $toFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($updatedContribution->financial_type_id
, 'Accounts Receivable Account is');
1186 $adjustedTrxnValues = [
1187 'from_financial_account_id' => NULL,
1188 'to_financial_account_id' => $toFinancialAccount,
1189 'total_amount' => $balanceAmt,
1190 'net_amount' => $balanceAmt,
1191 'status_id' => $completedStatusId,
1192 'payment_instrument_id' => $updatedContribution->payment_instrument_id
,
1193 'contribution_id' => $updatedContribution->id
,
1194 'trxn_date' => date('YmdHis'),
1195 'currency' => $updatedContribution->currency
,
1197 $adjustedTrxn = CRM_Core_BAO_FinancialTrxn
::create($adjustedTrxnValues);
1199 // CRM-17151: Update the contribution status to completed if balance is zero,
1200 // because due to sucessive fee change will leave the related contribution status incorrect
1202 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'contribution_status_id', $completedStatusId);
1205 return $adjustedTrxn;
1209 * Get Financial items, culling out any that have already been reversed.
1211 * @param int $entityID
1212 * @param string $entityTable
1215 * Array of financial items that have not be reversed.
1217 protected function getNonCancelledFinancialItems($entityID, $entityTable) {
1218 // gathering necessary info to record negative (deselected) financial_item
1219 $updateFinancialItem = "
1220 SELECT fi.*, price_field_value_id, financial_type_id, tax_amount
1221 FROM civicrm_financial_item fi LEFT JOIN civicrm_line_item li ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1222 WHERE (li.entity_table = '{$entityTable}' AND li.entity_id = {$entityID})
1223 GROUP BY li.entity_table, li.entity_id, price_field_value_id, fi.id
1225 $updateFinancialItemInfoDAO = CRM_Core_DAO
::executeQuery($updateFinancialItem);
1227 $financialItemResult = $updateFinancialItemInfoDAO->fetchAll();
1229 foreach ($financialItemResult as $index => $financialItem) {
1230 $items[$financialItem['price_field_value_id']][$index] = $financialItem['amount'];
1232 if (!empty($items[$financialItem['price_field_value_id']])) {
1233 foreach ($items[$financialItem['price_field_value_id']] as $existingItemID => $existingAmount) {
1234 if ($financialItem['amount'] +
$existingAmount == 0) {
1235 // Filter both rows as they cancel each other out.
1236 unset($financialItemResult[$index]);
1237 unset($financialItemResult[$existingItemID]);
1238 unset($items['price_field_value_id'][$existingItemID]);
1239 unset($items[$financialItem['price_field_value_id']][$index]);
1246 return $financialItemResult;
1250 * Get the string used to describe the sales tax (eg. VAT, GST).
1254 protected function getSalesTaxTerm() {
1255 return CRM_Contribute_BAO_Contribution
::checkContributeSettings('tax_term');
1259 * Whitelist of possible values for the entity_table field
1263 public static function entityTables(): array {
1265 'civicrm_contribution' => ts('Contribution'),
1266 'civicrm_participant' => ts('Participant'),
1267 'civicrm_membership' => ts('Membership'),