Revert "CRM-20321, CRM-20652 : Changing membership type should change related contrib...
authorcolemanw <coleman@civicrm.org>
Tue, 11 Jul 2017 16:33:04 +0000 (12:33 -0400)
committerGitHub <noreply@github.com>
Tue, 11 Jul 2017 16:33:04 +0000 (12:33 -0400)
12 files changed:
CRM/Admin/Form/Preferences/Contribute.php
CRM/Contribute/BAO/Contribution.php
CRM/Core/BAO/FinancialTrxn.php
CRM/Event/BAO/Participant.php
CRM/Event/Form/ParticipantFeeSelection.php
CRM/Member/Form/Membership.php
CRM/Price/BAO/LineItem.php
api/v3/examples/Setting/GetFields.php
settings/Contribute.setting.php
tests/phpunit/CRM/Event/BAO/AdditionalPaymentTest.php
tests/phpunit/CRM/Event/BAO/CRM19273Test.php
tests/phpunit/CRM/Member/Form/MembershipTest.php

index 9fb2377ccc66f1898641276d63be9174e7bd5a53..9bb789b6bfb44f90cdc30bdbb8a9237c14d09452 100644 (file)
@@ -37,7 +37,6 @@
 class CRM_Admin_Form_Preferences_Contribute extends CRM_Admin_Form_Preferences {
   protected $_settings = array(
     'cvv_backoffice_required' => CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME,
-    'update_contribution_on_membership_type_change' => CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME,
     'acl_financial_type' => CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME,
     'always_post_to_accounts_receivable' => CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME,
     'deferred_revenue_enabled' => CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME,
@@ -197,9 +196,6 @@ class CRM_Admin_Form_Preferences_Contribute extends CRM_Admin_Form_Preferences {
     unset($params['qfKey']);
     unset($params['entryURL']);
     Civi::settings()->set('contribution_invoice_settings', $params);
-    Civi::settings()->set('update_contribution_on_membership_type_change',
-      CRM_Utils_Array::value('update_contribution_on_membership_type_change', $params)
-    );
 
     // to set default value for 'Invoices / Credit Notes' checkbox on display preferences
     $values = CRM_Core_BAO_Setting::getItem("CiviCRM Preferences");
index 35e31ee32b34ac907419d74455dbb21db9e4f322..36375b3350c36ac05342341a90a32dcd62f2e50c 100644 (file)
@@ -4085,11 +4085,6 @@ WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
         }
       }
     }
-    elseif ($component == 'membership') {
-      $entity = $component;
-      $entityTable = 'civicrm_membership';
-      $contributionId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $id, 'contribution_id', 'membership_id');
-    }
     else {
       $contributionId = $id;
       $entity = 'contribution';
index 93300a1b89c2d3945d1f821fb08e98b699e22d6f..bfd11e3fc91e6ddba6492b614023019b9d7c4e76 100644 (file)
@@ -466,9 +466,6 @@ WHERE ceft.entity_id = %1";
     if ($entityName == 'participant') {
       $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $entityId, 'contribution_id', 'participant_id');
     }
-    elseif ($entityName == 'membership') {
-      $contributionId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $entityId, 'contribution_id', 'membership_id');
-    }
     else {
       $contributionId = $entityId;
     }
index e0d39c491c800d960ae745bc8c4037100d1a1a34..eb6fc33e74e1d53e92016beb7fae7bc1e50bbb10 100644 (file)
@@ -1880,6 +1880,323 @@ WHERE    civicrm_participant.contact_id = {$contactID} AND
     }
   }
 
