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;
218 $dao = CRM_Core_DAO
::executeQuery("$selectClause $fromClause $whereClause $orderByClause", $params);
219 while ($dao->fetch()) {
223 $lineItems[$dao->id
] = [
224 'qty' => (float) $dao->qty
,
225 'label' => $dao->label
,
226 'unit_price' => $dao->unit_price
,
227 'line_total' => $dao->line_total
,
228 'price_field_id' => $dao->price_field_id
,
229 'participant_count' => $dao->participant_count
,
230 'price_field_value_id' => $dao->price_field_value_id
,
231 'field_title' => $dao->field_title
,
232 'html_type' => $dao->html_type
,
233 'description' => $dao->description
,
234 'entity_id' => $dao->entity_id
,
235 'entity_table' => $dao->entity_table
,
236 'contribution_id' => $dao->contribution_id
,
237 'financial_type_id' => $dao->financial_type_id
,
238 'financial_type' => CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'financial_type_id', $dao->financial_type_id
),
239 'membership_type_id' => $dao->membership_type_id
,
240 'membership_num_terms' => $dao->membership_num_terms
,
241 'tax_amount' => (float) $dao->tax_amount
,
242 'price_set_id' => $dao->price_set_id
,
244 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
245 if (isset($lineItems[$dao->id
]['financial_type_id']) && array_key_exists($lineItems[$dao->id
]['financial_type_id'], $taxRates)) {
246 // Cast to float so trailing zero decimals are removed for display.
247 $lineItems[$dao->id
]['tax_rate'] = (float) $taxRates[$lineItems[$dao->id
]['financial_type_id']];
250 // There is no Tax Rate associated with this Financial Type
251 $lineItems[$dao->id
]['tax_rate'] = FALSE;
253 $lineItems[$dao->id
]['subTotal'] = $lineItems[$dao->id
]['qty'] * $lineItems[$dao->id
]['unit_price'];
254 if ($lineItems[$dao->id
]['tax_amount'] != '') {
255 $getTaxDetails = TRUE;
258 if (Civi
::settings()->get('invoicing')) {
259 // @todo - this is an inappropriate place to be doing form level assignments.
260 $taxTerm = Civi
::settings()->get('tax_term');
261 $smarty = CRM_Core_Smarty
::singleton();
262 $smarty->assign('taxTerm', $taxTerm);
263 $smarty->assign('getTaxDetails', $getTaxDetails);
269 * This method will create the lineItem array required for
270 * processAmount method
273 * Price set field id.
274 * @param array $params
275 * Reference to form values.
276 * @param array $fields
277 * Array of fields belonging to the price set used for particular event
278 * @param array $values
279 * Reference to the values array(.
282 * @param string $amount_override
283 * Amount override must be in format 1000.00 - ie no thousand separator & if
284 * a decimal point is used it should be a decimal
286 * @todo - this parameter is only used for partial payments. It's unclear why a partial
287 * payment would change the line item price.
289 public static function format($fid, $params, $fields, &$values, $amount_override = NULL) {
290 if (empty($params["price_{$fid}"])) {
294 //lets first check in fun parameter,
295 //since user might modified w/ hooks.
297 if (array_key_exists('options', $fields)) {
298 $options = $fields['options'];
301 CRM_Price_BAO_PriceFieldValue
::getValues($fid, $options, 'weight', TRUE);
303 $fieldTitle = $fields['label'] ??
NULL;
305 $fieldTitle = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'label');
308 foreach ($params["price_{$fid}"] as $oid => $qty) {
309 $price = $amount_override === NULL ?
$options[$oid]['amount'] : $amount_override;
311 $participantsPerField = CRM_Utils_Array
::value('count', $options[$oid], 0);
314 'price_field_id' => $fid,
315 'price_field_value_id' => $oid,
316 'label' => $options[$oid]['label'] ??
NULL,
317 'field_title' => $fieldTitle,
318 'description' => $options[$oid]['description'] ??
NULL,
320 'unit_price' => $price,
321 'line_total' => $qty * $price,
322 'participant_count' => $qty * $participantsPerField,
323 'max_value' => $options[$oid]['max_value'] ??
NULL,
324 'membership_type_id' => $options[$oid]['membership_type_id'] ??
NULL,
325 'membership_num_terms' => $options[$oid]['membership_num_terms'] ??
NULL,
326 'auto_renew' => $options[$oid]['auto_renew'] ??
NULL,
327 'html_type' => $fields['html_type'],
328 'financial_type_id' => $options[$oid]['financial_type_id'] ??
NULL,
329 'tax_amount' => CRM_Utils_Array
::value('tax_amount', $options[$oid], 0),
330 'non_deductible_amount' => $options[$oid]['non_deductible_amount'] ??
NULL,
333 if ($values[$oid]['membership_type_id'] && empty($values[$oid]['auto_renew'])) {
334 $values[$oid]['auto_renew'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $values[$oid]['membership_type_id'], 'auto_renew');
340 * Delete line items for given entity.
342 * @param int $entityId
343 * @param int $entityTable
347 public static function deleteLineItems($entityId, $entityTable) {
348 if (!$entityId ||
!$entityTable) {
352 if ($entityId && !is_array($entityId)) {
353 $entityId = [$entityId];
357 foreach ($entityId as $id) {
358 CRM_Utils_Hook
::pre('delete', 'LineItem', $id, $params);
361 $query = "DELETE FROM civicrm_line_item where entity_id IN ('" . implode("','", $entityId) . "') AND entity_table = '$entityTable'";
362 $dao = CRM_Core_DAO
::executeQuery($query);
367 * Process price set and line items.
369 * @param int $entityId
370 * @param array $lineItems
372 * @param object $contributionDetails
373 * @param string $entityTable
376 * @param bool $update
378 * @throws \CRM_Core_Exception
379 * @throws \CiviCRM_API3_Exception
381 public static function processPriceSet($entityId, $lineItems, $contributionDetails = NULL, $entityTable = 'civicrm_contribution', $update = FALSE) {
382 if (!$entityId ||
!is_array($lineItems)
383 || CRM_Utils_System
::isNull($lineItems)
388 foreach ($lineItems as $priceSetId => &$values) {
393 foreach ($values as &$line) {
394 if (empty($line['entity_table'])) {
395 $line['entity_table'] = $entityTable;
397 if (empty($line['entity_id'])) {
398 $line['entity_id'] = $entityId;
400 if (!empty($line['membership_type_id'])) {
401 if (($line['entity_table'] ??
'') !== 'civicrm_membership') {
402 CRM_Core_Error
::deprecatedWarning('entity table should be already set');
404 $line['entity_table'] = 'civicrm_membership';
406 if (!empty($contributionDetails->id
)) {
407 $line['contribution_id'] = $contributionDetails->id
;
408 if ($line['entity_table'] === 'civicrm_contribution') {
409 $line['entity_id'] = $contributionDetails->id
;
413 // if financial type is not set and if price field value is NOT NULL
414 // get financial type id of price field value
415 if (!empty($line['price_field_value_id']) && empty($line['financial_type_id'])) {
416 $line['financial_type_id'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $line['price_field_value_id'], 'financial_type_id');
418 $createdLineItem = CRM_Price_BAO_LineItem
::create($line);
419 if (!$update && $contributionDetails) {
420 $financialItem = CRM_Financial_BAO_FinancialItem
::add($createdLineItem, $contributionDetails);
421 $line['financial_item_id'] = $financialItem->id
;
422 if (!empty($line['tax_amount'])) {
423 CRM_Financial_BAO_FinancialItem
::add($createdLineItem, $contributionDetails, TRUE);
428 if (!$update && $contributionDetails) {
429 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn($lineItems, $contributionDetails);
434 * @param int $entityId
435 * @param string $entityTable
437 * @param array $otherParams
439 public static function syncLineItems($entityId, $entityTable, $amount, $otherParams = NULL) {
440 if (!$entityId || CRM_Utils_System
::isNull($amount)) {
444 $from = " civicrm_line_item li
445 LEFT JOIN civicrm_price_field pf ON pf.id = li.price_field_id
446 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id ";
448 $set = " li.unit_price = %3,
449 li.line_total = %3 ";
451 $where = " li.entity_id = %1 AND
452 li.entity_table = %2 ";
455 1 => [$entityId, 'Integer'],
456 2 => [$entityTable, 'String'],
457 3 => [$amount, 'Float'],
460 if ($entityTable == 'civicrm_contribution') {
461 $entityName = 'default_contribution_amount';
462 $where .= " AND ps.name = %4 ";
463 $params[4] = [$entityName, 'String'];
465 elseif ($entityTable == 'civicrm_participant') {
467 LEFT JOIN civicrm_price_set_entity cpse ON cpse.price_set_id = ps.id
468 LEFT JOIN civicrm_price_field_value cpfv ON cpfv.price_field_id = pf.id and cpfv.label = %4 ";
469 $set .= " ,li.label = %4,
470 li.price_field_value_id = cpfv.id ";
471 $where .= " AND cpse.entity_table = 'civicrm_event' AND cpse.entity_id = %5 ";
472 $amount = empty($amount) ?
0 : $amount;
474 4 => [$otherParams['fee_label'], 'String'],
475 5 => [$otherParams['event_id'], 'String'],
485 CRM_Core_DAO
::executeQuery($query, $params);
489 * Build line items array.
491 * @param array $params
494 * @param string $entityId
497 * @param string $entityTable
500 * @param bool $isRelatedID
502 public static function getLineItemArray(&$params, $entityId = NULL, $entityTable = 'contribution', $isRelatedID = FALSE) {
504 $priceSetDetails = CRM_Price_BAO_PriceSet
::getDefaultPriceSet($entityTable);
505 $totalAmount = $params['total_amount'] ??
0;
506 $financialType = $params['financial_type_id'] ??
NULL;
507 foreach ($priceSetDetails as $values) {
508 if ($entityTable === 'membership') {
509 if ($isRelatedID != $values['membership_type_id']) {
513 $totalAmount = $values['amount'];
515 $financialType = $values['financial_type_id'];
517 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
518 $taxRate = $taxRates[$financialType] ??
0;
519 $taxAmount = ($taxRate / 100) * $totalAmount / (1 +
($taxRate / 100));
521 'price_field_id' => $values['priceFieldID'],
522 'price_field_value_id' => $values['priceFieldValueID'],
523 'label' => $values['label'],
525 'unit_price' => $totalAmount - $taxAmount,
526 'line_total' => $totalAmount - $taxAmount,
527 'financial_type_id' => $financialType,
528 'membership_type_id' => $values['membership_type_id'],
529 'tax_amount' => $taxAmount,
531 $params['line_item'][$values['setID']][$values['priceFieldID']] = $lineItem;
537 $totalEntityId = count($entityId);
538 if ($entityTable == 'contribution') {
541 foreach ($entityId as $id) {
542 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($id, $entityTable, FALSE, TRUE, $isRelatedID);
543 foreach ($lineItems as $key => $values) {
544 if (!$setID && $values['price_field_id']) {
545 $setID = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $values['price_field_id'], 'price_set_id');
546 $params['is_quick_config'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $setID, 'is_quick_config');
548 if (!empty($params['is_quick_config']) && array_key_exists('total_amount', $params)
549 && $totalEntityId == 1 && count($lineItems) == 1
551 $values['line_total'] = $values['unit_price'] = $params['total_amount'];
553 $values['id'] = $key;
554 $params['line_item'][$setID][$key] = $values;
561 * Build the line items for the submitted price field.
563 * This is when first building them - not an update where an entityId is already present
564 * as this is intended as a subfunction of that. Ideally getLineItemArray would call this
565 * (resolving to the same format regardless of what type of price set is being used first).
567 * @param array $priceParams
568 * These are per the way the form processes them - ie
569 * ['price_1' => 1, 'price_2' => 8]
570 * This would mean price field id 1, option 1 (or 1 unit if using is_enter_qty).
571 * @param float|null $overrideAmount
572 * Optional override of the amount.
574 * @param int|null $financialTypeID
575 * Financial type ID is the type should be overridden.
578 * Line items formatted for processing. These will look like
579 * [4] => ['price_field_id' => 4, 'price_field_value_id' => x, 'label....qty...unit_price...line_total...financial_type_id]
580 * [5] => ['price_field_id' => 5, 'price_field_value_id' => x, 'label....qty...unit_price...line_total...financial_type_id]
583 public static function buildLineItemsForSubmittedPriceField($priceParams, $overrideAmount = NULL, $financialTypeID = NULL) {
585 foreach ($priceParams as $key => $value) {
586 $priceField = self
::getPriceFieldMetaData($key);
588 if ($priceField['html_type'] === 'Text') {
589 $valueSpec = reset($priceField['values']);
592 $valueSpec = $priceField['values'][$value];
594 $qty = $priceField['is_enter_qty'] ?
$value : 1;
595 $lineItems[$priceField['id']] = [
596 'price_field_id' => $priceField['id'],
597 'price_field_value_id' => $valueSpec['id'],
598 'label' => $valueSpec['label'],
600 'unit_price' => $overrideAmount ?
: $valueSpec['amount'],
601 'line_total' => $qty * ($overrideAmount ?
: $valueSpec['amount']),
602 'financial_type_id' => $financialTypeID ?
: $valueSpec['financial_type_id'],
603 'membership_type_id' => $valueSpec['membership_type_id'],
604 'price_set_id' => $priceField['price_set_id'],
611 * Function to update related contribution of a entity and
612 * add/update/cancel financial records
614 * @param array $params
615 * @param int $entityID
617 * @param int $contributionId
619 * @param array $lineItems
621 * @throws \CiviCRM_API3_Exception
623 public static function changeFeeSelections(
631 $entityTable = "civicrm_" . $entity;
633 CRM_Price_BAO_PriceSet
::processAmount($feeBlock,
634 $params, $newLineItems
636 // initialize empty Lineitem instance to call protected helper functions
637 $lineItemObj = new CRM_Price_BAO_LineItem();
639 // fetch submitted LineItems from input params and feeBlock information
640 $submittedLineItems = $lineItemObj->getSubmittedLineItems($params, $feeBlock);
642 $requiredChanges = $lineItemObj->getLineItemsToAlter($submittedLineItems, $entityID, $entity);
644 // get financial information that need to be recorded on basis on submitted price field value IDs
645 if (!empty($requiredChanges['line_items_to_cancel']) ||
!empty($requiredChanges['line_items_to_update'])) {
646 // @todo - this IF is to get this through PR merge but I suspect that it should not
647 // be necessary & is masking something else.
648 $financialItemsArray = $lineItemObj->getAdjustedFinancialItemsToRecord(
652 array_keys($requiredChanges['line_items_to_cancel']),
653 $requiredChanges['line_items_to_update']
657 // update line item with changed line total and other information
658 $totalParticipant = $participantCount = 0;
660 if (!empty($requiredChanges['line_items_to_update'])) {
661 foreach ($requiredChanges['line_items_to_update'] as $priceFieldValueID => $value) {
662 $amountLevel[] = $value['label'] . ' - ' . (float) $value['qty'];
663 if ($entity == 'participant' && isset($value['participant_count'])) {
664 $totalParticipant +
= $value['participant_count'];
669 foreach (array_merge($requiredChanges['line_items_to_resurrect'], $requiredChanges['line_items_to_cancel'], $requiredChanges['line_items_to_update']) as $lineItemToAlter) {
670 // Must use BAO rather than api because a bad line it in the api which we want to avoid.
671 CRM_Price_BAO_LineItem
::create($lineItemToAlter);
674 $lineItemObj->addLineItemOnChangeFeeSelection($requiredChanges['line_items_to_add'], $entityID, $entityTable, $contributionId);
677 if ($entity == 'participant') {
678 $count = count(CRM_Event_BAO_Participant
::getParticipantIds($contributionId));
681 $count = CRM_Utils_Array
::value('count', civicrm_api3('MembershipPayment', 'getcount', ['contribution_id' => $contributionId]));
684 $updatedAmount = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
687 $updatedAmount = CRM_Utils_Array
::value('amount', $params, CRM_Utils_Array
::value('total_amount', $params));
689 if (strlen($params['tax_amount']) != 0) {
690 $taxAmount = $params['tax_amount'];
695 $displayParticipantCount = '';
696 if ($totalParticipant > 0) {
697 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
699 $updateAmountLevel = NULL;
700 if (!empty($amountLevel)) {
701 $updateAmountLevel = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amountLevel) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
703 $trxn = $lineItemObj->_recordAdjustedAmt($updatedAmount, $contributionId, $taxAmount, $updateAmountLevel);
704 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_DAO_Contribution', 'contribution_status_id', CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'contribution_status_id'));
706 if (!empty($financialItemsArray)) {
707 foreach ($financialItemsArray as $updateFinancialItemInfoValues) {
708 $newFinancialItem = CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues);
709 // record reverse transaction only if Contribution is Completed because for pending refund or
710 // partially paid we are already recording the surplus owed or refund amount
711 if (!empty($updateFinancialItemInfoValues['financialTrxn']) && ($contributionStatus == 'Completed')) {
712 $updateFinancialItemInfoValues = array_merge($updateFinancialItemInfoValues['financialTrxn'], [
713 'entity_id' => $newFinancialItem->id
,
714 'entity_table' => 'civicrm_financial_item',
716 $reverseTrxn = CRM_Core_BAO_FinancialTrxn
::create($updateFinancialItemInfoValues);
717 // record reverse entity financial trxn linked to membership's related contribution
718 civicrm_api3('EntityFinancialTrxn', 'create', [
719 'entity_table' => "civicrm_contribution",
720 'entity_id' => $contributionId,
721 'financial_trxn_id' => $reverseTrxn->id
,
722 'amount' => $reverseTrxn->total_amount
,
724 unset($updateFinancialItemInfoValues['financialTrxn']);
726 elseif ($trxn && $newFinancialItem->amount
!= 0) {
727 civicrm_api3('EntityFinancialTrxn', 'create', [
728 'entity_id' => $newFinancialItem->id
,
729 'entity_table' => 'civicrm_financial_item',
730 'financial_trxn_id' => $trxn->id
,
731 'amount' => $newFinancialItem->amount
,
737 $lineItemObj->addFinancialItemsOnLineItemsChange(array_merge($requiredChanges['line_items_to_add'], $requiredChanges['line_items_to_resurrect']), $entityID, $entityTable, $contributionId, $trxn->id ??
NULL);
739 // update participant fee_amount column
740 $lineItemObj->updateEntityRecordOnChangeFeeSelection($params, $entityID, $entity);
744 * Function to retrieve financial items that need to be recorded as result of changed fee
746 * @param int $entityID
747 * @param string $entityTable
748 * @param int $contributionID
749 * @param array $priceFieldValueIDsToCancel
750 * @param array $lineItemsToUpdate
753 * List of formatted reverse Financial Items to be recorded
755 protected function getAdjustedFinancialItemsToRecord($entityID, $entityTable, $contributionID, $priceFieldValueIDsToCancel, $lineItemsToUpdate) {
756 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, str_replace('civicrm_', '', $entityTable));
758 $financialItemsArray = [];
759 $financialItemResult = $this->getNonCancelledFinancialItems($entityID, $entityTable);
760 foreach ($financialItemResult as $updateFinancialItemInfoValues) {
761 $updateFinancialItemInfoValues['transaction_date'] = date('YmdHis');
763 // the below params are not needed as we are creating new financial item
764 $previousFinancialItemID = $updateFinancialItemInfoValues['id'];
765 $totalFinancialAmount = $this->checkFinancialItemTotalAmountByLineItemID($updateFinancialItemInfoValues['entity_id']);
766 unset($updateFinancialItemInfoValues['id']);
767 unset($updateFinancialItemInfoValues['created_date']);
768 $previousLineItem = $previousLineItems[$updateFinancialItemInfoValues['entity_id']];
770 // if not submitted and difference is not 0 make it negative
771 if ((empty($lineItemsToUpdate) ||
(in_array($updateFinancialItemInfoValues['price_field_value_id'], $priceFieldValueIDsToCancel) &&
772 $totalFinancialAmount == $updateFinancialItemInfoValues['amount'])
773 ) && $updateFinancialItemInfoValues['amount'] > 0
776 // INSERT negative financial_items
777 $updateFinancialItemInfoValues['amount'] = -$updateFinancialItemInfoValues['amount'];
778 // reverse the related financial trxn too
779 $updateFinancialItemInfoValues['financialTrxn'] = $this->getRelatedCancelFinancialTrxn($previousFinancialItemID);
780 if ($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']) {
781 $updateFinancialItemInfoValues['tax']['amount'] = -($previousLineItem['tax_amount']);
782 $updateFinancialItemInfoValues['tax']['description'] = $this->getSalesTaxTerm();
784 // INSERT negative financial_items for tax amount
785 $financialItemsArray[$updateFinancialItemInfoValues['entity_id']] = $updateFinancialItemInfoValues;
787 // INSERT a financial item to record surplus/lesser amount when a text price fee is changed
789 !empty($lineItemsToUpdate)
790 && isset($lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']])
791 && $lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']]['html_type'] == 'Text'
792 && $updateFinancialItemInfoValues['amount'] > 0
794 $amountChangeOnTextLineItem = $lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']]['line_total'] - $totalFinancialAmount;
795 if ($amountChangeOnTextLineItem !== (float) 0) {
796 // calculate the amount difference, considered as financial item amount
797 $updateFinancialItemInfoValues['amount'] = $amountChangeOnTextLineItem;
798 if ($previousLineItem['tax_amount']
799 && $previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount'] !== 0.00) {
800 $updateFinancialItemInfoValues['tax']['amount'] = $lineItemsToUpdate[$updateFinancialItemInfoValues['entity_id']]['tax_amount'] - $previousLineItem['tax_amount'];
801 $updateFinancialItemInfoValues['tax']['description'] = $this->getSalesTaxTerm();
803 $financialItemsArray[$updateFinancialItemInfoValues['entity_id']] = $updateFinancialItemInfoValues;
808 return $financialItemsArray;
812 * Helper function to return sum of financial item's amount related to a line-item
813 * @param array $lineItemID
815 * @return float $financialItem
817 protected function checkFinancialItemTotalAmountByLineItemID($lineItemID) {
818 return CRM_Core_DAO
::singleValueQuery("
820 FROM civicrm_financial_item
821 WHERE entity_table = 'civicrm_line_item' AND entity_id = {$lineItemID}
826 * Helper function to retrieve submitted line items from form values $inputParams and used $feeBlock
828 * @param array $inputParams
829 * @param array $feeBlock
832 * List of submitted line items
834 protected function getSubmittedLineItems($inputParams, $feeBlock) {
835 $submittedLineItems = [];
836 foreach ($feeBlock as $id => $values) {
837 CRM_Price_BAO_LineItem
::format($id, $inputParams, $values, $submittedLineItems);
840 return $submittedLineItems;
844 * Helper function to retrieve line items that need to be altered.
846 * We iterate through the previous line items for the given entity to determine
847 * what alterations to line items need to be made to reflect the new line items.
849 * There are 4 possible changes required - per the keys in the return array.
851 * @param array $submittedLineItems
852 * @param int $entityID
853 * @param string $entity
856 * Array of line items to alter with the following keys
857 * - line_items_to_add. If the line items required are new radio options that
858 * have not previously been set then we should add line items for them
859 * - line_items_to_update. If we have already been an active option and a change has
860 * happened then it should be in this array.
861 * - line_items_to_cancel. Line items currently selected but not selected in the new selection.
862 * These need to be zero'd out.
863 * - line_items_to_resurrect. Line items previously selected and then deselected. These need to be
864 * re-enabled rather than a new one added.
866 protected function getLineItemsToAlter($submittedLineItems, $entityID, $entity) {
867 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, $entity);
869 $lineItemsToAdd = $submittedLineItems;
870 $lineItemsToUpdate = [];
871 $submittedPriceFieldValueIDs = array_keys($submittedLineItems);
872 $lineItemsToCancel = $lineItemsToResurrect = [];
874 foreach ($previousLineItems as $id => $previousLineItem) {
875 if (in_array($previousLineItem['price_field_value_id'], $submittedPriceFieldValueIDs)) {
876 $submittedLineItem = $submittedLineItems[$previousLineItem['price_field_value_id']];
877 if (CRM_Utils_Array
::value('html_type', $lineItemsToAdd[$previousLineItem['price_field_value_id']]) == 'Text') {
878 // If a 'Text' price field was updated by changing qty value, then we are not adding new line-item but updating the existing one,
879 // 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
880 // exception here by adding financial item for updated line-item and will reverse any previous financial item entries.
881 $lineItemsToUpdate[$previousLineItem['price_field_value_id']] = array_merge($submittedLineItem, ['id' => $id]);
882 unset($lineItemsToAdd[$previousLineItem['price_field_value_id']]);
885 $submittedLineItem = $submittedLineItems[$previousLineItem['price_field_value_id']];
886 // for updating the line items i.e. use-case - once deselect-option selecting again
887 if (($previousLineItem['line_total'] != $submittedLineItem['line_total'])
889 // This would be a $0 line item - but why it should be catered to
890 // other than when the above condition is unclear.
891 $submittedLineItem['line_total'] == 0 && $submittedLineItem['qty'] == 1
894 $previousLineItem['qty'] != $submittedLineItem['qty']
897 $lineItemsToUpdate[$previousLineItem['price_field_value_id']] = $submittedLineItem;
898 $lineItemsToUpdate[$previousLineItem['price_field_value_id']]['id'] = $id;
899 // Format is actually '0.00'
900 if ($previousLineItem['line_total'] == 0) {
901 $lineItemsToAdd[$previousLineItem['price_field_value_id']]['id'] = $id;
902 $lineItemsToResurrect[] = $lineItemsToAdd[$previousLineItem['price_field_value_id']];
905 // If there was previously a submitted line item for the same option value then there is
906 // either no change or a qty adjustment. In either case we are not doing an add + reversal.
907 unset($lineItemsToAdd[$previousLineItem['price_field_value_id']]);
908 unset($lineItemsToCancel[$previousLineItem['price_field_value_id']]);
912 if (!$this->isCancelled($previousLineItem)) {
913 $cancelParams = ['qty' => 0, 'line_total' => 0, 'tax_amount' => 0, 'participant_count' => 0, 'non_deductible_amount' => 0, 'id' => $id];
914 $lineItemsToCancel[$previousLineItem['price_field_value_id']] = array_merge($previousLineItem, $cancelParams);
921 'line_items_to_add' => $lineItemsToAdd,
922 'line_items_to_update' => $lineItemsToUpdate,
923 'line_items_to_cancel' => $lineItemsToCancel,
924 'line_items_to_resurrect' => $lineItemsToResurrect,
929 * Check if a line item has already been cancelled.
931 * @param array $lineItem
935 protected function isCancelled($lineItem) {
936 if ($lineItem['qty'] == 0 && $lineItem['line_total'] == 0) {
942 * Add line Items as result of fee change.
944 * @param array $lineItemsToAdd
945 * @param int $entityID
946 * @param string $entityTable
947 * @param int $contributionID
949 protected function addLineItemOnChangeFeeSelection(
955 // if there is no line item to add, do not proceed
956 if (empty($lineItemsToAdd)) {
960 $changedFinancialTypeID = NULL;
961 $updatedContribution = new CRM_Contribute_BAO_Contribution();
962 $updatedContribution->id
= (int) $contributionID;
963 // insert financial items
964 foreach ($lineItemsToAdd as $priceFieldValueID => $lineParams) {
965 $lineParams = array_merge($lineParams, [
966 'entity_table' => $entityTable,
967 'entity_id' => $entityID,
968 'contribution_id' => $contributionID,
970 if (!array_key_exists('skip', $lineParams)) {
971 self
::create($lineParams);
975 if ($changedFinancialTypeID) {
976 $updatedContribution->financial_type_id
= $changedFinancialTypeID;
977 $updatedContribution->save();
982 * Add financial transactions when an array of line items is changed.
984 * @param array $lineItemsToAdd
985 * @param int $entityID
986 * @param string $entityTable
987 * @param int $contributionID
988 * @param bool $trxnID
989 * Is there a change to the total balance requiring additional transactions to be created.
991 protected function addFinancialItemsOnLineItemsChange($lineItemsToAdd, $entityID, $entityTable, $contributionID, $trxnID) {
992 $updatedContribution = new CRM_Contribute_BAO_Contribution();
993 $updatedContribution->id
= $contributionID;
994 $updatedContribution->find(TRUE);
995 $trxnArray = $trxnID ?
['id' => $trxnID] : NULL;
997 foreach ($lineItemsToAdd as $priceFieldValueID => $lineParams) {
998 $lineParams = array_merge($lineParams, [
999 'entity_table' => $entityTable,
1000 'entity_id' => $entityID,
1001 'contribution_id' => $contributionID,
1003 $lineObj = CRM_Price_BAO_LineItem
::retrieve($lineParams);
1004 // insert financial items
1005 // ensure entity_financial_trxn table has a linking of it.
1006 CRM_Financial_BAO_FinancialItem
::add($lineObj, $updatedContribution, NULL, $trxnArray);
1007 if (isset($lineObj->tax_amount
) && (float) $lineObj->tax_amount
!== 0.00) {
1008 CRM_Financial_BAO_FinancialItem
::add($lineObj, $updatedContribution, TRUE, $trxnArray);
1014 * Helper function to update entity record on change fee selection
1016 * @param array $inputParams
1017 * @param int $entityID
1018 * @param string $entity
1021 protected function updateEntityRecordOnChangeFeeSelection($inputParams, $entityID, $entity) {
1022 $entityTable = "civicrm_{$entity}";
1024 if ($entity == 'participant') {
1025 $partUpdateFeeAmt = ['id' => $entityID];
1026 $getUpdatedLineItems = "SELECT *
1027 FROM civicrm_line_item
1028 WHERE (entity_table = '{$entityTable}' AND entity_id = {$entityID} AND qty > 0)";
1029 $getUpdatedLineItemsDAO = CRM_Core_DAO
::executeQuery($getUpdatedLineItems);
1031 while ($getUpdatedLineItemsDAO->fetch()) {
1032 $line[$getUpdatedLineItemsDAO->price_field_value_id
] = $getUpdatedLineItemsDAO->label
. ' - ' . (float) $getUpdatedLineItemsDAO->qty
;
1035 $partUpdateFeeAmt['fee_level'] = implode(', ', $line);
1036 $partUpdateFeeAmt['fee_amount'] = $inputParams['amount'];
1037 CRM_Event_BAO_Participant
::add($partUpdateFeeAmt);
1040 CRM_Event_BAO_Participant
::addActivityForSelection($entityID, 'Change Registration');
1045 * Get the metadata for a price field.
1047 * @param string|int $key
1048 * Price field id. Either as an integer or as 'price_4' where 4 is the id
1051 * Metadata for the price field with a values key for option values.
1053 protected static function getPriceFieldMetaData($key) {
1054 $priceFieldID = str_replace('price_', '', $key);
1055 if (!isset(Civi
::$statics[__CLASS__
]['price_fields'][$priceFieldID])) {
1056 $values = civicrm_api3('PriceFieldValue', 'get', [
1057 'price_field_id' => $priceFieldID,
1061 'financial_type_id',
1062 'membership_type_id',
1065 'price_field_id.price_set_id',
1066 'price_field_id.html_type',
1070 $firstValue = reset($values['values']);
1071 $values = $values['values'];
1072 foreach ($values as $index => $value) {
1073 // Let's be nice to calling functions & ensure membership_type_id is set
1074 // so they don't have to handle notices on it. Handle one place not many.
1075 if (!isset($value['membership_type_id'])) {
1076 $values[$index]['membership_type_id'] = NULL;
1080 Civi
::$statics[__CLASS__
]['price_fields'][$priceFieldID] = [
1081 'price_set_id' => $firstValue['price_field_id.price_set_id'],
1082 'id' => $firstValue['price_field_id'],
1083 'html_type' => $firstValue['price_field_id.html_type'],
1084 'is_enter_qty' => !empty($firstValue['is_enter_qty']),
1085 'values' => $values,
1088 return Civi
::$statics[__CLASS__
]['price_fields'][$priceFieldID];
1092 * Get the tax rate for the given line item.
1094 * @param array $params
1098 protected static function getTaxAmountForLineItem(array $params): float {
1099 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
1100 $taxRate = $taxRates[$params['financial_type_id']] ??
0;
1101 return ($taxRate / 100) * $params['line_total'];
1105 * Helper function to retrieve financial trxn parameters to reverse
1106 * for given financial item identified by $financialItemID
1108 * @param int $financialItemID
1110 * @return array $financialTrxn
1113 protected function _getRelatedCancelFinancialTrxn($financialItemID) {
1115 $financialTrxn = civicrm_api3('EntityFinancialTrxn', 'getsingle', [
1116 'entity_table' => 'civicrm_financial_item',
1117 'entity_id' => $financialItemID,
1119 'sort' => 'id DESC',
1122 'api.FinancialTrxn.getsingle' => [
1123 'id' => "\$value.financial_trxn_id",
1127 catch (CiviCRM_API3_Exception
$e) {
1131 $financialTrxn = array_merge($financialTrxn['api.FinancialTrxn.getsingle'], [
1132 'trxn_date' => date('YmdHis'),
1133 'total_amount' => -$financialTrxn['api.FinancialTrxn.getsingle']['total_amount'],
1134 'net_amount' => -$financialTrxn['api.FinancialTrxn.getsingle']['net_amount'],
1135 'entity_table' => 'civicrm_financial_item',
1136 'entity_id' => $financialItemID,
1138 unset($financialTrxn['id']);
1140 return $financialTrxn;
1144 * Record adjusted amount.
1146 * @param int $updatedAmount
1147 * @param int $contributionId
1148 * @param int $taxAmount
1149 * @param bool $updateAmountLevel
1151 * @return bool|\CRM_Core_BAO_FinancialTrxn
1153 protected function _recordAdjustedAmt($updatedAmount, $contributionId, $taxAmount = NULL, $updateAmountLevel = NULL) {
1154 $paidAmount = (float) CRM_Core_BAO_FinancialTrxn
::getTotalPayments($contributionId);
1155 $balanceAmt = $updatedAmount - $paidAmount;
1157 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1158 $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
1159 $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
1160 $completedStatusId = array_search('Completed', $contributionStatuses);
1162 $updatedContributionDAO = new CRM_Contribute_BAO_Contribution();
1163 $adjustedTrxn = FALSE;
1165 if ($paidAmount === 0.0) {
1166 //skip updating the contribution status if no payment is made
1167 $updatedContributionDAO->cancel_date
= 'null';
1168 $updatedContributionDAO->cancel_reason
= NULL;
1171 $updatedContributionDAO->contribution_status_id
= $balanceAmt > 0 ?
$partiallyPaidStatusId : $pendingRefundStatusId;
1174 // update contribution status and total amount without trigger financial code
1175 // as this is handled in current BAO function used for change selection
1176 $updatedContributionDAO->id
= $contributionId;
1178 $updatedContributionDAO->total_amount
= $updatedContributionDAO->net_amount
= $updatedAmount;
1179 $updatedContributionDAO->fee_amount
= 0;
1180 $updatedContributionDAO->tax_amount
= $taxAmount;
1181 if (!empty($updateAmountLevel)) {
1182 $updatedContributionDAO->amount_level
= $updateAmountLevel;
1184 $updatedContributionDAO->save();
1185 // adjusted amount financial_trxn creation
1186 $updatedContribution = CRM_Contribute_BAO_Contribution
::getValues(
1187 ['id' => $contributionId]
1189 $toFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($updatedContribution->financial_type_id
, 'Accounts Receivable Account is');
1190 $adjustedTrxnValues = [
1191 'from_financial_account_id' => NULL,
1192 'to_financial_account_id' => $toFinancialAccount,
1193 'total_amount' => $balanceAmt,
1194 'net_amount' => $balanceAmt,
1195 'status_id' => $completedStatusId,
1196 'payment_instrument_id' => $updatedContribution->payment_instrument_id
,
1197 'contribution_id' => $updatedContribution->id
,
1198 'trxn_date' => date('YmdHis'),
1199 'currency' => $updatedContribution->currency
,
1201 $adjustedTrxn = CRM_Core_BAO_FinancialTrxn
::create($adjustedTrxnValues);
1203 // CRM-17151: Update the contribution status to completed if balance is zero,
1204 // because due to sucessive fee change will leave the related contribution status incorrect
1206 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'contribution_status_id', $completedStatusId);
1209 return $adjustedTrxn;
1213 * Get Financial items, culling out any that have already been reversed.
1215 * @param int $entityID
1216 * @param string $entityTable
1219 * Array of financial items that have not be reversed.
1221 protected function getNonCancelledFinancialItems($entityID, $entityTable) {
1222 // gathering necessary info to record negative (deselected) financial_item
1223 $updateFinancialItem = "
1224 SELECT fi.*, price_field_value_id, financial_type_id, tax_amount
1225 FROM civicrm_financial_item fi LEFT JOIN civicrm_line_item li ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1226 WHERE (li.entity_table = '{$entityTable}' AND li.entity_id = {$entityID})
1227 GROUP BY li.entity_table, li.entity_id, price_field_value_id, fi.id
1229 $updateFinancialItemInfoDAO = CRM_Core_DAO
::executeQuery($updateFinancialItem);
1231 $financialItemResult = $updateFinancialItemInfoDAO->fetchAll();
1233 foreach ($financialItemResult as $index => $financialItem) {
1234 $items[$financialItem['price_field_value_id']][$index] = $financialItem['amount'];
1236 if (!empty($items[$financialItem['price_field_value_id']])) {
1237 foreach ($items[$financialItem['price_field_value_id']] as $existingItemID => $existingAmount) {
1238 if ($financialItem['amount'] +
$existingAmount == 0) {
1239 // Filter both rows as they cancel each other out.
1240 unset($financialItemResult[$index]);
1241 unset($financialItemResult[$existingItemID]);
1242 unset($items['price_field_value_id'][$existingItemID]);
1243 unset($items[$financialItem['price_field_value_id']][$index]);
1250 return $financialItemResult;
1254 * Get the string used to describe the sales tax (eg. VAT, GST).
1258 protected function getSalesTaxTerm() {
1259 return CRM_Contribute_BAO_Contribution
::checkContributeSettings('tax_term');
1263 * Whitelist of possible values for the entity_table field
1267 public static function entityTables(): array {
1269 'civicrm_contribution' => ts('Contribution'),
1270 'civicrm_participant' => ts('Participant'),
1271 'civicrm_membership' => ts('Membership'),