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