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