Exemple #1
0
 /**
  * Process price set and line items.
  *
  * @param int $membershipId
  * @param array $lineItem
  */
 public function processPriceSet($membershipId, $lineItem)
 {
     //FIXME : need to move this too
     if (!$membershipId || !is_array($lineItem) || CRM_Utils_System::isNull($lineItem)) {
         return;
     }
     foreach ($lineItem as $priceSetId => $values) {
         if (!$priceSetId) {
             continue;
         }
         foreach ($values as $line) {
             $line['entity_table'] = 'civicrm_membership';
             $line['entity_id'] = $membershipId;
             CRM_Price_BAO_LineItem::create($line);
         }
     }
 }
Exemple #2
0
 /**
  * Process price set and line items.
  *
  * @param int $entityId
  * @param array $lineItem
  *   Line item array.
  * @param object $contributionDetails
  * @param string $entityTable
  *   Entity table.
  *
  * @param bool $update
  *
  * @return void
  */
 public static function processPriceSet($entityId, $lineItem, $contributionDetails = NULL, $entityTable = 'civicrm_contribution', $update = FALSE)
 {
     if (!$entityId || !is_array($lineItem) || CRM_Utils_system::isNull($lineItem)) {
         return;
     }
     foreach ($lineItem as $priceSetId => $values) {
         if (!$priceSetId) {
             continue;
         }
         foreach ($values as $line) {
             $line['entity_table'] = $entityTable;
             if (empty($line['entity_id'])) {
                 $line['entity_id'] = $entityId;
             }
             if (!empty($line['membership_type_id'])) {
                 $line['entity_table'] = 'civicrm_membership';
             }
             if (!empty($contributionDetails->id)) {
                 $line['contribution_id'] = $contributionDetails->id;
                 if ($line['entity_table'] == 'civicrm_contribution') {
                     $line['entity_id'] = $contributionDetails->id;
                 }
             }
             // if financial type is not set and if price field value is NOT NULL
             // get financial type id of price field value
             if (!empty($line['price_field_value_id']) && empty($line['financial_type_id'])) {
                 $line['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $line['price_field_value_id'], 'financial_type_id');
             }
             $lineItems = CRM_Price_BAO_LineItem::create($line);
             if (!$update && $contributionDetails) {
                 CRM_Financial_BAO_FinancialItem::add($lineItems, $contributionDetails);
                 if (isset($line['tax_amount'])) {
                     CRM_Financial_BAO_FinancialItem::add($lineItems, $contributionDetails, TRUE);
                 }
             }
         }
     }
 }
 /**
  * @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');
 }
 /**
  * Function to process price set and line items.
  * @param int $contributionId contribution id
  * @param array $lineItem line item array
  * @param object $contributionDetails
  * @param decimal $initAmount amount
  * @param string $entityTable entity table
  *
  * @access public
  * @return void
  * @static
  */
 static function processPriceSet($entityId, $lineItem, $contributionDetails = NULL, $entityTable = 'civicrm_contribution', $update = FALSE)
 {
     if (!$entityId || !is_array($lineItem) || CRM_Utils_system::isNull($lineItem)) {
         return;
     }
     foreach ($lineItem as $priceSetId => $values) {
         if (!$priceSetId) {
             continue;
         }
         foreach ($values as $line) {
             $line['entity_table'] = $entityTable;
             $line['entity_id'] = $entityId;
             // if financial type is not set and if price field value is NOT NULL
             // get financial type id of price field value
             if (CRM_Utils_Array::value('price_field_value_id', $line) && !CRM_Utils_Array::value('financial_type_id', $line)) {
                 $line['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $line['price_field_value_id'], 'financial_type_id');
             }
             $lineItems = CRM_Price_BAO_LineItem::create($line);
             if (!$update && $contributionDetails) {
                 CRM_Financial_BAO_FinancialItem::add($lineItems, $contributionDetails);
             }
         }
     }
 }
Exemple #5
0
 /** 
  * Function to process the form 
  * 
  * @access public 
  */
 public function postProcess()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         require_once "CRM/Event/BAO/Participant.php";
         CRM_Event_BAO_Participant::deleteParticipant($this->_participantId);
         return;
     }
     // get the submitted form values.
     $params = $this->controller->exportValues($this->_name);
     // set the contact, when contact is selected
     if (CRM_Utils_Array::value('contact_select_id', $params)) {
         $this->_contactID = CRM_Utils_Array::value('contact_select_id', $params);
     }
     $config =& CRM_Core_Config::singleton();
     //check if discount is selected
     if (CRM_Utils_Array::value('discount_id', $params)) {
         $discountId = $params['discount_id'];
     } else {
         $params['discount_id'] = 'null';
         $discountId = null;
     }
     if ($this->_isPaidEvent) {
         //lets carry currency, CRM-4453
         $params['fee_currency'] = $config->defaultCurrency;
         // fix for CRM-3088
         if ($discountId && !empty($this->_values['discount'][$discountId])) {
             $params['amount_level'] = $this->_values['discount'][$discountId][$params['amount']]['label'];
             $params['amount'] = $this->_values['discount'][$discountId][$params['amount']]['value'];
             $this->assign('amount_level', $params['amount_level']);
         } else {
             if (!isset($params['priceSetId'])) {
                 $params['amount_level'] = $this->_values['fee'][$params['amount']]['label'];
                 $params['amount'] = $this->_values['fee'][$params['amount']]['value'];
                 $this->assign('amount_level', $params['amount_level']);
             } else {
                 if (!$this->_online) {
                     $lineItem = array();
                     CRM_Price_BAO_Set::processAmount($this->_values['fee']['fields'], $params, $lineItem[0]);
                     $this->set('lineItem', $lineItem);
                     $this->assign('lineItem', $lineItem);
                     $this->_lineItem = $lineItem;
                 }
             }
         }
         $params['fee_level'] = $params['amount_level'];
         $contributionParams = array();
         $contributionParams['total_amount'] = $params['amount'];
     }
     //fix for CRM-3086
     $params['fee_amount'] = $params['amount'];
     $this->_params = $params;
     unset($params['amount']);
     $params['register_date'] = CRM_Utils_Date::processDate($params['register_date'], $params['register_date_time']);
     $params['receive_date'] = CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $params));
     $params['contact_id'] = $this->_contactID;
     if ($this->_participantId) {
         $params['id'] = $this->_participantId;
     }
     $status = null;
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $participantBAO =& new CRM_Event_BAO_Participant();
         $participantBAO->id = $this->_participantId;
         $participantBAO->find();
         while ($participantBAO->fetch()) {
             $status = $participantBAO->status_id;
             $contributionParams['total_amount'] = $participantBAO->fee_amount;
         }
         $params['discount_id'] = null;
         //re-enter the values for UPDATE mode
         $params['fee_level'] = $params['amount_level'] = $participantBAO->fee_level;
         $params['fee_amount'] = $participantBAO->fee_amount;
     }
     require_once 'CRM/Contact/BAO/Contact.php';
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     $session =& CRM_Core_Session::singleton();
     $userID = $session->get('userID');
     list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
     require_once "CRM/Event/BAO/Participant.php";
     if ($this->_mode) {
         if (!$this->_isPaidEvent) {
             CRM_Core_Error::fatal(ts('Selected Event is not Paid Event '));
         }
         //modify params according to parameter used in create
         //participant method (addParticipant)
         $params['participant_status_id'] = $params['status_id'];
         $params['participant_role_id'] = $params['role_id'];
         $params['participant_register_date'] = $params['register_date'];
         $params['participant_source'] = $params['source'];
         require_once 'CRM/Core/BAO/PaymentProcessor.php';
         $this->_paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode);
         require_once "CRM/Contact/BAO/Contact.php";
         $now = date('YmdHis');
         $fields = array();
         // set email for primary location.
         $fields["email-Primary"] = 1;
         $params["email-Primary"] = $params["email-{$this->_bltID}"] = $this->_contributorEmail;
         $params['register_date'] = $now;
         // now set the values for the billing location.
         foreach ($this->_fields as $name => $dontCare) {
             $fields[$name] = 1;
         }
         // also add location name to the array
         $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
         $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
         $fields["address_name-{$this->_bltID}"] = 1;
         $fields["email-{$this->_bltID}"] = 1;
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type');
         $nameFields = array('first_name', 'middle_name', 'last_name');
         foreach ($nameFields as $name) {
             $fields[$name] = 1;
             if (array_key_exists("billing_{$name}", $params)) {
                 $params[$name] = $params["billing_{$name}"];
                 $params['preserveDBName'] = true;
             }
         }
         $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactID, null, null, $ctype);
     }
     // build custom data getFields array
     $customFieldsRole = CRM_Core_BAO_CustomField::getFields('Participant', false, false, CRM_Utils_Array::value('role_id', $params), $this->_roleCustomDataTypeID);
     $customFieldsEvent = CRM_Core_BAO_CustomField::getFields('Participant', false, false, CRM_Utils_Array::value('event_id', $params), $this->_eventNameCustomDataTypeID);
     $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole, CRM_Core_BAO_CustomField::getFields('Participant', false, false, null, null, true));
     $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields);
     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_participantId, 'Participant');
     if ($this->_mode) {
         // add all the additioanl payment params we need
         $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         $this->_params['year'] = $this->_params['credit_card_exp_date']['Y'];
         $this->_params['month'] = $this->_params['credit_card_exp_date']['M'];
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $params['fee_amount'];
         $this->_params['amount_level'] = $params['amount_level'];
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['payment_action'] = 'Sale';
         $this->_params['invoiceID'] = md5(uniqid(rand(), true));
         // at this point we've created a contact and stored its address etc
         // all the payment processors expect the name and address to be in the
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         require_once 'CRM/Core/Payment/Form.php';
         CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, true);
         $payment =& CRM_Core_Payment::singleton($this->_mode, 'Event', $this->_paymentProcessor, $this);
         $result =& $payment->doDirectPayment($paymentParams);
         if (is_a($result, 'CRM_Core_Error')) {
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&cid={$this->_contactID}&context=participant&mode={$this->_mode}"));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
         }
         $this->_params['receive_date'] = $now;
         if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $this->_params['receipt_date'] = $now;
         } else {
             $this->_params['receipt_date'] = null;
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', $result['trxn_id']);
         $this->assign('receive_date', CRM_Utils_Date::processDate($this->_params['receive_date']));
         // set source if not set
         $this->_params['description'] = ts('Submit Credit Card for Event Registration by: %1', array(1 => $userName));
         require_once 'CRM/Event/Form/Registration/Confirm.php';
         require_once 'CRM/Event/Form/Registration.php';
         //add contribution record
         $this->_params['contribution_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'contribution_type_id');
         $this->_params['mode'] = $this->_mode;
         //add contribution reocord
         $contribution = CRM_Event_Form_Registration_Confirm::processContribution($this, $this->_params, $result, $contactID, false);
         // add participant record
         $participants = array();
         $participants[] = CRM_Event_Form_Registration::addParticipant($this->_params, $contactID);
         //add custom data for participant
         require_once 'CRM/Core/BAO/CustomValueTable.php';
         CRM_Core_BAO_CustomValueTable::postProcess($this->_params, CRM_Core_DAO::$_nullArray, 'civicrm_participant', $participants[0]->id, 'Participant');
         //add participant payment
         require_once 'CRM/Event/BAO/ParticipantPayment.php';
         $paymentParticipant = array('participant_id' => $participants[0]->id, 'contribution_id' => $contribution->id);
         $ids = array();
         CRM_Event_BAO_ParticipantPayment::create($paymentParticipant, $ids);
         $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         $this->_contactIds[] = $this->_contactID;
     } else {
         $participants = array();
         // fix note if deleted
         if (!$params['note']) {
             $params['note'] = 'null';
         }
         if ($this->_single) {
             $participants[] = CRM_Event_BAO_Participant::create($params);
         } else {
             foreach ($this->_contactIds as $contactID) {
                 $commonParams = $params;
                 $commonParams['contact_id'] = $contactID;
                 $participants[] = CRM_Event_BAO_Participant::create($commonParams);
             }
         }
         if (isset($params['event_id'])) {
             $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         }
         if ($this->_single) {
             $this->_contactIds[] = $this->_contactID;
         }
         if (CRM_Utils_Array::value('record_contribution', $params)) {
             if (CRM_Utils_Array::value('id', $params)) {
                 if ($this->_onlinePendingContributionId) {
                     $ids['contribution'] = $this->_onlinePendingContributionId;
                 } else {
                     $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $params['id'], 'contribution_id', 'participant_id');
                 }
             }
             unset($params['note']);
             //build contribution params
             if (!$this->_onlinePendingContributionId) {
                 $contributionParams['source'] = "{$eventTitle}: Offline registration (by {$userName})";
             }
             $contributionParams['currency'] = $config->defaultCurrency;
             $contributionParams['non_deductible_amount'] = 'null';
             $contributionParams['receipt_date'] = CRM_Utils_Array::value('send_receipt', $params) ? CRM_Utils_Array::value('receive_date', $params) : 'null';
             $recordContribution = array('contact_id', 'contribution_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'receive_date', 'check_number');
             foreach ($recordContribution as $f) {
                 $contributionParams[$f] = CRM_Utils_Array::value($f, $params);
                 if ($f == 'trxn_id') {
                     $this->assign('trxn_id', $contributionParams[$f]);
                 }
             }
             //insert contribution type name in receipt.
             $this->assign('contributionTypeName', CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionType', $contributionParams['contribution_type_id']));
             require_once 'CRM/Contribute/BAO/Contribution.php';
             $contributions = array();
             if ($this->_single) {
                 $contributions[] =& CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
             } else {
                 $ids = array();
                 foreach ($this->_contactIds as $contactID) {
                     $contributionParams['contact_id'] = $contactID;
                     $contributions[] =& CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
                 }
             }
             //insert payment record for this participation
             if (!$ids['contribution']) {
                 require_once 'CRM/Event/DAO/ParticipantPayment.php';
                 foreach ($this->_contactIds as $num => $contactID) {
                     $ppDAO =& new CRM_Event_DAO_ParticipantPayment();
                     $ppDAO->participant_id = $participants[$num]->id;
                     $ppDAO->contribution_id = $contributions[$num]->id;
                     $ppDAO->save();
                 }
             }
         }
     }
     // also store lineitem stuff here
     if ($this->_lineItem) {
         require_once 'CRM/Price/BAO/LineItem.php';
         foreach ($this->_contactIds as $num => $contactID) {
             foreach ($this->_lineItem as $key => $value) {
                 if (is_array($value) && $value != 'skip') {
                     foreach ($value as $line) {
                         $line['entity_table'] = 'civicrm_participant';
                         $line['entity_id'] = $participants[$num]->id;
                         CRM_Price_BAO_LineItem::create($line);
                     }
                 }
             }
         }
     }
     $updateStatusMsg = null;
     //send mail when participant status changed, CRM-4326
     if ($this->_participantId && $this->_statusId && $this->_statusId != CRM_Utils_Array::value('status_id', $params) && CRM_Utils_Array::value('is_notify', $params)) {
         require_once "CRM/Event/BAO/Participant.php";
         $updateStatusMsg = CRM_Event_BAO_Participant::updateStatusMessage($this->_participantId, $params['status_id'], $this->_statusId);
     }
     if (CRM_Utils_Array::value('send_receipt', $params)) {
         $receiptFrom = "{$userName} <{$userEmail}>";
         $this->assign('module', 'Event Registration');
         //use of the message template below requires variables in different format
         $event = $events = array();
         $returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title');
         //get all event details.
         CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $params['event_id'], $events, $returnProperties);
         $event = $events[$params['event_id']];
         unset($event['start_date']);
         unset($event['end_date']);
         $role = CRM_Event_PseudoConstant::participantRole();
         $event['participant_role'] = $role[$params['role_id']];
         $event['is_monetary'] = $this->_isPaidEvent;
         if ($params['receipt_text']) {
             $event['confirm_email_text'] = $params['receipt_text'];
         }
         $this->assign('isAmountzero', 1);
         $this->assign('event', $event);
         $this->assign('isShowLocation', $event['is_show_location']);
         if (CRM_Utils_Array::value('is_show_location', $event) == 1) {
             $locationParams = array('entity_id' => $params['event_id'], 'entity_table' => 'civicrm_event');
             require_once 'CRM/Core/BAO/Location.php';
             $location = CRM_Core_BAO_Location::getValues($locationParams, true);
             $this->assign('location', $location);
         }
         $status = CRM_Event_PseudoConstant::participantStatus();
         if ($this->_isPaidEvent) {
             $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
             if (!$this->_mode) {
                 $this->assign('paidBy', CRM_Utils_Array::value($params['payment_instrument_id'], $paymentInstrument));
             }
             $this->assign('totalAmount', $contributionParams['total_amount']);
             $this->assign('isPrimary', 1);
             $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
         }
         if ($this->_mode) {
             if (CRM_Utils_Array::value('billing_first_name', $params)) {
                 $name = $params['billing_first_name'];
             }
             if (CRM_Utils_Array::value('billing_middle_name', $params)) {
                 $name .= " {$params['billing_middle_name']}";
             }
             if (CRM_Utils_Array::value('billing_last_name', $params)) {
                 $name .= " {$params['billing_last_name']}";
             }
             $this->assign('billingName', $name);
             // assign the address formatted up for display
             $addressParts = array("street_address-{$this->_bltID}", "city-{$this->_bltID}", "postal_code-{$this->_bltID}", "state_province-{$this->_bltID}", "country-{$this->_bltID}");
             $addressFields = array();
             foreach ($addressParts as $part) {
                 list($n, $id) = explode('-', $part);
                 if (isset($this->_params['billing_' . $part])) {
                     $addressFields[$n] = $this->_params['billing_' . $part];
                 }
             }
             require_once 'CRM/Utils/Address.php';
             $this->assign('address', CRM_Utils_Address::format($addressFields));
             $date = CRM_Utils_Date::format($params['credit_card_exp_date']);
             $date = CRM_Utils_Date::mysqlToIso($date);
             $this->assign('credit_card_exp_date', $date);
             $this->assign('credit_card_number', CRM_Utils_System::mungeCreditCard($params['credit_card_number']));
             $this->assign('credit_card_type', $params['credit_card_type']);
             $this->assign('contributeMode', 'direct');
             $this->assign('isAmountzero', 0);
             $this->assign('is_pay_later', 0);
             $this->assign('isPrimary', 1);
         }
         $this->assign('register_date', $params['register_date']);
         if ($params['receive_date']) {
             $this->assign('receive_date', $params['receive_date']);
         }
         $participant = array(array('participant_id', '=', $participants[0]->id, 0, 0));
         // check whether its a test drive ref CRM-3075
         if (CRM_Utils_Array::value('is_test', $this->_defaultValues)) {
             $participant[] = array('participant_test', '=', 1, 0, 0);
         }
         $template =& CRM_Core_Smarty::singleton();
         $customGroup = array();
         //format submitted data
         foreach ($params['custom'] as $fieldID => $values) {
             foreach ($values as $fieldValue) {
                 $customValue = array('data' => $fieldValue['value']);
                 $customFields[$fieldID]['id'] = $fieldID;
                 $formattedValue = CRM_Core_BAO_CustomGroup::formatCustomValues($customValue, $customFields[$fieldID]);
                 $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace('&nbsp;', '', $formattedValue);
             }
         }
         foreach ($this->_contactIds as $num => $contactID) {
             // Retrieve the name and email of the contact - this will be the TO for receipt email
             list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID);
             $this->_contributorDisplayName = $this->_contributorDisplayName == ' ' ? $this->_contributorEmail : $this->_contributorDisplayName;
             $this->assign('customGroup', $customGroup);
             $this->assign('contactID', $contactID);
             $this->assign('participantID', $participants[$num]->id);
             if ($this->_isPaidEvent) {
                 // fix amount for each of participants ( for bulk mode )
                 $eventAmount = array();
                 $eventAmount[$num] = array('label' => $params['amount_level'], 'amount' => $params['fee_amount']);
                 //as we are using same template for online & offline registration.
                 //So we have to build amount as array.
                 $this->assign('amount', $eventAmount);
             }
             $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_event', 'valueName' => 'event_offline_receipt', 'contactId' => $contactID, 'isTest' => (bool) CRM_Utils_Array::value('is_test', $this->_defaultValues));
             // try to send emails only if email id is present
             // and the do-not-email option is not checked for that contact
             if ($this->_contributorEmail and !$this->_toDoNotEmail) {
                 $sendTemplateParams['from'] = $receiptFrom;
                 $sendTemplateParams['toName'] = $this->_contributorDisplayName;
                 $sendTemplateParams['toEmail'] = $this->_contributorEmail;
             }
             require_once 'CRM/Core/BAO/MessageTemplates.php';
             list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplates::sendTemplate($sendTemplateParams);
             if ($mailSent) {
                 $sent[] = $contactID;
             } else {
                 $notSent[] = $contactID;
             }
         }
     }
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contributorDisplayName));
         if ($params['send_receipt'] && count($sent)) {
             $statusMsg .= ' ' . ts('A confirmation email has been sent to %1', array(1 => $this->_contributorEmail));
         }
         if ($updateStatusMsg) {
             $statusMsg = "{$statusMsg} {$updateStatusMsg}";
         }
     } elseif ($this->_action & CRM_Core_Action::ADD) {
         if ($this->_single) {
             $statusMsg = ts('Event registration for %1 has been added.', array(1 => $this->_contributorDisplayName));
             if (CRM_Utils_Array::value('send_receipt', $params) && count($sent)) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', array(1 => $this->_contributorEmail));
             }
         } else {
             $statusMsg = ts('Total Participant(s) added to event: %1.', array(1 => count($this->_contactIds)));
             if (count($notSent) > 0) {
                 $statusMsg .= ' ' . ts('Email has NOT been sent to %1 contact - communication preferences specify DO NOT EMAIL OR valid Email is NOT present. ', array(1 => count($notSent)));
             } elseif (isset($params['send_receipt'])) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to ALL participants');
             }
         }
     }
     require_once "CRM/Core/Session.php";
     CRM_Core_Session::setStatus("{$statusMsg}");
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/participant/add', 'reset=1&action=add&context=standalone'));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=participant"));
         }
     } else {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&context=participant&cid={$this->_contactID}"));
         }
     }
 }
