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