+  /**
+   * @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
+          if ($previousLineItem['line_total'] != 0) {
+            unset($insertLines[$previousLineItem['price_field_value_id']]);
+          }
+          else {
+            $insertLines[$previousLineItem['price_field_value_id']]['skip'] = TRUE;
+          }
+          // 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);
+    }
+    $financialItemsArray = array();
+    if (!empty($submittedFields) && !empty($submittedFieldValues)) {
+      $updateLineItem = "UPDATE civicrm_line_item li
+INNER JOIN civicrm_financial_item fi
+   ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
+SET li.qty = 0,
+    li.line_total = 0.00,
+    li.tax_amount = NULL
+WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND
+       (price_field_value_id NOT IN ({$submittedFieldValues}))
+";
+      CRM_Core_DAO::executeQuery($updateLineItem);
+
+      // gathering necessary info to record negative (deselected) financial_item
+      $updateFinancialItem = "
+  SELECT fi.*, SUM(fi.amount) as differenceAmt, price_field_value_id, financial_type_id, tax_amount
+    FROM civicrm_financial_item fi LEFT JOIN civicrm_line_item li ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
+WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId})
+GROUP BY li.entity_table, li.entity_id, price_field_value_id, fi.id
+";
+      $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();
+      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;
+        }
+        // if submitted and difference is 0 add a positive entry again
+        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
+        INNER JOIN civicrm_financial_item fi
+        ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
+        SET li.qty = 0,
+        li.line_total = 0.00,
+        li.tax_amount = NULL
+        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'] . ' - ' . (float) $vals['qty'];
+        if (isset($vals['participant_count'])) {
+          $participantCount = $vals['participant_count'];
+          $totalParticipant += $vals['participant_count'];
+        }
+        $updateLineItem = "
+UPDATE civicrm_line_item li
+SET li.qty = {$vals['qty']},
+    li.line_total = {$vals['line_total']},
+    li.tax_amount = {$taxAmount},
+    li.unit_price = {$vals['unit_price']},
+    li.participant_count = {$participantCount},
+    li.label = %1
+WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND
+      (price_field_value_id = {$valueId})
+";
+        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) {
+        if (!array_key_exists('skip', $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) {
+      $updatedAmount = CRM_Price_BAO_LineItem::getLineTotal($contributionId);
+    }
+    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 *
+FROM civicrm_line_item
+WHERE (entity_table = 'civicrm_participant' AND entity_id = {$participantId} AND qty > 0)";
+    $getUpdatedLineItemsDAO = CRM_Core_DAO::executeQuery($getUpdatedLineItems);
+    $line = array();
+    while ($getUpdatedLineItemsDAO->fetch()) {
+      $line[$getUpdatedLineItemsDAO->price_field_value_id] = $getUpdatedLineItemsDAO->label . ' - ' . (float) $getUpdatedLineItemsDAO->qty;
+    }
+
+    $partUpdateFeeAmt['fee_level'] = implode(', ', $line);
+    $partUpdateFeeAmt['fee_amount'] = $params['amount'];
+    self::add($partUpdateFeeAmt);
+
+    //activity creation
+    self::addActivityForSelection($participantId, 'Change Registration');
+  }
+
+  /**
+   * Record adjusted amount.
+   *
+   * @param int $updatedAmount
+   * @param int $paidAmount
+   * @param int $contributionId
+   *
+   * @param int $taxAmount
+   * @param bool $updateAmountLevel
+   *
+   * @return bool|\CRM_Core_BAO_FinancialTrxn
+   */
+  public static function recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount = NULL, $updateAmountLevel = NULL) {
+    $pendingAmount = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId);
+    $pendingAmount = CRM_Utils_Array::value('total_amount', $pendingAmount, 0);
+    $balanceAmt = $updatedAmount - $paidAmount;
+    if ($paidAmount != $pendingAmount) {
+      $balanceAmt -= $pendingAmount;
+    }
+
+    $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
+    $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
+    $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
+    $completedStatusId = array_search('Completed', $contributionStatuses);
+
+    $updatedContributionDAO = new CRM_Contribute_BAO_Contribution();
+    $adjustedTrxn = $skip = FALSE;
+    if ($balanceAmt) {
+      if ($balanceAmt > 0 && $paidAmount != 0) {
+        $contributionStatusVal = $partiallyPaidStatusId;
+      }
+      elseif ($balanceAmt < 0 && $paidAmount != 0) {
+        $contributionStatusVal = $pendingRefundStatusId;
+      }
+      elseif ($paidAmount == 0) {
+        //skip updating the contribution status if no payment is made
+        $skip = TRUE;
+        $updatedContributionDAO->cancel_date = 'null';
+        $updatedContributionDAO->cancel_reason = NULL;
+      }
+      // update contribution status and total amount without trigger financial code
+      // as this is handled in current BAO function used for change selection
+      $updatedContributionDAO->id = $contributionId;
+      if (!$skip) {
+        $updatedContributionDAO->contribution_status_id = $contributionStatusVal;
+      }
+      $updatedContributionDAO->total_amount = $updatedContributionDAO->net_amount = $updatedAmount;
+      $updatedContributionDAO->fee_amount = 0;
+      $updatedContributionDAO->tax_amount = $taxAmount;
+      if (!empty($updateAmountLevel)) {
+        $updatedContributionDAO->amount_level = $updateAmountLevel;
+      }
+      $updatedContributionDAO->save();
+      // adjusted amount financial_trxn creation
+      $updatedContribution = CRM_Contribute_BAO_Contribution::getValues(
+        array('id' => $contributionId),
+        CRM_Core_DAO::$_nullArray,
+        CRM_Core_DAO::$_nullArray
+      );
+      $toFinancialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($updatedContribution->financial_type_id, 'Accounts Receivable Account is');
+      $adjustedTrxnValues = array(
+        'from_financial_account_id' => NULL,
+        'to_financial_account_id' => $toFinancialAccount,
+        'total_amount' => $balanceAmt,
+        'net_amount' => $balanceAmt,
+        'status_id' => $completedStatusId,
+        'payment_instrument_id' => $updatedContribution->payment_instrument_id,
+        'contribution_id' => $updatedContribution->id,
+        'trxn_date' => date('YmdHis'),
+        'currency' => $updatedContribution->currency,
+      );
+      $adjustedTrxn = CRM_Core_BAO_FinancialTrxn::create($adjustedTrxnValues);
+    }
+    return $adjustedTrxn;
+  }
+
   /**
    * @param int $participantId
    * @param $activityType
index aab0a8375da30c9b78d89628bb9cde226f4ec8d5..3687471942850205863e6504ebf8414a1e178fe0 100644 (file)
@@ -239,7 +239,7 @@ class CRM_Event_Form_ParticipantFeeSelection extends CRM_Core_Form {
 
     $feeBlock = $this->_values['fee'];
     $lineItems = $this->_values['line_items'];
-    CRM_Price_BAO_LineItem::changeFeeSelections($params, $this->_participantId, 'participant', $this->_contributionId, $feeBlock, $lineItems, $this->_paidAmount);
+    CRM_Event_BAO_Participant::changeFeeSelections($params, $this->_participantId, $this->_contributionId, $feeBlock, $lineItems, $this->_paidAmount, $params['priceSetId']);
     $this->contributionAmt = CRM_Core_DAO::getFieldValue('CRM_Contribute_BAO_Contribution', $this->_contributionId, 'total_amount');
     // email sending
     if (!empty($params['send_receipt'])) {
index 163147f228763a586b63aff7a678beda0137daa8..b21338e75f9e1becd7a2c14ace77a874691803fa 100644 (file)
@@ -1725,91 +1725,10 @@ class CRM_Member_Form_Membership extends CRM_Member_Form {
     }
 
     $isRecur = CRM_Utils_Array::value('is_recur', $params);
-    $this->updateContributionOnMembershipTypeChange($params, $membership);
     $this->setStatusMessage($membership, $endDate, $receiptSent, $membershipTypes, $createdMemberships, $isRecur, $calcDates, $mailSend);
     return $createdMemberships;
   }
 
-  /**
-   * Update related contribution of a membership if update_contribution_on_membership_type_change
-   *   contribution setting is enabled and type is changed on edit
-   *
-   * @param array $inputParams
-   *      submitted form values
-   * @param CRM_Member_DAO_Membership $membership
-   *     Updated membership object
-   *
-   */
-  protected function updateContributionOnMembershipTypeChange($inputParams, $membership) {
-    if (Civi::settings()->get('update_contribution_on_membership_type_change') &&
-      ($this->_action & CRM_Core_Action::UPDATE) && // on update
-      $this->_id && // if ID is present
-      !in_array($this->_memType, $this->_memTypeSelected) // if selected membership doesn't match with earlier membership
-    ) {
-      if (CRM_Utils_Array::value('is_recur', $inputParams)) {
-        CRM_Core_Session::setStatus(ts('Associated recurring contribution cannot be updated on membership type change.', ts('Error'), 'error'));
-        return;
-      }
-
-      // fetch lineitems by updated membership ID
-      $lineItems = CRM_Price_BAO_LineItem::getLineItems($membership->id, 'membership');
-      // retrieve the related contribution ID
-      $contributionID = CRM_Core_DAO::getFieldValue(
-        'CRM_Member_DAO_MembershipPayment',
-        $membership->id,
-        'contribution_id',
-        'membership_id'
-      );
-      // get price fields of chosen price-set
-      $priceSetDetails = CRM_Utils_Array::value(
-        $this->_priceSetId,
-        CRM_Price_BAO_PriceSet::getSetDetail(
-          $this->_priceSetId,
-          TRUE,
-          TRUE
-        )
-      );
-
-      // add price field information in $inputParams
-      self::addPriceFieldByMembershipType($inputParams, $priceSetDetails['fields'], $membership->membership_type_id);
-      // paid amount
-      $paidAmount = CRM_Utils_Array::value('paid', CRM_Contribute_BAO_Contribution::getPaymentInfo($membership->id, 'membership'));
-      // update related contribution and financial records
-      CRM_Price_BAO_LineItem::changeFeeSelections(
-        $inputParams,
-        $membership->id,
-        'membership',
-        $contributionID,
-        $priceSetDetails['fields'],
-        $lineItems, $paidAmount
-      );
-      CRM_Core_Session::setStatus(ts('Associated contribution is updated on membership type change.'), ts('Success'), 'success');
-    }
-  }
-
-  /**
-   * Add selected price field information in $formValues
-   *
-   * @param array $formValues
-   *      submitted form values
-   * @param array $priceFields
-   *     Price fields of selected Priceset ID
-   * @param int $membershipTypeID
-   *     Selected membership type ID
-   *
-   */
-  public static function addPriceFieldByMembershipType(&$formValues, $priceFields, $membershipTypeID) {
-    foreach ($priceFields as $priceFieldID => $priceField) {
-      if (isset($priceField['options']) && count($priceField['options'])) {
-        foreach ($priceField['options'] as $option) {
-          if ($option['membership_type_id'] == $membershipTypeID) {
-            $formValues["price_{$priceFieldID}"] = $option['id'];
-            break;
-          }
-        }
-      }
-    }
-  }
   /**
    * Set context in session.
    */
