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