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