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