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
35 class CRM_Core_BAO_FinancialTrxn
extends CRM_Financial_DAO_FinancialTrxn
{
39 * @return \CRM_Financial_DAO_FinancialTrxn
43 public function __construct() {
44 parent
::__construct();
48 * Takes an associative array and creates a financial transaction object
50 * @param array $params
51 * (reference ) an assoc array of name/value pairs.
53 * @param string $trxnEntityTable
56 * @return CRM_Core_BAO_FinancialTrxn
59 public static function create(&$params, $trxnEntityTable = NULL) {
60 $trxn = new CRM_Financial_DAO_FinancialTrxn();
61 $trxn->copyValues($params);
63 if (!CRM_Utils_Rule
::currencyCode($trxn->currency
)) {
64 $config = CRM_Core_Config
::singleton();
65 $trxn->currency
= $config->defaultCurrency
;
70 // save to entity_financial_trxn table
71 $entityFinancialTrxnParams =
73 'entity_table' => "civicrm_contribution",
74 'financial_trxn_id' => $trxn->id
,
75 'amount' => $params['total_amount'],
76 'currency' => $trxn->currency
,
79 if (!empty($trxnEntityTable)) {
80 $entityFinancialTrxnParams['entity_table'] = $trxnEntityTable['entity_table'];
81 $entityFinancialTrxnParams['entity_id'] = $trxnEntityTable['entity_id'];
84 $entityFinancialTrxnParams['entity_id'] = $params['contribution_id'];
87 $entityTrxn = new CRM_Financial_DAO_EntityFinancialTrxn();
88 $entityTrxn->copyValues($entityFinancialTrxnParams);
94 * @param int $contributionId
95 * @param int $contributionFinancialTypeId
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');
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";
107 $p[1] = array($contributionId, 'Integer');
108 $p[2] = array($toFinancialAccount, 'Integer');
110 $balanceAmtDAO = CRM_Core_DAO
::executeQuery($q, $p);
112 while ($balanceAmtDAO->fetch()) {
113 $ret['trxn_id'] = $balanceAmtDAO->id
;
114 $ret['total_amount'] = $balanceAmtDAO->total_amount
;
121 * Fetch object based on array of properties
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.
128 * @return CRM_Contribute_BAO_ContributionType
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;
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.
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
152 * array of category id's the contact belongs to.
156 public static function getFinancialTrxnId($entity_id, $orderBy = 'ASC', $newTrxn = FALSE) {
157 $ids = array('entityFinancialTrxnId' => NULL, 'financialTrxnId' => NULL);
161 $condition = " AND ((ceft1.entity_table IS NOT NULL) OR (cft.payment_instrument_id IS NOT NULL AND ceft1.entity_table IS NULL)) ";
165 $orderBy = CRM_Utils_Type
::escape($orderBy, 'String');
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)
176 ORDER BY cft.id {$orderBy}
179 $params = array(1 => array($entity_id, 'Integer'));
180 $dao = CRM_Core_DAO
::executeQuery($query, $params);
182 $ids['entityFinancialTrxnId'] = $dao->id
;
183 $ids['financialTrxnId'] = $dao->financial_trxn_id
;
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.
192 * @param int $entity_id
193 * Id of the entity usually the contactID.
196 * array of catagory id's the contact belongs to.
200 public static function getFinancialTrxnTotal($entity_id) {
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
207 $sqlParams = array(1 => array($entity_id, 'Integer'));
208 return CRM_Core_DAO
::singleValueQuery($query, $sqlParams);
213 * Given an financial_trxn_id check for previous entity_financial_trxn.
215 * @param $financial_trxn_id
216 * Id of the latest payment.
220 * array of previous payments
224 public static function getPayments($financial_trxn_id) {
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
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'";
241 $sqlParams = array(1 => array($financial_trxn_id, 'Integer'));
242 $dao = CRM_Core_DAO
::executeQuery($query, $sqlParams);
245 while ($dao->fetch()) {
246 $result[$i]['financial_trxn_id'] = $dao->financial_trxn_id
;
247 $result[$i]['amount'] = $dao->amount
;
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);
257 $result[0]['financial_trxn_id'] = $financial_trxn_id;
258 $result[0]['amount'] = $dao->amount
;
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.
269 * Id of the entity usually the contactID.
270 * @param string $entity_table
271 * Name of the entity table usually 'civicrm_contact'.
274 * array of catagory id's the contact belongs to.
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 ";
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
;
289 if (!empty($result)) {
298 * Delete financial transaction
300 * @param int $entity_id
302 * TRUE on success, FALSE otherwise.
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')));
319 * Create financial transaction for premium
323 public static function createPremiumTrxn($params) {
324 if ((empty($params['financial_type_id']) ||
empty($params['contributionId'])) && empty($params['oldPremium'])) {
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),
343 $trxnEntityTable['entity_table'] = 'civicrm_contribution';
344 $trxnEntityTable['entity_id'] = $params['contributionId'];
345 CRM_Core_BAO_FinancialTrxn
::create($financialtrxn, $trxnEntityTable);
348 if (!empty($params['oldPremium'])) {
349 $premiumParams = array(
350 'id' => $params['oldPremium']['product_id'],
352 $productDetails = array();
353 CRM_Contribute_BAO_ManagePremiums
::retrieve($premiumParams, $productDetails);
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'],
361 CRM_Core_BAO_FinancialTrxn
::createPremiumTrxn($params);
366 * Create financial trxn and items when fee is charged
368 * @param array $params
369 * To create trxn entries.
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();
377 if (!empty($params['prevContribution'])) {
378 $amount = $params['prevContribution']->fee_amount
;
380 $amount = $params['fee_amount'] - $amount;
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');
389 $financialTypeId = $params['financial_type_id'];
391 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
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'];
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'),
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'],
418 $trxnIDS['id'] = $trxn->id
;
419 $financialItem = CRM_Financial_BAO_FinancialItem
::create($fItemParams, NULL, $trxnIDS);
423 * get partial payment amount and type of it
424 * return @array : payment type => amount
425 * payment type : 'amount_owed' or 'refund_due'
428 * @param int $entityId
429 * @param string $entityName
430 * @param bool $returnType
431 * @param NULL $lineItemTotal
433 * @return array|int|NULL|string
435 public static function getPartialPaymentWithType($entityId, $entityName = 'participant', $returnType = TRUE, $lineItemTotal = NULL) {
437 if (empty($entityName)) {
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');
445 if ($contributionId && $financialTypeId) {
446 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
447 $refundStatusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
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);
454 if (empty($lineItemTotal)) {
455 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
456 if (count($ids) > 1) {
458 foreach ($ids as $val) {
459 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, 'civicrm_participant');
461 $lineItemTotal = $total;
464 $lineItemTotal = CRM_Price_BAO_LineItem
::getLineTotal($entityId, 'civicrm_participant');
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})
476 $ftTotalAmt = CRM_Core_DAO
::singleValueQuery($sqlFtTotalAmt);
479 $value = $paymentVal = $lineItemTotal - $ftTotalAmt;
483 if ($paymentVal < 0) {
484 $value['refund_due'] = $paymentVal;
486 elseif ($paymentVal > 0) {
487 $value['amount_owed'] = $paymentVal;
489 elseif ($lineItemTotal == $ftTotalAmt) {
490 $value['full_paid'] = $ftTotalAmt;