Exemple #1
0
 /**
  * Get line item purchase information.
  *
  * This function takes the input parameters and interprets out of it what has been purchased.
  *
  * @param $fields
  *   This is the output of the function CRM_Price_BAO_PriceSet::getSetDetail($priceSetID, FALSE, FALSE);
  *   And, it would make sense to introduce caching into that function and call it from here rather than
  *   require the $fields array which is passed from pillar to post around the form in order to pass it in here.
  * @param array $params
  *   Params reflecting form input e.g with fields 'price_5' => 7, 'price_8' => array(7, 8)
  * @param $lineItem
  *   Line item array to be altered.
  * @param string $component
  *   This parameter appears to only be relevant to determining whether memberships should be auto-renewed.
  *   (and is effectively a boolean for 'is_membership' which could be calculated from the line items.)
  */
 public static function processAmount($fields, &$params, &$lineItem, $component = '')
 {
     // using price set
     $totalPrice = $totalTax = 0;
     $radioLevel = $checkboxLevel = $selectLevel = $textLevel = array();
     if ($component) {
         $autoRenew = array();
         $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
     }
     foreach ($fields as $id => $field) {
         if (empty($params["price_{$id}"]) || empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL) {
             // skip if nothing was submitted for this field
             continue;
         }
         switch ($field['html_type']) {
             case 'Text':
                 $firstOption = reset($field['options']);
                 $params["price_{$id}"] = array($firstOption['id'] => $params["price_{$id}"]);
                 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
                 if (CRM_Utils_Array::value('tax_rate', $field['options'][key($field['options'])])) {
                     $lineItem = self::setLineItem($field, $lineItem, key($field['options']));
                     $totalTax += $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
                 }
                 if (CRM_Utils_Array::value('name', $field['options'][key($field['options'])]) == 'contribution_amount') {
                     $taxRates = CRM_Core_PseudoConstant::getTaxRates();
                     if (array_key_exists($params['financial_type_id'], $taxRates)) {
                         $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']];
                         $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($field['options'][key($field['options'])]['amount'], $field['options'][key($field['options'])]['tax_rate']);
                         $field['options'][key($field['options'])]['tax_amount'] = round($taxAmount['tax_amount'], 2);
                         $lineItem = self::setLineItem($field, $lineItem, key($field['options']));
                         $totalTax += $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
                     }
                 }
                 $totalPrice += $lineItem[$firstOption['id']]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[key($field['options'])]);
                 break;
             case 'Radio':
                 //special case if user select -none-
                 if ($params["price_{$id}"] <= 0) {
                     continue;
                 }
                 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
                 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
                 $optionLabel = CRM_Utils_Array::value('label', $field['options'][$optionValueId]);
                 $params['amount_priceset_level_radio'] = array();
                 $params['amount_priceset_level_radio'][$optionValueId] = $optionLabel;
                 if (isset($radioLevel)) {
                     $radioLevel = array_merge($radioLevel, array_keys($params['amount_priceset_level_radio']));
                 } else {
                     $radioLevel = array_keys($params['amount_priceset_level_radio']);
                 }
                 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
                 if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionValueId])) {
                     $lineItem = self::setLineItem($field, $lineItem, $optionValueId);
                     $totalTax += $field['options'][$optionValueId]['tax_amount'];
                     if (CRM_Utils_Array::value('field_title', $lineItem[$optionValueId]) == 'Membership Amount') {
                         $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
                     }
                 }
                 $totalPrice += $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionValueId]);
                 if ($component && isset($lineItem[$optionValueId]['auto_renew']) && is_numeric($lineItem[$optionValueId]['auto_renew'])) {
                     $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total'];
                 }
                 break;
             case 'Select':
                 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
                 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
                 $optionLabel = $field['options'][$optionValueId]['label'];
                 $params['amount_priceset_level_select'] = array();
                 $params['amount_priceset_level_select'][CRM_Utils_Array::key(1, $params["price_{$id}"])] = $optionLabel;
                 if (isset($selectLevel)) {
                     $selectLevel = array_merge($selectLevel, array_keys($params['amount_priceset_level_select']));
                 } else {
                     $selectLevel = array_keys($params['amount_priceset_level_select']);
                 }
                 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
                 if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionValueId])) {
                     $lineItem = self::setLineItem($field, $lineItem, $optionValueId);
                     $totalTax += $field['options'][$optionValueId]['tax_amount'];
                 }
                 $totalPrice += $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionValueId]);
                 if ($component && isset($lineItem[$optionValueId]['auto_renew']) && is_numeric($lineItem[$optionValueId]['auto_renew'])) {
                     $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total'];
                 }
                 break;
             case 'CheckBox':
                 $params['amount_priceset_level_checkbox'] = $optionIds = array();
                 foreach ($params["price_{$id}"] as $optionId => $option) {
                     $optionIds[] = $optionId;
                     $optionLabel = $field['options'][$optionId]['label'];
                     $params['amount_priceset_level_checkbox']["{$field['options'][$optionId]['id']}"] = $optionLabel;
                     if (isset($checkboxLevel)) {
                         $checkboxLevel = array_unique(array_merge($checkboxLevel, array_keys($params['amount_priceset_level_checkbox'])));
                     } else {
                         $checkboxLevel = array_keys($params['amount_priceset_level_checkbox']);
                     }
                 }
                 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
                 foreach ($optionIds as $optionId) {
                     if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionId])) {
                         $lineItem = self::setLineItem($field, $lineItem, $optionId);
                         $totalTax += $field['options'][$optionId]['tax_amount'];
                     }
                     $totalPrice += $lineItem[$optionId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionId]);
                     if ($component && isset($lineItem[$optionId]['auto_renew']) && is_numeric($lineItem[$optionId]['auto_renew'])) {
                         $autoRenew[$lineItem[$optionId]['auto_renew']] += $lineItem[$optionId]['line_total'];
                     }
                 }
                 break;
         }
     }
     $amount_level = array();
     $totalParticipant = 0;
     if (is_array($lineItem)) {
         foreach ($lineItem as $values) {
             $totalParticipant += $values['participant_count'];
             $amount_level[] = $values['label'] . ' - ' . (double) $values['qty'];
         }
     }
     $displayParticipantCount = '';
     if ($totalParticipant > 0) {
         $displayParticipantCount = ' Participant Count -' . $totalParticipant;
     }
     $params['amount_level'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amount_level) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
     $params['amount'] = CRM_Utils_Money::format($totalPrice, NULL, NULL, TRUE);
     $params['tax_amount'] = $totalTax;
     if ($component) {
         foreach ($autoRenew as $dontCare => $eachAmount) {
             if (!$eachAmount) {
                 unset($autoRenew[$dontCare]);
             }
         }
         if (count($autoRenew) > 1) {
             $params['autoRenew'] = $autoRenew;
         }
     }
 }
 /**
  * @param array $params
  * @param int $participantId
  * @param int $contributionId
  * @param $feeBlock
  * @param array $lineItems
  * @param $paidAmount
  * @param int $priceSetId
  */
 public static function changeFeeSelections($params, $participantId, $contributionId, $feeBlock, $lineItems, $paidAmount, $priceSetId)
 {
     $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
     $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
     $previousLineItems = CRM_Price_BAO_LineItem::getLineItems($participantId, 'participant');
     CRM_Price_BAO_PriceSet::processAmount($feeBlock, $params, $lineItems);
     // get the submitted
     foreach ($feeBlock as $id => $values) {
         CRM_Price_BAO_LineItem::format($id, $params, $values, $submittedLineItems);
         $submittedFieldId[] = CRM_Utils_Array::retrieveValueRecursive($submittedLineItems, 'price_field_id');
     }
     if (!empty($submittedLineItems)) {
         $insertLines = $submittedLineItems;
         $submittedFieldValueIds = array_keys($submittedLineItems);
         $updateLines = array();
         foreach ($previousLineItems as $id => $previousLineItem) {
             // check through the submitted items if the previousItem exists,
             // if found in submitted items, do not use it for new item creations
             if (in_array($previousLineItem['price_field_value_id'], $submittedFieldValueIds)) {
                 // if submitted line items are existing don't fire INSERT query
                 unset($insertLines[$previousLineItem['price_field_value_id']]);
                 // for updating the line items i.e. use-case - once deselect-option selecting again
                 if ($previousLineItem['line_total'] != $submittedLineItems[$previousLineItem['price_field_value_id']]['line_total'] || $submittedLineItems[$previousLineItem['price_field_value_id']]['line_total'] == 0 && $submittedLineItems[$previousLineItem['price_field_value_id']]['qty'] == 1 || $previousLineItem['qty'] != $submittedLineItems[$previousLineItem['price_field_value_id']]['qty']) {
                     $updateLines[$previousLineItem['price_field_value_id']] = $submittedLineItems[$previousLineItem['price_field_value_id']];
                     $updateLines[$previousLineItem['price_field_value_id']]['id'] = $id;
                 }
             }
         }
         $submittedFields = implode(', ', $submittedFieldId);
         $submittedFieldValues = implode(', ', $submittedFieldValueIds);
     }
     if (!empty($submittedFields) && !empty($submittedFieldValues)) {
         $updateLineItem = "UPDATE civicrm_line_item li\nINNER JOIN civicrm_financial_item fi\n   ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')\nSET li.qty = 0,\n    li.line_total = 0.00,\n    li.tax_amount = NULL\nWHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND\n       (price_field_value_id NOT IN ({$submittedFieldValues}))\n";
         CRM_Core_DAO::executeQuery($updateLineItem);
         // gathering necessary info to record negative (deselected) financial_item
         $updateFinancialItem = "\n  SELECT fi.*, SUM(fi.amount) as differenceAmt, price_field_value_id, financial_type_id, tax_amount\n    FROM civicrm_financial_item fi LEFT JOIN civicrm_line_item li ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')\nWHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId})\nGROUP BY li.entity_table, li.entity_id, price_field_value_id, fi.id\n";
         $updateFinancialItemInfoDAO = CRM_Core_DAO::executeQuery($updateFinancialItem);
         $trxn = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId, 'DESC', TRUE);
         $trxnId['id'] = $trxn['financialTrxnId'];
         $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
         $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
         $updateFinancialItemInfoValues = array();
         $financialItemsArray = array();
         while ($updateFinancialItemInfoDAO->fetch()) {
             $updateFinancialItemInfoValues = (array) $updateFinancialItemInfoDAO;
             $updateFinancialItemInfoValues['transaction_date'] = date('YmdHis');
             // the below params are not needed
             unset($updateFinancialItemInfoValues['id']);
             unset($updateFinancialItemInfoValues['created_date']);
             // if not submitted and difference is not 0 make it negative
             if (!in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] != 0) {
                 // INSERT negative financial_items
                 $updateFinancialItemInfoValues['amount'] = -$updateFinancialItemInfoValues['amount'];
                 if ($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']) {
                     $updateFinancialItemInfoValues['tax']['amount'] = -$previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount'];
                     $updateFinancialItemInfoValues['tax']['description'] = $taxTerm;
                     if ($updateFinancialItemInfoValues['financial_type_id']) {
                         $updateFinancialItemInfoValues['tax']['financial_account_id'] = CRM_Contribute_BAO_Contribution::getFinancialAccountId($updateFinancialItemInfoValues['financial_type_id']);
                     }
                 }
                 // INSERT negative financial_items for tax amount
                 $financialItemsArray[] = $updateFinancialItemInfoValues;
             } elseif (in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] == 0) {
                 $updateFinancialItemInfoValues['amount'] = $updateFinancialItemInfoValues['amount'];
                 // INSERT financial_items for tax amount
                 if ($updateFinancialItemInfoValues['entity_id'] == $updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['id'] && isset($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'])) {
                     $updateFinancialItemInfoValues['tax']['amount'] = $updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'];
                     $updateFinancialItemInfoValues['tax']['description'] = $taxTerm;
                     if ($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']) {
                         $updateFinancialItemInfoValues['tax']['financial_account_id'] = CRM_Contribute_BAO_Contribution::getFinancialAccountId($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']);
                     }
                 }
                 $financialItemsArray[] = $updateFinancialItemInfoValues;
             }
         }
     } elseif (empty($submittedFields) && empty($submittedFieldValues)) {
         $updateLineItem = "UPDATE civicrm_line_item li\n        INNER JOIN civicrm_financial_item fi\n        ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')\n        SET li.qty = 0,\n        li.line_total = 0.00,\n        li.tax_amount = NULL\n        WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId})";
         CRM_Core_DAO::executeQuery($updateLineItem);
     }
     $amountLevel = array();
     $totalParticipant = $participantCount = 0;
     if (!empty($updateLines)) {
         foreach ($updateLines as $valueId => $vals) {
             $taxAmount = "NULL";
             if (isset($vals['tax_amount'])) {
                 $taxAmount = $vals['tax_amount'];
             }
             $amountLevel[] = $vals['label'] . ' - ' . (double) $vals['qty'];
             if (isset($vals['participant_count'])) {
                 $participantCount = $vals['participant_count'];
                 $totalParticipant += $vals['participant_count'];
             }
             $updateLineItem = "\nUPDATE civicrm_line_item li\nSET li.qty = {$vals['qty']},\n    li.line_total = {$vals['line_total']},\n    li.tax_amount = {$taxAmount},\n    li.unit_price = {$vals['unit_price']},\n    li.participant_count = {$participantCount},\n    li.label = %1\nWHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND\n      (price_field_value_id = {$valueId})\n";
             CRM_Core_DAO::executeQuery($updateLineItem, array(1 => array($vals['label'], 'String')));
         }
     }
     // insert new 'adjusted amount' transaction entry and update contribution entry.
     // ensure entity_financial_trxn table has a linking of it.
     // insert new line items
     if (!empty($insertLines)) {
         foreach ($insertLines as $valueId => $lineParams) {
             $lineParams['entity_table'] = 'civicrm_participant';
             $lineParams['entity_id'] = $participantId;
             $lineParams['contribution_id'] = $contributionId;
             $lineObj = CRM_Price_BAO_LineItem::create($lineParams);
         }
     }
     // the recordAdjustedAmt code would execute over here
     $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
     if (count($ids) > 1) {
         $total = 0;
         foreach ($ids as $val) {
             $total += CRM_Price_BAO_LineItem::getLineTotal($val, 'civicrm_participant');
         }
         $updatedAmount = $total;
     } else {
         $updatedAmount = $params['amount'];
     }
     if (strlen($params['tax_amount']) != 0) {
         $taxAmount = $params['tax_amount'];
     } else {
         $taxAmount = "NULL";
     }
     $displayParticipantCount = '';
     if ($totalParticipant > 0) {
         $displayParticipantCount = ' Participant Count -' . $totalParticipant;
     }
     $updateAmountLevel = NULL;
     if (!empty($amountLevel)) {
         $updateAmountLevel = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amountLevel) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
     }
     $trxn = self::recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount, $updateAmountLevel);
     $trxnId = array();
     if ($trxn) {
         $trxnId['id'] = $trxn->id;
         foreach ($financialItemsArray as $updateFinancialItemInfoValues) {
             CRM_Financial_BAO_FinancialItem::create($updateFinancialItemInfoValues, NULL, $trxnId);
             if (!empty($updateFinancialItemInfoValues['tax'])) {
                 $updateFinancialItemInfoValues['tax']['amount'] = $updateFinancialItemInfoValues['amount'];
                 $updateFinancialItemInfoValues['tax']['description'] = $updateFinancialItemInfoValues['description'];
                 if (!empty($updateFinancialItemInfoValues['financial_account_id'])) {
                     $updateFinancialItemInfoValues['financial_account_id'] = $updateFinancialItemInfoValues['tax']['financial_account_id'];
                 }
                 CRM_Financial_BAO_FinancialItem::create($updateFinancialItemInfoValues, NULL, $trxnId);
             }
         }
     }
     $fetchCon = array('id' => $contributionId);
     $updatedContribution = CRM_Contribute_BAO_Contribution::retrieve($fetchCon, CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
     // insert financial items
     if (!empty($insertLines)) {
         foreach ($insertLines as $valueId => $lineParams) {
             $lineParams['entity_table'] = 'civicrm_participant';
             $lineParams['entity_id'] = $participantId;
             $lineObj = CRM_Price_BAO_LineItem::retrieve($lineParams, CRM_Core_DAO::$_nullArray);
             // insert financial items
             // ensure entity_financial_trxn table has a linking of it.
             $prevItem = CRM_Financial_BAO_FinancialItem::add($lineObj, $updatedContribution, NULL, $trxnId);
             if (isset($lineObj->tax_amount)) {
                 CRM_Financial_BAO_FinancialItem::add($lineObj, $updatedContribution, TRUE, $trxnId);
             }
         }
     }
     // update participant fee_amount column
     $partUpdateFeeAmt['id'] = $participantId;
     $getUpdatedLineItems = "SELECT *\nFROM civicrm_line_item\nWHERE (entity_table = 'civicrm_participant' AND entity_id = {$participantId} AND qty > 0)";
     $getUpdatedLineItemsDAO = CRM_Core_DAO::executeQuery($getUpdatedLineItems);
     while ($getUpdatedLineItemsDAO->fetch()) {
         $line[$getUpdatedLineItemsDAO->price_field_value_id] = $getUpdatedLineItemsDAO->label . ' - ' . (double) $getUpdatedLineItemsDAO->qty;
     }
     $partUpdateFeeAmt['fee_level'] = implode(', ', $line);
     $partUpdateFeeAmt['fee_amount'] = $params['amount'];
     self::add($partUpdateFeeAmt);
     //activity creation
     self::addActivityForSelection($participantId, 'Change Registration');
 }