index 066da4aa1a6e6de15c7f33d9bb348ea3bd66398b..e1b629c4a721d07e65dc044b5d790e7371073099 100644 (file)
@@ -552,6 +552,7 @@ WHERE li.contribution_id = %1";
    * @param bool $isRelatedID
    */
   public static function getLineItemArray(&$params, $entityId = NULL, $entityTable = 'contribution', $isRelatedID = FALSE) {
+
     if (!$entityId) {
       $priceSetDetails = CRM_Price_BAO_PriceSet::getDefaultPriceSet($entityTable);
       $totalAmount = CRM_Utils_Array::value('partial_payment_total', $params, CRM_Utils_Array::value('total_amount', $params));
@@ -604,558 +605,4 @@ WHERE li.contribution_id = %1";
     }
   }
 
-  /**
-   * Function to update related contribution of a entity and
-   *  add/update/cancel financial records
-   *
-   * @param array $params
-   * @param int $entityID
-   * @param int $entity
-   * @param int $contributionId
-   * @param $feeBlock
-   * @param array $lineItems
-   * @param $paidAmount
-   *
-   */
-  public static function changeFeeSelections(
-    $params,
-    $entityID,
-    $entity,
-    $contributionId,
-    $feeBlock,
-    $lineItems,
-    $paidAmount
-  ) {
-    $entityTable = "civicrm_" . $entity;
-    CRM_Price_BAO_PriceSet::processAmount($feeBlock,
-      $params, $lineItems
-    );
-    // initialize empty Lineitem instance to call protected helper functions
-    $lineItemObj = new CRM_Price_BAO_LineItem();
-
-    // fetch submitted LineItems from input params and feeBlock information
-    $submittedLineItems = $lineItemObj->_getSubmittedLineItems($params, $feeBlock);
-
-    // retrieve the submitted price field value IDs from $submittedLineItems array keys
-    $submittedPriceFieldValueIDs = empty($submittedLineItems) ? array() : array_keys($submittedLineItems);
-
-    // get lineItems need to be updated and added to record changed fee
-    list($lineItemsToAdd, $lineItemsToUpdate) = $lineItemObj->_getLineItemsToAddAndUpdate($submittedLineItems, $entityID, $entity);
-
-    // cancel previous line item
-    $additionalWhereClause = empty($submittedPriceFieldValueIDs) ? NULL : sprintf("price_field_value_id NOT IN (%s)", implode(', ', $submittedPriceFieldValueIDs));
-    $lineItemObj->_cancelLineItems($entityID, $entityTable, $additionalWhereClause);
-
-    // get financial information that need to be recorded on basis on submitted price field value IDs
-    $financialItemsArray = $lineItemObj->_getFinancialItemsToRecord(
-      $entityID,
-      $entityTable,
-      $contributionId,
-      $submittedPriceFieldValueIDs
-    );
-
-    // update line item with changed line total and other information
-    $totalParticipant = $participantCount = 0;
-    $amountLevel = array();
-    if (!empty($lineItemsToUpdate)) {
-      foreach ($lineItemsToUpdate as $priceFieldValueID => $value) {
-        $taxAmount = "NULL";
-        if (isset($value['tax_amount'])) {
-          $taxAmount = $value['tax_amount'];
-        }
-        $amountLevel[] = $value['label'] . ' - ' . (float) $value['qty'];
-        if ($entity == 'participant' && isset($value['participant_count'])) {
-          $participantCount = $value['participant_count'];
-          $totalParticipant += $value['participant_count'];
-        }
-        $updateLineItemSQL = "
-        UPDATE civicrm_line_item li
-        SET li.qty = {$value['qty']},
-            li.line_total = {$value['line_total']},
-            li.tax_amount = {$taxAmount},
-            li.unit_price = {$value['unit_price']},
-            li.participant_count = {$participantCount},
-            li.label = %1
-      WHERE (li.entity_table = '{$entityTable}' AND li.entity_id = {$entityID}) AND
-        (price_field_value_id = {$priceFieldValueID}) ";
-
-        CRM_Core_DAO::executeQuery($updateLineItemSQL, array(1 => array($value['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
-    $lineItemObj->_addLineItemOnChangeFeeSelection($lineItemsToAdd, $entityID, $entityTable, $contributionId);
-
-    // the recordAdjustedAmt code would execute over here
-    $count = 0;
-    if ($entity == 'participant') {
-      $count = count(CRM_Event_BAO_Participant::getParticipantIds($contributionId));
-    }
-    else {
-      $count = CRM_Utils_Array::value('count', civicrm_api3('MembershipPayment', 'getcount', array('contribution_id' => $contributionId)));
-    }
-    if ($count > 1) {
-      $updatedAmount = CRM_Price_BAO_LineItem::getLineTotal($contributionId);
-    }
-    else {
-      $updatedAmount = CRM_Utils_Array::value('amount', $params, CRM_Utils_Array::value('total_amount', $params));
-    }
-    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 = $lineItemObj->_recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount, $updateAmountLevel);
-
-    $contributionCompletedStatusID = CRM_Core_PseudoConstant::getKey('CRM_Contribute_DAO_Contribution', 'contribution_status_id', 'Completed');
-    if (!empty($financialItemsArray)) {
-      foreach ($financialItemsArray as $updateFinancialItemInfoValues) {
-        $newFinancialItem = CRM_Financial_BAO_FinancialItem::create($updateFinancialItemInfoValues);
-        // record reverse transaction only if Contribution is Completed because for pending refund or
-        //   partially paid we are already recording the surplus owed or refund amount
-        if (!empty($updateFinancialItemInfoValues['financialTrxn']) && ($contributionCompletedStatusID ==
-          CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'contribution_status_id'))
-        ) {
-          $trxnTable = array(
-            'entity_id' => $newFinancialItem->id,
-            'entity_table' => 'civicrm_financial_item',
-          );
-          $reverseTrxn = CRM_Core_BAO_FinancialTrxn::create($updateFinancialItemInfoValues['financialTrxn'], $trxnTable);
-          // record reverse entity financial trxn linked to membership's related contribution
-          civicrm_api3('EntityFinancialTrxn', 'create', array(
-            'entity_table' => "civicrm_contribution",
-            'entity_id' => $contributionId,
-            'financial_trxn_id' => $reverseTrxn->id,
-            'amount' => $reverseTrxn->total_amount,
-          ));
-          unset($updateFinancialItemInfoValues['financialTrxn']);
-        }
-        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);
-        }
-      }
-    }
-
-    $trxnId = array();
-    if (!empty($trxn->id)) {
-      $trxnId['id'] = $trxn->id;
-    }
-    $lineItemObj->_addLineItemOnChangeFeeSelection($lineItemsToAdd, $entityID, $entityTable, $contributionId, $trxnId, TRUE);
-
-    // update participant fee_amount column
-    $lineItemObj->_updateEntityRecordOnChangeFeeSelection($params, $entityID, $entity);
-  }
-
-  /**
-   * Function to cancel Lineitem whose corrosponding price field option is
-   *  unselected on membership or participant backoffice form
-   *
-   * @param int $entityID
-   * @param string $entityTable
-   * @param string $additionalWhereClause
-   *
-   */
-  protected function _cancelLineItems($entityID, $entityTable, $additionalWhereClause = NULL) {
-    $whereClauses = array(
-      "li.entity_id = %1",
-      "li.entity_table = %2",
-    );
-    if ($additionalWhereClause) {
-      $whereClauses[] = $additionalWhereClause;
-    }
-
-    $where = implode(' AND ', $whereClauses);
-    $sql = "
-      UPDATE civicrm_line_item li
-        INNER JOIN civicrm_financial_item fi ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
-      SET li.qty = 0,
-        li.line_total = 0.00,
-        li.tax_amount = NULL,
-        li.participant_count = 0,
-        li.non_deductible_amount = 0.00
-      WHERE {$where} ";
-
-    CRM_Core_DAO::executeQuery($sql, array(
-      1 => array($entityID, 'Integer'),
-      2 => array($entityTable, 'String'),
-    ));
-  }
-
-  /**
-   * Function to retrieve formatted financial items that need to be recorded as result of changed fee
-   *
-   * @param int $entityID
-   * @param string $entityTable
-   * @param int $contributionID
-   * @param array $submittedPriceFieldValueIDs
-   *
-   * @return array
-   *      List of formatted Financial Items to be recorded
-   */
-  protected function _getFinancialItemsToRecord($entityID, $entityTable, $contributionID, $submittedPriceFieldValueIDs) {
-    $previousLineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, str_replace('civicrm_', '', $entityTable));
-
-    $financialItemsArray = array();
-
-    if (empty($submittedPriceFieldValueIDs)) {
-      return $financialItemsArray;
-    }
-
-    // gathering necessary info to record negative (deselected) financial_item
-    $updateFinancialItem = "
-  SELECT fi.*, SUM(fi.amount) as differenceAmt, price_field_value_id, financial_type_id, tax_amount
-    FROM civicrm_financial_item fi LEFT JOIN civicrm_line_item li ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
-  WHERE (li.entity_table = '{$entityTable}' AND li.entity_id = {$entityID})
-  GROUP BY li.entity_table, li.entity_id, price_field_value_id, fi.id
-    ";
-    $updateFinancialItemInfoDAO = CRM_Core_DAO::executeQuery($updateFinancialItem);
-
-    $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
-    $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
-    $updateFinancialItemInfoValues = array();
-    while ($updateFinancialItemInfoDAO->fetch()) {
-      $updateFinancialItemInfoValues = (array) $updateFinancialItemInfoDAO;
-      $updateFinancialItemInfoValues['transaction_date'] = date('YmdHis');
-      // the below params are not needed
-      $previousFinancialItemID = $updateFinancialItemInfoValues['id'];
-      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'], $submittedPriceFieldValueIDs) && $updateFinancialItemInfoValues['differenceAmt'] != 0) {
-        // INSERT negative financial_items
-        $updateFinancialItemInfoValues['amount'] = -$updateFinancialItemInfoValues['amount'];
-        // reverse the related financial trxn too
-        $updateFinancialItemInfoValues['financialTrxn'] = $this->_getRelatedCancelFinancialTrxn($previousFinancialItemID);
-        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;
-      }
-      // if submitted and difference is 0 add a positive entry again
-      elseif (in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedPriceFieldValueIDs) && $updateFinancialItemInfoValues['differenceAmt'] == 0) {
-        $updateFinancialItemInfoValues['amount'] = $updateFinancialItemInfoValues['amount'];
-        // INSERT financial_items for tax amount
-        if ($updateFinancialItemInfoValues['entity_id'] == $lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']]['id'] &&
-          isset($lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'])
-        ) {
-          $updateFinancialItemInfoValues['tax']['amount'] = $lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'];
-          $updateFinancialItemInfoValues['tax']['description'] = $taxTerm;
-          if ($lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']) {
-            $updateFinancialItemInfoValues['tax']['financial_account_id'] = CRM_Contribute_BAO_Contribution::getFinancialAccountId($lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']);
-          }
-        }
-        $financialItemsArray[] = $updateFinancialItemInfoValues;
-      }
-    }
-
-    return $financialItemsArray;
-  }
-
-  /**
-   * Helper function to retrieve submitted line items from form values $inputParams and used $feeBlock
-   *
-   * @param array $inputParams
-   * @param array $feeBlock
-   *
-   * @return array
-   *     List of submitted line items
-   */
-  protected function _getSubmittedLineItems($inputParams, $feeBlock) {
-    $submittedLineItems = array();
-    foreach ($feeBlock as $id => $values) {
-      CRM_Price_BAO_LineItem::format($id, $inputParams, $values, $submittedLineItems);
-    }
-
-    return $submittedLineItems;
-  }
-
-  /**
-   * Helper function to retrieve formatted lineitems need to be added and/or updated
-   *
-   * @param array $submittedLineItems
-   * @param int $entityID
-   * @param string $entity
-   *
-   * @return array
-   *    Array of formatted lineitems
-   */
-  protected function _getLineItemsToAddAndUpdate($submittedLineItems, $entityID, $entity) {
-    $previousLineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entity);
-
-    $lineItemsToAdd = $submittedLineItems;
-    $lineItemsToUpdate = array();
-    $submittedPriceFieldValueIDs = 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'], $submittedPriceFieldValueIDs)) {
-        // if submitted line items are existing don't fire INSERT query
-        if ($previousLineItem['line_total'] != 0) {
-          unset($lineItemsToAdd[$previousLineItem['price_field_value_id']]);
-        }
-        else {
-          $lineItemsToAdd[$previousLineItem['price_field_value_id']]['skip'] = TRUE;
-        }
-        // 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'])
-        ) {
-          $lineItemsToUpdate[$previousLineItem['price_field_value_id']] = $submittedLineItems[$previousLineItem['price_field_value_id']];
-          $lineItemsToUpdate[$previousLineItem['price_field_value_id']]['id'] = $id;
-        }
-      }
-    }
-
-    return array($lineItemsToAdd, $lineItemsToUpdate);
-  }
-
-  /**
-   * Helper function to add lineitems or financial item related to it, to as result of fee change
-   *
-   * @param array $lineItemsToAdd
-   * @param int $entityID
-   * @param string $entityTable
-   * @param int $contributionID
-   * @param array $adjustedFinancialTrxnID
-   * @param bool $addFinancialItemOnly
-   *
-   * @return void
-   */
-  protected function _addLineItemOnChangeFeeSelection(
-    $lineItemsToAdd,
-    $entityID,
-    $entityTable,
-    $contributionID,
-    $adjustedFinancialTrxnID = NULL,
-    $addFinancialItemOnly = FALSE
-  ) {
-    // if there is no line item to add, do not proceed
-    if (empty($lineItemsToAdd)) {
-      return;
-    }
-
-    $changedFinancialTypeID = NULL;
-    $fetchCon = array('id' => $contributionID);
-    $updatedContribution = CRM_Contribute_BAO_Contribution::retrieve($fetchCon, CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
-    // insert financial items
-    foreach ($lineItemsToAdd as $priceFieldValueID => $lineParams) {
-      $tempFinancialTrxnID = $adjustedFinancialTrxnID;
-      $lineParams = array_merge($lineParams, array(
-        'entity_table' => $entityTable,
-        'entity_id' => $entityID,
-        'contribution_id' => $contributionID,
-      ));
-      if ($addFinancialItemOnly) {
-        // don't add financial item for cancelled line item
-        if ($lineParams['qty'] == 0) {
-          continue;
-        }
-        elseif (empty($adjustedFinancialTrxnID)) {
-          // add financial item if ONLY financial type is changed
-          if ($lineParams['financial_type_id'] != $updatedContribution->financial_type_id) {
-            $changedFinancialTypeID = $lineParams['financial_type_id'];
-            $adjustedTrxnValues = array(
-              'from_financial_account_id' => NULL,
-              'to_financial_account_id' => CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($updatedContribution->payment_instrument_id),
-              'total_amount' => $lineParams['line_total'],
-              'net_amount' => $lineParams['line_total'],
-              'status_id' => $updatedContribution->contribution_status_id,
-              'payment_instrument_id' => $updatedContribution->payment_instrument_id,
-              'contribution_id' => $updatedContribution->id,
-              'is_payment' => TRUE, // since balance is 0, which means contribution is completed
-              'trxn_date' => date('YmdHis'),
-              'currency' => $updatedContribution->currency,
-            );
-            $adjustedTrxn = CRM_Core_BAO_FinancialTrxn::create($adjustedTrxnValues);
-            $tempFinancialTrxnID = array('id' => $adjustedTrxn->id);
-          }
-          // don't add financial item if line_total and financial type aren't changed,
-          //  which is identified by empty $adjustedFinancialTrxnID
-          else {
-            continue;
-          }
-        }
-        $lineObj = CRM_Price_BAO_LineItem::retrieve($lineParams, CRM_Core_DAO::$_nullArray);
-        // insert financial items
-        // ensure entity_financial_trxn table has a linking of it.
-        CRM_Financial_BAO_FinancialItem::add($lineObj, $updatedContribution, NULL, $tempFinancialTrxnID);
-        if (isset($lineObj->tax_amount)) {
-          CRM_Financial_BAO_FinancialItem::add($lineObj, $updatedContribution, TRUE, $tempFinancialTrxnID);
-        }
-      }
-      elseif (!array_key_exists('skip', $lineParams)) {
-        self::create($lineParams);
-      }
-    }
-
-    if ($changedFinancialTypeID) {
-      $updatedContribution->financial_type_id = $changedFinancialTypeID;
-      $updatedContribution->save();
-    }
-  }
-
-  /**
-   * Helper function to update entity record on change fee selection
-   *
-   * @param array $inputParams
-   * @param int $entityID
-   * @param string $entity
-   *
-   */
-  protected function _updateEntityRecordOnChangeFeeSelection($inputParams, $entityID, $entity) {
-    $entityTable = "civicrm_{$entity}";
-
-    if ($entity == 'participant') {
-      $partUpdateFeeAmt = array('id' => $entityID);
-      $getUpdatedLineItems = "SELECT *
-        FROM civicrm_line_item
-        WHERE (entity_table = '{$entityTable}' AND entity_id = {$entityID} AND qty > 0)";
-      $getUpdatedLineItemsDAO = CRM_Core_DAO::executeQuery($getUpdatedLineItems);
-      $line = array();
-      while ($getUpdatedLineItemsDAO->fetch()) {
-        $line[$getUpdatedLineItemsDAO->price_field_value_id] = $getUpdatedLineItemsDAO->label . ' - ' . (float) $getUpdatedLineItemsDAO->qty;
-      }
-
-      $partUpdateFeeAmt['fee_level'] = implode(', ', $line);
-      $partUpdateFeeAmt['fee_amount'] = $inputParams['amount'];
-      CRM_Event_BAO_Participant::add($partUpdateFeeAmt);
-
-      //activity creation
-      CRM_Event_BAO_Participant::addActivityForSelection($entityID, 'Change Registration');
-    }
-  }
-
-  /**
-   * Helper function to retrieve financial trxn parameters to reverse
-   *  for given financial item identified by $financialItemID
-   *
-   * @param int $financialItemID
-   *
-   * @return array $financialTrxn
-   *
-   */
-  protected function _getRelatedCancelFinancialTrxn($financialItemID) {
-    $financialTrxn = civicrm_api3('EntityFinancialTrxn', 'getsingle', array(
-      'entity_table' => 'civicrm_financial_item',
-      'entity_id' => $financialItemID,
-      'options' => array(
-        'sort' => 'id DESC',
-        'limit' => 1,
-      ),
-      'api.FinancialTrxn.getsingle' => array(
-        'id' => "\$value.financial_trxn_id",
-      ),
-    ));
-
-    $financialTrxn = array_merge($financialTrxn['api.FinancialTrxn.getsingle'], array(
-      'trxn_date' => date('YmdHis'),
-      'total_amount' => -$financialTrxn['api.FinancialTrxn.getsingle']['total_amount'],
-      'net_amount' => -$financialTrxn['api.FinancialTrxn.getsingle']['net_amount'],
-      'entity_table' => 'civicrm_financial_item',
-      'entity_id' => $financialItemID,
-    ));
-    unset($financialTrxn['id']);
-
-    return $financialTrxn;
-  }
-
-  /**
-   * Record adjusted amount.
-   *
-   * @param int $updatedAmount
-   * @param int $paidAmount
-   * @param int $contributionId
-   *
-   * @param int $taxAmount
-   * @param bool $updateAmountLevel
-   *
-   * @return bool|\CRM_Core_BAO_FinancialTrxn
-   */
-  protected function _recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount = NULL, $updateAmountLevel = NULL) {
-    $pendingAmount = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId);
-    $pendingAmount = CRM_Utils_Array::value('total_amount', $pendingAmount, 0);
-    $balanceAmt = $updatedAmount - $paidAmount;
-    if ($paidAmount != $pendingAmount) {
-      $balanceAmt -= $pendingAmount;
-    }
-
-    $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
-    $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
-    $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
-    $completedStatusId = array_search('Completed', $contributionStatuses);
-
-    $updatedContributionDAO = new CRM_Contribute_BAO_Contribution();
-    $adjustedTrxn = $skip = FALSE;
-    if ($balanceAmt) {
-      if ($balanceAmt > 0 && $paidAmount != 0) {
-        $contributionStatusVal = $partiallyPaidStatusId;
-      }
-      elseif ($balanceAmt < 0 && $paidAmount != 0) {
-        $contributionStatusVal = $pendingRefundStatusId;
-      }
-      elseif ($paidAmount == 0) {
-        //skip updating the contribution status if no payment is made
-        $skip = TRUE;
-        $updatedContributionDAO->cancel_date = 'null';
-        $updatedContributionDAO->cancel_reason = NULL;
-      }
-      // update contribution status and total amount without trigger financial code
-      // as this is handled in current BAO function used for change selection
-      $updatedContributionDAO->id = $contributionId;
-      if (!$skip) {
-        $updatedContributionDAO->contribution_status_id = $contributionStatusVal;
-      }
-      $updatedContributionDAO->total_amount = $updatedContributionDAO->net_amount = $updatedAmount;
-      $updatedContributionDAO->fee_amount = 0;
-      $updatedContributionDAO->tax_amount = $taxAmount;
-      if (!empty($updateAmountLevel)) {
-        $updatedContributionDAO->amount_level = $updateAmountLevel;
-      }
-      $updatedContributionDAO->save();
-      // adjusted amount financial_trxn creation
-      $updatedContribution = CRM_Contribute_BAO_Contribution::getValues(
-        array('id' => $contributionId),
-        CRM_Core_DAO::$_nullArray,
-        CRM_Core_DAO::$_nullArray
-      );
-      $toFinancialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($updatedContribution->financial_type_id, 'Accounts Receivable Account is');
-      $adjustedTrxnValues = array(
-        'from_financial_account_id' => NULL,
-        'to_financial_account_id' => $toFinancialAccount,
-        'total_amount' => $balanceAmt,
-        'net_amount' => $balanceAmt,
-        'status_id' => $completedStatusId,
-        'payment_instrument_id' => $updatedContribution->payment_instrument_id,
-        'contribution_id' => $updatedContribution->id,
-        'trxn_date' => date('YmdHis'),
-        'currency' => $updatedContribution->currency,
-      );
-      $adjustedTrxn = CRM_Core_BAO_FinancialTrxn::create($adjustedTrxnValues);
-    }
-    return $adjustedTrxn;
-  }
-
 }
