Deprecate guess work in processPriceSet
[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 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,
79 ];
80 if (!civicrm_api3('ParticipantPayment', 'getcount', $participantPaymentParams)) {
81 civicrm_api3('ParticipantPayment', 'create', $participantPaymentParams);
82 }
83 }
84
85 if ($id) {
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);
90 }
91 else {
92 CRM_Utils_Hook::post('create', 'LineItem', $lineItemBAO->id, $lineItemBAO);
93 }
94
95 return $return;
96 }
97
98 /**
99 * Retrieve DB object based on input parameters.
100 *
101 * It also stores all the retrieved values in the default array.
102 *
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.
107 *
108 * @return CRM_Price_BAO_LineItem
109 */
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);
115 return $lineItem;
116 }
117 return NULL;
118 }
119
120 /**
121 * @param int $contributionId
122 *
123 * @return null|string
124 */
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;
132 }
133
134 /**
135 * Wrapper for line item retrieval when contribution ID is known.
136 * @param int $contributionID
137 *
138 * @return array
139 */
140 public static function getLineItemsByContributionID($contributionID) {
141 return self::getLineItems($contributionID, 'contribution', NULL, TRUE, TRUE);
142 }
143
144 /**
145 * Given a participant id/contribution id,
146 * return contribution/fee line items
147 *
148 * @param int $entityId
149 * participant/contribution id.
150 * @param string $entity
151 * participant/contribution.
152 *
153 * @param bool $isQuick
154 * @param bool $isQtyZero
155 * @param bool $relatedEntity
156 *
157 * @return array
158 * Array of line items
159 */
160 public static function getLineItems($entityId, $entity = 'participant', $isQuick = FALSE, $isQtyZero = TRUE, $relatedEntity = FALSE) {
161 $whereClause = $fromClause = NULL;
162 $selectClause = '
163 SELECT li.id,
164 li.label,
165 li.contribution_id,
166 li.qty,
167 li.unit_price,
168 li.line_total,
169 li.entity_table,
170 li.entity_id,
171 pf.label as field_title,
172 pf.html_type,
173 pf.price_set_id,
174 pfv.membership_type_id,
175 pfv.membership_num_terms,
176 li.price_field_id,
177 li.participant_count,
178 li.price_field_value_id,
179 li.financial_type_id,
180 li.tax_amount,
181 pfv.description';
182
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 ';
186 }
187
188 $fromClause = "
189 FROM civicrm_%2
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";
195
196 if ($isQuick) {
197 $fromClause .= " LEFT JOIN civicrm_price_set cps on cps.id = pf.price_set_id ";
198 $whereClause .= " and cps.is_quick_config = 0";
199 }
200
201 if (!$isQtyZero) {
202 $whereClause .= " and li.qty != 0";
203 }
204
205 $lineItems = [];
206
207 if (!$entityId || !$entity || !$fromClause) {
208 return $lineItems;
209 }
210
211 $params = [
212 1 => [$entityId, 'Integer'],
213 2 => [$entity, 'Text'],
214 ];
215
216 $getTaxDetails = FALSE;
217 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
218 $invoicing = $invoiceSettings['invoicing'] ?? NULL;
219
220 $dao = CRM_Core_DAO::executeQuery("$selectClause $fromClause $whereClause $orderByClause", $params);
221 while ($dao->fetch()) {
222 if (!$dao->id) {
223 continue;
224 }
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,
245 ];
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']];
250 }
251 else {
252 // There is no Tax Rate associated with this Financial Type
253 $lineItems[$dao->id]['tax_rate'] = FALSE;
254 }
255 $lineItems[$dao->id]['subTotal'] = $lineItems[$dao->id]['qty'] * $lineItems[$dao->id]['unit_price'];
256 if ($lineItems[$dao->id]['tax_amount'] != '') {
257 $getTaxDetails = TRUE;
258 }
259 }
260 if ($invoicing) {
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);
266 }
267 return $lineItems;
268 }
269
270 /**
271 * This method will create the lineItem array required for
272 * processAmount method
273 *
274 * @param int $fid
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(.
282 * this is
283 * lineItem 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
287 *
288 * @todo - this parameter is only used for partial payments. It's unclear why a partial
289 * payment would change the line item price.
290 */
291 public static function format($fid, $params, $fields, &$values, $amount_override = NULL) {
292 if (empty($params["price_{$fid}"])) {
293 return;
294 }
295
296 //lets first check in fun parameter,
297 //since user might modified w/ hooks.
298 $options = [];
299 if (array_key_exists('options', $fields)) {
300 $options = $fields['options'];
301 }
302 else {
303 CRM_Price_BAO_PriceFieldValue::getValues($fid, $options, 'weight', TRUE);
304 }
305 $fieldTitle = $fields['label'] ?? NULL;
306 if (!$fieldTitle) {
307 $fieldTitle = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'label');
308 }
309
310 foreach ($params["price_{$fid}"] as $oid => $qty) {
311 $price = $amount_override === NULL ? $options[$oid]['amount'] : $amount_override;
312
313 $participantsPerField = CRM_Utils_Array::value('count', $options[$oid], 0);
314
315 $values[$oid] = [
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,
321 'qty' => $qty,
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,
333 ];
334
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');
337 }
338 }
339 }
340
341 /**
342 * Delete line items for given entity.
343 *
344 * @param int $entityId
345 * @param int $entityTable
346 *
347 * @return bool
348 */
349 public static function deleteLineItems($entityId, $entityTable) {
350 if (!$entityId || !$entityTable) {
351 return FALSE;
352 }
353
354 if ($entityId && !is_array($entityId)) {
355 $entityId = [$entityId];
356 }
357
358 $params = [];
359 foreach ($entityId as $id) {
360 CRM_Utils_Hook::pre('delete', 'LineItem', $id, $params);
361 }
362
363 $query = "DELETE FROM civicrm_line_item where entity_id IN ('" . implode("','", $entityId) . "') AND entity_table = '$entityTable'";
364 $dao = CRM_Core_DAO::executeQuery($query);
365 return TRUE;
366 }
367
368 /**
369 * Process price set and line items.
370 *
371 * @param int $entityId
372 * @param array $lineItems
373 * Line item array.
374 * @param object $contributionDetails
375 * @param string $entityTable
376 * Entity table.
377 *
378 * @param bool $update
379 *
380 * @throws \CRM_Core_Exception
381 * @throws \CiviCRM_API3_Exception
382 */
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)
386 ) {
387 return;
388 }
389
390 foreach ($lineItems as $priceSetId => &$values) {
391 if (!$priceSetId) {
392 continue;
393 }
394
395 foreach ($values as &$line) {
396 if (empty($line['entity_table'])) {
397 $line['entity_table'] = $entityTable;
398 }
399 if (empty($line['entity_id'])) {
400 $line['entity_id'] = $entityId;
401 }
402 if (!empty($line['membership_type_id'])) {
403 if (($line['entity_table'] ?? '') !== 'civicrm_membership') {
404 CRM_Core_Error::deprecatedWarning('entity table should be already set');
405 }
406 $line['entity_table'] = 'civicrm_membership';
407 }
408 if (!empty($contributionDetails->id)) {
409 $line['contribution_id'] = $contributionDetails->id;
410 if ($line['entity_table'] === 'civicrm_contribution') {
411 $line['entity_id'] = $contributionDetails->id;
412 }
413 }
414
415 // if financial type is not set and if price field value is NOT NULL
416 // get financial type id of price field value
417 if (!empty($line['price_field_value_id']) && empty($line['financial_type_id'])) {
418 $line['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $line['price_field_value_id'], 'financial_type_id');
419 }
420 $createdLineItem = CRM_Price_BAO_LineItem::create($line);
421 if (!$update && $contributionDetails) {
422 $financialItem = CRM_Financial_BAO_FinancialItem::add($createdLineItem, $contributionDetails);
423 $line['financial_item_id'] = $financialItem->id;
424 if (!empty($line['tax_amount'])) {
425 CRM_Financial_BAO_FinancialItem::add($createdLineItem, $contributionDetails, TRUE);
426 }
427 }
428 }
429 }
430 if (!$update && $contributionDetails) {
431 CRM_Core_BAO_FinancialTrxn::createDeferredTrxn($lineItems, $contributionDetails);
432 }
433 }
434
435 /**
436 * @param int $entityId
437 * @param string $entityTable
438 * @param $amount
439 * @param array $otherParams
440 */
441 public static function syncLineItems($entityId, $entityTable, $amount, $otherParams = NULL) {
442 if (!$entityId || CRM_Utils_System::isNull($amount)) {
443 return;
444 }
445
446 $from = " civicrm_line_item li
447 LEFT JOIN civicrm_price_field pf ON pf.id = li.price_field_id
448 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id ";
449
450 $set = " li.unit_price = %3,
451 li.line_total = %3 ";
452
453 $where = " li.entity_id = %1 AND
454 li.entity_table = %2 ";
455
456 $params = [
457 1 => [$entityId, 'Integer'],
458 2 => [$entityTable, 'String'],
459 3 => [$amount, 'Float'],
460 ];
461
462 if ($entityTable == 'civicrm_contribution') {
463 $entityName = 'default_contribution_amount';
464 $where .= " AND ps.name = %4 ";
465 $params[4] = [$entityName, 'String'];
466 }
467 elseif ($entityTable == 'civicrm_participant') {
468 $from .= "
469 LEFT JOIN civicrm_price_set_entity cpse ON cpse.price_set_id = ps.id
470 LEFT JOIN civicrm_price_field_value cpfv ON cpfv.price_field_id = pf.id and cpfv.label = %4 ";
471 $set .= " ,li.label = %4,
472 li.price_field_value_id = cpfv.id ";
473 $where .= " AND cpse.entity_table = 'civicrm_event' AND cpse.entity_id = %5 ";
474 $amount = empty($amount) ? 0 : $amount;
475 $params += [
476 4 => [$otherParams['fee_label'], 'String'],
477 5 => [$otherParams['event_id'], 'String'],
478 ];
479 }
480
481 $query = "
482 UPDATE $from
483 SET $set
484 WHERE $where
485 ";
486
487 CRM_Core_DAO::executeQuery($query, $params);
488 }
489
490 /**
491 * Build line items array.
492 *
493 * @param array $params
494 * Form values.
495 *
496 * @param string $entityId
497 * Entity id.
498 *
499 * @param string $entityTable
500 * Entity Table.
501 *
502 * @param bool $isRelatedID
503 */
504 public static function getLineItemArray(&$params, $entityId = NULL, $entityTable = 'contribution', $isRelatedID = FALSE) {
505 if (!$entityId) {
506 $priceSetDetails = CRM_Price_BAO_PriceSet::getDefaultPriceSet($entityTable);
507 $totalAmount = $params['total_amount'] ?? 0;
508 $financialType = $params['financial_type_id'] ?? NULL;
509 foreach ($priceSetDetails as $values) {
510 if ($entityTable === 'membership') {
511 if ($isRelatedID != $values['membership_type_id']) {
512 continue;
513 }
514 if (!$totalAmount) {
515 $totalAmount = $values['amount'];
516 }
517 $financialType = $values['financial_type_id'];
518 }
519 $lineItem = [
520 'price_field_id' => $values['priceFieldID'],
521 'price_field_value_id' => $values['priceFieldValueID'],
522 'label' => $values['label'],
523 'qty' => 1,
524 'unit_price' => $totalAmount,
525 'line_total' => $totalAmount,
526 'financial_type_id' => $financialType,
527 'membership_type_id' => $values['membership_type_id'],
528 ];
529 $lineItem['tax_amount'] = self::getTaxAmountForLineItem($lineItem);
530 $params['line_item'][$values['setID']][$values['priceFieldID']] = $lineItem;
531 break;
532 }
533 }
534 else {
535 $setID = NULL;
536 $totalEntityId = count($entityId);
537 if ($entityTable == 'contribution') {
538 $isRelatedID = TRUE;
539 }
540 foreach ($entityId as $id) {
541 $lineItems = CRM_Price_BAO_LineItem::getLineItems($id, $entityTable, FALSE, TRUE, $isRelatedID);
542 foreach ($lineItems as $key => $values) {
543 if (!$setID && $values['price_field_id']) {
544 $setID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $values['price_field_id'], 'price_set_id');
545 $params['is_quick_config'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $setID, 'is_quick_config');
546 }
547 if (!empty($params['is_quick_config']) && array_key_exists('total_amount', $params)
548 && $totalEntityId == 1 && count($lineItems) == 1
549 ) {
550 $values['line_total'] = $values['unit_price'] = $params['total_amount'];
551 }
552 $values['id'] = $key;
553 $params['line_item'][$setID][$key] = $values;
554 }
555 }
556 }
557 }
558
559 /**
560 * Build the line items for the submitted price field.
561 *
562 * This is when first building them - not an update where an entityId is already present
563 * as this is intended as a subfunction of that. Ideally getLineItemArray would call this
564 * (resolving to the same format regardless of what type of price set is being used first).
565 *
566 * @param array $priceParams
567 * These are per the way the form processes them - ie
568 * ['price_1' => 1, 'price_2' => 8]
569 * This would mean price field id 1, option 1 (or 1 unit if using is_enter_qty).
570 * @param float|null $overrideAmount
571 * Optional override of the amount.
572 *
573 * @param int|null $financialTypeID
574 * Financial type ID is the type should be overridden.
575 *
576 * @return array
577 * Line items formatted for processing. These will look like
578 * [4] => ['price_field_id' => 4, 'price_field_value_id' => x, 'label....qty...unit_price...line_total...financial_type_id]
579 * [5] => ['price_field_id' => 5, 'price_field_value_id' => x, 'label....qty...unit_price...line_total...financial_type_id]
580 *
581 */
582 public static function buildLineItemsForSubmittedPriceField($priceParams, $overrideAmount = NULL, $financialTypeID = NULL) {
583 $lineItems = [];
584 foreach ($priceParams as $key => $value) {
585 $priceField = self::getPriceFieldMetaData($key);
586
587 if ($priceField['html_type'] === 'Text') {
588 $valueSpec = reset($priceField['values']);
589 }
590 else {
591 $valueSpec = $priceField['values'][$value];
592 }
593 $qty = $priceField['is_enter_qty'] ? $value : 1;
594 $lineItems[$priceField['id']] = [
595 'price_field_id' => $priceField['id'],
596 'price_field_value_id' => $valueSpec['id'],
597 'label' => $valueSpec['label'],
598 'qty' => $qty,
599 'unit_price' => $overrideAmount ?: $valueSpec['amount'],
600 'line_total' => $qty * ($overrideAmount ?: $valueSpec['amount']),
601 'financial_type_id' => $financialTypeID ?: $valueSpec['financial_type_id'],
602 'membership_type_id' => $valueSpec['membership_type_id'],
603 'price_set_id' => $priceField['price_set_id'],
604 ];
605 }
606 return $lineItems;
607 }
608
609 /**
610 * Function to update related contribution of a entity and
611 * add/update/cancel financial records
612 *
613 * @param array $params
614 * @param int $entityID
615 * @param int $entity
616 * @param int $contributionId
617 * @param $feeBlock
618 * @param array $lineItems
619 *
620 * @throws \CiviCRM_API3_Exception
621 */
622 public static function changeFeeSelections(
623 $params,
624 $entityID,
625 $entity,
626 $contributionId,
627 $feeBlock,
628 $lineItems
629 ) {
630 $entityTable = "civicrm_" . $entity;
631 $newLineItems = [];
632 CRM_Price_BAO_PriceSet::processAmount($feeBlock,
633 $params, $newLineItems
634 );
635 // initialize empty Lineitem instance to call protected helper functions
636 $lineItemObj = new CRM_Price_BAO_LineItem();
637
638 // fetch submitted LineItems from input params and feeBlock information
639 $submittedLineItems = $lineItemObj->getSubmittedLineItems($params, $feeBlock);
640
641 $requiredChanges = $lineItemObj->getLineItemsToAlter($submittedLineItems, $entityID, $entity);
642
643 // get financial information that need to be recorded on basis on submitted price field value IDs
644 if (!empty($requiredChanges['line_items_to_cancel']) || !empty($requiredChanges['line_items_to_update'])) {
645 // @todo - this IF is to get this through PR merge but I suspect that it should not
646 // be necessary & is masking something else.
647 $financialItemsArray = $lineItemObj->getAdjustedFinancialItemsToRecord(
648 $entityID,
649 $entityTable,
650 $contributionId,
651 array_keys($requiredChanges['line_items_to_cancel']),
652 $requiredChanges['line_items_to_update']
653 );
654 }
655
656 // update line item with changed line total and other information
657 $totalParticipant = $participantCount = 0;
658 $amountLevel = [];
659 if (!empty($requiredChanges['line_items_to_update'])) {
660 foreach ($requiredChanges['line_items_to_update'] as $priceFieldValueID => $value) {
661 $amountLevel[] = $value['label'] . ' - ' . (float) $value['qty'];
662 if ($entity == 'participant' && isset($value['participant_count'])) {
663 $totalParticipant += $value['participant_count'];
664 }
665 }
666 }
667
668 foreach (array_merge($requiredChanges['line_items_to_resurrect'], $requiredChanges['line_items_to_cancel'], $requiredChanges['line_items_to_update']) as $lineItemToAlter) {
669 // Must use BAO rather than api because a bad line it in the api which we want to avoid.
670 CRM_Price_BAO_LineItem::create($lineItemToAlter);
671 }
672
673 $lineItemObj->addLineItemOnChangeFeeSelection($requiredChanges['line_items_to_add'], $entityID, $entityTable, $contributionId);
674
675 $count = 0;
676 if ($entity == 'participant') {
677 $count = count(CRM_Event_BAO_Participant::getParticipantIds($contributionId));
678 }
679 else {
680 $count = CRM_Utils_Array::value('count', civicrm_api3('MembershipPayment', 'getcount', ['contribution_id' => $contributionId]));
681 }
682 if ($count > 1) {
683 $updatedAmount = CRM_Price_BAO_LineItem::getLineTotal($contributionId);
684 }
685 else {
686 $updatedAmount = CRM_Utils_Array::value('amount', $params, CRM_Utils_Array::value('total_amount', $params));
687 }
688 if (strlen($params['tax_amount']) != 0) {
689 $taxAmount = $params['tax_amount'];
690 }
691 else {
692 $taxAmount = "NULL";
693 }
694 $displayParticipantCount = '';
695 if ($totalParticipant > 0) {
696 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
697 }
698 $updateAmountLevel = NULL;
699 if (!empty($amountLevel)) {
700 $updateAmountLevel = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amountLevel) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
701 }
702 $trxn = $lineItemObj->_recordAdjustedAmt($updatedAmount, $contributionId, $taxAmount, $updateAmountLevel);
703 $contributionStatus = CRM_Core_PseudoConstant::getName('CRM_Contribute_DAO_Contribution', 'contribution_status_id', CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'contribution_status_id'));
704
705 if (!empty($financialItemsArray)) {
706 foreach ($financialItemsArray as $updateFinancialItemInfoValues) {
707 $newFinancialItem = CRM_Financial_BAO_FinancialItem::create($updateFinancialItemInfoValues);
708 // record reverse transaction only if Contribution is Completed because for pending refund or
709 // partially paid we are already recording the surplus owed or refund amount
710 if (!empty($updateFinancialItemInfoValues['financialTrxn']) && ($contributionStatus == 'Completed')) {
711 $updateFinancialItemInfoValues = array_merge($updateFinancialItemInfoValues['financialTrxn'], [
712 'entity_id' => $newFinancialItem->id,
713 'entity_table' => 'civicrm_financial_item',
714 ]);
715 $reverseTrxn = CRM_Core_BAO_FinancialTrxn::create($updateFinancialItemInfoValues);
716 // record reverse entity financial trxn linked to membership's related contribution
717 civicrm_api3('EntityFinancialTrxn', 'create', [
718 'entity_table' => "civicrm_contribution",
719 'entity_id' => $contributionId,
720 'financial_trxn_id' => $reverseTrxn->id,
721 'amount' => $reverseTrxn->total_amount,
722 ]);
723 unset($updateFinancialItemInfoValues['financialTrxn']);
724 }
725 elseif ($trxn && $newFinancialItem->amount != 0) {
726 civicrm_api3('EntityFinancialTrxn', 'create', [
727 'entity_id' => $newFinancialItem->id,
728 'entity_table' => 'civicrm_financial_item',
729 'financial_trxn_id' => $trxn->id,
730 'amount' => $newFinancialItem->amount,
731 ]);
732 }
733 }
734 }
735
736 $lineItemObj->addFinancialItemsOnLineItemsChange(array_merge($requiredChanges['line_items_to_add'], $requiredChanges['line_items_to_resurrect']), $entityID, $entityTable, $contributionId, $trxn->id ?? NULL);
737
738 // update participant fee_amount column
739 $lineItemObj->updateEntityRecordOnChangeFeeSelection($params, $entityID, $entity);
740 }
741
742 /**
743 * Function to retrieve financial items that need to be recorded as result of changed fee
744 *
745 * @param int $entityID
746 * @param string $entityTable
747 * @param int $contributionID
748 * @param array $priceFieldValueIDsToCancel
749 * @param array $lineItemsToUpdate
750 *
751 * @return array
752 * List of formatted reverse Financial Items to be recorded
753 */
754 protected function getAdjustedFinancialItemsToRecord($entityID, $entityTable, $contributionID, $priceFieldValueIDsToCancel, $lineItemsToUpdate) {
755 $previousLineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, str_replace('civicrm_', '', $entityTable));
756
757 $financialItemsArray = [];
758 $financialItemResult = $this->getNonCancelledFinancialItems($entityID, $entityTable);
759 foreach ($financialItemResult as $updateFinancialItemInfoValues) {
760 $updateFinancialItemInfoValues['transaction_date'] = date('YmdHis');
761
762 // the below params are not needed as we are creating new financial item
763 $previousFinancialItemID = $updateFinancialItemInfoValues['id'];
764 $totalFinancialAmount = $this->checkFinancialItemTotalAmountByLineItemID($updateFinancialItemInfoValues['entity_id']);
765 unset($updateFinancialItemInfoValues['id']);
766 unset($updateFinancialItemInfoValues['created_date']);
767 $previousLineItem = $previousLineItems[$updateFinancialItemInfoValues['entity_id']];
768
769 // if not submitted and difference is not 0 make it negative
770 if ((empty($lineItemsToUpdate) || (in_array($updateFinancialItemInfoValues['price_field_value_id'], $priceFieldValueIDsToCancel) &&
771 $totalFinancialAmount == $updateFinancialItemInfoValues['amount'])
772 ) && $updateFinancialItemInfoValues['amount'] > 0
773 ) {
774
775 // INSERT negative financial_items
776 $updateFinancialItemInfoValues['amount'] = -$updateFinancialItemInfoValues['amount'];
777 // reverse the related financial trxn too
778 $updateFinancialItemInfoValues['financialTrxn'] = $this->getRelatedCancelFinancialTrxn($previousFinancialItemID);
779 if ($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']) {
780 $updateFinancialItemInfoValues['tax']['amount'] = -($previousLineItem['tax_amount']);
781 $updateFinancialItemInfoValues['tax']['description'] = $this->getSalesTaxTerm();
782 }
783 // INSERT negative financial_items for tax amount
784 $financialItemsArray[$updateFinancialItemInfoValues['entity_id']] = $updateFinancialItemInfoValues;
785 }
786 // INSERT a financial item to record surplus/lesser amount when a text price fee is changed
787 elseif (
788 !empty($lineItemsToUpdate)
789 && isset($lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']])
790 && $lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']]['html_type'] == 'Text'
791 && $updateFinancialItemInfoValues['amount'] > 0
792 ) {
793 $amountChangeOnTextLineItem = $lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']]['line_total'] - $totalFinancialAmount;
794 if ($amountChangeOnTextLineItem !== (float) 0) {
795 // calculate the amount difference, considered as financial item amount
796 $updateFinancialItemInfoValues['amount'] = $amountChangeOnTextLineItem;
797 if ($previousLineItem['tax_amount']
798 && $previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount'] !== 0.00) {
799 $updateFinancialItemInfoValues['tax']['amount'] = $lineItemsToUpdate[$updateFinancialItemInfoValues['entity_id']]['tax_amount'] - $previousLineItem['tax_amount'];
800 $updateFinancialItemInfoValues['tax']['description'] = $this->getSalesTaxTerm();
801 }
802 $financialItemsArray[$updateFinancialItemInfoValues['entity_id']] = $updateFinancialItemInfoValues;
803 }
804 }
805 }
806
807 return $financialItemsArray;
808 }
809
810 /**
811 * Helper function to return sum of financial item's amount related to a line-item
812 * @param array $lineItemID
813 *
814 * @return float $financialItem
815 */
816 protected function checkFinancialItemTotalAmountByLineItemID($lineItemID) {
817 return CRM_Core_DAO::singleValueQuery("
818 SELECT SUM(amount)
819 FROM civicrm_financial_item
820 WHERE entity_table = 'civicrm_line_item' AND entity_id = {$lineItemID}
821 ");
822 }
823
824 /**
825 * Helper function to retrieve submitted line items from form values $inputParams and used $feeBlock
826 *
827 * @param array $inputParams
828 * @param array $feeBlock
829 *
830 * @return array
831 * List of submitted line items
832 */
833 protected function getSubmittedLineItems($inputParams, $feeBlock) {
834 $submittedLineItems = [];
835 foreach ($feeBlock as $id => $values) {
836 CRM_Price_BAO_LineItem::format($id, $inputParams, $values, $submittedLineItems);
837 }
838
839 return $submittedLineItems;
840 }
841
842 /**
843 * Helper function to retrieve line items that need to be altered.
844 *
845 * We iterate through the previous line items for the given entity to determine
846 * what alterations to line items need to be made to reflect the new line items.
847 *
848 * There are 4 possible changes required - per the keys in the return array.
849 *
850 * @param array $submittedLineItems
851 * @param int $entityID
852 * @param string $entity
853 *
854 * @return array
855 * Array of line items to alter with the following keys
856 * - line_items_to_add. If the line items required are new radio options that
857 * have not previously been set then we should add line items for them
858 * - line_items_to_update. If we have already been an active option and a change has
859 * happened then it should be in this array.
860 * - line_items_to_cancel. Line items currently selected but not selected in the new selection.
861 * These need to be zero'd out.
862 * - line_items_to_resurrect. Line items previously selected and then deselected. These need to be
863 * re-enabled rather than a new one added.
864 */
865 protected function getLineItemsToAlter($submittedLineItems, $entityID, $entity) {
866 $previousLineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entity);
867
868 $lineItemsToAdd = $submittedLineItems;
869 $lineItemsToUpdate = [];
870 $submittedPriceFieldValueIDs = array_keys($submittedLineItems);
871 $lineItemsToCancel = $lineItemsToResurrect = [];
872
873 foreach ($previousLineItems as $id => $previousLineItem) {
874 if (in_array($previousLineItem['price_field_value_id'], $submittedPriceFieldValueIDs)) {
875 $submittedLineItem = $submittedLineItems[$previousLineItem['price_field_value_id']];
876 if (CRM_Utils_Array::value('html_type', $lineItemsToAdd[$previousLineItem['price_field_value_id']]) == 'Text') {
877 // If a 'Text' price field was updated by changing qty value, then we are not adding new line-item but updating the existing one,
878 // 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
879 // exception here by adding financial item for updated line-item and will reverse any previous financial item entries.
880 $lineItemsToUpdate[$previousLineItem['price_field_value_id']] = array_merge($submittedLineItem, ['id' => $id]);
881 unset($lineItemsToAdd[$previousLineItem['price_field_value_id']]);
882 }
883 else {
884 $submittedLineItem = $submittedLineItems[$previousLineItem['price_field_value_id']];
885 // for updating the line items i.e. use-case - once deselect-option selecting again
886 if (($previousLineItem['line_total'] != $submittedLineItem['line_total'])
887 || (
888 // This would be a $0 line item - but why it should be catered to
889 // other than when the above condition is unclear.
890 $submittedLineItem['line_total'] == 0 && $submittedLineItem['qty'] == 1
891 )
892 || (
893 $previousLineItem['qty'] != $submittedLineItem['qty']
894 )
895 ) {
896 $lineItemsToUpdate[$previousLineItem['price_field_value_id']] = $submittedLineItem;
897 $lineItemsToUpdate[$previousLineItem['price_field_value_id']]['id'] = $id;
898 // Format is actually '0.00'
899 if ($previousLineItem['line_total'] == 0) {
900 $lineItemsToAdd[$previousLineItem['price_field_value_id']]['id'] = $id;
901 $lineItemsToResurrect[] = $lineItemsToAdd[$previousLineItem['price_field_value_id']];
902 }
903 }
904 // If there was previously a submitted line item for the same option value then there is
905 // either no change or a qty adjustment. In either case we are not doing an add + reversal.
906 unset($lineItemsToAdd[$previousLineItem['price_field_value_id']]);
907 unset($lineItemsToCancel[$previousLineItem['price_field_value_id']]);
908 }
909 }
910 else {
911 if (!$this->isCancelled($previousLineItem)) {
912 $cancelParams = ['qty' => 0, 'line_total' => 0, 'tax_amount' => 0, 'participant_count' => 0, 'non_deductible_amount' => 0, 'id' => $id];
913 $lineItemsToCancel[$previousLineItem['price_field_value_id']] = array_merge($previousLineItem, $cancelParams);
914
915 }
916 }
917 }
918
919 return [
920 'line_items_to_add' => $lineItemsToAdd,
921 'line_items_to_update' => $lineItemsToUpdate,
922 'line_items_to_cancel' => $lineItemsToCancel,
923 'line_items_to_resurrect' => $lineItemsToResurrect,
924 ];
925 }
926
927 /**
928 * Check if a line item has already been cancelled.
929 *
930 * @param array $lineItem
931 *
932 * @return bool
933 */
934 protected function isCancelled($lineItem) {
935 if ($lineItem['qty'] == 0 && $lineItem['line_total'] == 0) {
936 return TRUE;
937 }
938 }
939
940 /**
941 * Add line Items as result of fee change.
942 *
943 * @param array $lineItemsToAdd
944 * @param int $entityID
945 * @param string $entityTable
946 * @param int $contributionID
947 */
948 protected function addLineItemOnChangeFeeSelection(
949 $lineItemsToAdd,
950 $entityID,
951 $entityTable,
952 $contributionID
953 ) {
954 // if there is no line item to add, do not proceed
955 if (empty($lineItemsToAdd)) {
956 return;
957 }
958
959 $changedFinancialTypeID = NULL;
960 $updatedContribution = new CRM_Contribute_BAO_Contribution();
961 $updatedContribution->id = (int) $contributionID;
962 // insert financial items
963 foreach ($lineItemsToAdd as $priceFieldValueID => $lineParams) {
964 $lineParams = array_merge($lineParams, [
965 'entity_table' => $entityTable,
966 'entity_id' => $entityID,
967 'contribution_id' => $contributionID,
968 ]);
969 if (!array_key_exists('skip', $lineParams)) {
970 self::create($lineParams);
971 }
972 }
973
974 if ($changedFinancialTypeID) {
975 $updatedContribution->financial_type_id = $changedFinancialTypeID;
976 $updatedContribution->save();
977 }
978 }
979
980 /**
981 * Add financial transactions when an array of line items is changed.
982 *
983 * @param array $lineItemsToAdd
984 * @param int $entityID
985 * @param string $entityTable
986 * @param int $contributionID
987 * @param bool $trxnID
988 * Is there a change to the total balance requiring additional transactions to be created.
989 */
990 protected function addFinancialItemsOnLineItemsChange($lineItemsToAdd, $entityID, $entityTable, $contributionID, $trxnID) {
991 $updatedContribution = new CRM_Contribute_BAO_Contribution();
992 $updatedContribution->id = $contributionID;
993 $updatedContribution->find(TRUE);
994 $trxnArray = $trxnID ? ['id' => $trxnID] : NULL;
995
996 foreach ($lineItemsToAdd as $priceFieldValueID => $lineParams) {
997 $lineParams = array_merge($lineParams, [
998 'entity_table' => $entityTable,
999 'entity_id' => $entityID,
1000 'contribution_id' => $contributionID,
1001 ]);
1002 $lineObj = CRM_Price_BAO_LineItem::retrieve($lineParams);
1003 // insert financial items
1004 // ensure entity_financial_trxn table has a linking of it.
1005 CRM_Financial_BAO_FinancialItem::add($lineObj, $updatedContribution, NULL, $trxnArray);
1006 if (isset($lineObj->tax_amount) && (float) $lineObj->tax_amount !== 0.00) {
1007 CRM_Financial_BAO_FinancialItem::add($lineObj, $updatedContribution, TRUE, $trxnArray);
1008 }
1009 }
1010 }
1011
1012 /**
1013 * Helper function to update entity record on change fee selection
1014 *
1015 * @param array $inputParams
1016 * @param int $entityID
1017 * @param string $entity
1018 *
1019 */
1020 protected function updateEntityRecordOnChangeFeeSelection($inputParams, $entityID, $entity) {
1021 $entityTable = "civicrm_{$entity}";
1022
1023 if ($entity == 'participant') {
1024 $partUpdateFeeAmt = ['id' => $entityID];
1025 $getUpdatedLineItems = "SELECT *
1026 FROM civicrm_line_item
1027 WHERE (entity_table = '{$entityTable}' AND entity_id = {$entityID} AND qty > 0)";
1028 $getUpdatedLineItemsDAO = CRM_Core_DAO::executeQuery($getUpdatedLineItems);
1029 $line = [];
1030 while ($getUpdatedLineItemsDAO->fetch()) {
1031 $line[$getUpdatedLineItemsDAO->price_field_value_id] = $getUpdatedLineItemsDAO->label . ' - ' . (float) $getUpdatedLineItemsDAO->qty;
1032 }
1033
1034 $partUpdateFeeAmt['fee_level'] = implode(', ', $line);
1035 $partUpdateFeeAmt['fee_amount'] = $inputParams['amount'];
1036 CRM_Event_BAO_Participant::add($partUpdateFeeAmt);
1037
1038 //activity creation
1039 CRM_Event_BAO_Participant::addActivityForSelection($entityID, 'Change Registration');
1040 }
1041 }
1042
1043 /**
1044 * Get the metadata for a price field.
1045 *
1046 * @param string|int $key
1047 * Price field id. Either as an integer or as 'price_4' where 4 is the id
1048 *
1049 * @return array
1050 * Metadata for the price field with a values key for option values.
1051 */
1052 protected static function getPriceFieldMetaData($key) {
1053 $priceFieldID = str_replace('price_', '', $key);
1054 if (!isset(Civi::$statics[__CLASS__]['price_fields'][$priceFieldID])) {
1055 $values = civicrm_api3('PriceFieldValue', 'get', [
1056 'price_field_id' => $priceFieldID,
1057 'return' => [
1058 'id',
1059 'amount',
1060 'financial_type_id',
1061 'membership_type_id',
1062 'label',
1063 'price_field_id',
1064 'price_field_id.price_set_id',
1065 'price_field_id.html_type',
1066 'is_enter_qty',
1067 ],
1068 ]);
1069 $firstValue = reset($values['values']);
1070 $values = $values['values'];
1071 foreach ($values as $index => $value) {
1072 // Let's be nice to calling functions & ensure membership_type_id is set
1073 // so they don't have to handle notices on it. Handle one place not many.
1074 if (!isset($value['membership_type_id'])) {
1075 $values[$index]['membership_type_id'] = NULL;
1076 }
1077 }
1078
1079 Civi::$statics[__CLASS__]['price_fields'][$priceFieldID] = [
1080 'price_set_id' => $firstValue['price_field_id.price_set_id'],
1081 'id' => $firstValue['price_field_id'],
1082 'html_type' => $firstValue['price_field_id.html_type'],
1083 'is_enter_qty' => !empty($firstValue['is_enter_qty']),
1084 'values' => $values,
1085 ];
1086 }
1087 return Civi::$statics[__CLASS__]['price_fields'][$priceFieldID];
1088 }
1089
1090 /**
1091 * Get the tax rate for the given line item.
1092 *
1093 * @param array $params
1094 *
1095 * @return float
1096 */
1097 protected static function getTaxAmountForLineItem(array $params): float {
1098 $taxRates = CRM_Core_PseudoConstant::getTaxRates();
1099 $taxRate = $taxRates[$params['financial_type_id']] ?? 0;
1100 return ($taxRate / 100) * $params['line_total'];
1101 }
1102
1103 /**
1104 * Helper function to retrieve financial trxn parameters to reverse
1105 * for given financial item identified by $financialItemID
1106 *
1107 * @param int $financialItemID
1108 *
1109 * @return array $financialTrxn
1110 *
1111 */
1112 protected function _getRelatedCancelFinancialTrxn($financialItemID) {
1113 try {
1114 $financialTrxn = civicrm_api3('EntityFinancialTrxn', 'getsingle', [
1115 'entity_table' => 'civicrm_financial_item',
1116 'entity_id' => $financialItemID,
1117 'options' => [
1118 'sort' => 'id DESC',
1119 'limit' => 1,
1120 ],
1121 'api.FinancialTrxn.getsingle' => [
1122 'id' => "\$value.financial_trxn_id",
1123 ],
1124 ]);
1125 }
1126 catch (CiviCRM_API3_Exception $e) {
1127 return [];
1128 }
1129
1130 $financialTrxn = array_merge($financialTrxn['api.FinancialTrxn.getsingle'], [
1131 'trxn_date' => date('YmdHis'),
1132 'total_amount' => -$financialTrxn['api.FinancialTrxn.getsingle']['total_amount'],
1133 'net_amount' => -$financialTrxn['api.FinancialTrxn.getsingle']['net_amount'],
1134 'entity_table' => 'civicrm_financial_item',
1135 'entity_id' => $financialItemID,
1136 ]);
1137 unset($financialTrxn['id']);
1138
1139 return $financialTrxn;
1140 }
1141
1142 /**
1143 * Record adjusted amount.
1144 *
1145 * @param int $updatedAmount
1146 * @param int $contributionId
1147 * @param int $taxAmount
1148 * @param bool $updateAmountLevel
1149 *
1150 * @return bool|\CRM_Core_BAO_FinancialTrxn
1151 */
1152 protected function _recordAdjustedAmt($updatedAmount, $contributionId, $taxAmount = NULL, $updateAmountLevel = NULL) {
1153 $paidAmount = (float) CRM_Core_BAO_FinancialTrxn::getTotalPayments($contributionId);
1154 $balanceAmt = $updatedAmount - $paidAmount;
1155
1156 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
1157 $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
1158 $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
1159 $completedStatusId = array_search('Completed', $contributionStatuses);
1160
1161 $updatedContributionDAO = new CRM_Contribute_BAO_Contribution();
1162 $adjustedTrxn = FALSE;
1163 if ($balanceAmt) {
1164 if ($paidAmount === 0.0) {
1165 //skip updating the contribution status if no payment is made
1166 $updatedContributionDAO->cancel_date = 'null';
1167 $updatedContributionDAO->cancel_reason = NULL;
1168 }
1169 else {
1170 $updatedContributionDAO->contribution_status_id = $balanceAmt > 0 ? $partiallyPaidStatusId : $pendingRefundStatusId;
1171 }
1172
1173 // update contribution status and total amount without trigger financial code
1174 // as this is handled in current BAO function used for change selection
1175 $updatedContributionDAO->id = $contributionId;
1176
1177 $updatedContributionDAO->total_amount = $updatedContributionDAO->net_amount = $updatedAmount;
1178 $updatedContributionDAO->fee_amount = 0;
1179 $updatedContributionDAO->tax_amount = $taxAmount;
1180 if (!empty($updateAmountLevel)) {
1181 $updatedContributionDAO->amount_level = $updateAmountLevel;
1182 }
1183 $updatedContributionDAO->save();
1184 // adjusted amount financial_trxn creation
1185 $updatedContribution = CRM_Contribute_BAO_Contribution::getValues(
1186 ['id' => $contributionId]
1187 );
1188 $toFinancialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($updatedContribution->financial_type_id, 'Accounts Receivable Account is');
1189 $adjustedTrxnValues = [
1190 'from_financial_account_id' => NULL,
1191 'to_financial_account_id' => $toFinancialAccount,
1192 'total_amount' => $balanceAmt,
1193 'net_amount' => $balanceAmt,
1194 'status_id' => $completedStatusId,
1195 'payment_instrument_id' => $updatedContribution->payment_instrument_id,
1196 'contribution_id' => $updatedContribution->id,
1197 'trxn_date' => date('YmdHis'),
1198 'currency' => $updatedContribution->currency,
1199 ];
1200 $adjustedTrxn = CRM_Core_BAO_FinancialTrxn::create($adjustedTrxnValues);
1201 }
1202 // CRM-17151: Update the contribution status to completed if balance is zero,
1203 // because due to sucessive fee change will leave the related contribution status incorrect
1204 else {
1205 CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'contribution_status_id', $completedStatusId);
1206 }
1207
1208 return $adjustedTrxn;
1209 }
1210
1211 /**
1212 * Get Financial items, culling out any that have already been reversed.
1213 *
1214 * @param int $entityID
1215 * @param string $entityTable
1216 *
1217 * @return array
1218 * Array of financial items that have not be reversed.
1219 */
1220 protected function getNonCancelledFinancialItems($entityID, $entityTable) {
1221 // gathering necessary info to record negative (deselected) financial_item
1222 $updateFinancialItem = "
1223 SELECT fi.*, price_field_value_id, financial_type_id, tax_amount
1224 FROM civicrm_financial_item fi LEFT JOIN civicrm_line_item li ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1225 WHERE (li.entity_table = '{$entityTable}' AND li.entity_id = {$entityID})
1226 GROUP BY li.entity_table, li.entity_id, price_field_value_id, fi.id
1227 ";
1228 $updateFinancialItemInfoDAO = CRM_Core_DAO::executeQuery($updateFinancialItem);
1229
1230 $financialItemResult = $updateFinancialItemInfoDAO->fetchAll();
1231 $items = [];
1232 foreach ($financialItemResult as $index => $financialItem) {
1233 $items[$financialItem['price_field_value_id']][$index] = $financialItem['amount'];
1234
1235 if (!empty($items[$financialItem['price_field_value_id']])) {
1236 foreach ($items[$financialItem['price_field_value_id']] as $existingItemID => $existingAmount) {
1237 if ($financialItem['amount'] + $existingAmount == 0) {
1238 // Filter both rows as they cancel each other out.
1239 unset($financialItemResult[$index]);
1240 unset($financialItemResult[$existingItemID]);
1241 unset($items['price_field_value_id'][$existingItemID]);
1242 unset($items[$financialItem['price_field_value_id']][$index]);
1243 }
1244 }
1245
1246 }
1247
1248 }
1249 return $financialItemResult;
1250 }
1251
1252 /**
1253 * Get the string used to describe the sales tax (eg. VAT, GST).
1254 *
1255 * @return string
1256 */
1257 protected function getSalesTaxTerm() {
1258 return CRM_Contribute_BAO_Contribution::checkContributeSettings('tax_term');
1259 }
1260
1261 /**
1262 * Whitelist of possible values for the entity_table field
1263 *
1264 * @return array
1265 */
1266 public static function entityTables(): array {
1267 return [
1268 'civicrm_contribution' => ts('Contribution'),
1269 'civicrm_participant' => ts('Participant'),
1270 'civicrm_membership' => ts('Membership'),
1271 ];
1272 }
1273
1274 }