3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
36 class CRM_Core_BAO_FinancialTrxn
extends CRM_Financial_DAO_FinancialTrxn
{
41 * @return \CRM_Financial_DAO_FinancialTrxn
46 function __construct() {
47 parent
::__construct();
51 * takes an associative array and creates a financial transaction object
53 * @param array $params (reference ) an assoc array of name/value pairs
55 * @param string $trxnEntityTable entity_table
57 * @return object CRM_Core_BAO_FinancialTrxn object
61 static function create(&$params, $trxnEntityTable = null ) {
62 $trxn = new CRM_Financial_DAO_FinancialTrxn();
63 $trxn->copyValues($params);
65 if (!CRM_Utils_Rule
::currencyCode($trxn->currency
)) {
66 $config = CRM_Core_Config
::singleton();
67 $trxn->currency
= $config->defaultCurrency
;
72 // save to entity_financial_trxn table
73 $entityFinancialTrxnParams =
75 'entity_table' => "civicrm_contribution",
76 'financial_trxn_id' => $trxn->id
,
77 'amount' => $params['total_amount'],
78 'currency' => $trxn->currency
,
81 if (!empty($trxnEntityTable)) {
82 $entityFinancialTrxnParams['entity_table'] = $trxnEntityTable['entity_table'];
83 $entityFinancialTrxnParams['entity_id'] = $trxnEntityTable['entity_id'];
86 $entityFinancialTrxnParams['entity_id'] = $params['contribution_id'];
89 $entityTrxn = new CRM_Financial_DAO_EntityFinancialTrxn();
90 $entityTrxn->copyValues($entityFinancialTrxnParams);
96 * @param $contributionId
97 * @param null $contributionFinancialTypeId
101 static function getBalanceTrxnAmt($contributionId, $contributionFinancialTypeId = NULL) {
102 if (!$contributionFinancialTypeId) {
103 $contributionFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'financial_type_id');
105 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
106 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionFinancialTypeId, $relationTypeId);
107 $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";
109 $p[1] = array($contributionId, 'Integer');
110 $p[2] = array($toFinancialAccount, 'Integer');
112 $balanceAmtDAO = CRM_Core_DAO
::executeQuery($q, $p);
114 while($balanceAmtDAO->fetch()) {
115 $ret['trxn_id'] = $balanceAmtDAO->id
;
116 $ret['total_amount'] = $balanceAmtDAO->total_amount
;
123 * Takes a bunch of params that are needed to match certain criteria and
124 * retrieves the relevant objects. Typically the valid params are only
125 * contact_id. We'll tweak this function to be more full featured over a period
126 * of time. This is the inverse function of create. It also stores all the retrieved
127 * values in the default array
129 * @param array $params (reference ) an assoc array of name/value pairs
130 * @param array $defaults (reference ) an assoc array to hold the flattened values
132 * @return object CRM_Contribute_BAO_ContributionType object
136 static function retrieve( &$params, &$defaults ) {
137 $financialItem = new CRM_Financial_DAO_FinancialTrxn( );
138 $financialItem->copyValues($params);
139 if ($financialItem->find(true)) {
140 CRM_Core_DAO
::storeValues( $financialItem, $defaults );
141 return $financialItem;
148 * Given an entity_id and entity_table, check for corresponding entity_financial_trxn and financial_trxn record.
149 * NOTE: This should be moved to separate BAO for EntityFinancialTrxn when we start adding more code for that object.
152 * @param string $orderBy to get single trxn id for a entity table i.e last or first.
154 * @param bool $newTrxn
156 * @internal param string $entityTable name of the entity table usually 'civicrm_contact'
157 * @internal param int $entityID id of the entity usually the contactID.
158 * @return array( ) reference $tag array of category id's the contact belongs to.
163 static function getFinancialTrxnId($entity_id, $orderBy = 'ASC', $newTrxn = FALSE) {
164 $ids = array('entityFinancialTrxnId' => NULL, 'financialTrxnId' => NULL);
168 $condition = " AND ((ceft1.entity_table IS NOT NULL) OR (cft.payment_instrument_id IS NOT NULL AND ceft1.entity_table IS NULL)) ";
172 $orderBy = CRM_Utils_Type
::escape($orderBy, 'String');
175 $query = "SELECT ceft.id, ceft.financial_trxn_id FROM `civicrm_financial_trxn` cft
176 LEFT JOIN civicrm_entity_financial_trxn ceft
177 ON ceft.financial_trxn_id = cft.id AND ceft.entity_table = 'civicrm_contribution'
178 LEFT JOIN civicrm_entity_financial_trxn ceft1
179 ON ceft1.financial_trxn_id = cft.id AND ceft1.entity_table = 'civicrm_financial_item'
180 LEFT JOIN civicrm_financial_item cfi ON ceft1.entity_table = 'civicrm_financial_item' and cfi.id = ceft1.entity_id
181 WHERE ceft.entity_id = %1 AND (cfi.entity_table <> 'civicrm_financial_trxn' or cfi.entity_table is NULL)
183 ORDER BY cft.id {$orderBy}
186 $params = array(1 => array($entity_id, 'Integer'));
187 $dao = CRM_Core_DAO
::executeQuery($query, $params);
189 $ids['entityFinancialTrxnId'] = $dao->id
;
190 $ids['financialTrxnId'] = $dao->financial_trxn_id
;
196 * Given an entity_id and entity_table, check for corresponding entity_financial_trxn and financial_trxn record.
197 * NOTE: This should be moved to separate BAO for EntityFinancialTrxn when we start adding more code for that object.
201 * @internal param string $entityTable name of the entity table usually 'civicrm_contact'
202 * @internal param int $entityID id of the entity usually the contactID.
204 * @return array( ) reference $tag array of catagory id's the contact belongs to.
209 static function getFinancialTrxnTotal($entity_id) {
211 SELECT (ft.amount+SUM(ceft.amount)) AS total FROM civicrm_entity_financial_trxn AS ft
212 LEFT JOIN civicrm_entity_financial_trxn AS ceft ON ft.financial_trxn_id = ceft.entity_id
213 WHERE ft.entity_table = 'civicrm_contribution' AND ft.entity_id = %1
216 $sqlParams = array(1 => array($entity_id, 'Integer'));
217 return CRM_Core_DAO
::singleValueQuery($query, $sqlParams);
222 * Given an financial_trxn_id check for previous entity_financial_trxn.
224 * @param $financial_trxn_id
226 * @internal param int $financialTrxn_id id of the latest payment.
228 * @return array( ) $payment array of previous payments
233 static function getPayments($financial_trxn_id) {
235 SELECT ef1.financial_trxn_id, sum(ef1.amount) amount
236 FROM civicrm_entity_financial_trxn ef1
237 LEFT JOIN civicrm_entity_financial_trxn ef2 ON ef1.financial_trxn_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_item'
241 GROUP BY ef1.financial_trxn_id
243 SELECT ef1.financial_trxn_id, ef1.amount
244 FROM civicrm_entity_financial_trxn ef1
245 LEFT JOIN civicrm_entity_financial_trxn ef2 ON ef1.entity_id = ef2.entity_id
246 WHERE ef2.financial_trxn_id =%1
247 AND ef2.entity_table = 'civicrm_financial_trxn'
248 AND ef1.entity_table = 'civicrm_financial_trxn'";
250 $sqlParams = array(1 => array($financial_trxn_id, 'Integer'));
251 $dao = CRM_Core_DAO
::executeQuery($query, $sqlParams);
254 while ($dao->fetch()) {
255 $result[$i]['financial_trxn_id'] = $dao->financial_trxn_id
;
256 $result[$i]['amount'] = $dao->amount
;
260 if (empty($result)) {
261 $query = "SELECT sum( amount ) amount FROM civicrm_entity_financial_trxn WHERE financial_trxn_id =%1 AND entity_table = 'civicrm_financial_item'";
262 $sqlParams = array(1 => array($financial_trxn_id, 'Integer'));
263 $dao = CRM_Core_DAO
::executeQuery($query, $sqlParams);
266 $result[0]['financial_trxn_id'] = $financial_trxn_id;
267 $result[0]['amount'] = $dao->amount
;
274 * Given an entity_id and entity_table, check for corresponding entity_financial_trxn and financial_trxn record.
275 * NOTE: This should be moved to separate BAO for EntityFinancialTrxn when we start adding more code for that object.
278 * @param string $entity_table
280 * @internal param string $entityTable name of the entity table usually 'civicrm_contact'
281 * @internal param int $entityID id of the entity usually the contactID.
283 * @return array( ) reference $tag array of catagory id's the contact belongs to.
288 static function getFinancialTrxnLineTotal($entity_id, $entity_table = 'civicrm_contribution') {
289 $query = "SELECT lt.price_field_value_id AS id, ft.financial_trxn_id,ft.amount AS amount FROM civicrm_entity_financial_trxn AS ft
290 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'
291 LEFT JOIN civicrm_line_item AS lt ON lt.id = fi.entity_id AND lt.entity_table = %2
292 WHERE lt.entity_id = %1 ";
294 $sqlParams = array(1 => array($entity_id, 'Integer'), 2 => array($entity_table, 'String'));
295 $dao = CRM_Core_DAO
::executeQuery($query, $sqlParams);
296 while($dao->fetch()){
297 $result[$dao->financial_trxn_id
][$dao->id
] = $dao->amount
;
299 if (!empty($result)) {
308 * Delete financial transaction
311 * @return true on success, false otherwise
315 static function deleteFinancialTrxn($entity_id) {
316 $query = "DELETE ceft1, cfi, ceft, cft FROM `civicrm_financial_trxn` cft
317 LEFT JOIN civicrm_entity_financial_trxn ceft
318 ON ceft.financial_trxn_id = cft.id AND ceft.entity_table = 'civicrm_contribution'
319 LEFT JOIN civicrm_entity_financial_trxn ceft1
320 ON ceft1.financial_trxn_id = cft.id AND ceft1.entity_table = 'civicrm_financial_item'
321 LEFT JOIN civicrm_financial_item cfi
322 ON ceft1.entity_table = 'civicrm_financial_item' and cfi.id = ceft1.entity_id
323 WHERE ceft.entity_id = %1";
324 CRM_Core_DAO
::executeQuery($query, array(1 => array($entity_id, 'Integer')));
329 * create financial transaction for premium
334 static function createPremiumTrxn($params) {
335 if ((empty($params['financial_type_id']) ||
empty($params['contributionId'])) && empty($params['oldPremium'])) {
339 if (!empty($params['cost'])) {
340 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
341 $financialAccountType = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id']);
342 $accountRelationship = CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND label IN ('Premiums Inventory Account is', 'Cost of Sales Account is')");
343 $toFinancialAccount = !empty($params['isDeleted']) ?
'Premiums Inventory Account is' : 'Cost of Sales Account is';
344 $fromFinancialAccount = !empty($params['isDeleted']) ?
'Cost of Sales Account is': 'Premiums Inventory Account is';
345 $accountRelationship = array_flip($accountRelationship);
346 $financialtrxn = array(
347 'to_financial_account_id' => $financialAccountType[$accountRelationship[$toFinancialAccount]],
348 'from_financial_account_id' => $financialAccountType[$accountRelationship[$fromFinancialAccount]],
349 'trxn_date' => date('YmdHis'),
350 'total_amount' => CRM_Utils_Array
::value('cost', $params) ?
$params['cost'] : 0,
351 'currency' => CRM_Utils_Array
::value('currency', $params),
352 'status_id' => array_search('Completed', $contributionStatuses)
354 $trxnEntityTable['entity_table'] = 'civicrm_contribution';
355 $trxnEntityTable['entity_id'] = $params['contributionId'];
356 CRM_Core_BAO_FinancialTrxn
::create($financialtrxn, $trxnEntityTable);
359 if (!empty($params['oldPremium'])) {
360 $premiumParams = array(
361 'id' => $params['oldPremium']['product_id']
363 $productDetails = array();
364 CRM_Contribute_BAO_ManagePremiums
::retrieve($premiumParams, $productDetails);
366 'cost' => CRM_Utils_Array
::value('cost', $productDetails),
367 'currency' => CRM_Utils_Array
::value('currency', $productDetails),
368 'financial_type_id' => CRM_Utils_Array
::value('financial_type_id', $productDetails),
369 'contributionId' => $params['oldPremium']['contribution_id'],
372 CRM_Core_BAO_FinancialTrxn
::createPremiumTrxn($params);
376 * create financial trxn and items when fee is charged
378 * @params params to create trxn entries
384 static function recordFees($params) {
385 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
386 $domainId = CRM_Core_Config
::domainID();
388 if (!empty($params['prevContribution'])) {
389 $amount = $params['prevContribution']->fee_amount
;
391 $amount = $params['fee_amount'] - $amount;
395 $contributionId = isset($params['contribution']->id
) ?
$params['contribution']->id
: $params['contribution_id'];
396 if (empty($params['financial_type_id'])) {
397 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id', 'id');
400 $financialTypeId = $params['financial_type_id'];
402 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
404 $params['trxnParams']['from_financial_account_id'] = $params['to_financial_account_id'];
405 $params['trxnParams']['to_financial_account_id'] = $financialAccount;
406 $params['trxnParams']['total_amount'] = $amount;
407 $params['trxnParams']['fee_amount'] =
408 $params['trxnParams']['net_amount'] = 0;
409 $params['trxnParams']['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status','Completed','name');
410 $params['trxnParams']['contribution_id'] = $contributionId;
411 $trxn = self
::create($params['trxnParams']);
412 if (empty($params['entity_id'])) {
413 $financialTrxnID = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['trxnParams']['contribution_id'], 'DESC');
414 $params['entity_id'] = $financialTrxnID['financialTrxnId'];
418 'financial_account_id' => $financialAccount,
419 'contact_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $domainId, 'contact_id'),
420 'created_date' => date('YmdHis'),
421 'transaction_date' => date('YmdHis'),
423 'description' => 'Fee',
424 'status_id' => CRM_Core_OptionGroup
::getValue('financial_item_status','Paid','name'),
425 'entity_table' => 'civicrm_financial_trxn',
426 'entity_id' => $params['entity_id'],
427 'currency' => $params['trxnParams']['currency'],
429 $trxnIDS['id'] = $trxn->id
;
430 $financialItem = CRM_Financial_BAO_FinancialItem
::create($fItemParams, NULL, $trxnIDS);
434 * function to get partial payment amount and type of it
435 * return @array : payment type => amount
436 * payment type : 'amount_owed' or 'refund_due'
440 * @param string $entityName
441 * @param bool $returnType
442 * @param null $lineItemTotal
444 * @return array|int|null|string
446 static function getPartialPaymentWithType($entityId, $entityName = 'participant', $returnType = TRUE, $lineItemTotal = NULL) {
448 if (empty($entityName)) {
452 if ($entityName == 'participant') {
453 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $entityId, 'contribution_id', 'participant_id');
454 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
456 if ($contributionId && $financialTypeId) {
457 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
458 $refundStatusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
460 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
461 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $relationTypeId);
463 if (empty($lineItemTotal)) {
464 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
465 if (count($ids) > 1) {
467 foreach ($ids as $val) {
468 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, 'civicrm_participant');
470 $lineItemTotal = $total;
473 $lineItemTotal = CRM_Price_BAO_LineItem
::getLineTotal($entityId, 'civicrm_participant');
477 SELECT SUM(ft.total_amount)
478 FROM civicrm_financial_trxn ft
479 LEFT JOIN civicrm_entity_financial_trxn eft ON (ft.id = eft.financial_trxn_id AND eft.entity_table = 'civicrm_contribution')
480 LEFT JOIN civicrm_contribution c ON (eft.entity_id = c.id)
481 LEFT JOIN civicrm_participant_payment pp ON (pp.contribution_id = c.id)
482 WHERE pp.participant_id = {$entityId} AND ft.to_financial_account_id != {$toFinancialAccount}
483 AND ft.status_id IN ({$statusId}, {$refundStatusId})
485 $ftTotalAmt = CRM_Core_DAO
::singleValueQuery($sqlFtTotalAmt);
488 $value = $paymentVal = $lineItemTotal - $ftTotalAmt;
492 if ($paymentVal < 0) {
493 $value['refund_due'] = $paymentVal;
495 elseif ($paymentVal > 0) {
496 $value['amount_owed'] = $paymentVal;
498 elseif ($lineItemTotal == $ftTotalAmt) {
499 $value['full_paid'] = $ftTotalAmt;