/**  
  * Function to set variables up before form is built  
  *                                                            
  * @return void  
  * @access public  
  */
 function preProcess()
 {
     require_once 'CRM/Contribute/BAO/Contribution.php';
     $values = array();
     $ids = array();
     $params = array('id' => $this->get('id'));
     CRM_Contribute_BAO_Contribution::getValues($params, $values, $ids);
     CRM_Contribute_BAO_Contribution::resolveDefaults($values);
     $groupTree =& CRM_Core_BAO_CustomGroup::getTree('Contribution', $this->get('id'));
     CRM_Core_BAO_CustomGroup::buildViewHTML($this, $groupTree);
     $id = $this->get('id');
     if ($id) {
         require_once 'CRM/Contribute/DAO/ContributionProduct.php';
         $dao =& new CRM_Contribute_DAO_ContributionProduct();
         $dao->contribution_id = $id;
         if ($dao->find(true)) {
             $premiumId = $dao->id;
             $productID = $dao->product_id;
         }
     }
     if ($premiumId) {
         require_once 'CRM/Contribute/DAO/Product.php';
         $productDAO =& new CRM_Contribute_DAO_Product();
         $productDAO->id = $productID;
         $productDAO->find(true);
         $this->assign('premium', $productDAO->name);
         $this->assign('option', $dao->product_option);
         $this->assign('fulfilled', $dao->fulfilled_date);
     }
     $this->assign($values);
 }
Beispiel #2
0
 /**
  * Set variables up before form is built.
  *
  * @return void
  */
 public function preProcess()
 {
     $id = $this->get('id');
     $values = $ids = array();
     $params = array('id' => $id);
     $context = CRM_Utils_Request::retrieve('context', 'String', $this);
     $this->assign('context', $context);
     CRM_Contribute_BAO_Contribution::getValues($params, $values, $ids);
     CRM_Contribute_BAO_Contribution::resolveDefaults($values);
     $cancelledStatus = TRUE;
     $status = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     if (CRM_Utils_Array::value('contribution_status_id', $values) == array_search('Cancelled', $status)) {
         $cancelledStatus = FALSE;
     }
     $this->assign('cancelledStatus', $cancelledStatus);
     if (!empty($values['contribution_page_id'])) {
         $contribPages = CRM_Contribute_PseudoConstant::contributionPage(NULL, TRUE);
         $values['contribution_page_title'] = CRM_Utils_Array::value(CRM_Utils_Array::value('contribution_page_id', $values), $contribPages);
     }
     // get recieved into i.e to_financial_account_id from last trxn
     $financialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($values['contribution_id'], 'DESC');
     $values['to_financial_account'] = '';
     if (!empty($financialTrxnId['financialTrxnId'])) {
         $values['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $financialTrxnId['financialTrxnId'], 'to_financial_account_id');
         if ($values['to_financial_account_id']) {
             $values['to_financial_account'] = CRM_Contribute_PseudoConstant::financialAccount($values['to_financial_account_id']);
         }
         $values['payment_processor_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $financialTrxnId['financialTrxnId'], 'payment_processor_id');
         if ($values['payment_processor_id']) {
             $values['payment_processor_name'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessor', $values['payment_processor_id'], 'name');
         }
     }
     if (!empty($values['contribution_recur_id'])) {
         $sql = "SELECT  installments, frequency_interval, frequency_unit FROM civicrm_contribution_recur WHERE id = %1";
         $params = array(1 => array($values['contribution_recur_id'], 'Integer'));
         $dao = CRM_Core_DAO::executeQuery($sql, $params);
         if ($dao->fetch()) {
             $values['recur_installments'] = $dao->installments;
             $values['recur_frequency_unit'] = $dao->frequency_unit;
             $values['recur_frequency_interval'] = $dao->frequency_interval;
         }
     }
     $groupTree = CRM_Core_BAO_CustomGroup::getTree('Contribution', $this, $id, 0, CRM_Utils_Array::value('financial_type_id', $values));
     CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree);
     $premiumId = NULL;
     if ($id) {
         $dao = new CRM_Contribute_DAO_ContributionProduct();
         $dao->contribution_id = $id;
         if ($dao->find(TRUE)) {
             $premiumId = $dao->id;
             $productID = $dao->product_id;
         }
     }
     if ($premiumId) {
         $productDAO = new CRM_Contribute_DAO_Product();
         $productDAO->id = $productID;
         $productDAO->find(TRUE);
         $this->assign('premium', $productDAO->name);
         $this->assign('option', $dao->product_option);
         $this->assign('fulfilled', $dao->fulfilled_date);
     }
     // Get Note
     $noteValue = CRM_Core_BAO_Note::getNote(CRM_Utils_Array::value('id', $values), 'civicrm_contribution');
     $values['note'] = array_values($noteValue);
     // show billing address location details, if exists
     if (!empty($values['address_id'])) {
         $addressParams = array('id' => CRM_Utils_Array::value('address_id', $values));
         $addressDetails = CRM_Core_BAO_Address::getValues($addressParams, FALSE, 'id');
         $addressDetails = array_values($addressDetails);
         $values['billing_address'] = $addressDetails[0]['display'];
     }
     //assign soft credit record if exists.
     $SCRecords = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($values['contribution_id'], TRUE);
     if (!empty($SCRecords['soft_credit'])) {
         $this->assign('softContributions', $SCRecords['soft_credit']);
         unset($SCRecords['soft_credit']);
     }
     //assign pcp record if exists
     foreach ($SCRecords as $name => $value) {
         $this->assign($name, $value);
     }
     $lineItems = array();
     if ($id) {
         $lineItem = CRM_Price_BAO_LineItem::getLineItems($id, 'contribution', 1, TRUE, TRUE);
         if (!empty($lineItem)) {
             $lineItems[] = $lineItem;
         }
     }
     $this->assign('lineItem', empty($lineItems) ? FALSE : $lineItems);
     $values['totalAmount'] = $values['total_amount'];
     //do check for campaigns
     if ($campaignId = CRM_Utils_Array::value('campaign_id', $values)) {
         $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId);
         $values['campaign'] = $campaigns[$campaignId];
     }
     // assign values to the template
     $this->assign($values);
     $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
     $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
     $this->assign('invoicing', $invoicing);
     if ($invoicing && isset($values['tax_amount'])) {
         $this->assign('totalTaxAmount', $values['tax_amount']);
     }
     $displayName = CRM_Contact_BAO_Contact::displayName($values['contact_id']);
     $this->assign('displayName', $displayName);
     // Check if this is default domain contact CRM-10482
     if (CRM_Contact_BAO_Contact::checkDomainContact($values['contact_id'])) {
         $displayName .= ' (' . ts('default organization') . ')';
     }
     // omitting contactImage from title for now since the summary overlay css doesn't work outside of our crm-container
     CRM_Utils_System::setTitle(ts('View Contribution from') . ' ' . $displayName);
     // add viewed contribution to recent items list
     $url = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=view&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home");
     $title = $displayName . ' - (' . CRM_Utils_Money::format($values['total_amount']) . ' ' . ' - ' . $values['financial_type'] . ')';
     $recentOther = array();
     if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::UPDATE)) {
         $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=update&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home");
     }
     if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::DELETE)) {
         $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=delete&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home");
     }
     CRM_Utils_Recent::add($title, $url, $values['id'], 'Contribution', $values['contact_id'], NULL, $recentOther);
 }
 /**
  * Check tax amount.
  *
  * @param array $params
  * @param bool $isLineItem
  *
  * @return mixed
  */
 public static function checkTaxAmount($params, $isLineItem = FALSE)
 {
     $taxRates = CRM_Core_PseudoConstant::getTaxRates();
     // Update contribution.
     if (!empty($params['id'])) {
         $id = $params['id'];
         $values = $ids = array();
         $contrbutionParams = array('id' => $id);
         $prevContributionValue = CRM_Contribute_BAO_Contribution::getValues($contrbutionParams, $values, $ids);
         // To assign pervious finantial type on update of contribution
         if (!isset($params['financial_type_id'])) {
             $params['financial_type_id'] = $prevContributionValue->financial_type_id;
         } elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
             // Assisn tax Amount on update of contrbution
             if (!empty($prevContributionValue->tax_amount)) {
                 $params['tax_amount'] = 'null';
                 CRM_Price_BAO_LineItem::getLineItemArray($params, array($params['id']));
                 foreach ($params['line_item'] as $setID => $priceField) {
                     foreach ($priceField as $priceFieldID => $priceFieldValue) {
                         $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
                     }
                 }
             }
         }
     }
     // New Contrbution and update of contribution with tax rate financial type
     if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && empty($params['skipLineItem']) && !$isLineItem) {
         $taxRateParams = $taxRates[$params['financial_type_id']];
         $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($params['total_amount'], $taxRateParams);
         $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
         // Get Line Item on update of contribution
         if (isset($params['id'])) {
             CRM_Price_BAO_LineItem::getLineItemArray($params, array($params['id']));
         } else {
             CRM_Price_BAO_LineItem::getLineItemArray($params);
         }
         foreach ($params['line_item'] as $setID => $priceField) {
             foreach ($priceField as $priceFieldID => $priceFieldValue) {
                 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
             }
         }
         $params['total_amount'] = $params['total_amount'] + $params['tax_amount'];
     } elseif (isset($params['api.line_item.create'])) {
         // Update total amount of contribution using lineItem
         $taxAmountArray = array();
         foreach ($params['api.line_item.create'] as $key => $value) {
             if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
                 $taxRate = $taxRates[$value['financial_type_id']];
                 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($value['line_total'], $taxRate);
                 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
             }
         }
         $params['tax_amount'] = array_sum($taxAmountArray);
         $params['total_amount'] = $params['total_amount'] + $params['tax_amount'];
     } else {
         // update line item of contrbution
         if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
             $taxRate = $taxRates[$params['financial_type_id']];
             $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($params['line_total'], $taxRate);
             $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
         }
     }
     return $params;
 }
