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