dev/core#2153 #REF Remove outdated updateCustomValues function
[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 */
6a488035 17class CRM_Core_BAO_FinancialTrxn extends CRM_Financial_DAO_FinancialTrxn {
b5c2afd0 18 /**
fe482240 19 * Class constructor.
b5c2afd0 20 *
b5c2afd0
EM
21 * @return \CRM_Financial_DAO_FinancialTrxn
22 */
518fa0ee 23
b5c2afd0 24 /**
b5c2afd0 25 */
00be9182 26 public function __construct() {
6a488035
TO
27 parent::__construct();
28 }
29
30 /**
fe482240 31 * Takes an associative array and creates a financial transaction object.
6a488035 32 *
6a0b768e
TO
33 * @param array $params
34 * (reference ) an assoc array of name/value pairs.
6a488035 35 *
5b541553 36 * @return CRM_Financial_DAO_FinancialTrxn
6a488035 37 */
8a40179e 38 public static function create($params) {
6a488035
TO
39 $trxn = new CRM_Financial_DAO_FinancialTrxn();
40 $trxn->copyValues($params);
4e92d4f4 41
f5269434 42 if (isset($params['fee_amount']) && is_numeric($params['fee_amount'])) {
43 if (!isset($params['total_amount'])) {
44 $trxn->fetch();
45 $params['total_amount'] = $trxn->total_amount;
46 }
47 $trxn->net_amount = $params['total_amount'] - $params['fee_amount'];
48 }
49
8a40179e 50 if (empty($params['id']) && !CRM_Utils_Rule::currencyCode($trxn->currency)) {
4e92d4f4 51 $trxn->currency = CRM_Core_Config::singleton()->defaultCurrency;
6a488035
TO
52 }
53
50f8ceb1 54 $trxn->save();
6a488035 55
3137781d 56 if (!empty($params['id'])) {
8a40179e 57 // For an update entity financial transaction record will already exist. Return early.
50f8ceb1 58 return $trxn;
6a488035
TO
59 }
60
3137781d 61 // Save to entity_financial_trxn table.
be2fb01f 62 $entityFinancialTrxnParams = [
50f8ceb1 63 'entity_table' => CRM_Utils_Array::value('entity_table', $params, 'civicrm_contribution'),
64 'entity_id' => CRM_Utils_Array::value('entity_id', $params, CRM_Utils_Array::value('contribution_id', $params)),
65 'financial_trxn_id' => $trxn->id,
66 'amount' => $params['total_amount'],
be2fb01f 67 ];
50f8ceb1 68
6a488035
TO
69 $entityTrxn = new CRM_Financial_DAO_EntityFinancialTrxn();
70 $entityTrxn->copyValues($entityFinancialTrxnParams);
71 $entityTrxn->save();
72 return $trxn;
73 }
74
b5c2afd0 75 /**
100fef9d
CW
76 * @param int $contributionId
77 * @param int $contributionFinancialTypeId
b5c2afd0
EM
78 *
79 * @return array
80 */
00be9182 81 public static function getBalanceTrxnAmt($contributionId, $contributionFinancialTypeId = NULL) {
29c61b58
PJ
82 if (!$contributionFinancialTypeId) {
83 $contributionFinancialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'financial_type_id');
84 }
876b8ab0 85 $toFinancialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($contributionFinancialTypeId, 'Accounts Receivable Account is');
520ec403 86 $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 87
be2fb01f
CW
88 $p[1] = [$contributionId, 'Integer'];
89 $p[2] = [$toFinancialAccount, 'Integer'];
1010c4e1 90
ede1935f 91 $balanceAmtDAO = CRM_Core_DAO::executeQuery($q, $p);
be2fb01f 92 $ret = [];
18fdfcc3
PN
93 if ($balanceAmtDAO->N) {
94 $ret['total_amount'] = 0;
95 }
22e263ad 96 while ($balanceAmtDAO->fetch()) {
ede1935f 97 $ret['trxn_id'] = $balanceAmtDAO->id;
18fdfcc3 98 $ret['total_amount'] += $balanceAmtDAO->total_amount;
ede1935f
PJ
99 }
100
101 return $ret;
102 }
103
6a488035 104 /**
fe482240 105 * Fetch object based on array of properties.
6a488035 106 *
6a0b768e
TO
107 * @param array $params
108 * (reference ) an assoc array of name/value pairs.
109 * @param array $defaults
110 * (reference ) an assoc array to hold the flattened values.
6a488035 111 *
5b541553 112 * @return \CRM_Financial_DAO_FinancialTrxn
6a488035 113 */
f0da41da 114 public static function retrieve(&$params, &$defaults = []) {
481a74f4 115 $financialItem = new CRM_Financial_DAO_FinancialTrxn();
6a488035 116 $financialItem->copyValues($params);
4eeb9a5b 117 if ($financialItem->find(TRUE)) {
481a74f4 118 CRM_Core_DAO::storeValues($financialItem, $defaults);
6a488035
TO
119 return $financialItem;
120 }
e60f24eb 121 return NULL;
6a488035
TO
122 }
123
124 /**
6a488035
TO
125 * Given an entity_id and entity_table, check for corresponding entity_financial_trxn and financial_trxn record.
126 * NOTE: This should be moved to separate BAO for EntityFinancialTrxn when we start adding more code for that object.
127 *
6a0b768e 128 * @param $entity_id
99cdd94d 129 * Id of the entity usually the contributionID.
6a0b768e
TO
130 * @param string $orderBy
131 * To get single trxn id for a entity table i.e last or first.
dd244018 132 * @param bool $newTrxn
99cdd94d 133 * @param string $whereClause
134 * Additional where parameters
518fa0ee 135 * @param int $fromAccountID
dd244018 136 *
a6c01b45
CW
137 * @return array
138 * array of category id's the contact belongs to.
6a488035 139 *
6a488035 140 */
8cf6bd83 141 public static function getFinancialTrxnId($entity_id, $orderBy = 'ASC', $newTrxn = FALSE, $whereClause = '', $fromAccountID = NULL) {
be2fb01f 142 $ids = ['entityFinancialTrxnId' => NULL, 'financialTrxnId' => NULL];
6a488035 143
be2fb01f 144 $params = [1 => [$entity_id, 'Integer']];
6a488035
TO
145 $condition = "";
146 if (!$newTrxn) {
147 $condition = " AND ((ceft1.entity_table IS NOT NULL) OR (cft.payment_instrument_id IS NOT NULL AND ceft1.entity_table IS NULL)) ";
148 }
21d32567 149
8cf6bd83
PN
150 if ($fromAccountID) {
151 $condition .= " AND (cft.from_financial_account_id <> %2 OR cft.from_financial_account_id IS NULL)";
be2fb01f 152 $params[2] = [$fromAccountID, 'Integer'];
8cf6bd83 153 }
21d32567
DL
154 if ($orderBy) {
155 $orderBy = CRM_Utils_Type::escape($orderBy, 'String');
156 }
157
99cdd94d 158 $query = "SELECT ceft.id, ceft.financial_trxn_id, cft.trxn_id FROM `civicrm_financial_trxn` cft
cbb7c7e0 159LEFT JOIN civicrm_entity_financial_trxn ceft
6a488035
TO
160ON ceft.financial_trxn_id = cft.id AND ceft.entity_table = 'civicrm_contribution'
161LEFT JOIN civicrm_entity_financial_trxn ceft1
162ON ceft1.financial_trxn_id = cft.id AND ceft1.entity_table = 'civicrm_financial_item'
163LEFT JOIN civicrm_financial_item cfi ON ceft1.entity_table = 'civicrm_financial_item' and cfi.id = ceft1.entity_id
164WHERE ceft.entity_id = %1 AND (cfi.entity_table <> 'civicrm_financial_trxn' or cfi.entity_table is NULL)
165{$condition}
99cdd94d 166{$whereClause}
6a488035 167ORDER BY cft.id {$orderBy}
cbb7c7e0 168LIMIT 1;";
169
6a488035
TO
170 $dao = CRM_Core_DAO::executeQuery($query, $params);
171 if ($dao->fetch()) {
172 $ids['entityFinancialTrxnId'] = $dao->id;
173 $ids['financialTrxnId'] = $dao->financial_trxn_id;
99cdd94d 174 $ids['trxn_id'] = $dao->trxn_id;
6a488035
TO
175 }
176 return $ids;
177 }
178
99cdd94d 179 /**
180 * Get the transaction id for the (latest) refund associated with a contribution.
181 *
182 * @param int $contributionID
183 * @return string
184 */
185 public static function getRefundTransactionTrxnID($contributionID) {
186 $ids = self::getRefundTransactionIDs($contributionID);
2e1f50d6 187 return $ids['trxn_id'] ?? NULL;
99cdd94d 188 }
189
190 /**
191 * Get the transaction id for the (latest) refund associated with a contribution.
192 *
193 * @param int $contributionID
81716ddb 194 * @return array
99cdd94d 195 */
196 public static function getRefundTransactionIDs($contributionID) {
197 $refundStatusID = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Refunded');
198 return self::getFinancialTrxnId($contributionID, 'DESC', FALSE, " AND cft.status_id = $refundStatusID");
199 }
200
6a488035
TO
201 /**
202 * Given an entity_id and entity_table, check for corresponding entity_financial_trxn and financial_trxn record.
c490a46a 203 * @todo This should be moved to separate BAO for EntityFinancialTrxn when we start adding more code for that object.
da6b46f4 204 *
6a0b768e
TO
205 * @param int $entity_id
206 * Id of the entity usually the contactID.
6a488035 207 *
a6c01b45 208 * @return array
b44e3f84 209 * array of category id's the contact belongs to.
6a488035 210 *
6a488035 211 */
00be9182 212 public static function getFinancialTrxnTotal($entity_id) {
6a488035
TO
213 $query = "
214 SELECT (ft.amount+SUM(ceft.amount)) AS total FROM civicrm_entity_financial_trxn AS ft
cbb7c7e0 215LEFT JOIN civicrm_entity_financial_trxn AS ceft ON ft.financial_trxn_id = ceft.entity_id
6a488035
TO
216WHERE ft.entity_table = 'civicrm_contribution' AND ft.entity_id = %1
217 ";
218
be2fb01f 219 $sqlParams = [1 => [$entity_id, 'Integer']];
d3e86119 220 return CRM_Core_DAO::singleValueQuery($query, $sqlParams);
6a488035
TO
221
222 }
77b97be7 223
6a488035
TO
224 /**
225 * Given an financial_trxn_id check for previous entity_financial_trxn.
226 *
6a0b768e
TO
227 * @param $financial_trxn_id
228 * Id of the latest payment.
77b97be7 229 *
6a488035 230 *
a6c01b45
CW
231 * @return array
232 * array of previous payments
6a488035 233 *
6a488035 234 */
00be9182 235 public static function getPayments($financial_trxn_id) {
6a488035
TO
236 $query = "
237SELECT ef1.financial_trxn_id, sum(ef1.amount) amount
238FROM civicrm_entity_financial_trxn ef1
239LEFT JOIN civicrm_entity_financial_trxn ef2 ON ef1.financial_trxn_id = ef2.entity_id
240WHERE ef2.financial_trxn_id =%1
241 AND ef2.entity_table = 'civicrm_financial_trxn'
242 AND ef1.entity_table = 'civicrm_financial_item'
243GROUP BY ef1.financial_trxn_id
244UNION
245SELECT ef1.financial_trxn_id, ef1.amount
246FROM civicrm_entity_financial_trxn ef1
247LEFT JOIN civicrm_entity_financial_trxn ef2 ON ef1.entity_id = ef2.entity_id
248WHERE ef2.financial_trxn_id =%1
249 AND ef2.entity_table = 'civicrm_financial_trxn'
250 AND ef1.entity_table = 'civicrm_financial_trxn'";
251
be2fb01f 252 $sqlParams = [1 => [$financial_trxn_id, 'Integer']];
6a488035
TO
253 $dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
254 $i = 0;
be2fb01f 255 $result = [];
6a488035
TO
256 while ($dao->fetch()) {
257 $result[$i]['financial_trxn_id'] = $dao->financial_trxn_id;
258 $result[$i]['amount'] = $dao->amount;
259 $i++;
260 }
261
262 if (empty($result)) {
263 $query = "SELECT sum( amount ) amount FROM civicrm_entity_financial_trxn WHERE financial_trxn_id =%1 AND entity_table = 'civicrm_financial_item'";
be2fb01f 264 $sqlParams = [1 => [$financial_trxn_id, 'Integer']];
6a488035
TO
265 $dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
266
267 if ($dao->fetch()) {
268 $result[0]['financial_trxn_id'] = $financial_trxn_id;
269 $result[0]['amount'] = $dao->amount;
270 }
271 }
272 return $result;
273 }
274
275 /**
276 * Given an entity_id and entity_table, check for corresponding entity_financial_trxn and financial_trxn record.
277 * NOTE: This should be moved to separate BAO for EntityFinancialTrxn when we start adding more code for that object.
278 *
6a0b768e
TO
279 * @param $entity_id
280 * Id of the entity usually the contactID.
281 * @param string $entity_table
282 * Name of the entity table usually 'civicrm_contact'.
6a488035 283 *
a6c01b45 284 * @return array
b44e3f84 285 * array of category id's the contact belongs to.
6a488035 286 *
6a488035 287 */
00be9182 288 public static function getFinancialTrxnLineTotal($entity_id, $entity_table = 'civicrm_contribution') {
6a488035
TO
289 $query = "SELECT lt.price_field_value_id AS id, ft.financial_trxn_id,ft.amount AS amount FROM civicrm_entity_financial_trxn AS ft
290LEFT 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 291LEFT JOIN civicrm_line_item AS lt ON lt.id = fi.entity_id AND lt.entity_table = %2
6a488035
TO
292WHERE lt.entity_id = %1 ";
293
be2fb01f 294 $sqlParams = [1 => [$entity_id, 'Integer'], 2 => [$entity_table, 'String']];
353ffa53 295 $dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
9b873358 296 while ($dao->fetch()) {
6a488035
TO
297 $result[$dao->financial_trxn_id][$dao->id] = $dao->amount;
298 }
299 if (!empty($result)) {
300 return $result;
301 }
302 else {
e60f24eb 303 return NULL;
6a488035
TO
304 }
305 }
306
307 /**
fe482240 308 * Delete financial transaction.
6a488035 309 *
100fef9d 310 * @param int $entity_id
4eeb9a5b 311 * @return bool
ab8a593e 312 * TRUE on success, FALSE otherwise.
6a488035 313 */
00be9182 314 public static function deleteFinancialTrxn($entity_id) {
de1c25e1 315 $query = "DELETE ceft1, cfi, ceft, cft FROM `civicrm_financial_trxn` cft
cbb7c7e0 316LEFT JOIN civicrm_entity_financial_trxn ceft
de1c25e1
PN
317 ON ceft.financial_trxn_id = cft.id AND ceft.entity_table = 'civicrm_contribution'
318LEFT JOIN civicrm_entity_financial_trxn ceft1
319 ON ceft1.financial_trxn_id = cft.id AND ceft1.entity_table = 'civicrm_financial_item'
cbb7c7e0 320LEFT JOIN civicrm_financial_item cfi
de1c25e1
PN
321 ON ceft1.entity_table = 'civicrm_financial_item' and cfi.id = ceft1.entity_id
322WHERE ceft.entity_id = %1";
be2fb01f 323 CRM_Core_DAO::executeQuery($query, [1 => [$entity_id, 'Integer']]);
de1c25e1 324 return TRUE;
6a488035
TO
325 }
326
327 /**
fe482240 328 * Create financial transaction for premium.
6a488035 329 *
dd9db60b
EM
330 * @param array $params
331 * - oldPremium
332 * - financial_type_id
333 * - contributionId
334 * - isDeleted
335 * - cost
336 * - currency
6a488035 337 */
00be9182 338 public static function createPremiumTrxn($params) {
8cc574cf 339 if ((empty($params['financial_type_id']) || empty($params['contributionId'])) && empty($params['oldPremium'])) {
6a488035
TO
340 return;
341 }
cbb7c7e0 342
a7488080 343 if (!empty($params['cost'])) {
6a488035 344 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
876b8ab0
PN
345 $toFinancialAccountType = !empty($params['isDeleted']) ? 'Premiums Inventory Account is' : 'Cost of Sales Account is';
346 $fromFinancialAccountType = !empty($params['isDeleted']) ? 'Cost of Sales Account is' : 'Premiums Inventory Account is';
be2fb01f 347 $financialtrxn = [
876b8ab0
PN
348 'to_financial_account_id' => CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($params['financial_type_id'], $toFinancialAccountType),
349 'from_financial_account_id' => CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($params['financial_type_id'], $fromFinancialAccountType),
6a488035 350 'trxn_date' => date('YmdHis'),
6b409353
CW
351 'total_amount' => $params['cost'] ?? 0,
352 'currency' => $params['currency'] ?? NULL,
21dfd5f5 353 'status_id' => array_search('Completed', $contributionStatuses),
3137781d 354 'entity_table' => 'civicrm_contribution',
50f8ceb1 355 'entity_id' => $params['contributionId'],
be2fb01f 356 ];
50f8ceb1 357 CRM_Core_BAO_FinancialTrxn::create($financialtrxn);
6a488035
TO
358 }
359
a7488080 360 if (!empty($params['oldPremium'])) {
be2fb01f 361 $premiumParams = [
21dfd5f5 362 'id' => $params['oldPremium']['product_id'],
be2fb01f
CW
363 ];
364 $productDetails = [];
37828d4f 365 CRM_Contribute_BAO_Product::retrieve($premiumParams, $productDetails);
be2fb01f 366 $params = [
6b409353
CW
367 'cost' => $productDetails['cost'] ?? NULL,
368 'currency' => $productDetails['currency'] ?? NULL,
369 'financial_type_id' => $productDetails['financial_type_id'] ?? NULL,
6a488035 370 'contributionId' => $params['oldPremium']['contribution_id'],
21dfd5f5 371 'isDeleted' => TRUE,
be2fb01f 372 ];
6a488035
TO
373 CRM_Core_BAO_FinancialTrxn::createPremiumTrxn($params);
374 }
375 }
c490a46a 376
6a488035 377 /**
fe482240 378 * Create financial trxn and items when fee is charged.
6a488035 379 *
6a0b768e
TO
380 * @param array $params
381 * To create trxn entries.
6a488035 382 *
1a459cc2 383 * @throws \CRM_Core_Exception
6a488035 384 */
00be9182 385 public static function recordFees($params) {
6a488035 386 $amount = 0;
a7488080 387 if (!empty($params['prevContribution'])) {
6a488035
TO
388 $amount = $params['prevContribution']->fee_amount;
389 }
390 $amount = $params['fee_amount'] - $amount;
78b79549 391 if (!$amount) {
1a459cc2 392 return;
78b79549 393 }
2e1f50d6 394 $contributionId = $params['contribution']->id ?? $params['contribution_id'];
39383f5f
PJ
395 if (empty($params['financial_type_id'])) {
396 $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id', 'id');
397 }
398 else {
399 $financialTypeId = $params['financial_type_id'];
400 }
928a340b 401 $financialAccount = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship($financialTypeId, 'Expense Account is');
39383f5f 402
6a488035
TO
403 $params['trxnParams']['from_financial_account_id'] = $params['to_financial_account_id'];
404 $params['trxnParams']['to_financial_account_id'] = $financialAccount;
405 $params['trxnParams']['total_amount'] = $amount;
79d7553f 406 $params['trxnParams']['fee_amount'] = $params['trxnParams']['net_amount'] = 0;
76c28c8d 407 $params['trxnParams']['status_id'] = $params['contribution_status_id'];
39383f5f 408 $params['trxnParams']['contribution_id'] = $contributionId;
87647fe2 409 $params['trxnParams']['is_payment'] = FALSE;
6a488035 410 $trxn = self::create($params['trxnParams']);
a7488080 411 if (empty($params['entity_id'])) {
6a488035
TO
412 $financialTrxnID = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['trxnParams']['contribution_id'], 'DESC');
413 $params['entity_id'] = $financialTrxnID['financialTrxnId'];
414 }
79d7553f 415 $fItemParams
be2fb01f 416 = [
6a488035 417 'financial_account_id' => $financialAccount,
d357f225 418 'contact_id' => CRM_Core_BAO_Domain::getDomain()->contact_id,
6a488035 419 'created_date' => date('YmdHis'),
83a30437 420 'transaction_date' => $params['trxnParams']['trxn_date'],
6a488035
TO
421 'amount' => $amount,
422 'description' => 'Fee',
4a413eb6 423 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Financial_BAO_FinancialItem', 'status_id', 'Paid'),
6a488035
TO
424 'entity_table' => 'civicrm_financial_trxn',
425 'entity_id' => $params['entity_id'],
426 'currency' => $params['trxnParams']['currency'],
be2fb01f 427 ];
6a488035 428 $trxnIDS['id'] = $trxn->id;
a28ce73f 429 CRM_Financial_BAO_FinancialItem::create($fItemParams, NULL, $trxnIDS);
6a488035 430 }
6a488035 431
b5c2afd0 432 /**
2fc731d5 433 * get partial payment amount.
434 *
435 * @deprecated
436 *
437 * This function basically calls CRM_Contribute_BAO_Contribution::getContributionBalance
438 * - just do that. If need be we could have a fn to get the contribution id but
439 * chances are the calling functions already know it anyway.
d424ffde 440 *
100fef9d 441 * @param int $entityId
b5c2afd0 442 * @param string $entityName
79d7553f 443 * @param int $lineItemTotal
b5c2afd0 444 *
2fc731d5 445 * @return array
b5c2afd0 446 */
2fc731d5 447 public static function getPartialPaymentWithType($entityId, $entityName = 'participant', $lineItemTotal = NULL) {
a168b222 448 CRM_Core_Error::deprecatedFunctionWarning('CRM_Contribute_BAO_Contribution::getContributionBalance');
0f602e3f
PJ
449 $value = NULL;
450 if (empty($entityName)) {
451 return $value;
452 }
453
a79d2ec2 454 // @todo - deprecate passing in entity & type - just figure out contribution id FIRST
0f602e3f 455 if ($entityName == 'participant') {
bc2eeabb 456 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $entityId, 'contribution_id', 'participant_id');
685dc433 457 }
f6e96aa8 458 elseif ($entityName == 'membership') {
459 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $entityId, 'contribution_id', 'membership_id');
460 }
685dc433
PN
461 else {
462 $contributionId = $entityId;
463 }
464 $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
465
466 if ($contributionId && $financialTypeId) {
685dc433 467
2fc731d5 468 $paymentVal = CRM_Contribute_BAO_Contribution::getContributionBalance($contributionId, $lineItemTotal);
469 $value = [];
470 if ($paymentVal < 0) {
471 $value['refund_due'] = $paymentVal;
472 }
473 elseif ($paymentVal > 0) {
474 $value['amount_owed'] = $paymentVal;
0f602e3f
PJ
475 }
476 }
477 return $value;
478 }
96025800 479
3efd9c58 480 /**
5ab2fd4f
MWMC
481 * Get the total sum of all payments (and optionally refunds) for a contribution record
482 *
89bfb100
MD
483 * @param int $contributionID
484 * @param bool $includeRefund
3efd9c58 485 *
5ab2fd4f 486 * @return float
3efd9c58 487 */
5ab2fd4f 488 public static function getTotalPayments($contributionID, $includeRefund = FALSE): float {
89bfb100
MD
489 $statusIDs = [CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed')];
490
491 if ($includeRefund) {
492 $statusIDs[] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Refunded');
493 }
76c28c8d
DG
494
495 $sql = "SELECT SUM(ft.total_amount) FROM civicrm_financial_trxn ft
496 INNER JOIN civicrm_entity_financial_trxn eft ON (eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution')
89bfb100 497 WHERE eft.entity_id = %1 AND ft.is_payment = 1 AND ft.status_id IN (%2) ";
76c28c8d 498
5ab2fd4f 499 return (float) CRM_Core_DAO::singleValueQuery($sql, [
89bfb100
MD
500 1 => [$contributionID, 'Integer'],
501 2 => [implode(',', $statusIDs), 'CommaSeparatedIntegers'],
502 ]);
3efd9c58
DG
503 }
504
f1eab68f
PN
505 /**
506 * Get revenue amount for membership.
507 *
508 * @param array $lineItem
509 *
510 * @return array
511 */
512 public static function getMembershipRevenueAmount($lineItem) {
be2fb01f
CW
513 $revenueAmount = [];
514 $membershipDetail = civicrm_api3('Membership', 'getsingle', [
f1eab68f 515 'id' => $lineItem['entity_id'],
be2fb01f 516 ]);
f1eab68f
PN
517 if (empty($membershipDetail['end_date'])) {
518 return $revenueAmount;
519 }
520
521 $startDate = strtotime($membershipDetail['start_date']);
522 $endDate = strtotime($membershipDetail['end_date']);
523 $startYear = date('Y', $startDate);
524 $endYear = date('Y', $endDate);
525 $startMonth = date('m', $startDate);
526 $endMonth = date('m', $endDate);
527
528 $monthOfService = (($endYear - $startYear) * 12) + ($endMonth - $startMonth);
529 $startDateOfRevenue = $membershipDetail['start_date'];
530 $typicalPayment = round(($lineItem['line_total'] / $monthOfService), 2);
531 for ($i = 0; $i <= $monthOfService - 1; $i++) {
532 $revenueAmount[$i]['amount'] = $typicalPayment;
533 if ($i == 0) {
534 $revenueAmount[$i]['amount'] -= (($typicalPayment * $monthOfService) - $lineItem['line_total']);
535 }
536 $revenueAmount[$i]['revenue_date'] = $startDateOfRevenue;
537 $startDateOfRevenue = date('Y-m', strtotime('+1 month', strtotime($startDateOfRevenue))) . '-01';
538 }
539 return $revenueAmount;
540 }
541
6419695f
PN
542 /**
543 * Create transaction for deferred revenue.
544 *
545 * @param array $lineItems
546 *
2ea48796 547 * @param CRM_Contribute_BAO_Contribution $contributionDetails
6419695f
PN
548 *
549 * @param bool $update
550 *
551 * @param string $context
552 *
553 */
554 public static function createDeferredTrxn($lineItems, $contributionDetails, $update = FALSE, $context = NULL) {
555 if (empty($lineItems)) {
2ea48796 556 return;
6419695f
PN
557 }
558 $revenueRecognitionDate = $contributionDetails->revenue_recognition_date;
559 if (!CRM_Utils_System::isNull($revenueRecognitionDate)) {
560 $statuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
561 if (!$update
562 && (CRM_Utils_Array::value($contributionDetails->contribution_status_id, $statuses) != 'Completed'
563 || (CRM_Utils_Array::value($contributionDetails->contribution_status_id, $statuses) != 'Pending'
564 && $contributionDetails->is_pay_later)
565 )
566 ) {
567 return;
568 }
be2fb01f 569 $trxnParams = [
6419695f
PN
570 'contribution_id' => $contributionDetails->id,
571 'fee_amount' => '0.00',
572 'currency' => $contributionDetails->currency,
573 'trxn_id' => $contributionDetails->trxn_id,
574 'status_id' => $contributionDetails->contribution_status_id,
575 'payment_instrument_id' => $contributionDetails->payment_instrument_id,
576 'check_number' => $contributionDetails->check_number,
be2fb01f 577 ];
6419695f 578
be2fb01f 579 $deferredRevenues = [];
6419695f
PN
580 foreach ($lineItems as $priceSetID => $lineItem) {
581 if (!$priceSetID) {
582 continue;
583 }
584 foreach ($lineItem as $key => $item) {
8cf6bd83
PN
585 $lineTotal = !empty($item['deferred_line_total']) ? $item['deferred_line_total'] : $item['line_total'];
586 if ($lineTotal <= 0 && !$update) {
6419695f
PN
587 continue;
588 }
589 $deferredRevenues[$key] = $item;
590 if ($context == 'changeFinancialType') {
591 $deferredRevenues[$key]['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_LineItem', $item['id'], 'financial_type_id');
592 }
593 if (in_array($item['entity_table'],
be2fb01f 594 ['civicrm_participant', 'civicrm_contribution'])
6419695f 595 ) {
be2fb01f 596 $deferredRevenues[$key]['revenue'][] = [
8cf6bd83 597 'amount' => $lineTotal,
6419695f 598 'revenue_date' => $revenueRecognitionDate,
be2fb01f 599 ];
6419695f
PN
600 }
601 else {
602 // for membership
8cf6bd83 603 $item['line_total'] = $lineTotal;
6419695f
PN
604 $deferredRevenues[$key]['revenue'] = self::getMembershipRevenueAmount($item);
605 }
606 }
607 }
608 $accountRel = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
7340e501 609
7f35de6b 610 CRM_Utils_Hook::alterDeferredRevenueItems($deferredRevenues, $contributionDetails, $update, $context);
7340e501 611
6419695f 612 foreach ($deferredRevenues as $key => $deferredRevenue) {
be2fb01f 613 $results = civicrm_api3('EntityFinancialAccount', 'get', [
6419695f
PN
614 'entity_table' => 'civicrm_financial_type',
615 'entity_id' => $deferredRevenue['financial_type_id'],
be2fb01f
CW
616 'account_relationship' => ['IN' => ['Income Account is', 'Deferred Revenue Account is']],
617 ]);
6419695f
PN
618 if ($results['count'] != 2) {
619 continue;
620 }
621 foreach ($results['values'] as $result) {
622 if ($result['account_relationship'] == $accountRel) {
f818aed5 623 $trxnParams['from_financial_account_id'] = $result['financial_account_id'];
6419695f
PN
624 }
625 else {
f818aed5 626 $trxnParams['to_financial_account_id'] = $result['financial_account_id'];
6419695f
PN
627 }
628 }
629 foreach ($deferredRevenue['revenue'] as $revenue) {
630 $trxnParams['total_amount'] = $trxnParams['net_amount'] = $revenue['amount'];
631 $trxnParams['trxn_date'] = CRM_Utils_Date::isoToMysql($revenue['revenue_date']);
632 $financialTxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
be2fb01f 633 $entityParams = [
6419695f
PN
634 'entity_id' => $deferredRevenue['financial_item_id'],
635 'entity_table' => 'civicrm_financial_item',
636 'amount' => $revenue['amount'],
637 'financial_trxn_id' => $financialTxn->id,
be2fb01f 638 ];
6419695f
PN
639 civicrm_api3('EntityFinancialTrxn', 'create', $entityParams);
640 }
641 }
642 }
643 }
644
2c4a6dc8
PN
645 /**
646 * Update Credit Card Details in civicrm_financial_trxn table.
647 *
648 * @param int $contributionID
649 * @param int $panTruncation
650 * @param int $cardType
651 *
652 */
653 public static function updateCreditCardDetails($contributionID, $panTruncation, $cardType) {
be2fb01f
CW
654 $financialTrxn = civicrm_api3('EntityFinancialTrxn', 'get', [
655 'return' => ['financial_trxn_id.payment_processor_id', 'financial_trxn_id'],
2c4a6dc8
PN
656 'entity_table' => 'civicrm_contribution',
657 'entity_id' => $contributionID,
658 'financial_trxn_id.is_payment' => TRUE,
be2fb01f
CW
659 'options' => ['sort' => 'financial_trxn_id DESC', 'limit' => 1],
660 ]);
2c4a6dc8 661
1da0f2fe
PN
662 // In case of Contribution status is Pending From Incomplete Transaction or Failed there is no Financial Entries created for Contribution.
663 // Above api will return 0 count, in such case we won't update card type and pan truncation field.
2c4a6dc8
PN
664 if (!$financialTrxn['count']) {
665 return NULL;
666 }
667
668 $financialTrxn = $financialTrxn['values'][$financialTrxn['id']];
9c1bc317 669 $paymentProcessorID = $financialTrxn['financial_trxn_id.payment_processor_id'] ?? NULL;
2c4a6dc8
PN
670
671 if ($paymentProcessorID) {
672 return NULL;
673 }
674
675 $financialTrxnId = $financialTrxn['financial_trxn_id'];
be2fb01f 676 $trxnparams = ['id' => $financialTrxnId];
2c4a6dc8 677 if (isset($cardType)) {
d72b084a 678 $trxnparams['card_type_id'] = $cardType;
2c4a6dc8
PN
679 }
680 if (isset($panTruncation)) {
681 $trxnparams['pan_truncation'] = $panTruncation;
682 }
683 civicrm_api3('FinancialTrxn', 'create', $trxnparams);
684 }
685
5ca657dd 686 /**
687 * The function is responsible for handling financial entries if payment instrument is changed
688 *
689 * @param array $inputParams
690 *
691 */
692 public static function updateFinancialAccountsOnPaymentInstrumentChange($inputParams) {
693 $prevContribution = $inputParams['prevContribution'];
694 $currentContribution = $inputParams['contribution'];
695 // ensure that there are all the information in updated contribution object identified by $currentContribution
696 $currentContribution->find(TRUE);
697
9c1bc317 698 $deferredFinancialAccount = $inputParams['deferred_financial_account_id'] ?? NULL;
5ca657dd 699 if (empty($deferredFinancialAccount)) {
700 $deferredFinancialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($prevContribution->financial_type_id, 'Deferred Revenue Account is');
701 }
702
703 $lastFinancialTrxnId = self::getFinancialTrxnId($prevContribution->id, 'DESC', FALSE, NULL, $deferredFinancialAccount);
704
705 // there is no point to proceed as we can't find the last payment made
b0e806fa 706 // @todo we should throw an exception here rather than return false.
5ca657dd 707 if (empty($lastFinancialTrxnId['financialTrxnId'])) {
708 return FALSE;
709 }
710
711 // If payment instrument is changed reverse the last payment
712 // in terms of reversing financial item and trxn
be2fb01f 713 $lastFinancialTrxn = civicrm_api3('FinancialTrxn', 'getsingle', ['id' => $lastFinancialTrxnId['financialTrxnId']]);
5ca657dd 714 unset($lastFinancialTrxn['id']);
715 $lastFinancialTrxn['trxn_date'] = $inputParams['trxnParams']['trxn_date'];
716 $lastFinancialTrxn['total_amount'] = -$inputParams['trxnParams']['total_amount'];
717 $lastFinancialTrxn['net_amount'] = -$inputParams['trxnParams']['net_amount'];
718 $lastFinancialTrxn['fee_amount'] = -$inputParams['trxnParams']['fee_amount'];
5ca657dd 719 $lastFinancialTrxn['contribution_id'] = $prevContribution->id;
be2fb01f 720 foreach ([$lastFinancialTrxn, $inputParams['trxnParams']] as $financialTrxnParams) {
5ca657dd 721 $trxn = CRM_Core_BAO_FinancialTrxn::create($financialTrxnParams);
be2fb01f 722 $trxnParams = [
5ca657dd 723 'total_amount' => $trxn->total_amount,
724 'contribution_id' => $currentContribution->id,
be2fb01f 725 ];
5ca657dd 726 CRM_Contribute_BAO_Contribution::assignProportionalLineItems($trxnParams, $trxn->id, $prevContribution->total_amount);
727 }
728
729 self::createDeferredTrxn(CRM_Utils_Array::value('line_item', $inputParams), $currentContribution, TRUE, 'changePaymentInstrument');
730
731 return TRUE;
732 }
733
a494d7a3 734 /**
735 * Generate and assign an arbitrary value to a field of a test object.
736 *
737 * Always set is_payment to 1 as this is used for Payment api as well as FinancialTrxn.
738 *
739 * @param string $fieldName
740 * @param array $fieldDef
741 * @param int $counter
742 * The globally-unique ID of the test object.
743 */
744 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
745 if ($fieldName === 'is_payment') {
746 $this->is_payment = 1;
747 }
748 else {
749 parent::assignTestValue($fieldName, $fieldDef, $counter);
750 }
751 }
752
0d8afee2 753}