Merge pull request #6539 from joannechester/CRM-16185-rename-date-filters
[civicrm-core.git] / CRM / Core / BAO / FinancialTrxn.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2015
32 * $Id$
33 *
34 */
35 class CRM_Core_BAO_FinancialTrxn extends CRM_Financial_DAO_FinancialTrxn {
36 /**
37 * Class constructor.
38 *
39 * @return \CRM_Financial_DAO_FinancialTrxn
40 */
41 /**
42 */
43 public function __construct() {
44 parent::__construct();
45 }
46
47 /**
48 * Takes an associative array and creates a financial transaction object.
49 *
50 * @param array $params
51 * (reference ) an assoc array of name/value pairs.
52 *
53 * @param string $trxnEntityTable
54 * Entity_table.
55 *
56 * @return CRM_Core_BAO_FinancialTrxn
57 */
58 public static function create(&$params, $trxnEntityTable = NULL) {
59 $trxn = new CRM_Financial_DAO_FinancialTrxn();
60 $trxn->copyValues($params);
61 $fids = array();
62 if (!CRM_Utils_Rule::currencyCode($trxn->currency)) {
63 $config = CRM_Core_Config::singleton();
64 $trxn->currency = $config->defaultCurrency;
65 }
66
67 $trxn->save();
68
69 // save to entity_financial_trxn table
70 $entityFinancialTrxnParams
71 = array(
72 'entity_table' => "civicrm_contribution",
73 'financial_trxn_id' => $trxn->id,
74 'amount' => $params['total_amount'],
75 'currency' => $trxn->currency,
76 );
77
78 if (!empty($trxnEntityTable)) {
79 $entityFinancialTrxnParams['entity_table'] = $trxnEntityTable['entity_table'];
80 $entityFinancialTrxnParams['entity_id'] = $trxnEntityTable['entity_id'];
81 }
82 else {
83 $entityFinancialTrxnParams['entity_id'] = $params['contribution_id'];
84 }
85
86 $entityTrxn = new CRM_Financial_DAO_EntityFinancialTrxn();
87 $entityTrxn->copyValues($entityFinancialTrxnParams);
88 $entityTrxn->save();
89 return $trxn;
90 }
91
92 /**
93 * @param int $contributionId
94 * @param int $contributionFinancialTypeId
95 *
96 * @return array
97 */
98 public static function getBalanceTrxnAmt($contributionId, $contributionFinancialTypeId = NULL) {
99 if (!$contributionFinancialTypeId) {
100 $contributionFinancialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'financial_type_id');
101 }
102 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
103 $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($contributionFinancialTypeId, $relationTypeId);
104 $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";
105
106 $p[1] = array($contributionId, 'Integer');
107 $p[2] = array($toFinancialAccount, 'Integer');
108
109 $balanceAmtDAO = CRM_Core_DAO::executeQuery($q, $p);
110 $ret = array();
111 if ($balanceAmtDAO->N) {
112 $ret['total_amount'] = 0;
113 }
114 while ($balanceAmtDAO->fetch()) {
115 $ret['trxn_id'] = $balanceAmtDAO->id;
116 $ret['total_amount'] += $balanceAmtDAO->total_amount;
117 }
118
119 return $ret;
120 }
121
122 /**
123 * Fetch object based on array of properties.
124 *
125 * @param array $params
126 * (reference ) an assoc array of name/value pairs.
127 * @param array $defaults
128 * (reference ) an assoc array to hold the flattened values.
129 *
130 * @return CRM_Contribute_BAO_ContributionType
131 */
132 public static function retrieve(&$params, &$defaults) {
133 $financialItem = new CRM_Financial_DAO_FinancialTrxn();
134 $financialItem->copyValues($params);
135 if ($financialItem->find(TRUE)) {
136 CRM_Core_DAO::storeValues($financialItem, $defaults);
137 return $financialItem;
138 }
139 return NULL;
140 }
141
142 /**
143 * Given an entity_id and entity_table, check for corresponding entity_financial_trxn and financial_trxn record.
144 * NOTE: This should be moved to separate BAO for EntityFinancialTrxn when we start adding more code for that object.
145 *
146 * @param $entity_id
147 * Id of the entity usually the contactID.
148 * @param string $orderBy
149 * To get single trxn id for a entity table i.e last or first.
150 * @param bool $newTrxn
151 *
152 * @return array
153 * array of category id's the contact belongs to.
154 *
155 */
156 public static function getFinancialTrxnId($entity_id, $orderBy = 'ASC', $newTrxn = FALSE) {
157 $ids = array('entityFinancialTrxnId' => NULL, 'financialTrxnId' => NULL);
158
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 }
163
164 if ($orderBy) {
165 $orderBy = CRM_Utils_Type::escape($orderBy, 'String');
166 }
167
168 $query = "SELECT ceft.id, ceft.financial_trxn_id FROM `civicrm_financial_trxn` cft
169 LEFT JOIN civicrm_entity_financial_trxn ceft
170 ON ceft.financial_trxn_id = cft.id AND ceft.entity_table = 'civicrm_contribution'
171 LEFT JOIN civicrm_entity_financial_trxn ceft1
172 ON ceft1.financial_trxn_id = cft.id AND ceft1.entity_table = 'civicrm_financial_item'
173 LEFT JOIN civicrm_financial_item cfi ON ceft1.entity_table = 'civicrm_financial_item' and cfi.id = ceft1.entity_id
174 WHERE ceft.entity_id = %1 AND (cfi.entity_table <> 'civicrm_financial_trxn' or cfi.entity_table is NULL)
175 {$condition}
176 ORDER BY cft.id {$orderBy}
177 LIMIT 1;";
178
179 $params = array(1 => array($entity_id, 'Integer'));
180 $dao = CRM_Core_DAO::executeQuery($query, $params);
181 if ($dao->fetch()) {
182 $ids['entityFinancialTrxnId'] = $dao->id;
183 $ids['financialTrxnId'] = $dao->financial_trxn_id;
184 }
185 return $ids;
186 }
187
188 /**
189 * Given an entity_id and entity_table, check for corresponding entity_financial_trxn and financial_trxn record.
190 * @todo This should be moved to separate BAO for EntityFinancialTrxn when we start adding more code for that object.
191 *
192 * @param int $entity_id
193 * Id of the entity usually the contactID.
194 *
195 * @return array
196 * array of category id's the contact belongs to.
197 *
198 */
199 public static function getFinancialTrxnTotal($entity_id) {
200 $query = "
201 SELECT (ft.amount+SUM(ceft.amount)) AS total FROM civicrm_entity_financial_trxn AS ft
202 LEFT JOIN civicrm_entity_financial_trxn AS ceft ON ft.financial_trxn_id = ceft.entity_id
203 WHERE ft.entity_table = 'civicrm_contribution' AND ft.entity_id = %1
204 ";
205
206 $sqlParams = array(1 => array($entity_id, 'Integer'));
207 return CRM_Core_DAO::singleValueQuery($query, $sqlParams);
208
209 }
210
211 /**
212 * Given an financial_trxn_id check for previous entity_financial_trxn.
213 *
214 * @param $financial_trxn_id
215 * Id of the latest payment.
216 *
217 *
218 * @return array
219 * array of previous payments
220 *
221 */
222 public static function getPayments($financial_trxn_id) {
223 $query = "
224 SELECT ef1.financial_trxn_id, sum(ef1.amount) amount
225 FROM civicrm_entity_financial_trxn ef1
226 LEFT JOIN civicrm_entity_financial_trxn ef2 ON ef1.financial_trxn_id = ef2.entity_id
227 WHERE ef2.financial_trxn_id =%1
228 AND ef2.entity_table = 'civicrm_financial_trxn'
229 AND ef1.entity_table = 'civicrm_financial_item'
230 GROUP BY ef1.financial_trxn_id
231 UNION
232 SELECT ef1.financial_trxn_id, ef1.amount
233 FROM civicrm_entity_financial_trxn ef1
234 LEFT JOIN civicrm_entity_financial_trxn ef2 ON ef1.entity_id = ef2.entity_id
235 WHERE ef2.financial_trxn_id =%1
236 AND ef2.entity_table = 'civicrm_financial_trxn'
237 AND ef1.entity_table = 'civicrm_financial_trxn'";
238
239 $sqlParams = array(1 => array($financial_trxn_id, 'Integer'));
240 $dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
241 $i = 0;
242 $result = array();
243 while ($dao->fetch()) {
244 $result[$i]['financial_trxn_id'] = $dao->financial_trxn_id;
245 $result[$i]['amount'] = $dao->amount;
246 $i++;
247 }
248
249 if (empty($result)) {
250 $query = "SELECT sum( amount ) amount FROM civicrm_entity_financial_trxn WHERE financial_trxn_id =%1 AND entity_table = 'civicrm_financial_item'";
251 $sqlParams = array(1 => array($financial_trxn_id, 'Integer'));
252 $dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
253
254 if ($dao->fetch()) {
255 $result[0]['financial_trxn_id'] = $financial_trxn_id;
256 $result[0]['amount'] = $dao->amount;
257 }
258 }
259 return $result;
260 }
261
262 /**
263 * Given an entity_id and entity_table, check for corresponding entity_financial_trxn and financial_trxn record.
264 * NOTE: This should be moved to separate BAO for EntityFinancialTrxn when we start adding more code for that object.
265 *
266 * @param $entity_id
267 * Id of the entity usually the contactID.
268 * @param string $entity_table
269 * Name of the entity table usually 'civicrm_contact'.
270 *
271 * @return array
272 * array of category id's the contact belongs to.
273 *
274 */
275 public static function getFinancialTrxnLineTotal($entity_id, $entity_table = 'civicrm_contribution') {
276 $query = "SELECT lt.price_field_value_id AS id, ft.financial_trxn_id,ft.amount AS amount FROM civicrm_entity_financial_trxn AS ft
277 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'
278 LEFT JOIN civicrm_line_item AS lt ON lt.id = fi.entity_id AND lt.entity_table = %2
279 WHERE lt.entity_id = %1 ";
280
281 $sqlParams = array(1 => array($entity_id, 'Integer'), 2 => array($entity_table, 'String'));
282 $dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
283 while ($dao->fetch()) {
284 $result[$dao->financial_trxn_id][$dao->id] = $dao->amount;
285 }
286 if (!empty($result)) {
287 return $result;
288 }
289 else {
290 return NULL;
291 }
292 }
293
294 /**
295 * Delete financial transaction.
296 *
297 * @param int $entity_id
298 * @return bool
299 * TRUE on success, FALSE otherwise.
300 */
301 public static function deleteFinancialTrxn($entity_id) {
302 $query = "DELETE ceft1, cfi, ceft, cft FROM `civicrm_financial_trxn` cft
303 LEFT JOIN civicrm_entity_financial_trxn ceft
304 ON ceft.financial_trxn_id = cft.id AND ceft.entity_table = 'civicrm_contribution'
305 LEFT JOIN civicrm_entity_financial_trxn ceft1
306 ON ceft1.financial_trxn_id = cft.id AND ceft1.entity_table = 'civicrm_financial_item'
307 LEFT JOIN civicrm_financial_item cfi
308 ON ceft1.entity_table = 'civicrm_financial_item' and cfi.id = ceft1.entity_id
309 WHERE ceft.entity_id = %1";
310 CRM_Core_DAO::executeQuery($query, array(1 => array($entity_id, 'Integer')));
311 return TRUE;
312 }
313
314 /**
315 * Create financial transaction for premium.
316 *
317 * @param array $params
318 * - oldPremium
319 * - financial_type_id
320 * - contributionId
321 * - isDeleted
322 * - cost
323 * - currency
324 */
325 public static function createPremiumTrxn($params) {
326 if ((empty($params['financial_type_id']) || empty($params['contributionId'])) && empty($params['oldPremium'])) {
327 return;
328 }
329
330 if (!empty($params['cost'])) {
331 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
332 $financialAccountType = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id']);
333 $accountRelationship = CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND label IN ('Premiums Inventory Account is', 'Cost of Sales Account is')");
334 $toFinancialAccount = !empty($params['isDeleted']) ? 'Premiums Inventory Account is' : 'Cost of Sales Account is';
335 $fromFinancialAccount = !empty($params['isDeleted']) ? 'Cost of Sales Account is' : 'Premiums Inventory Account is';
336 $accountRelationship = array_flip($accountRelationship);
337 $financialtrxn = array(
338 'to_financial_account_id' => $financialAccountType[$accountRelationship[$toFinancialAccount]],
339 'from_financial_account_id' => $financialAccountType[$accountRelationship[$fromFinancialAccount]],
340 'trxn_date' => date('YmdHis'),
341 'total_amount' => CRM_Utils_Array::value('cost', $params) ? $params['cost'] : 0,
342 'currency' => CRM_Utils_Array::value('currency', $params),
343 'status_id' => array_search('Completed', $contributionStatuses),
344 );
345 $trxnEntityTable['entity_table'] = 'civicrm_contribution';
346 $trxnEntityTable['entity_id'] = $params['contributionId'];
347 CRM_Core_BAO_FinancialTrxn::create($financialtrxn, $trxnEntityTable);
348 }
349
350 if (!empty($params['oldPremium'])) {
351 $premiumParams = array(
352 'id' => $params['oldPremium']['product_id'],
353 );
354 $productDetails = array();
355 CRM_Contribute_BAO_ManagePremiums::retrieve($premiumParams, $productDetails);
356 $params = array(
357 'cost' => CRM_Utils_Array::value('cost', $productDetails),
358 'currency' => CRM_Utils_Array::value('currency', $productDetails),
359 'financial_type_id' => CRM_Utils_Array::value('financial_type_id', $productDetails),
360 'contributionId' => $params['oldPremium']['contribution_id'],
361 'isDeleted' => TRUE,
362 );
363 CRM_Core_BAO_FinancialTrxn::createPremiumTrxn($params);
364 }
365 }
366
367 /**
368 * Create financial trxn and items when fee is charged.
369 *
370 * @param array $params
371 * To create trxn entries.
372 *
373 * @return bool
374 */
375 public static function recordFees($params) {
376 $expenseTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
377 $domainId = CRM_Core_Config::domainID();
378 $amount = 0;
379 if (!empty($params['prevContribution'])) {
380 $amount = $params['prevContribution']->fee_amount;
381 }
382 $amount = $params['fee_amount'] - $amount;
383 if (!$amount) {
384 return FALSE;
385 }
386 $contributionId = isset($params['contribution']->id) ? $params['contribution']->id : $params['contribution_id'];
387 if (empty($params['financial_type_id'])) {
388 $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id', 'id');
389 }
390 else {
391 $financialTypeId = $params['financial_type_id'];
392 }
393 $financialAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $expenseTypeId);
394
395 $params['trxnParams']['from_financial_account_id'] = $params['to_financial_account_id'];
396 $params['trxnParams']['to_financial_account_id'] = $financialAccount;
397 $params['trxnParams']['total_amount'] = $amount;
398 $params['trxnParams']['fee_amount'] = $params['trxnParams']['net_amount'] = 0;
399 $params['trxnParams']['status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
400 $params['trxnParams']['contribution_id'] = $contributionId;
401 $trxn = self::create($params['trxnParams']);
402 if (empty($params['entity_id'])) {
403 $financialTrxnID = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['trxnParams']['contribution_id'], 'DESC');
404 $params['entity_id'] = $financialTrxnID['financialTrxnId'];
405 }
406 $fItemParams
407 = array(
408 'financial_account_id' => $financialAccount,
409 'contact_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Domain', $domainId, 'contact_id'),
410 'created_date' => date('YmdHis'),
411 'transaction_date' => date('YmdHis'),
412 'amount' => $amount,
413 'description' => 'Fee',
414 'status_id' => CRM_Core_OptionGroup::getValue('financial_item_status', 'Paid', 'name'),
415 'entity_table' => 'civicrm_financial_trxn',
416 'entity_id' => $params['entity_id'],
417 'currency' => $params['trxnParams']['currency'],
418 );
419 $trxnIDS['id'] = $trxn->id;
420 $financialItem = CRM_Financial_BAO_FinancialItem::create($fItemParams, NULL, $trxnIDS);
421 }
422
423 /**
424 * get partial payment amount and type of it.
425 *
426 * @param int $entityId
427 * @param string $entityName
428 * @param bool $returnType
429 * @param int $lineItemTotal
430 *
431 * @return array|int|NULL|string
432 * [payment type => amount]
433 * payment type: 'amount_owed' or 'refund_due'
434 */
435 public static function getPartialPaymentWithType($entityId, $entityName = 'participant', $returnType = TRUE, $lineItemTotal = NULL) {
436 $value = NULL;
437 if (empty($entityName)) {
438 return $value;
439 }
440
441 if ($entityName == 'participant') {
442 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $entityId, 'contribution_id', 'participant_id');
443 $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
444
445 if ($contributionId && $financialTypeId) {
446 $statusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
447 $refundStatusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name');
448
449 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
450 $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $relationTypeId);
451 $feeRelationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
452 $feeFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $feeRelationTypeId);
453
454 if (empty($lineItemTotal)) {
455 $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
456 if (count($ids) > 1) {
457 $total = 0;
458 foreach ($ids as $val) {
459 $total += CRM_Price_BAO_LineItem::getLineTotal($val, 'civicrm_participant');
460 }
461 $lineItemTotal = $total;
462 }
463 else {
464 $lineItemTotal = CRM_Price_BAO_LineItem::getLineTotal($entityId, 'civicrm_participant');
465 }
466 }
467 $sqlFtTotalAmt = "
468 SELECT SUM(ft.total_amount)
469 FROM civicrm_financial_trxn ft
470 LEFT JOIN civicrm_entity_financial_trxn eft ON (ft.id = eft.financial_trxn_id AND eft.entity_table = 'civicrm_contribution')
471 LEFT JOIN civicrm_contribution c ON (eft.entity_id = c.id)
472 LEFT JOIN civicrm_participant_payment pp ON (pp.contribution_id = c.id)
473 WHERE pp.participant_id = {$entityId} AND ft.to_financial_account_id != {$toFinancialAccount} AND ft.to_financial_account_id != {$feeFinancialAccount}
474 AND ft.status_id IN ({$statusId}, {$refundStatusId})
475 ";
476 $ftTotalAmt = CRM_Core_DAO::singleValueQuery($sqlFtTotalAmt);
477 $value = 0;
478 if ($ftTotalAmt) {
479 $value = $paymentVal = $lineItemTotal - $ftTotalAmt;
480 }
481 if ($returnType) {
482 $value = array();
483 if ($paymentVal < 0) {
484 $value['refund_due'] = $paymentVal;
485 }
486 elseif ($paymentVal > 0) {
487 $value['amount_owed'] = $paymentVal;
488 }
489 elseif ($lineItemTotal == $ftTotalAmt) {
490 $value['full_paid'] = $ftTotalAmt;
491 }
492 }
493 }
494 }
495 return $value;
496 }
497
498 }