Exemple #3
0
 static function processAmount(&$fields, &$params, &$lineItem)
 {
     // using price set
     $totalPrice = 0;
     $radioLevel = $checkboxLevel = $selectLevel = $textLevel = array();
     require_once 'CRM/Price/BAO/LineItem.php';
     foreach ($fields as $id => $field) {
         if (empty($params["price_{$id}"]) && $params["price_{$id}"] == null) {
             // skip if nothing was submitted for this field
             continue;
         }
         switch ($field['html_type']) {
             case 'Text':
                 $params["price_{$id}"] = array(key($field['options']) => $params["price_{$id}"]);
                 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
                 $totalPrice += $lineItem[key($field['options'])]['line_total'];
                 break;
             case 'Radio':
                 //special case if user select -none-
                 if ($params["price_{$id}"] == 0) {
                     continue;
                 }
                 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
                 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
                 $optionLabel = $field['options'][$optionValueId]['label'];
                 $params['amount_priceset_level_radio'] = array();
                 $params['amount_priceset_level_radio'][$optionValueId] = $optionLabel;
                 if (isset($radioLevel)) {
                     $radioLevel = array_merge($radioLevel, array_keys($params['amount_priceset_level_radio']));
                 } else {
                     $radioLevel = array_keys($params['amount_priceset_level_radio']);
                 }
                 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
                 $totalPrice += $lineItem[$optionValueId]['line_total'];
                 break;
             case 'Select':
                 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
                 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
                 $optionLabel = $field['options'][$optionValueId]['label'];
                 $params['amount_priceset_level_select'] = array();
                 $params['amount_priceset_level_select'][CRM_Utils_Array::key(1, $params["price_{$id}"])] = $optionLabel;
                 if (isset($selectLevel)) {
                     $selectLevel = array_merge($selectLevel, array_keys($params['amount_priceset_level_select']));
                 } else {
                     $selectLevel = array_keys($params['amount_priceset_level_select']);
                 }
                 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
                 $totalPrice += $lineItem[$optionValueId]['line_total'];
                 break;
             case 'CheckBox':
                 $params['amount_priceset_level_checkbox'] = $optionIds = array();
                 foreach ($params["price_{$id}"] as $optionId => $option) {
                     $optionIds[] = $optionId;
                     $optionLabel = $field['options'][$optionId]['label'];
                     $params['amount_priceset_level_checkbox']["{$field['options'][$optionId]['id']}"] = $optionLabel;
                     if (isset($checkboxLevel)) {
                         $checkboxLevel = array_unique(array_merge($checkboxLevel, array_keys($params['amount_priceset_level_checkbox'])));
                     } else {
                         $checkboxLevel = array_keys($params['amount_priceset_level_checkbox']);
                     }
                 }
                 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
                 foreach ($optionIds as $optionId) {
                     $totalPrice += $lineItem[$optionId]['line_total'];
                 }
                 break;
         }
     }
     $amount_level = array();
     if (is_array($lineItem)) {
         foreach ($lineItem as $values) {
             if ($values['html_type'] == 'Text') {
                 $amount_level[] = $values['label'] . ' - ' . $values['qty'];
                 continue;
             }
             $amount_level[] = $values['label'];
         }
     }
     require_once 'CRM/Core/BAO/CustomOption.php';
     $params['amount_level'] = CRM_Core_BAO_CustomOption::VALUE_SEPERATOR . implode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, $amount_level) . CRM_Core_BAO_CustomOption::VALUE_SEPERATOR;
     $params['amount'] = $totalPrice;
 }
 /**
  * @param $params
  * @param $participantId
  * @param $contributionId
  * @param $feeBlock
  * @param $lineItems
  * @param $paidAmount
  * @param $priceSetId
  */
 static function changeFeeSelections($params, $participantId, $contributionId, $feeBlock, $lineItems, $paidAmount, $priceSetId)
 {
     $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
     $pendngRefundStatusId = array_search('Pending refund', $contributionStatuses);
     $previousLineItems = CRM_Price_BAO_LineItem::getLineItems($participantId, 'participant');
     CRM_Price_BAO_PriceSet::processAmount($feeBlock, $params, $lineItems);
     // get the submitted
     foreach ($feeBlock as $id => $values) {
         CRM_Price_BAO_LineItem::format($id, $params, $values, $submittedLineItems);
         $submittedFieldId[] = CRM_Utils_Array::retrieveValueRecursive($submittedLineItems, 'price_field_id');
     }
     $insertLines = $submittedLineItems;
     $submittedFieldValueIds = array_keys($submittedLineItems);
     $updateLines = array();
     foreach ($previousLineItems as $id => $previousLineItem) {
         // check through the submitted items if the previousItem exists,
         // if found in submitted items, do not use it for new item creations
         if (in_array($previousLineItem['price_field_value_id'], $submittedFieldValueIds)) {
             // if submitted line items are existing don't fire INSERT query
             unset($insertLines[$previousLineItem['price_field_value_id']]);
             // for updating the line items i.e. use-case - once deselect-option selecting again
             if ($previousLineItem['line_total'] != $submittedLineItems[$previousLineItem['price_field_value_id']]['line_total']) {
                 $updateLines[$previousLineItem['price_field_value_id']]['qty'] = $submittedLineItems[$previousLineItem['price_field_value_id']]['qty'];
                 $updateLines[$previousLineItem['price_field_value_id']]['line_total'] = $submittedLineItems[$previousLineItem['price_field_value_id']]['line_total'];
             }
         }
     }
     $submittedFields = implode(', ', $submittedFieldId);
     $submittedFieldValues = implode(', ', $submittedFieldValueIds);
     if (!empty($submittedFields) && !empty($submittedFieldValues)) {
         $updateLineItem = "UPDATE civicrm_line_item li\nINNER JOIN civicrm_financial_item fi\n   ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')\nSET li.qty = 0,\n    li.line_total = 0.00\nWHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND\n       (price_field_value_id NOT IN ({$submittedFieldValues}))\n";
         CRM_Core_DAO::executeQuery($updateLineItem);
         // gathering necessary info to record negative (deselected) financial_item
         $updateFinancialItem = "\n  SELECT fi.*, SUM(fi.amount) as differenceAmt, price_field_value_id\n    FROM civicrm_financial_item fi LEFT JOIN civicrm_line_item li ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')\nWHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId})\nGROUP BY li.entity_table, li.entity_id, price_field_value_id\n";
         $updateFinancialItemInfoDAO = CRM_Core_DAO::executeQuery($updateFinancialItem);
         $trxn = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId, 'ASC', TRUE);
         $trxnId['id'] = $trxn['financialTrxnId'];
         $updateFinancialItemInfoValues = array();
         while ($updateFinancialItemInfoDAO->fetch()) {
             $updateFinancialItemInfoValues = (array) $updateFinancialItemInfoDAO;
             $updateFinancialItemInfoValues['transaction_date'] = date('YmdHis');
             // the below params are not needed
             unset($updateFinancialItemInfoValues['id']);
             unset($updateFinancialItemInfoValues['created_date']);
             // if not submitted and difference is not 0 make it negative
             if (!in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] != 0) {
                 // INSERT negative financial_items
                 $updateFinancialItemInfoValues['amount'] = -$updateFinancialItemInfoValues['amount'];
                 CRM_Financial_BAO_FinancialItem::create($updateFinancialItemInfoValues, NULL, $trxnId);
             } elseif (in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] == 0) {
                 $updateFinancialItemInfoValues['amount'] = $updateFinancialItemInfoValues['amount'];
                 CRM_Financial_BAO_FinancialItem::create($updateFinancialItemInfoValues, NULL, $trxnId);
             }
         }
     }
     if (!empty($updateLines)) {
         foreach ($updateLines as $valueId => $vals) {
             $updateLineItem = "\nUPDATE civicrm_line_item li\nSET li.qty = {$vals['qty']},\n    li.line_total = {$vals['line_total']}\nWHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND\n      (price_field_value_id = {$valueId})\n";
             CRM_Core_DAO::executeQuery($updateLineItem);
         }
     }
     // insert new 'adjusted amount' transaction entry and update contribution entry.
     // ensure entity_financial_trxn table has a linking of it.
     // insert new line items
     foreach ($insertLines as $valueId => $lineParams) {
         $lineParams['entity_table'] = 'civicrm_participant';
         $lineParams['entity_id'] = $participantId;
         $lineObj = CRM_Price_BAO_LineItem::create($lineParams);
     }
     // the recordAdjustedAmt code would execute over here
     $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
     if (count($ids) > 1) {
         $total = 0;
         foreach ($ids as $val) {
             $total += CRM_Price_BAO_LineItem::getLineTotal($val, 'civicrm_participant');
         }
         $updatedAmount = $total;
     } else {
         $updatedAmount = $params['amount'];
     }
     self::recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId);
     $fetchCon = array('id' => $contributionId);
     $updatedContribution = CRM_Contribute_BAO_Contribution::retrieve($fetchCon, CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
     // insert financial items
     foreach ($insertLines as $valueId => $lineParams) {
         $lineParams['entity_table'] = 'civicrm_participant';
         $lineParams['entity_id'] = $participantId;
         $lineObj = CRM_Price_BAO_LineItem::retrieve($lineParams, CRM_Core_DAO::$_nullArray);
         // insert financial items
         // ensure entity_financial_trxn table has a linking of it.
         $prevItem = CRM_Financial_BAO_FinancialItem::add($lineObj, $updatedContribution);
     }
     // update participant fee_amount column
     $partUpdateFeeAmt['id'] = $participantId;
     $partUpdateFeeAmt['fee_amount'] = $params['amount'];
     self::add($partUpdateFeeAmt);
     //activity creation
     self::addActivityForSelection($participantId, 'Change Registration');
 }
 /**
  * Get line item purchase information.
  *
  * This function takes the input parameters and interprets out of it what has been purchased.
  *
  * @param $fields
  *   This is the output of the function CRM_Price_BAO_PriceSet::getSetDetail($priceSetID, FALSE, FALSE);
  *   And, it would make sense to introduce caching into that function and call it from here rather than
  *   require the $fields array which is passed from pillar to post around the form in order to pass it in here.
  * @param array $params
  *   Params reflecting form input e.g with fields 'price_5' => 7, 'price_8' => array(7, 8)
  * @param $lineItem
  *   Line item array to be altered.
  * @param string $component
  *   This parameter appears to only be relevant to determining whether memberships should be auto-renewed.
  *   (and is effectively a boolean for 'is_membership' which could be calculated from the line items.)
  */
 public static function processAmount($fields, &$params, &$lineItem, $component = '')
 {
     // using price set
     $totalPrice = $totalTax = 0;
     $radioLevel = $checkboxLevel = $selectLevel = $textLevel = array();
     if ($component) {
         $autoRenew = array();
         $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
     }
     foreach ($fields as $id => $field) {
         if (empty($params["price_{$id}"]) || empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL) {
             // skip if nothing was submitted for this field
             continue;
         }
         switch ($field['html_type']) {
             case 'Text':
                 $firstOption = reset($field['options']);
                 $params["price_{$id}"] = array($firstOption['id'] => $params["price_{$id}"]);
                 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
                 if (CRM_Utils_Array::value('tax_rate', $field['options'][key($field['options'])])) {
                     $lineItem = self::setLineItem($field, $lineItem, key($field['options']));
                     $totalTax += $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
                 }
                 if (CRM_Utils_Array::value('name', $field['options'][key($field['options'])]) == 'contribution_amount') {
                     $taxRates = CRM_Core_PseudoConstant::getTaxRates();
                     if (array_key_exists($params['financial_type_id'], $taxRates)) {
                         $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']];
                         $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($field['options'][key($field['options'])]['amount'], $field['options'][key($field['options'])]['tax_rate']);
                         $field['options'][key($field['options'])]['tax_amount'] = round($taxAmount['tax_amount'], 2);
                         $lineItem = self::setLineItem($field, $lineItem, key($field['options']));
                         $totalTax += $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
                     }
                 }
                 $totalPrice += $lineItem[$firstOption['id']]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[key($field['options'])]);
                 break;
             case 'Radio':
                 //special case if user select -none-
                 if ($params["price_{$id}"] <= 0) {
                     continue;
                 }
                 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
                 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
                 $optionLabel = CRM_Utils_Array::value('label', $field['options'][$optionValueId]);
                 $params['amount_priceset_level_radio'] = array();
                 $params['amount_priceset_level_radio'][$optionValueId] = $optionLabel;
                 if (isset($radioLevel)) {
                     $radioLevel = array_merge($radioLevel, array_keys($params['amount_priceset_level_radio']));
                 } else {
                     $radioLevel = array_keys($params['amount_priceset_level_radio']);
                 }
                 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
                 if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionValueId])) {
                     $lineItem = self::setLineItem($field, $lineItem, $optionValueId);
                     $totalTax += $field['options'][$optionValueId]['tax_amount'];
                     if (CRM_Utils_Array::value('field_title', $lineItem[$optionValueId]) == 'Membership Amount') {
                         $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
                     }
                 }
                 $totalPrice += $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionValueId]);
                 if ($component && isset($lineItem[$optionValueId]['auto_renew']) && is_numeric($lineItem[$optionValueId]['auto_renew'])) {
                     $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total'];
                 }
                 break;
             case 'Select':
                 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
                 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
                 $optionLabel = $field['options'][$optionValueId]['label'];
                 $params['amount_priceset_level_select'] = array();
                 $params['amount_priceset_level_select'][CRM_Utils_Array::key(1, $params["price_{$id}"])] = $optionLabel;
                 if (isset($selectLevel)) {
                     $selectLevel = array_merge($selectLevel, array_keys($params['amount_priceset_level_select']));
                 } else {
                     $selectLevel = array_keys($params['amount_priceset_level_select']);
                 }
                 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
                 if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionValueId])) {
                     $lineItem = self::setLineItem($field, $lineItem, $optionValueId);
                     $totalTax += $field['options'][$optionValueId]['tax_amount'];
                 }
                 $totalPrice += $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionValueId]);
                 if ($component && isset($lineItem[$optionValueId]['auto_renew']) && is_numeric($lineItem[$optionValueId]['auto_renew'])) {
                     $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total'];
                 }
                 break;
             case 'CheckBox':
                 $params['amount_priceset_level_checkbox'] = $optionIds = array();
                 foreach ($params["price_{$id}"] as $optionId => $option) {
                     $optionIds[] = $optionId;
                     $optionLabel = $field['options'][$optionId]['label'];
                     $params['amount_priceset_level_checkbox']["{$field['options'][$optionId]['id']}"] = $optionLabel;
                     if (isset($checkboxLevel)) {
                         $checkboxLevel = array_unique(array_merge($checkboxLevel, array_keys($params['amount_priceset_level_checkbox'])));
                     } else {
                         $checkboxLevel = array_keys($params['amount_priceset_level_checkbox']);
                     }
                 }
                 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
                 foreach ($optionIds as $optionId) {
                     if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionId])) {
                         $lineItem = self::setLineItem($field, $lineItem, $optionId);
                         $totalTax += $field['options'][$optionId]['tax_amount'];
                     }
                     $totalPrice += $lineItem[$optionId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionId]);
                     if ($component && isset($lineItem[$optionId]['auto_renew']) && is_numeric($lineItem[$optionId]['auto_renew'])) {
                         $autoRenew[$lineItem[$optionId]['auto_renew']] += $lineItem[$optionId]['line_total'];
                     }
                 }
                 break;
         }
     }
     $amount_level = array();
     $totalParticipant = 0;
     if (is_array($lineItem)) {
         foreach ($lineItem as $values) {
             $totalParticipant += $values['participant_count'];
             // This is a bit nasty. The logic of 'quick config' was because price set configuration was
             // (and still is) too difficult to replace the 'quick config' price set configuration on the contribution
             // page.
             //
             // However, because the quick config concept existed all sorts of logic was hung off it
             // and function behaviour sometimes depends on whether 'price set' is set - although actually it
             // is always set at the functional level. In this case we are dealing with the default 'quick config'
             // price set having a label of 'Contribution Amount' which could wind up creating a 'funny looking' label.
             // The correct answer is probably for it to have an empty label in the DB - the label is never shown so it is a
             // place holder.
             //
             // But, in the interests of being careful when capacity is low - avoiding the known default value
             // will get us by.
             // Crucially a test has been added so a better solution can be implemented later with some comfort.
             // @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it.
             if ($values['label'] != ts('Contribution Amount')) {
                 $amount_level[] = $values['label'] . ' - ' . (double) $values['qty'];
             }
         }
     }
     $displayParticipantCount = '';
     if ($totalParticipant > 0) {
         $displayParticipantCount = ' Participant Count -' . $totalParticipant;
     }
     // @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it.
     if (!empty($amount_level)) {
         $params['amount_level'] = CRM_Utils_Array::implodePadded($amount_level);
         if (!empty($displayParticipantCount)) {
             $params['amount_level'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amount_level) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
         }
     }
     $params['amount'] = CRM_Utils_Money::format($totalPrice, NULL, NULL, TRUE);
     $params['tax_amount'] = $totalTax;
     if ($component) {
         foreach ($autoRenew as $dontCare => $eachAmount) {
             if (!$eachAmount) {
                 unset($autoRenew[$dontCare]);
             }
         }
         if (count($autoRenew) > 1) {
             $params['autoRenew'] = $autoRenew;
         }
     }
 }
 /**
  * @param $fields
  * @param $params
  * @param $lineItem
  * @param string $component
  */
 static function processAmount(&$fields, &$params, &$lineItem, $component = '')
 {
     // using price set
     $totalPrice = 0;
     $radioLevel = $checkboxLevel = $selectLevel = $textLevel = array();
     if ($component) {
         $autoRenew = array();
         $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
     }
     foreach ($fields as $id => $field) {
         if (empty($params["price_{$id}"]) || empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL) {
             // skip if nothing was submitted for this field
             continue;
         }
         switch ($field['html_type']) {
             case 'Text':
                 $firstOption = reset($field['options']);
                 $params["price_{$id}"] = array($firstOption['id'] => $params["price_{$id}"]);
                 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
                 $totalPrice += $lineItem[$firstOption['id']]['line_total'];
                 break;
             case 'Radio':
                 //special case if user select -none-
                 if ($params["price_{$id}"] <= 0) {
                     continue;
                 }
                 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
                 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
                 $optionLabel = CRM_Utils_Array::value('label', $field['options'][$optionValueId]);
                 $params['amount_priceset_level_radio'] = array();
                 $params['amount_priceset_level_radio'][$optionValueId] = $optionLabel;
                 if (isset($radioLevel)) {
                     $radioLevel = array_merge($radioLevel, array_keys($params['amount_priceset_level_radio']));
                 } else {
                     $radioLevel = array_keys($params['amount_priceset_level_radio']);
                 }
                 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
                 $totalPrice += $lineItem[$optionValueId]['line_total'];
                 if ($component && isset($lineItem[$optionValueId]['auto_renew']) && is_numeric($lineItem[$optionValueId]['auto_renew'])) {
                     $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total'];
                 }
                 break;
             case 'Select':
                 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
                 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
                 $optionLabel = $field['options'][$optionValueId]['label'];
                 $params['amount_priceset_level_select'] = array();
                 $params['amount_priceset_level_select'][CRM_Utils_Array::key(1, $params["price_{$id}"])] = $optionLabel;
                 if (isset($selectLevel)) {
                     $selectLevel = array_merge($selectLevel, array_keys($params['amount_priceset_level_select']));
                 } else {
                     $selectLevel = array_keys($params['amount_priceset_level_select']);
                 }
                 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
                 $totalPrice += $lineItem[$optionValueId]['line_total'];
                 if ($component && isset($lineItem[$optionValueId]['auto_renew']) && is_numeric($lineItem[$optionValueId]['auto_renew'])) {
                     $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total'];
                 }
                 break;
             case 'CheckBox':
                 $params['amount_priceset_level_checkbox'] = $optionIds = array();
                 foreach ($params["price_{$id}"] as $optionId => $option) {
                     $optionIds[] = $optionId;
                     $optionLabel = $field['options'][$optionId]['label'];
                     $params['amount_priceset_level_checkbox']["{$field['options'][$optionId]['id']}"] = $optionLabel;
                     if (isset($checkboxLevel)) {
                         $checkboxLevel = array_unique(array_merge($checkboxLevel, array_keys($params['amount_priceset_level_checkbox'])));
                     } else {
                         $checkboxLevel = array_keys($params['amount_priceset_level_checkbox']);
                     }
                 }
                 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
                 foreach ($optionIds as $optionId) {
                     $totalPrice += $lineItem[$optionId]['line_total'];
                     if ($component && isset($lineItem[$optionId]['auto_renew']) && is_numeric($lineItem[$optionId]['auto_renew'])) {
                         $autoRenew[$lineItem[$optionId]['auto_renew']] += $lineItem[$optionId]['line_total'];
                     }
                 }
                 break;
         }
     }
     $amount_level = array();
     $totalParticipant = 0;
     if (is_array($lineItem)) {
         foreach ($lineItem as $values) {
             $totalParticipant += $values['participant_count'];
             if ($values['html_type'] == 'Text') {
                 $amount_level[] = $values['label'] . ' - ' . $values['qty'];
                 continue;
             }
             $amount_level[] = $values['label'];
         }
     }
     $displayParticipantCount = '';
     if ($totalParticipant > 0) {
         $displayParticipantCount = ' Participant Count -' . $totalParticipant;
     }
     $params['amount_level'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amount_level) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
     $params['amount'] = $totalPrice;
     if ($component) {
         foreach ($autoRenew as $dontCare => $eachAmount) {
             if (!$eachAmount) {
                 unset($autoRenew[$dontCare]);
             }
         }
         if (count($autoRenew) > 1) {
             $params['autoRenew'] = $autoRenew;
         }
     }
 }
 static function changeFeeSelections($params, $participantId, $contributionId, $feeBlock, $lineItems, $paidAmount, $priceSetId)
 {
     $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
     $pendngRefundStatusId = array_search('Pending refund', $contributionStatuses);
     $fetchCon = array('id' => $contributionId);
     $contributionObj = CRM_Contribute_BAO_Contribution::retrieve($fetchCon, CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
     $previousLineItems = CRM_Price_BAO_LineItem::getLineItems($participantId, 'participant');
     CRM_Price_BAO_PriceSet::processAmount($feeBlock, $params, $lineItems);
     // get the submitted
     foreach ($feeBlock as $id => $values) {
         CRM_Price_BAO_LineItem::format($id, $params, $values, $submittedLineItems);
         $submittedFieldId[] = CRM_Utils_Array::retrieveValueRecursive($submittedLineItems, 'price_field_id');
     }
     $insertLines = $submittedLineItems;
     $submittedFieldValueIds = array_keys($submittedLineItems);
     foreach ($previousLineItems as $id => $previousLineItem) {
         // check through the submitted items if the previousItem exists,
         // if found in submitted items, do not use it for new item creations
         if (in_array($previousLineItem['price_field_value_id'], $submittedFieldValueIds)) {
             unset($insertLines[$previousLineItem['price_field_value_id']]);
         }
     }
     $submittedFields = implode(', ', $submittedFieldId);
     $submittedFieldValues = implode(', ', $submittedFieldValueIds);
     if (!empty($submittedFields) && !empty($submittedFieldValues)) {
         // if previous line item is not submitted in selection, update the line total and QTY to '0'
         $updateLineItem = "\nUPDATE civicrm_line_item li\nINNER JOIN civicrm_financial_item fi\n   ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')\nINNER JOIN civicrm_entity_financial_trxn eft\n   ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')\nSET li.qty = 0,\n    li.line_total = 0.00,\n    fi.amount = 0.00,\n    eft.amount = 0.00\nWHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND\n      (price_field_value_id NOT IN ({$submittedFieldValues}) OR price_field_id NOT IN ({$submittedFields}))\n";
         CRM_Core_DAO::executeQuery($updateLineItem);
     }
     // insert new line items
     foreach ($insertLines as $valueId => $lineParams) {
         $lineParams['entity_table'] = 'civicrm_participant';
         $lineParams['entity_id'] = $participantId;
         $lineObj = CRM_Price_BAO_LineItem::create($lineParams);
         // insert financial items
         // ensure entity_financial_trxn table has a linking of it.
         $prevItem = CRM_Financial_BAO_FinancialItem::add($lineObj, $contributionObj);
     }
     // insert new 'adjusted amount' transaction entry and update contribution entry.
     // ensure entity_financial_trxn table has a linking of it.
     $updatedAmount = $params['amount'];
     $balanceAmt = $updatedAmount - $paidAmount;
     if ($balanceAmt) {
         if ($balanceAmt > 0) {
             $contributionStatusVal = $partiallyPaidStatusId;
         } elseif ($balanceAmt < 0) {
             $contributionStatusVal = $pendngRefundStatusId;
         }
         // update contribution status and total amount without trigger financial code
         // as this is handled in current BAO function used for change selection
         $updatedContributionDAO = new CRM_Contribute_BAO_Contribution();
         $updatedContributionDAO->id = $contributionId;
         $updatedContributionDAO->contribution_status_id = $contributionStatusVal;
         $updatedContributionDAO->total_amount = $updatedAmount;
         $updatedContributionDAO->save();
         /*
          * adjusted amount financial_trxn creation,
          * adjusted amount line_item creation,
          * adjusted amount financial_item creations,
          * adjusted amount enitity_financial_trxn creation
          */
         $updatedContribution = CRM_Contribute_BAO_Contribution::getValues(array('id' => $contributionId), CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
         $prevTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId);
         $fetchPrevTrxn['id'] = $prevTrxnId['financialTrxnId'];
         $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
         $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($updatedContribution->financial_type_id, $relationTypeId);
         $adjustedTrxnValues = array('from_financial_account_id' => NULL, 'to_financial_account_id' => $toFinancialAccount, 'trxn_date' => date('YmdHis'), 'total_amount' => $balanceAmt, 'currency' => $updatedContribution->currency, 'status_id' => CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name'), 'payment_instrument_id' => $updatedContribution->payment_instrument_id, 'contribution_id' => $updatedContribution->id);
         $adjustedTrxn = CRM_Core_BAO_FinancialTrxn::create($adjustedTrxnValues);
         // record line item
         $adjustPaymentLineParams = array('total_amount' => $updatedAmount, 'financial_type_id' => $updatedContribution->financial_type_id);
         $setId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
         CRM_Price_BAO_LineItem::getLineItemArray($adjustPaymentLineParams);
         $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id');
         $defaultPriceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($setId));
         $fieldID = key($defaultPriceSet['fields']);
         $adjustPaymentLineParams['line_item'][$setId][$fieldID]['entity_id'] = $updatedContribution->id;
         $adjustPaymentLineParams['line_item'][$setId][$fieldID]['entity_table'] = 'civicrm_contribution';
         $adjustPaymentLine = CRM_Price_BAO_LineItem::create($adjustPaymentLineParams['line_item'][$setId][$fieldID]);
         // record financial item
         $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id');
         $itemStatus = NULL;
         if ($updatedContribution->contribution_status_id == array_search('Pending refund', $contributionStatuses)) {
             $itemStatus = array_search('Paid', $financialItemStatus);
         } elseif ($updatedContribution->contribution_status_id == array_search('Partially paid', $contributionStatuses)) {
             $itemStatus = array_search('Partially paid', $financialItemStatus);
         }
         $params = array('transaction_date' => CRM_Utils_Date::isoToMysql($updatedContribution->receive_date), 'contact_id' => $updatedContribution->contact_id, 'amount' => $balanceAmt, 'currency' => $updatedContribution->currency, 'entity_table' => 'civicrm_line_item', 'entity_id' => $adjustPaymentLine->id, 'description' => ($adjustPaymentLine->qty != 1 ? $lineItem->qty . ' of ' : '') . ' ' . $adjustPaymentLine->label, 'status_id' => $itemStatus, 'financial_account_id' => $prevItem->financial_account_id);
         CRM_Financial_BAO_FinancialItem::create($params, NULL, array('id' => $adjustedTrxn->id));
     }
     //activity creation$contributionStatuses
     self::addActivityForSelection($participantId, 'Change Registration');
 }