3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
33 class CRM_Core_BAO_FinancialTrxn
extends CRM_Financial_DAO_FinancialTrxn
{
37 * @return \CRM_Financial_DAO_FinancialTrxn
42 public function __construct() {
43 parent
::__construct();
47 * Takes an associative array and creates a financial transaction object.
49 * @param array $params
50 * (reference ) an assoc array of name/value pairs.
52 * @return CRM_Financial_DAO_FinancialTrxn
54 public static function create($params) {
55 $trxn = new CRM_Financial_DAO_FinancialTrxn();
56 $trxn->copyValues($params);
58 if (empty($params['id']) && !CRM_Utils_Rule
::currencyCode($trxn->currency
)) {
59 $trxn->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
64 if (!empty($params['id'])) {
65 // For an update entity financial transaction record will already exist. Return early.
69 // Save to entity_financial_trxn table.
70 $entityFinancialTrxnParams = [
71 'entity_table' => CRM_Utils_Array
::value('entity_table', $params, 'civicrm_contribution'),
72 'entity_id' => CRM_Utils_Array
::value('entity_id', $params, CRM_Utils_Array
::value('contribution_id', $params)),
73 'financial_trxn_id' => $trxn->id
,
74 'amount' => $params['total_amount'],
77 $entityTrxn = new CRM_Financial_DAO_EntityFinancialTrxn();
78 $entityTrxn->copyValues($entityFinancialTrxnParams);
84 * @param int $contributionId
85 * @param int $contributionFinancialTypeId
89 public static function getBalanceTrxnAmt($contributionId, $contributionFinancialTypeId = NULL) {
90 if (!$contributionFinancialTypeId) {
91 $contributionFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'financial_type_id');
93 $toFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($contributionFinancialTypeId, 'Accounts Receivable Account is');
94 $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";
96 $p[1] = [$contributionId, 'Integer'];
97 $p[2] = [$toFinancialAccount, 'Integer'];
99 $balanceAmtDAO = CRM_Core_DAO
::executeQuery($q, $p);
101 if ($balanceAmtDAO->N
) {
102 $ret['total_amount'] = 0;
104 while ($balanceAmtDAO->fetch()) {
105 $ret['trxn_id'] = $balanceAmtDAO->id
;
106 $ret['total_amount'] +
= $balanceAmtDAO->total_amount
;
113 * Fetch object based on array of properties.
115 * @param array $params
116 * (reference ) an assoc array of name/value pairs.
117 * @param array $defaults
118 * (reference ) an assoc array to hold the flattened values.
120 * @return \CRM_Financial_DAO_FinancialTrxn
122 public static function retrieve(&$params, &$defaults = []) {
123 $financialItem = new CRM_Financial_DAO_FinancialTrxn();
124 $financialItem->copyValues($params);
125 if ($financialItem->find(TRUE)) {
126 CRM_Core_DAO
::storeValues($financialItem, $defaults);
127 return $financialItem;
133 * Given an entity_id and entity_table, check for corresponding entity_financial_trxn and financial_trxn record.
134 * NOTE: This should be moved to separate BAO for EntityFinancialTrxn when we start adding more code for that object.
137 * Id of the entity usually the contributionID.
138 * @param string $orderBy
139 * To get single trxn id for a entity table i.e last or first.
140 * @param bool $newTrxn
141 * @param string $whereClause
142 * Additional where parameters
143 * @param int $fromAccountID
146 * array of category id's the contact belongs to.
149 public static function getFinancialTrxnId($entity_id, $orderBy = 'ASC', $newTrxn = FALSE, $whereClause = '', $fromAccountID = NULL) {
150 $ids = ['entityFinancialTrxnId' => NULL, 'financialTrxnId' => NULL];
152 $params = [1 => [$entity_id, 'Integer']];
155 $condition = " AND ((ceft1.entity_table IS NOT NULL) OR (cft.payment_instrument_id IS NOT NULL AND ceft1.entity_table IS NULL)) ";
158 if ($fromAccountID) {
159 $condition .= " AND (cft.from_financial_account_id <> %2 OR cft.from_financial_account_id IS NULL)";
160 $params[2] = [$fromAccountID, 'Integer'];
163 $orderBy = CRM_Utils_Type
::escape($orderBy, 'String');
166 $query = "SELECT ceft.id, ceft.financial_trxn_id, cft.trxn_id FROM `civicrm_financial_trxn` cft
167 LEFT JOIN civicrm_entity_financial_trxn ceft
168 ON ceft.financial_trxn_id = cft.id AND ceft.entity_table = 'civicrm_contribution'
169 LEFT JOIN civicrm_entity_financial_trxn ceft1
170 ON ceft1.financial_trxn_id = cft.id AND ceft1.entity_table = 'civicrm_financial_item'
171 LEFT JOIN civicrm_financial_item cfi ON ceft1.entity_table = 'civicrm_financial_item' and cfi.id = ceft1.entity_id
172 WHERE ceft.entity_id = %1 AND (cfi.entity_table <> 'civicrm_financial_trxn' or cfi.entity_table is NULL)
175 ORDER BY cft.id {$orderBy}
178 $dao = CRM_Core_DAO
::executeQuery($query, $params);
180 $ids['entityFinancialTrxnId'] = $dao->id
;
181 $ids['financialTrxnId'] = $dao->financial_trxn_id
;
182 $ids['trxn_id'] = $dao->trxn_id
;
188 * Get the transaction id for the (latest) refund associated with a contribution.
190 * @param int $contributionID
193 public static function getRefundTransactionTrxnID($contributionID) {
194 $ids = self
::getRefundTransactionIDs($contributionID);
195 return isset($ids['trxn_id']) ?
$ids['trxn_id'] : NULL;
199 * Get the transaction id for the (latest) refund associated with a contribution.
201 * @param int $contributionID
204 public static function getRefundTransactionIDs($contributionID) {
205 $refundStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Refunded');
206 return self
::getFinancialTrxnId($contributionID, 'DESC', FALSE, " AND cft.status_id = $refundStatusID");
210 * Given an entity_id and entity_table, check for corresponding entity_financial_trxn and financial_trxn record.
211 * @todo This should be moved to separate BAO for EntityFinancialTrxn when we start adding more code for that object.
213 * @param int $entity_id
214 * Id of the entity usually the contactID.
217 * array of category id's the contact belongs to.
220 public static function getFinancialTrxnTotal($entity_id) {
222 SELECT (ft.amount+SUM(ceft.amount)) AS total FROM civicrm_entity_financial_trxn AS ft
223 LEFT JOIN civicrm_entity_financial_trxn AS ceft ON ft.financial_trxn_id = ceft.entity_id
224 WHERE ft.entity_table = 'civicrm_contribution' AND ft.entity_id = %1
227 $sqlParams = [1 => [$entity_id, 'Integer']];
228 return CRM_Core_DAO
::singleValueQuery($query, $sqlParams);
233 * Given an financial_trxn_id check for previous entity_financial_trxn.
235 * @param $financial_trxn_id
236 * Id of the latest payment.
240 * array of previous payments
243 public static function getPayments($financial_trxn_id) {
245 SELECT ef1.financial_trxn_id, sum(ef1.amount) amount
246 FROM civicrm_entity_financial_trxn ef1
247 LEFT JOIN civicrm_entity_financial_trxn ef2 ON ef1.financial_trxn_id = ef2.entity_id
248 WHERE ef2.financial_trxn_id =%1
249 AND ef2.entity_table = 'civicrm_financial_trxn'
250 AND ef1.entity_table = 'civicrm_financial_item'
251 GROUP BY ef1.financial_trxn_id
253 SELECT ef1.financial_trxn_id, ef1.amount
254 FROM civicrm_entity_financial_trxn ef1
255 LEFT JOIN civicrm_entity_financial_trxn ef2 ON ef1.entity_id = ef2.entity_id
256 WHERE ef2.financial_trxn_id =%1
257 AND ef2.entity_table = 'civicrm_financial_trxn'
258 AND ef1.entity_table = 'civicrm_financial_trxn'";
260 $sqlParams = [1 => [$financial_trxn_id, 'Integer']];
261 $dao = CRM_Core_DAO
::executeQuery($query, $sqlParams);
264 while ($dao->fetch()) {
265 $result[$i]['financial_trxn_id'] = $dao->financial_trxn_id
;
266 $result[$i]['amount'] = $dao->amount
;
270 if (empty($result)) {
271 $query = "SELECT sum( amount ) amount FROM civicrm_entity_financial_trxn WHERE financial_trxn_id =%1 AND entity_table = 'civicrm_financial_item'";
272 $sqlParams = [1 => [$financial_trxn_id, 'Integer']];
273 $dao = CRM_Core_DAO
::executeQuery($query, $sqlParams);
276 $result[0]['financial_trxn_id'] = $financial_trxn_id;
277 $result[0]['amount'] = $dao->amount
;
284 * Given an entity_id and entity_table, check for corresponding entity_financial_trxn and financial_trxn record.
285 * NOTE: This should be moved to separate BAO for EntityFinancialTrxn when we start adding more code for that object.
288 * Id of the entity usually the contactID.
289 * @param string $entity_table
290 * Name of the entity table usually 'civicrm_contact'.
293 * array of category id's the contact belongs to.
296 public static function getFinancialTrxnLineTotal($entity_id, $entity_table = 'civicrm_contribution') {
297 $query = "SELECT lt.price_field_value_id AS id, ft.financial_trxn_id,ft.amount AS amount FROM civicrm_entity_financial_trxn AS ft
298 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'
299 LEFT JOIN civicrm_line_item AS lt ON lt.id = fi.entity_id AND lt.entity_table = %2
300 WHERE lt.entity_id = %1 ";
302 $sqlParams = [1 => [$entity_id, 'Integer'], 2 => [$entity_table, 'String']];
303 $dao = CRM_Core_DAO
::executeQuery($query, $sqlParams);
304 while ($dao->fetch()) {
305 $result[$dao->financial_trxn_id
][$dao->id
] = $dao->amount
;
307 if (!empty($result)) {
316 * Delete financial transaction.
318 * @param int $entity_id
320 * TRUE on success, FALSE otherwise.
322 public static function deleteFinancialTrxn($entity_id) {
323 $query = "DELETE ceft1, cfi, ceft, cft FROM `civicrm_financial_trxn` cft
324 LEFT JOIN civicrm_entity_financial_trxn ceft
325 ON ceft.financial_trxn_id = cft.id AND ceft.entity_table = 'civicrm_contribution'
326 LEFT JOIN civicrm_entity_financial_trxn ceft1
327 ON ceft1.financial_trxn_id = cft.id AND ceft1.entity_table = 'civicrm_financial_item'
328 LEFT JOIN civicrm_financial_item cfi
329 ON ceft1.entity_table = 'civicrm_financial_item' and cfi.id = ceft1.entity_id
330 WHERE ceft.entity_id = %1";
331 CRM_Core_DAO
::executeQuery($query, [1 => [$entity_id, 'Integer']]);
336 * Create financial transaction for premium.
338 * @param array $params
340 * - financial_type_id
346 public static function createPremiumTrxn($params) {
347 if ((empty($params['financial_type_id']) ||
empty($params['contributionId'])) && empty($params['oldPremium'])) {
351 if (!empty($params['cost'])) {
352 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
353 $toFinancialAccountType = !empty($params['isDeleted']) ?
'Premiums Inventory Account is' : 'Cost of Sales Account is';
354 $fromFinancialAccountType = !empty($params['isDeleted']) ?
'Cost of Sales Account is' : 'Premiums Inventory Account is';
356 'to_financial_account_id' => CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['financial_type_id'], $toFinancialAccountType),
357 'from_financial_account_id' => CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['financial_type_id'], $fromFinancialAccountType),
358 'trxn_date' => date('YmdHis'),
359 'total_amount' => CRM_Utils_Array
::value('cost', $params) ?
$params['cost'] : 0,
360 'currency' => CRM_Utils_Array
::value('currency', $params),
361 'status_id' => array_search('Completed', $contributionStatuses),
362 'entity_table' => 'civicrm_contribution',
363 'entity_id' => $params['contributionId'],
365 CRM_Core_BAO_FinancialTrxn
::create($financialtrxn);
368 if (!empty($params['oldPremium'])) {
370 'id' => $params['oldPremium']['product_id'],
372 $productDetails = [];
373 CRM_Contribute_BAO_Product
::retrieve($premiumParams, $productDetails);
375 'cost' => CRM_Utils_Array
::value('cost', $productDetails),
376 'currency' => CRM_Utils_Array
::value('currency', $productDetails),
377 'financial_type_id' => CRM_Utils_Array
::value('financial_type_id', $productDetails),
378 'contributionId' => $params['oldPremium']['contribution_id'],
381 CRM_Core_BAO_FinancialTrxn
::createPremiumTrxn($params);
386 * Create financial trxn and items when fee is charged.
388 * @param array $params
389 * To create trxn entries.
393 public static function recordFees($params) {
394 $domainId = CRM_Core_Config
::domainID();
396 if (!empty($params['prevContribution'])) {
397 $amount = $params['prevContribution']->fee_amount
;
399 $amount = $params['fee_amount'] - $amount;
403 $contributionId = isset($params['contribution']->id
) ?
$params['contribution']->id
: $params['contribution_id'];
404 if (empty($params['financial_type_id'])) {
405 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id', 'id');
408 $financialTypeId = $params['financial_type_id'];
410 $financialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($financialTypeId, 'Expense Account is');
412 $params['trxnParams']['from_financial_account_id'] = $params['to_financial_account_id'];
413 $params['trxnParams']['to_financial_account_id'] = $financialAccount;
414 $params['trxnParams']['total_amount'] = $amount;
415 $params['trxnParams']['fee_amount'] = $params['trxnParams']['net_amount'] = 0;
416 $params['trxnParams']['status_id'] = $params['contribution_status_id'];
417 $params['trxnParams']['contribution_id'] = $contributionId;
418 $params['trxnParams']['is_payment'] = FALSE;
419 $trxn = self
::create($params['trxnParams']);
420 if (empty($params['entity_id'])) {
421 $financialTrxnID = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['trxnParams']['contribution_id'], 'DESC');
422 $params['entity_id'] = $financialTrxnID['financialTrxnId'];
426 'financial_account_id' => $financialAccount,
427 'contact_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $domainId, 'contact_id'),
428 'created_date' => date('YmdHis'),
429 'transaction_date' => date('YmdHis'),
431 'description' => 'Fee',
432 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_FinancialItem', 'status_id', 'Paid'),
433 'entity_table' => 'civicrm_financial_trxn',
434 'entity_id' => $params['entity_id'],
435 'currency' => $params['trxnParams']['currency'],
437 $trxnIDS['id'] = $trxn->id
;
438 CRM_Financial_BAO_FinancialItem
::create($fItemParams, NULL, $trxnIDS);
442 * get partial payment amount.
446 * This function basically calls CRM_Contribute_BAO_Contribution::getContributionBalance
447 * - just do that. If need be we could have a fn to get the contribution id but
448 * chances are the calling functions already know it anyway.
450 * @param int $entityId
451 * @param string $entityName
452 * @param int $lineItemTotal
456 public static function getPartialPaymentWithType($entityId, $entityName = 'participant', $lineItemTotal = NULL) {
458 if (empty($entityName)) {
462 // @todo - deprecate passing in entity & type - just figure out contribution id FIRST
463 if ($entityName == 'participant') {
464 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $entityId, 'contribution_id', 'participant_id');
466 elseif ($entityName == 'membership') {
467 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $entityId, 'contribution_id', 'membership_id');
470 $contributionId = $entityId;
472 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
474 if ($contributionId && $financialTypeId) {
476 $paymentVal = CRM_Contribute_BAO_Contribution
::getContributionBalance($contributionId, $lineItemTotal);
478 if ($paymentVal < 0) {
479 $value['refund_due'] = $paymentVal;
481 elseif ($paymentVal > 0) {
482 $value['amount_owed'] = $paymentVal;
489 * @param int $contributionID
490 * @param bool $includeRefund
494 public static function getTotalPayments($contributionID, $includeRefund = FALSE) {
495 $statusIDs = [CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed')];
497 if ($includeRefund) {
498 $statusIDs[] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Refunded');
501 $sql = "SELECT SUM(ft.total_amount) FROM civicrm_financial_trxn ft
502 INNER JOIN civicrm_entity_financial_trxn eft ON (eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution')
503 WHERE eft.entity_id = %1 AND ft.is_payment = 1 AND ft.status_id IN (%2) ";
505 return CRM_Core_DAO
::singleValueQuery($sql, [
506 1 => [$contributionID, 'Integer'],
507 2 => [implode(',', $statusIDs), 'CommaSeparatedIntegers'],
512 * Get revenue amount for membership.
514 * @param array $lineItem
518 public static function getMembershipRevenueAmount($lineItem) {
520 $membershipDetail = civicrm_api3('Membership', 'getsingle', [
521 'id' => $lineItem['entity_id'],
523 if (empty($membershipDetail['end_date'])) {
524 return $revenueAmount;
527 $startDate = strtotime($membershipDetail['start_date']);
528 $endDate = strtotime($membershipDetail['end_date']);
529 $startYear = date('Y', $startDate);
530 $endYear = date('Y', $endDate);
531 $startMonth = date('m', $startDate);
532 $endMonth = date('m', $endDate);
534 $monthOfService = (($endYear - $startYear) * 12) +
($endMonth - $startMonth);
535 $startDateOfRevenue = $membershipDetail['start_date'];
536 $typicalPayment = round(($lineItem['line_total'] / $monthOfService), 2);
537 for ($i = 0; $i <= $monthOfService - 1; $i++
) {
538 $revenueAmount[$i]['amount'] = $typicalPayment;
540 $revenueAmount[$i]['amount'] -= (($typicalPayment * $monthOfService) - $lineItem['line_total']);
542 $revenueAmount[$i]['revenue_date'] = $startDateOfRevenue;
543 $startDateOfRevenue = date('Y-m', strtotime('+1 month', strtotime($startDateOfRevenue))) . '-01';
545 return $revenueAmount;
549 * Create transaction for deferred revenue.
551 * @param array $lineItems
553 * @param CRM_Contribute_BAO_Contribution $contributionDetails
555 * @param bool $update
557 * @param string $context
560 public static function createDeferredTrxn($lineItems, $contributionDetails, $update = FALSE, $context = NULL) {
561 if (empty($lineItems)) {
564 $revenueRecognitionDate = $contributionDetails->revenue_recognition_date
;
565 if (!CRM_Utils_System
::isNull($revenueRecognitionDate)) {
566 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
568 && (CRM_Utils_Array
::value($contributionDetails->contribution_status_id
, $statuses) != 'Completed'
569 ||
(CRM_Utils_Array
::value($contributionDetails->contribution_status_id
, $statuses) != 'Pending'
570 && $contributionDetails->is_pay_later
)
576 'contribution_id' => $contributionDetails->id
,
577 'fee_amount' => '0.00',
578 'currency' => $contributionDetails->currency
,
579 'trxn_id' => $contributionDetails->trxn_id
,
580 'status_id' => $contributionDetails->contribution_status_id
,
581 'payment_instrument_id' => $contributionDetails->payment_instrument_id
,
582 'check_number' => $contributionDetails->check_number
,
585 $deferredRevenues = [];
586 foreach ($lineItems as $priceSetID => $lineItem) {
590 foreach ($lineItem as $key => $item) {
591 $lineTotal = !empty($item['deferred_line_total']) ?
$item['deferred_line_total'] : $item['line_total'];
592 if ($lineTotal <= 0 && !$update) {
595 $deferredRevenues[$key] = $item;
596 if ($context == 'changeFinancialType') {
597 $deferredRevenues[$key]['financial_type_id'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_LineItem', $item['id'], 'financial_type_id');
599 if (in_array($item['entity_table'],
600 ['civicrm_participant', 'civicrm_contribution'])
602 $deferredRevenues[$key]['revenue'][] = [
603 'amount' => $lineTotal,
604 'revenue_date' => $revenueRecognitionDate,
609 $item['line_total'] = $lineTotal;
610 $deferredRevenues[$key]['revenue'] = self
::getMembershipRevenueAmount($item);
614 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
616 CRM_Utils_Hook
::alterDeferredRevenueItems($deferredRevenues, $contributionDetails, $update, $context);
618 foreach ($deferredRevenues as $key => $deferredRevenue) {
619 $results = civicrm_api3('EntityFinancialAccount', 'get', [
620 'entity_table' => 'civicrm_financial_type',
621 'entity_id' => $deferredRevenue['financial_type_id'],
622 'account_relationship' => ['IN' => ['Income Account is', 'Deferred Revenue Account is']],
624 if ($results['count'] != 2) {
627 foreach ($results['values'] as $result) {
628 if ($result['account_relationship'] == $accountRel) {
629 $trxnParams['from_financial_account_id'] = $result['financial_account_id'];
632 $trxnParams['to_financial_account_id'] = $result['financial_account_id'];
635 foreach ($deferredRevenue['revenue'] as $revenue) {
636 $trxnParams['total_amount'] = $trxnParams['net_amount'] = $revenue['amount'];
637 $trxnParams['trxn_date'] = CRM_Utils_Date
::isoToMysql($revenue['revenue_date']);
638 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
640 'entity_id' => $deferredRevenue['financial_item_id'],
641 'entity_table' => 'civicrm_financial_item',
642 'amount' => $revenue['amount'],
643 'financial_trxn_id' => $financialTxn->id
,
645 civicrm_api3('EntityFinancialTrxn', 'create', $entityParams);
652 * Update Credit Card Details in civicrm_financial_trxn table.
654 * @param int $contributionID
655 * @param int $panTruncation
656 * @param int $cardType
659 public static function updateCreditCardDetails($contributionID, $panTruncation, $cardType) {
660 $financialTrxn = civicrm_api3('EntityFinancialTrxn', 'get', [
661 'return' => ['financial_trxn_id.payment_processor_id', 'financial_trxn_id'],
662 'entity_table' => 'civicrm_contribution',
663 'entity_id' => $contributionID,
664 'financial_trxn_id.is_payment' => TRUE,
665 'options' => ['sort' => 'financial_trxn_id DESC', 'limit' => 1],
668 // In case of Contribution status is Pending From Incomplete Transaction or Failed there is no Financial Entries created for Contribution.
669 // Above api will return 0 count, in such case we won't update card type and pan truncation field.
670 if (!$financialTrxn['count']) {
674 $financialTrxn = $financialTrxn['values'][$financialTrxn['id']];
675 $paymentProcessorID = CRM_Utils_Array
::value('financial_trxn_id.payment_processor_id', $financialTrxn);
677 if ($paymentProcessorID) {
681 $financialTrxnId = $financialTrxn['financial_trxn_id'];
682 $trxnparams = ['id' => $financialTrxnId];
683 if (isset($cardType)) {
684 $trxnparams['card_type_id'] = $cardType;
686 if (isset($panTruncation)) {
687 $trxnparams['pan_truncation'] = $panTruncation;
689 civicrm_api3('FinancialTrxn', 'create', $trxnparams);
693 * The function is responsible for handling financial entries if payment instrument is changed
695 * @param array $inputParams
698 public static function updateFinancialAccountsOnPaymentInstrumentChange($inputParams) {
699 $prevContribution = $inputParams['prevContribution'];
700 $currentContribution = $inputParams['contribution'];
701 // ensure that there are all the information in updated contribution object identified by $currentContribution
702 $currentContribution->find(TRUE);
704 $deferredFinancialAccount = CRM_Utils_Array
::value('deferred_financial_account_id', $inputParams);
705 if (empty($deferredFinancialAccount)) {
706 $deferredFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($prevContribution->financial_type_id
, 'Deferred Revenue Account is');
709 $lastFinancialTrxnId = self
::getFinancialTrxnId($prevContribution->id
, 'DESC', FALSE, NULL, $deferredFinancialAccount);
711 // there is no point to proceed as we can't find the last payment made
712 // @todo we should throw an exception here rather than return false.
713 if (empty($lastFinancialTrxnId['financialTrxnId'])) {
717 // If payment instrument is changed reverse the last payment
718 // in terms of reversing financial item and trxn
719 $lastFinancialTrxn = civicrm_api3('FinancialTrxn', 'getsingle', ['id' => $lastFinancialTrxnId['financialTrxnId']]);
720 unset($lastFinancialTrxn['id']);
721 $lastFinancialTrxn['trxn_date'] = $inputParams['trxnParams']['trxn_date'];
722 $lastFinancialTrxn['total_amount'] = -$inputParams['trxnParams']['total_amount'];
723 $lastFinancialTrxn['net_amount'] = -$inputParams['trxnParams']['net_amount'];
724 $lastFinancialTrxn['fee_amount'] = -$inputParams['trxnParams']['fee_amount'];
725 $lastFinancialTrxn['contribution_id'] = $prevContribution->id
;
726 foreach ([$lastFinancialTrxn, $inputParams['trxnParams']] as $financialTrxnParams) {
727 $trxn = CRM_Core_BAO_FinancialTrxn
::create($financialTrxnParams);
729 'total_amount' => $trxn->total_amount
,
730 'contribution_id' => $currentContribution->id
,
732 CRM_Contribute_BAO_Contribution
::assignProportionalLineItems($trxnParams, $trxn->id
, $prevContribution->total_amount
);
735 self
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $inputParams), $currentContribution, TRUE, 'changePaymentInstrument');