index 739f9d4814c11e43207a79c8356f73768da3df5d..0da8b46d79165f9f80d80b7d8e5e7ad15d3f374d 100644 (file)
@@ -240,21 +240,6 @@ function setting_getfields_expectedresult() {
         'description' => '',
         'help_text' => '',
       ),
-      'update_contribution_on_membership_type_change' => array(
-        'group_name' => 'Contribute Preferences',
-        'group' => 'contribute',
-        'name' => 'update_contribution_on_membership_type_change',
-        'type' => 'Integer',
-        'html_type' => 'checkbox',
-        'quick_form_type' => 'Element',
-        'default' => 0,
-        'add' => '4.7',
-        'title' => 'Automatically update related contributions when Membership Type is changed',
-        'is_domain' => 1,
-        'is_contact' => 0,
-        'description' => 'Enabling this setting will update related contribution of membership(s) except if the membership is paid for with a recurring contribution.',
-        'help_text' => '',
-      ),
       'contact_view_options' => array(
         'group_name' => 'CiviCRM Preferences',
         'group' => 'core',
index a9b510998806472f3730b7befc684d7c5f085935..67313e3031a626acc8e8b3a76e1d1add4c1946e6 100644 (file)
@@ -150,19 +150,4 @@ return array(
     'description' => NULL,
     'help_text' => NULL,
   ),
-  'update_contribution_on_membership_type_change' => array(
-    'group_name' => 'Contribute Preferences',
-    'group' => 'contribute',
-    'name' => 'update_contribution_on_membership_type_change',
-    'type' => 'Integer',
-    'html_type' => 'checkbox',
-    'quick_form_type' => 'Element',
-    'default' => 0,
-    'add' => '4.7',
-    'title' => 'Automatically update related contributions when Membership Type is changed',
-    'is_domain' => 1,
-    'is_contact' => 0,
-    'description' => 'Enabling this setting will update related contribution of membership(s) except if the membership is paid for with a recurring contribution.',
-    'help_text' => NULL,
-  ),
 );