Beispiel #4
0
 /**  
  * Function to set variables up before form is built  
  *                                                            
  * @return void  
  * @access public  
  */
 public function preProcess()
 {
     $id = $this->get('id');
     $values = $ids = array();
     $params = array('id' => $id);
     require_once 'CRM/Contribute/BAO/Contribution.php';
     CRM_Contribute_BAO_Contribution::getValues($params, $values, $ids);
     $softParams = array('contribution_id' => $values['contribution_id']);
     if ($softContribution = CRM_Contribute_BAO_Contribution::getSoftContribution($softParams, true)) {
         $values = array_merge($values, $softContribution);
     }
     CRM_Contribute_BAO_Contribution::resolveDefaults($values);
     if (CRM_Utils_Array::value('honor_contact_id', $values)) {
         $sql = "SELECT display_name FROM civicrm_contact WHERE id = %1";
         $params = array(1 => array($values['honor_contact_id'], 'Integer'));
         $dao = CRM_Core_DAO::executeQuery($sql, $params);
         if ($dao->fetch()) {
             $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$values['honor_contact_id']}");
             $values["honor_display"] = "<A href = {$url}>" . $dao->display_name . "</A>";
         }
         $honor = CRM_Core_PseudoConstant::honor();
         $values['honor_type'] = $honor[$values['honor_type_id']];
     }
     if (CRM_Utils_Array::value('contribution_recur_id', $values)) {
         $sql = "SELECT  installments, frequency_interval, frequency_unit FROM civicrm_contribution_recur WHERE id = %1";
         $params = array(1 => array($values['contribution_recur_id'], 'Integer'));
         $dao = CRM_Core_DAO::executeQuery($sql, $params);
         if ($dao->fetch()) {
             $values["recur_installments"] = $dao->installments;
             $values["recur_frequency_unit"] = $dao->frequency_unit;
             $values["recur_frequency_interval"] = $dao->frequency_interval;
         }
     }
     $groupTree =& CRM_Core_BAO_CustomGroup::getTree('Contribution', $this, $id, 0, $values['contribution_type_id']);
     CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree);
     $premiumId = null;
     if ($id) {
         require_once 'CRM/Contribute/DAO/ContributionProduct.php';
         $dao =& new CRM_Contribute_DAO_ContributionProduct();
         $dao->contribution_id = $id;
         if ($dao->find(true)) {
             $premiumId = $dao->id;
             $productID = $dao->product_id;
         }
     }
     if ($premiumId) {
         require_once 'CRM/Contribute/DAO/Product.php';
         $productDAO =& new CRM_Contribute_DAO_Product();
         $productDAO->id = $productID;
         $productDAO->find(true);
         $this->assign('premium', $productDAO->name);
         $this->assign('option', $dao->product_option);
         $this->assign('fulfilled', $dao->fulfilled_date);
     }
     // Get Note
     $noteValue = CRM_Core_BAO_Note::getNote($values['id'], 'civicrm_contribution');
     $values['note'] = array_values($noteValue);
     // show billing address location details, if exists
     if (CRM_Utils_Array::value('address_id', $values)) {
         $addressParams = array('id' => CRM_Utils_Array::value('address_id', $values));
         $addressDetails = CRM_Core_BAO_Address::getValues($addressParams, false, 'id');
         $addressDetails = array_values($addressDetails);
         $values['billing_address'] = $addressDetails[0]['display'];
     }
     //get soft credit record if exists.
     if ($softContribution = CRM_Contribute_BAO_Contribution::getSoftContribution($softParams)) {
         $softContribution['softCreditToName'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $softContribution['soft_credit_to'], 'display_name');
         //hack to avoid dispalyName conflict
         //for viewing softcredit record.
         $softContribution['displayName'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $values['contact_id'], 'display_name');
         $values = array_merge($values, $softContribution);
     }
     require_once 'CRM/Price/BAO/Set.php';
     $lineItems = array();
     if ($id && CRM_Price_BAO_Set::getFor('civicrm_contribution', $id)) {
         require_once 'CRM/Price/BAO/LineItem.php';
         $lineItems[] = CRM_Price_BAO_LineItem::getLineItems($id, 'contribution');
     }
     $this->assign('lineItem', empty($lineItems) ? false : $lineItems);
     $values['totalAmount'] = $values['total_amount'];
     // assign values to the template
     $this->assign($values);
     // add viewed contribution to recent items list
     require_once 'CRM/Utils/Recent.php';
     require_once 'CRM/Utils/Money.php';
     require_once 'CRM/Contact/BAO/Contact.php';
     $url = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=view&reset=1&id={$values['id']}&cid={$values['contact_id']}");
     $title = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $values['contact_id'], 'display_name') . ' - (' . CRM_Utils_Money::format($values['total_amount']) . ' ' . ' - ' . $values['contribution_type'] . ')';
     CRM_Utils_Recent::add($title, $url, $values['id'], 'Contribution', $values['contact_id'], null);
 }
 function setDefaultValues()
 {
     $defaults = array();
     if ($this->_action & CRM_CORE_ACTION_DELETE) {
         return $defaults;
     }
     if ($this->_id) {
         $ids = array();
         $params = array('id' => $this->_id);
         CRM_Contribute_BAO_Contribution::getValues($params, $defaults, $ids);
         $this->_contactID = $defaults['contact_id'];
     } else {
         $now = date("Y-m-d");
         $defaults['receive_date'] = $now;
     }
     if (isset($this->_groupTree)) {
         CRM_Core_BAO_CustomGroup::setDefaults($this->_groupTree, $defaults, false, false);
     }
     $this->assign('showOption', true);
     // for Premium section
     if ($this->_premiumId) {
         $this->assign('showOption', false);
         require_once 'CRM/Contribute/DAO/ContributionProduct.php';
         $dao =& new CRM_Contribute_DAO_ContributionProduct();
         $dao->id = $this->_premiumId;
         $dao->find(true);
         //if($this->_options[$dao->product_id];)
         $options = $this->_options[$dao->product_id];
         if (!$options) {
             $this->assign('showOption', true);
         }
         $options_key = CRM_Utils_Array::key($dao->product_option, $options);
         if ($options_key) {
             $defaults['product_name'] = array($dao->product_id, trim($options_key));
         } else {
             $defaults['product_name'] = array($dao->product_id);
         }
         $defaults['fulfilled_date'] = $dao->fulfilled_date;
     }
     return $defaults;
 }
/**
 * Get an existing contribution.
 *
 * Returns a single existing Contribution object which matches ALL property
 * values passed in $params. An error object is returned if there is
 * no match, or more than one match. This API can be used to retrieve
 * the CRM internal identifier (contribution_id) based on a unique property.
 * It can also be used to retrieve any desired
 * contribution properties based on a known contribution_id.
 *
 * @param array $params           Associative array of property name/value
 *                                pairs to attempt to match on.
 * @param array $returnProperties Which properties should be included in the
 *                                returned Contribution object. If NULL, the default
 *                                set of properties will be included.
 *
 * @return CRM_Contribution|CRM_Core_Error  Return the Contribution Object if found, else
 *                                Error Object
 *
 * @access public
 *
 */
