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