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