Merge pull request #14077 from pradpnayak/AutoComplete
[civicrm-core.git] / CRM / Core / BAO / FinancialTrxn.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2019
32 */
33 class CRM_Core_BAO_FinancialTrxn extends CRM_Financial_DAO_FinancialTrxn {
34 /**
35 * Class constructor.
36 *
37 * @return \CRM_Financial_DAO_FinancialTrxn
38 */
39
40 /**
41 */
42 public function __construct() {
43 parent::__construct();
44 }
45
46 /**
47 * Takes an associative array and creates a financial transaction object.
48 *
49 * @param array $params
50 * (reference ) an assoc array of name/value pairs.
51 *
52 * @return CRM_Financial_DAO_FinancialTrxn
53 */
54 public static function create($params) {
55 $trxn = new CRM_Financial_DAO_FinancialTrxn();
56 $trxn->copyValues($params);
57
58 if (empty($params['id']) && !CRM_Utils_Rule::currencyCode($trxn->currency)) {
59 $trxn->currency = CRM_Core_Config::singleton()->defaultCurrency;
60 }
61
62 $trxn->save();
63
64 if (!empty($params['id'])) {
65 // For an update entity financial transaction record will already exist. Return early.
66 return $trxn;
67 }
68
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'],
75 ];
76
77 $entityTrxn = new CRM_Financial_DAO_EntityFinancialTrxn();
78 $entityTrxn->copyValues($entityFinancialTrxnParams);
79 $entityTrxn->save();
80 return $trxn;
81 }
82
83 /**
84 * @param int $contributionId
85 * @param int $contributionFinancialTypeId
86 *
87 * @return array
88 */
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');
92 }
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";
95
96 $p[1] = [$contributionId, 'Integer'];
97 $p[2] = [$toFinancialAccount, 'Integer'];
98
99 $balanceAmtDAO = CRM_Core_DAO::executeQuery($q, $p);
100 $ret = [];
101 if ($balanceAmtDAO->N) {
102 $ret['total_amount'] = 0;
103 }
104 while ($balanceAmtDAO->fetch()) {
105 $ret['trxn_id'] = $balanceAmtDAO->id;
106 $ret['total_amount'] += $balanceAmtDAO->total_amount;
107 }
108
109 return $ret;
110 }
111
112 /**
113 * Fetch object based on array of properties.
114 *
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.
119 *
120 * @return \CRM_Financial_DAO_FinancialTrxn
121 */
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;
128 }
129 return NULL;
130 }
131
132 /**
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.
135 *
136 * @param $entity_id
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
144 *
145 * @return array
146 * array of category id's the contact belongs to.
147 *
148 */
149 public static function getFinancialTrxnId($entity_id, $orderBy = 'ASC', $newTrxn = FALSE, $whereClause = '', $fromAccountID = NULL) {
150 $ids = ['entityFinancialTrxnId' => NULL, 'financialTrxnId' => NULL];
151
152 $params = [1 => [$entity_id, 'Integer']];
153 $condition = "";
154 if (!$newTrxn) {
155 $condition = " AND ((ceft1.entity_table IS NOT NULL) OR (cft.payment_instrument_id IS NOT NULL AND ceft1.entity_table IS NULL)) ";
156 }
157
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'];
161 }
162 if ($orderBy) {
163 $orderBy = CRM_Utils_Type::escape($orderBy, 'String');
164 }
165
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)
173 {$condition}
174 {$whereClause}
175 ORDER BY cft.id {$orderBy}
176 LIMIT 1;";
177
178 $dao = CRM_Core_DAO::executeQuery($query, $params);
179 if ($dao->fetch()) {
180 $ids['entityFinancialTrxnId'] = $dao->id;
181 $ids['financialTrxnId'] = $dao->financial_trxn_id;
182 $ids['trxn_id'] = $dao->trxn_id;
183 }
184 return $ids;
185 }
186
187 /**
188 * Get the transaction id for the (latest) refund associated with a contribution.
189 *
190 * @param int $contributionID
191 * @return string
192 */
193 public static function getRefundTransactionTrxnID($contributionID) {
194 $ids = self::getRefundTransactionIDs($contributionID);
195 return isset($ids['trxn_id']) ? $ids['trxn_id'] : NULL;
196 }
197
198 /**
199 * Get the transaction id for the (latest) refund associated with a contribution.
200 *
201 * @param int $contributionID
202 * @return array
203 */
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");
207 }
208
209 /**
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.
212 *
213 * @param int $entity_id
214 * Id of the entity usually the contactID.
215 *
216 * @return array
217 * array of category id's the contact belongs to.
218 *
219 */
220 public static function getFinancialTrxnTotal($entity_id) {
221 $query = "
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
225 ";
226
227 $sqlParams = [1 => [$entity_id, 'Integer']];
228 return CRM_Core_DAO::singleValueQuery($query, $sqlParams);
229
230 }
231
232 /**
233 * Given an financial_trxn_id check for previous entity_financial_trxn.
234 *
235 * @param $financial_trxn_id
236 * Id of the latest payment.
237 *
238 *
239 * @return array
240 * array of previous payments
241 *
242 */
243 public static function getPayments($financial_trxn_id) {
244 $query = "
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
252 UNION
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'";
259
260 $sqlParams = [1 => [$financial_trxn_id, 'Integer']];
261 $dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
262 $i = 0;
263 $result = [];
264 while ($dao->fetch()) {
265 $result[$i]['financial_trxn_id'] = $dao->financial_trxn_id;
266 $result[$i]['amount'] = $dao->amount;
267 $i++;
268 }
269
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);
274
275 if ($dao->fetch()) {
276 $result[0]['financial_trxn_id'] = $financial_trxn_id;
277 $result[0]['amount'] = $dao->amount;
278 }
279 }
280 return $result;
281 }
282
283 /**
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.
286 *
287 * @param $entity_id
288 * Id of the entity usually the contactID.
289 * @param string $entity_table
290 * Name of the entity table usually 'civicrm_contact'.
291 *
292 * @return array
293 * array of category id's the contact belongs to.
294 *
295 */
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 ";
301
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;
306 }
307 if (!empty($result)) {
308 return $result;
309 }
310 else {
311 return NULL;
312 }
313 }
314
315 /**
316 * Delete financial transaction.
317 *
318 * @param int $entity_id
319 * @return bool
320 * TRUE on success, FALSE otherwise.
321 */
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']]);
332 return TRUE;
333 }
334
335 /**
336 * Create financial transaction for premium.
337 *
338 * @param array $params
339 * - oldPremium
340 * - financial_type_id
341 * - contributionId
342 * - isDeleted
343 * - cost
344 * - currency
345 */
346 public static function createPremiumTrxn($params) {
347 if ((empty($params['financial_type_id']) || empty($params['contributionId'])) && empty($params['oldPremium'])) {
348 return;
349 }
350
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';
355 $financialtrxn = [
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'],
364 ];
365 CRM_Core_BAO_FinancialTrxn::create($financialtrxn);
366 }
367
368 if (!empty($params['oldPremium'])) {
369 $premiumParams = [
370 'id' => $params['oldPremium']['product_id'],
371 ];
372 $productDetails = [];
373 CRM_Contribute_BAO_Product::retrieve($premiumParams, $productDetails);
374 $params = [
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'],
379 'isDeleted' => TRUE,
380 ];
381 CRM_Core_BAO_FinancialTrxn::createPremiumTrxn($params);
382 }
383 }
384
385 /**
386 * Create financial trxn and items when fee is charged.
387 *
388 * @param array $params
389 * To create trxn entries.
390 *
391 * @return bool|void
392 */
393 public static function recordFees($params) {
394 $domainId = CRM_Core_Config::domainID();
395 $amount = 0;
396 if (!empty($params['prevContribution'])) {
397 $amount = $params['prevContribution']->fee_amount;
398 }
399 $amount = $params['fee_amount'] - $amount;
400 if (!$amount) {
401 return FALSE;
402 }
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');
406 }
407 else {
408 $financialTypeId = $params['financial_type_id'];
409 }
410 $financialAccount = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship($financialTypeId, 'Expense Account is');
411
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'];
423 }
424 $fItemParams
425 = [
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'),
430 'amount' => $amount,
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'],
436 ];
437 $trxnIDS['id'] = $trxn->id;
438 CRM_Financial_BAO_FinancialItem::create($fItemParams, NULL, $trxnIDS);
439 }
440
441 /**
442 * get partial payment amount.
443 *
444 * @deprecated
445 *
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.
449 *
450 * @param int $entityId
451 * @param string $entityName
452 * @param int $lineItemTotal
453 *
454 * @return array
455 */
456 public static function getPartialPaymentWithType($entityId, $entityName = 'participant', $lineItemTotal = NULL) {
457 $value = NULL;
458 if (empty($entityName)) {
459 return $value;
460 }
461
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');
465 }
466 elseif ($entityName == 'membership') {
467 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $entityId, 'contribution_id', 'membership_id');
468 }
469 else {
470 $contributionId = $entityId;
471 }
472 $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
473
474 if ($contributionId && $financialTypeId) {
475
476 $paymentVal = CRM_Contribute_BAO_Contribution::getContributionBalance($contributionId, $lineItemTotal);
477 $value = [];
478 if ($paymentVal < 0) {
479 $value['refund_due'] = $paymentVal;
480 }
481 elseif ($paymentVal > 0) {
482 $value['amount_owed'] = $paymentVal;
483 }
484 }
485 return $value;
486 }
487
488 /**
489 * @param int $contributionID
490 * @param bool $includeRefund
491 *
492 * @return string
493 */
494 public static function getTotalPayments($contributionID, $includeRefund = FALSE) {
495 $statusIDs = [CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed')];
496
497 if ($includeRefund) {
498 $statusIDs[] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Refunded');
499 }
500
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) ";
504
505 return CRM_Core_DAO::singleValueQuery($sql, [
506 1 => [$contributionID, 'Integer'],
507 2 => [implode(',', $statusIDs), 'CommaSeparatedIntegers'],
508 ]);
509 }
510
511 /**
512 * Get revenue amount for membership.
513 *
514 * @param array $lineItem
515 *
516 * @return array
517 */
518 public static function getMembershipRevenueAmount($lineItem) {
519 $revenueAmount = [];
520 $membershipDetail = civicrm_api3('Membership', 'getsingle', [
521 'id' => $lineItem['entity_id'],
522 ]);
523 if (empty($membershipDetail['end_date'])) {
524 return $revenueAmount;
525 }
526
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);
533
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;
539 if ($i == 0) {
540 $revenueAmount[$i]['amount'] -= (($typicalPayment * $monthOfService) - $lineItem['line_total']);
541 }
542 $revenueAmount[$i]['revenue_date'] = $startDateOfRevenue;
543 $startDateOfRevenue = date('Y-m', strtotime('+1 month', strtotime($startDateOfRevenue))) . '-01';
544 }
545 return $revenueAmount;
546 }
547
548 /**
549 * Create transaction for deferred revenue.
550 *
551 * @param array $lineItems
552 *
553 * @param CRM_Contribute_BAO_Contribution $contributionDetails
554 *
555 * @param bool $update
556 *
557 * @param string $context
558 *
559 */
560 public static function createDeferredTrxn($lineItems, $contributionDetails, $update = FALSE, $context = NULL) {
561 if (empty($lineItems)) {
562 return;
563 }
564 $revenueRecognitionDate = $contributionDetails->revenue_recognition_date;
565 if (!CRM_Utils_System::isNull($revenueRecognitionDate)) {
566 $statuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
567 if (!$update
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)
571 )
572 ) {
573 return;
574 }
575 $trxnParams = [
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,
583 ];
584
585 $deferredRevenues = [];
586 foreach ($lineItems as $priceSetID => $lineItem) {
587 if (!$priceSetID) {
588 continue;
589 }
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) {
593 continue;
594 }
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');
598 }
599 if (in_array($item['entity_table'],
600 ['civicrm_participant', 'civicrm_contribution'])
601 ) {
602 $deferredRevenues[$key]['revenue'][] = [
603 'amount' => $lineTotal,
604 'revenue_date' => $revenueRecognitionDate,
605 ];
606 }
607 else {
608 // for membership
609 $item['line_total'] = $lineTotal;
610 $deferredRevenues[$key]['revenue'] = self::getMembershipRevenueAmount($item);
611 }
612 }
613 }
614 $accountRel = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
615
616 CRM_Utils_Hook::alterDeferredRevenueItems($deferredRevenues, $contributionDetails, $update, $context);
617
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']],
623 ]);
624 if ($results['count'] != 2) {
625 continue;
626 }
627 foreach ($results['values'] as $result) {
628 if ($result['account_relationship'] == $accountRel) {
629 $trxnParams['from_financial_account_id'] = $result['financial_account_id'];
630 }
631 else {
632 $trxnParams['to_financial_account_id'] = $result['financial_account_id'];
633 }
634 }
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);
639 $entityParams = [
640 'entity_id' => $deferredRevenue['financial_item_id'],
641 'entity_table' => 'civicrm_financial_item',
642 'amount' => $revenue['amount'],
643 'financial_trxn_id' => $financialTxn->id,
644 ];
645 civicrm_api3('EntityFinancialTrxn', 'create', $entityParams);
646 }
647 }
648 }
649 }
650
651 /**
652 * Update Credit Card Details in civicrm_financial_trxn table.
653 *
654 * @param int $contributionID
655 * @param int $panTruncation
656 * @param int $cardType
657 *
658 */
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],
666 ]);
667
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']) {
671 return NULL;
672 }
673
674 $financialTrxn = $financialTrxn['values'][$financialTrxn['id']];
675 $paymentProcessorID = CRM_Utils_Array::value('financial_trxn_id.payment_processor_id', $financialTrxn);
676
677 if ($paymentProcessorID) {
678 return NULL;
679 }
680
681 $financialTrxnId = $financialTrxn['financial_trxn_id'];
682 $trxnparams = ['id' => $financialTrxnId];
683 if (isset($cardType)) {
684 $trxnparams['card_type_id'] = $cardType;
685 }
686 if (isset($panTruncation)) {
687 $trxnparams['pan_truncation'] = $panTruncation;
688 }
689 civicrm_api3('FinancialTrxn', 'create', $trxnparams);
690 }
691
692 /**
693 * The function is responsible for handling financial entries if payment instrument is changed
694 *
695 * @param array $inputParams
696 *
697 */
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);
703
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');
707 }
708
709 $lastFinancialTrxnId = self::getFinancialTrxnId($prevContribution->id, 'DESC', FALSE, NULL, $deferredFinancialAccount);
710
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'])) {
714 return FALSE;
715 }
716
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);
728 $trxnParams = [
729 'total_amount' => $trxn->total_amount,
730 'contribution_id' => $currentContribution->id,
731 ];
732 CRM_Contribute_BAO_Contribution::assignProportionalLineItems($trxnParams, $trxn->id, $prevContribution->total_amount);
733 }
734
735 self::createDeferredTrxn(CRM_Utils_Array::value('line_item', $inputParams), $currentContribution, TRUE, 'changePaymentInstrument');
736
737 return TRUE;
738 }
739
740 }