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