Merge pull request #20652 from seamuslee001/fix_array_access_on_number
[civicrm-core.git] / CRM / Price / BAO / LineItem.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * Business objects for Line Items generated by monetary transactions
20 */
21 class CRM_Price_BAO_LineItem extends CRM_Price_DAO_LineItem {
22
23 /**
24 * Creates a new entry in the database.
25 *
26 * @param array $params
27 * (reference) an assoc array of name/value pairs.
28 *
29 * @return CRM_Price_BAO_LineItem
30 *
31 * @throws \CiviCRM_API3_Exception
32 * @throws \Exception
33 */
34 public static function create(&$params) {
35 $id = $params['id'] ?? NULL;
36 if ($id) {
37 CRM_Utils_Hook::pre('edit', 'LineItem', $id, $params);
38 }
39 else {
40 CRM_Utils_Hook::pre('create', 'LineItem', $id, $params);
41 }
42
43 // unset entity table and entity id in $params
44 // we never update the entity table and entity id during update mode
45 if ($id) {
46 $entity_id = $params['entity_id'] ?? NULL;
47 $entity_table = $params['entity_table'] ?? NULL;
48 unset($params['entity_id'], $params['entity_table']);
49 }
50 else {
51 if (!isset($params['unit_price'])) {
52 $params['unit_price'] = 0;
53 }
54 }
55 if (isset($params['financial_type_id'], $params['line_total'])) {
56 $params['tax_amount'] = self::getTaxAmountForLineItem($params);
57 }
58
59 $lineItemBAO = new CRM_Price_BAO_LineItem();
60 $lineItemBAO->copyValues($params);
61
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,
67 ];
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);
73 }
74 }
75
76 if ($id) {
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);
81 }
82 else {
83 CRM_Utils_Hook::post('create', 'LineItem', $lineItemBAO->id, $lineItemBAO);
84 }
85
86 return $return;
87 }
88
89 /**
90 * Retrieve DB object based on input parameters.
91 *
92 * It also stores all the retrieved values in the default array.
93 *
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.
98 *
99 * @return CRM_Price_BAO_LineItem
100 */
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);
106 return $lineItem;
107 }
108 return NULL;
109 }
110
111 /**
112 * @param int $contributionId
113 *
114 * @return null|string
115 */
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;
123 }
124
125 /**
126 * Wrapper for line item retrieval when contribution ID is known.
127 * @param int $contributionID
128 *
129 * @return array
130 */
131 public static function getLineItemsByContributionID($contributionID) {
132 return self::getLineItems($contributionID, 'contribution', NULL, TRUE, TRUE);
133 }
134
135 /**
136 * Given a participant id/contribution id,
137 * return contribution/fee line items
138 *
139 * @param int $entityId
140 * participant/contribution id.
141 * @param string $entity
142 * participant/contribution.
143 *
144 * @param bool $isQuick
145 * @param bool $isQtyZero
146 * @param bool $relatedEntity
147 *
148 * @return array
149 * Array of line items
150 */
151 public static function getLineItems($entityId, $entity = 'participant', $isQuick = FALSE, $isQtyZero = TRUE, $relatedEntity = FALSE) {
152 $whereClause = $fromClause = NULL;
153 $selectClause = '
154 SELECT li.id,
155 li.label,
156 li.contribution_id,
157 li.qty,
158 li.unit_price,
159 li.line_total,
160 li.entity_table,
161 li.entity_id,
162 pf.label as field_title,
163 pf.html_type,
164 pf.price_set_id,
165 pfv.membership_type_id,
166 pfv.membership_num_terms,
167 li.price_field_id,
168 li.participant_count,
169 li.price_field_value_id,
170 li.financial_type_id,
171 li.tax_amount,
172 pfv.description';
173
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 ';
177 }
178
179 $fromClause = "
180 FROM civicrm_%2
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";
186
187 if ($isQuick) {
188 $fromClause .= " LEFT JOIN civicrm_price_set cps on cps.id = pf.price_set_id ";
189 $whereClause .= " and cps.is_quick_config = 0";
190 }
191
192 if (!$isQtyZero) {
193 $whereClause .= " and li.qty != 0";
194 }
195
196 $lineItems = [];
197
198 if (!$entityId || !$entity || !$fromClause) {
199 return $lineItems;
200 }
201
202 $params = [
203 1 => [$entityId, 'Integer'],
204 2 => [$entity, 'Text'],
205 ];
206
207 $getTaxDetails = FALSE;
208 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
209 $invoicing = $invoiceSettings['invoicing'] ?? NULL;
210
211 $dao = CRM_Core_DAO::executeQuery("$selectClause $fromClause $whereClause $orderByClause", $params);
212 while ($dao->fetch()) {
213 if (!$dao->id) {
214 continue;
215 }
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,
236 ];
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']];
241 }
242 else {
243 // There is no Tax Rate associated with this Financial Type
244 $lineItems[$dao->id]['tax_rate'] = FALSE;
245 }
246 $lineItems[$dao->id]['subTotal'] = $lineItems[$dao->id]['qty'] * $lineItems[$dao->id]['unit_price'];
247 if ($lineItems[$dao->id]['tax_amount'] != '') {
248 $getTaxDetails = TRUE;
249 }
250 }
251 if ($invoicing) {
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);
257 }
258 return $lineItems;
259 }
260
261 /**
262 * This method will create the lineItem array required for
263 * processAmount method
264 *
265 * @param int $fid
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(.
273 * this is
274 * lineItem 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
278 *
279 * @todo - this parameter is only used for partial payments. It's unclear why a partial
280 * payment would change the line item price.
281 */
282 public static function format($fid, $params, $fields, &$values, $amount_override = NULL) {
283 if (empty($params["price_{$fid}"])) {
284 return;
285 }
286
287 //lets first check in fun parameter,
288 //since user might modified w/ hooks.
289 $options = [];
290 if (array_key_exists('options', $fields)) {
291 $options = $fields['options'];
292 }
293 else {
294 CRM_Price_BAO_PriceFieldValue::getValues($fid, $options, 'weight', TRUE);
295 }
296 $fieldTitle = $fields['label'] ?? NULL;
297 if (!$fieldTitle) {
298 $fieldTitle = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'label');
299 }
300
301 foreach ($params["price_{$fid}"] as $oid => $qty) {
302 $price = $amount_override === NULL ? $options[$oid]['amount'] : $amount_override;
303
304 $participantsPerField = CRM_Utils_Array::value('count', $options[$oid], 0);
305
306 $values[$oid] = [
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,
312 'qty' => $qty,
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,
324 ];
325
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');
328 }
329 }
330 }
331
332 /**
333 * Delete line items for given entity.
334 *
335 * @param int $entityId
336 * @param int $entityTable
337 *
338 * @return bool
339 */
340 public static function deleteLineItems($entityId, $entityTable) {
341 if (!$entityId || !$entityTable) {
342 return FALSE;
343 }
344
345 if ($entityId && !is_array($entityId)) {
346 $entityId = [$entityId];
347 }
348
349 $params = [];
350 foreach ($entityId as $id) {
351 CRM_Utils_Hook::pre('delete', 'LineItem', $id, $params);
352 }
353
354 $query = "DELETE FROM civicrm_line_item where entity_id IN ('" . implode("','", $entityId) . "') AND entity_table = '$entityTable'";
355 $dao = CRM_Core_DAO::executeQuery($query);
356 return TRUE;
357 }
358
359 /**
360 * Process price set and line items.
361 *
362 * @param int $entityId
363 * @param array $lineItems
364 * Line item array.
365 * @param object $contributionDetails
366 * @param string $entityTable
367 * Entity table.
368 *
369 * @param bool $update
370 *
371 * @throws \CRM_Core_Exception
372 * @throws \CiviCRM_API3_Exception
373 */
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)
377 ) {
378 return;
379 }
380
381 foreach ($lineItems as $priceSetId => &$values) {
382 if (!$priceSetId) {
383 continue;
384 }
385
386 foreach ($values as &$line) {
387 if (empty($line['entity_table'])) {
388 $line['entity_table'] = $entityTable;
389 }
390 if (empty($line['entity_id'])) {
391 $line['entity_id'] = $entityId;
392 }
393 if (!empty($line['membership_type_id'])) {
394 $line['entity_table'] = 'civicrm_membership';
395 }
396 if (!empty($contributionDetails->id)) {
397 $line['contribution_id'] = $contributionDetails->id;
398 if ($line['entity_table'] === 'civicrm_contribution') {
399 $line['entity_id'] = $contributionDetails->id;
400 }
401 }
402
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');
407 }
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);
414 }
415 }
416 }
417 }
418 if (!$update && $contributionDetails) {
419 CRM_Core_BAO_FinancialTrxn::createDeferredTrxn($lineItems, $contributionDetails);
420 }
421 }
422
423 /**
424 * @param int $entityId
425 * @param string $entityTable
426 * @param $amount
427 * @param array $otherParams
428 */
429 public static function syncLineItems($entityId, $entityTable, $amount, $otherParams = NULL) {
430 if (!$entityId || CRM_Utils_System::isNull($amount)) {
431 return;
432 }
433
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 ";
437
438 $set = " li.unit_price = %3,
439 li.line_total = %3 ";
440
441 $where = " li.entity_id = %1 AND
442 li.entity_table = %2 ";
443
444 $params = [
445 1 => [$entityId, 'Integer'],
446 2 => [$entityTable, 'String'],
447 3 => [$amount, 'Float'],
448 ];
449
450 if ($entityTable == 'civicrm_contribution') {
451 $entityName = 'default_contribution_amount';
452 $where .= " AND ps.name = %4 ";
453 $params[4] = [$entityName, 'String'];
454 }
455 elseif ($entityTable == 'civicrm_participant') {
456 $from .= "
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;
463 $params += [
464 4 => [$otherParams['fee_label'], 'String'],
465 5 => [$otherParams['event_id'], 'String'],
466 ];
467 }
468
469 $query = "
470 UPDATE $from
471 SET $set
472 WHERE $where
473 ";
474
475 CRM_Core_DAO::executeQuery($query, $params);
476 }
477
478 /**
479 * Build line items array.
480 *
481 * @param array $params
482 * Form values.
483 *
484 * @param string $entityId
485 * Entity id.
486 *
487 * @param string $entityTable
488 * Entity Table.
489 *
490 * @param bool $isRelatedID
491 */
492 public static function getLineItemArray(&$params, $entityId = NULL, $entityTable = 'contribution', $isRelatedID = FALSE) {
493 if (!$entityId) {
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']) {
500 continue;
501 }
502 if (!$totalAmount) {
503 $totalAmount = $values['amount'];
504 }
505 $financialType = $values['financial_type_id'];
506 }
507 $lineItem = [
508 'price_field_id' => $values['priceFieldID'],
509 'price_field_value_id' => $values['priceFieldValueID'],
510 'label' => $values['label'],
511 'qty' => 1,
512 'unit_price' => $totalAmount,
513 'line_total' => $totalAmount,
514 'financial_type_id' => $financialType,
515 'membership_type_id' => $values['membership_type_id'],
516 ];
517 $lineItem['tax_amount'] = self::getTaxAmountForLineItem($lineItem);
518 $params['line_item'][$values['setID']][$values['priceFieldID']] = $lineItem;
519 break;
520 }
521 }
522 else {
523 $setID = NULL;
524 $totalEntityId = count($entityId);
525 if ($entityTable == 'contribution') {
526 $isRelatedID = TRUE;
527 }
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');
534 }
535 if (!empty($params['is_quick_config']) && array_key_exists('total_amount', $params)
536 && $totalEntityId == 1 && count($lineItems) == 1
537 ) {
538 $values['line_total'] = $values['unit_price'] = $params['total_amount'];
539 }
540 $values['id'] = $key;
541 $params['line_item'][$setID][$key] = $values;
542 }
543 }
544 }
545 }
546
547 /**
548 * Build the line items for the submitted price field.
549 *
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).
553 *
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.
560 *
561 * @param int|null $financialTypeID
562 * Financial type ID is the type should be overridden.
563 *
564 * @return array
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]
568 *
569 */
570 public static function buildLineItemsForSubmittedPriceField($priceParams, $overrideAmount = NULL, $financialTypeID = NULL) {
571 $lineItems = [];
572 foreach ($priceParams as $key => $value) {
573 $priceField = self::getPriceFieldMetaData($key);
574
575 if ($priceField['html_type'] === 'Text') {
576 $valueSpec = reset($priceField['values']);
577 }
578 else {
579 $valueSpec = $priceField['values'][$value];
580 }
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'],
586 'qty' => $qty,
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'],
592 ];
593 }
594 return $lineItems;
595 }
596
597 /**
598 * Function to update related contribution of a entity and
599 * add/update/cancel financial records
600 *
601 * @param array $params
602 * @param int $entityID
603 * @param int $entity
604 * @param int $contributionId
605 * @param $feeBlock
606 * @param array $lineItems
607 *
608 * @throws \CiviCRM_API3_Exception
609 */
610 public static function changeFeeSelections(
611 $params,
612 $entityID,
613 $entity,
614 $contributionId,
615 $feeBlock,
616 $lineItems
617 ) {
618 $entityTable = "civicrm_" . $entity;
619 $newLineItems = [];
620 CRM_Price_BAO_PriceSet::processAmount($feeBlock,
621 $params, $newLineItems
622 );
623 // initialize empty Lineitem instance to call protected helper functions
624 $lineItemObj = new CRM_Price_BAO_LineItem();
625
626 // fetch submitted LineItems from input params and feeBlock information
627 $submittedLineItems = $lineItemObj->getSubmittedLineItems($params, $feeBlock);
628
629 $requiredChanges = $lineItemObj->getLineItemsToAlter($submittedLineItems, $entityID, $entity);
630
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(
636 $entityID,
637 $entityTable,
638 $contributionId,
639 array_keys($requiredChanges['line_items_to_cancel']),
640 $requiredChanges['line_items_to_update']
641 );
642 }
643
644 // update line item with changed line total and other information
645 $totalParticipant = $participantCount = 0;
646 $amountLevel = [];
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'];
652 }
653 }
654 }
655
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);
659 }
660
661 $lineItemObj->addLineItemOnChangeFeeSelection($requiredChanges['line_items_to_add'], $entityID, $entityTable, $contributionId);
662
663 $count = 0;
664 if ($entity == 'participant') {
665 $count = count(CRM_Event_BAO_Participant::getParticipantIds($contributionId));
666 }
667 else {
668 $count = CRM_Utils_Array::value('count', civicrm_api3('MembershipPayment', 'getcount', ['contribution_id' => $contributionId]));
669 }
670 if ($count > 1) {
671 $updatedAmount = CRM_Price_BAO_LineItem::getLineTotal($contributionId);
672 }
673 else {
674 $updatedAmount = CRM_Utils_Array::value('amount', $params, CRM_Utils_Array::value('total_amount', $params));
675 }
676 if (strlen($params['tax_amount']) != 0) {
677 $taxAmount = $params['tax_amount'];
678 }
679 else {
680 $taxAmount = "NULL";
681 }
682 $displayParticipantCount = '';
683 if ($totalParticipant > 0) {
684 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
685 }
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;
689 }
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'));
692
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',
702 ]);
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,
710 ]);
711 unset($updateFinancialItemInfoValues['financialTrxn']);
712 }
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,
719 ]);
720 }
721 }
722 }
723
724 $lineItemObj->addFinancialItemsOnLineItemsChange(array_merge($requiredChanges['line_items_to_add'], $requiredChanges['line_items_to_resurrect']), $entityID, $entityTable, $contributionId, $trxn->id ?? NULL);
725
726 // update participant fee_amount column
727 $lineItemObj->updateEntityRecordOnChangeFeeSelection($params, $entityID, $entity);
728 }
729
730 /**
731 * Function to retrieve financial items that need to be recorded as result of changed fee
732 *
733 * @param int $entityID
734 * @param string $entityTable
735 * @param int $contributionID
736 * @param array $priceFieldValueIDsToCancel
737 * @param array $lineItemsToUpdate
738 *
739 * @return array
740 * List of formatted reverse Financial Items to be recorded
741 */
742 protected function getAdjustedFinancialItemsToRecord($entityID, $entityTable, $contributionID, $priceFieldValueIDsToCancel, $lineItemsToUpdate) {
743 $previousLineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, str_replace('civicrm_', '', $entityTable));
744
745 $financialItemsArray = [];
746 $financialItemResult = $this->getNonCancelledFinancialItems($entityID, $entityTable);
747 foreach ($financialItemResult as $updateFinancialItemInfoValues) {
748 $updateFinancialItemInfoValues['transaction_date'] = date('YmdHis');
749
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']];
756
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
761 ) {
762
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();
770 }
771 // INSERT negative financial_items for tax amount
772 $financialItemsArray[$updateFinancialItemInfoValues['entity_id']] = $updateFinancialItemInfoValues;
773 }
774 // INSERT a financial item to record surplus/lesser amount when a text price fee is changed
775 elseif (
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
780 ) {
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();
789 }
790 $financialItemsArray[$updateFinancialItemInfoValues['entity_id']] = $updateFinancialItemInfoValues;
791 }
792 }
793 }
794
795 return $financialItemsArray;
796 }
797
798 /**
799 * Helper function to return sum of financial item's amount related to a line-item
800 * @param array $lineItemID
801 *
802 * @return float $financialItem
803 */
804 protected function checkFinancialItemTotalAmountByLineItemID($lineItemID) {
805 return CRM_Core_DAO::singleValueQuery("
806 SELECT SUM(amount)
807 FROM civicrm_financial_item
808 WHERE entity_table = 'civicrm_line_item' AND entity_id = {$lineItemID}
809 ");
810 }
811
812 /**
813 * Helper function to retrieve submitted line items from form values $inputParams and used $feeBlock
814 *
815 * @param array $inputParams
816 * @param array $feeBlock
817 *
818 * @return array
819 * List of submitted line items
820 */
821 protected function getSubmittedLineItems($inputParams, $feeBlock) {
822 $submittedLineItems = [];
823 foreach ($feeBlock as $id => $values) {
824 CRM_Price_BAO_LineItem::format($id, $inputParams, $values, $submittedLineItems);
825 }
826
827 return $submittedLineItems;
828 }
829
830 /**
831 * Helper function to retrieve line items that need to be altered.
832 *
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.
835 *
836 * There are 4 possible changes required - per the keys in the return array.
837 *
838 * @param array $submittedLineItems
839 * @param int $entityID
840 * @param string $entity
841 *
842 * @return array
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.
852 */
853 protected function getLineItemsToAlter($submittedLineItems, $entityID, $entity) {
854 $previousLineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entity);
855
856 $lineItemsToAdd = $submittedLineItems;
857 $lineItemsToUpdate = [];
858 $submittedPriceFieldValueIDs = array_keys($submittedLineItems);
859 $lineItemsToCancel = $lineItemsToResurrect = [];
860
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']]);
870 }
871 else {
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'])
875 || (
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
879 )
880 || (
881 $previousLineItem['qty'] != $submittedLineItem['qty']
882 )
883 ) {
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']];
890 }
891 }
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']]);
896 }
897 }
898 else {
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);
902
903 }
904 }
905 }
906
907 return [
908 'line_items_to_add' => $lineItemsToAdd,
909 'line_items_to_update' => $lineItemsToUpdate,
910 'line_items_to_cancel' => $lineItemsToCancel,
911 'line_items_to_resurrect' => $lineItemsToResurrect,
912 ];
913 }
914
915 /**
916 * Check if a line item has already been cancelled.
917 *
918 * @param array $lineItem
919 *
920 * @return bool
921 */
922 protected function isCancelled($lineItem) {
923 if ($lineItem['qty'] == 0 && $lineItem['line_total'] == 0) {
924 return TRUE;
925 }
926 }
927
928 /**
929 * Add line Items as result of fee change.
930 *
931 * @param array $lineItemsToAdd
932 * @param int $entityID
933 * @param string $entityTable
934 * @param int $contributionID
935 */
936 protected function addLineItemOnChangeFeeSelection(
937 $lineItemsToAdd,
938 $entityID,
939 $entityTable,
940 $contributionID
941 ) {
942 // if there is no line item to add, do not proceed
943 if (empty($lineItemsToAdd)) {
944 return;
945 }
946
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,
956 ]);
957 if (!array_key_exists('skip', $lineParams)) {
958 self::create($lineParams);
959 }
960 }
961
962 if ($changedFinancialTypeID) {
963 $updatedContribution->financial_type_id = $changedFinancialTypeID;
964 $updatedContribution->save();
965 }
966 }
967
968 /**
969 * Add financial transactions when an array of line items is changed.
970 *
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.
977 */
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;
983
984 foreach ($lineItemsToAdd as $priceFieldValueID => $lineParams) {
985 $lineParams = array_merge($lineParams, [
986 'entity_table' => $entityTable,
987 'entity_id' => $entityID,
988 'contribution_id' => $contributionID,
989 ]);
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);
996 }
997 }
998 }
999
1000 /**
1001 * Helper function to update entity record on change fee selection
1002 *
1003 * @param array $inputParams
1004 * @param int $entityID
1005 * @param string $entity
1006 *
1007 */
1008 protected function updateEntityRecordOnChangeFeeSelection($inputParams, $entityID, $entity) {
1009 $entityTable = "civicrm_{$entity}";
1010
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);
1017 $line = [];
1018 while ($getUpdatedLineItemsDAO->fetch()) {
1019 $line[$getUpdatedLineItemsDAO->price_field_value_id] = $getUpdatedLineItemsDAO->label . ' - ' . (float) $getUpdatedLineItemsDAO->qty;
1020 }
1021
1022 $partUpdateFeeAmt['fee_level'] = implode(', ', $line);
1023 $partUpdateFeeAmt['fee_amount'] = $inputParams['amount'];
1024 CRM_Event_BAO_Participant::add($partUpdateFeeAmt);
1025
1026 //activity creation
1027 CRM_Event_BAO_Participant::addActivityForSelection($entityID, 'Change Registration');
1028 }
1029 }
1030
1031 /**
1032 * Get the metadata for a price field.
1033 *
1034 * @param string|int $key
1035 * Price field id. Either as an integer or as 'price_4' where 4 is the id
1036 *
1037 * @return array
1038 * Metadata for the price field with a values key for option values.
1039 */
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,
1045 'return' => [
1046 'id',
1047 'amount',
1048 'financial_type_id',
1049 'membership_type_id',
1050 'label',
1051 'price_field_id',
1052 'price_field_id.price_set_id',
1053 'price_field_id.html_type',
1054 'is_enter_qty',
1055 ],
1056 ]);
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;
1064 }
1065 }
1066
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,
1073 ];
1074 }
1075 return Civi::$statics[__CLASS__]['price_fields'][$priceFieldID];
1076 }
1077
1078 /**
1079 * Get the tax rate for the given line item.
1080 *
1081 * @param array $params
1082 *
1083 * @return float
1084 */
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'];
1089 }
1090
1091 /**
1092 * Helper function to retrieve financial trxn parameters to reverse
1093 * for given financial item identified by $financialItemID
1094 *
1095 * @param int $financialItemID
1096 *
1097 * @return array $financialTrxn
1098 *
1099 */
1100 protected function _getRelatedCancelFinancialTrxn($financialItemID) {
1101 try {
1102 $financialTrxn = civicrm_api3('EntityFinancialTrxn', 'getsingle', [
1103 'entity_table' => 'civicrm_financial_item',
1104 'entity_id' => $financialItemID,
1105 'options' => [
1106 'sort' => 'id DESC',
1107 'limit' => 1,
1108 ],
1109 'api.FinancialTrxn.getsingle' => [
1110 'id' => "\$value.financial_trxn_id",
1111 ],
1112 ]);
1113 }
1114 catch (CiviCRM_API3_Exception $e) {
1115 return [];
1116 }
1117
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,
1124 ]);
1125 unset($financialTrxn['id']);
1126
1127 return $financialTrxn;
1128 }
1129
1130 /**
1131 * Record adjusted amount.
1132 *
1133 * @param int $updatedAmount
1134 * @param int $contributionId
1135 * @param int $taxAmount
1136 * @param bool $updateAmountLevel
1137 *
1138 * @return bool|\CRM_Core_BAO_FinancialTrxn
1139 */
1140 protected function _recordAdjustedAmt($updatedAmount, $contributionId, $taxAmount = NULL, $updateAmountLevel = NULL) {
1141 $paidAmount = (float) CRM_Core_BAO_FinancialTrxn::getTotalPayments($contributionId);
1142 $balanceAmt = $updatedAmount - $paidAmount;
1143
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);
1148
1149 $updatedContributionDAO = new CRM_Contribute_BAO_Contribution();
1150 $adjustedTrxn = FALSE;
1151 if ($balanceAmt) {
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;
1156 }
1157 else {
1158 $updatedContributionDAO->contribution_status_id = $balanceAmt > 0 ? $partiallyPaidStatusId : $pendingRefundStatusId;
1159 }
1160
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;
1164
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;
1170 }
1171 $updatedContributionDAO->save();
1172 // adjusted amount financial_trxn creation
1173 $updatedContribution = CRM_Contribute_BAO_Contribution::getValues(
1174 ['id' => $contributionId]
1175 );
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,
1187 ];
1188 $adjustedTrxn = CRM_Core_BAO_FinancialTrxn::create($adjustedTrxnValues);
1189 }
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
1192 else {
1193 CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'contribution_status_id', $completedStatusId);
1194 }
1195
1196 return $adjustedTrxn;
1197 }
1198
1199 /**
1200 * Get Financial items, culling out any that have already been reversed.
1201 *
1202 * @param int $entityID
1203 * @param string $entityTable
1204 *
1205 * @return array
1206 * Array of financial items that have not be reversed.
1207 */
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
1215 ";
1216 $updateFinancialItemInfoDAO = CRM_Core_DAO::executeQuery($updateFinancialItem);
1217
1218 $financialItemResult = $updateFinancialItemInfoDAO->fetchAll();
1219 $items = [];
1220 foreach ($financialItemResult as $index => $financialItem) {
1221 $items[$financialItem['price_field_value_id']][$index] = $financialItem['amount'];
1222
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]);
1231 }
1232 }
1233
1234 }
1235
1236 }
1237 return $financialItemResult;
1238 }
1239
1240 /**
1241 * Get the string used to describe the sales tax (eg. VAT, GST).
1242 *
1243 * @return string
1244 */
1245 protected function getSalesTaxTerm() {
1246 return CRM_Contribute_BAO_Contribution::checkContributeSettings('tax_term');
1247 }
1248
1249 /**
1250 * Whitelist of possible values for the entity_table field
1251 *
1252 * @return array
1253 */
1254 public static function entityTables(): array {
1255 return [
1256 'civicrm_contribution' => ts('Contribution'),
1257 'civicrm_participant' => ts('Participant'),
1258 'civicrm_membership' => ts('Membership'),
1259 ];
1260 }
1261
1262 }