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