Merge pull request #13324 from agileware/CIVICRM-947
[civicrm-core.git] / CRM / Core / BAO / FinancialTrxn.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
6a488035
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
6b83d5bd 31 * @copyright CiviCRM LLC (c) 2004-2019
6a488035 32 */
6a488035 33class CRM_Core_BAO_FinancialTrxn extends CRM_Financial_DAO_FinancialTrxn {
b5c2afd0 34 /**
fe482240 35 * Class constructor.
b5c2afd0 36 *
b5c2afd0
EM
37 * @return \CRM_Financial_DAO_FinancialTrxn
38 */
39 /**
b5c2afd0 40 */
00be9182 41 public function __construct() {
6a488035
TO
42 parent::__construct();
43 }
44
45 /**
fe482240 46 * Takes an associative array and creates a financial transaction object.
6a488035 47 *
6a0b768e
TO
48 * @param array $params
49 * (reference ) an assoc array of name/value pairs.
6a488035 50 *
5b541553 51 * @return CRM_Financial_DAO_FinancialTrxn
6a488035 52 */
8a40179e 53 public static function create($params) {
6a488035
TO
54 $trxn = new CRM_Financial_DAO_FinancialTrxn();
55 $trxn->copyValues($params);
4e92d4f4 56
8a40179e 57 if (empty($params['id']) && !CRM_Utils_Rule::currencyCode($trxn->currency)) {
4e92d4f4 58 $trxn->currency = CRM_Core_Config::singleton()->defaultCurrency;
6a488035
TO
59 }
60
50f8ceb1 61 $trxn->save();
6a488035 62
3137781d 63 if (!empty($params['id'])) {
8a40179e 64 // For an update entity financial transaction record will already exist. Return early.
50f8ceb1 65 return $trxn;
6a488035
TO
66 }
67
3137781d 68 // Save to entity_financial_trxn table.
50f8ceb1 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
6a488035
TO
76 $entityTrxn = new CRM_Financial_DAO_EntityFinancialTrxn();
77 $entityTrxn->copyValues($entityFinancialTrxnParams);
78 $entityTrxn->save();
79 return $trxn;
80 }
81
b5c2afd0 82 /**
100fef9d
CW
83 * @param int $contributionId
84 * @param int $contributionFinancialTypeId
b5c2afd0
EM
85 *
86 * @return array
87 */
00be9182 88 public static function getBalanceTrxnAmt($contributionId, $contributionFinancialTypeId = NULL) {
29c61b58
PJ
89 if (!$contributionFinancialTypeId) {
90 $contributionFinancialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'financial_type_id');
91 }
876b8ab0 92 $toFinancialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($contributionFinancialTypeId, 'Accounts Receivable Account is');
520ec403 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";
1010c4e1 94
ede1935f
PJ
95 $p[1] = array($contributionId, 'Integer');
96 $p[2] = array($toFinancialAccount, 'Integer');
1010c4e1 97
ede1935f
PJ
98 $balanceAmtDAO = CRM_Core_DAO::executeQuery($q, $p);
99 $ret = array();
18fdfcc3
PN
100 if ($balanceAmtDAO->N) {
101 $ret['total_amount'] = 0;
102 }
22e263ad 103 while ($balanceAmtDAO->fetch()) {
ede1935f 104 $ret['trxn_id'] = $balanceAmtDAO->id;
18fdfcc3 105 $ret['total_amount'] += $balanceAmtDAO->total_amount;
ede1935f
PJ
106 }
107
108 return $ret;
109 }
110
6a488035 111 /**
fe482240 112 * Fetch object based on array of properties.
6a488035 113 *
6a0b768e
TO
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.
6a488035 118 *
5b541553 119 * @return \CRM_Financial_DAO_FinancialTrxn
6a488035 120 */
481a74f4
TO
121 public static function retrieve(&$params, &$defaults) {
122 $financialItem = new CRM_Financial_DAO_FinancialTrxn();
6a488035 123 $financialItem->copyValues($params);
4eeb9a5b 124 if ($financialItem->find(TRUE)) {
481a74f4 125 CRM_Core_DAO::storeValues($financialItem, $defaults);
6a488035
TO
126 return $financialItem;
127 }
e60f24eb 128 return NULL;
6a488035
TO
129 }
130
131 /**
6a488035
TO
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 *
6a0b768e 135 * @param $entity_id
99cdd94d 136 * Id of the entity usually the contributionID.
6a0b768e
TO
137 * @param string $orderBy
138 * To get single trxn id for a entity table i.e last or first.
dd244018 139 * @param bool $newTrxn
99cdd94d 140 * @param string $whereClause
141 * Additional where parameters
dd244018 142 *
a6c01b45
CW
143 * @return array
144 * array of category id's the contact belongs to.
6a488035 145 *
6a488035 146 */
8cf6bd83 147 public static function getFinancialTrxnId($entity_id, $orderBy = 'ASC', $newTrxn = FALSE, $whereClause = '', $fromAccountID = NULL) {
6a488035
TO
148 $ids = array('entityFinancialTrxnId' => NULL, 'financialTrxnId' => NULL);
149
8cf6bd83 150 $params = array(1 => array($entity_id, 'Integer'));
6a488035
TO
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 }
21d32567 155
8cf6bd83
PN
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 }
21d32567
DL
160 if ($orderBy) {
161 $orderBy = CRM_Utils_Type::escape($orderBy, 'String');
162 }
163
99cdd94d 164 $query = "SELECT ceft.id, ceft.financial_trxn_id, cft.trxn_id FROM `civicrm_financial_trxn` cft
cbb7c7e0 165LEFT JOIN civicrm_entity_financial_trxn ceft
6a488035
TO
166ON ceft.financial_trxn_id = cft.id AND ceft.entity_table = 'civicrm_contribution'
167LEFT JOIN civicrm_entity_financial_trxn ceft1
168ON ceft1.financial_trxn_id = cft.id AND ceft1.entity_table = 'civicrm_financial_item'
169LEFT JOIN civicrm_financial_item cfi ON ceft1.entity_table = 'civicrm_financial_item' and cfi.id = ceft1.entity_id
170WHERE ceft.entity_id = %1 AND (cfi.entity_table <> 'civicrm_financial_trxn' or cfi.entity_table is NULL)
171{$condition}
99cdd94d 172{$whereClause}
6a488035 173ORDER BY cft.id {$orderBy}
cbb7c7e0 174LIMIT 1;";
175
6a488035
TO
176 $dao = CRM_Core_DAO::executeQuery($query, $params);
177 if ($dao->fetch()) {
178 $ids['entityFinancialTrxnId'] = $dao->id;
179 $ids['financialTrxnId'] = $dao->financial_trxn_id;
99cdd94d 180 $ids['trxn_id'] = $dao->trxn_id;
6a488035
TO
181 }
182 return $ids;
183 }
184
99cdd94d 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
81716ddb 200 * @return array
99cdd94d 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
6a488035
TO
207 /**
208 * Given an entity_id and entity_table, check for corresponding entity_financial_trxn and financial_trxn record.
c490a46a 209 * @todo This should be moved to separate BAO for EntityFinancialTrxn when we start adding more code for that object.
da6b46f4 210 *
6a0b768e
TO
211 * @param int $entity_id
212 * Id of the entity usually the contactID.
6a488035 213 *
a6c01b45 214 * @return array
b44e3f84 215 * array of category id's the contact belongs to.
6a488035 216 *
6a488035 217 */
00be9182 218 public static function getFinancialTrxnTotal($entity_id) {
6a488035
TO
219 $query = "
220 SELECT (ft.amount+SUM(ceft.amount)) AS total FROM civicrm_entity_financial_trxn AS ft
cbb7c7e0 221LEFT JOIN civicrm_entity_financial_trxn AS ceft ON ft.financial_trxn_id = ceft.entity_id
6a488035
TO
222WHERE ft.entity_table = 'civicrm_contribution' AND ft.entity_id = %1
223 ";
224
225 $sqlParams = array(1 => array($entity_id, 'Integer'));
d3e86119 226 return CRM_Core_DAO::singleValueQuery($query, $sqlParams);
6a488035
TO
227
228 }
77b97be7 229
6a488035
TO
230 /**
231 * Given an financial_trxn_id check for previous entity_financial_trxn.
232 *
6a0b768e
TO
233 * @param $financial_trxn_id
234 * Id of the latest payment.
77b97be7 235 *
6a488035 236 *
a6c01b45
CW
237 * @return array
238 * array of previous payments
6a488035 239 *
6a488035 240 */
00be9182 241 public static function getPayments($financial_trxn_id) {
6a488035
TO
242 $query = "
243SELECT ef1.financial_trxn_id, sum(ef1.amount) amount
244FROM civicrm_entity_financial_trxn ef1
245LEFT JOIN civicrm_entity_financial_trxn ef2 ON ef1.financial_trxn_id = ef2.entity_id
246WHERE ef2.financial_trxn_id =%1
247 AND ef2.entity_table = 'civicrm_financial_trxn'
248 AND ef1.entity_table = 'civicrm_financial_item'
249GROUP BY ef1.financial_trxn_id
250UNION
251SELECT ef1.financial_trxn_id, ef1.amount
252FROM civicrm_entity_financial_trxn ef1
253LEFT JOIN civicrm_entity_financial_trxn ef2 ON ef1.entity_id = ef2.entity_id
254WHERE 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 *
6a0b768e
TO
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'.
6a488035 289 *
a6c01b45 290 * @return array
b44e3f84 291 * array of category id's the contact belongs to.
6a488035 292 *
6a488035 293 */
00be9182 294 public static function getFinancialTrxnLineTotal($entity_id, $entity_table = 'civicrm_contribution') {
6a488035
TO
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
296LEFT 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'
cbb7c7e0 297LEFT JOIN civicrm_line_item AS lt ON lt.id = fi.entity_id AND lt.entity_table = %2
6a488035
TO
298WHERE lt.entity_id = %1 ";
299
300 $sqlParams = array(1 => array($entity_id, 'Integer'), 2 => array($entity_table, 'String'));
353ffa53 301 $dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
9b873358 302 while ($dao->fetch()) {
6a488035
TO
303 $result[$dao->financial_trxn_id][$dao->id] = $dao->amount;
304 }
305 if (!empty($result)) {
306 return $result;
307 }
308 else {
e60f24eb 309 return NULL;
6a488035
TO
310 }
311 }
312
313 /**
fe482240 314 * Delete financial transaction.
6a488035 315 *
100fef9d 316 * @param int $entity_id
4eeb9a5b 317 * @return bool
ab8a593e 318 * TRUE on success, FALSE otherwise.
6a488035 319 */
00be9182 320 public static function deleteFinancialTrxn($entity_id) {
de1c25e1 321 $query = "DELETE ceft1, cfi, ceft, cft FROM `civicrm_financial_trxn` cft
cbb7c7e0 322LEFT JOIN civicrm_entity_financial_trxn ceft
de1c25e1
PN
323 ON ceft.financial_trxn_id = cft.id AND ceft.entity_table = 'civicrm_contribution'
324LEFT JOIN civicrm_entity_financial_trxn ceft1
325 ON ceft1.financial_trxn_id = cft.id AND ceft1.entity_table = 'civicrm_financial_item'
cbb7c7e0 326LEFT JOIN civicrm_financial_item cfi
de1c25e1
PN
327 ON ceft1.entity_table = 'civicrm_financial_item' and cfi.id = ceft1.entity_id
328WHERE ceft.entity_id = %1";
329 CRM_Core_DAO::executeQuery($query, array(1 => array($entity_id, 'Integer')));
330 return TRUE;
6a488035
TO
331 }
332
333 /**
fe482240 334 * Create financial transaction for premium.
6a488035 335 *
dd9db60b
EM
336 * @param array $params
337 * - oldPremium
338 * - financial_type_id
339 * - contributionId
340 * - isDeleted
341 * - cost
342 * - currency
6a488035 343 */
00be9182 344 public static function createPremiumTrxn($params) {
8cc574cf 345 if ((empty($params['financial_type_id']) || empty($params['contributionId'])) && empty($params['oldPremium'])) {
6a488035
TO
346 return;
347 }
cbb7c7e0 348
a7488080 349 if (!empty($params['cost'])) {
6a488035 350 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
876b8ab0
PN
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';
6a488035 353 $financialtrxn = array(
876b8ab0
PN
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),
6a488035
TO
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),
21dfd5f5 359 'status_id' => array_search('Completed', $contributionStatuses),
3137781d 360 'entity_table' => 'civicrm_contribution',
50f8ceb1 361 'entity_id' => $params['contributionId'],
6a488035 362 );
50f8ceb1 363 CRM_Core_BAO_FinancialTrxn::create($financialtrxn);
6a488035
TO
364 }
365
a7488080 366 if (!empty($params['oldPremium'])) {
6a488035 367 $premiumParams = array(
21dfd5f5 368 'id' => $params['oldPremium']['product_id'],
6a488035
TO
369 );
370 $productDetails = array();
37828d4f 371 CRM_Contribute_BAO_Product::retrieve($premiumParams, $productDetails);
6a488035
TO
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'],
21dfd5f5 377 'isDeleted' => TRUE,
6a488035
TO
378 );
379 CRM_Core_BAO_FinancialTrxn::createPremiumTrxn($params);
380 }
381 }
c490a46a 382
6a488035 383 /**
fe482240 384 * Create financial trxn and items when fee is charged.
6a488035 385 *
6a0b768e
TO
386 * @param array $params
387 * To create trxn entries.
6a488035 388 *
a2fb4683 389 * @return bool|void
6a488035 390 */
00be9182 391 public static function recordFees($params) {
6a488035
TO
392 $domainId = CRM_Core_Config::domainID();
393 $amount = 0;
a7488080 394 if (!empty($params['prevContribution'])) {
6a488035
TO
395 $amount = $params['prevContribution']->fee_amount;
396 }
397 $amount = $params['fee_amount'] - $amount;
78b79549
PN
398 if (!$amount) {
399 return FALSE;
400 }
39383f5f
PJ
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 }
928a340b 408 $financialAccount = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship($financialTypeId, 'Expense Account is');
39383f5f 409
6a488035
TO
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;
79d7553f 413 $params['trxnParams']['fee_amount'] = $params['trxnParams']['net_amount'] = 0;
76c28c8d 414 $params['trxnParams']['status_id'] = $params['contribution_status_id'];
39383f5f 415 $params['trxnParams']['contribution_id'] = $contributionId;
87647fe2 416 $params['trxnParams']['is_payment'] = FALSE;
6a488035 417 $trxn = self::create($params['trxnParams']);
a7488080 418 if (empty($params['entity_id'])) {
6a488035
TO
419 $financialTrxnID = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['trxnParams']['contribution_id'], 'DESC');
420 $params['entity_id'] = $financialTrxnID['financialTrxnId'];
421 }
79d7553f 422 $fItemParams
423 = array(
6a488035
TO
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',
a28ce73f 430 'status_id' => CRM_Core_Pseudoconstant::getKey('CRM_Financial_BAO_FinancialItem', 'status_id', 'Paid'),
6a488035
TO
431 'entity_table' => 'civicrm_financial_trxn',
432 'entity_id' => $params['entity_id'],
433 'currency' => $params['trxnParams']['currency'],
434 );
435 $trxnIDS['id'] = $trxn->id;
a28ce73f 436 CRM_Financial_BAO_FinancialItem::create($fItemParams, NULL, $trxnIDS);
6a488035 437 }
6a488035 438
b5c2afd0 439 /**
fe482240 440 * get partial payment amount and type of it.
d424ffde 441 *
100fef9d 442 * @param int $entityId
b5c2afd0
EM
443 * @param string $entityName
444 * @param bool $returnType
79d7553f 445 * @param int $lineItemTotal
b5c2afd0 446 *
e60f24eb 447 * @return array|int|NULL|string
d424ffde
CW
448 * [payment type => amount]
449 * payment type: 'amount_owed' or 'refund_due'
b5c2afd0 450 */
00be9182 451 public static function getPartialPaymentWithType($entityId, $entityName = 'participant', $returnType = TRUE, $lineItemTotal = NULL) {
0f602e3f
PJ
452 $value = NULL;
453 if (empty($entityName)) {
454 return $value;
455 }
456
457 if ($entityName == 'participant') {
bc2eeabb 458 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $entityId, 'contribution_id', 'participant_id');
685dc433 459 }
f6e96aa8 460 elseif ($entityName == 'membership') {
461 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $entityId, 'contribution_id', 'membership_id');
462 }
685dc433
PN
463 else {
464 $contributionId = $entityId;
465 }
466 $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
467
468 if ($contributionId && $financialTypeId) {
685dc433 469
26085eab 470 $value = CRM_Contribute_BAO_Contribution::getContributionBalance($contributionId, $lineItemTotal);
471
472 $paymentVal = $value;
685dc433
PN
473 if ($returnType) {
474 $value = array();
475 if ($paymentVal < 0) {
476 $value['refund_due'] = $paymentVal;
bc2eeabb 477 }
685dc433
PN
478 elseif ($paymentVal > 0) {
479 $value['amount_owed'] = $paymentVal;
a3a70377 480 }
0f602e3f
PJ
481 }
482 }
483 return $value;
484 }
96025800 485
3efd9c58
DG
486 /**
487 * @param int $contributionId
488 *
5b541553 489 * @return string
3efd9c58
DG
490 */
491 public static function getTotalPayments($contributionId) {
76c28c8d
DG
492 $statusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
493
494 $sql = "SELECT SUM(ft.total_amount) FROM civicrm_financial_trxn ft
495 INNER JOIN civicrm_entity_financial_trxn eft ON (eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution')
3efd9c58
DG
496 WHERE eft.entity_id = %1 AND ft.is_payment = 1 AND ft.status_id = %2";
497
498 $params = array(
499 1 => array($contributionId, 'Integer'),
500 2 => array($statusId, 'Integer'),
501 );
76c28c8d 502
3efd9c58
DG
503 return CRM_Core_DAO::singleValueQuery($sql, $params);
504 }
505
78c99516 506 /**
a40f5d6b
PN
507 * Function records partial payment, complete's contribution if payment is fully paid
508 * and returns latest payment ie financial trxn
509 *
78c99516
PN
510 * @param array $contribution
511 * @param array $params
512 *
5b541553 513 * @return \CRM_Financial_DAO_FinancialTrxn
78c99516
PN
514 */
515 public static function getPartialPaymentTrxn($contribution, $params) {
516 $trxn = CRM_Contribute_BAO_Contribution::recordPartialPayment($contribution, $params);
517 $paid = CRM_Core_BAO_FinancialTrxn::getTotalPayments($params['contribution_id']);
518 $total = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution_id'], 'total_amount');
519 $cmp = bccomp($total, $paid, 5);
520 if ($cmp == 0 || $cmp == -1) {// If paid amount is greater or equal to total amount
521 civicrm_api3('Contribution', 'completetransaction', array('id' => $contribution['id']));
522 }
523 return $trxn;
524 }
525
f1eab68f
PN
526 /**
527 * Get revenue amount for membership.
528 *
529 * @param array $lineItem
530 *
531 * @return array
532 */
533 public static function getMembershipRevenueAmount($lineItem) {
534 $revenueAmount = array();
535 $membershipDetail = civicrm_api3('Membership', 'getsingle', array(
536 'id' => $lineItem['entity_id'],
537 ));
538 if (empty($membershipDetail['end_date'])) {
539 return $revenueAmount;
540 }
541
542 $startDate = strtotime($membershipDetail['start_date']);
543 $endDate = strtotime($membershipDetail['end_date']);
544 $startYear = date('Y', $startDate);
545 $endYear = date('Y', $endDate);
546 $startMonth = date('m', $startDate);
547 $endMonth = date('m', $endDate);
548
549 $monthOfService = (($endYear - $startYear) * 12) + ($endMonth - $startMonth);
550 $startDateOfRevenue = $membershipDetail['start_date'];
551 $typicalPayment = round(($lineItem['line_total'] / $monthOfService), 2);
552 for ($i = 0; $i <= $monthOfService - 1; $i++) {
553 $revenueAmount[$i]['amount'] = $typicalPayment;
554 if ($i == 0) {
555 $revenueAmount[$i]['amount'] -= (($typicalPayment * $monthOfService) - $lineItem['line_total']);
556 }
557 $revenueAmount[$i]['revenue_date'] = $startDateOfRevenue;
558 $startDateOfRevenue = date('Y-m', strtotime('+1 month', strtotime($startDateOfRevenue))) . '-01';
559 }
560 return $revenueAmount;
561 }
562
6419695f
PN
563 /**
564 * Create transaction for deferred revenue.
565 *
566 * @param array $lineItems
567 *
2ea48796 568 * @param CRM_Contribute_BAO_Contribution $contributionDetails
6419695f
PN
569 *
570 * @param bool $update
571 *
572 * @param string $context
573 *
574 */
575 public static function createDeferredTrxn($lineItems, $contributionDetails, $update = FALSE, $context = NULL) {
576 if (empty($lineItems)) {
2ea48796 577 return;
6419695f
PN
578 }
579 $revenueRecognitionDate = $contributionDetails->revenue_recognition_date;
580 if (!CRM_Utils_System::isNull($revenueRecognitionDate)) {
581 $statuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
582 if (!$update
583 && (CRM_Utils_Array::value($contributionDetails->contribution_status_id, $statuses) != 'Completed'
584 || (CRM_Utils_Array::value($contributionDetails->contribution_status_id, $statuses) != 'Pending'
585 && $contributionDetails->is_pay_later)
586 )
587 ) {
588 return;
589 }
590 $trxnParams = array(
591 'contribution_id' => $contributionDetails->id,
592 'fee_amount' => '0.00',
593 'currency' => $contributionDetails->currency,
594 'trxn_id' => $contributionDetails->trxn_id,
595 'status_id' => $contributionDetails->contribution_status_id,
596 'payment_instrument_id' => $contributionDetails->payment_instrument_id,
597 'check_number' => $contributionDetails->check_number,
6419695f
PN
598 );
599
600 $deferredRevenues = array();
601 foreach ($lineItems as $priceSetID => $lineItem) {
602 if (!$priceSetID) {
603 continue;
604 }
605 foreach ($lineItem as $key => $item) {
8cf6bd83
PN
606 $lineTotal = !empty($item['deferred_line_total']) ? $item['deferred_line_total'] : $item['line_total'];
607 if ($lineTotal <= 0 && !$update) {
6419695f
PN
608 continue;
609 }
610 $deferredRevenues[$key] = $item;
611 if ($context == 'changeFinancialType') {
612 $deferredRevenues[$key]['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_LineItem', $item['id'], 'financial_type_id');
613 }
614 if (in_array($item['entity_table'],
615 array('civicrm_participant', 'civicrm_contribution'))
616 ) {
617 $deferredRevenues[$key]['revenue'][] = array(
8cf6bd83 618 'amount' => $lineTotal,
6419695f
PN
619 'revenue_date' => $revenueRecognitionDate,
620 );
621 }
622 else {
623 // for membership
8cf6bd83 624 $item['line_total'] = $lineTotal;
6419695f
PN
625 $deferredRevenues[$key]['revenue'] = self::getMembershipRevenueAmount($item);
626 }
627 }
628 }
629 $accountRel = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
7340e501 630
7f35de6b 631 CRM_Utils_Hook::alterDeferredRevenueItems($deferredRevenues, $contributionDetails, $update, $context);
7340e501 632
6419695f
PN
633 foreach ($deferredRevenues as $key => $deferredRevenue) {
634 $results = civicrm_api3('EntityFinancialAccount', 'get', array(
635 'entity_table' => 'civicrm_financial_type',
636 'entity_id' => $deferredRevenue['financial_type_id'],
637 'account_relationship' => array('IN' => array('Income Account is', 'Deferred Revenue Account is')),
638 ));
639 if ($results['count'] != 2) {
640 continue;
641 }
642 foreach ($results['values'] as $result) {
643 if ($result['account_relationship'] == $accountRel) {
f818aed5 644 $trxnParams['from_financial_account_id'] = $result['financial_account_id'];
6419695f
PN
645 }
646 else {
f818aed5 647 $trxnParams['to_financial_account_id'] = $result['financial_account_id'];
6419695f
PN
648 }
649 }
650 foreach ($deferredRevenue['revenue'] as $revenue) {
651 $trxnParams['total_amount'] = $trxnParams['net_amount'] = $revenue['amount'];
652 $trxnParams['trxn_date'] = CRM_Utils_Date::isoToMysql($revenue['revenue_date']);
653 $financialTxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
654 $entityParams = array(
655 'entity_id' => $deferredRevenue['financial_item_id'],
656 'entity_table' => 'civicrm_financial_item',
657 'amount' => $revenue['amount'],
658 'financial_trxn_id' => $financialTxn->id,
659 );
660 civicrm_api3('EntityFinancialTrxn', 'create', $entityParams);
661 }
662 }
663 }
664 }
665
2c4a6dc8
PN
666 /**
667 * Update Credit Card Details in civicrm_financial_trxn table.
668 *
669 * @param int $contributionID
670 * @param int $panTruncation
671 * @param int $cardType
672 *
673 */
674 public static function updateCreditCardDetails($contributionID, $panTruncation, $cardType) {
675 $financialTrxn = civicrm_api3('EntityFinancialTrxn', 'get', array(
676 'return' => array('financial_trxn_id.payment_processor_id', 'financial_trxn_id'),
677 'entity_table' => 'civicrm_contribution',
678 'entity_id' => $contributionID,
679 'financial_trxn_id.is_payment' => TRUE,
680 'options' => array('sort' => 'financial_trxn_id DESC', 'limit' => 1),
681 ));
682
1da0f2fe
PN
683 // In case of Contribution status is Pending From Incomplete Transaction or Failed there is no Financial Entries created for Contribution.
684 // Above api will return 0 count, in such case we won't update card type and pan truncation field.
2c4a6dc8
PN
685 if (!$financialTrxn['count']) {
686 return NULL;
687 }
688
689 $financialTrxn = $financialTrxn['values'][$financialTrxn['id']];
690 $paymentProcessorID = CRM_Utils_Array::value('financial_trxn_id.payment_processor_id', $financialTrxn);
691
692 if ($paymentProcessorID) {
693 return NULL;
694 }
695
696 $financialTrxnId = $financialTrxn['financial_trxn_id'];
697 $trxnparams = array('id' => $financialTrxnId);
698 if (isset($cardType)) {
d72b084a 699 $trxnparams['card_type_id'] = $cardType;
2c4a6dc8
PN
700 }
701 if (isset($panTruncation)) {
702 $trxnparams['pan_truncation'] = $panTruncation;
703 }
704 civicrm_api3('FinancialTrxn', 'create', $trxnparams);
705 }
706
5ca657dd 707 /**
708 * The function is responsible for handling financial entries if payment instrument is changed
709 *
710 * @param array $inputParams
711 *
712 */
713 public static function updateFinancialAccountsOnPaymentInstrumentChange($inputParams) {
714 $prevContribution = $inputParams['prevContribution'];
715 $currentContribution = $inputParams['contribution'];
716 // ensure that there are all the information in updated contribution object identified by $currentContribution
717 $currentContribution->find(TRUE);
718
719 $deferredFinancialAccount = CRM_Utils_Array::value('deferred_financial_account_id', $inputParams);
720 if (empty($deferredFinancialAccount)) {
721 $deferredFinancialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($prevContribution->financial_type_id, 'Deferred Revenue Account is');
722 }
723
724 $lastFinancialTrxnId = self::getFinancialTrxnId($prevContribution->id, 'DESC', FALSE, NULL, $deferredFinancialAccount);
725
726 // there is no point to proceed as we can't find the last payment made
b0e806fa 727 // @todo we should throw an exception here rather than return false.
5ca657dd 728 if (empty($lastFinancialTrxnId['financialTrxnId'])) {
729 return FALSE;
730 }
731
732 // If payment instrument is changed reverse the last payment
733 // in terms of reversing financial item and trxn
734 $lastFinancialTrxn = civicrm_api3('FinancialTrxn', 'getsingle', array('id' => $lastFinancialTrxnId['financialTrxnId']));
735 unset($lastFinancialTrxn['id']);
736 $lastFinancialTrxn['trxn_date'] = $inputParams['trxnParams']['trxn_date'];
737 $lastFinancialTrxn['total_amount'] = -$inputParams['trxnParams']['total_amount'];
738 $lastFinancialTrxn['net_amount'] = -$inputParams['trxnParams']['net_amount'];
739 $lastFinancialTrxn['fee_amount'] = -$inputParams['trxnParams']['fee_amount'];
5ca657dd 740 $lastFinancialTrxn['contribution_id'] = $prevContribution->id;
741 foreach (array($lastFinancialTrxn, $inputParams['trxnParams']) as $financialTrxnParams) {
742 $trxn = CRM_Core_BAO_FinancialTrxn::create($financialTrxnParams);
743 $trxnParams = array(
744 'total_amount' => $trxn->total_amount,
745 'contribution_id' => $currentContribution->id,
746 );
747 CRM_Contribute_BAO_Contribution::assignProportionalLineItems($trxnParams, $trxn->id, $prevContribution->total_amount);
748 }
749
750 self::createDeferredTrxn(CRM_Utils_Array::value('line_item', $inputParams), $currentContribution, TRUE, 'changePaymentInstrument');
751
752 return TRUE;
753 }
754
0d8afee2 755}