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
{
40 * @return \CRM_Financial_DAO_FinancialTrxn
45 public function __construct() {
46 parent
::__construct();
50 * Takes an associative array and creates a financial transaction object
52 * @param array $params
53 * (reference ) an assoc array of name/value pairs.
55 * @param string $trxnEntityTable
58 * @return CRM_Core_BAO_FinancialTrxn object
61 public 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 public 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
126 * (reference ) an assoc array of name/value pairs.
127 * @param array $defaults
128 * (reference ) an assoc array to hold the flattened values.
130 * @return CRM_Contribute_BAO_ContributionType object
133 public static function retrieve(&$params, &$defaults) {
134 $financialItem = new CRM_Financial_DAO_FinancialTrxn();
135 $financialItem->copyValues($params);
136 if ($financialItem->find(TRUE)) {
137 CRM_Core_DAO
::storeValues($financialItem, $defaults);
138 return $financialItem;
144 * Given an entity_id and entity_table, check for corresponding entity_financial_trxn and financial_trxn record.
145 * NOTE: This should be moved to separate BAO for EntityFinancialTrxn when we start adding more code for that object.
148 * Id of the entity usually the contactID.
149 * @param string $orderBy
150 * To get single trxn id for a entity table i.e last or first.
151 * @param bool $newTrxn
153 * @return array $tag array of category id's the contact belongs to.
157 public static function getFinancialTrxnId($entity_id, $orderBy = 'ASC', $newTrxn = FALSE) {
158 $ids = array('entityFinancialTrxnId' => NULL, 'financialTrxnId' => NULL);
162 $condition = " AND ((ceft1.entity_table IS NOT NULL) OR (cft.payment_instrument_id IS NOT NULL AND ceft1.entity_table IS NULL)) ";
166 $orderBy = CRM_Utils_Type
::escape($orderBy, 'String');
169 $query = "SELECT ceft.id, ceft.financial_trxn_id FROM `civicrm_financial_trxn` cft
170 LEFT JOIN civicrm_entity_financial_trxn ceft
171 ON ceft.financial_trxn_id = cft.id AND ceft.entity_table = 'civicrm_contribution'
172 LEFT JOIN civicrm_entity_financial_trxn ceft1
173 ON ceft1.financial_trxn_id = cft.id AND ceft1.entity_table = 'civicrm_financial_item'
174 LEFT JOIN civicrm_financial_item cfi ON ceft1.entity_table = 'civicrm_financial_item' and cfi.id = ceft1.entity_id
175 WHERE ceft.entity_id = %1 AND (cfi.entity_table <> 'civicrm_financial_trxn' or cfi.entity_table is NULL)
177 ORDER BY cft.id {$orderBy}
180 $params = array(1 => array($entity_id, 'Integer'));
181 $dao = CRM_Core_DAO
::executeQuery($query, $params);
183 $ids['entityFinancialTrxnId'] = $dao->id
;
184 $ids['financialTrxnId'] = $dao->financial_trxn_id
;
190 * Given an entity_id and entity_table, check for corresponding entity_financial_trxn and financial_trxn record.
191 * @todo This should be moved to separate BAO for EntityFinancialTrxn when we start adding more code for that object.
193 * @param int $entity_id
194 * Id of the entity usually the contactID.
196 * @return array $tag 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.
219 * @return array $payment array of previous payments
223 public static function getPayments($financial_trxn_id) {
225 SELECT ef1.financial_trxn_id, sum(ef1.amount) amount
226 FROM civicrm_entity_financial_trxn ef1
227 LEFT JOIN civicrm_entity_financial_trxn ef2 ON ef1.financial_trxn_id = ef2.entity_id
228 WHERE ef2.financial_trxn_id =%1
229 AND ef2.entity_table = 'civicrm_financial_trxn'
230 AND ef1.entity_table = 'civicrm_financial_item'
231 GROUP BY ef1.financial_trxn_id
233 SELECT ef1.financial_trxn_id, ef1.amount
234 FROM civicrm_entity_financial_trxn ef1
235 LEFT JOIN civicrm_entity_financial_trxn ef2 ON ef1.entity_id = ef2.entity_id
236 WHERE ef2.financial_trxn_id =%1
237 AND ef2.entity_table = 'civicrm_financial_trxn'
238 AND ef1.entity_table = 'civicrm_financial_trxn'";
240 $sqlParams = array(1 => array($financial_trxn_id, 'Integer'));
241 $dao = CRM_Core_DAO
::executeQuery($query, $sqlParams);
244 while ($dao->fetch()) {
245 $result[$i]['financial_trxn_id'] = $dao->financial_trxn_id
;
246 $result[$i]['amount'] = $dao->amount
;
250 if (empty($result)) {
251 $query = "SELECT sum( amount ) amount FROM civicrm_entity_financial_trxn WHERE financial_trxn_id =%1 AND entity_table = 'civicrm_financial_item'";
252 $sqlParams = array(1 => array($financial_trxn_id, 'Integer'));
253 $dao = CRM_Core_DAO
::executeQuery($query, $sqlParams);
256 $result[0]['financial_trxn_id'] = $financial_trxn_id;
257 $result[0]['amount'] = $dao->amount
;
264 * Given an entity_id and entity_table, check for corresponding entity_financial_trxn and financial_trxn record.
265 * NOTE: This should be moved to separate BAO for EntityFinancialTrxn when we start adding more code for that object.
268 * Id of the entity usually the contactID.
269 * @param string $entity_table
270 * Name of the entity table usually 'civicrm_contact'.
272 * @return array $tag array of catagory id's the contact belongs to.
276 public static function getFinancialTrxnLineTotal($entity_id, $entity_table = 'civicrm_contribution') {
277 $query = "SELECT lt.price_field_value_id AS id, ft.financial_trxn_id,ft.amount AS amount FROM civicrm_entity_financial_trxn AS ft
278 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'
279 LEFT JOIN civicrm_line_item AS lt ON lt.id = fi.entity_id AND lt.entity_table = %2
280 WHERE lt.entity_id = %1 ";
282 $sqlParams = array(1 => array($entity_id, 'Integer'), 2 => array($entity_table, 'String'));
283 $dao = CRM_Core_DAO
::executeQuery($query, $sqlParams);
284 while ($dao->fetch()) {
285 $result[$dao->financial_trxn_id
][$dao->id
] = $dao->amount
;
287 if (!empty($result)) {
296 * Delete financial transaction
298 * @param int $entity_id
300 * TRUE on success, FALSE otherwise.
303 public static function deleteFinancialTrxn($entity_id) {
304 $query = "DELETE ceft1, cfi, ceft, cft FROM `civicrm_financial_trxn` cft
305 LEFT JOIN civicrm_entity_financial_trxn ceft
306 ON ceft.financial_trxn_id = cft.id AND ceft.entity_table = 'civicrm_contribution'
307 LEFT JOIN civicrm_entity_financial_trxn ceft1
308 ON ceft1.financial_trxn_id = cft.id AND ceft1.entity_table = 'civicrm_financial_item'
309 LEFT JOIN civicrm_financial_item cfi
310 ON ceft1.entity_table = 'civicrm_financial_item' and cfi.id = ceft1.entity_id
311 WHERE ceft.entity_id = %1";
312 CRM_Core_DAO
::executeQuery($query, array(1 => array($entity_id, 'Integer')));
317 * Create financial transaction for premium
321 public static function createPremiumTrxn($params) {
322 if ((empty($params['financial_type_id']) ||
empty($params['contributionId'])) && empty($params['oldPremium'])) {
326 if (!empty($params['cost'])) {
327 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
328 $financialAccountType = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id']);
329 $accountRelationship = CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND label IN ('Premiums Inventory Account is', 'Cost of Sales Account is')");
330 $toFinancialAccount = !empty($params['isDeleted']) ?
'Premiums Inventory Account is' : 'Cost of Sales Account is';
331 $fromFinancialAccount = !empty($params['isDeleted']) ?
'Cost of Sales Account is' : 'Premiums Inventory Account is';
332 $accountRelationship = array_flip($accountRelationship);
333 $financialtrxn = array(
334 'to_financial_account_id' => $financialAccountType[$accountRelationship[$toFinancialAccount]],
335 'from_financial_account_id' => $financialAccountType[$accountRelationship[$fromFinancialAccount]],
336 'trxn_date' => date('YmdHis'),
337 'total_amount' => CRM_Utils_Array
::value('cost', $params) ?
$params['cost'] : 0,
338 'currency' => CRM_Utils_Array
::value('currency', $params),
339 'status_id' => array_search('Completed', $contributionStatuses),
341 $trxnEntityTable['entity_table'] = 'civicrm_contribution';
342 $trxnEntityTable['entity_id'] = $params['contributionId'];
343 CRM_Core_BAO_FinancialTrxn
::create($financialtrxn, $trxnEntityTable);
346 if (!empty($params['oldPremium'])) {
347 $premiumParams = array(
348 'id' => $params['oldPremium']['product_id'],
350 $productDetails = array();
351 CRM_Contribute_BAO_ManagePremiums
::retrieve($premiumParams, $productDetails);
353 'cost' => CRM_Utils_Array
::value('cost', $productDetails),
354 'currency' => CRM_Utils_Array
::value('currency', $productDetails),
355 'financial_type_id' => CRM_Utils_Array
::value('financial_type_id', $productDetails),
356 'contributionId' => $params['oldPremium']['contribution_id'],
359 CRM_Core_BAO_FinancialTrxn
::createPremiumTrxn($params);
364 * Create financial trxn and items when fee is charged
366 * @param array $params
367 * To create trxn entries.
371 public static function recordFees($params) {
372 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
373 $domainId = CRM_Core_Config
::domainID();
375 if (!empty($params['prevContribution'])) {
376 $amount = $params['prevContribution']->fee_amount
;
378 $amount = $params['fee_amount'] - $amount;
382 $contributionId = isset($params['contribution']->id
) ?
$params['contribution']->id
: $params['contribution_id'];
383 if (empty($params['financial_type_id'])) {
384 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id', 'id');
387 $financialTypeId = $params['financial_type_id'];
389 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
391 $params['trxnParams']['from_financial_account_id'] = $params['to_financial_account_id'];
392 $params['trxnParams']['to_financial_account_id'] = $financialAccount;
393 $params['trxnParams']['total_amount'] = $amount;
394 $params['trxnParams']['fee_amount'] =
395 $params['trxnParams']['net_amount'] = 0;
396 $params['trxnParams']['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status','Completed','name');
397 $params['trxnParams']['contribution_id'] = $contributionId;
398 $trxn = self
::create($params['trxnParams']);
399 if (empty($params['entity_id'])) {
400 $financialTrxnID = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['trxnParams']['contribution_id'], 'DESC');
401 $params['entity_id'] = $financialTrxnID['financialTrxnId'];
405 'financial_account_id' => $financialAccount,
406 'contact_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $domainId, 'contact_id'),
407 'created_date' => date('YmdHis'),
408 'transaction_date' => date('YmdHis'),
410 'description' => 'Fee',
411 'status_id' => CRM_Core_OptionGroup
::getValue('financial_item_status','Paid','name'),
412 'entity_table' => 'civicrm_financial_trxn',
413 'entity_id' => $params['entity_id'],
414 'currency' => $params['trxnParams']['currency'],
416 $trxnIDS['id'] = $trxn->id
;
417 $financialItem = CRM_Financial_BAO_FinancialItem
::create($fItemParams, NULL, $trxnIDS);
421 * get partial payment amount and type of it
422 * return @array : payment type => amount
423 * payment type : 'amount_owed' or 'refund_due'
426 * @param int $entityId
427 * @param string $entityName
428 * @param bool $returnType
429 * @param NULL $lineItemTotal
431 * @return array|int|NULL|string
433 public static function getPartialPaymentWithType($entityId, $entityName = 'participant', $returnType = TRUE, $lineItemTotal = NULL) {
435 if (empty($entityName)) {
439 if ($entityName == 'participant') {
440 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $entityId, 'contribution_id', 'participant_id');
441 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
443 if ($contributionId && $financialTypeId) {
444 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
445 $refundStatusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
447 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
448 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $relationTypeId);
449 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
450 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
452 if (empty($lineItemTotal)) {
453 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
454 if (count($ids) > 1) {
456 foreach ($ids as $val) {
457 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, 'civicrm_participant');
459 $lineItemTotal = $total;
462 $lineItemTotal = CRM_Price_BAO_LineItem
::getLineTotal($entityId, 'civicrm_participant');
466 SELECT SUM(ft.total_amount)
467 FROM civicrm_financial_trxn ft
468 LEFT JOIN civicrm_entity_financial_trxn eft ON (ft.id = eft.financial_trxn_id AND eft.entity_table = 'civicrm_contribution')
469 LEFT JOIN civicrm_contribution c ON (eft.entity_id = c.id)
470 LEFT JOIN civicrm_participant_payment pp ON (pp.contribution_id = c.id)
471 WHERE pp.participant_id = {$entityId} AND ft.to_financial_account_id != {$toFinancialAccount} AND ft.to_financial_account_id != {$feeFinancialAccount}
472 AND ft.status_id IN ({$statusId}, {$refundStatusId})
474 $ftTotalAmt = CRM_Core_DAO
::singleValueQuery($sqlFtTotalAmt);
477 $value = $paymentVal = $lineItemTotal - $ftTotalAmt;
481 if ($paymentVal < 0) {
482 $value['refund_due'] = $paymentVal;
484 elseif ($paymentVal > 0) {
485 $value['amount_owed'] = $paymentVal;
487 elseif ($lineItemTotal == $ftTotalAmt) {
488 $value['full_paid'] = $ftTotalAmt;