Exemple #6
0
 /**
  * Function to process the form
  *
  * @access public
  * @return None
  */
 public function postProcess()
 {
     require_once 'CRM/Event/BAO/Participant.php';
     $config =& CRM_Core_Config::singleton();
     $session =& CRM_Core_Session::singleton();
     $contactID = $session->get('userID');
     $now = date('YmdHis');
     $this->_params = $this->get('params');
     // if a discount has been applied, lets now deduct it from the amount
     // and fix the fee level
     if (CRM_Utils_Array::value('discount', $this->_params[0]) && CRM_Utils_Array::value('applied', $this->_params[0]['discount'])) {
         foreach ($this->_params as $k => $v) {
             if (CRM_Utils_Array::value('amount', $this->_params[$k]) > 0 && CRM_Utils_Array::value('discountAmount', $this->_params[$k])) {
                 $this->_params[$k]['amount'] -= $this->_params[$k]['discountAmount'];
                 $this->_params[$k]['amount_level'] .= CRM_Utils_Array::value('discountMessage', $this->_params[$k]);
             }
         }
         $this->set('params', $this->_params);
     }
     // CRM-4320, lets build array of cancelled additional participant ids
     // those are drop or skip by primary at the time of confirmation.
     // get all in and then unset those we want to process.
     $cancelledIds = $this->_additionalParticipantIds;
     $params = $this->_params;
     $this->set('finalAmount', $this->_amount);
     $participantCount = array();
     //unset the skip participant from params.
     //build the $participantCount array.
     //maintain record for all participants.
     foreach ($params as $participantNum => $record) {
         if ($record == 'skip') {
             unset($params[$participantNum]);
             $participantCount[$participantNum] = 'skip';
         } else {
             if ($participantNum) {
                 $participantCount[$participantNum] = 'participant';
             }
         }
         //lets get additional participant id to cancel.
         if ($this->_allowConfirmation && is_array($cancelledIds)) {
             $additonalId = CRM_Utils_Array::value('participant_id', $record);
             if ($additonalId && ($key = array_search($additonalId, $cancelledIds))) {
                 unset($cancelledIds[$key]);
             }
         }
     }
     $payment = $registerByID = $primaryCurrencyID = $contribution = null;
     foreach ($params as $key => $value) {
         $this->_values['params'] = array();
         $this->fixLocationFields($value, $fields);
         //unset the billing parameters if it is pay later mode
         //to avoid creation of billing location
         if ($this->_allowWaitlist || $this->_requireApproval || CRM_Utils_Array::value('is_pay_later', $value) || !CRM_Utils_Array::value('is_primary', $value)) {
             $billingFields = array("email-{$this->_bltID}", "billing_first_name", "billing_middle_name", "billing_last_name", "billing_street_address-{$this->_bltID}", "billing_city-{$this->_bltID}", "billing_state_province-{$this->_bltID}", "billing_state_province_id-{$this->_bltID}", "billing_postal_code-{$this->_bltID}", "billing_country-{$this->_bltID}", "billing_country_id-{$this->_bltID}", "address_name-{$this->_bltID}");
             foreach ($billingFields as $field) {
                 unset($value[$field]);
             }
             if (CRM_Utils_Array::value('is_pay_later', $value)) {
                 $this->_values['params']['is_pay_later'] = true;
             }
         }
         //Unset ContactID for additional participants and set RegisterBy Id.
         if (!CRM_Utils_Array::value('is_primary', $value)) {
             $contactID = CRM_Utils_Array::value('contact_id', $value);
             $registerByID = $this->get('registerByID');
             if ($registerByID) {
                 $value['registered_by_id'] = $registerByID;
             }
         } else {
             $value['amount'] = $this->_totalAmount;
         }
         $contactID =& $this->updateContactFields($contactID, $value, $fields);
         // lets store the contactID in the session
         // we dont store in userID in case the user is doing multiple
         // transactions etc
         // for things like tell a friend
         if (!$session->get('userID') && CRM_Utils_Array::value('is_primary', $value)) {
             $session->set('transaction.userID', $contactID);
         }
         $value['description'] = ts('Online Event Registration') . ': ' . $this->_values['event']['title'];
         $value['accountingCode'] = CRM_Utils_Array::value('accountingCode', $this->_values['event']);
         // required only if paid event
         if ($this->_values['event']['is_monetary']) {
             require_once 'CRM/Core/Payment.php';
             if (is_array($this->_paymentProcessor)) {
                 $payment =& CRM_Core_Payment::singleton($this->_mode, 'Event', $this->_paymentProcessor, $this);
             }
             $pending = false;
             $result = null;
             require_once 'CRM/Event/PseudoConstant.php';
             if ($this->_allowWaitlist || $this->_requireApproval) {
                 //get the participant statuses.
                 $waitingStatuses = CRM_Event_PseudoConstant::participantStatus(null, "class = 'Waiting'");
                 if ($this->_allowWaitlist) {
                     $value['participant_status_id'] = array_search('On waitlist', $waitingStatuses);
                 } else {
                     $value['participant_status_id'] = array_search('Awaiting approval', $waitingStatuses);
                 }
                 //there might be case user seleted pay later and
                 //now becomes part of run time waiting list.
                 $value['is_pay_later'] = false;
             } else {
                 if (CRM_Utils_Array::value('is_pay_later', $value) || $value['amount'] == 0 || $this->_contributeMode == 'checkout' || $this->_contributeMode == 'notify') {
                     if ($value['amount'] != 0) {
                         $pending = true;
                         //get the participant statuses.
                         require_once 'CRM/Event/PseudoConstant.php';
                         $pendingStatuses = CRM_Event_PseudoConstant::participantStatus(null, "class = 'Pending'");
                         $status = CRM_Utils_Array::value('is_pay_later', $value) ? 'Pending from pay later' : 'Pending from incomplete transaction';
                         $value['participant_status_id'] = array_search($status, $pendingStatuses);
                     }
                 } else {
                     if ($this->_contributeMode == 'express' && CRM_Utils_Array::value('is_primary', $value)) {
                         $result =& $payment->doExpressCheckout($value);
                     } else {
                         if (CRM_Utils_Array::value('is_primary', $value)) {
                             require_once 'CRM/Core/Payment/Form.php';
                             CRM_Core_Payment_Form::mapParams($this->_bltID, $value, $value, true);
                             $result =& $payment->doDirectPayment($value);
                         }
                     }
                 }
             }
             if (is_a($result, 'CRM_Core_Error')) {
                 CRM_Core_Error::displaySessionError($result);
                 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/event/register', "id={$this->_eventId}"));
             }
             if ($result) {
                 $value = array_merge($value, $result);
             }
             $value['receive_date'] = $now;
             if ($this->_allowConfirmation) {
                 $value['participant_register_date'] = $this->_values['participant']['register_date'];
             }
             $createContrib = $value['amount'] != 0 ? true : false;
             // force to create zero amount contribution, CRM-5095
             if (!$createContrib && $value['amount'] == 0 && $this->_priceSetId && $this->_lineItem) {
                 $createContrib = true;
             }
             if ($createContrib && CRM_Utils_Array::value('is_primary', $value) && !$this->_allowWaitlist && !$this->_requireApproval) {
                 // if paid event add a contribution record
                 //if primary participant contributing additional amount
                 //append (multiple participants) to its fee level. CRM-4196.
                 $isAdditionalAmount = false;
                 if (count($params) > 1) {
                     $isAdditionalAmount = true;
                 }
                 //passing contribution id is already registered.
                 $contribution =& self::processContribution($this, $value, $result, $contactID, $pending, $isAdditionalAmount);
                 $value['contributionID'] = $contribution->id;
                 $value['contributionTypeID'] = $contribution->contribution_type_id;
                 $value['receive_date'] = $contribution->receive_date;
                 $value['trxn_id'] = $contribution->trxn_id;
                 $value['contributionID'] = $contribution->id;
                 $value['contributionTypeID'] = $contribution->contribution_type_id;
             }
             $value['contactID'] = $contactID;
             $value['eventID'] = $this->_eventId;
             $value['item_name'] = $value['description'];
         }
         //CRM-4453.
         if (CRM_Utils_Array::value('is_primary', $value)) {
             $primaryCurrencyID = CRM_Utils_Array::value('currencyID', $value);
         }
         if (!CRM_Utils_Array::value('currencyID', $value)) {
             $value['currencyID'] = $primaryCurrencyID;
         }
         if (!$pending && CRM_Utils_Array::value('is_primary', $value) && !$this->_allowWaitlist && !$this->_requireApproval) {
             // transactionID & receive date required while building email template
             $this->assign('trxn_id', $value['trxn_id']);
             $this->assign('receive_date', CRM_Utils_Date::mysqlToIso($value['receive_date']));
             $this->set('receiveDate', CRM_Utils_Date::mysqlToIso($value['receive_date']));
             $this->set('trxnId', CRM_Utils_Array::value('trxn_id', $value));
         }
         $value['fee_amount'] = $value['amount'];
         $this->set('value', $value);
         // handle register date CRM-4320
         if ($this->_allowConfirmation) {
             $registerDate = $params['participant_register_date'];
         } else {
             if (is_array($params['participant_register_date']) && !empty($params['participant_register_date'])) {
                 $registerDate = CRM_Utils_Date::format($params['participant_register_date']);
             } else {
                 $registerDate = date('YmdHis');
             }
         }
         $this->assign('register_date', $registerDate);
         $this->confirmPostProcess($contactID, $contribution, $payment);
     }
     //handle if no additional participant.
     if (!$registerByID) {
         $registerByID = $this->get('registerByID');
     }
     // create line items, CRM-5313
     if ($this->_priceSetId && !empty($this->_lineItem)) {
         require_once 'CRM/Price/BAO/LineItem.php';
         // take all processed participant ids.
         $allParticipantIds = $this->_participantIDS;
         // when participant re-walk wizard.
         if ($this->_allowConfirmation && !empty($this->_additionalParticipantIds)) {
             $allParticipantIds = array_merge(array($registerByID), $this->_additionalParticipantIds);
         }
         $entityTable = 'civicrm_participant';
         foreach ($this->_lineItem as $key => $value) {
             if ($value != 'skip' && ($entityId = CRM_Utils_Array::value($key, $allParticipantIds))) {
                 // do cleanup line  items if participant re-walking wizard.
                 if ($this->_allowConfirmation) {
                     CRM_Price_BAO_LineItem::deleteLineItems($entityId, $entityTable);
                 }
                 // create line.
                 foreach ($value as $line) {
                     $line['entity_id'] = $entityId;
                     $line['entity_table'] = $entityTable;
                     CRM_Price_BAO_LineItem::create($line);
                 }
             }
         }
     }
     //update status and send mail to cancelled additonal participants, CRM-4320
     if ($this->_allowConfirmation && is_array($cancelledIds) && !empty($cancelledIds)) {
         require_once 'CRM/Event/BAO/Participant.php';
         require_once 'CRM/Event/PseudoConstant.php';
         $cancelledId = array_search('Cancelled', CRM_Event_PseudoConstant::participantStatus(null, "class = 'Negative'"));
         CRM_Event_BAO_Participant::transitionParticipants($cancelledIds, $cancelledId);
     }
     $isTest = false;
     if ($this->_action & CRM_Core_Action::PREVIEW) {
         $isTest = true;
     }
     // for Transfer checkout.
     require_once "CRM/Event/BAO/Event.php";
     if (($this->_contributeMode == 'checkout' || $this->_contributeMode == 'notify') && !CRM_Utils_Array::value('is_pay_later', $params[0]) && !$this->_allowWaitlist && !$this->_requireApproval && $this->_totalAmount > 0) {
         $primaryParticipant = $this->get('primaryParticipant');
         if (!CRM_Utils_Array::value('participantID', $primaryParticipant)) {
             $primaryParticipant['participantID'] = $registerByID;
         }
         //build an array of custom profile and assigning it to template
         $customProfile = CRM_Event_BAO_Event::buildCustomProfile($registerByID, $this->_values, null, $isTest);
         if (count($customProfile)) {
             $this->assign('customProfile', $customProfile);
             $this->set('customProfile', $customProfile);
         }
         // do a transfer only if a monetary payment greater than 0
         if ($this->_values['event']['is_monetary'] && $primaryParticipant && $payment) {
             $payment->doTransferCheckout($primaryParticipant);
         }
     } else {
         //otherwise send mail Confirmation/Receipt
         $primaryContactId = $this->get('primaryContactId');
         //build an array of cId/pId of participants
         require_once "CRM/Event/BAO/Event.php";
         $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($registerByID, null, $primaryContactId, $isTest, true);
         //lets send  mails to all with meaningful text, CRM-4320.
         $this->assign('isOnWaitlist', $this->_allowWaitlist);
         $this->assign('isRequireApproval', $this->_requireApproval);
         foreach ($additionalIDs as $participantID => $contactId) {
             if ($participantID == $registerByID) {
                 //set as Primary Participant
                 $this->assign('isPrimary', 1);
                 //build an array of custom profile and assigning it to template.
                 $customProfile = CRM_Event_BAO_Event::buildCustomProfile($participantID, $this->_values, null, $isTest);
                 if (count($customProfile)) {
                     $this->assign('customProfile', $customProfile);
                     $this->set('customProfile', $customProfile);
                 }
                 $this->_values['params']['additionalParticipant'] = false;
             } else {
                 //take the Additional participant number.
                 if ($paticipantNum = array_search('participant', $participantCount)) {
                     unset($participantCount[$paticipantNum]);
                 }
                 $this->assign('isPrimary', 0);
                 $this->assign('customProfile', null);
                 //Additional Participant should get only it's payment information
                 if ($this->_amount) {
                     $amount = array();
                     $params = $this->get('params');
                     $amount[$paticipantNum]['label'] = $params[$paticipantNum]['amount_level'];
                     $amount[$paticipantNum]['amount'] = $params[$paticipantNum]['amount'];
                     $this->assign('amount', $amount);
                 }
                 if ($this->_lineItem) {
                     $lineItems = $this->_lineItem;
                     $lineItem = array();
                     $lineItem[] = CRM_Utils_Array::value($paticipantNum, $lineItems);
                     $this->assign('lineItem', $lineItem);
                 }
                 $this->_values['params']['additionalParticipant'] = true;
             }
             //pass these variables since these are run time calculated.
             $this->_values['params']['isOnWaitlist'] = $this->_allowWaitlist;
             $this->_values['params']['isRequireApproval'] = $this->_requireApproval;
             //send mail to primary as well as additional participants.
             $this->assign('contactID', $contactId);
             $this->assign('participantID', $participantID);
             CRM_Event_BAO_Event::sendMail($contactId, $this->_values, $participantID, $isTest);
         }
     }
 }
 /**
  * check method create()
  */
 function testCreate()
 {
     $firstName = 'Shane';
     $lastName = 'Whatson';
     $params = array('first_name' => $firstName, 'last_name' => $lastName, 'contact_type' => 'Individual');
     $contact = CRM_Contact_BAO_Contact::add($params);
     $price = 100.0;
     $cParams = array('contact_id' => $contact->id, 'total_amount' => $price, 'financial_type_id' => 1, 'is_active' => 1, 'skipLineItem' => 1);
     $defaults = array();
     $contribution = CRM_Contribute_BAO_Contribution::add($cParams, $defaults);
     $lParams = array('entity_id' => $contribution->id, 'entity_table' => 'civicrm_contribution', 'price_field_id' => 1, 'qty' => 1, 'label' => 'Contribution Amount', 'unit_price' => $price, 'line_total' => $price, 'price_field_value_id' => 1, 'financial_type_id' => 1);
     $lineItem = CRM_Price_BAO_LineItem::create($lParams);
     $fParams = array('contact_id' => $contact->id, 'description' => 'Contribution Amount', 'amount' => $price, 'financial_account_id' => 1, 'status_id' => 1, 'transaction_date' => date('YmdHis'), 'entity_id' => $lineItem->id, 'entity_table' => 'civicrm_line_item');
     CRM_Financial_BAO_FinancialItem::create($fParams);
     $entityTrxn = new CRM_Financial_DAO_EntityFinancialTrxn();
     $entityTrxn->entity_table = 'civicrm_contribution';
     $entityTrxn->entity_id = $contribution->id;
     $entityTrxn->amount = $price;
     if ($entityTrxn->find(TRUE)) {
         $entityId = $entityTrxn->entity_id;
     }
     $result = $this->assertDBNotNull('CRM_Financial_DAO_FinancialItem', $lineItem->id, 'amount', 'entity_id', 'Database check on added financial item record.');
     $this->assertEquals($result, $price, 'Verify Amount for Financial Item');
     $entityResult = $this->assertDBNotNull('CRM_Financial_DAO_EntityFinancialTrxn', $entityId, 'amount', 'entity_id', 'Database check on added entity financial trxn record.');
     $this->assertEquals($entityResult, $price, 'Verify Amount for Financial Item');
 }
 /** 
  * Function to process price set and line items. 
  * 
  * @access public 
  * @return None 
  */
 function processPriceSet($contributionId, $lineItem)
 {
     if (!$contributionId || !is_array($lineItem) || CRM_Utils_system::isNull($lineItem)) {
         return;
     }
     require_once 'CRM/Price/BAO/Set.php';
     require_once 'CRM/Price/BAO/LineItem.php';
     foreach ($lineItem as $priceSetId => $values) {
         if (!$priceSetId) {
             continue;
         }
         foreach ($values as $line) {
             $line['entity_table'] = 'civicrm_contribution';
             $line['entity_id'] = $contributionId;
             CRM_Price_BAO_LineItem::create($line);
         }
         CRM_Price_BAO_Set::addTo('civicrm_contribution', $contributionId, $priceSetId);
     }
 }
 /**
  * @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');
 }
 /**
  * Process transfer - first add the new participant to the event, then cancel
  * source participant - send confirmation email to transferee
  */
 public function postProcess()
 {
     //For transfer, process form to allow selection of transferree
     $params = $this->controller->exportValues($this->_name);
     //cancel 'from' participant row
     $query = "select contact_id from civicrm_email where email = '" . $params['email'] . "'";
     $dao = CRM_Core_DAO::executeQuery($query);
     while ($dao->fetch()) {
         $contact_id = $dao->contact_id;
     }
     $from_participant = $params = array();
     $query = "select role_id, source, fee_level, is_test, is_pay_later, fee_amount, discount_id, fee_currency,campaign_id, discount_amount from civicrm_participant where id = " . $this->_from_participant_id;
     $dao = CRM_Core_DAO::executeQuery($query);
     $value_to = array();
     while ($dao->fetch()) {
         $value_to['role_id'] = $dao->role_id;
         $value_to['source'] = $dao->source;
         $value_to['fee_level'] = $dao->fee_level;
         $value_to['is_test'] = $dao->is_test;
         $value_to['is_pay_later'] = $dao->is_pay_later;
         $value_to['fee_amount'] = $dao->fee_amount;
     }
     $value_to['contact_id'] = $contact_id;
     $value_to['event_id'] = $this->_event_id;
     $value_to['status_id'] = 1;
     $value_to['register_date'] = date("Y-m-d");
     //first create the new participant row -don't set registered_by yet or email won't be sent
     $participant = CRM_Event_BAO_Participant::create($value_to);
     //send a confirmation email to the new participant
     $this->participantTransfer($participant);
     //now update registered_by_id
     $query = "UPDATE civicrm_participant cp SET cp.registered_by_id = %1 WHERE  cp.id = ({$participant->id})";
     $params = array(1 => array($this->_from_participant_id, 'Integer'));
     $dao = CRM_Core_DAO::executeQuery($query, $params);
     //copy line items to new participant
     $line_items = CRM_Price_BAO_LineItem::getLineItems($this->_from_participant_id);
     foreach ($line_items as $item) {
         $item['entity_id'] = $participant->id;
         $item['id'] = NULL;
         $item['entity_table'] = "civicrm_participant";
         $new_item = CRM_Price_BAO_LineItem::create($item);
     }
     //now cancel the from participant record, leaving the original line-item(s)
     $value_from = array();
     $value_from['id'] = $this->_from_participant_id;
     $tansferId = array_search('Transferred', CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'"));
     $value_from['status_id'] = $tansferId;
     $value_from['transferred_to_contact_id'] = $contact_id;
     $contact_details = CRM_Contact_BAO_Contact::getContactDetails($contact_id);
     $display_name = current($contact_details);
     $this->assign('to_participant', $display_name);
     CRM_Event_BAO_Participant::create($value_from);
     $this->sendCancellation();
     list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contact_id);
     $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $displayName));
     $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', array(1 => $email));
     CRM_Core_Session::setStatus($statusMsg, ts('Registration Transferred'), 'success');
     $url = CRM_Utils_System::url('civicrm/event/info', "reset=1&id={$this->_event_id}");
     CRM_Utils_System::redirect($url);
 }
 /**
  * Function to process price set and line items.
  *
  * @access public
  *
  * @return None
  */
 function processPriceSet($contributionId, $lineItem, $entityTable = 'civicrm_contribution')
 {
     if (!$contributionId || !is_array($lineItem) || CRM_Utils_system::isNull($lineItem)) {
         return;
     }
     foreach ($lineItem as $priceSetId => $values) {
         if (!$priceSetId) {
             continue;
         }
         foreach ($values as $line) {
             $line['entity_table'] = $entityTable;
             $line['entity_id'] = $contributionId;
             CRM_Price_BAO_LineItem::create($line);
         }
     }
 }
 /**
  * Update price option label in line_item, civicrm_contribution and civicrm_participant.
  *
  * @param int $id - id of the price_field_value
  * @param string $prevLabel
  * @param string $newLabel
  *
  */
 public static function updateAmountAndFeeLevel($id, $prevLabel, $newLabel)
 {
     // update price field label in line item.
     $lineItem = new CRM_Price_DAO_LineItem();
     $lineItem->price_field_value_id = $id;
     $lineItem->label = $prevLabel;
     $lineItem->find();
     while ($lineItem->fetch()) {
         $lineItemParams['id'] = $lineItem->id;
         $lineItemParams['label'] = $newLabel;
         CRM_Price_BAO_LineItem::create($lineItemParams);
         // update amount and fee level in civicrm_contribution and civicrm_participant
         $params = array(1 => array(CRM_Core_DAO::VALUE_SEPARATOR . $prevLabel . ' -', 'String'), 2 => array(CRM_Core_DAO::VALUE_SEPARATOR . $newLabel . ' -', 'String'));
         // Update contribution
         if (!empty($lineItem->contribution_id)) {
             CRM_Core_DAO::executeQuery("UPDATE `civicrm_contribution` SET `amount_level` = REPLACE(amount_level, %1, %2) WHERE id = {$lineItem->contribution_id}", $params);
         }
         // Update participant
         if ($lineItem->entity_table == 'civicrm_participant') {
             CRM_Core_DAO::executeQuery("UPDATE `civicrm_participant` SET `fee_level` = REPLACE(fee_level, %1, %2) WHERE id = {$lineItem->entity_id}", $params);
         }
     }
 }
 /**
  * (Queue Task Callback)
  *
  * Find any participant records and create corresponding line-item
  * records.
  *
  * @param $startId int, the first/lowest participant ID to convert
  * @param $endId int, the last/highest participant ID to convert
  */
 static function task_4_2_alpha1_convertParticipants(CRM_Queue_TaskContext $ctx, $startId, $endId)
 {
     $upgrade = new CRM_Upgrade_Form();
     //create lineitems for participant in edge cases using default price set for contribution.
     $query = "\nSELECT    cp.id as participant_id, cp.fee_amount, cp.fee_level,ce.is_monetary,\n          cpse.price_set_id, cpf.id as price_field_id, cpfv.id as price_field_value_id\nFROM      civicrm_participant cp\nLEFT JOIN civicrm_line_item cli ON cli.entity_id=cp.id and cli.entity_table = 'civicrm_participant'\nLEFT JOIN civicrm_event ce ON ce.id=cp.event_id\nLEFT JOIN civicrm_price_set_entity cpse ON cp.event_id = cpse.entity_id and cpse.entity_table = 'civicrm_event'\nLEFT JOIN civicrm_price_field cpf ON cpf.price_set_id = cpse.price_set_id\nLEFT JOIN civicrm_price_field_value cpfv ON cpfv.price_field_id = cpf.id AND cpfv.label = cp.fee_level\nWHERE     (cp.id BETWEEN %1 AND %2)\nAND       cli.entity_id IS NULL AND cp.fee_amount IS NOT NULL";
     $sqlParams = array(1 => array($startId, 'Integer'), 2 => array($endId, 'Integer'));
     $dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
     if ($dao->N) {
         $defaultPriceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Set', 'default_contribution_amount', 'id', 'name');
         $priceSets = current(CRM_Price_BAO_Set::getSetDetail($defaultPriceSetId));
         $fieldID = key($priceSets['fields']);
     }
     while ($dao->fetch()) {
         $lineParams = array('entity_table' => 'civicrm_participant', 'entity_id' => $dao->participant_id, 'label' => $dao->fee_level ? $dao->fee_level : ts('Default'), 'qty' => 1, 'unit_price' => $dao->fee_amount, 'line_total' => $dao->fee_amount, 'participant_count' => 1);
         if ($dao->is_monetary && $dao->price_field_id) {
             $lineParams += array('price_field_id' => $dao->price_field_id, 'price_field_value_id' => $dao->price_field_value_id);
             $priceSetId = $dao->price_set_id;
         } else {
             $lineParams['price_field_id'] = $fieldID;
             $priceSetId = $defaultPriceSetId;
         }
         CRM_Price_BAO_LineItem::create($lineParams);
     }
     return TRUE;
 }
 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');
 }