CRM-16189, added link on contribution edit form to record payment for pending pay...
[civicrm-core.git] / CRM / Core / BAO / FinancialTrxn.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
32 * $Id$
33 *
34 */
35 class CRM_Core_BAO_FinancialTrxn extends CRM_Financial_DAO_FinancialTrxn {
36 /**
37 * Class constructor.
38 *
39 * @return \CRM_Financial_DAO_FinancialTrxn
40 */
41 /**
42 */
43 public function __construct() {
44 parent::__construct();
45 }
46
47 /**
48 * Takes an associative array and creates a financial transaction object.
49 *
50 * @param array $params
51 * (reference ) an assoc array of name/value pairs.
52 *
53 * @param string $trxnEntityTable
54 * Entity_table.
55 *
56 * @return CRM_Core_BAO_FinancialTrxn
57 */
58 public static function create(&$params, $trxnEntityTable = NULL) {
59 $trxn = new CRM_Financial_DAO_FinancialTrxn();
60 $trxn->copyValues($params);
61
62 if (!CRM_Utils_Rule::currencyCode($trxn->currency)) {
63 $trxn->currency = CRM_Core_Config::singleton()->defaultCurrency;
64 }
65
66 $trxn->save();
67
68 // save to entity_financial_trxn table
69 $entityFinancialTrxnParams
70 = array(
71 'entity_table' => "civicrm_contribution",
72 'financial_trxn_id' => $trxn->id,
73 'amount' => $params['total_amount'],
74 );
75
76 if (!empty($trxnEntityTable)) {
77 $entityFinancialTrxnParams['entity_table'] = $trxnEntityTable['entity_table'];
78 $entityFinancialTrxnParams['entity_id'] = $trxnEntityTable['entity_id'];
79 }
80 else {
81 $entityFinancialTrxnParams['entity_id'] = $params['contribution_id'];
82 }
83
84 $entityTrxn = new CRM_Financial_DAO_EntityFinancialTrxn();
85 $entityTrxn->copyValues($entityFinancialTrxnParams);
86 $entityTrxn->save();
87 return $trxn;
88 }
89
90 /**
91 * @param int $contributionId
92 * @param int $contributionFinancialTypeId
93 *
94 * @return array
95 */
96 public static function getBalanceTrxnAmt($contributionId, $contributionFinancialTypeId = NULL) {
97 if (!$contributionFinancialTypeId) {
98 $contributionFinancialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'financial_type_id');
99 }
100 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
101 $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($contributionFinancialTypeId, $relationTypeId);
102 $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";
103
104 $p[1] = array($contributionId, 'Integer');
105 $p[2] = array($toFinancialAccount, 'Integer');
106
107 $balanceAmtDAO = CRM_Core_DAO::executeQuery($q, $p);
108 $ret = array();
109 if ($balanceAmtDAO->N) {
110 $ret['total_amount'] = 0;
111 }
112 while ($balanceAmtDAO->fetch()) {
113 $ret['trxn_id'] = $balanceAmtDAO->id;
114 $ret['total_amount'] += $balanceAmtDAO->total_amount;
115 }
116
117 return $ret;
118 }
119
120 /**
121 * Fetch object based on array of properties.
122 *
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.
127 *
128 * @return CRM_Contribute_BAO_ContributionType
129 */
130 public static function retrieve(&$params, &$defaults) {
131 $financialItem = new CRM_Financial_DAO_FinancialTrxn();
132 $financialItem->copyValues($params);
133 if ($financialItem->find(TRUE)) {
134 CRM_Core_DAO::storeValues($financialItem, $defaults);
135 return $financialItem;
136 }
137 return NULL;
138 }
139
140 /**
141 * Given an entity_id and entity_table, check for corresponding entity_financial_trxn and financial_trxn record.
142 * NOTE: This should be moved to separate BAO for EntityFinancialTrxn when we start adding more code for that object.
143 *
144 * @param $entity_id
145 * Id of the entity usually the contributionID.
146 * @param string $orderBy
147 * To get single trxn id for a entity table i.e last or first.
148 * @param bool $newTrxn
149 * @param string $whereClause
150 * Additional where parameters
151 *
152 * @return array
153 * array of category id's the contact belongs to.
154 *
155 */
156 public static function getFinancialTrxnId($entity_id, $orderBy = 'ASC', $newTrxn = FALSE, $whereClause = '', $fromAccountID = NULL) {
157 $ids = array('entityFinancialTrxnId' => NULL, 'financialTrxnId' => NULL);
158
159 $params = array(1 => array($entity_id, 'Integer'));
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 ($fromAccountID) {
166 $condition .= " AND (cft.from_financial_account_id <> %2 OR cft.from_financial_account_id IS NULL)";
167 $params[2] = array($fromAccountID, 'Integer');
168 }
169 if ($orderBy) {
170 $orderBy = CRM_Utils_Type::escape($orderBy, 'String');
171 }
172
173 $query = "SELECT ceft.id, ceft.financial_trxn_id, cft.trxn_id FROM `civicrm_financial_trxn` cft
174 LEFT JOIN civicrm_entity_financial_trxn ceft
175 ON ceft.financial_trxn_id = cft.id AND ceft.entity_table = 'civicrm_contribution'
176 LEFT JOIN civicrm_entity_financial_trxn ceft1
177 ON ceft1.financial_trxn_id = cft.id AND ceft1.entity_table = 'civicrm_financial_item'
178 LEFT JOIN civicrm_financial_item cfi ON ceft1.entity_table = 'civicrm_financial_item' and cfi.id = ceft1.entity_id
179 WHERE ceft.entity_id = %1 AND (cfi.entity_table <> 'civicrm_financial_trxn' or cfi.entity_table is NULL)
180 {$condition}
181 {$whereClause}
182 ORDER BY cft.id {$orderBy}
183 LIMIT 1;";
184
185 $dao = CRM_Core_DAO::executeQuery($query, $params);
186 if ($dao->fetch()) {
187 $ids['entityFinancialTrxnId'] = $dao->id;
188 $ids['financialTrxnId'] = $dao->financial_trxn_id;
189 $ids['trxn_id'] = $dao->trxn_id;
190 }
191 return $ids;
192 }
193
194 /**
195 * Get the transaction id for the (latest) refund associated with a contribution.
196 *
197 * @param int $contributionID
198 * @return string
199 */
200 public static function getRefundTransactionTrxnID($contributionID) {
201 $ids = self::getRefundTransactionIDs($contributionID);
202 return isset($ids['trxn_id']) ? $ids['trxn_id'] : NULL;
203 }
204
205 /**
206 * Get the transaction id for the (latest) refund associated with a contribution.
207 *
208 * @param int $contributionID
209 * @return string
210 */
211 public static function getRefundTransactionIDs($contributionID) {
212 $refundStatusID = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Refunded');
213 return self::getFinancialTrxnId($contributionID, 'DESC', FALSE, " AND cft.status_id = $refundStatusID");
214 }
215
216 /**
217 * Given an entity_id and entity_table, check for corresponding entity_financial_trxn and financial_trxn record.
218 * @todo This should be moved to separate BAO for EntityFinancialTrxn when we start adding more code for that object.
219 *
220 * @param int $entity_id
221 * Id of the entity usually the contactID.
222 *
223 * @return array
224 * array of category id's the contact belongs to.
225 *
226 */
227 public static function getFinancialTrxnTotal($entity_id) {
228 $query = "
229 SELECT (ft.amount+SUM(ceft.amount)) AS total FROM civicrm_entity_financial_trxn AS ft
230 LEFT JOIN civicrm_entity_financial_trxn AS ceft ON ft.financial_trxn_id = ceft.entity_id
231 WHERE ft.entity_table = 'civicrm_contribution' AND ft.entity_id = %1
232 ";
233
234 $sqlParams = array(1 => array($entity_id, 'Integer'));
235 return CRM_Core_DAO::singleValueQuery($query, $sqlParams);
236
237 }
238
239 /**
240 * Given an financial_trxn_id check for previous entity_financial_trxn.
241 *
242 * @param $financial_trxn_id
243 * Id of the latest payment.
244 *
245 *
246 * @return array
247 * array of previous payments
248 *
249 */
250 public static function getPayments($financial_trxn_id) {
251 $query = "
252 SELECT ef1.financial_trxn_id, sum(ef1.amount) amount
253 FROM civicrm_entity_financial_trxn ef1
254 LEFT JOIN civicrm_entity_financial_trxn ef2 ON ef1.financial_trxn_id = ef2.entity_id
255 WHERE ef2.financial_trxn_id =%1
256 AND ef2.entity_table = 'civicrm_financial_trxn'
257 AND ef1.entity_table = 'civicrm_financial_item'
258 GROUP BY ef1.financial_trxn_id
259 UNION
260 SELECT ef1.financial_trxn_id, ef1.amount
261 FROM civicrm_entity_financial_trxn ef1
262 LEFT JOIN civicrm_entity_financial_trxn ef2 ON ef1.entity_id = ef2.entity_id
263 WHERE ef2.financial_trxn_id =%1
264 AND ef2.entity_table = 'civicrm_financial_trxn'
265 AND ef1.entity_table = 'civicrm_financial_trxn'";
266
267 $sqlParams = array(1 => array($financial_trxn_id, 'Integer'));
268 $dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
269 $i = 0;
270 $result = array();
271 while ($dao->fetch()) {
272 $result[$i]['financial_trxn_id'] = $dao->financial_trxn_id;
273 $result[$i]['amount'] = $dao->amount;
274 $i++;
275 }
276
277 if (empty($result)) {
278 $query = "SELECT sum( amount ) amount FROM civicrm_entity_financial_trxn WHERE financial_trxn_id =%1 AND entity_table = 'civicrm_financial_item'";
279 $sqlParams = array(1 => array($financial_trxn_id, 'Integer'));
280 $dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
281
282 if ($dao->fetch()) {
283 $result[0]['financial_trxn_id'] = $financial_trxn_id;
284 $result[0]['amount'] = $dao->amount;
285 }
286 }
287 return $result;
288 }
289
290 /**
291 * Given an entity_id and entity_table, check for corresponding entity_financial_trxn and financial_trxn record.
292 * NOTE: This should be moved to separate BAO for EntityFinancialTrxn when we start adding more code for that object.
293 *
294 * @param $entity_id
295 * Id of the entity usually the contactID.
296 * @param string $entity_table
297 * Name of the entity table usually 'civicrm_contact'.
298 *
299 * @return array
300 * array of category id's the contact belongs to.
301 *
302 */
303 public static function getFinancialTrxnLineTotal($entity_id, $entity_table = 'civicrm_contribution') {
304 $query = "SELECT lt.price_field_value_id AS id, ft.financial_trxn_id,ft.amount AS amount FROM civicrm_entity_financial_trxn AS ft
305 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'
306 LEFT JOIN civicrm_line_item AS lt ON lt.id = fi.entity_id AND lt.entity_table = %2
307 WHERE lt.entity_id = %1 ";
308
309 $sqlParams = array(1 => array($entity_id, 'Integer'), 2 => array($entity_table, 'String'));
310 $dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
311 while ($dao->fetch()) {
312 $result[$dao->financial_trxn_id][$dao->id] = $dao->amount;
313 }
314 if (!empty($result)) {
315 return $result;
316 }
317 else {
318 return NULL;
319 }
320 }
321
322 /**
323 * Delete financial transaction.
324 *
325 * @param int $entity_id
326 * @return bool
327 * TRUE on success, FALSE otherwise.
328 */
329 public static function deleteFinancialTrxn($entity_id) {
330 $query = "DELETE ceft1, cfi, ceft, cft FROM `civicrm_financial_trxn` cft
331 LEFT JOIN civicrm_entity_financial_trxn ceft
332 ON ceft.financial_trxn_id = cft.id AND ceft.entity_table = 'civicrm_contribution'
333 LEFT JOIN civicrm_entity_financial_trxn ceft1
334 ON ceft1.financial_trxn_id = cft.id AND ceft1.entity_table = 'civicrm_financial_item'
335 LEFT JOIN civicrm_financial_item cfi
336 ON ceft1.entity_table = 'civicrm_financial_item' and cfi.id = ceft1.entity_id
337 WHERE ceft.entity_id = %1";
338 CRM_Core_DAO::executeQuery($query, array(1 => array($entity_id, 'Integer')));
339 return TRUE;
340 }
341
342 /**
343 * Create financial transaction for premium.
344 *
345 * @param array $params
346 * - oldPremium
347 * - financial_type_id
348 * - contributionId
349 * - isDeleted
350 * - cost
351 * - currency
352 */
353 public static function createPremiumTrxn($params) {
354 if ((empty($params['financial_type_id']) || empty($params['contributionId'])) && empty($params['oldPremium'])) {
355 return;
356 }
357
358 if (!empty($params['cost'])) {
359 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
360 $financialAccountType = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id']);
361 $accountRelationship = CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name IN ('Premiums Inventory Account is', 'Cost of Sales Account is')");
362 $toFinancialAccount = !empty($params['isDeleted']) ? 'Premiums Inventory Account is' : 'Cost of Sales Account is';
363 $fromFinancialAccount = !empty($params['isDeleted']) ? 'Cost of Sales Account is' : 'Premiums Inventory Account is';
364 $accountRelationship = array_flip($accountRelationship);
365 $financialtrxn = array(
366 'to_financial_account_id' => $financialAccountType[$accountRelationship[$toFinancialAccount]],
367 'from_financial_account_id' => $financialAccountType[$accountRelationship[$fromFinancialAccount]],
368 'trxn_date' => date('YmdHis'),
369 'total_amount' => CRM_Utils_Array::value('cost', $params) ? $params['cost'] : 0,
370 'currency' => CRM_Utils_Array::value('currency', $params),
371 'status_id' => array_search('Completed', $contributionStatuses),
372 );
373 $trxnEntityTable['entity_table'] = 'civicrm_contribution';
374 $trxnEntityTable['entity_id'] = $params['contributionId'];
375 CRM_Core_BAO_FinancialTrxn::create($financialtrxn, $trxnEntityTable);
376 }
377
378 if (!empty($params['oldPremium'])) {
379 $premiumParams = array(
380 'id' => $params['oldPremium']['product_id'],
381 );
382 $productDetails = array();
383 CRM_Contribute_BAO_ManagePremiums::retrieve($premiumParams, $productDetails);
384 $params = array(
385 'cost' => CRM_Utils_Array::value('cost', $productDetails),
386 'currency' => CRM_Utils_Array::value('currency', $productDetails),
387 'financial_type_id' => CRM_Utils_Array::value('financial_type_id', $productDetails),
388 'contributionId' => $params['oldPremium']['contribution_id'],
389 'isDeleted' => TRUE,
390 );
391 CRM_Core_BAO_FinancialTrxn::createPremiumTrxn($params);
392 }
393 }
394
395 /**
396 * Create financial trxn and items when fee is charged.
397 *
398 * @param array $params
399 * To create trxn entries.
400 *
401 * @return bool
402 */
403 public static function recordFees($params) {
404 $expenseTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
405 $domainId = CRM_Core_Config::domainID();
406 $amount = 0;
407 if (!empty($params['prevContribution'])) {
408 $amount = $params['prevContribution']->fee_amount;
409 }
410 $amount = $params['fee_amount'] - $amount;
411 if (!$amount) {
412 return FALSE;
413 }
414 $contributionId = isset($params['contribution']->id) ? $params['contribution']->id : $params['contribution_id'];
415 if (empty($params['financial_type_id'])) {
416 $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id', 'id');
417 }
418 else {
419 $financialTypeId = $params['financial_type_id'];
420 }
421 $financialAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $expenseTypeId);
422
423 $params['trxnParams']['from_financial_account_id'] = $params['to_financial_account_id'];
424 $params['trxnParams']['to_financial_account_id'] = $financialAccount;
425 $params['trxnParams']['total_amount'] = $amount;
426 $params['trxnParams']['fee_amount'] = $params['trxnParams']['net_amount'] = 0;
427 $params['trxnParams']['status_id'] = $params['contribution_status_id'];
428 $params['trxnParams']['contribution_id'] = $contributionId;
429 $params['trxnParams']['is_payment'] = FALSE;
430 $trxn = self::create($params['trxnParams']);
431 if (empty($params['entity_id'])) {
432 $financialTrxnID = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['trxnParams']['contribution_id'], 'DESC');
433 $params['entity_id'] = $financialTrxnID['financialTrxnId'];
434 }
435 $fItemParams
436 = array(
437 'financial_account_id' => $financialAccount,
438 'contact_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Domain', $domainId, 'contact_id'),
439 'created_date' => date('YmdHis'),
440 'transaction_date' => date('YmdHis'),
441 'amount' => $amount,
442 'description' => 'Fee',
443 'status_id' => CRM_Core_OptionGroup::getValue('financial_item_status', 'Paid', 'name'),
444 'entity_table' => 'civicrm_financial_trxn',
445 'entity_id' => $params['entity_id'],
446 'currency' => $params['trxnParams']['currency'],
447 );
448 $trxnIDS['id'] = $trxn->id;
449 $financialItem = CRM_Financial_BAO_FinancialItem::create($fItemParams, NULL, $trxnIDS);
450 }
451
452 /**
453 * get partial payment amount and type of it.
454 *
455 * @param int $entityId
456 * @param string $entityName
457 * @param bool $returnType
458 * @param int $lineItemTotal
459 *
460 * @return array|int|NULL|string
461 * [payment type => amount]
462 * payment type: 'amount_owed' or 'refund_due'
463 */
464 public static function getPartialPaymentWithType($entityId, $entityName = 'participant', $returnType = TRUE, $lineItemTotal = NULL) {
465 $value = NULL;
466 if (empty($entityName)) {
467 return $value;
468 }
469
470 if ($entityName == 'participant') {
471 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $entityId, 'contribution_id', 'participant_id');
472 }
473 else {
474 $contributionId = $entityId;
475 }
476 $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
477
478 if ($contributionId && $financialTypeId) {
479 $statusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
480 $refundStatusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name');
481
482 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
483 $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $relationTypeId);
484 $feeRelationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
485 $feeFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $feeRelationTypeId);
486
487 if (empty($lineItemTotal)) {
488 $lineItemTotal = CRM_Price_BAO_LineItem::getLineTotal($contributionId);
489 }
490 $sqlFtTotalAmt = "
491 SELECT SUM(ft.total_amount)
492 FROM civicrm_financial_trxn ft
493 INNER JOIN civicrm_entity_financial_trxn eft ON (ft.id = eft.financial_trxn_id AND eft.entity_table = 'civicrm_contribution' AND eft.entity_id = {$contributionId})
494 WHERE ft.to_financial_account_id != {$toFinancialAccount} AND ft.to_financial_account_id != {$feeFinancialAccount}
495 AND ft.status_id IN ({$statusId}, {$refundStatusId})
496 ";
497 $ftTotalAmt = CRM_Core_DAO::singleValueQuery($sqlFtTotalAmt);
498 $value = 0;
499 if (!$ftTotalAmt) {
500 $ftTotalAmt = 0;
501 }
502 $value = $paymentVal = $lineItemTotal - $ftTotalAmt;
503 if ($returnType) {
504 $value = array();
505 if ($paymentVal < 0) {
506 $value['refund_due'] = $paymentVal;
507 }
508 elseif ($paymentVal > 0) {
509 $value['amount_owed'] = $paymentVal;
510 }
511 elseif ($lineItemTotal == $ftTotalAmt) {
512 $value['full_paid'] = $ftTotalAmt;
513 }
514 }
515 }
516 return $value;
517 }
518
519 /**
520 * @param int $contributionId
521 *
522 * @return array
523 */
524 public static function getTotalPayments($contributionId) {
525 $statusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
526
527 $sql = "SELECT SUM(ft.total_amount) FROM civicrm_financial_trxn ft
528 INNER JOIN civicrm_entity_financial_trxn eft ON (eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution')
529 WHERE eft.entity_id = %1 AND ft.is_payment = 1 AND ft.status_id = %2";
530
531 $params = array(
532 1 => array($contributionId, 'Integer'),
533 2 => array($statusId, 'Integer'),
534 );
535
536 return CRM_Core_DAO::singleValueQuery($sql, $params);
537 }
538
539 /**
540 * Function records partial payment, complete's contribution if payment is fully paid
541 * and returns latest payment ie financial trxn
542 *
543 * @param array $contribution
544 * @param array $params
545 *
546 * @return CRM_Core_BAO_FinancialTrxn
547 */
548 public static function getPartialPaymentTrxn($contribution, $params) {
549 $trxn = CRM_Contribute_BAO_Contribution::recordPartialPayment($contribution, $params);
550 $paid = CRM_Core_BAO_FinancialTrxn::getTotalPayments($params['contribution_id']);
551 $total = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution_id'], 'total_amount');
552 $cmp = bccomp($total, $paid, 5);
553 if ($cmp == 0 || $cmp == -1) {// If paid amount is greater or equal to total amount
554 civicrm_api3('Contribution', 'completetransaction', array('id' => $contribution['id']));
555 }
556 return $trxn;
557 }
558
559 /**
560 * Get revenue amount for membership.
561 *
562 * @param array $lineItem
563 *
564 * @return array
565 */
566 public static function getMembershipRevenueAmount($lineItem) {
567 $revenueAmount = array();
568 $membershipDetail = civicrm_api3('Membership', 'getsingle', array(
569 'id' => $lineItem['entity_id'],
570 ));
571 if (empty($membershipDetail['end_date'])) {
572 return $revenueAmount;
573 }
574
575 $startDate = strtotime($membershipDetail['start_date']);
576 $endDate = strtotime($membershipDetail['end_date']);
577 $startYear = date('Y', $startDate);
578 $endYear = date('Y', $endDate);
579 $startMonth = date('m', $startDate);
580 $endMonth = date('m', $endDate);
581
582 $monthOfService = (($endYear - $startYear) * 12) + ($endMonth - $startMonth);
583 $startDateOfRevenue = $membershipDetail['start_date'];
584 $typicalPayment = round(($lineItem['line_total'] / $monthOfService), 2);
585 for ($i = 0; $i <= $monthOfService - 1; $i++) {
586 $revenueAmount[$i]['amount'] = $typicalPayment;
587 if ($i == 0) {
588 $revenueAmount[$i]['amount'] -= (($typicalPayment * $monthOfService) - $lineItem['line_total']);
589 }
590 $revenueAmount[$i]['revenue_date'] = $startDateOfRevenue;
591 $startDateOfRevenue = date('Y-m', strtotime('+1 month', strtotime($startDateOfRevenue))) . '-01';
592 }
593 return $revenueAmount;
594 }
595
596 /**
597 * Create transaction for deferred revenue.
598 *
599 * @param array $lineItems
600 *
601 * @param array $contributionDetails
602 *
603 * @param bool $update
604 *
605 * @param string $context
606 *
607 */
608 public static function createDeferredTrxn($lineItems, $contributionDetails, $update = FALSE, $context = NULL) {
609 if (empty($lineItems)) {
610 return FALSE;
611 }
612 $revenueRecognitionDate = $contributionDetails->revenue_recognition_date;
613 if (!CRM_Utils_System::isNull($revenueRecognitionDate)) {
614 $statuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
615 if (!$update
616 && (CRM_Utils_Array::value($contributionDetails->contribution_status_id, $statuses) != 'Completed'
617 || (CRM_Utils_Array::value($contributionDetails->contribution_status_id, $statuses) != 'Pending'
618 && $contributionDetails->is_pay_later)
619 )
620 ) {
621 return;
622 }
623 $trxnParams = array(
624 'contribution_id' => $contributionDetails->id,
625 'fee_amount' => '0.00',
626 'currency' => $contributionDetails->currency,
627 'trxn_id' => $contributionDetails->trxn_id,
628 'status_id' => $contributionDetails->contribution_status_id,
629 'payment_instrument_id' => $contributionDetails->payment_instrument_id,
630 'check_number' => $contributionDetails->check_number,
631 );
632
633 $deferredRevenues = array();
634 foreach ($lineItems as $priceSetID => $lineItem) {
635 if (!$priceSetID) {
636 continue;
637 }
638 foreach ($lineItem as $key => $item) {
639 $lineTotal = !empty($item['deferred_line_total']) ? $item['deferred_line_total'] : $item['line_total'];
640 if ($lineTotal <= 0 && !$update) {
641 continue;
642 }
643 $deferredRevenues[$key] = $item;
644 if ($context == 'changeFinancialType') {
645 $deferredRevenues[$key]['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_LineItem', $item['id'], 'financial_type_id');
646 }
647 if (in_array($item['entity_table'],
648 array('civicrm_participant', 'civicrm_contribution'))
649 ) {
650 $deferredRevenues[$key]['revenue'][] = array(
651 'amount' => $lineTotal,
652 'revenue_date' => $revenueRecognitionDate,
653 );
654 }
655 else {
656 // for membership
657 $item['line_total'] = $lineTotal;
658 $deferredRevenues[$key]['revenue'] = self::getMembershipRevenueAmount($item);
659 }
660 }
661 }
662 $accountRel = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
663
664 CRM_Utils_Hook::alterDeferredRevenueItems($deferredRevenues, $contributionDetails, $update, $context);
665
666 foreach ($deferredRevenues as $key => $deferredRevenue) {
667 $results = civicrm_api3('EntityFinancialAccount', 'get', array(
668 'entity_table' => 'civicrm_financial_type',
669 'entity_id' => $deferredRevenue['financial_type_id'],
670 'account_relationship' => array('IN' => array('Income Account is', 'Deferred Revenue Account is')),
671 ));
672 if ($results['count'] != 2) {
673 continue;
674 }
675 foreach ($results['values'] as $result) {
676 if ($result['account_relationship'] == $accountRel) {
677 $trxnParams['to_financial_account_id'] = $result['financial_account_id'];
678 }
679 else {
680 $trxnParams['from_financial_account_id'] = $result['financial_account_id'];
681 }
682 }
683 foreach ($deferredRevenue['revenue'] as $revenue) {
684 $trxnParams['total_amount'] = $trxnParams['net_amount'] = $revenue['amount'];
685 $trxnParams['trxn_date'] = CRM_Utils_Date::isoToMysql($revenue['revenue_date']);
686 $financialTxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
687 $entityParams = array(
688 'entity_id' => $deferredRevenue['financial_item_id'],
689 'entity_table' => 'civicrm_financial_item',
690 'amount' => $revenue['amount'],
691 'financial_trxn_id' => $financialTxn->id,
692 );
693 civicrm_api3('EntityFinancialTrxn', 'create', $entityParams);
694 }
695 }
696 }
697 }
698
699 }