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