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