Merge pull request #17253 from mattwire/utf8convertblocksize
[civicrm-core.git] / CRM / Financial / BAO / Payment.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * This class contains payment related functions.
20 */
21 class CRM_Financial_BAO_Payment {
22
23 /**
24 * Function to process additional payment for partial and refund contributions.
25 *
26 * This function is called via API payment.create function. All forms that add payments
27 * should use this.
28 *
29 * @param array $params
30 * - contribution_id
31 * - total_amount
32 * - line_item
33 *
34 * @return \CRM_Financial_DAO_FinancialTrxn
35 *
36 * @throws \CRM_Core_Exception
37 * @throws \CiviCRM_API3_Exception
38 */
39 public static function create($params) {
40 $contribution = civicrm_api3('Contribution', 'getsingle', ['id' => $params['contribution_id']]);
41 $contributionStatus = CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution['contribution_status_id']);
42 $isPaymentCompletesContribution = self::isPaymentCompletesContribution($params['contribution_id'], $params['total_amount'], $contributionStatus);
43 $lineItems = self::getPayableLineItems($params);
44
45 $whiteList = ['check_number', 'payment_processor_id', 'fee_amount', 'total_amount', 'contribution_id', 'net_amount', 'card_type_id', 'pan_truncation', 'trxn_result_code', 'payment_instrument_id', 'trxn_id', 'trxn_date'];
46 $paymentTrxnParams = array_intersect_key($params, array_fill_keys($whiteList, 1));
47 $paymentTrxnParams['is_payment'] = 1;
48 // Really we should have a DB default.
49 $paymentTrxnParams['fee_amount'] = $paymentTrxnParams['fee_amount'] ?? 0;
50
51 if (isset($paymentTrxnParams['payment_processor_id']) && empty($paymentTrxnParams['payment_processor_id'])) {
52 // Don't pass 0 - ie the Pay Later processor as it is a pseudo-processor.
53 unset($paymentTrxnParams['payment_processor_id']);
54 }
55 if (empty($paymentTrxnParams['payment_instrument_id'])) {
56 if (!empty($params['payment_processor_id'])) {
57 $paymentTrxnParams['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', ['return' => 'payment_instrument_id', 'id' => $paymentTrxnParams['payment_processor_id']]);
58 }
59 else {
60 // Fall back on the payment instrument already used - should we deprecate this?
61 $paymentTrxnParams['payment_instrument_id'] = $contribution['payment_instrument_id'];
62 }
63 }
64 if (empty($paymentTrxnParams['trxn_id']) && !empty($paymentTrxnParams['contribution_trxn_id'])) {
65 CRM_Core_Error::deprecatedFunctionWarning('contribution_trxn_id is deprecated - use trxn_id');
66 $paymentTrxnParams['trxn_id'] = $paymentTrxnParams['contribution_trxn_id'];
67 }
68
69 $paymentTrxnParams['currency'] = $contribution['currency'];
70
71 $accountsReceivableAccount = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship($contribution['financial_type_id'], 'Accounts Receivable Account is');
72 $paymentTrxnParams['to_financial_account_id'] = CRM_Contribute_BAO_Contribution::getToFinancialAccount($contribution, $params);
73 $paymentTrxnParams['from_financial_account_id'] = $accountsReceivableAccount;
74
75 if ($params['total_amount'] > 0) {
76 $paymentTrxnParams['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_FinancialTrxn', 'status_id', 'Completed');
77 }
78 elseif ($params['total_amount'] < 0) {
79 $paymentTrxnParams['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Refunded');
80 }
81
82 $trxn = CRM_Core_BAO_FinancialTrxn::create($paymentTrxnParams);
83
84 if ($params['total_amount'] < 0 && !empty($params['cancelled_payment_id'])) {
85 self::reverseAllocationsFromPreviousPayment($params, $trxn->id);
86 return $trxn;
87 }
88 list($ftIds, $taxItems) = CRM_Contribute_BAO_Contribution::getLastFinancialItemIds($params['contribution_id']);
89
90 foreach ($lineItems as $key => $value) {
91 if ($value['allocation'] === (float) 0) {
92 continue;
93 }
94
95 if (!empty($ftIds[$value['price_field_value_id']])) {
96 $financialItemID = $ftIds[$value['price_field_value_id']];
97 }
98 else {
99 $financialItemID = self::getNewFinancialItemID($value, $params['trxn_date'], $contribution['contact_id'], $paymentTrxnParams['currency']);
100 }
101
102 $eftParams = [
103 'entity_table' => 'civicrm_financial_item',
104 'financial_trxn_id' => $trxn->id,
105 'entity_id' => $financialItemID,
106 'amount' => $value['allocation'],
107 ];
108
109 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
110
111 if (array_key_exists($value['price_field_value_id'], $taxItems)) {
112 // @todo - this is expected to be broken - it should be fixed to
113 // a) have the getPayableLineItems add the amount to allocate for tax
114 // b) call EntityFinancialTrxn directly - per above.
115 // - see https://github.com/civicrm/civicrm-core/pull/14763
116 $entityParams = [
117 'contribution_total_amount' => $contribution['total_amount'],
118 'trxn_total_amount' => $params['total_amount'],
119 'trxn_id' => $trxn->id,
120 'line_item_amount' => $taxItems[$value['price_field_value_id']]['amount'],
121 ];
122 $eftParams['entity_id'] = $taxItems[$value['price_field_value_id']]['financial_item_id'];
123 CRM_Contribute_BAO_Contribution::createProportionalEntry($entityParams, $eftParams);
124 }
125 }
126
127 if ($isPaymentCompletesContribution) {
128 if ($contributionStatus === 'Pending refund') {
129 // Ideally we could still call completetransaction as non-payment related actions should
130 // be outside this class. However, for now we just update the contribution here.
131 // Unit test cover in CRM_Event_BAO_AdditionalPaymentTest::testTransactionInfo.
132 civicrm_api3('Contribution', 'create',
133 [
134 'id' => $contribution['id'],
135 'contribution_status_id' => 'Completed',
136 ]
137 );
138 }
139 else {
140 civicrm_api3('Contribution', 'completetransaction', [
141 'id' => $contribution['id'],
142 'is_post_payment_create' => TRUE,
143 'is_email_receipt' => $params['is_send_contribution_notification'],
144 ]);
145 // Get the trxn
146 $trxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contribution['id'], 'DESC');
147 $ftParams = ['id' => $trxnId['financialTrxnId']];
148 $trxn = CRM_Core_BAO_FinancialTrxn::retrieve($ftParams);
149 }
150 }
151 elseif ($contributionStatus === 'Pending' && $params['total_amount'] > 0) {
152 self::updateContributionStatus($contribution['id'], 'Partially Paid');
153 $participantPayments = civicrm_api3('ParticipantPayment', 'get', [
154 'contribution_id' => $contribution['id'],
155 'participant_id.status_id' => ['IN' => ['Pending from pay later', 'Pending from incomplete transaction']],
156 ])['values'];
157 foreach ($participantPayments as $participantPayment) {
158 civicrm_api3('Participant', 'create', ['id' => $participantPayment['participant_id'], 'status_id' => 'Partially paid']);
159 }
160 }
161 elseif ($contributionStatus === 'Completed' && ((float) CRM_Core_BAO_FinancialTrxn::getTotalPayments($contribution['id'], TRUE) === 0.0)) {
162 // If the contribution has previously been completed (fully paid) and now has total payments adding up to 0
163 // change status to refunded.
164 self::updateContributionStatus($contribution['id'], 'Refunded');
165 }
166 self::updateRelatedContribution($params, $params['contribution_id']);
167 CRM_Contribute_BAO_Contribution::recordPaymentActivity($params['contribution_id'], CRM_Utils_Array::value('participant_id', $params), $params['total_amount'], $trxn->currency, $trxn->trxn_date);
168 return $trxn;
169 }
170
171 /**
172 * Function to update contribution's check_number and trxn_id by
173 * concatenating values from financial trxn's check_number and trxn_id respectively
174 *
175 * @param array $params
176 * @param int $contributionID
177 */
178 public static function updateRelatedContribution($params, $contributionID) {
179 $contributionDAO = new CRM_Contribute_DAO_Contribution();
180 $contributionDAO->id = $contributionID;
181 $contributionDAO->find(TRUE);
182
183 foreach (['trxn_id', 'check_number'] as $fieldName) {
184 if (!empty($params[$fieldName])) {
185 $values = [];
186 if (!empty($contributionDAO->$fieldName)) {
187 $values = explode(',', $contributionDAO->$fieldName);
188 }
189 // if submitted check_number or trxn_id value is
190 // already present then ignore else add to $values array
191 if (!in_array($params[$fieldName], $values)) {
192 $values[] = $params[$fieldName];
193 }
194 $contributionDAO->$fieldName = implode(',', $values);
195 }
196 }
197
198 $contributionDAO->save();
199 }
200
201 /**
202 * Send an email confirming a payment that has been received.
203 *
204 * @param array $params
205 *
206 * @return array
207 *
208 * @throws \CiviCRM_API3_Exception
209 */
210 public static function sendConfirmation($params) {
211
212 $entities = self::loadRelatedEntities($params['id']);
213 $sendTemplateParams = [
214 'groupName' => 'msg_tpl_workflow_contribution',
215 'valueName' => 'payment_or_refund_notification',
216 'PDFFilename' => ts('notification') . '.pdf',
217 'contactId' => $entities['contact']['id'],
218 'toName' => $entities['contact']['display_name'],
219 'toEmail' => $entities['contact']['email'],
220 'tplParams' => self::getConfirmationTemplateParameters($entities),
221 ];
222 if (!empty($params['from']) && !empty($params['check_permissions'])) {
223 // Filter from against permitted emails.
224 $validEmails = self::getValidFromEmailsForPayment($entities['event']['id'] ?? NULL);
225 if (!isset($validEmails[$params['from']])) {
226 // Ignore unpermitted parameter.
227 unset($params['from']);
228 }
229 }
230 $sendTemplateParams['from'] = $params['from'] ?? key(CRM_Core_BAO_Email::domainEmails());
231 return CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
232 }
233
234 /**
235 * Get valid from emails for payment.
236 *
237 * @param int $eventID
238 *
239 * @return array
240 */
241 public static function getValidFromEmailsForPayment($eventID = NULL) {
242 if ($eventID) {
243 $emails = CRM_Event_BAO_Event::getFromEmailIds($eventID);
244 }
245 else {
246 $emails['from_email_id'] = CRM_Core_BAO_Email::getFromEmail();
247 }
248 return $emails['from_email_id'];
249 }
250
251 /**
252 * Load entities related to the current payment id.
253 *
254 * This gives us all the data we need to send an email confirmation but avoiding
255 * getting anything not tested for the confirmations. We retrieve the 'full' event as
256 * it has been traditionally assigned in full.
257 *
258 * @param int $id
259 *
260 * @return array
261 * - contact = ['id' => x, 'display_name' => y, 'email' => z]
262 * - event = [.... full event details......]
263 * - contribution = ['id' => x],
264 * - payment = [payment info + payment summary info]
265 * @throws \CiviCRM_API3_Exception
266 */
267 protected static function loadRelatedEntities($id) {
268 $entities = [];
269 $contributionID = (int) civicrm_api3('EntityFinancialTrxn', 'getvalue', [
270 'financial_trxn_id' => $id,
271 'entity_table' => 'civicrm_contribution',
272 'return' => 'entity_id',
273 ]);
274 $entities['contribution'] = ['id' => $contributionID];
275 $entities['payment'] = array_merge(civicrm_api3('FinancialTrxn', 'getsingle', ['id' => $id]),
276 CRM_Contribute_BAO_Contribution::getPaymentInfo($contributionID)
277 );
278
279 $contactID = self::getPaymentContactID($contributionID);
280 list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
281 $entities['contact'] = ['id' => $contactID, 'display_name' => $displayName, 'email' => $email];
282 $contact = civicrm_api3('Contact', 'getsingle', ['id' => $contactID, 'return' => 'email_greeting']);
283 $entities['contact']['email_greeting'] = $contact['email_greeting_display'];
284
285 $participantRecords = civicrm_api3('ParticipantPayment', 'get', [
286 'contribution_id' => $contributionID,
287 'api.Participant.get' => ['return' => 'event_id'],
288 'sequential' => 1,
289 ])['values'];
290 if (!empty($participantRecords)) {
291 $entities['event'] = civicrm_api3('Event', 'getsingle', ['id' => $participantRecords[0]['api.Participant.get']['values'][0]['event_id']]);
292 if (!empty($entities['event']['is_show_location'])) {
293 $locationParams = [
294 'entity_id' => $entities['event']['id'],
295 'entity_table' => 'civicrm_event',
296 ];
297 $entities['location'] = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
298 }
299 }
300
301 return $entities;
302 }
303
304 /**
305 * @param int $contributionID
306 *
307 * @return int
308 * @throws \CiviCRM_API3_Exception
309 * @throws \CiviCRM_API3_Exception
310 */
311 public static function getPaymentContactID($contributionID) {
312 $contribution = civicrm_api3('Contribution', 'getsingle', [
313 'id' => $contributionID ,
314 'return' => ['contact_id'],
315 ]);
316 return (int) $contribution['contact_id'];
317 }
318
319 /**
320 * @param array $entities
321 * Related entities as an array keyed by the various entities.
322 *
323 * @return array
324 * Values required for the notification
325 * - contact_id
326 * - template_variables
327 * - event (DAO of event if relevant)
328 */
329 public static function getConfirmationTemplateParameters($entities) {
330 $templateVariables = [
331 'contactDisplayName' => $entities['contact']['display_name'],
332 'emailGreeting' => $entities['contact']['email_greeting'],
333 'totalAmount' => $entities['payment']['total'],
334 'amountOwed' => $entities['payment']['balance'],
335 'totalPaid' => $entities['payment']['paid'],
336 'paymentAmount' => $entities['payment']['total_amount'],
337 'checkNumber' => $entities['payment']['check_number'] ?? NULL,
338 'receive_date' => $entities['payment']['trxn_date'],
339 'paidBy' => CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $entities['payment']['payment_instrument_id']),
340 'isShowLocation' => (!empty($entities['event']) ? $entities['event']['is_show_location'] : FALSE),
341 'location' => $entities['location'] ?? NULL,
342 'event' => $entities['event'] ?? NULL,
343 'component' => (!empty($entities['event']) ? 'event' : 'contribution'),
344 'isRefund' => $entities['payment']['total_amount'] < 0,
345 'isAmountzero' => $entities['payment']['total_amount'] === 0,
346 'refundAmount' => ($entities['payment']['total_amount'] < 0 ? $entities['payment']['total_amount'] : NULL),
347 'paymentsComplete' => ($entities['payment']['balance'] == 0),
348 ];
349
350 return self::filterUntestedTemplateVariables($templateVariables);
351 }
352
353 /**
354 * Filter out any untested variables.
355 *
356 * This just serves to highlight if any variables are added without a unit test also being added.
357 *
358 * (if hit then add a unit test for the param & add to this array).
359 *
360 * @param array $params
361 *
362 * @return array
363 */
364 public static function filterUntestedTemplateVariables($params) {
365 $testedTemplateVariables = [
366 'contactDisplayName',
367 'totalAmount',
368 'amountOwed',
369 'paymentAmount',
370 'event',
371 'component',
372 'checkNumber',
373 'receive_date',
374 'paidBy',
375 'isShowLocation',
376 'location',
377 'isRefund',
378 'isAmountzero',
379 'refundAmount',
380 'totalPaid',
381 'paymentsComplete',
382 'emailGreeting',
383 ];
384 // These are assigned by the payment form - they still 'get through' from the
385 // form for now without being in here but we should ideally load
386 // and assign. Note we should update the tpl to use {if $billingName}
387 // and ditch contributeMode - although it might need to be deprecated rather than removed.
388 $todoParams = [
389 'contributeMode',
390 'billingName',
391 'address',
392 'credit_card_type',
393 'credit_card_number',
394 'credit_card_exp_date',
395 ];
396 $filteredParams = [];
397 foreach ($testedTemplateVariables as $templateVariable) {
398 // This will cause an a-notice if any are NOT set - by design. Ensuring
399 // they are set prevents leakage.
400 $filteredParams[$templateVariable] = $params[$templateVariable];
401 }
402 return $filteredParams;
403 }
404
405 /**
406 * Does this payment complete the contribution.
407 *
408 * @param int $contributionID
409 * @param float $paymentAmount
410 * @param string $previousStatus
411 *
412 * @return bool
413 */
414 protected static function isPaymentCompletesContribution($contributionID, $paymentAmount, $previousStatus) {
415 if ($previousStatus === 'Completed') {
416 return FALSE;
417 }
418 $outstandingBalance = CRM_Contribute_BAO_Contribution::getContributionBalance($contributionID);
419 $cmp = bccomp($paymentAmount, $outstandingBalance, 5);
420 return ($cmp == 0 || $cmp == 1);
421 }
422
423 /**
424 * Update the status of the contribution.
425 *
426 * We pass the is_post_payment_create as we have already created the line items
427 *
428 * @param int $contributionID
429 * @param string $status
430 *
431 * @throws \CiviCRM_API3_Exception
432 */
433 private static function updateContributionStatus(int $contributionID, string $status) {
434 civicrm_api3('Contribution', 'create',
435 [
436 'id' => $contributionID,
437 'is_post_payment_create' => TRUE,
438 'contribution_status_id' => $status,
439 ]
440 );
441 }
442
443 /**
444 * Get the line items for the contribution.
445 *
446 * Retrieve the line items and wrangle the following
447 *
448 * - get the outstanding balance on a line item basis.
449 * - determine what amount is being paid on this line item - we get the total being paid
450 * for the whole contribution and determine the ratio of the balance that is being paid
451 * and then assign apply that ratio to each line item.
452 * - if overrides have been passed in we use those amounts instead.
453 *
454 * @param $params
455 *
456 * @return array
457 * @throws \CiviCRM_API3_Exception
458 */
459 protected static function getPayableLineItems($params): array {
460 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($params['contribution_id']);
461 $lineItemOverrides = [];
462 if (!empty($params['line_item'])) {
463 // The format is a bit weird here - $params['line_item'] => [[1 => 10], [2 => 40]]
464 // Squash to [1 => 10, 2 => 40]
465 foreach ($params['line_item'] as $lineItem) {
466 $lineItemOverrides += $lineItem;
467 }
468 }
469 $outstandingBalance = CRM_Contribute_BAO_Contribution::getContributionBalance($params['contribution_id']);
470 if ($outstandingBalance !== 0.0) {
471 $ratio = $params['total_amount'] / $outstandingBalance;
472 }
473 else {
474 // Help we are making a payment but no money is owed. We won't allocate the overpayment to any line item.
475 $ratio = 0;
476 }
477 foreach ($lineItems as $lineItemID => $lineItem) {
478 // Ideally id would be set deeper but for now just add in here.
479 $lineItems[$lineItemID]['id'] = $lineItemID;
480 $lineItems[$lineItemID]['paid'] = self::getAmountOfLineItemPaid($lineItemID);
481 $lineItems[$lineItemID]['balance'] = $lineItem['subTotal'] - $lineItems[$lineItemID]['paid'];
482
483 if (!empty($lineItemOverrides)) {
484 $lineItems[$lineItemID]['allocation'] = $lineItemOverrides[$lineItemID] ?? NULL;
485 }
486 else {
487 $lineItems[$lineItemID]['allocation'] = $lineItems[$lineItemID]['balance'] * $ratio;
488 }
489 }
490 return $lineItems;
491 }
492
493 /**
494 * Get the amount paid so far against this line item.
495 *
496 * @param int $lineItemID
497 *
498 * @return float
499 *
500 * @throws \CiviCRM_API3_Exception
501 */
502 protected static function getAmountOfLineItemPaid($lineItemID) {
503 $paid = 0;
504 $financialItems = civicrm_api3('FinancialItem', 'get', [
505 'entity_id' => $lineItemID,
506 'entity_table' => 'civicrm_line_item',
507 'options' => ['sort' => 'id DESC', 'limit' => 0],
508 ])['values'];
509 if (!empty($financialItems)) {
510 $entityFinancialTrxns = civicrm_api3('EntityFinancialTrxn', 'get', [
511 'entity_table' => 'civicrm_financial_item',
512 'entity_id' => ['IN' => array_keys($financialItems)],
513 'options' => ['limit' => 0],
514 'financial_trxn_id.is_payment' => 1,
515 ])['values'];
516 foreach ($entityFinancialTrxns as $entityFinancialTrxn) {
517 $paid += $entityFinancialTrxn['amount'];
518 }
519 }
520 return (float) $paid;
521 }
522
523 /**
524 * Reverse the entity financial transactions associated with the cancelled payment.
525 *
526 * The reversals are linked to the new payemnt.
527 *
528 * @param array $params
529 * @param int $trxnID
530 *
531 * @throws \CiviCRM_API3_Exception
532 */
533 protected static function reverseAllocationsFromPreviousPayment($params, $trxnID) {
534 // Do a direct reversal of any entity_financial_trxn records being cancelled.
535 $entityFinancialTrxns = civicrm_api3('EntityFinancialTrxn', 'get', [
536 'entity_table' => 'civicrm_financial_item',
537 'options' => ['limit' => 0],
538 'financial_trxn_id.id' => $params['cancelled_payment_id'],
539 ])['values'];
540 foreach ($entityFinancialTrxns as $entityFinancialTrxn) {
541 civicrm_api3('EntityFinancialTrxn', 'create', [
542 'entity_table' => 'civicrm_financial_item',
543 'entity_id' => $entityFinancialTrxn['entity_id'],
544 'amount' => -$entityFinancialTrxn['amount'],
545 'financial_trxn_id' => $trxnID,
546 ]);
547 }
548 }
549
550 /**
551 * Create a financial items & return the ID.
552 *
553 * Ideally this will never be called.
554 *
555 * However, I hit a scenario in testing where 'something' had created a pending payment with
556 * no financial items and that would result in a fatal error without handling here. I failed
557 * to replicate & am not investigating via a new test methodology
558 * https://github.com/civicrm/civicrm-core/pull/15706
559 *
560 * After this is in I will do more digging & once I feel confident new instances are not being
561 * created I will add deprecation notices into this function with a view to removing.
562 *
563 * However, I think we want to add it in 5.20 as there is a risk of users experiencing an error
564 * if there is incorrect data & we need time to ensure that what I hit was not a 'thing.
565 * (it might be the demo site data is a bit flawed & that was the issue).
566 *
567 * @param array $lineItem
568 * @param string $trxn_date
569 * @param int $contactID
570 * @param string $currency
571 *
572 * @return int
573 *
574 * @throws \CiviCRM_API3_Exception
575 */
576 protected static function getNewFinancialItemID($lineItem, $trxn_date, $contactID, $currency): int {
577 $financialAccount = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship(
578 $lineItem['financial_type_id'],
579 'Income Account Is'
580 );
581 $itemParams = [
582 'transaction_date' => $trxn_date,
583 'contact_id' => $contactID,
584 'currency' => $currency,
585 'amount' => $lineItem['line_total'],
586 'description' => $lineItem['label'],
587 'status_id' => 'Unpaid',
588 'financial_account_id' => $financialAccount,
589 'entity_table' => 'civicrm_line_item',
590 'entity_id' => $lineItem['id'],
591 ];
592 return (int) civicrm_api3('FinancialItem', 'create', $itemParams)['id'];
593 }
594
595 }