3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
35 * Business objects for Line Items generated by monetary transactions
37 class CRM_Price_BAO_LineItem
extends CRM_Price_DAO_LineItem
{
40 * Creates a new entry in the database.
42 * @param array $params
43 * (reference) an assoc array of name/value pairs.
45 * @return \CRM_Price_DAO_LineItem
47 * @throws \CiviCRM_API3_Exception
50 public static function create(&$params) {
51 $id = CRM_Utils_Array
::value('id', $params);
53 CRM_Utils_Hook
::pre('edit', 'LineItem', $id, $params);
54 $op = CRM_Core_Action
::UPDATE
;
57 CRM_Utils_Hook
::pre('create', 'LineItem', $params['entity_id'], $params);
58 $op = CRM_Core_Action
::ADD
;
61 // unset entity table and entity id in $params
62 // we never update the entity table and entity id during update mode
64 $entity_id = CRM_Utils_Array
::value('entity_id', $params);
65 $entity_table = CRM_Utils_Array
::value('entity_table', $params);
66 unset($params['entity_id'], $params['entity_table']);
69 if (!isset($params['unit_price'])) {
70 $params['unit_price'] = 0;
73 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus() && CRM_Utils_Array
::value('check_permissions', $params)) {
74 if (empty($params['financial_type_id'])) {
75 throw new Exception('Mandatory key(s) missing from params array: financial_type_id');
77 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($types, $op);
78 if (!in_array($params['financial_type_id'], array_keys($types))) {
79 throw new Exception('You do not have permission to create this line item');
83 $lineItemBAO = new CRM_Price_BAO_LineItem();
84 $lineItemBAO->copyValues($params);
86 $return = $lineItemBAO->save();
87 if ($lineItemBAO->entity_table
== 'civicrm_membership' && $lineItemBAO->contribution_id
&& $lineItemBAO->entity_id
) {
88 $membershipPaymentParams = array(
89 'membership_id' => $lineItemBAO->entity_id
,
90 'contribution_id' => $lineItemBAO->contribution_id
,
92 if (!civicrm_api3('MembershipPayment', 'getcount', $membershipPaymentParams)) {
93 civicrm_api3('MembershipPayment', 'create', $membershipPaymentParams);
98 // CRM-21281: Restore entity reference in case the post hook needs it
99 $lineItemBAO->entity_id
= $entity_id;
100 $lineItemBAO->entity_table
= $entity_table;
101 CRM_Utils_Hook
::post('edit', 'LineItem', $id, $lineItemBAO);
104 CRM_Utils_Hook
::post('create', 'LineItem', $lineItemBAO->id
, $lineItemBAO);
111 * Retrieve DB object based on input parameters.
113 * It also stores all the retrieved values in the default array.
115 * @param array $params
116 * (reference ) an assoc array of name/value pairs.
117 * @param array $defaults
118 * (reference ) an assoc array to hold the flattened values.
120 * @return CRM_Price_BAO_LineItem
122 public static function retrieve(&$params, &$defaults) {
123 $lineItem = new CRM_Price_BAO_LineItem();
124 $lineItem->copyValues($params);
125 if ($lineItem->find(TRUE)) {
126 CRM_Core_DAO
::storeValues($lineItem, $defaults);
133 * Modifies $params array for filtering financial types.
135 * @param array $params
136 * (reference ) an assoc array of name/value pairs.
139 public static function getAPILineItemParams(&$params) {
140 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($types);
141 if ($types && empty($params['financial_type_id'])) {
142 $params['financial_type_id'] = array('IN' => array_keys($types));
145 if (is_array($params['financial_type_id'])) {
146 $invalidFts = array_diff($params['financial_type_id'], array_keys($types));
148 elseif (!in_array($params['financial_type_id'], array_keys($types))) {
149 $invalidFts = $params['financial_type_id'];
152 $params['financial_type_id'] = array('NOT IN' => $invalidFts);
156 $params['financial_type_id'] = 0;
161 * @param int $contributionId
163 * @return null|string
165 public static function getLineTotal($contributionId) {
166 $sqlLineItemTotal = "SELECT SUM(li.line_total + COALESCE(li.tax_amount,0))
167 FROM civicrm_line_item li
168 WHERE li.contribution_id = %1";
169 $params = array(1 => array($contributionId, 'Integer'));
170 $lineItemTotal = CRM_Core_DAO
::singleValueQuery($sqlLineItemTotal, $params);
171 return $lineItemTotal;
175 * Wrapper for line item retrieval when contribution ID is known.
176 * @param int $contributionID
180 public static function getLineItemsByContributionID($contributionID) {
181 return self
::getLineItems($contributionID, 'contribution', NULL, TRUE, TRUE, " WHERE contribution_id = " . (int) $contributionID);
185 * Given a participant id/contribution id,
186 * return contribution/fee line items
188 * @param int $entityId
189 * participant/contribution id.
190 * @param string $entity
191 * participant/contribution.
193 * @param bool $isQuick
194 * @param bool $isQtyZero
195 * @param bool $relatedEntity
197 * @param bool $invoice
199 * Array of line items
201 public static function getLineItems($entityId, $entity = 'participant', $isQuick = FALSE, $isQtyZero = TRUE, $relatedEntity = FALSE, $invoice = FALSE) {
202 $whereClause = $fromClause = NULL;
212 pf.label as field_title,
215 pfv.membership_type_id,
216 pfv.membership_num_terms,
218 li.participant_count,
219 li.price_field_value_id,
220 li.financial_type_id,
224 $condition = "li.entity_id = %2.id AND li.entity_table = 'civicrm_%2'";
225 if ($relatedEntity) {
226 $condition = "li.contribution_id = %2.id ";
230 FROM civicrm_%2 as %2
231 LEFT JOIN civicrm_line_item li ON ({$condition})
232 LEFT JOIN civicrm_price_field_value pfv ON ( pfv.id = li.price_field_value_id )
233 LEFT JOIN civicrm_price_field pf ON (pf.id = li.price_field_id )";
237 // CRM-16250 get additional participant's fee selection details only for invoice PDF (if any)
238 if ($entity == 'participant' && $invoice) {
239 $additionalParticipantIDs = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
240 if (!empty($additionalParticipantIDs)) {
241 $whereClause = "WHERE %2.id IN (%1, " . implode(', ', $additionalParticipantIDs) . ")";
245 $orderByClause = " ORDER BY pf.weight, pfv.weight";
248 $fromClause .= " LEFT JOIN civicrm_price_set cps on cps.id = pf.price_set_id ";
249 $whereClause .= " and cps.is_quick_config = 0";
253 $whereClause .= " and li.qty != 0";
256 $lineItems = array();
258 if (!$entityId ||
!$entity ||
!$fromClause) {
263 1 => array($entityId, 'Integer'),
264 2 => array($entity, 'Text'),
267 $getTaxDetails = FALSE;
268 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
269 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
271 $dao = CRM_Core_DAO
::executeQuery("$selectClause $fromClause $whereClause $orderByClause", $params);
272 while ($dao->fetch()) {
276 $lineItems[$dao->id
] = array(
277 'qty' => (float) $dao->qty
,
278 'label' => $dao->label
,
279 'unit_price' => $dao->unit_price
,
280 'line_total' => $dao->line_total
,
281 'price_field_id' => $dao->price_field_id
,
282 'participant_count' => $dao->participant_count
,
283 'price_field_value_id' => $dao->price_field_value_id
,
284 'field_title' => $dao->field_title
,
285 'html_type' => $dao->html_type
,
286 'description' => $dao->description
,
287 'entity_id' => $dao->entity_id
,
288 'entity_table' => $dao->entity_table
,
289 'contribution_id' => $dao->contribution_id
,
290 'financial_type_id' => $dao->financial_type_id
,
291 'financial_type' => CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'financial_type_id', $dao->financial_type_id
),
292 'membership_type_id' => $dao->membership_type_id
,
293 'membership_num_terms' => $dao->membership_num_terms
,
294 'tax_amount' => $dao->tax_amount
,
295 'price_set_id' => $dao->price_set_id
,
297 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
298 if (isset($lineItems[$dao->id
]['financial_type_id']) && array_key_exists($lineItems[$dao->id
]['financial_type_id'], $taxRates)) {
299 // Cast to float so trailing zero decimals are removed for display.
300 $lineItems[$dao->id
]['tax_rate'] = (float) $taxRates[$lineItems[$dao->id
]['financial_type_id']];
303 // There is no Tax Rate associated with this Financial Type
304 $lineItems[$dao->id
]['tax_rate'] = FALSE;
306 $lineItems[$dao->id
]['subTotal'] = $lineItems[$dao->id
]['qty'] * $lineItems[$dao->id
]['unit_price'];
307 if ($lineItems[$dao->id
]['tax_amount'] != '') {
308 $getTaxDetails = TRUE;
312 // @todo - this is an inappropriate place to be doing form level assignments.
313 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
314 $smarty = CRM_Core_Smarty
::singleton();
315 $smarty->assign('taxTerm', $taxTerm);
316 $smarty->assign('getTaxDetails', $getTaxDetails);
322 * This method will create the lineItem array required for
323 * processAmount method
326 * Price set field id.
327 * @param array $params
328 * Reference to form values.
329 * @param array $fields
330 * Array of fields belonging to the price set used for particular event
331 * @param array $values
332 * Reference to the values array(.
335 * @param string $amount_override
337 public static function format($fid, $params, $fields, &$values, $amount_override = NULL) {
338 if (empty($params["price_{$fid}"])) {
342 //lets first check in fun parameter,
343 //since user might modified w/ hooks.
345 if (array_key_exists('options', $fields)) {
346 $options = $fields['options'];
349 CRM_Price_BAO_PriceFieldValue
::getValues($fid, $options, 'weight', TRUE);
351 $fieldTitle = CRM_Utils_Array
::value('label', $fields);
353 $fieldTitle = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'label');
356 foreach ($params["price_{$fid}"] as $oid => $qty) {
357 $price = $amount_override === NULL ?
$options[$oid]['amount'] : $amount_override;
359 // lets clean the price in case it is not yet cleant
361 $price = CRM_Utils_Rule
::cleanMoney($price);
363 $participantsPerField = CRM_Utils_Array
::value('count', $options[$oid], 0);
365 $values[$oid] = array(
366 'price_field_id' => $fid,
367 'price_field_value_id' => $oid,
368 'label' => CRM_Utils_Array
::value('label', $options[$oid]),
369 'field_title' => $fieldTitle,
370 'description' => CRM_Utils_Array
::value('description', $options[$oid]),
372 'unit_price' => $price,
373 'line_total' => $qty * $price,
374 'participant_count' => $qty * $participantsPerField,
375 'max_value' => CRM_Utils_Array
::value('max_value', $options[$oid]),
376 'membership_type_id' => CRM_Utils_Array
::value('membership_type_id', $options[$oid]),
377 'membership_num_terms' => CRM_Utils_Array
::value('membership_num_terms', $options[$oid]),
378 'auto_renew' => CRM_Utils_Array
::value('auto_renew', $options[$oid]),
379 'html_type' => $fields['html_type'],
380 'financial_type_id' => CRM_Utils_Array
::value('financial_type_id', $options[$oid]),
381 'tax_amount' => CRM_Utils_Array
::value('tax_amount', $options[$oid]),
382 'non_deductible_amount' => CRM_Utils_Array
::value('non_deductible_amount', $options[$oid]),
385 if ($values[$oid]['membership_type_id'] && empty($values[$oid]['auto_renew'])) {
386 $values[$oid]['auto_renew'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $values[$oid]['membership_type_id'], 'auto_renew');
392 * Delete line items for given entity.
394 * @param int $entityId
395 * @param int $entityTable
399 public static function deleteLineItems($entityId, $entityTable) {
400 if (!$entityId ||
!$entityTable) {
404 if ($entityId && !is_array($entityId)) {
405 $entityId = array($entityId);
408 $query = "DELETE FROM civicrm_line_item where entity_id IN ('" . implode("','", $entityId) . "') AND entity_table = '$entityTable'";
409 $dao = CRM_Core_DAO
::executeQuery($query);
414 * Process price set and line items.
416 * @param int $entityId
417 * @param array $lineItem
419 * @param object $contributionDetails
420 * @param string $entityTable
423 * @param bool $update
427 public static function processPriceSet($entityId, $lineItem, $contributionDetails = NULL, $entityTable = 'civicrm_contribution', $update = FALSE) {
428 if (!$entityId ||
!is_array($lineItem)
429 || CRM_Utils_system
::isNull($lineItem)
434 foreach ($lineItem as $priceSetId => &$values) {
439 foreach ($values as &$line) {
440 if (empty($line['entity_table'])) {
441 $line['entity_table'] = $entityTable;
443 if (empty($line['entity_id'])) {
444 $line['entity_id'] = $entityId;
446 if (!empty($line['membership_type_id'])) {
447 $line['entity_table'] = 'civicrm_membership';
449 if (!empty($contributionDetails->id
)) {
450 $line['contribution_id'] = $contributionDetails->id
;
451 if ($line['entity_table'] == 'civicrm_contribution') {
452 $line['entity_id'] = $contributionDetails->id
;
454 // CRM-19094: entity_table is set to civicrm_membership then ensure
455 // the entityId is set to membership ID not contribution by default
456 elseif ($line['entity_table'] == 'civicrm_membership' && !empty($line['entity_id']) && $line['entity_id'] == $contributionDetails->id
) {
457 $membershipId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', 'contribution_id', $line['entity_id'], 'membership_id');
458 $line['entity_id'] = $membershipId ?
$membershipId : $line['entity_id'];
462 // if financial type is not set and if price field value is NOT NULL
463 // get financial type id of price field value
464 if (!empty($line['price_field_value_id']) && empty($line['financial_type_id'])) {
465 $line['financial_type_id'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $line['price_field_value_id'], 'financial_type_id');
467 $lineItems = CRM_Price_BAO_LineItem
::create($line);
468 if (!$update && $contributionDetails) {
469 $financialItem = CRM_Financial_BAO_FinancialItem
::add($lineItems, $contributionDetails);
470 $line['financial_item_id'] = $financialItem->id
;
471 if (!empty($line['tax_amount'])) {
472 CRM_Financial_BAO_FinancialItem
::add($lineItems, $contributionDetails, TRUE);
477 if (!$update && $contributionDetails) {
478 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn($lineItem, $contributionDetails);
483 * @param int $entityId
484 * @param string $entityTable
486 * @param array $otherParams
488 public static function syncLineItems($entityId, $entityTable = 'civicrm_contribution', $amount, $otherParams = NULL) {
489 if (!$entityId || CRM_Utils_System
::isNull($amount)) {
493 $from = " civicrm_line_item li
494 LEFT JOIN civicrm_price_field pf ON pf.id = li.price_field_id
495 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id ";
497 $set = " li.unit_price = %3,
498 li.line_total = %3 ";
500 $where = " li.entity_id = %1 AND
501 li.entity_table = %2 ";
504 1 => array($entityId, 'Integer'),
505 2 => array($entityTable, 'String'),
506 3 => array($amount, 'Float'),
509 if ($entityTable == 'civicrm_contribution') {
510 $entityName = 'default_contribution_amount';
511 $where .= " AND ps.name = %4 ";
512 $params[4] = array($entityName, 'String');
514 elseif ($entityTable == 'civicrm_participant') {
516 LEFT JOIN civicrm_price_set_entity cpse ON cpse.price_set_id = ps.id
517 LEFT JOIN civicrm_price_field_value cpfv ON cpfv.price_field_id = pf.id and cpfv.label = %4 ";
518 $set .= " ,li.label = %4,
519 li.price_field_value_id = cpfv.id ";
520 $where .= " AND cpse.entity_table = 'civicrm_event' AND cpse.entity_id = %5 ";
521 $amount = empty($amount) ?
0 : $amount;
523 4 => array($otherParams['fee_label'], 'String'),
524 5 => array($otherParams['event_id'], 'String'),
534 CRM_Core_DAO
::executeQuery($query, $params);
538 * Build line items array.
540 * @param array $params
543 * @param string $entityId
546 * @param string $entityTable
549 * @param bool $isRelatedID
551 public static function getLineItemArray(&$params, $entityId = NULL, $entityTable = 'contribution', $isRelatedID = FALSE) {
553 $priceSetDetails = CRM_Price_BAO_PriceSet
::getDefaultPriceSet($entityTable);
554 $totalAmount = CRM_Utils_Array
::value('partial_payment_total', $params, CRM_Utils_Array
::value('total_amount', $params));
555 $financialType = CRM_Utils_Array
::value('financial_type_id', $params);
556 foreach ($priceSetDetails as $values) {
557 if ($entityTable == 'membership') {
558 if ($isRelatedID != $values['membership_type_id']) {
562 $totalAmount = $values['amount'];
564 $financialType = $values['financial_type_id'];
566 $params['line_item'][$values['setID']][$values['priceFieldID']] = array(
567 'price_field_id' => $values['priceFieldID'],
568 'price_field_value_id' => $values['priceFieldValueID'],
569 'label' => $values['label'],
571 'unit_price' => $totalAmount,
572 'line_total' => $totalAmount,
573 'financial_type_id' => $financialType,
574 'membership_type_id' => $values['membership_type_id'],
581 $totalEntityId = count($entityId);
582 if ($entityTable == 'contribution') {
585 foreach ($entityId as $id) {
586 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($id, $entityTable, FALSE, TRUE, $isRelatedID);
587 foreach ($lineItems as $key => $values) {
588 if (!$setID && $values['price_field_id']) {
589 $setID = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $values['price_field_id'], 'price_set_id');
590 $params['is_quick_config'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $setID, 'is_quick_config');
592 if (!empty($params['is_quick_config']) && array_key_exists('total_amount', $params)
593 && $totalEntityId == 1
595 $values['line_total'] = $values['unit_price'] = $params['total_amount'];
597 $values['id'] = $key;
598 $params['line_item'][$setID][$key] = $values;
605 * Function to update related contribution of a entity and
606 * add/update/cancel financial records
608 * @param array $params
609 * @param int $entityID
611 * @param int $contributionId
613 * @param array $lineItems
617 public static function changeFeeSelections(
626 $entityTable = "civicrm_" . $entity;
627 CRM_Price_BAO_PriceSet
::processAmount($feeBlock,
630 // initialize empty Lineitem instance to call protected helper functions
631 $lineItemObj = new CRM_Price_BAO_LineItem();
633 // fetch submitted LineItems from input params and feeBlock information
634 $submittedLineItems = $lineItemObj->getSubmittedLineItems($params, $feeBlock);
636 // retrieve the submitted price field value IDs from $submittedLineItems array keys
637 $submittedPriceFieldValueIDs = empty($submittedLineItems) ?
array() : array_keys($submittedLineItems);
639 $requiredChanges = $lineItemObj->getLineItemsToAlter($submittedLineItems, $entityID, $entity);
641 // cancel previous line item
642 $additionalWhereClause = empty($submittedPriceFieldValueIDs) ?
NULL : sprintf("price_field_value_id NOT IN (%s)", implode(', ', $submittedPriceFieldValueIDs));
643 $lineItemObj->cancelLineItems($entityID, $entityTable, $additionalWhereClause);
645 // get financial information that need to be recorded on basis on submitted price field value IDs
646 $financialItemsArray = $lineItemObj->getReverseFinancialItemsToRecord(
650 $submittedPriceFieldValueIDs
653 // update line item with changed line total and other information
654 $totalParticipant = $participantCount = 0;
655 $amountLevel = array();
656 if (!empty($requiredChanges['line_items_to_update'])) {
657 foreach ($requiredChanges['line_items_to_update'] as $priceFieldValueID => $value) {
659 if (isset($value['tax_amount'])) {
660 $taxAmount = $value['tax_amount'];
662 $amountLevel[] = $value['label'] . ' - ' . (float) $value['qty'];
663 if ($entity == 'participant' && isset($value['participant_count'])) {
664 $participantCount = $value['participant_count'];
665 $totalParticipant +
= $value['participant_count'];
667 $updateLineItemSQL = "
668 UPDATE civicrm_line_item li
669 SET li.qty = {$value['qty']},
670 li.line_total = {$value['line_total']},
671 li.tax_amount = {$taxAmount},
672 li.unit_price = {$value['unit_price']},
673 li.participant_count = {$participantCount},
675 WHERE (li.entity_table = '{$entityTable}' AND li.entity_id = {$entityID}) AND
676 (price_field_value_id = {$priceFieldValueID}) ";
678 CRM_Core_DAO
::executeQuery($updateLineItemSQL, array(1 => array($value['label'], 'String')));
682 // insert new 'adjusted amount' transaction entry and update contribution entry.
683 // ensure entity_financial_trxn table has a linking of it.
684 // insert new line items
685 $lineItemObj->addLineItemOnChangeFeeSelection($requiredChanges['line_items_to_add'], $entityID, $entityTable, $contributionId);
687 // the recordAdjustedAmt code would execute over here
689 if ($entity == 'participant') {
690 $count = count(CRM_Event_BAO_Participant
::getParticipantIds($contributionId));
693 $count = CRM_Utils_Array
::value('count', civicrm_api3('MembershipPayment', 'getcount', array('contribution_id' => $contributionId)));
696 $updatedAmount = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
699 $updatedAmount = CRM_Utils_Array
::value('amount', $params, CRM_Utils_Array
::value('total_amount', $params));
701 if (strlen($params['tax_amount']) != 0) {
702 $taxAmount = $params['tax_amount'];
707 $displayParticipantCount = '';
708 if ($totalParticipant > 0) {
709 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
711 $updateAmountLevel = NULL;
712 if (!empty($amountLevel)) {
713 $updateAmountLevel = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amountLevel) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
715 $trxn = $lineItemObj->recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount, $updateAmountLevel);
717 $contributionCompletedStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_DAO_Contribution', 'contribution_status_id', 'Completed');
718 if (!empty($financialItemsArray)) {
719 foreach ($financialItemsArray as $updateFinancialItemInfoValues) {
720 $newFinancialItem = CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues);
721 // record reverse transaction only if Contribution is Completed because for pending refund or
722 // partially paid we are already recording the surplus owed or refund amount
723 if (!empty($updateFinancialItemInfoValues['financialTrxn']) && ($contributionCompletedStatusID ==
724 CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'contribution_status_id'))
726 $updateFinancialItemInfoValues = array_merge($updateFinancialItemInfoValues['financialTrxn'], array(
727 'entity_id' => $newFinancialItem->id
,
728 'entity_table' => 'civicrm_financial_item',
730 $reverseTrxn = CRM_Core_BAO_FinancialTrxn
::create($updateFinancialItemInfoValues);
731 // record reverse entity financial trxn linked to membership's related contribution
732 civicrm_api3('EntityFinancialTrxn', 'create', array(
733 'entity_table' => "civicrm_contribution",
734 'entity_id' => $contributionId,
735 'financial_trxn_id' => $reverseTrxn->id
,
736 'amount' => $reverseTrxn->total_amount
,
738 unset($updateFinancialItemInfoValues['financialTrxn']);
740 if (!empty($updateFinancialItemInfoValues['tax'])) {
741 $updateFinancialItemInfoValues['tax']['amount'] = $updateFinancialItemInfoValues['amount'];
742 $updateFinancialItemInfoValues['tax']['description'] = $updateFinancialItemInfoValues['description'];
743 if (!empty($updateFinancialItemInfoValues['financial_account_id'])) {
744 $updateFinancialItemInfoValues['financial_account_id'] = $updateFinancialItemInfoValues['tax']['financial_account_id'];
746 CRM_Financial_BAO_FinancialItem
::create($updateFinancialItemInfoValues);
751 $trxnId = !empty($trxn->id
) ?
array('id' => $trxn->id
) : array();
752 $lineItemObj->addFinancialItemsOnLineItemsChange($requiredChanges['line_items_to_add'], $entityID, $entityTable, $contributionId, $trxnId);
754 // update participant fee_amount column
755 $lineItemObj->updateEntityRecordOnChangeFeeSelection($params, $entityID, $entity);
759 * Function to cancel Lineitem whose corrosponding price field option is
760 * unselected on membership or participant backoffice form
762 * @param int $entityID
763 * @param string $entityTable
764 * @param string $additionalWhereClause
767 protected function cancelLineItems($entityID, $entityTable, $additionalWhereClause = NULL) {
768 $whereClauses = array(
770 "li.entity_table = %2",
772 if ($additionalWhereClause) {
773 $whereClauses[] = $additionalWhereClause;
776 $where = implode(' AND ', $whereClauses);
778 UPDATE civicrm_line_item li
779 INNER JOIN civicrm_financial_item fi ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
781 li.line_total = 0.00,
782 li.tax_amount = NULL,
783 li.participant_count = 0,
784 li.non_deductible_amount = 0.00
787 CRM_Core_DAO
::executeQuery($sql, array(
788 1 => array($entityID, 'Integer'),
789 2 => array($entityTable, 'String'),
794 * Function to retrieve formatted financial items that need to be recorded as result of changed fee
796 * @param int $entityID
797 * @param string $entityTable
798 * @param int $contributionID
799 * @param array $submittedPriceFieldValueIDs
802 * List of formatted Financial Items to be recorded
804 protected function getReverseFinancialItemsToRecord($entityID, $entityTable, $contributionID, $submittedPriceFieldValueIDs) {
805 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, str_replace('civicrm_', '', $entityTable));
807 $financialItemsArray = array();
809 if (empty($submittedPriceFieldValueIDs)) {
810 return $financialItemsArray;
813 $financialItemResult = $this->getNonCancelledFinancialItems($entityID, $entityTable);
815 foreach ($financialItemResult as $updateFinancialItemInfoValues) {
816 $updateFinancialItemInfoValues['transaction_date'] = date('YmdHis');
817 // the below params are not needed
818 $previousFinancialItemID = $updateFinancialItemInfoValues['id'];
819 unset($updateFinancialItemInfoValues['id']);
820 unset($updateFinancialItemInfoValues['created_date']);
821 // if not submitted and difference is not 0 make it negative
822 if (!in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedPriceFieldValueIDs) && $updateFinancialItemInfoValues['differenceAmt'] != 0) {
823 // INSERT negative financial_items
824 $updateFinancialItemInfoValues['amount'] = -$updateFinancialItemInfoValues['amount'];
825 // reverse the related financial trxn too
826 $updateFinancialItemInfoValues['financialTrxn'] = $this->getRelatedCancelFinancialTrxn($previousFinancialItemID);
827 if ($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']) {
828 $updateFinancialItemInfoValues['tax']['amount'] = -($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']);
829 $updateFinancialItemInfoValues['tax']['description'] = $this->getSalesTaxTerm();
830 if ($updateFinancialItemInfoValues['financial_type_id']) {
831 $updateFinancialItemInfoValues['tax']['financial_account_id'] = CRM_Contribute_BAO_Contribution
::getFinancialAccountId($updateFinancialItemInfoValues['financial_type_id']);
834 // INSERT negative financial_items for tax amount
835 $financialItemsArray[] = $updateFinancialItemInfoValues;
837 // if submitted and difference is 0 add a positive entry again
838 elseif (in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedPriceFieldValueIDs) && $updateFinancialItemInfoValues['differenceAmt'] == 0) {
839 $updateFinancialItemInfoValues['amount'] = $updateFinancialItemInfoValues['amount'];
840 // INSERT financial_items for tax amount
841 if ($updateFinancialItemInfoValues['entity_id'] == $lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']]['id'] &&
842 isset($lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'])
844 $updateFinancialItemInfoValues['tax']['amount'] = $lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'];
845 $updateFinancialItemInfoValues['tax']['description'] = $this->getSalesTaxTerm();
846 if ($lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']) {
847 $updateFinancialItemInfoValues['tax']['financial_account_id'] = CRM_Contribute_BAO_Contribution
::getFinancialAccountId($lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']);
850 $financialItemsArray[] = $updateFinancialItemInfoValues;
854 return $financialItemsArray;
858 * Helper function to retrieve submitted line items from form values $inputParams and used $feeBlock
860 * @param array $inputParams
861 * @param array $feeBlock
864 * List of submitted line items
866 protected function getSubmittedLineItems($inputParams, $feeBlock) {
867 $submittedLineItems = array();
868 foreach ($feeBlock as $id => $values) {
869 CRM_Price_BAO_LineItem
::format($id, $inputParams, $values, $submittedLineItems);
872 return $submittedLineItems;
876 * Helper function to retrieve formatted line items that need to be altered.
878 * @param array $submittedLineItems
879 * @param int $entityID
880 * @param string $entity
883 * Array of formatted line items
885 protected function getLineItemsToAlter($submittedLineItems, $entityID, $entity) {
886 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, $entity);
888 $lineItemsToAdd = $submittedLineItems;
889 $lineItemsToUpdate = array();
890 $submittedPriceFieldValueIDs = array_keys($submittedLineItems);
892 foreach ($previousLineItems as $id => $previousLineItem) {
893 // check through the submitted items if the previousItem exists,
894 // if found in submitted items, do not use it for new item creations
895 if (in_array($previousLineItem['price_field_value_id'], $submittedPriceFieldValueIDs)) {
896 $submittedLineItem = $submittedLineItems[$previousLineItem['price_field_value_id']];
897 // if submitted line items are existing don't fire INSERT query
898 if ($previousLineItem['line_total'] != 0) {
899 unset($lineItemsToAdd[$previousLineItem['price_field_value_id']]);
902 $submittedLineItem['skip'] = TRUE;
904 // for updating the line items i.e. use-case - once deselect-option selecting again
905 if (($previousLineItem['line_total'] != $submittedLineItem['line_total'])
907 // This would be a $0 line item - but why it should be catered to
908 // other than when the above condition is unclear.
909 $submittedLineItem['line_total'] == 0 && $submittedLineItem['qty'] == 1
912 $previousLineItem['qty'] != $submittedLineItem['qty']
915 $lineItemsToUpdate[$previousLineItem['price_field_value_id']] = $submittedLineItem;
916 $lineItemsToUpdate[$previousLineItem['price_field_value_id']]['id'] = $id;
922 'line_items_to_add' => $lineItemsToAdd,
923 'line_items_to_update' => $lineItemsToUpdate,
928 * Helper function to add lineitems or financial item related to it, to as result of fee change
930 * @param array $lineItemsToAdd
931 * @param int $entityID
932 * @param string $entityTable
933 * @param int $contributionID
935 protected function addLineItemOnChangeFeeSelection(
941 // if there is no line item to add, do not proceed
942 if (empty($lineItemsToAdd)) {
946 foreach ($lineItemsToAdd as $priceFieldValueID => $lineParams) {
947 $lineParams = array_merge($lineParams, array(
948 'entity_table' => $entityTable,
949 'entity_id' => $entityID,
950 'contribution_id' => $contributionID,
952 if (!array_key_exists('skip', $lineParams)) {
953 self
::create($lineParams);
959 * Helper function to add lineitems or financial item related to it, to as result of fee change
961 * @param array $lineItemsToAdd
962 * @param int $entityID
963 * @param string $entityTable
964 * @param int $contributionID
965 * @param array $adjustedFinancialTrxnID
969 protected function addFinancialItemsOnLineItemsChange(
974 $adjustedFinancialTrxnID = NULL
976 // if there is no line item to add, do not proceed
977 if (empty($lineItemsToAdd)) {
981 $changedFinancialTypeID = NULL;
982 $fetchCon = array('id' => $contributionID);
983 $updatedContribution = CRM_Contribute_BAO_Contribution
::retrieve($fetchCon, CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
984 // insert financial items
985 foreach ($lineItemsToAdd as $priceFieldValueID => $lineParams) {
986 $tempFinancialTrxnID = $adjustedFinancialTrxnID;
987 $lineParams = array_merge($lineParams, array(
988 'entity_table' => $entityTable,
989 'entity_id' => $entityID,
990 'contribution_id' => $contributionID,
992 $changedFinancialTypeID = $this->addFinancialItemsOnLineItemChange(empty($adjustedFinancialTrxnID), $lineParams, $updatedContribution, $tempFinancialTrxnID, $changedFinancialTypeID);
995 if ($changedFinancialTypeID) {
996 $updatedContribution->financial_type_id
= $changedFinancialTypeID;
997 $updatedContribution->save();
1002 * Helper function to update entity record on change fee selection
1004 * @param array $inputParams
1005 * @param int $entityID
1006 * @param string $entity
1009 protected function updateEntityRecordOnChangeFeeSelection($inputParams, $entityID, $entity) {
1010 $entityTable = "civicrm_{$entity}";
1012 if ($entity == 'participant') {
1013 $partUpdateFeeAmt = array('id' => $entityID);
1014 $getUpdatedLineItems = "SELECT *
1015 FROM civicrm_line_item
1016 WHERE (entity_table = '{$entityTable}' AND entity_id = {$entityID} AND qty > 0)";
1017 $getUpdatedLineItemsDAO = CRM_Core_DAO
::executeQuery($getUpdatedLineItems);
1019 while ($getUpdatedLineItemsDAO->fetch()) {
1020 $line[$getUpdatedLineItemsDAO->price_field_value_id
] = $getUpdatedLineItemsDAO->label
. ' - ' . (float) $getUpdatedLineItemsDAO->qty
;
1023 $partUpdateFeeAmt['fee_level'] = implode(', ', $line);
1024 $partUpdateFeeAmt['fee_amount'] = $inputParams['amount'];
1025 CRM_Event_BAO_Participant
::add($partUpdateFeeAmt);
1028 CRM_Event_BAO_Participant
::addActivityForSelection($entityID, 'Change Registration');
1033 * Helper function to retrieve financial trxn parameters to reverse
1034 * for given financial item identified by $financialItemID
1036 * @param int $financialItemID
1038 * @return array $financialTrxn
1041 protected function getRelatedCancelFinancialTrxn($financialItemID) {
1042 $financialTrxn = civicrm_api3('EntityFinancialTrxn', 'getsingle', array(
1043 'entity_table' => 'civicrm_financial_item',
1044 'entity_id' => $financialItemID,
1046 'sort' => 'id DESC',
1049 'api.FinancialTrxn.getsingle' => array(
1050 'id' => "\$value.financial_trxn_id",
1054 $financialTrxn = array_merge($financialTrxn['api.FinancialTrxn.getsingle'], array(
1055 'trxn_date' => date('YmdHis'),
1056 'total_amount' => -$financialTrxn['api.FinancialTrxn.getsingle']['total_amount'],
1057 'net_amount' => -$financialTrxn['api.FinancialTrxn.getsingle']['net_amount'],
1058 'entity_table' => 'civicrm_financial_item',
1059 'entity_id' => $financialItemID,
1061 unset($financialTrxn['id']);
1063 return $financialTrxn;
1067 * Record adjusted amount.
1069 * @param int $updatedAmount
1070 * @param int $paidAmount
1071 * @param int $contributionId
1073 * @param int $taxAmount
1074 * @param bool $updateAmountLevel
1076 * @return bool|\CRM_Core_BAO_FinancialTrxn
1078 protected function recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount = NULL, $updateAmountLevel = NULL) {
1079 $pendingAmount = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
1080 $pendingAmount = CRM_Utils_Array
::value('total_amount', $pendingAmount, 0);
1081 $balanceAmt = $updatedAmount - $paidAmount;
1082 if ($paidAmount != $pendingAmount) {
1083 $balanceAmt -= $pendingAmount;
1086 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1087 $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
1088 $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
1089 $completedStatusId = array_search('Completed', $contributionStatuses);
1091 $updatedContributionDAO = new CRM_Contribute_BAO_Contribution();
1092 $adjustedTrxn = $skip = FALSE;
1094 if ($balanceAmt > 0 && $paidAmount != 0) {
1095 $contributionStatusVal = $partiallyPaidStatusId;
1097 elseif ($balanceAmt < 0 && $paidAmount != 0) {
1098 $contributionStatusVal = $pendingRefundStatusId;
1100 elseif ($paidAmount == 0) {
1101 //skip updating the contribution status if no payment is made
1103 $updatedContributionDAO->cancel_date
= 'null';
1104 $updatedContributionDAO->cancel_reason
= NULL;
1106 // update contribution status and total amount without trigger financial code
1107 // as this is handled in current BAO function used for change selection
1108 $updatedContributionDAO->id
= $contributionId;
1110 $updatedContributionDAO->contribution_status_id
= $contributionStatusVal;
1112 $updatedContributionDAO->total_amount
= $updatedContributionDAO->net_amount
= $updatedAmount;
1113 $updatedContributionDAO->fee_amount
= 0;
1114 $updatedContributionDAO->tax_amount
= $taxAmount;
1115 if (!empty($updateAmountLevel)) {
1116 $updatedContributionDAO->amount_level
= $updateAmountLevel;
1118 $updatedContributionDAO->save();
1119 // adjusted amount financial_trxn creation
1120 $updatedContribution = CRM_Contribute_BAO_Contribution
::getValues(
1121 array('id' => $contributionId),
1122 CRM_Core_DAO
::$_nullArray,
1123 CRM_Core_DAO
::$_nullArray
1125 $toFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($updatedContribution->financial_type_id
, 'Accounts Receivable Account is');
1126 $adjustedTrxnValues = array(
1127 'from_financial_account_id' => NULL,
1128 'to_financial_account_id' => $toFinancialAccount,
1129 'total_amount' => $balanceAmt,
1130 'net_amount' => $balanceAmt,
1131 'status_id' => $completedStatusId,
1132 'payment_instrument_id' => $updatedContribution->payment_instrument_id
,
1133 'contribution_id' => $updatedContribution->id
,
1134 'trxn_date' => date('YmdHis'),
1135 'currency' => $updatedContribution->currency
,
1137 $adjustedTrxn = CRM_Core_BAO_FinancialTrxn
::create($adjustedTrxnValues);
1139 return $adjustedTrxn;
1143 * Add financial items to reflect line item change.
1145 * @param bool $isCreateAdditionalFinancialTrxn
1146 * @param array $lineParams
1147 * @param \CRM_Contribute_BAO_Contribution $updatedContribution
1148 * @param int $tempFinancialTrxnID
1149 * @param int|NULL $changedFinancialTypeID
1153 protected function addFinancialItemsOnLineItemChange($isCreateAdditionalFinancialTrxn, $lineParams, $updatedContribution, $tempFinancialTrxnID, $changedFinancialTypeID) {
1154 // don't add financial item for cancelled line item
1155 if ($lineParams['qty'] == 0) {
1156 return $changedFinancialTypeID;
1158 elseif ($isCreateAdditionalFinancialTrxn) {
1159 // This routine & the return below is super uncomfortable.
1160 // I have refactored to here but don't understand how this would be hit
1161 // and it is how it would be a good thing, given the odd return below which
1162 // does not seem consistent with what is going on.
1163 // I'm tempted to add an e-deprecated into it to confirm my suspicion it only exists to
1164 // cause mental anguish.
1165 // original comment : add financial item if ONLY financial type is changed
1166 if ($lineParams['financial_type_id'] != $updatedContribution->financial_type_id
) {
1167 $changedFinancialTypeID = (int) $lineParams['financial_type_id'];
1168 $adjustedTrxnValues = array(
1169 'from_financial_account_id' => NULL,
1170 'to_financial_account_id' => CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($updatedContribution->payment_instrument_id
),
1171 'total_amount' => $lineParams['line_total'],
1172 'net_amount' => $lineParams['line_total'],
1173 'status_id' => $updatedContribution->contribution_status_id
,
1174 'payment_instrument_id' => $updatedContribution->payment_instrument_id
,
1175 'contribution_id' => $updatedContribution->id
,
1176 'is_payment' => TRUE,
1177 // since balance is 0, which means contribution is completed
1178 'trxn_date' => date('YmdHis'),
1179 'currency' => $updatedContribution->currency
,
1181 $adjustedTrxn = CRM_Core_BAO_FinancialTrxn
::create($adjustedTrxnValues);
1182 $tempFinancialTrxnID = array('id' => $adjustedTrxn->id
);
1184 // don't add financial item if line_total and financial type aren't changed,
1185 // which is identified by empty $adjustedFinancialTrxnID
1187 return $changedFinancialTypeID;
1190 $lineObj = CRM_Price_BAO_LineItem
::retrieve($lineParams, CRM_Core_DAO
::$_nullArray);
1191 // insert financial items
1192 // ensure entity_financial_trxn table has a linking of it.
1193 CRM_Financial_BAO_FinancialItem
::add($lineObj, $updatedContribution, NULL, $tempFinancialTrxnID);
1194 if (isset($lineObj->tax_amount
)) {
1195 CRM_Financial_BAO_FinancialItem
::add($lineObj, $updatedContribution, TRUE, $tempFinancialTrxnID);
1197 return $changedFinancialTypeID;
1201 * Get Financial items, culling out any that have already been reversed.
1203 * @param int $entityID
1204 * @param string $entityTable
1207 * Array of financial items that have not be reversed.
1209 protected function getNonCancelledFinancialItems($entityID, $entityTable) {
1210 $updateFinancialItem = "
1211 SELECT fi.*, SUM(fi.amount) as differenceAmt, price_field_value_id, financial_type_id, tax_amount
1212 FROM civicrm_financial_item fi LEFT JOIN civicrm_line_item li ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1213 WHERE (li.entity_table = '{$entityTable}' AND li.entity_id = {$entityID})
1214 GROUP BY li.entity_table, li.entity_id, price_field_value_id, fi.id
1216 $updateFinancialItemInfoDAO = CRM_Core_DAO
::executeQuery($updateFinancialItem);
1218 $financialItemResult = $updateFinancialItemInfoDAO->fetchAll();
1220 foreach ($financialItemResult as $index => $financialItem) {
1221 $items[$financialItem['price_field_value_id']][$index] = $financialItem['amount'];
1223 if (!empty($items[$financialItem['price_field_value_id']])) {
1224 foreach ($items[$financialItem['price_field_value_id']] as $existingItemID => $existingAmount) {
1225 if ($financialItem['amount'] +
$existingAmount == 0) {
1226 // Filter both rows as they cancel each other out.
1227 unset($financialItemResult[$index]);
1228 unset($financialItemResult[$existingItemID]);
1229 unset($items['price_field_value_id'][$existingItemID]);
1230 unset($items[$financialItem['price_field_value_id']][$index]);
1237 return $financialItemResult;
1241 * Get the string used to describe the sales tax (eg. VAT, GST).
1245 protected function getSalesTaxTerm() {
1246 return CRM_Contribute_BAO_Contribution
::checkContributeSettings('tax_term');