function &crm_get_contribution($params, $returnProperties = null)
{
    _crm_initialize();
    // empty parameters ?
    if (empty($params)) {
        return _crm_error('$params is empty');
    }
    // correct parameter format ?
    if (!is_array($params)) {
        return _crm_error('$params is not an array');
    }
    if (!CRM_Utils_Array::value('contribution_id', $params)) {
        $returnProperties = array('trxn_id');
        $contributions = crm_contribution_search($params, $returnProperties);
        if (count($contributions) != 1) {
            return _crm_error(count($contributions) . " contributions matching input params.");
        }
        $contributionIds = array_keys($contributions);
        $params['contribution_id'] = $contributionIds[0];
    }
    $params['id'] = $params['contribution_id'];
    $ids = array();
    $contribution =& CRM_Contribute_BAO_Contribution::getValues($params, $defaults, $ids);
    if ($contribution == null || is_a($contribution, 'CRM_Core_Error') || !$contribution->id) {
        return _crm_error('Did not find contribution object for ' . $params['contribution_id']);
    }
    unset($params['id']);
    $contribution->contribution_type_object = CRM_Contribute_BAO_Contribution::getValues($params, $defaults, $ids);
    $contribution->custom_values =& CRM_Core_BAO_CustomValue::getContributionValues($contribution->id);
    return $contribution;
}
 /**
  * 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);
         $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, 'total_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;
 }
Beispiel #8
0
 /**
  * Set default values for the form. MobileProvider that in edit/view mode
  * the default values are retrieved from the database
  *
  *
  * @return void
  */
 public function setDefaultValues()
 {
     if ($this->_cdType) {
         return CRM_Custom_Form_CustomData::setDefaultValues($this);
     }
     if ($this->_priceSetId) {
         return CRM_Price_BAO_PriceSet::setDefaultPriceSet($this, $defaults);
     }
     $defaults = parent::setDefaultValues();
     //setting default join date and receive date
     list($now, $currentTime) = CRM_Utils_Date::setDateDefaults();
     if ($this->_action == CRM_Core_Action::ADD) {
         $defaults['receive_date'] = $now;
         $defaults['receive_date_time'] = $currentTime;
     }
     if (is_numeric($this->_memType)) {
         $defaults['membership_type_id'] = array();
         $defaults['membership_type_id'][0] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'member_of_contact_id', 'id');
         $defaults['membership_type_id'][1] = $this->_memType;
     } else {
         $defaults['membership_type_id'] = $this->_memType;
     }
     $defaults['num_terms'] = 1;
     if (!empty($defaults['id'])) {
         if ($this->_onlinePendingContributionId) {
             $defaults['record_contribution'] = $this->_onlinePendingContributionId;
         } else {
             $contributionId = CRM_Core_DAO::singleValueQuery("\n  SELECT contribution_id\n  FROM civicrm_membership_payment\n  WHERE membership_id = {$this->_id}\n  ORDER BY contribution_id\n  DESC limit 1");
             if ($contributionId) {
                 $defaults['record_contribution'] = $contributionId;
             }
         }
     }
     //set Soft Credit Type to Gift by default
     $scTypes = CRM_Core_OptionGroup::values("soft_credit_type");
     $defaults['soft_credit_type_id'] = CRM_Utils_Array::value(ts('Gift'), array_flip($scTypes));
     if (!empty($defaults['record_contribution']) && !$this->_mode) {
         $contributionParams = array('id' => $defaults['record_contribution']);
         $contributionIds = array();
         //keep main object campaign in hand.
         $memberCampaignId = CRM_Utils_Array::value('campaign_id', $defaults);
         CRM_Contribute_BAO_Contribution::getValues($contributionParams, $defaults, $contributionIds);
         //get back original object campaign id.
         $defaults['campaign_id'] = $memberCampaignId;
         if (!empty($defaults['receive_date'])) {
             list($defaults['receive_date']) = CRM_Utils_Date::setDateDefaults($defaults['receive_date']);
         }
         // Contribution::getValues() over-writes the membership record's source field value - so we need to restore it.
         if (!empty($defaults['membership_source'])) {
             $defaults['source'] = $defaults['membership_source'];
         }
     }
     //CRM-13420
     if (empty($defaults['payment_instrument_id'])) {
         $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
     }
     // User must explicitly choose to send a receipt in both add and update mode.
     $defaults['send_receipt'] = 0;
     if ($this->_action & CRM_Core_Action::UPDATE) {
         // in this mode by default uncheck this checkbox
         unset($defaults['record_contribution']);
     }
     if (!empty($defaults['id'])) {
         $subscriptionCancelled = CRM_Member_BAO_Membership::isSubscriptionCancelled($this->_id);
     }
     $alreadyAutoRenew = FALSE;
     if (!empty($defaults['contribution_recur_id']) && !$subscriptionCancelled) {
         $defaults['auto_renew'] = 1;
         $alreadyAutoRenew = TRUE;
     }
     $this->assign('alreadyAutoRenew', $alreadyAutoRenew);
     $this->assign('member_is_test', CRM_Utils_Array::value('member_is_test', $defaults));
     $this->assign('membership_status_id', CRM_Utils_Array::value('status_id', $defaults));
     if (!empty($defaults['is_pay_later'])) {
         $this->assign('is_pay_later', TRUE);
     }
     if ($this->_mode) {
         // set default country from config if no country set
         $config = CRM_Core_Config::singleton();
         if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
             $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry;
         }
         if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
             $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince;
         }
         $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID);
         $defaults = array_merge($defaults, $billingDefaults);
         //             // hack to simplify credit card entry for testing
         //             $defaults['credit_card_type']     = 'Visa';
         //             $defaults['credit_card_number']   = '4807731747657838';
         //             $defaults['cvv2']                 = '000';
         //             $defaults['credit_card_exp_date'] = array( 'Y' => '2012', 'M' => '05' );
     }
     $dates = array('join_date', 'start_date', 'end_date');
     foreach ($dates as $key) {
         if (!empty($defaults[$key])) {
             list($defaults[$key]) = CRM_Utils_Date::setDateDefaults(CRM_Utils_Array::value($key, $defaults));
         }
     }
     //setting default join date if there is no join date
     if (empty($defaults['join_date'])) {
         $defaults['join_date'] = $now;
     }
     if (!empty($defaults['membership_end_date'])) {
         $this->assign('endDate', $defaults['membership_end_date']);
     }
     return $defaults;
 }
 /**
  * Function to set variables up before form is built
  *
  * @return void
  * @access public
  */
 public function preProcess()
 {
     $id = $this->get('id');
     $values = $ids = array();
     $params = array('id' => $id);
     $context = CRM_Utils_Request::retrieve('context', 'String', $this);
     $this->assign('context', $context);
     CRM_Contribute_BAO_Contribution::getValues($params, $values, $ids);
     $softParams = array('contribution_id' => $values['contribution_id']);
     if ($softContribution = CRM_Contribute_BAO_Contribution::getSoftContribution($softParams, TRUE)) {
         $values = array_merge($values, $softContribution);
     }
     CRM_Contribute_BAO_Contribution::resolveDefaults($values);
     if (CRM_Utils_Array::value('contribution_page_id', $values)) {
         $contribPages = CRM_Contribute_PseudoConstant::contributionPage(NULL, TRUE);
         $values['contribution_page_title'] = CRM_Utils_Array::value(CRM_Utils_Array::value('contribution_page_id', $values), $contribPages);
     }
     if (CRM_Utils_Array::value('honor_contact_id', $values)) {
         $sql = "SELECT display_name FROM civicrm_contact WHERE id = %1";
         $params = array(1 => array($values['honor_contact_id'], 'Integer'));
         $dao = CRM_Core_DAO::executeQuery($sql, $params);
         if ($dao->fetch()) {
             $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$values['honor_contact_id']}");
             $values['honor_display'] = "<A href = {$url}>" . $dao->display_name . "</A>";
         }
         $honor = CRM_Core_PseudoConstant::honor();
         $values['honor_type'] = CRM_Utils_Array::value(CRM_Utils_Array::value('honor_type_id', $values), $honor);
     }
     if (CRM_Utils_Array::value('contribution_recur_id', $values)) {
         $sql = "SELECT  installments, frequency_interval, frequency_unit FROM civicrm_contribution_recur WHERE id = %1";
         $params = array(1 => array($values['contribution_recur_id'], 'Integer'));
         $dao = CRM_Core_DAO::executeQuery($sql, $params);
         if ($dao->fetch()) {
             $values['recur_installments'] = $dao->installments;
             $values['recur_frequency_unit'] = $dao->frequency_unit;
             $values['recur_frequency_interval'] = $dao->frequency_interval;
         }
     }
     $groupTree = CRM_Core_BAO_CustomGroup::getTree('Contribution', $this, $id, 0, $values['contribution_type_id']);
     CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree);
     $premiumId = NULL;
     if ($id) {
         $dao = new CRM_Contribute_DAO_ContributionProduct();
         $dao->contribution_id = $id;
         if ($dao->find(TRUE)) {
             $premiumId = $dao->id;
             $productID = $dao->product_id;
         }
     }
     if ($premiumId) {
         $productDAO = new CRM_Contribute_DAO_Product();
         $productDAO->id = $productID;
         $productDAO->find(TRUE);
         $this->assign('premium', $productDAO->name);
         $this->assign('option', $dao->product_option);
         $this->assign('fulfilled', $dao->fulfilled_date);
     }
     // Get Note
     $noteValue = CRM_Core_BAO_Note::getNote($values['id'], 'civicrm_contribution');
     $values['note'] = array_values($noteValue);
     // show billing address location details, if exists
     if (CRM_Utils_Array::value('address_id', $values)) {
         $addressParams = array('id' => CRM_Utils_Array::value('address_id', $values));
         $addressDetails = CRM_Core_BAO_Address::getValues($addressParams, FALSE, 'id');
         $addressDetails = array_values($addressDetails);
         $values['billing_address'] = $addressDetails[0]['display'];
     }
     //get soft credit record if exists.
     if ($softContribution = CRM_Contribute_BAO_Contribution::getSoftContribution($softParams)) {
         $softContribution['softCreditToName'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $softContribution['soft_credit_to'], 'display_name');
         //hack to avoid dispalyName conflict
         //for viewing softcredit record.
         $softContribution['displayName'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $values['contact_id'], 'display_name');
         $values = array_merge($values, $softContribution);
     }
     $lineItems = array();
     if ($id) {
         $lineItem = CRM_Price_BAO_LineItem::getLineItems($id, 'contribution', 1);
         empty($lineItem) ? null : ($lineItems[] = $lineItem);
     }
     $this->assign('lineItem', empty($lineItems) ? FALSE : $lineItems);
     $values['totalAmount'] = $values['total_amount'];
     //do check for campaigns
     if ($campaignId = CRM_Utils_Array::value('campaign_id', $values)) {
         $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId);
         $values['campaign'] = $campaigns[$campaignId];
     }
     // assign values to the template
     $this->assign($values);
     // add viewed contribution to recent items list
     $url = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=view&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home");
     $displayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $values['contact_id'], 'display_name');
     $this->assign('displayName', $displayName);
     $title = $displayName . ' - (' . CRM_Utils_Money::format($values['total_amount']) . ' ' . ' - ' . $values['contribution_type'] . ')';
     $recentOther = array();
     if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::UPDATE)) {
         $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=update&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home");
     }
     if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::DELETE)) {
         $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=delete&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home");
     }
     CRM_Utils_Recent::add($title, $url, $values['id'], 'Contribution', $values['contact_id'], NULL, $recentOther);
 }
 /**
  * @param $updatedAmount
  * @param $paidAmount
  * @param $contributionId
  */
 static function recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId)
 {
     $balanceAmt = $updatedAmount - $paidAmount;
     $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
     $pendngRefundStatusId = array_search('Pending refund', $contributionStatuses);
     $completedStatusId = array_search('Completed', $contributionStatuses);
     $updatedContributionDAO = new CRM_Contribute_BAO_Contribution();
     if ($balanceAmt) {
         if ($balanceAmt > 0 && $paidAmount != 0) {
             $contributionStatusVal = $partiallyPaidStatusId;
         } elseif ($balanceAmt < 0 && $paidAmount != 0) {
             $contributionStatusVal = $pendngRefundStatusId;
         } elseif ($paidAmount == 0) {
             $contributionStatusVal = $completedStatusId;
             $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;
         $updatedContributionDAO->contribution_status_id = $contributionStatusVal;
         $updatedContributionDAO->total_amount = $updatedAmount;
         $updatedContributionDAO->save();
         $ftDetail = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId);
         // adjusted amount financial_trxn creation
         if (empty($ftDetail['trxn_id'])) {
             $updatedContribution = CRM_Contribute_BAO_Contribution::getValues(array('id' => $contributionId), CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
             $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, 'total_amount' => $balanceAmt, 'status_id' => CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name'), '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);
         } else {
             // update the financial trxn amount as well, as the fee selections has been updated
             if ($balanceAmt != $ftDetail['total_amount']) {
                 CRM_Core_DAO::setFieldValue('CRM_Core_BAO_FinancialTrxn', $ftDetail['trxn_id'], 'total_amount', $balanceAmt);
             }
         }
     }
 }
