Merge pull request #23895 from colemanw/searchKitManaged
[civicrm-core.git] / CRM / Core / BAO / FinancialTrxn.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035 16 */
ebc12a9d 17class CRM_Core_BAO_FinancialTrxn extends CRM_Financial_BAO_FinancialTrxn {
6a488035 18
b5c2afd0 19 /**
100fef9d
CW
20 * @param int $contributionId
21 * @param int $contributionFinancialTypeId
b5c2afd0
EM
22 *
23 * @return array
24 */
00be9182 25 public static function getBalanceTrxnAmt($contributionId, $contributionFinancialTypeId = NULL) {
29c61b58
PJ
26 if (!$contributionFinancialTypeId) {
27 $contributionFinancialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'financial_type_id');
28 }
876b8ab0 29 $toFinancialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($contributionFinancialTypeId, 'Accounts Receivable Account is');
520ec403 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";
1010c4e1 31
be2fb01f
CW
32 $p[1] = [$contributionId, 'Integer'];
33 $p[2] = [$toFinancialAccount, 'Integer'];
1010c4e1 34
ede1935f 35 $balanceAmtDAO = CRM_Core_DAO::executeQuery($q, $p);
be2fb01f 36 $ret = [];
18fdfcc3
PN
37 if ($balanceAmtDAO->N) {
38 $ret['total_amount'] = 0;
39 }
22e263ad 40 while ($balanceAmtDAO->fetch()) {
ede1935f 41 $ret['trxn_id'] = $balanceAmtDAO->id;
18fdfcc3 42 $ret['total_amount'] += $balanceAmtDAO->total_amount;
ede1935f
PJ
43 }
44
45 return $ret;
46 }
47
6a488035 48 /**
4f940304 49 * Retrieve DB object and copy to defaults array.
6a488035 50 *
6a0b768e 51 * @param array $params
4f940304 52 * Array of criteria values.
6a0b768e 53 * @param array $defaults
4f940304
CW
54 * Array to be populated with found values.
55 *
56 * @return self|null
57 * The DAO object, if found.
6a488035 58 *
4f940304 59 * @deprecated
6a488035 60 */
4f940304
CW
61 public static function retrieve($params, &$defaults = []) {
62 return self::commonRetrieve(self::class, $params, $defaults);
6a488035
TO
63 }
64
65 /**
6a488035
TO
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 *
6a0b768e 69 * @param $entity_id
99cdd94d 70 * Id of the entity usually the contributionID.
6a0b768e
TO
71 * @param string $orderBy
72 * To get single trxn id for a entity table i.e last or first.
dd244018 73 * @param bool $newTrxn
99cdd94d 74 * @param string $whereClause
75 * Additional where parameters
518fa0ee 76 * @param int $fromAccountID
dd244018 77 *
a6c01b45
CW
78 * @return array
79 * array of category id's the contact belongs to.
6a488035 80 *
6a488035 81 */
8cf6bd83 82 public static function getFinancialTrxnId($entity_id, $orderBy = 'ASC', $newTrxn = FALSE, $whereClause = '', $fromAccountID = NULL) {
be2fb01f 83 $ids = ['entityFinancialTrxnId' => NULL, 'financialTrxnId' => NULL];
6a488035 84
be2fb01f 85 $params = [1 => [$entity_id, 'Integer']];
6a488035
TO
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 }
21d32567 90
8cf6bd83
PN
91 if ($fromAccountID) {
92 $condition .= " AND (cft.from_financial_account_id <> %2 OR cft.from_financial_account_id IS NULL)";
be2fb01f 93 $params[2] = [$fromAccountID, 'Integer'];
8cf6bd83 94 }
21d32567
DL
95 if ($orderBy) {
96 $orderBy = CRM_Utils_Type::escape($orderBy, 'String');
97 }
98
99cdd94d 99 $query = "SELECT ceft.id, ceft.financial_trxn_id, cft.trxn_id FROM `civicrm_financial_trxn` cft
cbb7c7e0 100LEFT JOIN civicrm_entity_financial_trxn ceft
6a488035
TO
101ON ceft.financial_trxn_id = cft.id AND ceft.entity_table = 'civicrm_contribution'
102LEFT JOIN civicrm_entity_financial_trxn ceft1
103ON ceft1.financial_trxn_id = cft.id AND ceft1.entity_table = 'civicrm_financial_item'
104LEFT JOIN civicrm_financial_item cfi ON ceft1.entity_table = 'civicrm_financial_item' and cfi.id = ceft1.entity_id
105WHERE ceft.entity_id = %1 AND (cfi.entity_table <> 'civicrm_financial_trxn' or cfi.entity_table is NULL)
106{$condition}
99cdd94d 107{$whereClause}
6a488035 108ORDER BY cft.id {$orderBy}
cbb7c7e0 109LIMIT 1;";
110
6a488035
TO
111 $dao = CRM_Core_DAO::executeQuery($query, $params);
112 if ($dao->fetch()) {
113 $ids['entityFinancialTrxnId'] = $dao->id;
114 $ids['financialTrxnId'] = $dao->financial_trxn_id;
99cdd94d 115 $ids['trxn_id'] = $dao->trxn_id;
6a488035
TO
116 }
117 return $ids;
118 }
119
99cdd94d 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);
2e1f50d6 128 return $ids['trxn_id'] ?? NULL;
99cdd94d 129 }
130
131 /**
132 * Get the transaction id for the (latest) refund associated with a contribution.
133 *
134 * @param int $contributionID
81716ddb 135 * @return array
99cdd94d 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
6a488035
TO
142 /**
143 * Given an financial_trxn_id check for previous entity_financial_trxn.
144 *
6a0b768e
TO
145 * @param $financial_trxn_id
146 * Id of the latest payment.
77b97be7 147 *
6a488035 148 *
a6c01b45
CW
149 * @return array
150 * array of previous payments
6a488035 151 *
6a488035 152 */
00be9182 153 public static function getPayments($financial_trxn_id) {
6a488035
TO
154 $query = "
155SELECT ef1.financial_trxn_id, sum(ef1.amount) amount
156FROM civicrm_entity_financial_trxn ef1
157LEFT JOIN civicrm_entity_financial_trxn ef2 ON ef1.financial_trxn_id = ef2.entity_id
158WHERE ef2.financial_trxn_id =%1
159 AND ef2.entity_table = 'civicrm_financial_trxn'
160 AND ef1.entity_table = 'civicrm_financial_item'
161GROUP BY ef1.financial_trxn_id
162UNION
163SELECT ef1.financial_trxn_id, ef1.amount
164FROM civicrm_entity_financial_trxn ef1
165LEFT JOIN civicrm_entity_financial_trxn ef2 ON ef1.entity_id = ef2.entity_id
166WHERE ef2.financial_trxn_id =%1
167 AND ef2.entity_table = 'civicrm_financial_trxn'
168 AND ef1.entity_table = 'civicrm_financial_trxn'";
169
be2fb01f 170 $sqlParams = [1 => [$financial_trxn_id, 'Integer']];
6a488035
TO
171 $dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
172 $i = 0;
be2fb01f 173 $result = [];
6a488035
TO
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'";
be2fb01f 182 $sqlParams = [1 => [$financial_trxn_id, 'Integer']];
6a488035
TO
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 *
6a0b768e
TO
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'.
6a488035 201 *
a6c01b45 202 * @return array
b44e3f84 203 * array of category id's the contact belongs to.
6a488035 204 *
6a488035 205 */
00be9182 206 public static function getFinancialTrxnLineTotal($entity_id, $entity_table = 'civicrm_contribution') {
6a488035
TO
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
208LEFT 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'
cbb7c7e0 209LEFT JOIN civicrm_line_item AS lt ON lt.id = fi.entity_id AND lt.entity_table = %2
6a488035
TO
210WHERE lt.entity_id = %1 ";
211
be2fb01f 212 $sqlParams = [1 => [$entity_id, 'Integer'], 2 => [$entity_table, 'String']];
353ffa53 213 $dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
9b873358 214 while ($dao->fetch()) {
6a488035
TO
215 $result[$dao->financial_trxn_id][$dao->id] = $dao->amount;
216 }
217 if (!empty($result)) {
218 return $result;
219 }
220 else {
e60f24eb 221 return NULL;
6a488035
TO
222 }
223 }
224
225 /**
fe482240 226 * Delete financial transaction.
6a488035 227 *
100fef9d 228 * @param int $entity_id
4eeb9a5b 229 * @return bool
ab8a593e 230 * TRUE on success, FALSE otherwise.
6a488035 231 */
00be9182 232 public static function deleteFinancialTrxn($entity_id) {
de1c25e1 233 $query = "DELETE ceft1, cfi, ceft, cft FROM `civicrm_financial_trxn` cft
cbb7c7e0 234LEFT JOIN civicrm_entity_financial_trxn ceft
de1c25e1
PN
235 ON ceft.financial_trxn_id = cft.id AND ceft.entity_table = 'civicrm_contribution'
236LEFT JOIN civicrm_entity_financial_trxn ceft1
237 ON ceft1.financial_trxn_id = cft.id AND ceft1.entity_table = 'civicrm_financial_item'
cbb7c7e0 238LEFT JOIN civicrm_financial_item cfi
de1c25e1
PN
239 ON ceft1.entity_table = 'civicrm_financial_item' and cfi.id = ceft1.entity_id
240WHERE ceft.entity_id = %1";
be2fb01f 241 CRM_Core_DAO::executeQuery($query, [1 => [$entity_id, 'Integer']]);
de1c25e1 242 return TRUE;
6a488035
TO
243 }
244
245 /**
fe482240 246 * Create financial transaction for premium.
6a488035 247 *
dd9db60b
EM
248 * @param array $params
249 * - oldPremium
250 * - financial_type_id
251 * - contributionId
252 * - isDeleted
253 * - cost
254 * - currency
6a488035 255 */
00be9182 256 public static function createPremiumTrxn($params) {
8cc574cf 257 if ((empty($params['financial_type_id']) || empty($params['contributionId'])) && empty($params['oldPremium'])) {
6a488035
TO
258 return;
259 }
cbb7c7e0 260
a7488080 261 if (!empty($params['cost'])) {
6a488035 262 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
876b8ab0
PN
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';
be2fb01f 265 $financialtrxn = [
876b8ab0
PN
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),
6a488035 268 'trxn_date' => date('YmdHis'),
6b409353
CW
269 'total_amount' => $params['cost'] ?? 0,
270 'currency' => $params['currency'] ?? NULL,
21dfd5f5 271 'status_id' => array_search('Completed', $contributionStatuses),
3137781d 272 'entity_table' => 'civicrm_contribution',
50f8ceb1 273 'entity_id' => $params['contributionId'],
be2fb01f 274 ];
50f8ceb1 275 CRM_Core_BAO_FinancialTrxn::create($financialtrxn);
6a488035
TO
276 }
277
a7488080 278 if (!empty($params['oldPremium'])) {
be2fb01f 279 $premiumParams = [
21dfd5f5 280 'id' => $params['oldPremium']['product_id'],
be2fb01f
CW
281 ];
282 $productDetails = [];
37828d4f 283 CRM_Contribute_BAO_Product::retrieve($premiumParams, $productDetails);
be2fb01f 284 $params = [
6b409353
CW
285 'cost' => $productDetails['cost'] ?? NULL,
286 'currency' => $productDetails['currency'] ?? NULL,
287 'financial_type_id' => $productDetails['financial_type_id'] ?? NULL,
6a488035 288 'contributionId' => $params['oldPremium']['contribution_id'],
21dfd5f5 289 'isDeleted' => TRUE,
be2fb01f 290 ];
6a488035
TO
291 CRM_Core_BAO_FinancialTrxn::createPremiumTrxn($params);
292 }
293 }
c490a46a 294
6a488035 295 /**
fe482240 296 * Create financial trxn and items when fee is charged.
6a488035 297 *
6a0b768e
TO
298 * @param array $params
299 * To create trxn entries.
6a488035 300 *
1a459cc2 301 * @throws \CRM_Core_Exception
6a488035 302 */
00be9182 303 public static function recordFees($params) {
6a488035 304 $amount = 0;
a7488080 305 if (!empty($params['prevContribution'])) {
6a488035
TO
306 $amount = $params['prevContribution']->fee_amount;
307 }
308 $amount = $params['fee_amount'] - $amount;
78b79549 309 if (!$amount) {
1a459cc2 310 return;
78b79549 311 }
2e1f50d6 312 $contributionId = $params['contribution']->id ?? $params['contribution_id'];
39383f5f
PJ
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 }
928a340b 319 $financialAccount = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship($financialTypeId, 'Expense Account is');
39383f5f 320
6a488035
TO
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;
79d7553f 324 $params['trxnParams']['fee_amount'] = $params['trxnParams']['net_amount'] = 0;
76c28c8d 325 $params['trxnParams']['status_id'] = $params['contribution_status_id'];
39383f5f 326 $params['trxnParams']['contribution_id'] = $contributionId;
87647fe2 327 $params['trxnParams']['is_payment'] = FALSE;
6a488035 328 $trxn = self::create($params['trxnParams']);
a7488080 329 if (empty($params['entity_id'])) {
6a488035
TO
330 $financialTrxnID = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['trxnParams']['contribution_id'], 'DESC');
331 $params['entity_id'] = $financialTrxnID['financialTrxnId'];
332 }
79d7553f 333 $fItemParams
be2fb01f 334 = [
6a488035 335 'financial_account_id' => $financialAccount,
d357f225 336 'contact_id' => CRM_Core_BAO_Domain::getDomain()->contact_id,
6a488035 337 'created_date' => date('YmdHis'),
83a30437 338 'transaction_date' => $params['trxnParams']['trxn_date'],
6a488035
TO
339 'amount' => $amount,
340 'description' => 'Fee',
4a413eb6 341 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Financial_BAO_FinancialItem', 'status_id', 'Paid'),
6a488035
TO
342 'entity_table' => 'civicrm_financial_trxn',
343 'entity_id' => $params['entity_id'],
344 'currency' => $params['trxnParams']['currency'],
be2fb01f 345 ];
6a488035 346 $trxnIDS['id'] = $trxn->id;
a28ce73f 347 CRM_Financial_BAO_FinancialItem::create($fItemParams, NULL, $trxnIDS);
6a488035 348 }
6a488035 349
b5c2afd0 350 /**
2fc731d5 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.
d424ffde 358 *
100fef9d 359 * @param int $entityId
b5c2afd0 360 * @param string $entityName
79d7553f 361 * @param int $lineItemTotal
b5c2afd0 362 *
2fc731d5 363 * @return array
b5c2afd0 364 */
2fc731d5 365 public static function getPartialPaymentWithType($entityId, $entityName = 'participant', $lineItemTotal = NULL) {
a168b222 366 CRM_Core_Error::deprecatedFunctionWarning('CRM_Contribute_BAO_Contribution::getContributionBalance');
0f602e3f
PJ
367 $value = NULL;
368 if (empty($entityName)) {
369 return $value;
370 }
371
a79d2ec2 372 // @todo - deprecate passing in entity & type - just figure out contribution id FIRST
0f602e3f 373 if ($entityName == 'participant') {
bc2eeabb 374 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $entityId, 'contribution_id', 'participant_id');
685dc433 375 }
f6e96aa8 376 elseif ($entityName == 'membership') {
377 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $entityId, 'contribution_id', 'membership_id');
378 }
685dc433
PN
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) {
685dc433 385
2fc731d5 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;
0f602e3f
PJ
393 }
394 }
395 return $value;
396 }
96025800 397
3efd9c58 398 /**
5ab2fd4f
MWMC
399 * Get the total sum of all payments (and optionally refunds) for a contribution record
400 *
89bfb100
MD
401 * @param int $contributionID
402 * @param bool $includeRefund
3efd9c58 403 *
5ab2fd4f 404 * @return float
3efd9c58 405 */
5ab2fd4f 406 public static function getTotalPayments($contributionID, $includeRefund = FALSE): float {
89bfb100
MD
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 }
76c28c8d
DG
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')
89bfb100 415 WHERE eft.entity_id = %1 AND ft.is_payment = 1 AND ft.status_id IN (%2) ";
76c28c8d 416
5ab2fd4f 417 return (float) CRM_Core_DAO::singleValueQuery($sql, [
89bfb100
MD
418 1 => [$contributionID, 'Integer'],
419 2 => [implode(',', $statusIDs), 'CommaSeparatedIntegers'],
420 ]);
3efd9c58
DG
421 }
422
f1eab68f
PN
423 /**
424 * Get revenue amount for membership.
425 *
426 * @param array $lineItem
427 *
428 * @return array
429 */
430 public static function getMembershipRevenueAmount($lineItem) {
be2fb01f
CW
431 $revenueAmount = [];
432 $membershipDetail = civicrm_api3('Membership', 'getsingle', [
f1eab68f 433 'id' => $lineItem['entity_id'],
be2fb01f 434 ]);
f1eab68f
PN
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
6419695f
PN
460 /**
461 * Create transaction for deferred revenue.
462 *
463 * @param array $lineItems
464 *
2ea48796 465 * @param CRM_Contribute_BAO_Contribution $contributionDetails
6419695f
PN
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)) {
2ea48796 474 return;
6419695f
PN
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 }
be2fb01f 487 $trxnParams = [
6419695f
PN
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,
be2fb01f 495 ];
6419695f 496
be2fb01f 497 $deferredRevenues = [];
6419695f
PN
498 foreach ($lineItems as $priceSetID => $lineItem) {
499 if (!$priceSetID) {
500 continue;
501 }
502 foreach ($lineItem as $key => $item) {
8cf6bd83
PN
503 $lineTotal = !empty($item['deferred_line_total']) ? $item['deferred_line_total'] : $item['line_total'];
504 if ($lineTotal <= 0 && !$update) {
6419695f
PN
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'],
be2fb01f 512 ['civicrm_participant', 'civicrm_contribution'])
6419695f 513 ) {
be2fb01f 514 $deferredRevenues[$key]['revenue'][] = [
8cf6bd83 515 'amount' => $lineTotal,
6419695f 516 'revenue_date' => $revenueRecognitionDate,
be2fb01f 517 ];
6419695f
PN
518 }
519 else {
520 // for membership
8cf6bd83 521 $item['line_total'] = $lineTotal;
6419695f
PN
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' "));
7340e501 527
7f35de6b 528 CRM_Utils_Hook::alterDeferredRevenueItems($deferredRevenues, $contributionDetails, $update, $context);
7340e501 529
6419695f 530 foreach ($deferredRevenues as $key => $deferredRevenue) {
be2fb01f 531 $results = civicrm_api3('EntityFinancialAccount', 'get', [
6419695f
PN
532 'entity_table' => 'civicrm_financial_type',
533 'entity_id' => $deferredRevenue['financial_type_id'],
be2fb01f
CW
534 'account_relationship' => ['IN' => ['Income Account is', 'Deferred Revenue Account is']],
535 ]);
6419695f
PN
536 if ($results['count'] != 2) {
537 continue;
538 }
539 foreach ($results['values'] as $result) {
540 if ($result['account_relationship'] == $accountRel) {
f818aed5 541 $trxnParams['from_financial_account_id'] = $result['financial_account_id'];
6419695f
PN
542 }
543 else {
f818aed5 544 $trxnParams['to_financial_account_id'] = $result['financial_account_id'];
6419695f
PN
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);
be2fb01f 551 $entityParams = [
6419695f
PN
552 'entity_id' => $deferredRevenue['financial_item_id'],
553 'entity_table' => 'civicrm_financial_item',
554 'amount' => $revenue['amount'],
555 'financial_trxn_id' => $financialTxn->id,
be2fb01f 556 ];
6419695f
PN
557 civicrm_api3('EntityFinancialTrxn', 'create', $entityParams);
558 }
559 }
560 }
561 }
562
2c4a6dc8
PN
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) {
be2fb01f
CW
572 $financialTrxn = civicrm_api3('EntityFinancialTrxn', 'get', [
573 'return' => ['financial_trxn_id.payment_processor_id', 'financial_trxn_id'],
2c4a6dc8
PN
574 'entity_table' => 'civicrm_contribution',
575 'entity_id' => $contributionID,
576 'financial_trxn_id.is_payment' => TRUE,
be2fb01f
CW
577 'options' => ['sort' => 'financial_trxn_id DESC', 'limit' => 1],
578 ]);
2c4a6dc8 579
1da0f2fe
PN
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.
2c4a6dc8
PN
582 if (!$financialTrxn['count']) {
583 return NULL;
584 }
585
586 $financialTrxn = $financialTrxn['values'][$financialTrxn['id']];
9c1bc317 587 $paymentProcessorID = $financialTrxn['financial_trxn_id.payment_processor_id'] ?? NULL;
2c4a6dc8
PN
588
589 if ($paymentProcessorID) {
590 return NULL;
591 }
592
593 $financialTrxnId = $financialTrxn['financial_trxn_id'];
be2fb01f 594 $trxnparams = ['id' => $financialTrxnId];
2c4a6dc8 595 if (isset($cardType)) {
d72b084a 596 $trxnparams['card_type_id'] = $cardType;
2c4a6dc8
PN
597 }
598 if (isset($panTruncation)) {
599 $trxnparams['pan_truncation'] = $panTruncation;
600 }
601 civicrm_api3('FinancialTrxn', 'create', $trxnparams);
602 }
603
5ca657dd 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
9c1bc317 616 $deferredFinancialAccount = $inputParams['deferred_financial_account_id'] ?? NULL;
5ca657dd 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
b0e806fa 624 // @todo we should throw an exception here rather than return false.
5ca657dd 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
be2fb01f 631 $lastFinancialTrxn = civicrm_api3('FinancialTrxn', 'getsingle', ['id' => $lastFinancialTrxnId['financialTrxnId']]);
5ca657dd 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'];
5ca657dd 637 $lastFinancialTrxn['contribution_id'] = $prevContribution->id;
be2fb01f 638 foreach ([$lastFinancialTrxn, $inputParams['trxnParams']] as $financialTrxnParams) {
5ca657dd 639 $trxn = CRM_Core_BAO_FinancialTrxn::create($financialTrxnParams);
be2fb01f 640 $trxnParams = [
5ca657dd 641 'total_amount' => $trxn->total_amount,
642 'contribution_id' => $currentContribution->id,
be2fb01f 643 ];
5ca657dd 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
0d8afee2 652}