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