Beispiel #11
0
 /**
  * Complete an order.
  *
  * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
  *
  * Currently overloaded to complete a transaction & repeat a transaction - fix!
  *
  * Moving it out of the BaseIPN class is just the first step.
  *
  * @param array $input
  * @param array $ids
  * @param array $objects
  * @param CRM_Core_Transaction $transaction
  * @param int $recur
  * @param CRM_Contribute_BAO_Contribution $contribution
  * @param bool $isRecurring
  *   Duplication of param needs review. Only used by AuthorizeNetIPN
  * @param int $isFirstOrLastRecurringPayment
  *   Deprecated param only used by AuthorizeNetIPN.
  */
 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution, $isRecurring, $isFirstOrLastRecurringPayment)
 {
     $primaryContributionID = isset($contribution->id) ? $contribution->id : $objects['first_contribution']->id;
     // The previous details are used when calculating line items so keep it before any code that 'does something'
     if (!empty($contribution->id)) {
         $input['prevContribution'] = CRM_Contribute_BAO_Contribution::getValues(array('id' => $contribution->id), CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
     }
     $inputContributionWhiteList = array('fee_amount', 'net_amount', 'trxn_id', 'check_number', 'payment_instrument_id', 'is_test', 'campaign_id', 'receive_date', 'receipt_date', 'contribution_status_id');
     if (self::isSingleLineItem($primaryContributionID)) {
         $inputContributionWhiteList[] = 'financial_type_id';
     }
     $participant = CRM_Utils_Array::value('participant', $objects);
     $memberships = CRM_Utils_Array::value('membership', $objects);
     $recurContrib = CRM_Utils_Array::value('contributionRecur', $objects);
     $recurringContributionID = empty($recurContrib->id) ? NULL : $recurContrib->id;
     $event = CRM_Utils_Array::value('event', $objects);
     $paymentProcessorId = '';
     if (isset($objects['paymentProcessor'])) {
         if (is_array($objects['paymentProcessor'])) {
             $paymentProcessorId = $objects['paymentProcessor']['id'];
         } else {
             $paymentProcessorId = $objects['paymentProcessor']->id;
         }
     }
     $completedContributionStatusID = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
     $contributionParams = array_merge(array('contribution_status_id' => $completedContributionStatusID, 'source' => self::getRecurringContributionDescription($contribution, $event)), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)));
     $contributionParams['payment_processor'] = $input['payment_processor'] = $paymentProcessorId;
     if ($recurringContributionID) {
         $contributionParams['contribution_recur_id'] = $recurringContributionID;
     }
     $changeDate = CRM_Utils_Array::value('trxn_date', $input, date('YmdHis'));
     if (empty($contributionParams['receive_date']) && $changeDate) {
         $contributionParams['receive_date'] = $changeDate;
     }
     self::repeatTransaction($contribution, $input, $contributionParams, $paymentProcessorId);
     $contributionParams['financial_type_id'] = $contribution->financial_type_id;
     if (is_numeric($memberships)) {
         $memberships = array($objects['membership']);
     }
     $values = array();
     if (isset($input['is_email_receipt'])) {
         $values['is_email_receipt'] = $input['is_email_receipt'];
     }
     if ($input['component'] == 'contribute') {
         if ($contribution->contribution_page_id) {
             // Figure out what we gain from this.
             CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values);
         } elseif ($recurContrib && $recurringContributionID) {
             $values['amount'] = $recurContrib->amount;
             $values['financial_type_id'] = $objects['contributionType']->id;
             $values['title'] = $source = ts('Offline Recurring Contribution');
         }
         if ($recurContrib && $recurringContributionID && !isset($input['is_email_receipt'])) {
             //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
             // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
             $values['is_email_receipt'] = $recurContrib->is_email_receipt;
         }
         if (!empty($memberships)) {
             foreach ($memberships as $membershipTypeIdKey => $membership) {
                 if ($membership) {
                     $membershipParams = array('id' => $membership->id, 'contact_id' => $membership->contact_id, 'is_test' => $membership->is_test, 'membership_type_id' => $membership->membership_type_id);
                     $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membershipParams['contact_id'], $membershipParams['membership_type_id'], $membershipParams['is_test'], $membershipParams['id']);
                     // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
                     // this picks up membership type changes during renewals
                     $sql = "\nSELECT    membership_type_id\nFROM      civicrm_membership_log\nWHERE     membership_id={$membershipParams['id']}\nORDER BY  id DESC\nLIMIT 1;";
                     $dao = CRM_Core_DAO::executeQuery($sql);
                     if ($dao->fetch()) {
                         if (!empty($dao->membership_type_id)) {
                             $membershipParams['membership_type_id'] = $dao->membership_type_id;
                         }
                     }
                     $dao->free();
                     $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType($membershipParams['membership_type_id'], $primaryContributionID);
                     $dates = array_fill_keys(array('join_date', 'start_date', 'end_date'), NULL);
                     if ($currentMembership) {
                         /*
                          * Fixed FOR CRM-4433
                          * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
                          * when Contribution mode is notify and membership is for renewal )
                          */
                         CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
                         // @todo - we should pass membership_type_id instead of null here but not
                         // adding as not sure of testing
                         $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membershipParams['id'], $changeDate, NULL, $membershipParams['num_terms']);
                         $dates['join_date'] = $currentMembership['join_date'];
                     }
                     //get the status for membership.
                     $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], $dates['end_date'], $dates['join_date'], 'today', TRUE, $membershipParams['membership_type_id'], $membershipParams);
                     $membershipParams['status_id'] = CRM_Utils_Array::value('id', $calcStatus, 'New');
                     //we might be renewing membership,
                     //so make status override false.
                     $membershipParams['is_override'] = FALSE;
                     //CRM-17723 - reset static $relatedContactIds array()
                     $var = TRUE;
                     CRM_Member_BAO_Membership::createRelatedMemberships($var, $var, TRUE);
                     civicrm_api3('Membership', 'create', $membershipParams);
                 }
             }
         }
     } else {
         if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
             if ($event->is_email_confirm) {
                 // @todo this should be set by the function that sends the mail after sending.
                 $contributionParams['receipt_date'] = $changeDate;
             }
             $participantParams['id'] = $participant->id;
             $participantParams['status_id'] = 'Registered';
             civicrm_api3('Participant', 'create', $participantParams);
         }
     }
     $contributionParams['id'] = $contribution->id;
     // CRM-19309 - if you update the contribution here with financial_type_id it can/will mess with $lineItem
     // unsetting it here does NOT cause any other contribution test to fail!
     unset($contributionParams['financial_type_id']);
     $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
     // Add new soft credit against current $contribution.
     if (CRM_Utils_Array::value('contributionRecur', $objects) && $objects['contributionRecur']->id) {
         CRM_Contribute_BAO_ContributionRecur::addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id);
     }
     $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array('labelColumn' => 'name', 'flip' => 1));
     if (isset($input['prevContribution']) && (!$input['prevContribution']->is_pay_later && $input['prevContribution']->contribution_status_id == $contributionStatuses['Pending'])) {
         $input['payment_processor'] = $paymentProcessorId;
     }
     if (!empty($contribution->_relatedObjects['participant'])) {
         $input['contribution_mode'] = 'participant';
         $input['participant_id'] = $contribution->_relatedObjects['participant']->id;
     } elseif (!empty($contribution->_relatedObjects['membership'])) {
         $input['contribution_mode'] = 'membership';
         $contribution->contribution_status_id = $contributionParams['contribution_status_id'];
         $contribution->trxn_id = CRM_Utils_Array::value('trxn_id', $input);
         $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
     }
     CRM_Core_Error::debug_log_message("Contribution record updated successfully");
     $transaction->commit();
     CRM_Contribute_BAO_ContributionRecur::updateRecurLinkedPledge($contribution->id, $recurringContributionID, $contributionParams['contribution_status_id'], $input['amount']);
     // create an activity record
     if ($input['component'] == 'contribute') {
         //CRM-4027
         $targetContactID = NULL;
         if (!empty($ids['related_contact'])) {
             $targetContactID = $contribution->contact_id;
             $contribution->contact_id = $ids['related_contact'];
         }
         CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
         // event
     } else {
         CRM_Activity_BAO_Activity::addActivity($participant);
     }
     // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
     // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
     if (!array_key_exists('is_email_receipt', $values) || $values['is_email_receipt'] == 1) {
         civicrm_api3('Contribution', 'sendconfirmation', array('id' => $contribution->id, 'payment_processor_id' => $paymentProcessorId));
         CRM_Core_Error::debug_log_message("Receipt sent");
     }
     CRM_Core_Error::debug_log_message("Success: Database updated");
     if ($isRecurring) {
         CRM_Contribute_BAO_ContributionRecur::sendRecurringStartOrEndNotification($ids, $recur, $isFirstOrLastRecurringPayment);
     }
     return $contributionResult;
 }
Beispiel #12
0
 /**
  * This function sets the default values for the form. MobileProvider that in edit/view mode
  * the default values are retrieved from the database
  * 
  * @access public
  * @return None
  */
 public function setDefaultValues()
 {
     if ($this->_cdType) {
         return CRM_Custom_Form_CustomData::setDefaultValues($this);
     }
     $defaults = array();
     $defaults =& parent::setDefaultValues();
     //setting default join date and receive date
     list($now) = CRM_Utils_Date::setDateDefaults();
     if ($this->_action == CRM_Core_Action::ADD) {
         $defaults['receive_date'] = $now;
     }
     if (is_numeric($this->_memType)) {
         $defaults["membership_type_id"] = array();
         $defaults["membership_type_id"][0] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'member_of_contact_id', 'id');
         $defaults["membership_type_id"][1] = $this->_memType;
     } else {
         $defaults["membership_type_id"] = $this->_memType;
     }
     if (CRM_Utils_Array::value('id', $defaults)) {
         if ($this->_onlinePendingContributionId) {
             $defaults['record_contribution'] = $this->_onlinePendingContributionId;
         } else {
             $defaults['record_contribution'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $defaults['id'], 'contribution_id', 'membership_id');
         }
     }
     if ($this->_memType) {
         $defaults['contribution_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'contribution_type_id');
         $defaults['total_amount'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'minimum_fee');
     }
     if (CRM_Utils_Array::value('record_contribution', $defaults) && !$this->_mode) {
         $contributionParams = array('id' => $defaults['record_contribution']);
         $contributionIds = array();
         require_once "CRM/Contribute/BAO/Contribution.php";
         CRM_Contribute_BAO_Contribution::getValues($contributionParams, $defaults, $contributionIds);
         // Contribution::getValues() over-writes the membership record's source field value - so we need to restore it.
         if (CRM_Utils_Array::value('membership_source', $defaults)) {
             $defaults['source'] = $defaults['membership_source'];
         }
     }
     // User must explicitly choose to send a receipt in both add and update mode.
     $defaults['send_receipt'] = 0;
     if ($this->_action & CRM_Core_Action::UPDATE) {
         // in this mode by default uncheck this checkbox
         unset($defaults['record_contribution']);
     }
     if ($defaults['membership_type_id'][1]) {
         $defaults['receipt_text_signup'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $defaults['membership_type_id'][1], 'receipt_text_signup');
     }
     $this->assign("member_is_test", CRM_Utils_Array::value('member_is_test', $defaults));
     $this->assign('membership_status_id', CRM_Utils_Array::value('status_id', $defaults));
     if (CRM_Utils_Array::value('is_pay_later', $defaults)) {
         $this->assign('is_pay_later', true);
     }
     if ($this->_mode) {
         $fields = array();
         foreach ($this->_fields as $name => $dontCare) {
             $fields[$name] = 1;
         }
         $names = array("first_name", "middle_name", "last_name", "street_address-{$this->_bltID}", "city-{$this->_bltID}", "postal_code-{$this->_bltID}", "country_id-{$this->_bltID}", "state_province_id-{$this->_bltID}");
         foreach ($names as $name) {
             $fields[$name] = 1;
         }
         $fields["state_province-{$this->_bltID}"] = 1;
         $fields["country-{$this->_bltID}"] = 1;
         $fields["email-{$this->_bltID}"] = 1;
         $fields["email-Primary"] = 1;
         if ($this->_contactID) {
             require_once "CRM/Core/BAO/UFGroup.php";
             CRM_Core_BAO_UFGroup::setProfileDefaults($this->_contactID, $fields, $this->_defaults);
         }
         // use primary email address if billing email address is empty
         if (empty($this->_defaults["email-{$this->_bltID}"]) && !empty($this->_defaults["email-Primary"])) {
             $defaults["email-{$this->_bltID}"] = $this->_defaults["email-Primary"];
         }
         foreach ($names as $name) {
             if (!empty($this->_defaults[$name])) {
                 $defaults["billing_" . $name] = $this->_defaults[$name];
             }
         }
     }
     $dates = array('join_date', 'start_date', 'end_date');
     foreach ($dates as $key) {
         if (CRM_Utils_Array::value($key, $defaults)) {
             list($defaults[$key]) = CRM_Utils_Date::setDateDefaults(CRM_Utils_Array::value($key, $defaults));
         }
     }
     //setting default join date if there is no join date
     if (!CRM_Utils_Array::value('join_date', $defaults)) {
         $defaults['join_date'] = $now;
     }
     return $defaults;
 }
