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