3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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 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 int $contributionId
97 * @param int $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 * Fetch object based on array of properties
125 * @param array $params (reference ) an assoc array of name/value pairs
126 * @param array $defaults (reference ) an assoc array to hold the flattened values
128 * @return CRM_Contribute_BAO_ContributionType object
132 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;
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.
146 * @param $entity_id id of the entity usually the contactID.
147 * @param string $orderBy to get single trxn id for a entity table i.e last or first.
148 * @param bool $newTrxn
150 * @return array $tag array of category id's the contact belongs to.
155 static function getFinancialTrxnId($entity_id, $orderBy = 'ASC', $newTrxn = FALSE) {
156 $ids = array('entityFinancialTrxnId' => NULL, 'financialTrxnId' => NULL);
160 $condition = " AND ((ceft1.entity_table IS NOT NULL) OR (cft.payment_instrument_id IS NOT NULL AND ceft1.entity_table IS NULL)) ";
164 $orderBy = CRM_Utils_Type
::escape($orderBy, 'String');
167 $query = "SELECT ceft.id, ceft.financial_trxn_id FROM `civicrm_financial_trxn` cft
168 LEFT JOIN civicrm_entity_financial_trxn ceft
169 ON ceft.financial_trxn_id = cft.id AND ceft.entity_table = 'civicrm_contribution'
170 LEFT JOIN civicrm_entity_financial_trxn ceft1
171 ON ceft1.financial_trxn_id = cft.id AND ceft1.entity_table = 'civicrm_financial_item'
172 LEFT JOIN civicrm_financial_item cfi ON ceft1.entity_table = 'civicrm_financial_item' and cfi.id = ceft1.entity_id
173 WHERE ceft.entity_id = %1 AND (cfi.entity_table <> 'civicrm_financial_trxn' or cfi.entity_table is NULL)
175 ORDER BY cft.id {$orderBy}
178 $params = array(1 => array($entity_id, 'Integer'));
179 $dao = CRM_Core_DAO
::executeQuery($query, $params);
181 $ids['entityFinancialTrxnId'] = $dao->id
;
182 $ids['financialTrxnId'] = $dao->financial_trxn_id
;
188 * Given an entity_id and entity_table, check for corresponding entity_financial_trxn and financial_trxn record.
189 * @todo This should be moved to separate BAO for EntityFinancialTrxn when we start adding more code for that object.
191 * @param int $entity_id id of the entity usually the contactID.
193 * @return array $tag array of catagory id's the contact belongs to.
198 static function getFinancialTrxnTotal($entity_id) {
200 SELECT (ft.amount+SUM(ceft.amount)) AS total FROM civicrm_entity_financial_trxn AS ft
201 LEFT JOIN civicrm_entity_financial_trxn AS ceft ON ft.financial_trxn_id = ceft.entity_id
202 WHERE ft.entity_table = 'civicrm_contribution' AND ft.entity_id = %1
205 $sqlParams = array(1 => array($entity_id, 'Integer'));
206 return CRM_Core_DAO
::singleValueQuery($query, $sqlParams);
211 * Given an financial_trxn_id check for previous entity_financial_trxn.
213 * @param $financial_trxn_id id of the latest payment.
216 * @return array $payment array of previous payments
221 static function getPayments($financial_trxn_id) {
223 SELECT ef1.financial_trxn_id, sum(ef1.amount) amount
224 FROM civicrm_entity_financial_trxn ef1
225 LEFT JOIN civicrm_entity_financial_trxn ef2 ON ef1.financial_trxn_id = ef2.entity_id
226 WHERE ef2.financial_trxn_id =%1
227 AND ef2.entity_table = 'civicrm_financial_trxn'
228 AND ef1.entity_table = 'civicrm_financial_item'
229 GROUP BY ef1.financial_trxn_id
231 SELECT ef1.financial_trxn_id, ef1.amount
232 FROM civicrm_entity_financial_trxn ef1
233 LEFT JOIN civicrm_entity_financial_trxn ef2 ON ef1.entity_id = ef2.entity_id
234 WHERE ef2.financial_trxn_id =%1
235 AND ef2.entity_table = 'civicrm_financial_trxn'
236 AND ef1.entity_table = 'civicrm_financial_trxn'";
238 $sqlParams = array(1 => array($financial_trxn_id, 'Integer'));
239 $dao = CRM_Core_DAO
::executeQuery($query, $sqlParams);
242 while ($dao->fetch()) {
243 $result[$i]['financial_trxn_id'] = $dao->financial_trxn_id
;
244 $result[$i]['amount'] = $dao->amount
;
248 if (empty($result)) {
249 $query = "SELECT sum( amount ) amount FROM civicrm_entity_financial_trxn WHERE financial_trxn_id =%1 AND entity_table = 'civicrm_financial_item'";
250 $sqlParams = array(1 => array($financial_trxn_id, 'Integer'));
251 $dao = CRM_Core_DAO
::executeQuery($query, $sqlParams);
254 $result[0]['financial_trxn_id'] = $financial_trxn_id;
255 $result[0]['amount'] = $dao->amount
;
262 * Given an entity_id and entity_table, check for corresponding entity_financial_trxn and financial_trxn record.
263 * NOTE: This should be moved to separate BAO for EntityFinancialTrxn when we start adding more code for that object.
265 * @param $entity_id id of the entity usually the contactID.
266 * @param string $entity_table name of the entity table usually 'civicrm_contact'
268 * @return array $tag array of catagory id's the contact belongs to.
273 static function getFinancialTrxnLineTotal($entity_id, $entity_table = 'civicrm_contribution') {
274 $query = "SELECT lt.price_field_value_id AS id, ft.financial_trxn_id,ft.amount AS amount FROM civicrm_entity_financial_trxn AS ft
275 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'
276 LEFT JOIN civicrm_line_item AS lt ON lt.id = fi.entity_id AND lt.entity_table = %2
277 WHERE lt.entity_id = %1 ";
279 $sqlParams = array(1 => array($entity_id, 'Integer'), 2 => array($entity_table, 'String'));
280 $dao = CRM_Core_DAO
::executeQuery($query, $sqlParams);
281 while($dao->fetch()){
282 $result[$dao->financial_trxn_id
][$dao->id
] = $dao->amount
;
284 if (!empty($result)) {
293 * Delete financial transaction
295 * @param int $entity_id
296 * @return true on success, false otherwise
300 static function deleteFinancialTrxn($entity_id) {
301 $query = "DELETE ceft1, cfi, ceft, cft FROM `civicrm_financial_trxn` cft
302 LEFT JOIN civicrm_entity_financial_trxn ceft
303 ON ceft.financial_trxn_id = cft.id AND ceft.entity_table = 'civicrm_contribution'
304 LEFT JOIN civicrm_entity_financial_trxn ceft1
305 ON ceft1.financial_trxn_id = cft.id AND ceft1.entity_table = 'civicrm_financial_item'
306 LEFT JOIN civicrm_financial_item cfi
307 ON ceft1.entity_table = 'civicrm_financial_item' and cfi.id = ceft1.entity_id
308 WHERE ceft.entity_id = %1";
309 CRM_Core_DAO
::executeQuery($query, array(1 => array($entity_id, 'Integer')));
314 * Create financial transaction for premium
319 static function createPremiumTrxn($params) {
320 if ((empty($params['financial_type_id']) ||
empty($params['contributionId'])) && empty($params['oldPremium'])) {
324 if (!empty($params['cost'])) {
325 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
326 $financialAccountType = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id']);
327 $accountRelationship = CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND label IN ('Premiums Inventory Account is', 'Cost of Sales Account is')");
328 $toFinancialAccount = !empty($params['isDeleted']) ?
'Premiums Inventory Account is' : 'Cost of Sales Account is';
329 $fromFinancialAccount = !empty($params['isDeleted']) ?
'Cost of Sales Account is': 'Premiums Inventory Account is';
330 $accountRelationship = array_flip($accountRelationship);
331 $financialtrxn = array(
332 'to_financial_account_id' => $financialAccountType[$accountRelationship[$toFinancialAccount]],
333 'from_financial_account_id' => $financialAccountType[$accountRelationship[$fromFinancialAccount]],
334 'trxn_date' => date('YmdHis'),
335 'total_amount' => CRM_Utils_Array
::value('cost', $params) ?
$params['cost'] : 0,
336 'currency' => CRM_Utils_Array
::value('currency', $params),
337 'status_id' => array_search('Completed', $contributionStatuses)
339 $trxnEntityTable['entity_table'] = 'civicrm_contribution';
340 $trxnEntityTable['entity_id'] = $params['contributionId'];
341 CRM_Core_BAO_FinancialTrxn
::create($financialtrxn, $trxnEntityTable);
344 if (!empty($params['oldPremium'])) {
345 $premiumParams = array(
346 'id' => $params['oldPremium']['product_id']
348 $productDetails = array();
349 CRM_Contribute_BAO_ManagePremiums
::retrieve($premiumParams, $productDetails);
351 'cost' => CRM_Utils_Array
::value('cost', $productDetails),
352 'currency' => CRM_Utils_Array
::value('currency', $productDetails),
353 'financial_type_id' => CRM_Utils_Array
::value('financial_type_id', $productDetails),
354 'contributionId' => $params['oldPremium']['contribution_id'],
357 CRM_Core_BAO_FinancialTrxn
::createPremiumTrxn($params);
362 * Create financial trxn and items when fee is charged
364 * @param array $params to create trxn entries
369 static function recordFees($params) {
370 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
371 $domainId = CRM_Core_Config
::domainID();
373 if (!empty($params['prevContribution'])) {
374 $amount = $params['prevContribution']->fee_amount
;
376 $amount = $params['fee_amount'] - $amount;
380 $contributionId = isset($params['contribution']->id
) ?
$params['contribution']->id
: $params['contribution_id'];
381 if (empty($params['financial_type_id'])) {
382 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id', 'id');
385 $financialTypeId = $params['financial_type_id'];
387 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
389 $params['trxnParams']['from_financial_account_id'] = $params['to_financial_account_id'];
390 $params['trxnParams']['to_financial_account_id'] = $financialAccount;
391 $params['trxnParams']['total_amount'] = $amount;
392 $params['trxnParams']['fee_amount'] =
393 $params['trxnParams']['net_amount'] = 0;
394 $params['trxnParams']['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status','Completed','name');
395 $params['trxnParams']['contribution_id'] = $contributionId;
396 $trxn = self
::create($params['trxnParams']);
397 if (empty($params['entity_id'])) {
398 $financialTrxnID = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['trxnParams']['contribution_id'], 'DESC');
399 $params['entity_id'] = $financialTrxnID['financialTrxnId'];
403 'financial_account_id' => $financialAccount,
404 'contact_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $domainId, 'contact_id'),
405 'created_date' => date('YmdHis'),
406 'transaction_date' => date('YmdHis'),
408 'description' => 'Fee',
409 'status_id' => CRM_Core_OptionGroup
::getValue('financial_item_status','Paid','name'),
410 'entity_table' => 'civicrm_financial_trxn',
411 'entity_id' => $params['entity_id'],
412 'currency' => $params['trxnParams']['currency'],
414 $trxnIDS['id'] = $trxn->id
;
415 $financialItem = CRM_Financial_BAO_FinancialItem
::create($fItemParams, NULL, $trxnIDS);
419 * get partial payment amount and type of it
420 * return @array : payment type => amount
421 * payment type : 'amount_owed' or 'refund_due'
424 * @param int $entityId
425 * @param string $entityName
426 * @param bool $returnType
427 * @param null $lineItemTotal
429 * @return array|int|null|string
431 static function getPartialPaymentWithType($entityId, $entityName = 'participant', $returnType = TRUE, $lineItemTotal = NULL) {
433 if (empty($entityName)) {
437 if ($entityName == 'participant') {
438 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $entityId, 'contribution_id', 'participant_id');
439 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
441 if ($contributionId && $financialTypeId) {
442 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
443 $refundStatusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
445 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
446 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $relationTypeId);
447 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
448 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
450 if (empty($lineItemTotal)) {
451 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
452 if (count($ids) > 1) {
454 foreach ($ids as $val) {
455 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, 'civicrm_participant');
457 $lineItemTotal = $total;
460 $lineItemTotal = CRM_Price_BAO_LineItem
::getLineTotal($entityId, 'civicrm_participant');
464 SELECT SUM(ft.total_amount)
465 FROM civicrm_financial_trxn ft
466 LEFT JOIN civicrm_entity_financial_trxn eft ON (ft.id = eft.financial_trxn_id AND eft.entity_table = 'civicrm_contribution')
467 LEFT JOIN civicrm_contribution c ON (eft.entity_id = c.id)
468 LEFT JOIN civicrm_participant_payment pp ON (pp.contribution_id = c.id)
469 WHERE pp.participant_id = {$entityId} AND ft.to_financial_account_id != {$toFinancialAccount} AND ft.to_financial_account_id != {$feeFinancialAccount}
470 AND ft.status_id IN ({$statusId}, {$refundStatusId})
472 $ftTotalAmt = CRM_Core_DAO
::singleValueQuery($sqlFtTotalAmt);
475 $value = $paymentVal = $lineItemTotal - $ftTotalAmt;
479 if ($paymentVal < 0) {
480 $value['refund_due'] = $paymentVal;
482 elseif ($paymentVal > 0) {
483 $value['amount_owed'] = $paymentVal;
485 elseif ($lineItemTotal == $ftTotalAmt) {
486 $value['full_paid'] = $ftTotalAmt;