Beispiel #13
0
 /** 
  * Function to set variables up before form is built 
  *                                                           
  * @return void 
  * @access public 
  */
 public function preProcess()
 {
     //check permission for action.
     if (!CRM_Core_Permission::checkActionPermission('CiviContribute', $this->_action)) {
         CRM_Core_Error::fatal(ts('You do not have permission to access this page'));
     }
     $this->_cdType = CRM_Utils_Array::value('type', $_GET);
     $this->assign('cdType', false);
     if ($this->_cdType) {
         $this->assign('cdType', true);
         return CRM_Custom_Form_CustomData::preProcess($this);
     }
     $this->_formType = CRM_Utils_Array::value('formType', $_GET);
     // get price set id.
     $this->_priceSetId = CRM_Utils_Array::value('priceSetId', $_GET);
     $this->set('priceSetId', $this->_priceSetId);
     $this->assign('priceSetId', $this->_priceSetId);
     //get the pledge payment id
     $this->_ppID = CRM_Utils_Request::retrieve('ppid', 'Positive', $this);
     //get the contact id
     $this->_contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
     //get the action.
     $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, false, 'add');
     $this->assign('action', $this->_action);
     //get the contribution id if update
     $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
     $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
     $this->assign('context', $this->_context);
     //set the contribution mode.
     $this->_mode = CRM_Utils_Request::retrieve('mode', 'String', $this);
     $this->assign('contributionMode', $this->_mode);
     $this->_paymentProcessor = array('billing_mode' => 1);
     $this->assign('showCheckNumber', false);
     //ensure that processor has a valid config
     //only valid processors get display to user
     if ($this->_mode) {
         $validProcessors = array();
         $processors = CRM_Core_PseudoConstant::paymentProcessor(false, false, "billing_mode IN ( 1, 3 )");
         foreach ($processors as $ppID => $label) {
             require_once 'CRM/Core/BAO/PaymentProcessor.php';
             require_once 'CRM/Core/Payment.php';
             $paymentProcessor =& CRM_Core_BAO_PaymentProcessor::getPayment($ppID, $this->_mode);
             if ($paymentProcessor['payment_processor_type'] == 'PayPal' && !$paymentProcessor['user_name']) {
                 continue;
             } else {
                 if ($paymentProcessor['payment_processor_type'] == 'Dummy' && $this->_mode == 'live') {
                     continue;
                 } else {
                     $paymentObject =& CRM_Core_Payment::singleton($this->_mode, 'Contribute', $paymentProcessor, $this);
                     $error = $paymentObject->checkConfig();
                     if (empty($error)) {
                         $validProcessors[$ppID] = $label;
                     }
                     $paymentObject = null;
                 }
             }
         }
         if (empty($validProcessors)) {
             CRM_Core_Error::fatal(ts('You will need to configure the %1 settings for your Payment Processor before you can submit credit card transactions.', array(1 => $this->_mode)));
         } else {
             $this->_processors = $validProcessors;
         }
     }
     // this required to show billing block
     $this->assign_by_ref('paymentProcessor', $paymentProcessor);
     $this->assign('hidePayPalExpress', true);
     if ($this->_contactID) {
         require_once 'CRM/Contact/BAO/Contact/Location.php';
         list($this->userDisplayName, $this->userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
         $this->assign('displayName', $this->userDisplayName);
     }
     // also check for billing information
     // get the billing location type
     $locationTypes =& CRM_Core_PseudoConstant::locationType();
     $this->_bltID = array_search('Billing', $locationTypes);
     if (!$this->_bltID) {
         CRM_Core_Error::fatal(ts('Please set a location type of %1', array(1 => 'Billing')));
     }
     $this->set('bltID', $this->_bltID);
     $this->assign('bltID', $this->_bltID);
     $this->_fields = array();
     require_once 'CRM/Core/Payment.php';
     require_once 'CRM/Core/Payment/Form.php';
     // payment fields are depending on payment type
     if ($this->_processors['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_DIRECT_DEBIT) {
         CRM_Core_Payment_Form::setDirectDebitFields($this);
     } else {
         CRM_Core_Payment_Form::setCreditCardFields($this);
     }
     if ($this->_action & CRM_Core_Action::DELETE) {
         return;
     }
     $config =& CRM_Core_Config::singleton();
     if (in_array("CiviPledge", $config->enableComponents) && !$this->_formType) {
         //get the payment values associated with given pledge payment id OR check for payments due.
         $this->_pledgeValues = array();
         if ($this->_ppID) {
             $payParams = array('id' => $this->_ppID);
             require_once "CRM/Pledge/BAO/Payment.php";
             CRM_Pledge_BAO_Payment::retrieve($payParams, $this->_pledgeValues['pledgePayment']);
             $this->_pledgeID = CRM_Utils_Array::value('pledge_id', $this->_pledgeValues['pledgePayment']);
             $paymentStatusID = CRM_Utils_Array::value('status_id', $this->_pledgeValues['pledgePayment']);
             $this->_id = CRM_Utils_Array::value('contribution_id', $this->_pledgeValues['pledgePayment']);
             //get all status
             $allStatus = CRM_Contribute_PseudoConstant::contributionStatus();
             if (!($paymentStatusID == array_search('Pending', $allStatus) || $paymentStatusID == array_search('Overdue', $allStatus))) {
                 CRM_Core_Error::fatal(ts("Pledge payment status should be 'Pending' or  'Overdue'."));
             }
             //get the pledge values associated with given pledge payment.
             require_once 'CRM/Pledge/BAO/Pledge.php';
             $ids = array();
             $pledgeParams = array('id' => $this->_pledgeID);
             CRM_Pledge_BAO_Pledge::getValues($pledgeParams, $this->_pledgeValues, $ids);
             $this->assign('ppID', $this->_ppID);
         } else {
             // Not making a pledge payment, so check if pledge payment(s) are due for this contact so we can alert the user. CRM-5206
             if (isset($this->_contactID)) {
                 require_once "CRM/Pledge/BAO/Pledge.php";
                 $contactPledges = array();
                 $contactPledges = CRM_Pledge_BAO_Pledge::getContactPledges($this->_contactID);
                 if (!empty($contactPledges)) {
                     $payments = null;
                     $paymentsDue = null;
                     $multipleDue = false;
                     require_once "CRM/Pledge/BAO/Payment.php";
                     foreach ($contactPledges as $key => $pledgeId) {
                         $payments = CRM_Pledge_BAO_Payment::getOldestPledgePayment($pledgeId);
                         if ($payments) {
                             if ($paymentsDue) {
                                 $multipleDue = true;
                                 break;
                             } else {
                                 $paymentsDue = $payments;
                             }
                         }
                     }
                     if ($multipleDue) {
                         // Show link to pledge tab since more than one pledge has a payment due
                         $pledgeTab = CRM_Utils_System::url('civicrm/contact/view', "reset=1&force=1&cid={$this->_contactID}&selectedChild=pledge");
                         CRM_Core_Session::setStatus(ts('This contact has pending or overdue pledge payments. <a href="%1">Click here to view their Pledges tab</a> and verify whether this contribution should be applied as a pledge payment.', array(1 => $pledgeTab)));
                     } else {
                         if ($paymentsDue) {
                             // Show user link to oldest Pending or Overdue pledge payment
                             require_once 'CRM/Utils/Date.php';
                             require_once 'CRM/Utils/Money.php';
                             $ppAmountDue = CRM_Utils_Money::format($payments['amount']);
                             $ppSchedDate = CRM_Utils_Date::customFormat(CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Payment', $payments['id'], 'scheduled_date'));
                             if ($this->_mode) {
                                 $ppUrl = CRM_Utils_System::url('civicrm/contact/view/contribution', "reset=1&action=add&cid={$this->_contactID}&ppid={$payments['id']}&context=pledge&mode=live");
                             } else {
                                 $ppUrl = CRM_Utils_System::url('civicrm/contact/view/contribution', "reset=1&action=add&cid={$this->_contactID}&ppid={$payments['id']}&context=pledge");
                             }
                             CRM_Core_Session::setStatus(ts('This contact has a pending or overdue pledge payment of %2 which is scheduled for %3. <a href="%1">Click here to apply this contribution as a pledge payment<a/>.', array(1 => $ppUrl, 2 => $ppAmountDue, 3 => $ppSchedDate)));
                         }
                     }
                 }
             }
         }
     }
     $this->_values = array();
     // current contribution id
     if ($this->_id) {
         $this->_online = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_FinancialTrxn', $this->_id, 'id', 'contribution_id');
         if ($this->_online) {
             $this->assign('isOnline', true);
         }
         //to get Premium id
         $sql = "\nSELECT *\nFROM   civicrm_contribution_product\nWHERE  contribution_id = {$this->_id}\n";
         $dao = CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
         if ($dao->fetch()) {
             $this->_premiumID = $dao->id;
             $this->_productDAO = $dao;
         }
         $dao->free();
         $ids = array();
         $params = array('id' => $this->_id);
         require_once "CRM/Contribute/BAO/Contribution.php";
         CRM_Contribute_BAO_Contribution::getValues($params, $this->_values, $ids);
         //unset the honor type id:when delete the honor_contact_id
         //and edit the contribution, honoree infomation pane open
         //since honor_type_id is present
         if (!CRM_Utils_Array::value('honor_contact_id', $this->_values)) {
             unset($this->_values['honor_type_id']);
         }
         //to get note id
         require_once 'CRM/Core/BAO/Note.php';
         $daoNote =& new CRM_Core_BAO_Note();
         $daoNote->entity_table = 'civicrm_contribution';
         $daoNote->entity_id = $this->_id;
         if ($daoNote->find(true)) {
             $this->_noteID = $daoNote->id;
             $this->_values['note'] = $daoNote->note;
         }
         $this->_contributionType = $this->_values['contribution_type_id'];
         $csParams = array('contribution_id' => $this->_id);
         $softCredit = CRM_Contribute_BAO_Contribution::getSoftContribution($csParams, true);
         if (CRM_Utils_Array::value('soft_credit_to', $softCredit)) {
             $softCredit['sort_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $softCredit['soft_credit_to'], 'sort_name');
         }
         $this->_values['soft_credit_to'] = $softCredit['sort_name'];
         $this->_values['softID'] = $softCredit['soft_credit_id'];
         $this->_values['soft_contact_id'] = $softCredit['soft_credit_to'];
         $this->_values['pcp_made_through_id'] = $softCredit['pcp_id'];
         $this->_values['pcp_display_in_roll'] = $softCredit['pcp_display_in_roll'];
         $this->_values['pcp_roll_nickname'] = $softCredit['pcp_roll_nickname'];
         $this->_values['pcp_personal_note'] = $softCredit['pcp_personal_note'];
         //display check number field only if its having value or its offline mode.
         if (CRM_Utils_Array::value('payment_instrument_id', $this->_values) == CRM_Core_OptionGroup::getValue('payment_instrument', 'Check', 'name') || CRM_Utils_Array::value('check_number', $this->_values)) {
             $this->assign('showCheckNumber', true);
         }
     }
     // when custom data is included in this page
     if (CRM_Utils_Array::value("hidden_custom", $_POST)) {
         $this->set('type', 'Contribution');
         $this->set('subType', $this->_contributionType);
         $this->set('entityId', $this->_id);
         CRM_Custom_Form_Customdata::preProcess($this);
         CRM_Custom_Form_Customdata::buildQuickForm($this);
         CRM_Custom_Form_Customdata::setDefaultValues($this);
     }
     require_once 'CRM/Price/BAO/Set.php';
     $this->_lineItems = array();
     if ($this->_id && ($priceSetId = CRM_Price_BAO_Set::getFor('civicrm_contribution', $this->_id))) {
         $this->_priceSetId = $priceSetId;
         require_once 'CRM/Price/BAO/LineItem.php';
         $this->_lineItems[] = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution');
     }
     $this->assign('lineItem', empty($this->_lineItems) ? false : $this->_lineItems);
 }
 /**
  * @param int $id
  * @param $values
  */
 public function buildValuesAndAssignOnline_Note_Type($id, &$values)
 {
     $ids = array();
     $params = array('id' => $id);
     CRM_Contribute_BAO_Contribution::getValues($params, $values, $ids);
     //Check if this is an online transaction (financial_trxn.payment_processor_id NOT NULL)
     $this->_online = FALSE;
     $fids = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($id);
     if (!empty($fids['financialTrxnId'])) {
         $this->_online = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $fids['financialTrxnId'], 'payment_processor_id');
     }
     // Also don't allow user to update some fields for recurring contributions.
     if (!$this->_online) {
         $this->_online = CRM_Utils_Array::value('contribution_recur_id', $values);
     }
     $this->assign('isOnline', $this->_online ? TRUE : FALSE);
     //to get note id
     $daoNote = new CRM_Core_BAO_Note();
     $daoNote->entity_table = 'civicrm_contribution';
     $daoNote->entity_id = $id;
     if ($daoNote->find(TRUE)) {
         $this->_noteID = $daoNote->id;
         $values['note'] = $daoNote->note;
     }
     $this->_contributionType = $values['financial_type_id'];
 }
Beispiel #15
0
 /**
  * This function sets the default values for the form.
  * the default values are retrieved from the database
  * 
  * @access public
  * @return None
  */
 public function setDefaultValues()
 {
     $defaults = array();
     $defaults =& parent::setDefaultValues();
     $this->_memType = $defaults["membership_type_id"];
     $defaults['renewal_date'] = CRM_Utils_Date::getToday($defaults['renewal_date'], 'm/d/Y');
     if ($defaults['id']) {
         $defaults['record_contribution'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $defaults['id'], 'contribution_id', 'membership_id');
     }
     $defaults['contribution_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'contribution_type_id');
     $defaults['total_amount'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'minimum_fee');
     $defaults['record_contribution'] = 0;
     if ($defaults['record_contribution']) {
         $contributionParams = array('id' => $defaults['record_contribution']);
         $contributionIds = array();
         require_once "CRM/Contribute/BAO/Contribution.php";
         CRM_Contribute_BAO_Contribution::getValues($contributionParams, $defaults, $contributionIds);
     }
     $defaults['send_receipt'] = 0;
     if ($defaults['membership_type_id']) {
         $defaults['receipt_text_renewal'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $defaults['membership_type_id'], 'receipt_text_renewal');
     }
     $this->assign("member_is_test", CRM_Utils_Array::value('member_is_test', $defaults));
     if ($this->_mode) {
         $fields = array();
         foreach ($this->_fields as $name => $dontCare) {
             $fields[$name] = 1;
         }
         $names = array("first_name", "middle_name", "last_name", "street_address-{$this->_bltID}", "city-{$this->_bltID}", "postal_code-{$this->_bltID}", "country_id-{$this->_bltID}", "state_province_id-{$this->_bltID}");
         foreach ($names as $name) {
             $fields[$name] = 1;
         }
         $fields["state_province-{$this->_bltID}"] = 1;
         $fields["country-{$this->_bltID}"] = 1;
         $fields["email-{$this->_bltID}"] = 1;
         $fields["email-Primary"] = 1;
         require_once "CRM/Core/BAO/UFGroup.php";
         CRM_Core_BAO_UFGroup::setProfileDefaults($this->_contactID, $fields, $this->_defaults);
         // use primary email address if billing email address is empty
         if (empty($this->_defaults["email-{$this->_bltID}"]) && !empty($this->_defaults["email-Primary"])) {
             $defaults["email-{$this->_bltID}"] = $this->_defaults["email-Primary"];
         }
         foreach ($names as $name) {
             if (!empty($this->_defaults[$name])) {
                 $defaults["billing_" . $name] = $this->_defaults[$name];
             }
         }
     }
     return $defaults;
 }
Beispiel #16
0
 /**
  * Complete an order.
  *
  * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
  *
  * Currently overloaded to complete a transaction & repeat a transaction - fix!
  *
  * Moving it out of the BaseIPN class is just the first step.
  *
  * @param array $input
  * @param array $ids
  * @param array $objects
  * @param CRM_Core_Transaction $transaction
  * @param int $recur
  * @param CRM_Contribute_BAO_Contribution $contribution
  * @param bool $isRecurring
  *   Duplication of param needs review. Only used by AuthorizeNetIPN
  * @param int $isFirstOrLastRecurringPayment
  *   Deprecated param only used by AuthorizeNetIPN.
  */
 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution, $isRecurring, $isFirstOrLastRecurringPayment)
 {
     $primaryContributionID = isset($contribution->id) ? $contribution->id : $objects['first_contribution']->id;
     // The previous details are used when calculating line items so keep it before any code that 'does something'
     if (!empty($contribution->id)) {
         $input['prevContribution'] = CRM_Contribute_BAO_Contribution::getValues(array('id' => $contribution->id), CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
     }
     $inputContributionWhiteList = array('fee_amount', 'net_amount', 'trxn_id', 'check_number', 'payment_instrument_id', 'is_test', 'campaign_id', 'receive_date');
     $contributionParams = array_merge(array('contribution_status_id' => 'Completed'), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)));
     $participant = CRM_Utils_Array::value('participant', $objects);
     $memberships = CRM_Utils_Array::value('membership', $objects);
     $recurContrib = CRM_Utils_Array::value('contributionRecur', $objects);
     if (!empty($recurContrib->id)) {
         $contributionParams['contribution_recur_id'] = $recurContrib->id;
     }
     self::repeatTransaction($contribution, $input, $contributionParams);
     if (is_numeric($memberships)) {
         $memberships = array($objects['membership']);
     }
     $changeDate = CRM_Utils_Array::value('trxn_date', $input, date('YmdHis'));
     $values = array();
     if (isset($input['is_email_receipt'])) {
         $values['is_email_receipt'] = $input['is_email_receipt'];
     }
     if ($input['component'] == 'contribute') {
         if ($contribution->contribution_page_id) {
             CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values);
             $contributionParams['source'] = ts('Online Contribution') . ': ' . $values['title'];
         } elseif ($recurContrib && $recurContrib->id) {
             $contributionParams['contribution_page_id'] = NULL;
             $values['amount'] = $recurContrib->amount;
             $values['financial_type_id'] = $objects['contributionType']->id;
             $values['title'] = $source = ts('Offline Recurring Contribution');
             $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
             $values['receipt_from_name'] = $domainValues[0];
             $values['receipt_from_email'] = $domainValues[1];
         }
         if ($recurContrib && $recurContrib->id && !isset($input['is_email_receipt'])) {
             //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
             // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
             $values['is_email_receipt'] = $recurContrib->is_email_receipt;
         }
         if (!empty($values['is_email_receipt'])) {
             $contributionParams['receipt_date'] = $changeDate;
         }
         if (!empty($memberships)) {
             foreach ($memberships as $membershipTypeIdKey => $membership) {
                 if ($membership) {
                     $membershipParams = array('id' => $membership->id, 'contact_id' => $membership->contact_id, 'is_test' => $membership->is_test, 'membership_type_id' => $membership->membership_type_id);
                     $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membershipParams['contact_id'], $membershipParams['membership_type_id'], $membershipParams['is_test'], $membershipParams['id']);
                     // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
                     // this picks up membership type changes during renewals
                     $sql = "\nSELECT    membership_type_id\nFROM      civicrm_membership_log\nWHERE     membership_id={$membershipParams['id']}\nORDER BY  id DESC\nLIMIT 1;";
                     $dao = CRM_Core_DAO::executeQuery($sql);
                     if ($dao->fetch()) {
                         if (!empty($dao->membership_type_id)) {
                             $membershipParams['membership_type_id'] = $dao->membership_type_id;
                         }
                     }
                     $dao->free();
                     $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType($membershipParams['membership_type_id'], $primaryContributionID);
                     $dates = array_fill_keys(array('join_date', 'start_date', 'end_date'), NULL);
                     if ($currentMembership) {
                         /*
                          * Fixed FOR CRM-4433
                          * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
                          * when Contribution mode is notify and membership is for renewal )
                          */
                         CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
                         // @todo - we should pass membership_type_id instead of null here but not
                         // adding as not sure of testing
                         $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membershipParams['id'], $changeDate, NULL, $membershipParams['num_terms']);
                         $dates['join_date'] = $currentMembership['join_date'];
                     }
                     //get the status for membership.
                     $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], $dates['end_date'], $dates['join_date'], 'today', TRUE, $membershipParams['membership_type_id'], $membershipParams);
                     $membershipParams['status_id'] = CRM_Utils_Array::value('id', $calcStatus, 'New');
                     //we might be renewing membership,
                     //so make status override false.
                     $membershipParams['is_override'] = FALSE;
                     civicrm_api3('Membership', 'create', $membershipParams);
                     //update related Memberships.
                     CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $membershipParams);
                 }
             }
         }
     } else {
         if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
             $eventDetail = civicrm_api3('Event', 'getsingle', array('id' => $objects['event']->id));
             $contributionParams['source'] = ts('Online Event Registration') . ': ' . $eventDetail['title'];
             if ($eventDetail['is_email_confirm']) {
                 // @todo this should be set by the function that sends the mail after sending.
                 $contributionParams['receipt_date'] = $changeDate;
             }
             $participantParams['id'] = $participant->id;
             $participantParams['status_id'] = 'Registered';
             civicrm_api3('Participant', 'create', $participantParams);
         }
     }
     $contributionParams['id'] = $contribution->id;
     civicrm_api3('Contribution', 'create', $contributionParams);
     // Add new soft credit against current $contribution.
     if (CRM_Utils_Array::value('contributionRecur', $objects) && $objects['contributionRecur']->id) {
         CRM_Contribute_BAO_ContributionRecur::addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id);
     }
     $paymentProcessorId = '';
     if (isset($objects['paymentProcessor'])) {
         if (is_array($objects['paymentProcessor'])) {
             $paymentProcessorId = $objects['paymentProcessor']['id'];
         } else {
             $paymentProcessorId = $objects['paymentProcessor']->id;
         }
     }
     $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array('labelColumn' => 'name', 'flip' => 1));
     if (empty($input['prevContribution']) && $paymentProcessorId || !$input['prevContribution']->is_pay_later && $input['prevContribution']->contribution_status_id == $contributionStatuses['Pending']) {
         $input['payment_processor'] = $paymentProcessorId;
     }
     $input['contribution_status_id'] = $contributionStatuses['Completed'];
     $input['total_amount'] = $input['amount'];
     $input['contribution'] = $contribution;
     $input['financial_type_id'] = $contribution->financial_type_id;
     if (!empty($contribution->_relatedObjects['participant'])) {
         $input['contribution_mode'] = 'participant';
         $input['participant_id'] = $contribution->_relatedObjects['participant']->id;
         $input['skipLineItem'] = 1;
     } elseif (!empty($contribution->_relatedObjects['membership'])) {
         $input['skipLineItem'] = TRUE;
         $input['contribution_mode'] = 'membership';
     }
     //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
     // and subsequent payments. In this case the line items are created at
     // CRM_Contribute_BAO_ContributionRecur::addRecurLineItems
     // and since the contribution is saved prior to this line there is always a contribution-id,
     // however there is never a prevContribution (which appears to mean original contribution not previous
     // contribution - or preUpdateContributionObject most accurately)
     // so, this is always called & only appears to succeed when prevContribution exists - which appears
     // to mean "are we updating an exisitng pending contribution"
     //I was able to make the unit test complete as fataling here doesn't prevent
     // the contribution being created - but activities would not be created or emails sent
     CRM_Contribute_BAO_Contribution::recordFinancialAccounts($input, NULL);
     CRM_Core_Error::debug_log_message("Contribution record updated successfully");
     $transaction->commit();
     CRM_Contribute_BAO_ContributionRecur::updateRecurLinkedPledge($contribution);
     // create an activity record
     if ($input['component'] == 'contribute') {
         //CRM-4027
         $targetContactID = NULL;
         if (!empty($ids['related_contact'])) {
             $targetContactID = $contribution->contact_id;
             $contribution->contact_id = $ids['related_contact'];
         }
         CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
         // event
     } else {
         CRM_Activity_BAO_Activity::addActivity($participant);
     }
     // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
     // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
     if (!array_key_exists('is_email_receipt', $values) || $values['is_email_receipt'] == 1) {
         self::sendMail($input, $ids, $objects['contribution'], $values, $recur, FALSE);
         CRM_Core_Error::debug_log_message("Receipt sent");
     }
     CRM_Core_Error::debug_log_message("Success: Database updated");
     if ($isRecurring) {
         CRM_Contribute_BAO_ContributionRecur::sendRecurringStartOrEndNotification($ids, $recur, $isFirstOrLastRecurringPayment);
     }
 }
