INFRA-132 - Comment grammar cleanup
[civicrm-core.git] / CRM / Core / BAO / FinancialTrxn.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35
36 class CRM_Core_BAO_FinancialTrxn extends CRM_Financial_DAO_FinancialTrxn {
37 /**
38 * Class constructor
39 *
40 * @return \CRM_Financial_DAO_FinancialTrxn
41 */
42 /**
43 *
44 */
45 public function __construct() {
46 parent::__construct();
47 }
48
49 /**
50 * Takes an associative array and creates a financial transaction object
51 *
52 * @param array $params
53 * (reference ) an assoc array of name/value pairs.
54 *
55 * @param string $trxnEntityTable
56 * Entity_table.
57 *
58 * @return CRM_Core_BAO_FinancialTrxn object
59 * @static
60 */
61 public static function create(&$params, $trxnEntityTable = NULL) {
62 $trxn = new CRM_Financial_DAO_FinancialTrxn();
63 $trxn->copyValues($params);
64 $fids = array();
65 if (!CRM_Utils_Rule::currencyCode($trxn->currency)) {
66 $config = CRM_Core_Config::singleton();
67 $trxn->currency = $config->defaultCurrency;
68 }
69
70 $trxn->save();
71
72 // save to entity_financial_trxn table
73 $entityFinancialTrxnParams =
74 array(
75 'entity_table' => "civicrm_contribution",
76 'financial_trxn_id' => $trxn->id,
77 'amount' => $params['total_amount'],
78 'currency' => $trxn->currency,
79 );
80
81 if (!empty($trxnEntityTable)) {
82 $entityFinancialTrxnParams['entity_table'] = $trxnEntityTable['entity_table'];
83 $entityFinancialTrxnParams['entity_id'] = $trxnEntityTable['entity_id'];
84 }
85 else {
86 $entityFinancialTrxnParams['entity_id'] = $params['contribution_id'];
87 }
88
89 $entityTrxn = new CRM_Financial_DAO_EntityFinancialTrxn();
90 $entityTrxn->copyValues($entityFinancialTrxnParams);
91 $entityTrxn->save();
92 return $trxn;
93 }
94
95 /**
96 * @param int $contributionId
97 * @param int $contributionFinancialTypeId
98 *
99 * @return array
100 */
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');
104 }
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";
108
109 $p[1] = array($contributionId, 'Integer');
110 $p[2] = array($toFinancialAccount, 'Integer');
111
112 $balanceAmtDAO = CRM_Core_DAO::executeQuery($q, $p);
113 $ret = array();
114 while ($balanceAmtDAO->fetch()) {
115 $ret['trxn_id'] = $balanceAmtDAO->id;
116 $ret['total_amount'] = $balanceAmtDAO->total_amount;
117 }
118
119 return $ret;
120 }
121
122 /**
123 * Fetch object based on array of properties
124 *
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.
129 *
130 * @return CRM_Contribute_BAO_ContributionType object
131 * @static
132 */
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;
139 }
140 return NULL;
141 }
142
143 /**
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.
146 *
147 * @param $entity_id
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
152 *
153 * @return array $tag array of category id's the contact belongs to.
154 *
155 * @static
156 */
157 public static function getFinancialTrxnId($entity_id, $orderBy = 'ASC', $newTrxn = FALSE) {
158 $ids = array('entityFinancialTrxnId' => NULL, 'financialTrxnId' => NULL);
159
160 $condition = "";
161 if (!$newTrxn) {
162 $condition = " AND ((ceft1.entity_table IS NOT NULL) OR (cft.payment_instrument_id IS NOT NULL AND ceft1.entity_table IS NULL)) ";
163 }
164
165 if ($orderBy) {
166 $orderBy = CRM_Utils_Type::escape($orderBy, 'String');
167 }
168
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)
176 {$condition}
177 ORDER BY cft.id {$orderBy}
178 LIMIT 1;";
179
180 $params = array(1 => array($entity_id, 'Integer'));
181 $dao = CRM_Core_DAO::executeQuery($query, $params);
182 if ($dao->fetch()) {
183 $ids['entityFinancialTrxnId'] = $dao->id;
184 $ids['financialTrxnId'] = $dao->financial_trxn_id;
185 }
186 return $ids;
187 }
188
189 /**
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.
192 *
193 * @param int $entity_id
194 * Id of the entity usually the contactID.
195 *
196 * @return array $tag array of catagory id's the contact belongs to.
197 *
198 * @static
199 */
200 public static function getFinancialTrxnTotal($entity_id) {
201 $query = "
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
205 ";
206
207 $sqlParams = array(1 => array($entity_id, 'Integer'));
208 return CRM_Core_DAO::singleValueQuery($query, $sqlParams);
209
210 }
211
212 /**
213 * Given an financial_trxn_id check for previous entity_financial_trxn.
214 *
215 * @param $financial_trxn_id
216 * Id of the latest payment.
217 *
218 *
219 * @return array $payment array of previous payments
220 *
221 * @static
222 */
223 public static function getPayments($financial_trxn_id) {
224 $query = "
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
232 UNION
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'";
239
240 $sqlParams = array(1 => array($financial_trxn_id, 'Integer'));
241 $dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
242 $i = 0;
243 $result = array();
244 while ($dao->fetch()) {
245 $result[$i]['financial_trxn_id'] = $dao->financial_trxn_id;
246 $result[$i]['amount'] = $dao->amount;
247 $i++;
248 }
249
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);
254
255 if ($dao->fetch()) {
256 $result[0]['financial_trxn_id'] = $financial_trxn_id;
257 $result[0]['amount'] = $dao->amount;
258 }
259 }
260 return $result;
261 }
262
263 /**
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.
266 *
267 * @param $entity_id
268 * Id of the entity usually the contactID.
269 * @param string $entity_table
270 * Name of the entity table usually 'civicrm_contact'.
271 *
272 * @return array $tag array of catagory id's the contact belongs to.
273 *
274 * @static
275 */
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 ";
281
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;
286 }
287 if (!empty($result)) {
288 return $result;
289 }
290 else {
291 return NULL;
292 }
293 }
294
295 /**
296 * Delete financial transaction
297 *
298 * @param int $entity_id
299 * @return bool
300 * TRUE on success, FALSE otherwise.
301 * @static
302 */
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')));
313 return TRUE;
314 }
315
316 /**
317 * Create financial transaction for premium
318 *
319 * @static
320 */
321 public static function createPremiumTrxn($params) {
322 if ((empty($params['financial_type_id']) || empty($params['contributionId'])) && empty($params['oldPremium'])) {
323 return;
324 }
325
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),
340 );
341 $trxnEntityTable['entity_table'] = 'civicrm_contribution';
342 $trxnEntityTable['entity_id'] = $params['contributionId'];
343 CRM_Core_BAO_FinancialTrxn::create($financialtrxn, $trxnEntityTable);
344 }
345
346 if (!empty($params['oldPremium'])) {
347 $premiumParams = array(
348 'id' => $params['oldPremium']['product_id'],
349 );
350 $productDetails = array();
351 CRM_Contribute_BAO_ManagePremiums::retrieve($premiumParams, $productDetails);
352 $params = array(
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'],
357 'isDeleted' => TRUE,
358 );
359 CRM_Core_BAO_FinancialTrxn::createPremiumTrxn($params);
360 }
361 }
362
363 /**
364 * Create financial trxn and items when fee is charged
365 *
366 * @param array $params
367 * To create trxn entries.
368 *
369 * @static
370 */
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();
374 $amount = 0;
375 if (!empty($params['prevContribution'])) {
376 $amount = $params['prevContribution']->fee_amount;
377 }
378 $amount = $params['fee_amount'] - $amount;
379 if (!$amount) {
380 return FALSE;
381 }
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');
385 }
386 else {
387 $financialTypeId = $params['financial_type_id'];
388 }
389 $financialAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $expenseTypeId);
390
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'];
402 }
403 $fItemParams =
404 array(
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'),
409 'amount' => $amount,
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'],
415 );
416 $trxnIDS['id'] = $trxn->id;
417 $financialItem = CRM_Financial_BAO_FinancialItem::create($fItemParams, NULL, $trxnIDS);
418 }
419
420 /*
421 * get partial payment amount and type of it
422 * return @array : payment type => amount
423 * payment type : 'amount_owed' or 'refund_due'
424 */
425 /**
426 * @param int $entityId
427 * @param string $entityName
428 * @param bool $returnType
429 * @param NULL $lineItemTotal
430 *
431 * @return array|int|NULL|string
432 */
433 public static function getPartialPaymentWithType($entityId, $entityName = 'participant', $returnType = TRUE, $lineItemTotal = NULL) {
434 $value = NULL;
435 if (empty($entityName)) {
436 return $value;
437 }
438
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');
442
443 if ($contributionId && $financialTypeId) {
444 $statusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
445 $refundStatusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name');
446
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);
451
452 if (empty($lineItemTotal)) {
453 $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
454 if (count($ids) > 1) {
455 $total = 0;
456 foreach ($ids as $val) {
457 $total += CRM_Price_BAO_LineItem::getLineTotal($val, 'civicrm_participant');
458 }
459 $lineItemTotal = $total;
460 }
461 else {
462 $lineItemTotal = CRM_Price_BAO_LineItem::getLineTotal($entityId, 'civicrm_participant');
463 }
464 }
465 $sqlFtTotalAmt = "
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})
473 ";
474 $ftTotalAmt = CRM_Core_DAO::singleValueQuery($sqlFtTotalAmt);
475 $value = 0;
476 if ($ftTotalAmt) {
477 $value = $paymentVal = $lineItemTotal - $ftTotalAmt;
478 }
479 if ($returnType) {
480 $value = array();
481 if ($paymentVal < 0) {
482 $value['refund_due'] = $paymentVal;
483 }
484 elseif ($paymentVal > 0) {
485 $value['amount_owed'] = $paymentVal;
486 }
487 elseif ($lineItemTotal == $ftTotalAmt) {
488 $value['full_paid'] = $ftTotalAmt;
489 }
490 }
491 }
492 }
493 return $value;
494 }
495 }