index e015a86720ff88ca8ea0d19130a863e764e75e8b..f0b3663934bfa74b0bb41462e55fe9fb747dba74 100644 (file)
@@ -176,7 +176,7 @@ class CRM_Event_BAO_AdditionalPaymentTest extends CiviUnitTestCase {
 
     //Change selection to a lower amount.
     $params['price_2'] = 50;
-    CRM_Price_BAO_LineItem::changeFeeSelections($params, $participant['id'], 'participant', $contribution->id, $feeBlock, $lineItem, $feeAmt);
+    CRM_Event_BAO_Participant::changeFeeSelections($params, $participant['id'], $contribution->id, $feeBlock, $lineItem, $feeAmt, $priceSetId);
 
     //Record a refund of the remaining amount.
     $submittedValues['total_amount'] = 50;
index 0675353f7c44e1b4dc9038ca431b754c8138c1e2..108e2e7d10f024a16f479590170877e77b4bc49b 100644 (file)
@@ -227,20 +227,21 @@ class CRM_Event_BAO_CRM19273 extends CiviUnitTestCase {
   }
 
   public function testCRM19273() {
+
     $PSparams['price_1'] = 2;
     $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->participantID, 'participant');
-    CRM_Price_BAO_LineItem::changeFeeSelections($PSparams, $this->participantID, 'participant', $this->_contributionId, $this->_feeBlock, $lineItem, $this->_expensiveFee);
+    CRM_Event_BAO_Participant::changeFeeSelections($PSparams, $this->participantID, $this->_contributionId, $this->_feeBlock, $lineItem, $this->_expensiveFee, $this->_priceSetID);
     $this->balanceCheck($this->_cheapFee);
 
     $PSparams['price_1'] = 1;
     $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->participantID, 'participant');
