CRM-21513: Change fee selection for text price field on backoffice Event registration...
[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 $requiredChanges = $lineItemObj->getLineItemsToAlter($submittedLineItems, $entityID, $entity);
637
638 // get financial information that need to be recorded on basis on submitted price field value IDs
639 if (!empty($requiredChanges['line_items_to_cancel']) || !empty($requiredChanges['line_items_to_update'])) {
640 // @todo - this IF is to get this through PR merge but I suspect that it should not
641 // be necessary & is masking something else.
642 $financialItemsArray = $lineItemObj->getReverseFinancialItemsToRecord(
643 $entityID,
644 $entityTable,
645 $contributionId,
646 array_keys($requiredChanges['line_items_to_cancel']),
647 $requiredChanges['line_items_to_update']
648 );
649 }
650
651 // update line item with changed line total and other information
652 $totalParticipant = $participantCount = 0;
653 $amountLevel = array();
654 if (!empty($requiredChanges['line_items_to_update'])) {
655 foreach ($requiredChanges['line_items_to_update'] as $priceFieldValueID => $value) {
656 $amountLevel[] = $value['label'] . ' - ' . (float) $value['qty'];
657 if ($entity == 'participant' && isset($value['participant_count'])) {
658 $totalParticipant += $value['participant_count'];
659 }
660 }
661 }
662
663 foreach (array_merge($requiredChanges['line_items_to_resurrect'], $requiredChanges['line_items_to_cancel'], $requiredChanges['line_items_to_update']) as $lineItemToAlter) {
664 // Must use BAO rather than api because a bad line it in the api which we want to avoid.
665 CRM_Price_BAO_LineItem::create($lineItemToAlter);
666 }
667
668 $lineItemObj->addLineItemOnChangeFeeSelection($requiredChanges['line_items_to_add'], $entityID, $entityTable, $contributionId);
669
670 $count = 0;
671 if ($entity == 'participant') {
672 $count = count(CRM_Event_BAO_Participant::getParticipantIds($contributionId));
673 }
674 else {
675 $count = CRM_Utils_Array::value('count', civicrm_api3('MembershipPayment', 'getcount', array('contribution_id' => $contributionId)));
676 }
677 if ($count > 1) {
678 $updatedAmount = CRM_Price_BAO_LineItem::getLineTotal($contributionId);
679 }
680 else {
681 $updatedAmount = CRM_Utils_Array::value('amount', $params, CRM_Utils_Array::value('total_amount', $params));
682 }
683 if (strlen($params['tax_amount']) != 0) {
684 $taxAmount = $params['tax_amount'];
685 }
686 else {
687 $taxAmount = "NULL";
688 }
689 $displayParticipantCount = '';
690 if ($totalParticipant > 0) {
691 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
692 }
693 $updateAmountLevel = NULL;
694 if (!empty($amountLevel)) {
695 $updateAmountLevel = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amountLevel) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
696 }
697 $trxn = $lineItemObj->recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount, $updateAmountLevel);
698
699 $contributionStatus = CRM_Core_PseudoConstant::getName('CRM_Contribute_DAO_Contribution', 'contribution_status_id', CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'contribution_status_id'));
700
701 if (!empty($financialItemsArray)) {
702 foreach ($financialItemsArray as $updateFinancialItemInfoValues) {
703 $newFinancialItem = CRM_Financial_BAO_FinancialItem::create($updateFinancialItemInfoValues);
704 // record reverse transaction only if Contribution is Completed because for pending refund or
705 // partially paid we are already recording the surplus owed or refund amount
706 if (!empty($updateFinancialItemInfoValues['financialTrxn']) && ($contributionStatus == 'Completed')) {
707 $updateFinancialItemInfoValues = array_merge($updateFinancialItemInfoValues['financialTrxn'], array(
708 'entity_id' => $newFinancialItem->id,
709 'entity_table' => 'civicrm_financial_item',
710 ));
711 $reverseTrxn = CRM_Core_BAO_FinancialTrxn::create($updateFinancialItemInfoValues);
712 // record reverse entity financial trxn linked to membership's related contribution
713 civicrm_api3('EntityFinancialTrxn', 'create', array(
714 'entity_table' => "civicrm_contribution",
715 'entity_id' => $contributionId,
716 'financial_trxn_id' => $reverseTrxn->id,
717 'amount' => $reverseTrxn->total_amount,
718 ));
719 unset($updateFinancialItemInfoValues['financialTrxn']);
720 }
721 elseif (!empty($updateFinancialItemInfoValues['link-financial-trxn'])) {
722 civicrm_api3('EntityFinancialTrxn', 'create', array(
723 'entity_id' => $newFinancialItem->id,
724 'entity_table' => 'civicrm_financial_item',
725 'financial_trxn_id' => $trxn->id,
726 'amount' => $newFinancialItem->amount,
727 ));
728 unset($updateFinancialItemInfoValues['link-financial-trxn']);
729 }
730 }
731 }
732
733 // @todo - it may be that trxn_id is always empty - flush out scenarios. Add tests.
734 $trxnId = !empty($trxn->id) ? array('id' => $trxn->id) : array();
735 $lineItemObj->addFinancialItemsOnLineItemsChange(array_merge($requiredChanges['line_items_to_add'], $requiredChanges['line_items_to_resurrect']), $entityID, $entityTable, $contributionId, $trxnId);
736
737 // update participant fee_amount column
738 $lineItemObj->updateEntityRecordOnChangeFeeSelection($params, $entityID, $entity);
739 }
740
741 /**
742 * Function to retrieve financial items that need to be recorded as result of changed fee
743 *
744 * @param int $entityID
745 * @param string $entityTable
746 * @param int $contributionID
747 * @param array $priceFieldValueIDsToCancel
748 * @param array $lineItemsToUpdate
749 *
750 * @return array
751 * List of formatted reverse Financial Items to be recorded
752 */
753 protected function getReverseFinancialItemsToRecord($entityID, $entityTable, $contributionID, $priceFieldValueIDsToCancel, $lineItemsToUpdate) {
754 $previousLineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, str_replace('civicrm_', '', $entityTable));
755
756 $financialItemsArray = array();
757 $financialItemResult = $this->getNonCancelledFinancialItems($entityID, $entityTable);
758 foreach ($financialItemResult as $updateFinancialItemInfoValues) {
759 $updateFinancialItemInfoValues['transaction_date'] = date('YmdHis');
760
761 // the below params are not needed as we are creating new financial item
762 $previousFinancialItemID = $updateFinancialItemInfoValues['id'];
763 $totalFinancialAmount = $this->checkFinancialItemTotalAmountByLineItemID($updateFinancialItemInfoValues['entity_id']);
764 unset($updateFinancialItemInfoValues['id']);
765 unset($updateFinancialItemInfoValues['created_date']);
766
767 // if not submitted and difference is not 0 make it negative
768 if ((empty($lineItemsToUpdate) || (in_array($updateFinancialItemInfoValues['price_field_value_id'], $priceFieldValueIDsToCancel) &&
769 $totalFinancialAmount == $updateFinancialItemInfoValues['amount'])
770 ) && $updateFinancialItemInfoValues['amount'] > 0
771 ) {
772 // INSERT negative financial_items
773 $updateFinancialItemInfoValues['amount'] = -$updateFinancialItemInfoValues['amount'];
774 // reverse the related financial trxn too
775 $updateFinancialItemInfoValues['financialTrxn'] = $this->getRelatedCancelFinancialTrxn($previousFinancialItemID);
776 if ($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']) {
777 $updateFinancialItemInfoValues['tax']['amount'] = -($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']);
778 $updateFinancialItemInfoValues['tax']['description'] = $this->getSalesTaxTerm();
779 }
780 // INSERT negative financial_items for tax amount
781 $financialItemsArray[$updateFinancialItemInfoValues['entity_id']] = $updateFinancialItemInfoValues;
782 }
783 elseif (!empty($lineItemsToUpdate) &&
784 $lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']]['html_type'] == 'Text' &&
785 $updateFinancialItemInfoValues['amount'] > 0
786 ) {
787 $updateFinancialItemInfoValues['link-financial-trxn'] = TRUE;
788 $financialItemsArray[$updateFinancialItemInfoValues['entity_id']] = $updateFinancialItemInfoValues;
789 }
790 }
791
792 return $financialItemsArray;
793 }
794
795 /**
796 * Helper function to return sum of financial item's amount related to a line-item
797 * @param array $lineItemID
798 *
799 * @return float $financialItem
800 */
801 protected function checkFinancialItemTotalAmountByLineItemID($lineItemID) {
802 return CRM_Core_DAO::singleValueQuery("
803 SELECT SUM(amount)
804 FROM civicrm_financial_item
805 WHERE entity_table = 'civicrm_line_item' AND entity_id = {$lineItemID}
806 ");
807 }
808
809 /**
810 * Helper function to retrieve submitted line items from form values $inputParams and used $feeBlock
811 *
812 * @param array $inputParams
813 * @param array $feeBlock
814 *
815 * @return array
816 * List of submitted line items
817 */
818 protected function getSubmittedLineItems($inputParams, $feeBlock) {
819 $submittedLineItems = array();
820 foreach ($feeBlock as $id => $values) {
821 CRM_Price_BAO_LineItem::format($id, $inputParams, $values, $submittedLineItems);
822 }
823
824 return $submittedLineItems;
825 }
826
827 /**
828 * Helper function to retrieve line items that need to be altered.
829 *
830 * We iterate through the previous line items for the given entity to determine
831 * what alterations to line items need to be made to reflect the new line items.
832 *
833 * There are 4 possible changes required - per the keys in the return array.
834 *
835 * @param array $submittedLineItems
836 * @param int $entityID
837 * @param string $entity
838 *
839 * @return array
840 * Array of line items to alter with the following keys
841 * - line_items_to_add. If the line items required are new radio options that
842 * have not previously been set then we should add line items for them
843 * - line_items_to_update. If we have already been an active option and a change has
844 * happened then it should be in this array.
845 * - line_items_to_cancel. Line items currently selected but not selected in the new selection.
846 * These need to be zero'd out.
847 * - line_items_to_resurrect. Line items previously selected and then deselected. These need to be
848 * re-enabled rather than a new one added.
849 */
850 protected function getLineItemsToAlter($submittedLineItems, $entityID, $entity) {
851 $previousLineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entity);
852
853 $lineItemsToAdd = $submittedLineItems;
854 $lineItemsToUpdate = array();
855 $submittedPriceFieldValueIDs = array_keys($submittedLineItems);
856 $lineItemsToCancel = $lineItemsToResurrect = array();
857
858 foreach ($previousLineItems as $id => $previousLineItem) {
859 if (in_array($previousLineItem['price_field_value_id'], $submittedPriceFieldValueIDs)) {
860 $submittedLineItem = $submittedLineItems[$previousLineItem['price_field_value_id']];
861 if (CRM_Utils_Array::value('html_type', $lineItemsToAdd[$previousLineItem['price_field_value_id']]) == 'Text') {
862 // If a 'Text' price field was updated by changing qty value, then we are not adding new line-item but updating the existing one,
863 // because unlike other kind of price-field, it's related price-field-value-id isn't changed and thats why we need to make an
864 // exception here by adding financial item for updated line-item and will reverse any previous financial item entries.
865 $lineItemsToUpdate[$previousLineItem['price_field_value_id']] = array_merge($submittedLineItem, array('id' => $id));
866 unset($lineItemsToAdd[$previousLineItem['price_field_value_id']]);
867 }
868 else {
869 $submittedLineItem = $submittedLineItems[$previousLineItem['price_field_value_id']];
870 // for updating the line items i.e. use-case - once deselect-option selecting again
871 if (($previousLineItem['line_total'] != $submittedLineItem['line_total'])
872 || (
873 // This would be a $0 line item - but why it should be catered to
874 // other than when the above condition is unclear.
875 $submittedLineItem['line_total'] == 0 && $submittedLineItem['qty'] == 1
876 )
877 || (
878 $previousLineItem['qty'] != $submittedLineItem['qty']
879 )
880 ) {
881 $lineItemsToUpdate[$previousLineItem['price_field_value_id']] = $submittedLineItem;
882 $lineItemsToUpdate[$previousLineItem['price_field_value_id']]['id'] = $id;
883 // Format is actually '0.00'
884 if ($previousLineItem['line_total'] == 0) {
885 $lineItemsToAdd[$previousLineItem['price_field_value_id']]['id'] = $id;
886 $lineItemsToResurrect[] = $lineItemsToAdd[$previousLineItem['price_field_value_id']];
887 }
888 }
889 // If there was previously a submitted line item for the same option value then there is
890 // either no change or a qty adjustment. In either case we are not doing an add + reversal.
891 unset($lineItemsToAdd[$previousLineItem['price_field_value_id']]);
892 unset($lineItemsToCancel[$previousLineItem['price_field_value_id']]);
893 }
894 }
895 else {
896 if (!$this->isCancelled($previousLineItem)) {
897 $cancelParams = array('qty' => 0, 'line_total' => 0, 'tax_amount' => 0, 'participant_count' => 0, 'non_deductible_amount' => 0, 'id' => $id);
898 $lineItemsToCancel[$previousLineItem['price_field_value_id']] = array_merge($previousLineItem, $cancelParams);
899
900 }
901 }
902 }
903
904 return array(
905 'line_items_to_add' => $lineItemsToAdd,
906 'line_items_to_update' => $lineItemsToUpdate,
907 'line_items_to_cancel' => $lineItemsToCancel,
908 'line_items_to_resurrect' => $lineItemsToResurrect,
909 );
910 }
911
912 /**
913 * Check if a line item has already been cancelled.
914 *
915 * @param array $lineItem
916 *
917 * @return bool
918 */
919 protected function isCancelled($lineItem) {
920 if ($lineItem['qty'] == 0 && $lineItem['line_total'] == 0) {
921 return TRUE;
922 }
923 }
924 /**
925 * Add line Items as result of fee change.
926 *
927 * @param array $lineItemsToAdd
928 * @param int $entityID
929 * @param string $entityTable
930 * @param int $contributionID
931 */
932 protected function addLineItemOnChangeFeeSelection(
933 $lineItemsToAdd,
934 $entityID,
935 $entityTable,
936 $contributionID
937 ) {
938 // if there is no line item to add, do not proceed
939 if (empty($lineItemsToAdd)) {
940 return;
941 }
942
943 $changedFinancialTypeID = NULL;
944 $updatedContribution = new CRM_Contribute_BAO_Contribution();
945 $updatedContribution->id = (int) $contributionID;
946 // insert financial items
947 foreach ($lineItemsToAdd as $priceFieldValueID => $lineParams) {
948 $lineParams = array_merge($lineParams, array(
949 'entity_table' => $entityTable,
950 'entity_id' => $entityID,
951 'contribution_id' => $contributionID,
952 ));
953 if (!array_key_exists('skip', $lineParams)) {
954 self::create($lineParams);
955 }
956 }
957
958 if ($changedFinancialTypeID) {
959 $updatedContribution->financial_type_id = $changedFinancialTypeID;
960 $updatedContribution->save();
961 }
962 }
963
964 /**
965 * Add financial transactions when an array of line items is changed.
966 *
967 * @param array $lineItemsToAdd
968 * @param int $entityID
969 * @param string $entityTable
970 * @param int $contributionID
971 * @param bool $isCreateAdditionalFinancialTrxn
972 * Is there a change to the total balance requiring additional transactions to be created.
973 */
974 protected function addFinancialItemsOnLineItemsChange($lineItemsToAdd, $entityID, $entityTable, $contributionID, $isCreateAdditionalFinancialTrxn) {
975 $updatedContribution = new CRM_Contribute_BAO_Contribution();
976 $updatedContribution->id = $contributionID;
977 $updatedContribution->find(TRUE);
978
979 foreach ($lineItemsToAdd as $priceFieldValueID => $lineParams) {
980 $lineParams = array_merge($lineParams, array(
981 'entity_table' => $entityTable,
982 'entity_id' => $entityID,
983 'contribution_id' => $contributionID,
984 ));
985 $this->addFinancialItemsOnLineItemChange($isCreateAdditionalFinancialTrxn, $lineParams, $updatedContribution);
986 }
987 }
988
989 /**
990 * Helper function to update entity record on change fee selection
991 *
992 * @param array $inputParams
993 * @param int $entityID
994 * @param string $entity
995 *
996 */
997 protected function updateEntityRecordOnChangeFeeSelection($inputParams, $entityID, $entity) {
998 $entityTable = "civicrm_{$entity}";
999
1000 if ($entity == 'participant') {
1001 $partUpdateFeeAmt = array('id' => $entityID);
1002 $getUpdatedLineItems = "SELECT *
1003 FROM civicrm_line_item
1004 WHERE (entity_table = '{$entityTable}' AND entity_id = {$entityID} AND qty > 0)";
1005 $getUpdatedLineItemsDAO = CRM_Core_DAO::executeQuery($getUpdatedLineItems);
1006 $line = array();
1007 while ($getUpdatedLineItemsDAO->fetch()) {
1008 $line[$getUpdatedLineItemsDAO->price_field_value_id] = $getUpdatedLineItemsDAO->label . ' - ' . (float) $getUpdatedLineItemsDAO->qty;
1009 }
1010
1011 $partUpdateFeeAmt['fee_level'] = implode(', ', $line);
1012 $partUpdateFeeAmt['fee_amount'] = $inputParams['amount'];
1013 CRM_Event_BAO_Participant::add($partUpdateFeeAmt);
1014
1015 //activity creation
1016 CRM_Event_BAO_Participant::addActivityForSelection($entityID, 'Change Registration');
1017 }
1018 }
1019
1020 /**
1021 * Helper function to retrieve financial trxn parameters to reverse
1022 * for given financial item identified by $financialItemID
1023 *
1024 * @param int $financialItemID
1025 *
1026 * @return array $financialTrxn
1027 *
1028 */
1029 protected function getRelatedCancelFinancialTrxn($financialItemID) {
1030 $financialTrxn = civicrm_api3('EntityFinancialTrxn', 'getsingle', array(
1031 'entity_table' => 'civicrm_financial_item',
1032 'entity_id' => $financialItemID,
1033 'options' => array(
1034 'sort' => 'id DESC',
1035 'limit' => 1,
1036 ),
1037 'api.FinancialTrxn.getsingle' => array(
1038 'id' => "\$value.financial_trxn_id",
1039 ),
1040 ));
1041
1042 $financialTrxn = array_merge($financialTrxn['api.FinancialTrxn.getsingle'], array(
1043 'trxn_date' => date('YmdHis'),
1044 'total_amount' => -$financialTrxn['api.FinancialTrxn.getsingle']['total_amount'],
1045 'net_amount' => -$financialTrxn['api.FinancialTrxn.getsingle']['net_amount'],
1046 'entity_table' => 'civicrm_financial_item',
1047 'entity_id' => $financialItemID,
1048 ));
1049 unset($financialTrxn['id']);
1050
1051 return $financialTrxn;
1052 }
1053
1054 /**
1055 * Record adjusted amount.
1056 *
1057 * @param int $updatedAmount
1058 * @param int $paidAmount
1059 * @param int $contributionId
1060 *
1061 * @param int $taxAmount
1062 * @param bool $updateAmountLevel
1063 *
1064 * @return bool|\CRM_Core_BAO_FinancialTrxn
1065 */
1066 protected function recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount = NULL, $updateAmountLevel = NULL) {
1067 $pendingAmount = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId);
1068 $pendingAmount = CRM_Utils_Array::value('total_amount', $pendingAmount, 0);
1069 $balanceAmt = $updatedAmount - $paidAmount;
1070 if ($paidAmount != $pendingAmount) {
1071 $balanceAmt -= $pendingAmount;
1072 }
1073
1074 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
1075 $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
1076 $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
1077 $completedStatusId = array_search('Completed', $contributionStatuses);
1078
1079 $updatedContributionDAO = new CRM_Contribute_BAO_Contribution();
1080 $adjustedTrxn = $skip = FALSE;
1081 if ($balanceAmt) {
1082 if ($balanceAmt > 0 && $paidAmount != 0) {
1083 $contributionStatusVal = $partiallyPaidStatusId;
1084 }
1085 elseif ($balanceAmt < 0 && $paidAmount != 0) {
1086 $contributionStatusVal = $pendingRefundStatusId;
1087 }
1088 elseif ($paidAmount == 0) {
1089 //skip updating the contribution status if no payment is made
1090 $skip = TRUE;
1091 $updatedContributionDAO->cancel_date = 'null';
1092 $updatedContributionDAO->cancel_reason = NULL;
1093 }
1094 // update contribution status and total amount without trigger financial code
1095 // as this is handled in current BAO function used for change selection
1096 $updatedContributionDAO->id = $contributionId;
1097 if (!$skip) {
1098 $updatedContributionDAO->contribution_status_id = $contributionStatusVal;
1099 }
1100 $updatedContributionDAO->total_amount = $updatedContributionDAO->net_amount = $updatedAmount;
1101 $updatedContributionDAO->fee_amount = 0;
1102 $updatedContributionDAO->tax_amount = $taxAmount;
1103 if (!empty($updateAmountLevel)) {
1104 $updatedContributionDAO->amount_level = $updateAmountLevel;
1105 }
1106 $updatedContributionDAO->save();
1107 // adjusted amount financial_trxn creation
1108 $updatedContribution = CRM_Contribute_BAO_Contribution::getValues(
1109 array('id' => $contributionId),
1110 CRM_Core_DAO::$_nullArray,
1111 CRM_Core_DAO::$_nullArray
1112 );
1113 $toFinancialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($updatedContribution->financial_type_id, 'Accounts Receivable Account is');
1114 $adjustedTrxnValues = array(
1115 'from_financial_account_id' => NULL,
1116 'to_financial_account_id' => $toFinancialAccount,
1117 'total_amount' => $balanceAmt,
1118 'net_amount' => $balanceAmt,
1119 'status_id' => $completedStatusId,
1120 'payment_instrument_id' => $updatedContribution->payment_instrument_id,
1121 'contribution_id' => $updatedContribution->id,
1122 'trxn_date' => date('YmdHis'),
1123 'currency' => $updatedContribution->currency,
1124 );
1125 $adjustedTrxn = CRM_Core_BAO_FinancialTrxn::create($adjustedTrxnValues);
1126 }
1127 return $adjustedTrxn;
1128 }
1129
1130 /**
1131 * Add financial items to reflect line item change.
1132 *
1133 * @param bool $isCreateAdditionalFinancialTrxn
1134 * @param array $lineParams
1135 * @param \CRM_Contribute_BAO_Contribution $updatedContribution
1136 */
1137 protected function addFinancialItemsOnLineItemChange($isCreateAdditionalFinancialTrxn, $lineParams, $updatedContribution) {
1138 $tempFinancialTrxnID = NULL;
1139 // don't add financial item for cancelled line item
1140 if ($lineParams['qty'] == 0) {
1141 return;
1142 }
1143 elseif ($isCreateAdditionalFinancialTrxn) {
1144 // This routine & the return below is super uncomfortable.
1145 // I have refactored to here but don't understand how this would be hit
1146 // and it is how it would be a good thing, given the odd return below which
1147 // does not seem consistent with what is going on.
1148 // I'm tempted to add an e-deprecated into it to confirm my suspicion it only exists to
1149 // cause mental anguish.
1150 // original comment : add financial item if ONLY financial type is changed
1151 if ($lineParams['financial_type_id'] != $updatedContribution->financial_type_id) {
1152 $changedFinancialTypeID = (int) $lineParams['financial_type_id'];
1153 $adjustedTrxnValues = array(
1154 'from_financial_account_id' => NULL,
1155 'to_financial_account_id' => CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($updatedContribution->payment_instrument_id),
1156 'total_amount' => $lineParams['line_total'],
1157 'net_amount' => $lineParams['line_total'],
1158 'status_id' => $updatedContribution->contribution_status_id,
1159 'payment_instrument_id' => $updatedContribution->payment_instrument_id,
1160 'contribution_id' => $updatedContribution->id,
1161 'is_payment' => TRUE,
1162 // since balance is 0, which means contribution is completed
1163 'trxn_date' => date('YmdHis'),
1164 'currency' => $updatedContribution->currency,
1165 );
1166 $adjustedTrxn = CRM_Core_BAO_FinancialTrxn::create($adjustedTrxnValues);
1167 $tempFinancialTrxnID = array('id' => $adjustedTrxn->id);
1168 }
1169 }
1170 $lineObj = CRM_Price_BAO_LineItem::retrieve($lineParams, CRM_Core_DAO::$_nullArray);
1171 // insert financial items
1172 // ensure entity_financial_trxn table has a linking of it.
1173 CRM_Financial_BAO_FinancialItem::add($lineObj, $updatedContribution, NULL, $tempFinancialTrxnID);
1174 if (isset($lineObj->tax_amount)) {
1175 CRM_Financial_BAO_FinancialItem::add($lineObj, $updatedContribution, TRUE, $tempFinancialTrxnID);
1176 }
1177 }
1178
1179 /**
1180 * Get Financial items, culling out any that have already been reversed.
1181 *
1182 * @param int $entityID
1183 * @param string $entityTable
1184 *
1185 * @return array
1186 * Array of financial items that have not be reversed.
1187 */
1188 protected function getNonCancelledFinancialItems($entityID, $entityTable) {
1189 // gathering necessary info to record negative (deselected) financial_item
1190 $updateFinancialItem = "
1191 SELECT fi.*, price_field_value_id, financial_type_id, tax_amount
1192 FROM civicrm_financial_item fi LEFT JOIN civicrm_line_item li ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
1193 WHERE (li.entity_table = '{$entityTable}' AND li.entity_id = {$entityID})
1194 GROUP BY li.entity_table, li.entity_id, price_field_value_id, fi.id
1195 ";
1196 $updateFinancialItemInfoDAO = CRM_Core_DAO::executeQuery($updateFinancialItem);
1197
1198 $financialItemResult = $updateFinancialItemInfoDAO->fetchAll();
1199 $items = array();
1200 foreach ($financialItemResult as $index => $financialItem) {
1201 $items[$financialItem['price_field_value_id']][$index] = $financialItem['amount'];
1202
1203 if (!empty($items[$financialItem['price_field_value_id']])) {
1204 foreach ($items[$financialItem['price_field_value_id']] as $existingItemID => $existingAmount) {
1205 if ($financialItem['amount'] + $existingAmount == 0) {
1206 // Filter both rows as they cancel each other out.
1207 unset($financialItemResult[$index]);
1208 unset($financialItemResult[$existingItemID]);
1209 unset($items['price_field_value_id'][$existingItemID]);
1210 unset($items[$financialItem['price_field_value_id']][$index]);
1211 }
1212 }
1213
1214 }
1215
1216 }
1217 return $financialItemResult;
1218 }
1219
1220 /**
1221 * Get the string used to describe the sales tax (eg. VAT, GST).
1222 *
1223 * @return string
1224 */
1225 protected function getSalesTaxTerm() {
1226 return CRM_Contribute_BAO_Contribution::checkContributeSettings('tax_term');
1227 }
1228
1229 }