Merge pull request #10986 from eileenmcnaughton/pp
[civicrm-core.git] / CRM / Price / BAO / LineItem.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
32 */
33
34 /**
35 * Business objects for Line Items generated by monetary transactions
36 */
37 class CRM_Price_BAO_LineItem extends CRM_Price_DAO_LineItem {
38
39 /**
40 * Creates a new entry in the database.
41 *
42 * @param array $params
43 * (reference) an assoc array of name/value pairs.
44 *
45 * @return \CRM_Price_DAO_LineItem
46 *
47 * @throws \CiviCRM_API3_Exception
48 * @throws \Exception
49 */
50 public static function create(&$params) {
51 $id = CRM_Utils_Array::value('id', $params);
52 if ($id) {
53 CRM_Utils_Hook::pre('edit', 'LineItem', $id, $params);
54 $op = CRM_Core_Action::UPDATE;
55 }
56 else {
57 CRM_Utils_Hook::pre('create', 'LineItem', $params['entity_id'], $params);
58 $op = CRM_Core_Action::ADD;
59 }
60
61 // unset entity table and entity id in $params
62 // we never update the entity table and entity id during update mode
63 if ($id) {
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']);
67 }
68 else {
69 if (!isset($params['unit_price'])) {
70 $params['unit_price'] = 0;
71 }
72 }
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');
76 }
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');
80 }
81 }
82
83 $lineItemBAO = new CRM_Price_BAO_LineItem();
84 $lineItemBAO->copyValues($params);
85
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,
91 );
92 if (!civicrm_api3('MembershipPayment', 'getcount', $membershipPaymentParams)) {
93 civicrm_api3('MembershipPayment', 'create', $membershipPaymentParams);
94 }
95 }
96
97 if ($id) {
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);
102 }
103 else {
104 CRM_Utils_Hook::post('create', 'LineItem', $lineItemBAO->id, $lineItemBAO);
105 }
106
107 return $return;
108 }
109
110 /**
111 * Retrieve DB object based on input parameters.
112 *
113 * It also stores all the retrieved values in the default array.
114 *
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.
119 *
120 * @return CRM_Price_BAO_LineItem
121 */
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);
127 return $lineItem;
128 }
129 return NULL;
130 }
131
132 /**
133 * Modifies $params array for filtering financial types.
134 *
135 * @param array $params
136 * (reference ) an assoc array of name/value pairs.
137 *
138 */
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));
143 }
144 elseif ($types) {
145 if (is_array($params['financial_type_id'])) {
146 $invalidFts = array_diff($params['financial_type_id'], array_keys($types));
147 }
148 elseif (!in_array($params['financial_type_id'], array_keys($types))) {
149 $invalidFts = $params['financial_type_id'];
150 }
151 if ($invalidFts) {
152 $params['financial_type_id'] = array('NOT IN' => $invalidFts);
153 }
154 }
155 else {
156 $params['financial_type_id'] = 0;
157 }
158 }
159
160 /**
161 * @param int $contributionId
162 *
163 * @return null|string
164 */
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;
172 }
173
174 /**
175 * Wrapper for line item retrieval when contribution ID is known.
176 * @param int $contributionID
177 *
178 * @return array
179 */
180 public static function getLineItemsByContributionID($contributionID) {
181 return self::getLineItems($contributionID, 'contribution', NULL, TRUE, TRUE, " WHERE contribution_id = " . (int) $contributionID);
182 }
183
184 /**
185 * Given a participant id/contribution id,
186 * return contribution/fee line items
187 *
188 * @param int $entityId
189 * participant/contribution id.
190 * @param string $entity
191 * participant/contribution.
192 *
193 * @param bool $isQuick
194 * @param bool $isQtyZero
195 * @param bool $relatedEntity
196 *
197 * @param bool $invoice
198 * @return array
199 * Array of line items
200 */
201 public static function getLineItems($entityId, $entity = 'participant', $isQuick = FALSE, $isQtyZero = TRUE, $relatedEntity = FALSE, $invoice = FALSE) {
202 $whereClause = $fromClause = NULL;
203 $selectClause = "
204 SELECT li.id,
205 li.label,
206 li.contribution_id,
207 li.qty,
208 li.unit_price,
209 li.line_total,
210 li.entity_table,
211 li.entity_id,
212 pf.label as field_title,
213 pf.html_type,
214 pf.price_set_id,
215 pfv.membership_type_id,
216 pfv.membership_num_terms,
217 li.price_field_id,
218 li.participant_count,
219 li.price_field_value_id,
220 li.financial_type_id,
221 li.tax_amount,
222 pfv.description";
223
224 $condition = "li.entity_id = %2.id AND li.entity_table = 'civicrm_%2'";
225 if ($relatedEntity) {
226 $condition = "li.contribution_id = %2.id ";
227 }
228
229 $fromClause = "
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 )";
234 $whereClause = "
235 WHERE %2.id = %1";
236
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) . ")";
242 }
243 }
244
245 $orderByClause = " ORDER BY pf.weight, pfv.weight";
246
247 if ($isQuick) {
248 $fromClause .= " LEFT JOIN civicrm_price_set cps on cps.id = pf.price_set_id ";
249 $whereClause .= " and cps.is_quick_config = 0";
250 }
251
252 if (!$isQtyZero) {
253 $whereClause .= " and li.qty != 0";
254 }
255
256 $lineItems = array();
257
258 if (!$entityId || !$entity || !$fromClause) {
259 return $lineItems;
260 }
261
262 $params = array(
263 1 => array($entityId, 'Integer'),
264 2 => array($entity, 'Text'),
265 );
266
267 $getTaxDetails = FALSE;
268 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
269 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
270
271 $dao = CRM_Core_DAO::executeQuery("$selectClause $fromClause $whereClause $orderByClause", $params);
272 while ($dao->fetch()) {
273 if (!$dao->id) {
274 continue;
275 }
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,
296 );
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']];
301 }
302 else {
303 // There is no Tax Rate associated with this Financial Type
304 $lineItems[$dao->id]['tax_rate'] = FALSE;
305 }
306 $lineItems[$dao->id]['subTotal'] = $lineItems[$dao->id]['qty'] * $lineItems[$dao->id]['unit_price'];
307 if ($lineItems[$dao->id]['tax_amount'] != '') {
308 $getTaxDetails = TRUE;
309 }
310 }
311 if ($invoicing) {
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);
317 }
318 return $lineItems;
319 }
320
321 /**
322 * This method will create the lineItem array required for
323 * processAmount method
324 *
325 * @param int $fid
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(.
333 * this is
334 * lineItem array)
335 * @param string $amount_override
336 */
337 public static function format($fid, $params, $fields, &$values, $amount_override = NULL) {
338 if (empty($params["price_{$fid}"])) {
339 return;
340 }
341
342 //lets first check in fun parameter,
343 //since user might modified w/ hooks.
344 $options = array();
345 if (array_key_exists('options', $fields)) {
346 $options = $fields['options'];
347 }
348 else {
349 CRM_Price_BAO_PriceFieldValue::getValues($fid, $options, 'weight', TRUE);
350 }
351 $fieldTitle = CRM_Utils_Array::value('label', $fields);
352 if (!$fieldTitle) {
353 $fieldTitle = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'label');
354 }
355
356 foreach ($params["price_{$fid}"] as $oid => $qty) {
357 $price = $amount_override === NULL ? $options[$oid]['amount'] : $amount_override;
358
359 // lets clean the price in case it is not yet cleant
360 // CRM-10974
361 $price = CRM_Utils_Rule::cleanMoney($price);
362
363 $participantsPerField = CRM_Utils_Array::value('count', $options[$oid], 0);
364
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]),
371 'qty' => $qty,
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]),
383 );
384
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');
387 }
388 }
389 }
390
391 /**
392 * Delete line items for given entity.
393 *
394 * @param int $entityId
395 * @param int $entityTable
396 *
397 * @return bool
398 */
399 public static function deleteLineItems($entityId, $entityTable) {
400 if (!$entityId || !$entityTable) {
401 return FALSE;
402 }
403
404 if ($entityId && !is_array($entityId)) {
405 $entityId = array($entityId);
406 }
407
408 $query = "DELETE FROM civicrm_line_item where entity_id IN ('" . implode("','", $entityId) . "') AND entity_table = '$entityTable'";
409 $dao = CRM_Core_DAO::executeQuery($query);
410 return TRUE;
411 }
412
413 /**
414 * Process price set and line items.
415 *
416 * @param int $entityId
417 * @param array $lineItem
418 * Line item array.
419 * @param object $contributionDetails
420 * @param string $entityTable
421 * Entity table.
422 *
423 * @param bool $update
424 *
425 * @return void
426 */
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)
430 ) {
431 return;
432 }
433
434 foreach ($lineItem as $priceSetId => &$values) {
435 if (!$priceSetId) {
436 continue;
437 }
438
439 foreach ($values as &$line) {
440 if (empty($line['entity_table'])) {
441 $line['entity_table'] = $entityTable;
442 }
443 if (empty($line['entity_id'])) {
444 $line['entity_id'] = $entityId;
445 }
446 if (!empty($line['membership_type_id'])) {
447 $line['entity_table'] = 'civicrm_membership';
448 }
449 if (!empty($contributionDetails->id)) {
450 $line['contribution_id'] = $contributionDetails->id;
451 if ($line['entity_table'] == 'civicrm_contribution') {
452 $line['entity_id'] = $contributionDetails->id;
453 }
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'];
459 }
460 }
461
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');
466 }
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);
473 }
474 }
475 }
476 }
477 if (!$update && $contributionDetails) {
478 CRM_Core_BAO_FinancialTrxn::createDeferredTrxn($lineItem, $contributionDetails);
479 }
480 }
481
482 /**
483 * @param int $entityId
484 * @param string $entityTable
485 * @param $amount
486 * @param array $otherParams
487 */
488 public static function syncLineItems($entityId, $entityTable = 'civicrm_contribution', $amount, $otherParams = NULL) {
489 if (!$entityId || CRM_Utils_System::isNull($amount)) {
490 return;
491 }
492
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 ";
496
497 $set = " li.unit_price = %3,
498 li.line_total = %3 ";
499
500 $where = " li.entity_id = %1 AND
501 li.entity_table = %2 ";
502
503 $params = array(
504 1 => array($entityId, 'Integer'),
505 2 => array($entityTable, 'String'),
506 3 => array($amount, 'Float'),
507 );
508
509 if ($entityTable == 'civicrm_contribution') {
510 $entityName = 'default_contribution_amount';
511 $where .= " AND ps.name = %4 ";
512 $params[4] = array($entityName, 'String');
513 }
514 elseif ($entityTable == 'civicrm_participant') {
515 $from .= "
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;
522 $params += array(
523 4 => array($otherParams['fee_label'], 'String'),
524 5 => array($otherParams['event_id'], 'String'),
525 );
526 }
527
528 $query = "
529 UPDATE $from
530 SET $set
531 WHERE $where
532 ";
533
534 CRM_Core_DAO::executeQuery($query, $params);
535 }
536
537 /**
538 * Build line items array.
539 *
540 * @param array $params
541 * Form values.
542 *
543 * @param string $entityId
544 * Entity id.
545 *
546 * @param string $entityTable
547 * Entity Table.
548 *
549 * @param bool $isRelatedID
550 */
551 public static function getLineItemArray(&$params, $entityId = NULL, $entityTable = 'contribution', $isRelatedID = FALSE) {
552 if (!$entityId) {
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']) {
559 continue;
560 }
561 if (!$totalAmount) {
562 $totalAmount = $values['amount'];
563 }
564 $financialType = $values['financial_type_id'];
565 }
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'],
570 'qty' => 1,
571 'unit_price' => $totalAmount,
572 'line_total' => $totalAmount,
573 'financial_type_id' => $financialType,
574 'membership_type_id' => $values['membership_type_id'],
575 );
576 break;
577 }
578 }
579 else {
580 $setID = NULL;
581 $totalEntityId = count($entityId);
582 if ($entityTable == 'contribution') {
583 $isRelatedID = TRUE;
584 }
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');
591 }
592 if (!empty($params['is_quick_config']) && array_key_exists('total_amount', $params)
593 && $totalEntityId == 1
594 ) {
595 $values['line_total'] = $values['unit_price'] = $params['total_amount'];
596 }
597 $values['id'] = $key;
598 $params['line_item'][$setID][$key] = $values;
599 }
600 }
601 }
602 }
603
604 /**
605 * Function to update related contribution of a entity and
606 * add/update/cancel financial records
607 *
608 * @param array $params
609 * @param int $entityID
610 * @param int $entity
611 * @param int $contributionId
612 * @param $feeBlock
613 * @param array $lineItems
614 * @param $paidAmount
615 *
616 */
617 public static function changeFeeSelections(
618 $params,
619 $entityID,
620 $entity,
621 $contributionId,
622 $feeBlock,
623 $lineItems,
624 $paidAmount
625 ) {
626 $entityTable = "civicrm_" . $entity;
627 CRM_Price_BAO_PriceSet::processAmount($feeBlock,
628 $params, $lineItems
629 );
630 // initialize empty Lineitem instance to call protected helper functions
631 $lineItemObj = new CRM_Price_BAO_LineItem();
632
633 // fetch submitted LineItems from input params and feeBlock information
634 $submittedLineItems = $lineItemObj->getSubmittedLineItems($params, $feeBlock);
635
636 // retrieve the submitted price field value IDs from $submittedLineItems array keys
637 $submittedPriceFieldValueIDs = empty($submittedLineItems) ? array() : array_keys($submittedLineItems);
638
639 $requiredChanges = $lineItemObj->getLineItemsToAlter($submittedLineItems, $entityID, $entity);
640
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);
644
645 // get financial information that need to be recorded on basis on submitted price field value IDs
646 $financialItemsArray = $lineItemObj->getReverseFinancialItemsToRecord(
647 $entityID,
648 $entityTable,
649 $contributionId,
650 $submittedPriceFieldValueIDs
651 );
652
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) {
658 $taxAmount = "NULL";
659 if (isset($value['tax_amount'])) {
660 $taxAmount = $value['tax_amount'];
661 }
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'];
666 }
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},
674 li.label = %1
675 WHERE (li.entity_table = '{$entityTable}' AND li.entity_id = {$entityID}) AND
676 (price_field_value_id = {$priceFieldValueID}) ";
677
678 CRM_Core_DAO::executeQuery($updateLineItemSQL, array(1 => array($value['label'], 'String')));
679 }
680 }
681
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);
686
687 // the recordAdjustedAmt code would execute over here
688 $count = 0;
689 if ($entity == 'participant') {
690 $count = count(CRM_Event_BAO_Participant::getParticipantIds($contributionId));
691 }
692 else {
693 $count = CRM_Utils_Array::value('count', civicrm_api3('MembershipPayment', 'getcount', array('contribution_id' => $contributionId)));
694 }
695 if ($count > 1) {
696 $updatedAmount = CRM_Price_BAO_LineItem::getLineTotal($contributionId);
697 }
698 else {
699 $updatedAmount = CRM_Utils_Array::value('amount', $params, CRM_Utils_Array::value('total_amount', $params));
700 }
701 if (strlen($params['tax_amount']) != 0) {
702 $taxAmount = $params['tax_amount'];
703 }
704 else {
705 $taxAmount = "NULL";
706 }
707 $displayParticipantCount = '';
708 if ($totalParticipant > 0) {
709 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
710 }
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;
714 }
715 $trxn = $lineItemObj->recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount, $updateAmountLevel);
716
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'))
725 ) {
726 $updateFinancialItemInfoValues = array_merge($updateFinancialItemInfoValues['financialTrxn'], array(
727 'entity_id' => $newFinancialItem->id,
728 'entity_table' => 'civicrm_financial_item',
729 ));
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,
737 ));
738 unset($updateFinancialItemInfoValues['financialTrxn']);
739 }
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'];
745 }
746 CRM_Financial_BAO_FinancialItem::create($updateFinancialItemInfoValues);
747 }
748 }
749 }
750
751 $trxnId = !empty($trxn->id) ? array('id' => $trxn->id) : array();
752 $lineItemObj->addFinancialItemsOnLineItemsChange($requiredChanges['line_items_to_add'], $entityID, $entityTable, $contributionId, $trxnId);
753
754 // update participant fee_amount column
755 $lineItemObj->updateEntityRecordOnChangeFeeSelection($params, $entityID, $entity);
756 }
757
758 /**
759 * Function to cancel Lineitem whose corrosponding price field option is
760 * unselected on membership or participant backoffice form
761 *
762 * @param int $entityID
763 * @param string $entityTable
764 * @param string $additionalWhereClause
765 *
766 */
767 protected function cancelLineItems($entityID, $entityTable, $additionalWhereClause = NULL) {
768 $whereClauses = array(
769 "li.entity_id = %1",
770 "li.entity_table = %2",
771 );
772 if ($additionalWhereClause) {
773 $whereClauses[] = $additionalWhereClause;
774 }
775
776 $where = implode(' AND ', $whereClauses);
777 $sql = "
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')
780 SET li.qty = 0,
781 li.line_total = 0.00,
782 li.tax_amount = NULL,
783 li.participant_count = 0,
784 li.non_deductible_amount = 0.00
785 WHERE {$where} ";
786
787 CRM_Core_DAO::executeQuery($sql, array(
788 1 => array($entityID, 'Integer'),
789 2 => array($entityTable, 'String'),
790 ));
791 }
792
793 /**
794 * Function to retrieve formatted financial items that need to be recorded as result of changed fee
795 *
796 * @param int $entityID
797 * @param string $entityTable
798 * @param int $contributionID
799 * @param array $submittedPriceFieldValueIDs
800 *
801 * @return array
802 * List of formatted Financial Items to be recorded
803 */
804 protected function getReverseFinancialItemsToRecord($entityID, $entityTable, $contributionID, $submittedPriceFieldValueIDs) {
805 $previousLineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, str_replace('civicrm_', '', $entityTable));
806
807 $financialItemsArray = array();
808
809 if (empty($submittedPriceFieldValueIDs)) {
810 return $financialItemsArray;
811 }
812
813 $financialItemResult = $this->getNonCancelledFinancialItems($entityID, $entityTable);
814
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']);
832 }
833 }
834 // INSERT negative financial_items for tax amount
835 $financialItemsArray[] = $updateFinancialItemInfoValues;
836 }
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'])
843 ) {
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']);
848 }
849 }
850 $financialItemsArray[] = $updateFinancialItemInfoValues;
851 }
852 }
853
854 return $financialItemsArray;
855 }
856
857 /**
858 * Helper function to retrieve submitted line items from form values $inputParams and used $feeBlock
859 *
860 * @param array $inputParams
861 * @param array $feeBlock
862 *
863 * @return array
864 * List of submitted line items
865 */
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);
870 }
871
872 return $submittedLineItems;
873 }
874
875 /**
876 * Helper function to retrieve formatted line items that need to be altered.
877 *
878 * @param array $submittedLineItems
879 * @param int $entityID
880 * @param string $entity
881 *
882 * @return array
883 * Array of formatted line items
884 */
885 protected function getLineItemsToAlter($submittedLineItems, $entityID, $entity) {
886 $previousLineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entity);
887
888 $lineItemsToAdd = $submittedLineItems;
889 $lineItemsToUpdate = array();
890 $submittedPriceFieldValueIDs = array_keys($submittedLineItems);
891
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']]);
900 }
901 else {
902 $submittedLineItem['skip'] = TRUE;
903 }
904 // for updating the line items i.e. use-case - once deselect-option selecting again
905 if (($previousLineItem['line_total'] != $submittedLineItem['line_total'])
906 || (
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
910 )
911 || (
912 $previousLineItem['qty'] != $submittedLineItem['qty']
913 )
914 ) {
915 $lineItemsToUpdate[$previousLineItem['price_field_value_id']] = $submittedLineItem;
916 $lineItemsToUpdate[$previousLineItem['price_field_value_id']]['id'] = $id;
917 }
918 }
919 }
920
921 return array(
922 'line_items_to_add' => $lineItemsToAdd,
923 'line_items_to_update' => $lineItemsToUpdate,
924 );
925 }
926
927 /**
928 * Helper function to add lineitems or financial item related to it, to as result of fee change
929 *
930 * @param array $lineItemsToAdd
931 * @param int $entityID
932 * @param string $entityTable
933 * @param int $contributionID
934 */
935 protected function addLineItemOnChangeFeeSelection(
936 $lineItemsToAdd,
937 $entityID,
938 $entityTable,
939 $contributionID
940 ) {
941 // if there is no line item to add, do not proceed
942 if (empty($lineItemsToAdd)) {
943 return;
944 }
945
946 foreach ($lineItemsToAdd as $priceFieldValueID => $lineParams) {
947 $lineParams = array_merge($lineParams, array(
948 'entity_table' => $entityTable,
949 'entity_id' => $entityID,
950 'contribution_id' => $contributionID,
951 ));
952 if (!array_key_exists('skip', $lineParams)) {
953 self::create($lineParams);
954 }
955 }
956 }
957
958 /**
959 * Helper function to add lineitems or financial item related to it, to as result of fee change
960 *
961 * @param array $lineItemsToAdd
962 * @param int $entityID
963 * @param string $entityTable
964 * @param int $contributionID
965 * @param array $adjustedFinancialTrxnID
966 *
967 * @return void
968 */
969 protected function addFinancialItemsOnLineItemsChange(
970 $lineItemsToAdd,
971 $entityID,
972 $entityTable,
973 $contributionID,
974 $adjustedFinancialTrxnID = NULL
975 ) {
976 // if there is no line item to add, do not proceed
977 if (empty($lineItemsToAdd)) {
978 return;
979 }
980
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,
991 ));
992 $changedFinancialTypeID = $this->addFinancialItemsOnLineItemChange(empty($adjustedFinancialTrxnID), $lineParams, $updatedContribution, $tempFinancialTrxnID, $changedFinancialTypeID);
993 }
994
995 if ($changedFinancialTypeID) {
996 $updatedContribution->financial_type_id = $changedFinancialTypeID;
997 $updatedContribution->save();
998 }
999 }
1000
1001 /**
1002 * Helper function to update entity record on change fee selection
1003 *
1004 * @param array $inputParams
1005 * @param int $entityID
1006 * @param string $entity
1007 *
1008 */
1009 protected function updateEntityRecordOnChangeFeeSelection($inputParams, $entityID, $entity) {
1010 $entityTable = "civicrm_{$entity}";
1011
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);
1018 $line = array();
1019 while ($getUpdatedLineItemsDAO->fetch()) {
1020 $line[$getUpdatedLineItemsDAO->price_field_value_id] = $getUpdatedLineItemsDAO->label . ' - ' . (float) $getUpdatedLineItemsDAO->qty;
1021 }
1022
1023 $partUpdateFeeAmt['fee_level'] = implode(', ', $line);
1024 $partUpdateFeeAmt['fee_amount'] = $inputParams['amount'];
1025 CRM_Event_BAO_Participant::add($partUpdateFeeAmt);
1026
1027 //activity creation
1028 CRM_Event_BAO_Participant::addActivityForSelection($entityID, 'Change Registration');
1029 }
1030 }
1031
1032 /**
1033 * Helper function to retrieve financial trxn parameters to reverse
1034 * for given financial item identified by $financialItemID
1035 *
1036 * @param int $financialItemID
1037 *
1038 * @return array $financialTrxn
1039 *
1040 */
1041 protected function getRelatedCancelFinancialTrxn($financialItemID) {
1042 $financialTrxn = civicrm_api3('EntityFinancialTrxn', 'getsingle', array(
1043 'entity_table' => 'civicrm_financial_item',
1044 'entity_id' => $financialItemID,
1045 'options' => array(
1046 'sort' => 'id DESC',
1047 'limit' => 1,
1048 ),
1049 'api.FinancialTrxn.getsingle' => array(
1050 'id' => "\$value.financial_trxn_id",
1051 ),
1052 ));
1053
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,
1060 ));
1061 unset($financialTrxn['id']);
1062
1063 return $financialTrxn;
1064 }
1065
1066 /**
1067 * Record adjusted amount.
1068 *
1069 * @param int $updatedAmount
1070 * @param int $paidAmount
1071 * @param int $contributionId
1072 *
1073 * @param int $taxAmount
1074 * @param bool $updateAmountLevel
1075 *
1076 * @return bool|\CRM_Core_BAO_FinancialTrxn
1077 */
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;
1084 }
1085
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);
1090
1091 $updatedContributionDAO = new CRM_Contribute_BAO_Contribution();
1092 $adjustedTrxn = $skip = FALSE;
1093 if ($balanceAmt) {
1094 if ($balanceAmt > 0 && $paidAmount != 0) {
1095 $contributionStatusVal = $partiallyPaidStatusId;
1096 }
1097 elseif ($balanceAmt < 0 && $paidAmount != 0) {
1098 $contributionStatusVal = $pendingRefundStatusId;
1099 }
1100 elseif ($paidAmount == 0) {
1101 //skip updating the contribution status if no payment is made
1102 $skip = TRUE;
1103 $updatedContributionDAO->cancel_date = 'null';
1104 $updatedContributionDAO->cancel_reason = NULL;
1105 }
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;
1109 if (!$skip) {
1110 $updatedContributionDAO->contribution_status_id = $contributionStatusVal;
1111 }
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;
1117 }
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
1124 );
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,
1136 );
1137 $adjustedTrxn = CRM_Core_BAO_FinancialTrxn::create($adjustedTrxnValues);
1138 }
1139 return $adjustedTrxn;
1140 }
1141
1142 /**
1143 * Add financial items to reflect line item change.
1144 *
1145 * @param bool $isCreateAdditionalFinancialTrxn
1146 * @param array $lineParams
1147 * @param \CRM_Contribute_BAO_Contribution $updatedContribution
1148 * @param int $tempFinancialTrxnID
1149 * @param int|NULL $changedFinancialTypeID
1150 *
1151 * @return int|NULL
1152 */
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;
1157 }
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,
1180 );
1181 $adjustedTrxn = CRM_Core_BAO_FinancialTrxn::create($adjustedTrxnValues);
1182 $tempFinancialTrxnID = array('id' => $adjustedTrxn->id);
1183 }
1184 // don't add financial item if line_total and financial type aren't changed,
1185 // which is identified by empty $adjustedFinancialTrxnID
1186 else {
1187 return $changedFinancialTypeID;
1188 }
1189 }
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);
1196 }
1197 return $changedFinancialTypeID;
1198 }
1199
1200 /**
1201 * Get Financial items, culling out any that have already been reversed.
1202 *
1203 * @param int $entityID
1204 * @param string $entityTable
1205 *
1206 * @return array
1207 * Array of financial items that have not be reversed.
1208 */
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
1215 ";
1216 $updateFinancialItemInfoDAO = CRM_Core_DAO::executeQuery($updateFinancialItem);
1217
1218 $financialItemResult = $updateFinancialItemInfoDAO->fetchAll();
1219 $items = array();
1220 foreach ($financialItemResult as $index => $financialItem) {
1221 $items[$financialItem['price_field_value_id']][$index] = $financialItem['amount'];
1222
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]);
1231 }
1232 }
1233
1234 }
1235
1236 }
1237 return $financialItemResult;
1238 }
1239
1240 /**
1241 * Get the string used to describe the sales tax (eg. VAT, GST).
1242 *
1243 * @return string
1244 */
1245 protected function getSalesTaxTerm() {
1246 return CRM_Contribute_BAO_Contribution::checkContributeSettings('tax_term');
1247 }
1248
1249 }