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