Merge pull request #4887 from pratikshad/broken-webtest
[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 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 * @static
58 */
59 public static function create(&$params, $trxnEntityTable = NULL) {
60 $trxn = new CRM_Financial_DAO_FinancialTrxn();
61 $trxn->copyValues($params);
62 $fids = array();
63 if (!CRM_Utils_Rule::currencyCode($trxn->currency)) {
64 $config = CRM_Core_Config::singleton();
65 $trxn->currency = $config->defaultCurrency;
66 }
67
68 $trxn->save();
69
70 // save to entity_financial_trxn table
71 $entityFinancialTrxnParams =
72 array(
73 'entity_table' => "civicrm_contribution",
74 'financial_trxn_id' => $trxn->id,
75 'amount' => $params['total_amount'],
76 'currency' => $trxn->currency,
77 );
78
79 if (!empty($trxnEntityTable)) {
80 $entityFinancialTrxnParams['entity_table'] = $trxnEntityTable['entity_table'];
81 $entityFinancialTrxnParams['entity_id'] = $trxnEntityTable['entity_id'];
82 }
83 else {
84 $entityFinancialTrxnParams['entity_id'] = $params['contribution_id'];
85 }
86
87 $entityTrxn = new CRM_Financial_DAO_EntityFinancialTrxn();
88 $entityTrxn->copyValues($entityFinancialTrxnParams);
89 $entityTrxn->save();
90 return $trxn;
91 }
92
93 /**
94 * @param int $contributionId
95 * @param int $contributionFinancialTypeId
96 *
97 * @return array
98 */
99 public static function getBalanceTrxnAmt($contributionId, $contributionFinancialTypeId = NULL) {
100 if (!$contributionFinancialTypeId) {
101 $contributionFinancialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'financial_type_id');
102 }
103 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
104 $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($contributionFinancialTypeId, $relationTypeId);
105 $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";
106
107 $p[1] = array($contributionId, 'Integer');
108 $p[2] = array($toFinancialAccount, 'Integer');
109
110 $balanceAmtDAO = CRM_Core_DAO::executeQuery($q, $p);
111 $ret = array();
112 while ($balanceAmtDAO->fetch()) {
113 $ret['trxn_id'] = $balanceAmtDAO->id;
114 $ret['total_amount'] = $balanceAmtDAO->total_amount;
115 }
116
117 return $ret;
118 }
119
120 /**
121 * Fetch object based on array of properties
122 *
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.
127 *
128 * @return CRM_Contribute_BAO_ContributionType
129 * @static
130 */
131 public static function retrieve(&$params, &$defaults) {
132 $financialItem = new CRM_Financial_DAO_FinancialTrxn();
133 $financialItem->copyValues($params);
134 if ($financialItem->find(TRUE)) {
135 CRM_Core_DAO::storeValues($financialItem, $defaults);
136 return $financialItem;
137 }
138 return NULL;
139 }
140
141 /**
142 * Given an entity_id and entity_table, check for corresponding entity_financial_trxn and financial_trxn record.
143 * NOTE: This should be moved to separate BAO for EntityFinancialTrxn when we start adding more code for that object.
144 *
145 * @param $entity_id
146 * Id of the entity usually the contactID.
147 * @param string $orderBy
148 * To get single trxn id for a entity table i.e last or first.
149 * @param bool $newTrxn
150 *
151 * @return array
152 * array of category id's the contact belongs to.
153 *
154 * @static
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 catagory id's the contact belongs to.
197 *
198 * @static
199 */
200 public static function getFinancialTrxnTotal($entity_id) {
201 $query = "
202 SELECT (ft.amount+SUM(ceft.amount)) AS total FROM civicrm_entity_financial_trxn AS ft
203 LEFT JOIN civicrm_entity_financial_trxn AS ceft ON ft.financial_trxn_id = ceft.entity_id
204 WHERE ft.entity_table = 'civicrm_contribution' AND ft.entity_id = %1
205 ";
206
207 $sqlParams = array(1 => array($entity_id, 'Integer'));
208 return CRM_Core_DAO::singleValueQuery($query, $sqlParams);
209
210 }
211
212 /**
213 * Given an financial_trxn_id check for previous entity_financial_trxn.
214 *
215 * @param $financial_trxn_id
216 * Id of the latest payment.
217 *
218 *
219 * @return array
220 * array of previous payments
221 *
222 * @static
223 */
224 public static function getPayments($financial_trxn_id) {
225 $query = "
226 SELECT ef1.financial_trxn_id, sum(ef1.amount) amount
227 FROM civicrm_entity_financial_trxn ef1
228 LEFT JOIN civicrm_entity_financial_trxn ef2 ON ef1.financial_trxn_id = ef2.entity_id
229 WHERE ef2.financial_trxn_id =%1
230 AND ef2.entity_table = 'civicrm_financial_trxn'
231 AND ef1.entity_table = 'civicrm_financial_item'
232 GROUP BY ef1.financial_trxn_id
233 UNION
234 SELECT ef1.financial_trxn_id, ef1.amount
235 FROM civicrm_entity_financial_trxn ef1
236 LEFT JOIN civicrm_entity_financial_trxn ef2 ON ef1.entity_id = ef2.entity_id
237 WHERE ef2.financial_trxn_id =%1
238 AND ef2.entity_table = 'civicrm_financial_trxn'
239 AND ef1.entity_table = 'civicrm_financial_trxn'";
240
241 $sqlParams = array(1 => array($financial_trxn_id, 'Integer'));
242 $dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
243 $i = 0;
244 $result = array();
245 while ($dao->fetch()) {
246 $result[$i]['financial_trxn_id'] = $dao->financial_trxn_id;
247 $result[$i]['amount'] = $dao->amount;
248 $i++;
249 }
250
251 if (empty($result)) {
252 $query = "SELECT sum( amount ) amount FROM civicrm_entity_financial_trxn WHERE financial_trxn_id =%1 AND entity_table = 'civicrm_financial_item'";
253 $sqlParams = array(1 => array($financial_trxn_id, 'Integer'));
254 $dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
255
256 if ($dao->fetch()) {
257 $result[0]['financial_trxn_id'] = $financial_trxn_id;
258 $result[0]['amount'] = $dao->amount;
259 }
260 }
261 return $result;
262 }
263
264 /**
265 * Given an entity_id and entity_table, check for corresponding entity_financial_trxn and financial_trxn record.
266 * NOTE: This should be moved to separate BAO for EntityFinancialTrxn when we start adding more code for that object.
267 *
268 * @param $entity_id
269 * Id of the entity usually the contactID.
270 * @param string $entity_table
271 * Name of the entity table usually 'civicrm_contact'.
272 *
273 * @return array
274 * array of catagory id's the contact belongs to.
275 *
276 * @static
277 */
278 public static function getFinancialTrxnLineTotal($entity_id, $entity_table = 'civicrm_contribution') {
279 $query = "SELECT lt.price_field_value_id AS id, ft.financial_trxn_id,ft.amount AS amount FROM civicrm_entity_financial_trxn AS ft
280 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'
281 LEFT JOIN civicrm_line_item AS lt ON lt.id = fi.entity_id AND lt.entity_table = %2
282 WHERE lt.entity_id = %1 ";
283
284 $sqlParams = array(1 => array($entity_id, 'Integer'), 2 => array($entity_table, 'String'));
285 $dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
286 while ($dao->fetch()) {
287 $result[$dao->financial_trxn_id][$dao->id] = $dao->amount;
288 }
289 if (!empty($result)) {
290 return $result;
291 }
292 else {
293 return NULL;
294 }
295 }
296
297 /**
298 * Delete financial transaction
299 *
300 * @param int $entity_id
301 * @return bool
302 * TRUE on success, FALSE otherwise.
303 * @static
304 */
305 public static function deleteFinancialTrxn($entity_id) {
306 $query = "DELETE ceft1, cfi, ceft, cft FROM `civicrm_financial_trxn` cft
307 LEFT JOIN civicrm_entity_financial_trxn ceft
308 ON ceft.financial_trxn_id = cft.id AND ceft.entity_table = 'civicrm_contribution'
309 LEFT JOIN civicrm_entity_financial_trxn ceft1
310 ON ceft1.financial_trxn_id = cft.id AND ceft1.entity_table = 'civicrm_financial_item'
311 LEFT JOIN civicrm_financial_item cfi
312 ON ceft1.entity_table = 'civicrm_financial_item' and cfi.id = ceft1.entity_id
313 WHERE ceft.entity_id = %1";
314 CRM_Core_DAO::executeQuery($query, array(1 => array($entity_id, 'Integer')));
315 return TRUE;
316 }
317
318 /**
319 * Create financial transaction for premium
320 *
321 * @static
322 */
323 public static function createPremiumTrxn($params) {
324 if ((empty($params['financial_type_id']) || empty($params['contributionId'])) && empty($params['oldPremium'])) {
325 return;
326 }
327
328 if (!empty($params['cost'])) {
329 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
330 $financialAccountType = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id']);
331 $accountRelationship = CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND label IN ('Premiums Inventory Account is', 'Cost of Sales Account is')");
332 $toFinancialAccount = !empty($params['isDeleted']) ? 'Premiums Inventory Account is' : 'Cost of Sales Account is';
333 $fromFinancialAccount = !empty($params['isDeleted']) ? 'Cost of Sales Account is' : 'Premiums Inventory Account is';
334 $accountRelationship = array_flip($accountRelationship);
335 $financialtrxn = array(
336 'to_financial_account_id' => $financialAccountType[$accountRelationship[$toFinancialAccount]],
337 'from_financial_account_id' => $financialAccountType[$accountRelationship[$fromFinancialAccount]],
338 'trxn_date' => date('YmdHis'),
339 'total_amount' => CRM_Utils_Array::value('cost', $params) ? $params['cost'] : 0,
340 'currency' => CRM_Utils_Array::value('currency', $params),
341 'status_id' => array_search('Completed', $contributionStatuses),
342 );
343 $trxnEntityTable['entity_table'] = 'civicrm_contribution';
344 $trxnEntityTable['entity_id'] = $params['contributionId'];
345 CRM_Core_BAO_FinancialTrxn::create($financialtrxn, $trxnEntityTable);
346 }
347
348 if (!empty($params['oldPremium'])) {
349 $premiumParams = array(
350 'id' => $params['oldPremium']['product_id'],
351 );
352 $productDetails = array();
353 CRM_Contribute_BAO_ManagePremiums::retrieve($premiumParams, $productDetails);
354 $params = array(
355 'cost' => CRM_Utils_Array::value('cost', $productDetails),
356 'currency' => CRM_Utils_Array::value('currency', $productDetails),
357 'financial_type_id' => CRM_Utils_Array::value('financial_type_id', $productDetails),
358 'contributionId' => $params['oldPremium']['contribution_id'],
359 'isDeleted' => TRUE,
360 );
361 CRM_Core_BAO_FinancialTrxn::createPremiumTrxn($params);
362 }
363 }
364
365 /**
366 * Create financial trxn and items when fee is charged
367 *
368 * @param array $params
369 * To create trxn entries.
370 *
371 * @static
372 */
373 public static function recordFees($params) {
374 $expenseTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
375 $domainId = CRM_Core_Config::domainID();
376 $amount = 0;
377 if (!empty($params['prevContribution'])) {
378 $amount = $params['prevContribution']->fee_amount;
379 }
380 $amount = $params['fee_amount'] - $amount;
381 if (!$amount) {
382 return FALSE;
383 }
384 $contributionId = isset($params['contribution']->id) ? $params['contribution']->id : $params['contribution_id'];
385 if (empty($params['financial_type_id'])) {
386 $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id', 'id');
387 }
388 else {
389 $financialTypeId = $params['financial_type_id'];
390 }
391 $financialAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $expenseTypeId);
392
393 $params['trxnParams']['from_financial_account_id'] = $params['to_financial_account_id'];
394 $params['trxnParams']['to_financial_account_id'] = $financialAccount;
395 $params['trxnParams']['total_amount'] = $amount;
396 $params['trxnParams']['fee_amount'] =
397 $params['trxnParams']['net_amount'] = 0;
398 $params['trxnParams']['status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
399 $params['trxnParams']['contribution_id'] = $contributionId;
400 $trxn = self::create($params['trxnParams']);
401 if (empty($params['entity_id'])) {
402 $financialTrxnID = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['trxnParams']['contribution_id'], 'DESC');
403 $params['entity_id'] = $financialTrxnID['financialTrxnId'];
404 }
405 $fItemParams =
406 array(
407 'financial_account_id' => $financialAccount,
408 'contact_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Domain', $domainId, 'contact_id'),
409 'created_date' => date('YmdHis'),
410 'transaction_date' => date('YmdHis'),
411 'amount' => $amount,
412 'description' => 'Fee',
413 'status_id' => CRM_Core_OptionGroup::getValue('financial_item_status', 'Paid', 'name'),
414 'entity_table' => 'civicrm_financial_trxn',
415 'entity_id' => $params['entity_id'],
416 'currency' => $params['trxnParams']['currency'],
417 );
418 $trxnIDS['id'] = $trxn->id;
419 $financialItem = CRM_Financial_BAO_FinancialItem::create($fItemParams, NULL, $trxnIDS);
420 }
421
422 /*
423 * get partial payment amount and type of it
424 * return @array : payment type => amount
425 * payment type : 'amount_owed' or 'refund_due'
426 */
427 /**
428 * @param int $entityId
429 * @param string $entityName
430 * @param bool $returnType
431 * @param NULL $lineItemTotal
432 *
433 * @return array|int|NULL|string
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 }