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