Merge pull request #3209 from eileenmcnaughton/comments
[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 *
136 * @param string $entityTable name of the entity table usually 'civicrm_contact'
137 * @param int $entityID id of the entity usually the contactID.
138 * @param string $orderBy to get single trxn id for a entity table i.e last or first.
139 *
140 * @return array( ) reference $tag array of catagory id's the contact belongs to.
141 *
142 * @access public
143 * @static
144 */
145 static function getFinancialTrxnId($entity_id, $orderBy = 'ASC', $newTrxn = FALSE) {
146 $ids = array('entityFinancialTrxnId' => NULL, 'financialTrxnId' => NULL);
147
148 $condition = "";
149 if (!$newTrxn) {
150 $condition = " AND ((ceft1.entity_table IS NOT NULL) OR (cft.payment_instrument_id IS NOT NULL AND ceft1.entity_table IS NULL)) ";
151 }
21d32567
DL
152
153 if ($orderBy) {
154 $orderBy = CRM_Utils_Type::escape($orderBy, 'String');
155 }
156
6a488035 157 $query = "SELECT ceft.id, ceft.financial_trxn_id FROM `civicrm_financial_trxn` cft
cbb7c7e0 158LEFT JOIN civicrm_entity_financial_trxn ceft
6a488035
TO
159ON ceft.financial_trxn_id = cft.id AND ceft.entity_table = 'civicrm_contribution'
160LEFT JOIN civicrm_entity_financial_trxn ceft1
161ON ceft1.financial_trxn_id = cft.id AND ceft1.entity_table = 'civicrm_financial_item'
162LEFT JOIN civicrm_financial_item cfi ON ceft1.entity_table = 'civicrm_financial_item' and cfi.id = ceft1.entity_id
163WHERE ceft.entity_id = %1 AND (cfi.entity_table <> 'civicrm_financial_trxn' or cfi.entity_table is NULL)
164{$condition}
165ORDER BY cft.id {$orderBy}
cbb7c7e0 166LIMIT 1;";
167
6a488035
TO
168 $params = array(1 => array($entity_id, 'Integer'));
169 $dao = CRM_Core_DAO::executeQuery($query, $params);
170 if ($dao->fetch()) {
171 $ids['entityFinancialTrxnId'] = $dao->id;
172 $ids['financialTrxnId'] = $dao->financial_trxn_id;
173 }
174 return $ids;
175 }
176
177 /**
178 * Given an entity_id and entity_table, check for corresponding entity_financial_trxn and financial_trxn record.
179 * NOTE: This should be moved to separate BAO for EntityFinancialTrxn when we start adding more code for that object.
180 *
181 * @param string $entityTable name of the entity table usually 'civicrm_contact'
182 * @param int $entityID id of the entity usually the contactID.
183 *
184 * @return array( ) reference $tag array of catagory id's the contact belongs to.
185 *
186 * @access public
187 * @static
188 */
189 static function getFinancialTrxnTotal($entity_id) {
190 $query = "
191 SELECT (ft.amount+SUM(ceft.amount)) AS total FROM civicrm_entity_financial_trxn AS ft
cbb7c7e0 192LEFT JOIN civicrm_entity_financial_trxn AS ceft ON ft.financial_trxn_id = ceft.entity_id
6a488035
TO
193WHERE ft.entity_table = 'civicrm_contribution' AND ft.entity_id = %1
194 ";
195
196 $sqlParams = array(1 => array($entity_id, 'Integer'));
197 return CRM_Core_DAO::singleValueQuery($query, $sqlParams);
198
199 }
77b97be7 200
6a488035
TO
201 /**
202 * Given an financial_trxn_id check for previous entity_financial_trxn.
203 *
77b97be7
EM
204 * @param $financial_trxn_id
205 *
206 * @internal param int $financialTrxn_id id of the latest payment.
6a488035
TO
207 *
208 * @return array( ) $payment array of previous payments
209 *
210 * @access public
211 * @static
212 */
213 static function getPayments($financial_trxn_id) {
214 $query = "
215SELECT ef1.financial_trxn_id, sum(ef1.amount) amount
216FROM civicrm_entity_financial_trxn ef1
217LEFT JOIN civicrm_entity_financial_trxn ef2 ON ef1.financial_trxn_id = ef2.entity_id
218WHERE ef2.financial_trxn_id =%1
219 AND ef2.entity_table = 'civicrm_financial_trxn'
220 AND ef1.entity_table = 'civicrm_financial_item'
221GROUP BY ef1.financial_trxn_id
222UNION
223SELECT ef1.financial_trxn_id, ef1.amount
224FROM civicrm_entity_financial_trxn ef1
225LEFT JOIN civicrm_entity_financial_trxn ef2 ON ef1.entity_id = ef2.entity_id
226WHERE ef2.financial_trxn_id =%1
227 AND ef2.entity_table = 'civicrm_financial_trxn'
228 AND ef1.entity_table = 'civicrm_financial_trxn'";
229
230 $sqlParams = array(1 => array($financial_trxn_id, 'Integer'));
231 $dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
232 $i = 0;
233 $result = array();
234 while ($dao->fetch()) {
235 $result[$i]['financial_trxn_id'] = $dao->financial_trxn_id;
236 $result[$i]['amount'] = $dao->amount;
237 $i++;
238 }
239
240 if (empty($result)) {
241 $query = "SELECT sum( amount ) amount FROM civicrm_entity_financial_trxn WHERE financial_trxn_id =%1 AND entity_table = 'civicrm_financial_item'";
242 $sqlParams = array(1 => array($financial_trxn_id, 'Integer'));
243 $dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
244
245 if ($dao->fetch()) {
246 $result[0]['financial_trxn_id'] = $financial_trxn_id;
247 $result[0]['amount'] = $dao->amount;
248 }
249 }
250 return $result;
251 }
252
253 /**
254 * Given an entity_id and entity_table, check for corresponding entity_financial_trxn and financial_trxn record.
255 * NOTE: This should be moved to separate BAO for EntityFinancialTrxn when we start adding more code for that object.
256 *
77b97be7
EM
257 * @param $entity_id
258 * @param string $entity_table
259 *
260 * @internal param string $entityTable name of the entity table usually 'civicrm_contact'
261 * @internal param int $entityID id of the entity usually the contactID.
6a488035
TO
262 *
263 * @return array( ) reference $tag array of catagory id's the contact belongs to.
264 *
265 * @access public
266 * @static
267 */
268 static function getFinancialTrxnLineTotal($entity_id, $entity_table = 'civicrm_contribution') {
269 $query = "SELECT lt.price_field_value_id AS id, ft.financial_trxn_id,ft.amount AS amount FROM civicrm_entity_financial_trxn AS ft
270LEFT 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 271LEFT JOIN civicrm_line_item AS lt ON lt.id = fi.entity_id AND lt.entity_table = %2
6a488035
TO
272WHERE lt.entity_id = %1 ";
273
274 $sqlParams = array(1 => array($entity_id, 'Integer'), 2 => array($entity_table, 'String'));
275 $dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
276 while($dao->fetch()){
277 $result[$dao->financial_trxn_id][$dao->id] = $dao->amount;
278 }
279 if (!empty($result)) {
280 return $result;
281 }
282 else {
283 return null;
284 }
285 }
286
287 /**
288 * Delete financial transaction
289 *
290 * @return true on success, false otherwise
291 * @access public
292 * @static
293 */
294 static function deleteFinancialTrxn($entity_id) {
de1c25e1 295 $query = "DELETE ceft1, cfi, ceft, cft FROM `civicrm_financial_trxn` cft
cbb7c7e0 296LEFT JOIN civicrm_entity_financial_trxn ceft
de1c25e1
PN
297 ON ceft.financial_trxn_id = cft.id AND ceft.entity_table = 'civicrm_contribution'
298LEFT JOIN civicrm_entity_financial_trxn ceft1
299 ON ceft1.financial_trxn_id = cft.id AND ceft1.entity_table = 'civicrm_financial_item'
cbb7c7e0 300LEFT JOIN civicrm_financial_item cfi
de1c25e1
PN
301 ON ceft1.entity_table = 'civicrm_financial_item' and cfi.id = ceft1.entity_id
302WHERE ceft.entity_id = %1";
303 CRM_Core_DAO::executeQuery($query, array(1 => array($entity_id, 'Integer')));
304 return TRUE;
6a488035
TO
305 }
306
307 /**
308 * create financial transaction for premium
309 *
310 * @access public
311 * @static
312 */
313 static function createPremiumTrxn($params) {
8cc574cf 314 if ((empty($params['financial_type_id']) || empty($params['contributionId'])) && empty($params['oldPremium'])) {
6a488035
TO
315 return;
316 }
cbb7c7e0 317
a7488080 318 if (!empty($params['cost'])) {
6a488035
TO
319 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
320 $financialAccountType = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id']);
f743a6eb 321 $accountRelationship = CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND label IN ('Premiums Inventory Account is', 'Cost of Sales Account is')");
0d8afee2
CW
322 $toFinancialAccount = !empty($params['isDeleted']) ? 'Premiums Inventory Account is' : 'Cost of Sales Account is';
323 $fromFinancialAccount = !empty($params['isDeleted']) ? 'Cost of Sales Account is': 'Premiums Inventory Account is';
6a488035
TO
324 $accountRelationship = array_flip($accountRelationship);
325 $financialtrxn = array(
326 'to_financial_account_id' => $financialAccountType[$accountRelationship[$toFinancialAccount]],
327 'from_financial_account_id' => $financialAccountType[$accountRelationship[$fromFinancialAccount]],
328 'trxn_date' => date('YmdHis'),
329 'total_amount' => CRM_Utils_Array::value('cost', $params) ? $params['cost'] : 0,
330 'currency' => CRM_Utils_Array::value('currency', $params),
331 'status_id' => array_search('Completed', $contributionStatuses)
332 );
333 $trxnEntityTable['entity_table'] = 'civicrm_contribution';
334 $trxnEntityTable['entity_id'] = $params['contributionId'];
335 CRM_Core_BAO_FinancialTrxn::create($financialtrxn, $trxnEntityTable);
336 }
337
a7488080 338 if (!empty($params['oldPremium'])) {
6a488035
TO
339 $premiumParams = array(
340 'id' => $params['oldPremium']['product_id']
341 );
342 $productDetails = array();
343 CRM_Contribute_BAO_ManagePremiums::retrieve($premiumParams, $productDetails);
344 $params = array(
345 'cost' => CRM_Utils_Array::value('cost', $productDetails),
346 'currency' => CRM_Utils_Array::value('currency', $productDetails),
347 'financial_type_id' => CRM_Utils_Array::value('financial_type_id', $productDetails),
348 'contributionId' => $params['oldPremium']['contribution_id'],
349 'isDeleted' => TRUE
350 );
351 CRM_Core_BAO_FinancialTrxn::createPremiumTrxn($params);
352 }
353 }
354 /**
355 * create financial trxn and items when fee is charged
356 *
357 * @params params to create trxn entries
358 *
359 * @access public
360 * @static
361 */
362
363 static function recordFees($params) {
f743a6eb 364 $expenseTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
6a488035
TO
365 $domainId = CRM_Core_Config::domainID();
366 $amount = 0;
a7488080 367 if (!empty($params['prevContribution'])) {
6a488035
TO
368 $amount = $params['prevContribution']->fee_amount;
369 }
370 $amount = $params['fee_amount'] - $amount;
78b79549
PN
371 if (!$amount) {
372 return FALSE;
373 }
39383f5f
PJ
374 $contributionId = isset($params['contribution']->id) ? $params['contribution']->id : $params['contribution_id'];
375 if (empty($params['financial_type_id'])) {
376 $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id', 'id');
377 }
378 else {
379 $financialTypeId = $params['financial_type_id'];
380 }
381 $financialAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $expenseTypeId);
382
6a488035
TO
383 $params['trxnParams']['from_financial_account_id'] = $params['to_financial_account_id'];
384 $params['trxnParams']['to_financial_account_id'] = $financialAccount;
385 $params['trxnParams']['total_amount'] = $amount;
cbb7c7e0 386 $params['trxnParams']['fee_amount'] =
6a488035
TO
387 $params['trxnParams']['net_amount'] = 0;
388 $params['trxnParams']['status_id'] = CRM_Core_OptionGroup::getValue('contribution_status','Completed','name');
39383f5f 389 $params['trxnParams']['contribution_id'] = $contributionId;
6a488035 390 $trxn = self::create($params['trxnParams']);
a7488080 391 if (empty($params['entity_id'])) {
6a488035
TO
392 $financialTrxnID = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['trxnParams']['contribution_id'], 'DESC');
393 $params['entity_id'] = $financialTrxnID['financialTrxnId'];
394 }
cbb7c7e0 395 $fItemParams =
6a488035
TO
396 array(
397 'financial_account_id' => $financialAccount,
398 'contact_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Domain', $domainId, 'contact_id'),
399 'created_date' => date('YmdHis'),
400 'transaction_date' => date('YmdHis'),
401 'amount' => $amount,
402 'description' => 'Fee',
403 'status_id' => CRM_Core_OptionGroup::getValue('financial_item_status','Paid','name'),
404 'entity_table' => 'civicrm_financial_trxn',
405 'entity_id' => $params['entity_id'],
406 'currency' => $params['trxnParams']['currency'],
407 );
408 $trxnIDS['id'] = $trxn->id;
409 $financialItem = CRM_Financial_BAO_FinancialItem::create($fItemParams, NULL, $trxnIDS);
410 }
6a488035 411
0f602e3f
PJ
412 /*
413 * function to get partial payment amount and type of it
414 * return @array : payment type => amount
415 * payment type : 'amount_owed' or 'refund_due'
416 */
bc2eeabb 417 static function getPartialPaymentWithType($entityId, $entityName = 'participant', $returnType = TRUE, $lineItemTotal = NULL) {
0f602e3f
PJ
418 $value = NULL;
419 if (empty($entityName)) {
420 return $value;
421 }
422
423 if ($entityName == 'participant') {
bc2eeabb 424 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $entityId, 'contribution_id', 'participant_id');
e8cf3013 425 $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
0f602e3f
PJ
426
427 if ($contributionId && $financialTypeId) {
428 $statusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
1010c4e1
PJ
429 $refundStatusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name');
430
0f602e3f
PJ
431 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
432 $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $relationTypeId);
433
bc2eeabb 434 if (empty($lineItemTotal)) {
28e4e707
PJ
435 $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
436 if (count($ids) > 1) {
437 $total = 0;
438 foreach ($ids as $val) {
439 $total += CRM_Price_BAO_LineItem::getLineTotal($val, 'civicrm_participant');
440 }
441 $lineItemTotal = $total;
442 }
443 else {
444 $lineItemTotal = CRM_Price_BAO_LineItem::getLineTotal($entityId, 'civicrm_participant');
445 }
bc2eeabb
PJ
446 }
447 $sqlFtTotalAmt = "
448SELECT SUM(ft.total_amount)
0f602e3f 449FROM civicrm_financial_trxn ft
bc2eeabb
PJ
450 LEFT JOIN civicrm_entity_financial_trxn eft ON (ft.id = eft.financial_trxn_id AND eft.entity_table = 'civicrm_contribution')
451 LEFT JOIN civicrm_contribution c ON (eft.entity_id = c.id)
452 LEFT JOIN civicrm_participant_payment pp ON (pp.contribution_id = c.id)
453WHERE pp.participant_id = {$entityId} AND ft.to_financial_account_id != {$toFinancialAccount}
1010c4e1 454 AND ft.status_id IN ({$statusId}, {$refundStatusId})
0f602e3f
PJ
455";
456 $ftTotalAmt = CRM_Core_DAO::singleValueQuery($sqlFtTotalAmt);
bc2eeabb
PJ
457 $value = 0;
458 if ($ftTotalAmt) {
459 $value = $paymentVal = $lineItemTotal - $ftTotalAmt;
460 }
29c61b58
PJ
461 if ($returnType) {
462 $value = array();
463 if ($paymentVal < 0) {
464 $value['refund_due'] = $paymentVal;
465 }
466 elseif ($paymentVal > 0) {
467 $value['amount_owed'] = $paymentVal;
468 }
bc2eeabb
PJ
469 elseif ($lineItemTotal == $ftTotalAmt) {
470 $value['full_paid'] = $ftTotalAmt;
471 }
0f602e3f
PJ
472 }
473 }
474 }
475 return $value;
476 }
0d8afee2 477}