Merge remote-tracking branch 'origin/5.52' into master-552
[civicrm-core.git] / CRM / Core / BAO / FinancialTrxn.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 class CRM_Core_BAO_FinancialTrxn extends CRM_Financial_BAO_FinancialTrxn {
18
19 /**
20 * @param int $contributionId
21 * @param int $contributionFinancialTypeId
22 *
23 * @return array
24 */
25 public static function getBalanceTrxnAmt($contributionId, $contributionFinancialTypeId = NULL) {
26 if (!$contributionFinancialTypeId) {
27 $contributionFinancialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'financial_type_id');
28 }
29 $toFinancialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($contributionFinancialTypeId, 'Accounts Receivable Account is');
30 $q = "SELECT ft.id, ft.total_amount FROM civicrm_financial_trxn ft INNER JOIN civicrm_entity_financial_trxn eft ON (eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution') WHERE eft.entity_id = %1 AND ft.to_financial_account_id = %2";
31
32 $p[1] = [$contributionId, 'Integer'];
33 $p[2] = [$toFinancialAccount, 'Integer'];
34
35 $balanceAmtDAO = CRM_Core_DAO::executeQuery($q, $p);
36 $ret = [];
37 if ($balanceAmtDAO->N) {
38 $ret['total_amount'] = 0;
39 }
40 while ($balanceAmtDAO->fetch()) {
41 $ret['trxn_id'] = $balanceAmtDAO->id;
42 $ret['total_amount'] += $balanceAmtDAO->total_amount;
43 }
44
45 return $ret;
46 }
47
48 /**
49 * Retrieve DB object and copy to defaults array.
50 *
51 * @param array $params
52 * Array of criteria values.
53 * @param array $defaults
54 * Array to be populated with found values.
55 *
56 * @return self|null
57 * The DAO object, if found.
58 *
59 * @deprecated
60 */
61 public static function retrieve($params, &$defaults = []) {
62 return self::commonRetrieve(self::class, $params, $defaults);
63 }
64
65 /**
66 * Given an entity_id and entity_table, check for corresponding entity_financial_trxn and financial_trxn record.
67 * NOTE: This should be moved to separate BAO for EntityFinancialTrxn when we start adding more code for that object.
68 *
69 * @param $entity_id
70 * Id of the entity usually the contributionID.
71 * @param string $orderBy
72 * To get single trxn id for a entity table i.e last or first.
73 * @param bool $newTrxn
74 * @param string $whereClause
75 * Additional where parameters
76 * @param int $fromAccountID
77 *
78 * @return array
79 * array of category id's the contact belongs to.
80 *
81 */
82 public static function getFinancialTrxnId($entity_id, $orderBy = 'ASC', $newTrxn = FALSE, $whereClause = '', $fromAccountID = NULL) {
83 $ids = ['entityFinancialTrxnId' => NULL, 'financialTrxnId' => NULL];
84
85 $params = [1 => [$entity_id, 'Integer']];
86 $condition = "";
87 if (!$newTrxn) {
88 $condition = " AND ((ceft1.entity_table IS NOT NULL) OR (cft.payment_instrument_id IS NOT NULL AND ceft1.entity_table IS NULL)) ";
89 }
90
91 if ($fromAccountID) {
92 $condition .= " AND (cft.from_financial_account_id <> %2 OR cft.from_financial_account_id IS NULL)";
93 $params[2] = [$fromAccountID, 'Integer'];
94 }
95 if ($orderBy) {
96 $orderBy = CRM_Utils_Type::escape($orderBy, 'String');
97 }
98
99 $query = "SELECT ceft.id, ceft.financial_trxn_id, cft.trxn_id FROM `civicrm_financial_trxn` cft
100 LEFT JOIN civicrm_entity_financial_trxn ceft
101 ON ceft.financial_trxn_id = cft.id AND ceft.entity_table = 'civicrm_contribution'
102 LEFT JOIN civicrm_entity_financial_trxn ceft1
103 ON ceft1.financial_trxn_id = cft.id AND ceft1.entity_table = 'civicrm_financial_item'
104 LEFT JOIN civicrm_financial_item cfi ON ceft1.entity_table = 'civicrm_financial_item' and cfi.id = ceft1.entity_id
105 WHERE ceft.entity_id = %1 AND (cfi.entity_table <> 'civicrm_financial_trxn' or cfi.entity_table is NULL)
106 {$condition}
107 {$whereClause}
108 ORDER BY cft.id {$orderBy}
109 LIMIT 1;";
110
111 $dao = CRM_Core_DAO::executeQuery($query, $params);
112 if ($dao->fetch()) {
113 $ids['entityFinancialTrxnId'] = $dao->id;
114 $ids['financialTrxnId'] = $dao->financial_trxn_id;
115 $ids['trxn_id'] = $dao->trxn_id;
116 }
117 return $ids;
118 }
119
120 /**
121 * Get the transaction id for the (latest) refund associated with a contribution.
122 *
123 * @param int $contributionID
124 * @return string
125 */
126 public static function getRefundTransactionTrxnID($contributionID) {
127 $ids = self::getRefundTransactionIDs($contributionID);
128 return $ids['trxn_id'] ?? NULL;
129 }
130
131 /**
132 * Get the transaction id for the (latest) refund associated with a contribution.
133 *
134 * @param int $contributionID
135 * @return array
136 */
137 public static function getRefundTransactionIDs($contributionID) {
138 $refundStatusID = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Refunded');
139 return self::getFinancialTrxnId($contributionID, 'DESC', FALSE, " AND cft.status_id = $refundStatusID");
140 }
141
142 /**
143 * Given an financial_trxn_id check for previous entity_financial_trxn.
144 *
145 * @param $financial_trxn_id
146 * Id of the latest payment.
147 *
148 *
149 * @return array
150 * array of previous payments
151 *
152 */
153 public static function getPayments($financial_trxn_id) {
154 $query = "
155 SELECT ef1.financial_trxn_id, sum(ef1.amount) amount
156 FROM civicrm_entity_financial_trxn ef1
157 LEFT JOIN civicrm_entity_financial_trxn ef2 ON ef1.financial_trxn_id = ef2.entity_id
158 WHERE ef2.financial_trxn_id =%1
159 AND ef2.entity_table = 'civicrm_financial_trxn'
160 AND ef1.entity_table = 'civicrm_financial_item'
161 GROUP BY ef1.financial_trxn_id
162 UNION
163 SELECT ef1.financial_trxn_id, ef1.amount
164 FROM civicrm_entity_financial_trxn ef1
165 LEFT JOIN civicrm_entity_financial_trxn ef2 ON ef1.entity_id = ef2.entity_id
166 WHERE ef2.financial_trxn_id =%1
167 AND ef2.entity_table = 'civicrm_financial_trxn'
168 AND ef1.entity_table = 'civicrm_financial_trxn'";
169
170 $sqlParams = [1 => [$financial_trxn_id, 'Integer']];
171 $dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
172 $i = 0;
173 $result = [];
174 while ($dao->fetch()) {
175 $result[$i]['financial_trxn_id'] = $dao->financial_trxn_id;
176 $result[$i]['amount'] = $dao->amount;
177 $i++;
178 }
179
180 if (empty($result)) {
181 $query = "SELECT sum( amount ) amount FROM civicrm_entity_financial_trxn WHERE financial_trxn_id =%1 AND entity_table = 'civicrm_financial_item'";
182 $sqlParams = [1 => [$financial_trxn_id, 'Integer']];
183 $dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
184
185 if ($dao->fetch()) {
186 $result[0]['financial_trxn_id'] = $financial_trxn_id;
187 $result[0]['amount'] = $dao->amount;
188 }
189 }
190 return $result;
191 }
192
193 /**
194 * Given an entity_id and entity_table, check for corresponding entity_financial_trxn and financial_trxn record.
195 * NOTE: This should be moved to separate BAO for EntityFinancialTrxn when we start adding more code for that object.
196 *
197 * @param $entity_id
198 * Id of the entity usually the contactID.
199 * @param string $entity_table
200 * Name of the entity table usually 'civicrm_contact'.
201 *
202 * @return array
203 * array of category id's the contact belongs to.
204 *
205 */
206 public static function getFinancialTrxnLineTotal($entity_id, $entity_table = 'civicrm_contribution') {
207 $query = "SELECT lt.price_field_value_id AS id, ft.financial_trxn_id,ft.amount AS amount FROM civicrm_entity_financial_trxn AS ft
208 LEFT JOIN civicrm_financial_item AS fi ON fi.id = ft.entity_id AND fi.entity_table = 'civicrm_line_item' AND ft.entity_table = 'civicrm_financial_item'
209 LEFT JOIN civicrm_line_item AS lt ON lt.id = fi.entity_id AND lt.entity_table = %2
210 WHERE lt.entity_id = %1 ";
211
212 $sqlParams = [1 => [$entity_id, 'Integer'], 2 => [$entity_table, 'String']];
213 $dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
214 while ($dao->fetch()) {
215 $result[$dao->financial_trxn_id][$dao->id] = $dao->amount;
216 }
217 if (!empty($result)) {
218 return $result;
219 }
220 else {
221 return NULL;
222 }
223 }
224
225 /**
226 * Delete financial transaction.
227 *
228 * @param int $entity_id
229 * @return bool
230 * TRUE on success, FALSE otherwise.
231 */
232 public static function deleteFinancialTrxn($entity_id) {
233 $query = "DELETE ceft1, cfi, ceft, cft FROM `civicrm_financial_trxn` cft
234 LEFT JOIN civicrm_entity_financial_trxn ceft
235 ON ceft.financial_trxn_id = cft.id AND ceft.entity_table = 'civicrm_contribution'
236 LEFT JOIN civicrm_entity_financial_trxn ceft1
237 ON ceft1.financial_trxn_id = cft.id AND ceft1.entity_table = 'civicrm_financial_item'
238 LEFT JOIN civicrm_financial_item cfi
239 ON ceft1.entity_table = 'civicrm_financial_item' and cfi.id = ceft1.entity_id
240 WHERE ceft.entity_id = %1";
241 CRM_Core_DAO::executeQuery($query, [1 => [$entity_id, 'Integer']]);
242 return TRUE;
243 }
244
245 /**
246 * Create financial transaction for premium.
247 *
248 * @param array $params
249 * - oldPremium
250 * - financial_type_id
251 * - contributionId
252 * - isDeleted
253 * - cost
254 * - currency
255 */
256 public static function createPremiumTrxn($params) {
257 if ((empty($params['financial_type_id']) || empty($params['contributionId'])) && empty($params['oldPremium'])) {
258 return;
259 }
260
261 if (!empty($params['cost'])) {
262 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
263 $toFinancialAccountType = !empty($params['isDeleted']) ? 'Premiums Inventory Account is' : 'Cost of Sales Account is';
264 $fromFinancialAccountType = !empty($params['isDeleted']) ? 'Cost of Sales Account is' : 'Premiums Inventory Account is';
265 $financialtrxn = [
266 'to_financial_account_id' => CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($params['financial_type_id'], $toFinancialAccountType),
267 'from_financial_account_id' => CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($params['financial_type_id'], $fromFinancialAccountType),
268 'trxn_date' => date('YmdHis'),
269 'total_amount' => $params['cost'] ?? 0,
270 'currency' => $params['currency'] ?? NULL,
271 'status_id' => array_search('Completed', $contributionStatuses),
272 'entity_table' => 'civicrm_contribution',
273 'entity_id' => $params['contributionId'],
274 ];
275 CRM_Core_BAO_FinancialTrxn::create($financialtrxn);
276 }
277
278 if (!empty($params['oldPremium'])) {
279 $premiumParams = [
280 'id' => $params['oldPremium']['product_id'],
281 ];
282 $productDetails = [];
283 CRM_Contribute_BAO_Product::retrieve($premiumParams, $productDetails);
284 $params = [
285 'cost' => $productDetails['cost'] ?? NULL,
286 'currency' => $productDetails['currency'] ?? NULL,
287 'financial_type_id' => $productDetails['financial_type_id'] ?? NULL,
288 'contributionId' => $params['oldPremium']['contribution_id'],
289 'isDeleted' => TRUE,
290 ];
291 CRM_Core_BAO_FinancialTrxn::createPremiumTrxn($params);
292 }
293 }
294
295 /**
296 * Create financial trxn and items when fee is charged.
297 *
298 * @param array $params
299 * To create trxn entries.
300 *
301 * @throws \CRM_Core_Exception
302 */
303 public static function recordFees($params) {
304 $amount = 0;
305 if (!empty($params['prevContribution'])) {
306 $amount = $params['prevContribution']->fee_amount;
307 }
308 $amount = $params['fee_amount'] - $amount;
309 if (!$amount) {
310 return;
311 }
312 $contributionId = $params['contribution']->id ?? $params['contribution_id'];
313 if (empty($params['financial_type_id'])) {
314 $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id', 'id');
315 }
316 else {
317 $financialTypeId = $params['financial_type_id'];
318 }
319 $financialAccount = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship($financialTypeId, 'Expense Account is');
320
321 $params['trxnParams']['from_financial_account_id'] = $params['to_financial_account_id'];
322 $params['trxnParams']['to_financial_account_id'] = $financialAccount;
323 $params['trxnParams']['total_amount'] = $amount;
324 $params['trxnParams']['fee_amount'] = $params['trxnParams']['net_amount'] = 0;
325 $params['trxnParams']['status_id'] = $params['contribution_status_id'];
326 $params['trxnParams']['contribution_id'] = $contributionId;
327 $params['trxnParams']['is_payment'] = FALSE;
328 $trxn = self::create($params['trxnParams']);
329 if (empty($params['entity_id'])) {
330 $financialTrxnID = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['trxnParams']['contribution_id'], 'DESC');
331 $params['entity_id'] = $financialTrxnID['financialTrxnId'];
332 }
333 $fItemParams
334 = [
335 'financial_account_id' => $financialAccount,
336 'contact_id' => CRM_Core_BAO_Domain::getDomain()->contact_id,
337 'created_date' => date('YmdHis'),
338 'transaction_date' => $params['trxnParams']['trxn_date'],
339 'amount' => $amount,
340 'description' => 'Fee',
341 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Financial_BAO_FinancialItem', 'status_id', 'Paid'),
342 'entity_table' => 'civicrm_financial_trxn',
343 'entity_id' => $params['entity_id'],
344 'currency' => $params['trxnParams']['currency'],
345 ];
346 $trxnIDS['id'] = $trxn->id;
347 CRM_Financial_BAO_FinancialItem::create($fItemParams, NULL, $trxnIDS);
348 }
349
350 /**
351 * get partial payment amount.
352 *
353 * @deprecated
354 *
355 * This function basically calls CRM_Contribute_BAO_Contribution::getContributionBalance
356 * - just do that. If need be we could have a fn to get the contribution id but
357 * chances are the calling functions already know it anyway.
358 *
359 * @param int $entityId
360 * @param string $entityName
361 * @param int $lineItemTotal
362 *
363 * @return array
364 */
365 public static function getPartialPaymentWithType($entityId, $entityName = 'participant', $lineItemTotal = NULL) {
366 CRM_Core_Error::deprecatedFunctionWarning('CRM_Contribute_BAO_Contribution::getContributionBalance');
367 $value = NULL;
368 if (empty($entityName)) {
369 return $value;
370 }
371
372 // @todo - deprecate passing in entity & type - just figure out contribution id FIRST
373 if ($entityName == 'participant') {
374 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $entityId, 'contribution_id', 'participant_id');
375 }
376 elseif ($entityName == 'membership') {
377 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $entityId, 'contribution_id', 'membership_id');
378 }
379 else {
380 $contributionId = $entityId;
381 }
382 $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
383
384 if ($contributionId && $financialTypeId) {
385
386 $paymentVal = CRM_Contribute_BAO_Contribution::getContributionBalance($contributionId, $lineItemTotal);
387 $value = [];
388 if ($paymentVal < 0) {
389 $value['refund_due'] = $paymentVal;
390 }
391 elseif ($paymentVal > 0) {
392 $value['amount_owed'] = $paymentVal;
393 }
394 }
395 return $value;
396 }
397
398 /**
399 * Get the total sum of all payments (and optionally refunds) for a contribution record
400 *
401 * @param int $contributionID
402 * @param bool $includeRefund
403 *
404 * @return float
405 */
406 public static function getTotalPayments($contributionID, $includeRefund = FALSE): float {
407 $statusIDs = [CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed')];
408
409 if ($includeRefund) {
410 $statusIDs[] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Refunded');
411 }
412
413 $sql = "SELECT SUM(ft.total_amount) FROM civicrm_financial_trxn ft
414 INNER JOIN civicrm_entity_financial_trxn eft ON (eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution')
415 WHERE eft.entity_id = %1 AND ft.is_payment = 1 AND ft.status_id IN (%2) ";
416
417 return (float) CRM_Core_DAO::singleValueQuery($sql, [
418 1 => [$contributionID, 'Integer'],
419 2 => [implode(',', $statusIDs), 'CommaSeparatedIntegers'],
420 ]);
421 }
422
423 /**
424 * Get revenue amount for membership.
425 *
426 * @param array $lineItem
427 *
428 * @return array
429 */
430 public static function getMembershipRevenueAmount($lineItem) {
431 $revenueAmount = [];
432 $membershipDetail = civicrm_api3('Membership', 'getsingle', [
433 'id' => $lineItem['entity_id'],
434 ]);
435 if (empty($membershipDetail['end_date'])) {
436 return $revenueAmount;
437 }
438
439 $startDate = strtotime($membershipDetail['start_date']);
440 $endDate = strtotime($membershipDetail['end_date']);
441 $startYear = date('Y', $startDate);
442 $endYear = date('Y', $endDate);
443 $startMonth = date('m', $startDate);
444 $endMonth = date('m', $endDate);
445
446 $monthOfService = (($endYear - $startYear) * 12) + ($endMonth - $startMonth);
447 $startDateOfRevenue = $membershipDetail['start_date'];
448 $typicalPayment = round(($lineItem['line_total'] / $monthOfService), 2);
449 for ($i = 0; $i <= $monthOfService - 1; $i++) {
450 $revenueAmount[$i]['amount'] = $typicalPayment;
451 if ($i == 0) {
452 $revenueAmount[$i]['amount'] -= (($typicalPayment * $monthOfService) - $lineItem['line_total']);
453 }
454 $revenueAmount[$i]['revenue_date'] = $startDateOfRevenue;
455 $startDateOfRevenue = date('Y-m', strtotime('+1 month', strtotime($startDateOfRevenue))) . '-01';
456 }
457 return $revenueAmount;
458 }
459
460 /**
461 * Create transaction for deferred revenue.
462 *
463 * @param array $lineItems
464 *
465 * @param CRM_Contribute_BAO_Contribution $contributionDetails
466 *
467 * @param bool $update
468 *
469 * @param string $context
470 *
471 */
472 public static function createDeferredTrxn($lineItems, $contributionDetails, $update = FALSE, $context = NULL) {
473 if (empty($lineItems)) {
474 return;
475 }
476 $revenueRecognitionDate = $contributionDetails->revenue_recognition_date;
477 if (!CRM_Utils_System::isNull($revenueRecognitionDate)) {
478 $statuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
479 if (!$update
480 && (CRM_Utils_Array::value($contributionDetails->contribution_status_id, $statuses) != 'Completed'
481 || (CRM_Utils_Array::value($contributionDetails->contribution_status_id, $statuses) != 'Pending'
482 && $contributionDetails->is_pay_later)
483 )
484 ) {
485 return;
486 }
487 $trxnParams = [
488 'contribution_id' => $contributionDetails->id,
489 'fee_amount' => '0.00',
490 'currency' => $contributionDetails->currency,
491 'trxn_id' => $contributionDetails->trxn_id,
492 'status_id' => $contributionDetails->contribution_status_id,
493 'payment_instrument_id' => $contributionDetails->payment_instrument_id,
494 'check_number' => $contributionDetails->check_number,
495 ];
496
497 $deferredRevenues = [];
498 foreach ($lineItems as $priceSetID => $lineItem) {
499 if (!$priceSetID) {
500 continue;
501 }
502 foreach ($lineItem as $key => $item) {
503 $lineTotal = !empty($item['deferred_line_total']) ? $item['deferred_line_total'] : $item['line_total'];
504 if ($lineTotal <= 0 && !$update) {
505 continue;
506 }
507 $deferredRevenues[$key] = $item;
508 if ($context == 'changeFinancialType') {
509 $deferredRevenues[$key]['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_LineItem', $item['id'], 'financial_type_id');
510 }
511 if (in_array($item['entity_table'],
512 ['civicrm_participant', 'civicrm_contribution'])
513 ) {
514 $deferredRevenues[$key]['revenue'][] = [
515 'amount' => $lineTotal,
516 'revenue_date' => $revenueRecognitionDate,
517 ];
518 }
519 else {
520 // for membership
521 $item['line_total'] = $lineTotal;
522 $deferredRevenues[$key]['revenue'] = self::getMembershipRevenueAmount($item);
523 }
524 }
525 }
526 $accountRel = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
527
528 CRM_Utils_Hook::alterDeferredRevenueItems($deferredRevenues, $contributionDetails, $update, $context);
529
530 foreach ($deferredRevenues as $key => $deferredRevenue) {
531 $results = civicrm_api3('EntityFinancialAccount', 'get', [
532 'entity_table' => 'civicrm_financial_type',
533 'entity_id' => $deferredRevenue['financial_type_id'],
534 'account_relationship' => ['IN' => ['Income Account is', 'Deferred Revenue Account is']],
535 ]);
536 if ($results['count'] != 2) {
537 continue;
538 }
539 foreach ($results['values'] as $result) {
540 if ($result['account_relationship'] == $accountRel) {
541 $trxnParams['from_financial_account_id'] = $result['financial_account_id'];
542 }
543 else {
544 $trxnParams['to_financial_account_id'] = $result['financial_account_id'];
545 }
546 }
547 foreach ($deferredRevenue['revenue'] as $revenue) {
548 $trxnParams['total_amount'] = $trxnParams['net_amount'] = $revenue['amount'];
549 $trxnParams['trxn_date'] = CRM_Utils_Date::isoToMysql($revenue['revenue_date']);
550 $financialTxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
551 $entityParams = [
552 'entity_id' => $deferredRevenue['financial_item_id'],
553 'entity_table' => 'civicrm_financial_item',
554 'amount' => $revenue['amount'],
555 'financial_trxn_id' => $financialTxn->id,
556 ];
557 civicrm_api3('EntityFinancialTrxn', 'create', $entityParams);
558 }
559 }
560 }
561 }
562
563 /**
564 * Update Credit Card Details in civicrm_financial_trxn table.
565 *
566 * @param int $contributionID
567 * @param int $panTruncation
568 * @param int $cardType
569 *
570 */
571 public static function updateCreditCardDetails($contributionID, $panTruncation, $cardType) {
572 $financialTrxn = civicrm_api3('EntityFinancialTrxn', 'get', [
573 'return' => ['financial_trxn_id.payment_processor_id', 'financial_trxn_id'],
574 'entity_table' => 'civicrm_contribution',
575 'entity_id' => $contributionID,
576 'financial_trxn_id.is_payment' => TRUE,
577 'options' => ['sort' => 'financial_trxn_id DESC', 'limit' => 1],
578 ]);
579
580 // In case of Contribution status is Pending From Incomplete Transaction or Failed there is no Financial Entries created for Contribution.
581 // Above api will return 0 count, in such case we won't update card type and pan truncation field.
582 if (!$financialTrxn['count']) {
583 return NULL;
584 }
585
586 $financialTrxn = $financialTrxn['values'][$financialTrxn['id']];
587 $paymentProcessorID = $financialTrxn['financial_trxn_id.payment_processor_id'] ?? NULL;
588
589 if ($paymentProcessorID) {
590 return NULL;
591 }
592
593 $financialTrxnId = $financialTrxn['financial_trxn_id'];
594 $trxnparams = ['id' => $financialTrxnId];
595 if (isset($cardType)) {
596 $trxnparams['card_type_id'] = $cardType;
597 }
598 if (isset($panTruncation)) {
599 $trxnparams['pan_truncation'] = $panTruncation;
600 }
601 civicrm_api3('FinancialTrxn', 'create', $trxnparams);
602 }
603
604 /**
605 * The function is responsible for handling financial entries if payment instrument is changed
606 *
607 * @param array $inputParams
608 *
609 */
610 public static function updateFinancialAccountsOnPaymentInstrumentChange($inputParams) {
611 $prevContribution = $inputParams['prevContribution'];
612 $currentContribution = $inputParams['contribution'];
613 // ensure that there are all the information in updated contribution object identified by $currentContribution
614 $currentContribution->find(TRUE);
615
616 $deferredFinancialAccount = $inputParams['deferred_financial_account_id'] ?? NULL;
617 if (empty($deferredFinancialAccount)) {
618 $deferredFinancialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($prevContribution->financial_type_id, 'Deferred Revenue Account is');
619 }
620
621 $lastFinancialTrxnId = self::getFinancialTrxnId($prevContribution->id, 'DESC', FALSE, NULL, $deferredFinancialAccount);
622
623 // there is no point to proceed as we can't find the last payment made
624 // @todo we should throw an exception here rather than return false.
625 if (empty($lastFinancialTrxnId['financialTrxnId'])) {
626 return FALSE;
627 }
628
629 // If payment instrument is changed reverse the last payment
630 // in terms of reversing financial item and trxn
631 $lastFinancialTrxn = civicrm_api3('FinancialTrxn', 'getsingle', ['id' => $lastFinancialTrxnId['financialTrxnId']]);
632 unset($lastFinancialTrxn['id']);
633 $lastFinancialTrxn['trxn_date'] = $inputParams['trxnParams']['trxn_date'];
634 $lastFinancialTrxn['total_amount'] = -$inputParams['trxnParams']['total_amount'];
635 $lastFinancialTrxn['net_amount'] = -$inputParams['trxnParams']['net_amount'];
636 $lastFinancialTrxn['fee_amount'] = -$inputParams['trxnParams']['fee_amount'];
637 $lastFinancialTrxn['contribution_id'] = $prevContribution->id;
638 foreach ([$lastFinancialTrxn, $inputParams['trxnParams']] as $financialTrxnParams) {
639 $trxn = CRM_Core_BAO_FinancialTrxn::create($financialTrxnParams);
640 $trxnParams = [
641 'total_amount' => $trxn->total_amount,
642 'contribution_id' => $currentContribution->id,
643 ];
644 CRM_Contribute_BAO_Contribution::assignProportionalLineItems($trxnParams, $trxn->id, $prevContribution->total_amount);
645 }
646
647 self::createDeferredTrxn(CRM_Utils_Array::value('line_item', $inputParams), $currentContribution, TRUE, 'changePaymentInstrument');
648
649 return TRUE;
650 }
651
652 }