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