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