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