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