-    CRM_Price_BAO_LineItem::changeFeeSelections($PSparams, $this->participantID, 'participant', $this->_contributionId, $this->_feeBlock, $lineItem, $this->_expensiveFee);
+    CRM_Event_BAO_Participant::changeFeeSelections($PSparams, $this->participantID, $this->_contributionId, $this->_feeBlock, $lineItem, $this->_expensiveFee, $this->_priceSetID);
     $this->balanceCheck($this->_expensiveFee);
 
     $PSparams['price_1'] = 3;
     $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->participantID, 'participant');
 
-    CRM_Price_BAO_LineItem::changeFeeSelections($PSparams, $this->participantID, 'participant', $this->_contributionId, $this->_feeBlock, $lineItem, $this->_expensiveFee);
+    CRM_Event_BAO_Participant::changeFeeSelections($PSparams, $this->participantID, $this->_contributionId, $this->_feeBlock, $lineItem, $this->_expensiveFee, $this->_priceSetID);
     $this->balanceCheck($this->_veryExpensive);
 
   }
index 09476038bc60738bbe4f3f7c1f1e61a0167e8810..0c2c1dee82f9fdd0eb4dac76a29a87fb877d4273 100644 (file)
@@ -110,7 +110,6 @@ class CRM_Member_Form_MembershipTest extends CiviUnitTestCase {
       'name' => "AnnualFixed",
       'member_of_contact_id' => 23,
       'duration_unit' => "year",
-      'minimum_fee' => 50,
       'duration_interval' => 1,
       'period_type' => "fixed",
       'fixed_period_start_day' => "101",
@@ -513,100 +512,6 @@ class CRM_Member_Form_MembershipTest extends CiviUnitTestCase {
     $this->mut->stop();
   }
 
-  /**
-   * Test the submit function of the membership form on membership type change.
-   *  Check if the related contribuion is also updated if the minimum_fee didn't match
-   */
-  public function testContributionUpdateOnMembershipTypeChange() {
-    // Step 1: Create a Membership via backoffice whose with 50.00 payment
-    $form = $this->getForm();
-    $form->preProcess();
-    $this->mut = new CiviMailUtils($this, TRUE);
-    $this->createLoggedInUser();
-    $priceSet = $this->callAPISuccess('PriceSet', 'Get', array("extends" => "CiviMember"));
-    $form->set('priceSetId', $priceSet['id']);
-    CRM_Price_BAO_PriceSet::buildPriceSet($form);
-    $params = array(
-      'cid' => $this->_individualId,
-      'join_date' => date('m/d/Y', time()),
-      'start_date' => '',
-      'end_date' => '',
-      // This format reflects the 23 being the organisation & the 25 being the type.
-      'membership_type_id' => array(23, $this->membershipTypeAnnualFixedID),
-      'record_contribution' => 1,
-      'total_amount' => 50,
-      'receive_date' => date('m/d/Y', time()),
-      'receive_date_time' => '08:36PM',
-      'payment_instrument_id' => array_search('Check', $this->paymentInstruments),
-      'contribution_status_id' => CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
-      'financial_type_id' => '2', //Member dues, see data.xml
-      'payment_processor_id' => $this->_paymentProcessorID,
-    );
-    $form->_contactID = $this->_individualId;
-    $form->testSubmit($params);
-    $membership = $this->callAPISuccessGetSingle('Membership', array('contact_id' => $this->_individualId));
-    // check the membership status after partial payment, if its Pending
-    $this->assertEquals(array_search('New', CRM_Member_PseudoConstant::membershipStatus()), $membership['status_id']);
-    $contribution = $this->callAPISuccessGetSingle('Contribution', array(
-      'contact_id' => $this->_individualId,
-    ));
-    $this->assertEquals('Completed', $contribution['contribution_status']);
-    $this->assertEquals(50.00, $contribution['total_amount']);
-    $this->assertEquals(50.00, $contribution['net_amount']);
-
-    // Step 2: Change the membership type whose minimum free is less than earlier membership
-    $secondMembershipType = $this->callAPISuccess('membership_type', 'create', array(
-      'domain_id' => 1,
-      'name' => "Second Test Membership",
-      'member_of_contact_id' => 23,
-      'duration_unit' => "month",
-      'minimum_fee' => 25,
-      'duration_interval' => 1,
-      'period_type' => "fixed",
-      'fixed_period_start_day' => "101",
-      'fixed_period_rollover_day' => "1231",
-      'relationship_type_id' => 20,
-      'financial_type_id' => 2,
-    ));
-    Civi::settings()->set('update_contribution_on_membership_type_change', TRUE);
-    $form = $this->getForm();
-    $form->preProcess();
-    $form->_id = $membership['id'];
-    $form->set('priceSetId', $priceSet['id']);
-    CRM_Price_BAO_PriceSet::buildPriceSet($form);
-    $form->_action = CRM_Core_Action::UPDATE;
-    $params = array(
-      'cid' => $this->_individualId,
-      'join_date' => date('m/d/Y', time()),
-      'start_date' => '',
-      'end_date' => '',
-      // This format reflects the 23 being the organisation & the 25 being the type.
-      'membership_type_id' => array(23, $secondMembershipType['id']),
-      'record_contribution' => 1,
-      'status_id' => 1,
-      'total_amount' => 25,
-      'receive_date' => date('m/d/Y', time()),
-      'receive_date_time' => '08:36PM',
-      'payment_instrument_id' => array_search('Check', $this->paymentInstruments),
-      'financial_type_id' => '2', //Member dues, see data.xml
-      'payment_processor_id' => $this->_paymentProcessorID,
-    );
-    $form->_contactID = $this->_individualId;
-    $form->testSubmit($params);
-    $membership = $this->callAPISuccessGetSingle('Membership', array('contact_id' => $this->_individualId));
-    // check the membership status after partial payment, if its Pending
-    $contribution = $this->callAPISuccessGetSingle('Contribution', array(
-      'contact_id' => $this->_individualId,
-    ));
-    $payment = CRM_Contribute_BAO_Contribution::getPaymentInfo($membership['id'], 'membership', FALSE, TRUE);
-    // Check the contribution status on membership type change whose minimum fee was less than earlier memebership
-    $this->assertEquals('Pending refund', $contribution['contribution_status']);
-    // Earlier paid amount
-    $this->assertEquals(50, $payment['paid']);
-    // balance remaning
-    $this->assertEquals(-25, $payment['balance']);
-  }
-
   /**
    * Test the submit function of the membership form.
    */