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