Beispiel #17
0
/**
 * Get an existing contribution.
 *
 * Returns a single existing Contribution object which matches ALL property
 * values passed in $params. An error object is returned if there is
 * no match, or more than one match. This API can be used to retrieve
 * the CRM internal identifier (contribution_id) based on a unique property.
 * It can also be used to retrieve any desired
 * contribution properties based on a known contribution_id.
 *
 * @param array $params           Associative array of property name/value
 *                                pairs to attempt to match on.
 * @param array $returnProperties Which properties should be included in the
 *                                returned Contribution object. If NULL, the default
 *                                set of properties will be included.
 *
 * @return CRM_Contribution|CRM_Core_Error  Return the Contribution Object if found, else
 *                                Error Object
 *
 * @access public
 *
 */
function &crm_get_contribution($params, $returnProperties = null)
{
    _crm_initialize();
    // empty parameters ?
    if (empty($params)) {
        return _crm_error('$params is empty');
    }
    // correct parameter format ?
    if (!is_array($params)) {
        return _crm_error('$params is not an array');
    }
    if (!CRM_Utils_Array::value('contribution_id', $params)) {
        $returnProperties = array('trxn_id' => 1, 'contributiom_id' => 1);
        require_once 'CRM/Contact/BAO/Query.php';
        $newP =& CRM_Contact_BAO_Query::convertFormValues($params);
        list($contributions, $options) = crm_search($newP, $returnProperties);
        if (count($contributions) != 1) {
            return _crm_error(count($contributions) . " contributions matching input params.");
        }
        $contributionIds = array_values($contributions);
        $params['contribution_id'] = $contributionIds[0]["contribution_id"];
    }
    $newParams = array('id' => $params['contribution_id']);
    $ids = array();
    $contribution =& CRM_Contribute_BAO_Contribution::getValues($newParams, $defaults, $ids);
    if ($contribution == null || is_a($contribution, 'CRM_Core_Error') || !$contribution->id) {
        return _crm_error('Did not find contribution object for ' . $params['contribution_id']);
    }
    return $contribution;
}
 /**
  * Takes a bunch of params that are needed to match certain criteria and
  * retrieves the relevant objects. We'll tweak this function to be more
  * full featured over a period of time. This is the inverse function of
  * create.  It also stores all the retrieved values in the default array
  *
  * @param array $params   (reference ) an assoc array of name/value pairs
  * @param array $defaults (reference ) an assoc array to hold the name / value pairs
  *                        in a hierarchical manner
  * @param array $ids      (reference) the array that holds all the db ids
  *
  * @return object CRM_Contribute_BAO_Contribution object
  * @access public
  * @static
  */
 static function retrieve(&$params, &$defaults, &$ids)
 {
     $contribution = CRM_Contribute_BAO_Contribution::getValues($params, $defaults, $ids);
     return $contribution;
 }
 /**
  * This function sets the default values for the form. MobileProvider that in edit/view mode
  * the default values are retrieved from the database
  *
  * @access public
  *
  * @return None
  */
 public function setDefaultValues()
 {
     if ($this->_cdType) {
         return CRM_Custom_Form_CustomData::setDefaultValues($this);
     }
     if ($this->_priceSetId) {
         return CRM_Price_BAO_Set::setDefaultPriceSet($this, $defaults);
     }
     $defaults = parent::setDefaultValues();
     //setting default join date and receive date
     list($now) = CRM_Utils_Date::setDateDefaults();
     if ($this->_action == CRM_Core_Action::ADD) {
         $defaults['receive_date'] = $now;
     }
     if (is_numeric($this->_memType)) {
         $defaults["membership_type_id"] = array();
         $defaults["membership_type_id"][0] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'member_of_contact_id', 'id');
         $defaults["membership_type_id"][1] = $this->_memType;
     } else {
         $defaults["membership_type_id"] = $this->_memType;
     }
     if (CRM_Utils_Array::value('id', $defaults)) {
         if ($this->_onlinePendingContributionId) {
             $defaults['record_contribution'] = $this->_onlinePendingContributionId;
         } else {
             $contributionId = CRM_Core_DAO::singleValueQuery("\n  SELECT contribution_id\n  FROM civicrm_membership_payment\n  WHERE membership_id = {$this->_id}\n  ORDER BY contribution_id\n  DESC limit 1");
             if ($contributionId) {
                 $defaults['record_contribution'] = $contributionId;
             }
         }
     }
     if (CRM_Utils_Array::value('record_contribution', $defaults) && !$this->_mode) {
         $contributionParams = array('id' => $defaults['record_contribution']);
         $contributionIds = array();
         //keep main object campaign in hand.
         $memberCampaignId = CRM_Utils_Array::value('campaign_id', $defaults);
         CRM_Contribute_BAO_Contribution::getValues($contributionParams, $defaults, $contributionIds);
         //get back original object campaign id.
         $defaults['campaign_id'] = $memberCampaignId;
         if (CRM_Utils_Array::value('receive_date', $defaults)) {
             list($defaults['receive_date']) = CRM_Utils_Date::setDateDefaults($defaults['receive_date']);
         }
         // Contribution::getValues() over-writes the membership record's source field value - so we need to restore it.
         if (CRM_Utils_Array::value('membership_source', $defaults)) {
             $defaults['source'] = $defaults['membership_source'];
         }
     }
     // User must explicitly choose to send a receipt in both add and update mode.
     $defaults['send_receipt'] = 0;
     if ($this->_action & CRM_Core_Action::UPDATE) {
         // in this mode by default uncheck this checkbox
         unset($defaults['record_contribution']);
     }
     if (CRM_Utils_Array::value('id', $defaults)) {
         $subscriptionCancelled = CRM_Member_BAO_Membership::isSubscriptionCancelled($this->_id);
     }
     $alreadyAutoRenew = FALSE;
     if (CRM_Utils_Array::value('contribution_recur_id', $defaults) && !$subscriptionCancelled) {
         $defaults['auto_renew'] = 1;
         $alreadyAutoRenew = TRUE;
     }
     $this->assign('alreadyAutoRenew', $alreadyAutoRenew);
     $this->assign("member_is_test", CRM_Utils_Array::value('member_is_test', $defaults));
     $this->assign('membership_status_id', CRM_Utils_Array::value('status_id', $defaults));
     if (CRM_Utils_Array::value('is_pay_later', $defaults)) {
         $this->assign('is_pay_later', TRUE);
     }
     if ($this->_mode) {
         $fields = array();
         foreach ($this->_fields as $name => $dontCare) {
             $fields[$name] = 1;
         }
         $names = array("first_name", "middle_name", "last_name", "street_address-{$this->_bltID}", "city-{$this->_bltID}", "postal_code-{$this->_bltID}", "country_id-{$this->_bltID}", "state_province_id-{$this->_bltID}");
         foreach ($names as $name) {
             $fields[$name] = 1;
         }
         $fields["state_province-{$this->_bltID}"] = 1;
         $fields["country-{$this->_bltID}"] = 1;
         $fields["email-{$this->_bltID}"] = 1;
         $fields["email-Primary"] = 1;
         if ($this->_contactID) {
             CRM_Core_BAO_UFGroup::setProfileDefaults($this->_contactID, $fields, $this->_defaults);
         }
         // use primary email address if billing email address is empty
         if (empty($this->_defaults["email-{$this->_bltID}"]) && !empty($this->_defaults["email-Primary"])) {
             $defaults["email-{$this->_bltID}"] = $this->_defaults["email-Primary"];
         }
         foreach ($names as $name) {
             if (!empty($this->_defaults[$name])) {
                 $defaults["billing_" . $name] = $this->_defaults[$name];
             }
         }
         //             // hack to simplify credit card entry for testing
         //             $defaults['credit_card_type']     = 'Visa';
         //             $defaults['credit_card_number']   = '4807731747657838';
         //             $defaults['cvv2']                 = '000';
         //             $defaults['credit_card_exp_date'] = array( 'Y' => '2012', 'M' => '05' );
     }
     $dates = array('join_date', 'start_date', 'end_date');
     foreach ($dates as $key) {
         if (CRM_Utils_Array::value($key, $defaults)) {
             list($defaults[$key]) = CRM_Utils_Date::setDateDefaults(CRM_Utils_Array::value($key, $defaults));
         }
     }
     //setting default join date if there is no join date
     if (!CRM_Utils_Array::value('join_date', $defaults)) {
         $defaults['join_date'] = $now;
     }
     if (CRM_Utils_Array::value('membership_end_date', $defaults)) {
         $this->assign('endDate', $defaults['membership_end_date']);
     }
     return $defaults;
 }
 function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE)
 {
     $contribution =& $objects['contribution'];
     $primaryContributionID = isset($contribution->id) ? $contribution->id : $objects['first_contribution']->id;
     $memberships =& $objects['membership'];
     if (is_numeric($memberships)) {
         $memberships = array($objects['membership']);
     }
     $participant =& $objects['participant'];
     $event =& $objects['event'];
     $changeToday = CRM_Utils_Array::value('trxn_date', $input, self::$_now);
     $recurContrib =& $objects['contributionRecur'];
     $values = array();
     if (isset($input['is_email_receipt'])) {
         $values['is_email_receipt'] = $input['is_email_receipt'];
     }
     $source = NULL;
     if ($input['component'] == 'contribute') {
         if ($contribution->contribution_page_id) {
             CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values);
             $source = ts('Online Contribution') . ': ' . $values['title'];
         } elseif ($recurContrib && $recurContrib->id) {
             $contribution->contribution_page_id = NULL;
             $values['amount'] = $recurContrib->amount;
             $values['financial_type_id'] = $objects['contributionType']->id;
             $values['title'] = $source = ts('Offline Recurring Contribution');
             $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
             $values['receipt_from_name'] = $domainValues[0];
             $values['receipt_from_email'] = $domainValues[1];
         }
         if ($recurContrib && $recurContrib->id && !isset($input['is_email_receipt'])) {
             //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
             // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
             $values['is_email_receipt'] = $recurContrib->is_email_receipt;
         }
         $contribution->source = $source;
         if (CRM_Utils_Array::value('is_email_receipt', $values)) {
             $contribution->receipt_date = self::$_now;
         }
         if (!empty($memberships)) {
             $membershipsUpdate = array();
             foreach ($memberships as $membershipTypeIdKey => $membership) {
                 if ($membership) {
                     $format = '%Y%m%d';
                     $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id, $membership->membership_type_id, $membership->is_test, $membership->id);
                     // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
                     // this picks up membership type changes during renewals
                     $sql = "\nSELECT    membership_type_id\nFROM      civicrm_membership_log\nWHERE     membership_id={$membership->id}\nORDER BY  id DESC\nLIMIT 1;";
                     $dao = new CRM_Core_DAO();
                     $dao->query($sql);
                     if ($dao->fetch()) {
                         if (!empty($dao->membership_type_id)) {
                             $membership->membership_type_id = $dao->membership_type_id;
                             $membership->save();
                         }
                         // else fall back to using current membership type
                     }
                     // else fall back to using current membership type
                     $dao->free();
                     $num_terms = $contribution->getNumTermsByContributionAndMembershipType($membership->membership_type_id, $primaryContributionID);
                     if ($currentMembership) {
                         /*
                          * Fixed FOR CRM-4433
                          * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
                          * when Contribution mode is notify and membership is for renewal )
                          */
                         CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
                         // @todo - we should pass membership_type_id instead of null here but not
                         // adding as not sure of testing
                         $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, $changeToday, NULL, $num_terms);
                         $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
                     } else {
                         $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, NULL, NULL, NULL, $num_terms);
                     }
                     //get the status for membership.
                     $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], $dates['end_date'], $dates['join_date'], 'today', TRUE, $membership->membership_type_id, (array) $membership);
                     $formatedParams = array('status_id' => CRM_Utils_Array::value('id', $calcStatus, 2), 'join_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('join_date', $dates), $format), 'start_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('start_date', $dates), $format), 'end_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $dates), $format));
                     //we might be renewing membership,
                     //so make status override false.
                     $formatedParams['is_override'] = FALSE;
                     $membership->copyValues($formatedParams);
                     $membership->save();
                     //updating the membership log
                     $membershipLog = array();
                     $membershipLog = $formatedParams;
                     $logStartDate = $formatedParams['start_date'];
                     if (CRM_Utils_Array::value('log_start_date', $dates)) {
                         $logStartDate = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
                         $logStartDate = CRM_Utils_Date::isoToMysql($logStartDate);
                     }
                     $membershipLog['start_date'] = $logStartDate;
                     $membershipLog['membership_id'] = $membership->id;
                     $membershipLog['modified_id'] = $membership->contact_id;
                     $membershipLog['modified_date'] = date('Ymd');
                     $membershipLog['membership_type_id'] = $membership->membership_type_id;
                     CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
                     //update related Memberships.
                     CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formatedParams);
                     //update the membership type key of membership relatedObjects array
                     //if it has changed after membership update
                     if ($membershipTypeIdKey != $membership->membership_type_id) {
                         $membershipsUpdate[$membership->membership_type_id] = $membership;
                         $contribution->_relatedObjects['membership'][$membership->membership_type_id] = $membership;
                         unset($contribution->_relatedObjects['membership'][$membershipTypeIdKey]);
                         unset($memberships[$membershipTypeIdKey]);
                     }
                 }
             }
             //update the memberships object with updated membershipTypeId data
             //if membershipTypeId has changed after membership update
             if (!empty($membershipsUpdate)) {
                 $memberships = $memberships + $membershipsUpdate;
             }
         }
     } else {
         // event
         $eventParams = array('id' => $objects['event']->id);
         $values['event'] = array();
         CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
         //get location details
         $locationParams = array('entity_id' => $objects['event']->id, 'entity_table' => 'civicrm_event');
         $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
         $ufJoinParams = array('entity_table' => 'civicrm_event', 'entity_id' => $ids['event'], 'module' => 'CiviEvent');
         list($custom_pre_id, $custom_post_ids) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
         $values['custom_pre_id'] = $custom_pre_id;
         $values['custom_post_id'] = $custom_post_ids;
         //for tasks 'Change Participant Status' and 'Batch Update Participants Via Profile' case
         //and cases involving status updation through ipn
         $values['totalAmount'] = $input['amount'];
         $contribution->source = ts('Online Event Registration') . ': ' . $values['event']['title'];
         if ($values['event']['is_email_confirm']) {
             $contribution->receipt_date = self::$_now;
             $values['is_email_receipt'] = 1;
         }
         if (!CRM_Utils_Array::value('skipComponentSync', $input)) {
             $participant->status_id = 1;
         }
         $participant->save();
     }
     if (CRM_Utils_Array::value('net_amount', $input, 0) == 0 && CRM_Utils_Array::value('fee_amount', $input, 0) != 0) {
         $input['net_amount'] = $input['amount'] - $input['fee_amount'];
     }
     // This complete transaction function is being overloaded to create new contributions too.
     // here we record if it is a new contribution.
     // @todo separate the 2 more appropriately.
     $isNewContribution = FALSE;
     if (empty($contribution->id)) {
         $isNewContribution = TRUE;
         if (!empty($input['amount']) && $input['amount'] != $contribution->total_amount) {
             $contribution->total_amount = $input['amount'];
             // The BAO does this stuff but we are actually kinda bypassing it here (bad code! go sit in the corner)
             // so we have to handle net_amount in this (naughty) code.
             if (isset($input['fee_amount']) && is_numeric($input['fee_amount'])) {
                 $contribution->fee_amount = $input['fee_amount'];
             }
             $contribution->net_amount = $contribution->total_amount - $contribution->fee_amount;
         }
         if (!empty($input['campaign_id'])) {
             $contribution->campaign_id = $input['campaign_id'];
         }
     }
     $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array('labelColumn' => 'name', 'flip' => 1));
     // @todo this section should call the api  in order to have hooks called &
     // because all this 'messiness' setting variables could be avoided
     // by letting the api resolve pseudoconstants & copy set values and format dates.
     $contribution->contribution_status_id = $contributionStatuses['Completed'];
     $contribution->is_test = $input['is_test'];
     // CRM-15960 If we don't have a value we 'want' for the amounts, leave it to the BAO to sort out.
     if (isset($input['net_amount'])) {
         $contribution->fee_amount = CRM_Utils_Array::value('fee_amount', $input, 0);
     }
     if (isset($input['net_amount'])) {
         $contribution->net_amount = $input['net_amount'];
     }
     $contribution->trxn_id = $input['trxn_id'];
     $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
     $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date);
     $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date);
     $contribution->cancel_date = 'null';
     if (CRM_Utils_Array::value('check_number', $input)) {
         $contribution->check_number = $input['check_number'];
     }
     if (CRM_Utils_Array::value('payment_instrument_id', $input)) {
         $contribution->payment_instrument_id = $input['payment_instrument_id'];
     }
     if (!empty($contribution->id)) {
         $contributionId['id'] = $contribution->id;
         $input['prevContribution'] = CRM_Contribute_BAO_Contribution::getValues($contributionId, CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
     }
     $contribution->save();
     //add line items for recurring payments
     if (!empty($contribution->contribution_recur_id)) {
         if ($isNewContribution) {
             $input['line_item'] = $this->addRecurLineItems($contribution->contribution_recur_id, $contribution);
         } else {
             // this is just to prevent e-notices when we call recordFinancialAccounts - per comments on that line - intention is somewhat unclear
             $input['line_item'] = array();
         }
         if (!empty($memberships) && $primaryContributionID != $contribution->id) {
             foreach ($memberships as $membership) {
                 try {
                     $membershipPayment = array('membership_id' => $membership->id, 'contribution_id' => $contribution->id);
                     if (!civicrm_api3('membership_payment', 'getcount', $membershipPayment)) {
                         civicrm_api3('membership_payment', 'create', $membershipPayment);
                     }
                 } catch (CiviCRM_API3_Exception $e) {
                     echo $e->getMessage();
                     // we are catching & ignoring errors as an extra precaution since lost IPNs may be more serious that lost membership_payment data
                     // this fn is unit-tested so risk of changes elsewhere breaking it are otherwise mitigated
                 }
             }
         }
     }
     //copy initial contribution custom fields for recurring contributions
     if ($recurContrib && $recurContrib->id) {
         $this->copyCustomValues($recurContrib->id, $contribution->id);
     }
     // next create the transaction record
     $paymentProcessor = $paymentProcessorId = '';
     if (isset($objects['paymentProcessor'])) {
         if (is_array($objects['paymentProcessor'])) {
             $paymentProcessor = $objects['paymentProcessor']['payment_processor_type'];
             $paymentProcessorId = $objects['paymentProcessor']['id'];
         } else {
             $paymentProcessor = $objects['paymentProcessor']->payment_processor_type;
             $paymentProcessorId = $objects['paymentProcessor']->id;
         }
     }
     //it's hard to see how it could reach this point without a contributon id as it is saved in line 511 above
     // which raised the question as to whether this check preceded line 511 & if so whether something could be broken
     // From a lot of code reading /debugging I'm still not sure the intent WRT first & subsequent payments in this code
     // it would be good if someone added some comments or refactored this
     if ($contribution->id) {
         $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
         if (empty($input['prevContribution']) && $paymentProcessorId || !$input['prevContribution']->is_pay_later && $input['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatuses)) {
             $input['payment_processor'] = $paymentProcessorId;
         }
         $input['contribution_status_id'] = array_search('Completed', $contributionStatuses);
         $input['total_amount'] = $input['amount'];
         $input['contribution'] = $contribution;
         $input['financial_type_id'] = $contribution->financial_type_id;
         if (CRM_Utils_Array::value('participant', $contribution->_relatedObjects)) {
             $input['contribution_mode'] = 'participant';
             $input['participant_id'] = $contribution->_relatedObjects['participant']->id;
             $input['skipLineItem'] = 1;
         }
         //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
         // and subsequent payments. In this case the line items are created at $this->addRecurLineItems
         // and since the contribution is saved prior to this line there is always a contribution-id,
         // however there is never a prevContribution (which appears to mean original contribution not previous
         // contribution - or preUpdateContributionObject most accurately)
         // so, this is always called & only appears to succeed when prevContribution exists - which appears
         // to mean "are we updating an exisitng pending contribution"
         //I was able to make the unit test complete as fataling here doesn't prevent
         // the contribution being created - but activities would not be created or emails sent
         CRM_Contribute_BAO_Contribution::recordFinancialAccounts($input, NULL);
     }
     self::updateRecurLinkedPledge($contribution);
     // create an activity record
     if ($input['component'] == 'contribute') {
         //CRM-4027
         $targetContactID = NULL;
         if (CRM_Utils_Array::value('related_contact', $ids)) {
             $targetContactID = $contribution->contact_id;
             $contribution->contact_id = $ids['related_contact'];
         }
         CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
         // event
     } else {
         CRM_Activity_BAO_Activity::addActivity($participant);
     }
     CRM_Core_Error::debug_log_message("Contribution record updated successfully");
     $transaction->commit();
     // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
     // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
     if (!array_key_exists('is_email_receipt', $values) || $values['is_email_receipt'] == 1) {
         self::sendMail($input, $ids, $objects, $values, $recur, FALSE);
         CRM_Core_Error::debug_log_message("Receipt sent");
     }
     CRM_Core_Error::debug_log_message("Success: Database updated");
 }
 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');
 }