示例#1
0
 /**
  * @param array $submittedValues
  *
  * @param int $action
  *   Action constant
  *    - CRM_Core_Action::UPDATE
  *
  * @param $pledgePaymentID
  *
  * @return array
  * @throws \Exception
  */
 protected function submit($submittedValues, $action, $pledgePaymentID)
 {
     $softParams = $softIDs = array();
     $pId = $contribution = $isRelatedId = FALSE;
     $this->_params = $submittedValues;
     $this->beginPostProcess();
     if (!empty($submittedValues['price_set_id']) && $action & CRM_Core_Action::UPDATE) {
         $line = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution');
         $lineID = key($line);
         $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array::value('price_field_id', $line[$lineID]), 'price_set_id');
         $quickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
         // Why do we do this? Seems like a like a wrapper for old functionality - but single line price sets & quick
         // config should be treated the same.
         if ($quickConfig) {
             CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_contribution');
         }
     }
     // Process price set and get total amount and line items.
     $lineItem = array();
     $priceSetId = CRM_Utils_Array::value('price_set_id', $submittedValues);
     if (empty($priceSetId) && !$this->_id) {
         $this->_priceSetId = $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
         $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
         $fieldID = key($this->_priceSet['fields']);
         $fieldValueId = key($this->_priceSet['fields'][$fieldID]['options']);
         $this->_priceSet['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
         $submittedValues['price_' . $fieldID] = 1;
     }
     // Every contribution has a price-set - the only reason it shouldn't be set is if we are dealing with
     // quick config (very very arguably) & yet we see that this could still be quick config so this should be understood
     // as a point of fragility rather than a logical 'if' clause.
     if ($priceSetId) {
         CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $submittedValues, $lineItem[$priceSetId]);
         // Unset tax amount for offline 'is_quick_config' contribution.
         // @todo WHY  - quick config was conceived as a quick way to configure contribution forms.
         // this is an example of 'other' functionality being hung off it.
         if ($this->_priceSet['is_quick_config'] && !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant::getTaxRates())) {
             unset($submittedValues['tax_amount']);
         }
         $submittedValues['total_amount'] = CRM_Utils_Array::value('amount', $submittedValues);
     }
     if ($this->_id) {
         if ($this->_compId) {
             if ($this->_context == 'participant') {
                 $pId = $this->_compId;
             } elseif ($this->_context == 'membership') {
                 $isRelatedId = TRUE;
             } else {
                 $pId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'participant_id', 'contribution_id');
             }
         } else {
             $contributionDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
             if (array_key_exists('membership', $contributionDetails)) {
                 $isRelatedId = TRUE;
             } elseif (array_key_exists('participant', $contributionDetails)) {
                 $pId = $contributionDetails['participant'];
             }
         }
     }
     if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id) {
         // CRM-10117 update the line items for participants.
         // @todo - if we are completing a contribution then the api call
         // civicrm_api3('Contribution', 'completetransaction') should take care of
         // all associated updates rather than replicating them on the form layer.
         if ($pId) {
             $entityTable = 'participant';
             $entityID = $pId;
             $isRelatedId = FALSE;
             $participantParams = array('fee_amount' => $submittedValues['total_amount'], 'id' => $entityID);
             CRM_Event_BAO_Participant::add($participantParams);
             if (empty($this->_lineItems)) {
                 $this->_lineItems[] = CRM_Price_BAO_LineItem::getLineItems($entityID, 'participant', 1);
             }
         } else {
             $entityTable = 'contribution';
             $entityID = $this->_id;
         }
         $lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entityTable, NULL, TRUE, $isRelatedId);
         foreach (array_keys($lineItems) as $id) {
             $lineItems[$id]['id'] = $id;
         }
         $itemId = key($lineItems);
         if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
             $this->_priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
         }
         // @todo see above - new functionality has been inappropriately added to the quick config concept
         // and new functionality has been added onto the form layer rather than the BAO :-(
         if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
             //CRM-16833: Ensure tax is applied only once for membership conribution, when status changed.(e.g Pending to Completed).
             $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
             if (!(CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails))) {
                 if (!($this->_action & CRM_Core_Action::UPDATE && $this->_defaults['contribution_status_id'] != $submittedValues['contribution_status_id'])) {
                     $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value('total_amount', $submittedValues));
                 }
             }
             // Update line total and total amount with tax on edit.
             $financialItemsId = CRM_Core_PseudoConstant::getTaxRates();
             if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
                 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
             } else {
                 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
                 $submittedValues['tax_amount'] = 'null';
             }
             if ($lineItems[$itemId]['tax_rate']) {
                 $lineItems[$itemId]['tax_amount'] = $lineItems[$itemId]['tax_rate'] / 100 * $lineItems[$itemId]['line_total'];
                 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] + $lineItems[$itemId]['tax_amount'];
                 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
             }
         }
         // CRM-10117 update the line items for participants.
         if (!empty($lineItems[$itemId]['price_field_id'])) {
             $lineItem[$this->_priceSetId] = $lineItems;
         }
     }
     $isQuickConfig = 0;
     if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
         $isQuickConfig = 1;
     }
     //CRM-11529 for quick config back office transactions
     //when financial_type_id is passed in form, update the
     //line items with the financial type selected in form
     // NOTE that this IS still a legitimate use of 'quick-config' for contributions under the current DB but
     // we should look at having a price field per contribution type & then there would be little reason
     // for the back-office contribution form postProcess to know if it is a quick-config form.
     if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array::value($this->_priceSetId, $lineItem)) {
         foreach ($lineItem[$this->_priceSetId] as &$values) {
             $values['financial_type_id'] = $submittedValues['financial_type_id'];
         }
     }
     if (!isset($submittedValues['total_amount'])) {
         $submittedValues['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_values);
     }
     $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
     $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
     if ($this->_id && count($isEmpty) == 1 && key($isEmpty) == NULL) {
         //Delete existing soft credit records if soft credit list is empty on update
         CRM_Contribute_BAO_ContributionSoft::del(array('contribution_id' => $this->_id, 'pcp_id' => 0));
     }
     // set the contact, when contact is selected
     if (!empty($submittedValues['contact_id'])) {
         $this->_contactID = $submittedValues['contact_id'];
     }
     $formValues = $submittedValues;
     // Credit Card Contribution.
     if ($this->_mode) {
         $paramsSetByPaymentProcessingSubsystem = array('trxn_id', 'payment_instrument_id', 'contribution_status_id', 'cancel_date', 'cancel_reason');
         foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
             if (isset($formValues[$key])) {
                 unset($formValues[$key]);
             }
         }
         $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID);
         foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
             $formValues[$key] = $contribution->{$key};
         }
     } else {
         // Offline Contribution.
         $submittedValues = $this->unsetCreditCardFields($submittedValues);
         // get the required field value only.
         $params = $ids = array();
         $params['contact_id'] = $this->_contactID;
         $params['currency'] = $this->getCurrency($submittedValues);
         //format soft-credit/pcp param first
         CRM_Contribute_BAO_ContributionSoft::formatSoftCreditParams($submittedValues, $this);
         $params = array_merge($params, $submittedValues);
         $fields = array('financial_type_id', 'contribution_status_id', 'payment_instrument_id', 'cancel_reason', 'source', 'check_number');
         foreach ($fields as $f) {
             $params[$f] = CRM_Utils_Array::value($f, $formValues);
         }
         // CRM-5740 if priceset is used, no need to cleanup money.
         if ($priceSetId) {
             $params['skipCleanMoney'] = 1;
         }
         $dates = array('receive_date', 'receipt_date', 'cancel_date');
         foreach ($dates as $d) {
             $params[$d] = CRM_Utils_Date::processDate($formValues[$d], $formValues[$d . '_time'], TRUE);
         }
         if (!empty($formValues['is_email_receipt'])) {
             $params['receipt_date'] = date("Y-m-d");
         }
         if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Cancelled', 'name') || $params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name')) {
             if (CRM_Utils_System::isNull(CRM_Utils_Array::value('cancel_date', $params))) {
                 $params['cancel_date'] = date('YmdHis');
             }
         } else {
             $params['cancel_date'] = $params['cancel_reason'] = 'null';
         }
         // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
         // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
         if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) {
             $params['is_pay_later'] = 1;
         } elseif ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
             $params['is_pay_later'] = 0;
         }
         $ids['contribution'] = $params['id'] = $this->_id;
         // Add Additional common information to formatted params.
         CRM_Contribute_Form_AdditionalInfo::postProcessCommon($formValues, $params, $this);
         if ($pId) {
             $params['contribution_mode'] = 'participant';
             $params['participant_id'] = $pId;
             $params['skipLineItem'] = 1;
         } elseif ($isRelatedId) {
             $params['contribution_mode'] = 'membership';
         }
         $params['line_item'] = $lineItem;
         $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array::value('id', $this->_paymentProcessor);
         if (isset($submittedValues['tax_amount'])) {
             $params['tax_amount'] = $submittedValues['tax_amount'];
         }
         //create contribution.
         if ($isQuickConfig) {
             $params['is_quick_config'] = 1;
         }
         $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
         // we are already handling note below, so to avoid duplicate notes against $contribution
         if (!empty($params['note']) && !empty($submittedValues['note'])) {
             unset($params['note']);
         }
         $contribution = CRM_Contribute_BAO_Contribution::create($params, $ids);
         // process associated membership / participant, CRM-4395
         if ($contribution->id && $action & CRM_Core_Action::UPDATE) {
             $this->statusMessage[] = $this->updateRelatedComponent($contribution->id, $contribution->contribution_status_id, CRM_Utils_Array::value('contribution_status_id', $this->_values), $contribution->receive_date);
         }
         array_unshift($this->statusMessage, ts('The contribution record has been saved.'));
         $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
         //send receipt mail.
         if ($contribution->id && !empty($formValues['is_email_receipt'])) {
             $formValues['contact_id'] = $this->_contactID;
             $formValues['contribution_id'] = $contribution->id;
             $formValues += CRM_Contribute_BAO_ContributionSoft::getSoftContribution($contribution->id);
             // to get 'from email id' for send receipt
             $this->fromEmailId = $formValues['from_email_address'];
             if (CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $formValues)) {
                 $this->statusMessage[] = ts('A receipt has been emailed to the contributor.');
             }
         }
         $this->statusMessageTitle = ts('Saved');
     }
     if ($contribution->id && isset($formValues['product_name'][0])) {
         CRM_Contribute_Form_AdditionalInfo::processPremium($submittedValues, $contribution->id, $this->_premiumID, $this->_options);
     }
     if ($contribution->id && !empty($submittedValues['note'])) {
         CRM_Contribute_Form_AdditionalInfo::processNote($submittedValues, $this->_contactID, $contribution->id, $this->_noteID);
     }
     CRM_Core_Session::setStatus(implode(' ', $this->statusMessage), $this->statusMessageTitle, 'success');
     CRM_Contribute_BAO_Contribution::updateRelatedPledge($action, $pledgePaymentID, $contribution->id, CRM_Utils_Array::value('option_type', $formValues) == 2 ? TRUE : FALSE, $formValues['total_amount'], CRM_Utils_Array::value('total_amount', $this->_defaults), $formValues['contribution_status_id'], CRM_Utils_Array::value('contribution_status_id', $this->_defaults));
     return $contribution;
 }
示例#2
0
    /**
     * Build the form object.
     *
     * @return void
     */
    public function buildQuickForm()
    {
        if ($this->_cdType) {
            return CRM_Custom_Form_CustomData::buildQuickForm($this);
        }
        $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant::getTaxRates()));
        $config = CRM_Core_Config::singleton();
        $this->assign('currency', $config->defaultCurrencySymbol);
        $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
        $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
        if (isset($invoicing)) {
            $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
        }
        // build price set form.
        $buildPriceSet = FALSE;
        if ($this->_priceSetId || !empty($_POST['price_set_id'])) {
            if (!empty($_POST['price_set_id'])) {
                $buildPriceSet = TRUE;
            }
            $getOnlyPriceSetElements = TRUE;
            if (!$this->_priceSetId) {
                $this->_priceSetId = $_POST['price_set_id'];
                $getOnlyPriceSetElements = FALSE;
            }
            $this->set('priceSetId', $this->_priceSetId);
            CRM_Price_BAO_PriceSet::buildPriceSet($this);
            $optionsMembershipTypes = array();
            foreach ($this->_priceSet['fields'] as $pField) {
                if (empty($pField['options'])) {
                    continue;
                }
                foreach ($pField['options'] as $opId => $opValues) {
                    $optionsMembershipTypes[$opId] = CRM_Utils_Array::value('membership_type_id', $opValues, 0);
                }
            }
            $this->assign('autoRenewOption', CRM_Price_BAO_PriceSet::checkAutoRenewForPriceSet($this->_priceSetId));
            $this->assign('optionsMembershipTypes', $optionsMembershipTypes);
            $this->assign('contributionType', CRM_Utils_Array::value('financial_type_id', $this->_priceSet));
            // get only price set form elements.
            if ($getOnlyPriceSetElements) {
                return;
            }
        }
        // use to build form during form rule.
        $this->assign('buildPriceSet', $buildPriceSet);
        if ($this->_action & CRM_Core_Action::ADD) {
            $buildPriceSet = FALSE;
            $priceSets = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviMember');
            if (!empty($priceSets)) {
                $buildPriceSet = TRUE;
            }
            if ($buildPriceSet) {
                $this->add('select', 'price_set_id', ts('Choose price set'), array('' => ts('Choose price set')) + $priceSets, NULL, array('onchange' => "buildAmount( this.value );"));
            }
            $this->assign('hasPriceSets', $buildPriceSet);
        }
        //need to assign custom data type and subtype to the template
        $this->assign('customDataType', 'Membership');
        $this->assign('customDataSubType', $this->_memType);
        $this->assign('entityID', $this->_id);
        if ($this->_action & CRM_Core_Action::DELETE) {
            $this->addButtons(array(array('type' => 'next', 'name' => ts('Delete'), 'spacing' => '         ', 'isDefault' => TRUE), array('type' => 'cancel', 'name' => ts('Cancel'))));
            return;
        }
        if ($this->_context == 'standalone') {
            $this->addEntityRef('contact_id', ts('Contact'), array('create' => TRUE, 'api' => array('extra' => array('email'))), TRUE);
        }
        $selOrgMemType[0][0] = $selMemTypeOrg[0] = ts('- select -');
        $dao = new CRM_Member_DAO_MembershipType();
        $dao->domain_id = CRM_Core_Config::domainID();
        $dao->find();
        // retrieve all memberships
        $allMemberships = CRM_Member_BAO_Membership::buildMembershipTypeValues($this);
        $allMembershipInfo = $membershipType = array();
        foreach ($allMemberships as $key => $values) {
            if (!empty($values['is_active'])) {
                $membershipType[$key] = CRM_Utils_Array::value('name', $values);
                if ($this->_mode && empty($values['minimum_fee'])) {
                    continue;
                } else {
                    $memberOfContactId = CRM_Utils_Array::value('member_of_contact_id', $values);
                    if (empty($selMemTypeOrg[$memberOfContactId])) {
                        $selMemTypeOrg[$memberOfContactId] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $memberOfContactId, 'display_name', 'id');
                        $selOrgMemType[$memberOfContactId][0] = ts('- select -');
                    }
                    if (empty($selOrgMemType[$memberOfContactId][$key])) {
                        $selOrgMemType[$memberOfContactId][$key] = CRM_Utils_Array::value('name', $values);
                    }
                }
                // build membership info array, which is used when membership type is selected to:
                // - set the payment information block
                // - set the max related block
                $allMembershipInfo[$key] = array('financial_type_id' => CRM_Utils_Array::value('financial_type_id', $values), 'total_amount' => CRM_Utils_Money::format($values['minimum_fee'], NULL, '%a'), 'total_amount_numeric' => CRM_Utils_Array::value('minimum_fee', $values), 'auto_renew' => CRM_Utils_Array::value('auto_renew', $values), 'has_related' => isset($values['relationship_type_id']), 'max_related' => CRM_Utils_Array::value('max_related', $values));
            }
        }
        $this->assign('allMembershipInfo', json_encode($allMembershipInfo));
        // show organization by default, if only one organization in
        // the list
        if (count($selMemTypeOrg) == 2) {
            unset($selMemTypeOrg[0], $selOrgMemType[0][0]);
        }
        //sort membership organization and type, CRM-6099
        natcasesort($selMemTypeOrg);
        foreach ($selOrgMemType as $index => $orgMembershipType) {
            natcasesort($orgMembershipType);
            $selOrgMemType[$index] = $orgMembershipType;
        }
        $memTypeJs = array('onChange' => "CRM.buildCustomData( 'Membership', this.value );");
        //build the form for auto renew.
        $recurProcessor = $autoRenew = array();
        if ($this->_mode || $this->_action & CRM_Core_Action::UPDATE) {
            $autoRenewElement = $this->addElement('checkbox', 'auto_renew', ts('Membership renewed automatically'), NULL, array('onclick' => "buildReceiptANDNotice( );"));
            if ($this->_mode) {
                //get the valid recurring processors.
                $test = strtolower($this->_mode) == 'test' ? TRUE : FALSE;
                $recurring = CRM_Core_PseudoConstant::paymentProcessor(FALSE, $test, 'is_recur = 1');
                $recurProcessor = array_intersect_key($this->_processors, $recurring);
                $autoRenew = array();
                if (!empty($recurProcessor)) {
                    if (!empty($membershipType)) {
                        $sql = '
SELECT  id,
        auto_renew,
        duration_unit,
        duration_interval
 FROM   civicrm_membership_type
WHERE   id IN ( ' . implode(' , ', array_keys($membershipType)) . ' )';
                        $recurMembershipTypes = CRM_Core_DAO::executeQuery($sql);
                        while ($recurMembershipTypes->fetch()) {
                            $autoRenew[$recurMembershipTypes->id] = $recurMembershipTypes->auto_renew;
                            foreach (array('id', 'auto_renew', 'duration_unit', 'duration_interval') as $fld) {
                                $this->_recurMembershipTypes[$recurMembershipTypes->id][$fld] = $recurMembershipTypes->{$fld};
                            }
                        }
                    }
                    $memTypeJs = array('onChange' => "CRM.buildCustomData( 'Membership', this.value ); buildAutoRenew(this.value, null );");
                }
            }
        }
        $allowAutoRenew = FALSE;
        if ($this->_mode && !empty($recurProcessor)) {
            $allowAutoRenew = TRUE;
        }
        $this->assign('allowAutoRenew', $allowAutoRenew);
        $this->assign('autoRenewOptions', json_encode($autoRenew));
        $this->assign('recurProcessor', json_encode($recurProcessor));
        // for max_related: a little JS to show/hide & set default value
        $memTypeJs['onChange'] = "buildMaxRelated(this.value,true); " . $memTypeJs['onChange'];
        $this->add('text', 'max_related', ts('Max related'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_Membership', 'max_related'));
        $sel =& $this->addElement('hierselect', 'membership_type_id', ts('Membership Organization and Type'), $memTypeJs);
        $sel->setOptions(array($selMemTypeOrg, $selOrgMemType));
        $elements = array();
        if ($sel) {
            $elements[] = $sel;
        }
        $this->applyFilter('__ALL__', 'trim');
        if ($this->_action & CRM_Core_Action::ADD) {
            $this->add('text', 'num_terms', ts('Number of Terms'), array('size' => 6));
        }
        $this->addDate('join_date', ts('Member Since'), FALSE, array('formatType' => 'activityDate'));
        $this->addDate('start_date', ts('Start Date'), FALSE, array('formatType' => 'activityDate'));
        $endDate = $this->addDate('end_date', ts('End Date'), FALSE, array('formatType' => 'activityDate'));
        if ($endDate) {
            $elements[] = $endDate;
        }
        $this->add('text', 'source', ts('Source'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_Membership', 'source'));
        //CRM-7362 --add campaigns.
        $campaignId = NULL;
        if ($this->_id) {
            $campaignId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_id, 'campaign_id');
        }
        CRM_Campaign_BAO_Campaign::addCampaign($this, $campaignId);
        if (!$this->_mode) {
            $this->add('select', 'status_id', ts('Membership Status'), array('' => ts('- select -')) + CRM_Member_PseudoConstant::membershipStatus(NULL, NULL, 'label'));
            $statusOverride = $this->addElement('checkbox', 'is_override', ts('Status Override?'), NULL, array('onClick' => 'showHideMemberStatus()'));
            if ($statusOverride) {
                $elements[] = $statusOverride;
            }
            $this->addElement('checkbox', 'record_contribution', ts('Record Membership Payment?'));
            $this->add('text', 'total_amount', ts('Amount'));
            $this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
            $this->addDate('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
            $this->add('select', 'payment_instrument_id', ts('Paid By'), array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(), FALSE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);"));
            $this->add('text', 'trxn_id', ts('Transaction ID'));
            $this->addRule('trxn_id', ts('Transaction ID already exists in Database.'), 'objectExists', array('CRM_Contribute_DAO_Contribution', $this->_id, 'trxn_id'));
            $allowStatuses = array();
            $statuses = CRM_Contribute_PseudoConstant::contributionStatus();
            if ($this->_onlinePendingContributionId) {
                $statusNames = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
                foreach ($statusNames as $val => $name) {
                    if (in_array($name, array('In Progress', 'Overdue'))) {
                        continue;
                    }
                    $allowStatuses[$val] = $statuses[$val];
                }
            } else {
                $allowStatuses = $statuses;
            }
            $this->add('select', 'contribution_status_id', ts('Payment Status'), $allowStatuses);
            $this->add('text', 'check_number', ts('Check Number'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution', 'check_number'));
        } else {
            //add field for amount to allow an amount to be entered that differs from minimum
            $this->add('text', 'total_amount', ts('Amount'));
        }
        $this->add('select', 'financial_type_id', ts('Financial Type'), array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::financialType());
        //CRM-10223 - allow contribution to be recorded against different contact
        // causes a conflict in standalone mode so skip in standalone for now
        $this->addElement('checkbox', 'is_different_contribution_contact', ts('Record Payment from a Different Contact?'));
        $this->addSelect('soft_credit_type_id', array('entity' => 'contribution_soft'));
        $this->addEntityRef('soft_credit_contact_id', ts('Payment From'), array('create' => TRUE));
        $this->addElement('checkbox', 'send_receipt', ts('Send Confirmation and Receipt?'), NULL, array('onclick' => "showHideByValue( 'send_receipt', '', 'notice', 'table-row', 'radio', false); showHideByValue( 'send_receipt', '', 'fromEmail', 'table-row', 'radio', false);"));
        $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
        $this->add('textarea', 'receipt_text_signup', ts('Receipt Message'));
        // Retrieve the name and email of the contact - this will be the TO for receipt email
        if ($this->_contactID) {
            list($this->_memberDisplayName, $this->_memberEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
            $this->assign('emailExists', $this->_memberEmail);
            $this->assign('displayName', $this->_memberDisplayName);
        }
        $isRecur = FALSE;
        if ($this->_action & CRM_Core_Action::UPDATE) {
            $recurContributionId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_id, 'contribution_recur_id');
            if ($recurContributionId && !CRM_Member_BAO_Membership::isSubscriptionCancelled($this->_id)) {
                $isRecur = TRUE;
                if (CRM_Member_BAO_Membership::isCancelSubscriptionSupported($this->_id)) {
                    $this->assign('cancelAutoRenew', CRM_Utils_System::url('civicrm/contribute/unsubscribe', "reset=1&mid={$this->_id}"));
                }
                foreach ($elements as $elem) {
                    $elem->freeze();
                }
            }
        }
        $this->assign('isRecur', $isRecur);
        $this->addFormRule(array('CRM_Member_Form_Membership', 'formRule'), $this);
        $mailingInfo = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME, 'mailing_backend');
        $this->assign('outBound_option', $mailingInfo['outBound_option']);
        parent::buildQuickForm();
    }
示例#3
0
 /**
  * Retrieve a list of options for the specified field.
  *
  * @param int $fieldId
  *   Price field ID.
  * @param bool $inactiveNeeded
  *   Include inactive options.
  * @param bool $reset
  *   Ignore stored values\.
  *
  * @return array
  *   array of options
  */
 public static function getOptions($fieldId, $inactiveNeeded = FALSE, $reset = FALSE)
 {
     static $options = array();
     if ($reset || empty($options[$fieldId])) {
         $values = array();
         CRM_Price_BAO_PriceFieldValue::getValues($fieldId, $values, 'weight', !$inactiveNeeded);
         $options[$fieldId] = $values;
         $taxRates = CRM_Core_PseudoConstant::getTaxRates();
         // ToDo - Code for Hook Invoke
         foreach ($options[$fieldId] as $priceFieldId => $priceFieldValues) {
             if (isset($priceFieldValues['financial_type_id']) && array_key_exists($priceFieldValues['financial_type_id'], $taxRates)) {
                 $options[$fieldId][$priceFieldId]['tax_rate'] = $taxRates[$priceFieldValues['financial_type_id']];
                 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($priceFieldValues['amount'], $options[$fieldId][$priceFieldId]['tax_rate']);
                 $options[$fieldId][$priceFieldId]['tax_amount'] = round($taxAmount['tax_amount'], 2);
             }
         }
     }
     return $options[$fieldId];
 }
示例#4
0
 /**
  * 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;
 }
示例#5
0
 /**
  * Browse all price fields.
  *
  * @return void
  */
 public function browse()
 {
     $customOption = array();
     CRM_Price_BAO_PriceFieldValue::getValues($this->_fid, $customOption);
     // CRM-15378 - check if these price options are in an Event price set
     $isEvent = FALSE;
     $extendComponentId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_sid, 'extends', 'id');
     $allComponents = explode(CRM_Core_DAO::VALUE_SEPARATOR, $extendComponentId);
     $eventComponentId = CRM_Core_Component::getComponentID('CiviEvent');
     if (in_array($eventComponentId, $allComponents)) {
         $isEvent = TRUE;
     }
     $config = CRM_Core_Config::singleton();
     $financialType = CRM_Contribute_PseudoConstant::financialType();
     $taxRate = CRM_Core_PseudoConstant::getTaxRates();
     // display taxTerm for priceFields
     $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
     $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
     $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
     $getTaxDetails = FALSE;
     foreach ($customOption as $id => $values) {
         $action = array_sum(array_keys($this->actionLinks()));
         // Adding the required fields in the array
         if (isset($taxRate[$values['financial_type_id']])) {
             $customOption[$id]['tax_rate'] = $taxRate[$values['financial_type_id']];
             if ($invoicing && isset($customOption[$id]['tax_rate'])) {
                 $getTaxDetails = TRUE;
             }
             $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($customOption[$id]['amount'], $customOption[$id]['tax_rate']);
             $customOption[$id]['tax_amount'] = $taxAmount['tax_amount'];
         }
         if (!empty($values['financial_type_id'])) {
             $customOption[$id]['financial_type_id'] = $financialType[$values['financial_type_id']];
         }
         // update enable/disable links depending on price_field properties.
         if ($this->_isSetReserved) {
             $action -= CRM_Core_Action::UPDATE + CRM_Core_Action::DELETE + CRM_Core_Action::DISABLE + CRM_Core_Action::ENABLE;
         } else {
             if ($values['is_active']) {
                 $action -= CRM_Core_Action::ENABLE;
             } else {
                 $action -= CRM_Core_Action::DISABLE;
             }
         }
         if (!empty($customOption[$id]['is_default'])) {
             $customOption[$id]['is_default'] = '<img src="' . $config->resourceBase . 'i/check.gif" />';
         } else {
             $customOption[$id]['is_default'] = '';
         }
         $customOption[$id]['order'] = $customOption[$id]['weight'];
         $customOption[$id]['action'] = CRM_Core_Action::formLink(self::actionLinks(), $action, array('oid' => $id, 'fid' => $this->_fid, 'sid' => $this->_sid), ts('more'), FALSE, 'priceFieldValue.row.actions', 'PriceFieldValue', $id);
     }
     // Add order changing widget to selector
     $returnURL = CRM_Utils_System::url('civicrm/admin/price/field/option', "action=browse&reset=1&fid={$this->_fid}&sid={$this->_sid}");
     $filter = "price_field_id = {$this->_fid}";
     CRM_Utils_Weight::addOrder($customOption, 'CRM_Price_DAO_PriceFieldValue', 'id', $returnURL, $filter);
     $this->assign('taxTerm', $taxTerm);
     $this->assign('getTaxDetails', $getTaxDetails);
     $this->assign('customOption', $customOption);
     $this->assign('sid', $this->_sid);
     $this->assign('isEvent', $isEvent);
 }
 /**
  * Process the form submission.
  */
 public function postProcess()
 {
     $sendReceipt = $pId = $contribution = $isRelatedId = FALSE;
     $softParams = $softIDs = array();
     if ($this->_action & CRM_Core_Action::DELETE) {
         CRM_Contribute_BAO_Contribution::deleteContribution($this->_id);
         CRM_Core_Session::singleton()->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=contribute"));
         return;
     }
     // Get the submitted form values.
     $submittedValues = $this->controller->exportValues($this->_name);
     if (!empty($submittedValues['price_set_id']) && $this->_action & CRM_Core_Action::UPDATE) {
         $line = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution');
         $lineID = key($line);
         $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array::value('price_field_id', $line[$lineID]), 'price_set_id');
         $quickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
         if ($quickConfig) {
             CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_contribution');
         }
     }
     // Process price set and get total amount and line items.
     $lineItem = array();
     $priceSetId = CRM_Utils_Array::value('price_set_id', $submittedValues);
     if (empty($priceSetId) && !$this->_id) {
         $this->_priceSetId = $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
         $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
         $fieldID = key($this->_priceSet['fields']);
         $fieldValueId = key($this->_priceSet['fields'][$fieldID]['options']);
         $this->_priceSet['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
         $submittedValues['price_' . $fieldID] = 1;
     }
     if ($priceSetId) {
         CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $submittedValues, $lineItem[$priceSetId]);
         // Unset tax amount for offline 'is_quick_config' contribution.
         if ($this->_priceSet['is_quick_config'] && !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant::getTaxRates())) {
             unset($submittedValues['tax_amount']);
         }
         $submittedValues['total_amount'] = CRM_Utils_Array::value('amount', $submittedValues);
     }
     if ($this->_id) {
         if ($this->_compId) {
             if ($this->_context == 'participant') {
                 $pId = $this->_compId;
             } elseif ($this->_context == 'membership') {
                 $isRelatedId = TRUE;
             } else {
                 $pId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'participant_id', 'contribution_id');
             }
         } else {
             $contributionDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
             if (array_key_exists('membership', $contributionDetails)) {
                 $isRelatedId = TRUE;
             } elseif (array_key_exists('participant', $contributionDetails)) {
                 $pId = $contributionDetails['participant'];
             }
         }
     }
     if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id) {
         // CRM-10117 update the line items for participants.
         if ($pId) {
             $entityTable = 'participant';
             $entityID = $pId;
             $isRelatedId = FALSE;
             $participantParams = array('fee_amount' => $submittedValues['total_amount'], 'id' => $entityID);
             CRM_Event_BAO_Participant::add($participantParams);
             if (empty($this->_lineItems)) {
                 $this->_lineItems[] = CRM_Price_BAO_LineItem::getLineItems($entityID, 'participant', 1);
             }
         } else {
             $entityTable = 'contribution';
             $entityID = $this->_id;
         }
         $lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entityTable, NULL, TRUE, $isRelatedId);
         foreach (array_keys($lineItems) as $id) {
             $lineItems[$id]['id'] = $id;
         }
         $itemId = key($lineItems);
         if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
             $this->_priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
         }
         if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
             $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value('total_amount', $submittedValues));
             // Update line total and total amount with tax on edit.
             $financialItemsId = CRM_Core_PseudoConstant::getTaxRates();
             if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
                 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
             } else {
                 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
                 $submittedValues['tax_amount'] = 'null';
             }
             if ($lineItems[$itemId]['tax_rate']) {
                 $lineItems[$itemId]['tax_amount'] = $lineItems[$itemId]['tax_rate'] / 100 * $lineItems[$itemId]['line_total'];
                 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] + $lineItems[$itemId]['tax_amount'];
                 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
             }
         }
         // CRM-10117 update the line items for participants.
         if (!empty($lineItems[$itemId]['price_field_id'])) {
             $lineItem[$this->_priceSetId] = $lineItems;
         }
     }
     $isQuickConfig = 0;
     if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
         $isQuickConfig = 1;
     }
     //CRM-11529 for quick config back office transactions
     //when financial_type_id is passed in form, update the
     //line items with the financial type selected in form
     if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array::value($this->_priceSetId, $lineItem)) {
         foreach ($lineItem[$this->_priceSetId] as &$values) {
             $values['financial_type_id'] = $submittedValues['financial_type_id'];
         }
     }
     if (!isset($submittedValues['total_amount'])) {
         $submittedValues['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_values);
     }
     $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
     if (!empty($submittedValues['pcp_made_through_id'])) {
         $pcp = array();
         $fields = array('pcp_made_through_id', 'pcp_display_in_roll', 'pcp_roll_nickname', 'pcp_personal_note');
         foreach ($fields as $f) {
             $pcp[$f] = CRM_Utils_Array::value($f, $submittedValues);
         }
     }
     $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
     if ($this->_id && count($isEmpty) == 1 && key($isEmpty) == NULL) {
         //Delete existing soft credit records if soft credit list is empty on update
         CRM_Contribute_BAO_ContributionSoft::del(array('contribution_id' => $this->_id));
     } else {
         //build soft credit params
         foreach ($submittedValues['soft_credit_contact_id'] as $key => $val) {
             if ($val && $submittedValues['soft_credit_amount'][$key]) {
                 $softParams[$key]['contact_id'] = $val;
                 $softParams[$key]['amount'] = CRM_Utils_Rule::cleanMoney($submittedValues['soft_credit_amount'][$key]);
                 $softParams[$key]['soft_credit_type_id'] = $submittedValues['soft_credit_type'][$key];
                 if (!empty($submittedValues['soft_credit_id'][$key])) {
                     $softIDs[] = $softParams[$key]['id'] = $submittedValues['soft_credit_id'][$key];
                 }
             }
         }
     }
     // set the contact, when contact is selected
     if (!empty($submittedValues['contact_id'])) {
         $this->_contactID = $submittedValues['contact_id'];
     }
     // Credit Card Contribution.
     if ($this->_mode) {
         $this->processCreditCard($submittedValues, $lineItem);
     } else {
         // Offline Contribution.
         $submittedValues = $this->unsetCreditCardFields($submittedValues);
         // get the required field value only.
         $formValues = $submittedValues;
         $params = $ids = array();
         $params['contact_id'] = $this->_contactID;
         $params['currency'] = $this->getCurrency($submittedValues);
         $fields = array('financial_type_id', 'contribution_status_id', 'payment_instrument_id', 'cancel_reason', 'source', 'check_number');
         foreach ($fields as $f) {
             $params[$f] = CRM_Utils_Array::value($f, $formValues);
         }
         if (!empty($pcp)) {
             $params['pcp'] = $pcp;
         }
         if (!empty($softParams)) {
             $params['soft_credit'] = $softParams;
             $params['soft_credit_ids'] = $softIDs;
         }
         // CRM-5740 if priceset is used, no need to cleanup money.
         if ($priceSetId) {
             $params['skipCleanMoney'] = 1;
         }
         $dates = array('receive_date', 'receipt_date', 'cancel_date');
         foreach ($dates as $d) {
             $params[$d] = CRM_Utils_Date::processDate($formValues[$d], $formValues[$d . '_time'], TRUE);
         }
         if (!empty($formValues['is_email_receipt'])) {
             $params['receipt_date'] = date("Y-m-d");
         }
         if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Cancelled', 'name') || $params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name')) {
             if (CRM_Utils_System::isNull(CRM_Utils_Array::value('cancel_date', $params))) {
                 $params['cancel_date'] = date('Y-m-d');
             }
         } else {
             $params['cancel_date'] = $params['cancel_reason'] = 'null';
         }
         // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
         // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
         if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) {
             $params['is_pay_later'] = 1;
         } elseif ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
             $params['is_pay_later'] = 0;
         }
         $ids['contribution'] = $params['id'] = $this->_id;
         // Add Additional common information to formatted params.
         CRM_Contribute_Form_AdditionalInfo::postProcessCommon($formValues, $params, $this);
         if ($pId) {
             $params['contribution_mode'] = 'participant';
             $params['participant_id'] = $pId;
             $params['skipLineItem'] = 1;
         } elseif ($isRelatedId) {
             $params['contribution_mode'] = 'membership';
         }
         $params['line_item'] = $lineItem;
         $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array::value('id', $this->_paymentProcessor);
         if (isset($submittedValues['tax_amount'])) {
             $params['tax_amount'] = $submittedValues['tax_amount'];
         }
         //create contribution.
         if ($isQuickConfig) {
             $params['is_quick_config'] = 1;
         }
         // CRM-11956
         // if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
         // if non_deductible_amount does NOT exist - then calculate it depending on:
         // $ContributionType->is_deductible and whether there is a product (premium).
         if (empty($params['non_deductible_amount'])) {
             $contributionType = new CRM_Financial_DAO_FinancialType();
             $contributionType->id = $params['financial_type_id'];
             if (!$contributionType->find(TRUE)) {
                 CRM_Core_Error::fatal('Could not find a system table');
             }
             if ($contributionType->is_deductible) {
                 if (isset($formValues['product_name'][0])) {
                     $selectProduct = $formValues['product_name'][0];
                 }
                 // if there is a product - compare the value to the contribution amount
                 if (isset($selectProduct)) {
                     $productDAO = new CRM_Contribute_DAO_Product();
                     $productDAO->id = $selectProduct;
                     $productDAO->find(TRUE);
                     // product value exceeds contribution amount
                     if ($params['total_amount'] < $productDAO->price) {
                         $params['non_deductible_amount'] = $params['total_amount'];
                     } else {
                         $params['non_deductible_amount'] = $productDAO->price;
                     }
                 } else {
                     $params['non_deductible_amount'] = '0.00';
                 }
             } else {
                 $params['non_deductible_amount'] = $params['total_amount'];
             }
         }
         $contribution = CRM_Contribute_BAO_Contribution::create($params, $ids);
         // process associated membership / participant, CRM-4395
         $relatedComponentStatusMsg = NULL;
         if ($contribution->id && $this->_action & CRM_Core_Action::UPDATE) {
             $relatedComponentStatusMsg = $this->updateRelatedComponent($contribution->id, $contribution->contribution_status_id, CRM_Utils_Array::value('contribution_status_id', $this->_values), $contribution->receive_date);
         }
         //process  note
         if ($contribution->id && isset($formValues['note'])) {
             CRM_Contribute_Form_AdditionalInfo::processNote($formValues, $this->_contactID, $contribution->id, $this->_noteID);
         }
         //process premium
         if ($contribution->id && isset($formValues['product_name'][0])) {
             CRM_Contribute_Form_AdditionalInfo::processPremium($formValues, $contribution->id, $this->_premiumID, $this->_options);
         }
         // assign tax calculation for contribution receipts
         $taxRate = array();
         $getTaxDetails = FALSE;
         $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
         $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
         if ($invoicing) {
             if ($this->_action & CRM_Core_Action::ADD) {
                 $line = $lineItem;
             } elseif ($this->_action & CRM_Core_Action::UPDATE) {
                 $line = $this->_lineItems;
             }
             foreach ($line as $key => $value) {
                 foreach ($value as $v) {
                     if (isset($taxRate[(string) CRM_Utils_Array::value('tax_rate', $v)])) {
                         $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array::value('tax_amount', $v);
                     } else {
                         if (isset($v['tax_rate'])) {
                             $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array::value('tax_amount', $v);
                             $getTaxDetails = TRUE;
                         }
                     }
                 }
             }
         }
         if ($invoicing) {
             if ($this->_action & CRM_Core_Action::UPDATE) {
                 if (isset($submittedValues['tax_amount'])) {
                     $totalTaxAmount = $submittedValues['tax_amount'];
                 } else {
                     $totalTaxAmount = $this->_values['tax_amount'];
                 }
                 $this->assign('totalTaxAmount', $totalTaxAmount);
                 $this->assign('dataArray', $taxRate);
             } else {
                 if (!empty($submittedValues['price_set_id'])) {
                     $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
                     $this->assign('getTaxDetails', $getTaxDetails);
                     $this->assign('dataArray', $taxRate);
                     $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
                 } else {
                     $this->assign('totalTaxAmount', CRM_Utils_Array::value('tax_amount', $submittedValues));
                 }
             }
         }
         //send receipt mail.
         if ($contribution->id && !empty($formValues['is_email_receipt'])) {
             $formValues['contact_id'] = $this->_contactID;
             $formValues['contribution_id'] = $contribution->id;
             $formValues += CRM_Contribute_BAO_ContributionSoft::getSoftContribution($contribution->id);
             // to get 'from email id' for send receipt
             $this->fromEmailId = $formValues['from_email_address'];
             $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $formValues);
         }
         $pledgePaymentId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $contribution->id, 'id', 'contribution_id');
         //update pledge payment status.
         if ($this->_ppID && $contribution->id && $this->_action & CRM_Core_Action::ADD || $pledgePaymentId && $this->_action & CRM_Core_Action::UPDATE) {
             if ($this->_ppID) {
                 //store contribution id in payment record.
                 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID, 'contribution_id', $contribution->id);
             } else {
                 $this->_ppID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $contribution->id, 'id', 'contribution_id');
                 $this->_pledgeID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $contribution->id, 'pledge_id', 'contribution_id');
             }
             $adjustTotalAmount = FALSE;
             if (CRM_Utils_Array::value('option_type', $formValues) == 2) {
                 $adjustTotalAmount = TRUE;
             }
             $updatePledgePaymentStatus = FALSE;
             //do only if either the status or the amount has changed
             if ($this->_action & CRM_Core_Action::ADD) {
                 $updatePledgePaymentStatus = TRUE;
             } elseif ($this->_action & CRM_Core_Action::UPDATE && ($this->_defaults['contribution_status_id'] != $formValues['contribution_status_id'] || $this->_defaults['total_amount'] != $formValues['total_amount'])) {
                 $updatePledgePaymentStatus = TRUE;
             }
             if ($updatePledgePaymentStatus) {
                 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($this->_pledgeID, array($this->_ppID), $contribution->contribution_status_id, NULL, $contribution->total_amount, $adjustTotalAmount);
             }
         }
         $statusMsg = ts('The contribution record has been saved.');
         if (!empty($formValues['is_email_receipt']) && $sendReceipt) {
             $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
         }
         if ($relatedComponentStatusMsg) {
             $statusMsg .= ' ' . $relatedComponentStatusMsg;
         }
         CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
         //Offline Contribution ends.
     }
     $session = CRM_Core_Session::singleton();
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contribute/add', 'reset=1&action=add&context=standalone'));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=contribute"));
         }
     } elseif ($this->_context == 'contribution' && $this->_mode && $buttonName == $this->getButtonName('upload', 'new')) {
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution', "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"));
     } elseif ($buttonName == $this->getButtonName('upload', 'new')) {
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution', "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"));
     }
     //store contribution ID if not yet set (on create)
     if (empty($this->_id) && !empty($contribution->id)) {
         $this->_id = $contribution->id;
     }
 }
示例#7
0
 /**
  * Browse all price set fields.
  *
  * @return void
  */
 public function browse()
 {
     $resourceManager = CRM_Core_Resources::singleton();
     if (!empty($_GET['new']) && $resourceManager->ajaxPopupsEnabled) {
         $resourceManager->addScriptFile('civicrm', 'js/crm.addNew.js', 999, 'html-header');
     }
     $priceField = array();
     $priceFieldBAO = new CRM_Price_BAO_PriceField();
     // fkey is sid
     $priceFieldBAO->price_set_id = $this->_sid;
     $priceFieldBAO->orderBy('weight, label');
     $priceFieldBAO->find();
     // display taxTerm for priceFields
     $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
     $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
     $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
     $getTaxDetails = FALSE;
     $taxRate = CRM_Core_PseudoConstant::getTaxRates();
     CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes);
     while ($priceFieldBAO->fetch()) {
         $priceField[$priceFieldBAO->id] = array();
         CRM_Core_DAO::storeValues($priceFieldBAO, $priceField[$priceFieldBAO->id]);
         // get price if it's a text field
         if ($priceFieldBAO->html_type == 'Text') {
             $optionValues = array();
             $params = array('price_field_id' => $priceFieldBAO->id);
             CRM_Price_BAO_PriceFieldValue::retrieve($params, $optionValues);
             $financialTypeId = $optionValues['financial_type_id'];
             if (!array_key_exists($financialTypeId, $financialTypes)) {
                 unset($priceField[$priceFieldBAO->id]);
                 continue;
             }
             $priceField[$priceFieldBAO->id]['price'] = CRM_Utils_Array::value('amount', $optionValues);
             if ($invoicing && isset($taxRate[$financialTypeId])) {
                 $priceField[$priceFieldBAO->id]['tax_rate'] = $taxRate[$financialTypeId];
                 $getTaxDetails = TRUE;
             }
             if (isset($priceField[$priceFieldBAO->id]['tax_rate'])) {
                 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($priceField[$priceFieldBAO->id]['price'], $priceField[$priceFieldBAO->id]['tax_rate']);
                 $priceField[$priceFieldBAO->id]['tax_amount'] = $taxAmount['tax_amount'];
             }
         }
         $action = array_sum(array_keys(self::actionLinks()));
         if ($this->_isSetReserved) {
             $action -= CRM_Core_Action::UPDATE + CRM_Core_Action::DELETE + CRM_Core_Action::ENABLE + CRM_Core_Action::DISABLE;
         } else {
             if ($priceFieldBAO->is_active) {
                 $action -= CRM_Core_Action::ENABLE;
             } else {
                 $action -= CRM_Core_Action::DISABLE;
             }
         }
         if ($priceFieldBAO->active_on == '0000-00-00 00:00:00') {
             $priceField[$priceFieldBAO->id]['active_on'] = '';
         }
         if ($priceFieldBAO->expire_on == '0000-00-00 00:00:00') {
             $priceField[$priceFieldBAO->id]['expire_on'] = '';
         }
         // need to translate html types from the db
         $htmlTypes = CRM_Price_BAO_PriceField::htmlTypes();
         $priceField[$priceFieldBAO->id]['html_type_display'] = $htmlTypes[$priceField[$priceFieldBAO->id]['html_type']];
         $priceField[$priceFieldBAO->id]['order'] = $priceField[$priceFieldBAO->id]['weight'];
         $priceField[$priceFieldBAO->id]['action'] = CRM_Core_Action::formLink(self::actionLinks(), $action, array('fid' => $priceFieldBAO->id, 'sid' => $this->_sid), ts('more'), FALSE, 'priceField.row.actions', 'PriceField', $priceFieldBAO->id);
         $this->assign('taxTerm', $taxTerm);
         $this->assign('getTaxDetails', $getTaxDetails);
     }
     $returnURL = CRM_Utils_System::url('civicrm/admin/price/field', "reset=1&action=browse&sid={$this->_sid}");
     $filter = "price_set_id = {$this->_sid}";
     CRM_Utils_Weight::addOrder($priceField, 'CRM_Price_DAO_PriceField', 'id', $returnURL, $filter);
     $this->assign('priceField', $priceField);
 }
示例#8
0
 /**
  * Build the form object.
  */
 public function buildQuickForm()
 {
     parent::buildQuickForm();
     $defaults = parent::setDefaultValues();
     $this->_memType = $defaults['membership_type_id'];
     $this->assign('customDataType', 'Membership');
     $this->assign('customDataSubType', $this->_memType);
     $this->assign('entityID', $this->_id);
     $selOrgMemType[0][0] = $selMemTypeOrg[0] = ts('- select -');
     $allMembershipInfo = array();
     //CRM-16950
     $taxRates = CRM_Core_PseudoConstant::getTaxRates();
     $taxRate = CRM_Utils_Array::value($allMemberships[$defaults['membership_type_id']]['financial_type_id'], $taxRates);
     $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
     // auto renew options if enabled for the membership
     $options = CRM_Core_SelectValues::memberAutoRenew();
     foreach ($this->allMembershipTypeDetails as $key => $values) {
         if (!empty($values['is_active'])) {
             if ($this->_mode && empty($values['minimum_fee'])) {
                 continue;
             } else {
                 $memberOfContactId = CRM_Utils_Array::value('member_of_contact_id', $values);
                 if (empty($selMemTypeOrg[$memberOfContactId])) {
                     $selMemTypeOrg[$memberOfContactId] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $memberOfContactId, 'display_name', 'id');
                     $selOrgMemType[$memberOfContactId][0] = ts('- select -');
                 }
                 if (empty($selOrgMemType[$memberOfContactId][$key])) {
                     $selOrgMemType[$memberOfContactId][$key] = CRM_Utils_Array::value('name', $values);
                 }
             }
             //CRM-16950
             $taxAmount = NULL;
             $totalAmount = CRM_Utils_Array::value('minimum_fee', $values);
             if (CRM_Utils_Array::value($values['financial_type_id'], $taxRates)) {
                 $taxAmount = $taxRate / 100 * CRM_Utils_Array::value('minimum_fee', $values);
                 $totalAmount = $totalAmount + $taxAmount;
             }
             // build membership info array, which is used to set the payment information block when
             // membership type is selected.
             $allMembershipInfo[$key] = array('financial_type_id' => CRM_Utils_Array::value('financial_type_id', $values), 'total_amount' => CRM_Utils_Money::format($totalAmount, NULL, '%a'), 'total_amount_numeric' => $totalAmount, 'tax_message' => $taxAmount ? ts("Includes %1 amount of %2", array(1 => CRM_Utils_Array::value('tax_term', $invoiceSettings), 2 => CRM_Utils_Money::format($taxAmount))) : $taxAmount);
             if (!empty($values['auto_renew'])) {
                 $allMembershipInfo[$key]['auto_renew'] = $options[$values['auto_renew']];
             }
         }
     }
     $this->assign('allMembershipInfo', json_encode($allMembershipInfo));
     if ($this->_memType) {
         $this->assign('orgName', $selMemTypeOrg[$this->allMembershipTypeDetails[$this->_memType]['member_of_contact_id']]);
         $this->assign('memType', $this->allMembershipTypeDetails[$this->_memType]['name']);
     }
     // force select of organization by default, if only one organization in
     // the list
     if (count($selMemTypeOrg) == 2) {
         unset($selMemTypeOrg[0], $selOrgMemType[0][0]);
     }
     //sort membership organization and type, CRM-6099
     natcasesort($selMemTypeOrg);
     foreach ($selOrgMemType as $index => $orgMembershipType) {
         natcasesort($orgMembershipType);
         $selOrgMemType[$index] = $orgMembershipType;
     }
     $js = array('onChange' => "setPaymentBlock(); CRM.buildCustomData('Membership', this.value);");
     $sel =& $this->addElement('hierselect', 'membership_type_id', ts('Renewal Membership Organization and Type'), $js);
     $sel->setOptions(array($selMemTypeOrg, $selOrgMemType));
     $elements = array();
     if ($sel) {
         $elements[] = $sel;
     }
     $this->applyFilter('__ALL__', 'trim');
     $this->addDate('renewal_date', ts('Date Renewal Entered'), FALSE, array('formatType' => 'activityDate'));
     $this->add('select', 'financial_type_id', ts('Financial Type'), array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::financialType());
     $this->add('text', 'num_terms', ts('Extend Membership by'), array('onchange' => "setPaymentBlock();"), TRUE);
     $this->addRule('num_terms', ts('Please enter a whole number for how many periods to renew.'), 'integer');
     if (CRM_Core_Permission::access('CiviContribute') && !$this->_mode) {
         $this->addElement('checkbox', 'record_contribution', ts('Record Renewal Payment?'), NULL, array('onclick' => "checkPayment();"));
         $this->add('text', 'total_amount', ts('Amount'));
         $this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
         $this->addDate('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
         $this->add('select', 'payment_instrument_id', ts('Payment Method'), array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(), FALSE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);"));
         $this->add('text', 'trxn_id', ts('Transaction ID'));
         $this->addRule('trxn_id', ts('Transaction ID already exists in Database.'), 'objectExists', array('CRM_Contribute_DAO_Contribution', $this->_id, 'trxn_id'));
         $this->add('select', 'contribution_status_id', ts('Payment Status'), CRM_Contribute_PseudoConstant::contributionStatus());
         $this->add('text', 'check_number', ts('Check Number'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution', 'check_number'));
     } else {
         $this->add('text', 'total_amount', ts('Amount'));
         $this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
     }
     $this->addElement('checkbox', 'send_receipt', ts('Send Confirmation and Receipt?'), NULL, array('onclick' => "showHideByValue( 'send_receipt', '', 'notice', 'table-row', 'radio', false ); showHideByValue( 'send_receipt', '', 'fromEmail', 'table-row', 'radio',false);"));
     $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
     $this->add('textarea', 'receipt_text_renewal', ts('Renewal Message'));
     // Retrieve the name and email of the contact - this will be the TO for receipt email
     list($this->_contributorDisplayName, $this->_contributorEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
     $this->assign('email', $this->_contributorEmail);
     // The member form uses emailExists. Assigning both while we transition / synchronise.
     $this->assign('emailExists', $this->_contributorEmail);
     $mailingInfo = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME, 'mailing_backend');
     $this->assign('outBound_option', $mailingInfo['outBound_option']);
     if (CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_id, 'contribution_recur_id')) {
         if (CRM_Member_BAO_Membership::isCancelSubscriptionSupported($this->_id)) {
             $this->assign('cancelAutoRenew', CRM_Utils_System::url('civicrm/contribute/unsubscribe', "reset=1&mid={$this->_id}"));
         }
     }
     $this->addFormRule(array('CRM_Member_Form_MembershipRenewal', 'formRule'));
     $this->addElement('checkbox', 'is_different_contribution_contact', ts('Record Payment from a Different
   Contact?'));
     $this->addSelect('soft_credit_type_id', array('entity' => 'contribution_soft'));
     $this->addEntityRef('soft_credit_contact_id', ts('Payment From'), array('create' => TRUE));
 }
示例#9
0
 /**
  * @param array $submittedValues
  *
  * @param int $action
  *   Action constant
  *    - CRM_Core_Action::UPDATE
  *
  * @param $pledgePaymentID
  *
  * @return array
  * @throws \Exception
  */
 protected function submit($submittedValues, $action, $pledgePaymentID)
 {
     $softParams = $softIDs = array();
     $pId = $contribution = $isRelatedId = FALSE;
     if (!empty($submittedValues['price_set_id']) && $action & CRM_Core_Action::UPDATE) {
         $line = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution');
         $lineID = key($line);
         $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array::value('price_field_id', $line[$lineID]), 'price_set_id');
         $quickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
         if ($quickConfig) {
             CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_contribution');
         }
     }
     // Process price set and get total amount and line items.
     $lineItem = array();
     $priceSetId = CRM_Utils_Array::value('price_set_id', $submittedValues);
     if (empty($priceSetId) && !$this->_id) {
         $this->_priceSetId = $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
         $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
         $fieldID = key($this->_priceSet['fields']);
         $fieldValueId = key($this->_priceSet['fields'][$fieldID]['options']);
         $this->_priceSet['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
         $submittedValues['price_' . $fieldID] = 1;
     }
     if ($priceSetId) {
         CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $submittedValues, $lineItem[$priceSetId]);
         // Unset tax amount for offline 'is_quick_config' contribution.
         if ($this->_priceSet['is_quick_config'] && !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant::getTaxRates())) {
             unset($submittedValues['tax_amount']);
         }
         $submittedValues['total_amount'] = CRM_Utils_Array::value('amount', $submittedValues);
     }
     if ($this->_id) {
         if ($this->_compId) {
             if ($this->_context == 'participant') {
                 $pId = $this->_compId;
             } elseif ($this->_context == 'membership') {
                 $isRelatedId = TRUE;
             } else {
                 $pId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'participant_id', 'contribution_id');
             }
         } else {
             $contributionDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
             if (array_key_exists('membership', $contributionDetails)) {
                 $isRelatedId = TRUE;
             } elseif (array_key_exists('participant', $contributionDetails)) {
                 $pId = $contributionDetails['participant'];
             }
         }
     }
     if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id) {
         // CRM-10117 update the line items for participants.
         if ($pId) {
             $entityTable = 'participant';
             $entityID = $pId;
             $isRelatedId = FALSE;
             $participantParams = array('fee_amount' => $submittedValues['total_amount'], 'id' => $entityID);
             CRM_Event_BAO_Participant::add($participantParams);
             if (empty($this->_lineItems)) {
                 $this->_lineItems[] = CRM_Price_BAO_LineItem::getLineItems($entityID, 'participant', 1);
             }
         } else {
             $entityTable = 'contribution';
             $entityID = $this->_id;
         }
         $lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entityTable, NULL, TRUE, $isRelatedId);
         foreach (array_keys($lineItems) as $id) {
             $lineItems[$id]['id'] = $id;
         }
         $itemId = key($lineItems);
         if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
             $this->_priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
         }
         if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
             $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value('total_amount', $submittedValues));
             // Update line total and total amount with tax on edit.
             $financialItemsId = CRM_Core_PseudoConstant::getTaxRates();
             if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
                 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
             } else {
                 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
                 $submittedValues['tax_amount'] = 'null';
             }
             if ($lineItems[$itemId]['tax_rate']) {
                 $lineItems[$itemId]['tax_amount'] = $lineItems[$itemId]['tax_rate'] / 100 * $lineItems[$itemId]['line_total'];
                 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] + $lineItems[$itemId]['tax_amount'];
                 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
             }
         }
         // CRM-10117 update the line items for participants.
         if (!empty($lineItems[$itemId]['price_field_id'])) {
             $lineItem[$this->_priceSetId] = $lineItems;
         }
     }
     $isQuickConfig = 0;
     if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
         $isQuickConfig = 1;
     }
     //CRM-11529 for quick config back office transactions
     //when financial_type_id is passed in form, update the
     //line items with the financial type selected in form
     if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array::value($this->_priceSetId, $lineItem)) {
         foreach ($lineItem[$this->_priceSetId] as &$values) {
             $values['financial_type_id'] = $submittedValues['financial_type_id'];
         }
     }
     if (!isset($submittedValues['total_amount'])) {
         $submittedValues['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_values);
     }
     $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
     if (!empty($submittedValues['pcp_made_through_id'])) {
         $pcp = array();
         $fields = array('pcp_made_through_id', 'pcp_display_in_roll', 'pcp_roll_nickname', 'pcp_personal_note');
         foreach ($fields as $f) {
             $pcp[$f] = CRM_Utils_Array::value($f, $submittedValues);
         }
     }
     $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
     if ($this->_id && count($isEmpty) == 1 && key($isEmpty) == NULL) {
         //Delete existing soft credit records if soft credit list is empty on update
         CRM_Contribute_BAO_ContributionSoft::del(array('contribution_id' => $this->_id));
     } else {
         //build soft credit params
         foreach ($submittedValues['soft_credit_contact_id'] as $key => $val) {
             if ($val && $submittedValues['soft_credit_amount'][$key]) {
                 $softParams[$key]['contact_id'] = $val;
                 $softParams[$key]['amount'] = CRM_Utils_Rule::cleanMoney($submittedValues['soft_credit_amount'][$key]);
                 $softParams[$key]['soft_credit_type_id'] = $submittedValues['soft_credit_type'][$key];
                 if (!empty($submittedValues['soft_credit_id'][$key])) {
                     $softIDs[] = $softParams[$key]['id'] = $submittedValues['soft_credit_id'][$key];
                 }
             }
         }
     }
     // set the contact, when contact is selected
     if (!empty($submittedValues['contact_id'])) {
         $this->_contactID = $submittedValues['contact_id'];
     }
     $formValues = $submittedValues;
     // Credit Card Contribution.
     if ($this->_mode) {
         $paramsSetByPaymentProcessingSubsystem = array('trxn_id', 'payment_instrument_id', 'contribution_status_id', 'cancel_date', 'cancel_reason');
         foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
             if (isset($formValues[$key])) {
                 unset($formValues[$key]);
             }
         }
         $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID);
         foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
             $formValues[$key] = $contribution->{$key};
         }
     } else {
         // Offline Contribution.
         $submittedValues = $this->unsetCreditCardFields($submittedValues);
         // get the required field value only.
         $params = $ids = array();
         $params['contact_id'] = $this->_contactID;
         $params['currency'] = $this->getCurrency($submittedValues);
         $fields = array('financial_type_id', 'contribution_status_id', 'payment_instrument_id', 'cancel_reason', 'source', 'check_number');
         foreach ($fields as $f) {
             $params[$f] = CRM_Utils_Array::value($f, $formValues);
         }
         if (!empty($pcp)) {
             $params['pcp'] = $pcp;
         }
         if (!empty($softParams)) {
             $params['soft_credit'] = $softParams;
             $params['soft_credit_ids'] = $softIDs;
         }
         // CRM-5740 if priceset is used, no need to cleanup money.
         if ($priceSetId) {
             $params['skipCleanMoney'] = 1;
         }
         $dates = array('receive_date', 'receipt_date', 'cancel_date');
         foreach ($dates as $d) {
             $params[$d] = CRM_Utils_Date::processDate($formValues[$d], $formValues[$d . '_time'], TRUE);
         }
         if (!empty($formValues['is_email_receipt'])) {
             $params['receipt_date'] = date("Y-m-d");
         }
         if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Cancelled', 'name') || $params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name')) {
             if (CRM_Utils_System::isNull(CRM_Utils_Array::value('cancel_date', $params))) {
                 $params['cancel_date'] = date('Y-m-d');
             }
         } else {
             $params['cancel_date'] = $params['cancel_reason'] = 'null';
         }
         // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
         // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
         if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) {
             $params['is_pay_later'] = 1;
         } elseif ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
             $params['is_pay_later'] = 0;
         }
         $ids['contribution'] = $params['id'] = $this->_id;
         // Add Additional common information to formatted params.
         CRM_Contribute_Form_AdditionalInfo::postProcessCommon($formValues, $params, $this);
         if ($pId) {
             $params['contribution_mode'] = 'participant';
             $params['participant_id'] = $pId;
             $params['skipLineItem'] = 1;
         } elseif ($isRelatedId) {
             $params['contribution_mode'] = 'membership';
         }
         $params['line_item'] = $lineItem;
         $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array::value('id', $this->_paymentProcessor);
         if (isset($submittedValues['tax_amount'])) {
             $params['tax_amount'] = $submittedValues['tax_amount'];
         }
         //create contribution.
         if ($isQuickConfig) {
             $params['is_quick_config'] = 1;
         }
         $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
         $contribution = CRM_Contribute_BAO_Contribution::create($params, $ids);
         // process associated membership / participant, CRM-4395
         if ($contribution->id && $action & CRM_Core_Action::UPDATE) {
             $this->statusMessage[] = $this->updateRelatedComponent($contribution->id, $contribution->contribution_status_id, CRM_Utils_Array::value('contribution_status_id', $this->_values), $contribution->receive_date);
         }
         array_unshift($this->statusMessage, ts('The contribution record has been saved.'));
         $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
         //send receipt mail.
         if ($contribution->id && !empty($formValues['is_email_receipt'])) {
             $formValues['contact_id'] = $this->_contactID;
             $formValues['contribution_id'] = $contribution->id;
             $formValues += CRM_Contribute_BAO_ContributionSoft::getSoftContribution($contribution->id);
             // to get 'from email id' for send receipt
             $this->fromEmailId = $formValues['from_email_address'];
             if (CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $formValues)) {
                 $this->statusMessage[] = ts('A receipt has been emailed to the contributor.');
             }
         }
         $this->statusMessageTitle = ts('Saved');
     }
     if ($contribution->id && !empty($formValues['product_name'][0])) {
         CRM_Contribute_Form_AdditionalInfo::processPremium($submittedValues, $contribution->id, $this->_premiumID, $this->_options);
     }
     if ($contribution->id && isset($submittedValues['note'])) {
         CRM_Contribute_Form_AdditionalInfo::processNote($submittedValues, $this->_contactID, $contribution->id, $this->_noteID);
     }
     CRM_Core_Session::setStatus(implode(' ', $this->statusMessage), $this->statusMessageTitle, 'success');
     CRM_Contribute_BAO_Contribution::updateRelatedPledge($action, $pledgePaymentID, $contribution->id, CRM_Utils_Array::value('option_type', $formValues) == 2 ? TRUE : FALSE, $formValues['total_amount'], CRM_Utils_Array::value('total_amount', $this->_defaults), $formValues['contribution_status_id'], CRM_Utils_Array::value('contribution_status_id', $this->_defaults));
     return $contribution;
 }
示例#10
0
 /**
  * Get line item purchase information.
  *
  * This function takes the input parameters and interprets out of it what has been purchased.
  *
  * @param $fields
  *   This is the output of the function CRM_Price_BAO_PriceSet::getSetDetail($priceSetID, FALSE, FALSE);
  *   And, it would make sense to introduce caching into that function and call it from here rather than
  *   require the $fields array which is passed from pillar to post around the form in order to pass it in here.
  * @param array $params
  *   Params reflecting form input e.g with fields 'price_5' => 7, 'price_8' => array(7, 8)
  * @param $lineItem
  *   Line item array to be altered.
  * @param string $component
  *   This parameter appears to only be relevant to determining whether memberships should be auto-renewed.
  *   (and is effectively a boolean for 'is_membership' which could be calculated from the line items.)
  */
 public static function processAmount($fields, &$params, &$lineItem, $component = '')
 {
     // using price set
     $totalPrice = $totalTax = 0;
     $radioLevel = $checkboxLevel = $selectLevel = $textLevel = array();
     if ($component) {
         $autoRenew = array();
         $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
     }
     foreach ($fields as $id => $field) {
         if (empty($params["price_{$id}"]) || empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL) {
             // skip if nothing was submitted for this field
             continue;
         }
         switch ($field['html_type']) {
             case 'Text':
                 $firstOption = reset($field['options']);
                 $params["price_{$id}"] = array($firstOption['id'] => $params["price_{$id}"]);
                 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
                 if (CRM_Utils_Array::value('tax_rate', $field['options'][key($field['options'])])) {
                     $lineItem = self::setLineItem($field, $lineItem, key($field['options']));
                     $totalTax += $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
                 }
                 if (CRM_Utils_Array::value('name', $field['options'][key($field['options'])]) == 'contribution_amount') {
                     $taxRates = CRM_Core_PseudoConstant::getTaxRates();
                     if (array_key_exists($params['financial_type_id'], $taxRates)) {
                         $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']];
                         $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($field['options'][key($field['options'])]['amount'], $field['options'][key($field['options'])]['tax_rate']);
                         $field['options'][key($field['options'])]['tax_amount'] = round($taxAmount['tax_amount'], 2);
                         $lineItem = self::setLineItem($field, $lineItem, key($field['options']));
                         $totalTax += $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
                     }
                 }
                 $totalPrice += $lineItem[$firstOption['id']]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[key($field['options'])]);
                 break;
             case 'Radio':
                 //special case if user select -none-
                 if ($params["price_{$id}"] <= 0) {
                     continue;
                 }
                 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
                 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
                 $optionLabel = CRM_Utils_Array::value('label', $field['options'][$optionValueId]);
                 $params['amount_priceset_level_radio'] = array();
                 $params['amount_priceset_level_radio'][$optionValueId] = $optionLabel;
                 if (isset($radioLevel)) {
                     $radioLevel = array_merge($radioLevel, array_keys($params['amount_priceset_level_radio']));
                 } else {
                     $radioLevel = array_keys($params['amount_priceset_level_radio']);
                 }
                 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
                 if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionValueId])) {
                     $lineItem = self::setLineItem($field, $lineItem, $optionValueId);
                     $totalTax += $field['options'][$optionValueId]['tax_amount'];
                     if (CRM_Utils_Array::value('field_title', $lineItem[$optionValueId]) == 'Membership Amount') {
                         $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
                     }
                 }
                 $totalPrice += $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionValueId]);
                 if ($component && isset($lineItem[$optionValueId]['auto_renew']) && is_numeric($lineItem[$optionValueId]['auto_renew'])) {
                     $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total'];
                 }
                 break;
             case 'Select':
                 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
                 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
                 $optionLabel = $field['options'][$optionValueId]['label'];
                 $params['amount_priceset_level_select'] = array();
                 $params['amount_priceset_level_select'][CRM_Utils_Array::key(1, $params["price_{$id}"])] = $optionLabel;
                 if (isset($selectLevel)) {
                     $selectLevel = array_merge($selectLevel, array_keys($params['amount_priceset_level_select']));
                 } else {
                     $selectLevel = array_keys($params['amount_priceset_level_select']);
                 }
                 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
                 if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionValueId])) {
                     $lineItem = self::setLineItem($field, $lineItem, $optionValueId);
                     $totalTax += $field['options'][$optionValueId]['tax_amount'];
                 }
                 $totalPrice += $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionValueId]);
                 if ($component && isset($lineItem[$optionValueId]['auto_renew']) && is_numeric($lineItem[$optionValueId]['auto_renew'])) {
                     $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total'];
                 }
                 break;
             case 'CheckBox':
                 $params['amount_priceset_level_checkbox'] = $optionIds = array();
                 foreach ($params["price_{$id}"] as $optionId => $option) {
                     $optionIds[] = $optionId;
                     $optionLabel = $field['options'][$optionId]['label'];
                     $params['amount_priceset_level_checkbox']["{$field['options'][$optionId]['id']}"] = $optionLabel;
                     if (isset($checkboxLevel)) {
                         $checkboxLevel = array_unique(array_merge($checkboxLevel, array_keys($params['amount_priceset_level_checkbox'])));
                     } else {
                         $checkboxLevel = array_keys($params['amount_priceset_level_checkbox']);
                     }
                 }
                 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
                 foreach ($optionIds as $optionId) {
                     if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionId])) {
                         $lineItem = self::setLineItem($field, $lineItem, $optionId);
                         $totalTax += $field['options'][$optionId]['tax_amount'];
                     }
                     $totalPrice += $lineItem[$optionId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionId]);
                     if ($component && isset($lineItem[$optionId]['auto_renew']) && is_numeric($lineItem[$optionId]['auto_renew'])) {
                         $autoRenew[$lineItem[$optionId]['auto_renew']] += $lineItem[$optionId]['line_total'];
                     }
                 }
                 break;
         }
     }
     $amount_level = array();
     $totalParticipant = 0;
     if (is_array($lineItem)) {
         foreach ($lineItem as $values) {
             $totalParticipant += $values['participant_count'];
             $amount_level[] = $values['label'] . ' - ' . (double) $values['qty'];
         }
     }
     $displayParticipantCount = '';
     if ($totalParticipant > 0) {
         $displayParticipantCount = ' Participant Count -' . $totalParticipant;
     }
     $params['amount_level'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amount_level) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
     $params['amount'] = CRM_Utils_Money::format($totalPrice, NULL, NULL, TRUE);
     $params['tax_amount'] = $totalTax;
     if ($component) {
         foreach ($autoRenew as $dontCare => $eachAmount) {
             if (!$eachAmount) {
                 unset($autoRenew[$dontCare]);
             }
         }
         if (count($autoRenew) > 1) {
             $params['autoRenew'] = $autoRenew;
         }
     }
 }
示例#11
0
 /**
  * Build the form object.
  */
 public function buildQuickForm()
 {
     $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant::getTaxRates()));
     $this->assign('currency', CRM_Core_Config::singleton()->defaultCurrencySymbol);
     $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
     $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
     if (isset($invoicing)) {
         $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
     }
     // build price set form.
     $buildPriceSet = FALSE;
     if ($this->_priceSetId || !empty($_POST['price_set_id'])) {
         if (!empty($_POST['price_set_id'])) {
             $buildPriceSet = TRUE;
         }
         $getOnlyPriceSetElements = TRUE;
         if (!$this->_priceSetId) {
             $this->_priceSetId = $_POST['price_set_id'];
             $getOnlyPriceSetElements = FALSE;
         }
         $this->set('priceSetId', $this->_priceSetId);
         CRM_Price_BAO_PriceSet::buildPriceSet($this);
         $optionsMembershipTypes = array();
         foreach ($this->_priceSet['fields'] as $pField) {
             if (empty($pField['options'])) {
                 continue;
             }
             foreach ($pField['options'] as $opId => $opValues) {
                 $optionsMembershipTypes[$opId] = CRM_Utils_Array::value('membership_type_id', $opValues, 0);
             }
         }
         $this->assign('autoRenewOption', CRM_Price_BAO_PriceSet::checkAutoRenewForPriceSet($this->_priceSetId));
         $this->assign('optionsMembershipTypes', $optionsMembershipTypes);
         $this->assign('contributionType', CRM_Utils_Array::value('financial_type_id', $this->_priceSet));
         // get only price set form elements.
         if ($getOnlyPriceSetElements) {
             return;
         }
     }
     // use to build form during form rule.
     $this->assign('buildPriceSet', $buildPriceSet);
     if ($this->_action & CRM_Core_Action::ADD) {
         $buildPriceSet = FALSE;
         $priceSets = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviMember');
         if (!empty($priceSets)) {
             $buildPriceSet = TRUE;
         }
         if ($buildPriceSet) {
             $this->add('select', 'price_set_id', ts('Choose price set'), array('' => ts('Choose price set')) + $priceSets, NULL, array('onchange' => "buildAmount( this.value );"));
         }
         $this->assign('hasPriceSets', $buildPriceSet);
     }
     //need to assign custom data type and subtype to the template
     $this->assign('customDataType', 'Membership');
     $this->assign('customDataSubType', $this->_memType);
     $this->assign('entityID', $this->_id);
     if ($this->_action & CRM_Core_Action::DELETE) {
         $this->addButtons(array(array('type' => 'next', 'name' => ts('Delete'), 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', 'isDefault' => TRUE), array('type' => 'cancel', 'name' => ts('Cancel'))));
         return;
     }
     if ($this->_context == 'standalone') {
         $this->addEntityRef('contact_id', ts('Contact'), array('create' => TRUE, 'api' => array('extra' => array('email'))), TRUE);
     }
     $selOrgMemType[0][0] = $selMemTypeOrg[0] = ts('- select -');
     // Throw status bounce when no Membership type or priceset is present
     if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus() && empty($this->allMembershipTypeDetails) && empty($priceSets)) {
         CRM_Core_Error::statusBounce(ts('You do not have all the permissions needed for this page.'));
     }
     // retrieve all memberships
     $allMembershipInfo = array();
     foreach ($this->allMembershipTypeDetails as $key => $values) {
         if ($this->_mode && empty($values['minimum_fee'])) {
             continue;
         } else {
             $memberOfContactId = CRM_Utils_Array::value('member_of_contact_id', $values);
             if (empty($selMemTypeOrg[$memberOfContactId])) {
                 $selMemTypeOrg[$memberOfContactId] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $memberOfContactId, 'display_name', 'id');
                 $selOrgMemType[$memberOfContactId][0] = ts('- select -');
             }
             if (empty($selOrgMemType[$memberOfContactId][$key])) {
                 $selOrgMemType[$memberOfContactId][$key] = CRM_Utils_Array::value('name', $values);
             }
         }
         $totalAmount = CRM_Utils_Array::value('minimum_fee', $values);
         //CRM-18827 - override the default value if total_amount is submitted
         if (!empty($this->_submitValues['total_amount'])) {
             $totalAmount = $this->_submitValues['total_amount'];
         }
         // build membership info array, which is used when membership type is selected to:
         // - set the payment information block
         // - set the max related block
         $allMembershipInfo[$key] = array('financial_type_id' => CRM_Utils_Array::value('financial_type_id', $values), 'total_amount' => CRM_Utils_Money::format($totalAmount, NULL, '%a'), 'total_amount_numeric' => $totalAmount, 'auto_renew' => CRM_Utils_Array::value('auto_renew', $values), 'has_related' => isset($values['relationship_type_id']), 'max_related' => CRM_Utils_Array::value('max_related', $values));
     }
     $this->assign('allMembershipInfo', json_encode($allMembershipInfo));
     // show organization by default, if only one organization in
     // the list
     if (count($selMemTypeOrg) == 2) {
         unset($selMemTypeOrg[0], $selOrgMemType[0][0]);
     }
     //sort membership organization and type, CRM-6099
     natcasesort($selMemTypeOrg);
     foreach ($selOrgMemType as $index => $orgMembershipType) {
         natcasesort($orgMembershipType);
         $selOrgMemType[$index] = $orgMembershipType;
     }
     $memTypeJs = array('onChange' => "buildMaxRelated(this.value,true); CRM.buildCustomData('Membership', this.value);");
     if (!empty($this->_recurPaymentProcessors)) {
         $memTypeJs['onChange'] = "" . $memTypeJs['onChange'] . "buildAutoRenew(this.value, null, '{$this->_mode}');";
     }
     $this->add('text', 'max_related', ts('Max related'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_Membership', 'max_related'));
     $sel =& $this->addElement('hierselect', 'membership_type_id', ts('Membership Organization and Type'), $memTypeJs);
     $sel->setOptions(array($selMemTypeOrg, $selOrgMemType));
     $elements = array();
     if ($sel) {
         $elements[] = $sel;
     }
     $this->applyFilter('__ALL__', 'trim');
     if ($this->_action & CRM_Core_Action::ADD) {
         $this->add('text', 'num_terms', ts('Number of Terms'), array('size' => 6));
     }
     $this->addDate('join_date', ts('Member Since'), FALSE, array('formatType' => 'activityDate'));
     $this->addDate('start_date', ts('Start Date'), FALSE, array('formatType' => 'activityDate'));
     $endDate = $this->addDate('end_date', ts('End Date'), FALSE, array('formatType' => 'activityDate'));
     if ($endDate) {
         $elements[] = $endDate;
     }
     $this->add('text', 'source', ts('Source'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_Membership', 'source'));
     //CRM-7362 --add campaigns.
     $campaignId = NULL;
     if ($this->_id) {
         $campaignId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_id, 'campaign_id');
     }
     CRM_Campaign_BAO_Campaign::addCampaign($this, $campaignId);
     if (!$this->_mode) {
         $this->add('select', 'status_id', ts('Membership Status'), array('' => ts('- select -')) + CRM_Member_PseudoConstant::membershipStatus(NULL, NULL, 'label'));
         $statusOverride = $this->addElement('checkbox', 'is_override', ts('Status Override?'), NULL, array('onClick' => 'showHideMemberStatus()'));
         if ($statusOverride) {
             $elements[] = $statusOverride;
         }
         $this->addElement('checkbox', 'record_contribution', ts('Record Membership Payment?'));
         $this->add('text', 'total_amount', ts('Amount'));
         $this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
         $this->addDate('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
         $this->add('select', 'payment_instrument_id', ts('Payment Method'), array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(), FALSE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);"));
         $this->add('text', 'trxn_id', ts('Transaction ID'));
         $this->addRule('trxn_id', ts('Transaction ID already exists in Database.'), 'objectExists', array('CRM_Contribute_DAO_Contribution', $this->_id, 'trxn_id'));
         $allowStatuses = array();
         $statuses = CRM_Contribute_PseudoConstant::contributionStatus();
         if ($this->_onlinePendingContributionId) {
             $statusNames = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
             foreach ($statusNames as $val => $name) {
                 if (in_array($name, array('In Progress', 'Overdue'))) {
                     continue;
                 }
                 $allowStatuses[$val] = $statuses[$val];
             }
         } else {
             $allowStatuses = $statuses;
         }
         $this->add('select', 'contribution_status_id', ts('Payment Status'), $allowStatuses);
         $this->add('text', 'check_number', ts('Check Number'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution', 'check_number'));
     } else {
         //add field for amount to allow an amount to be entered that differs from minimum
         $this->add('text', 'total_amount', ts('Amount'));
     }
     $this->add('select', 'financial_type_id', ts('Financial Type'), array('' => ts('- select -')) + CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, $this->_action));
     $this->addElement('checkbox', 'is_different_contribution_contact', ts('Record Payment from a Different Contact?'));
     $this->addSelect('soft_credit_type_id', array('entity' => 'contribution_soft'));
     $this->addEntityRef('soft_credit_contact_id', ts('Payment From'), array('create' => TRUE));
     $this->addElement('checkbox', 'send_receipt', ts('Send Confirmation and Receipt?'), NULL, array('onclick' => "showEmailOptions()"));
     $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
     $this->add('textarea', 'receipt_text', ts('Receipt Message'));
     // Retrieve the name and email of the contact - this will be the TO for receipt email
     if ($this->_contactID) {
         list($this->_memberDisplayName, $this->_memberEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
         $this->assign('emailExists', $this->_memberEmail);
         $this->assign('displayName', $this->_memberDisplayName);
     }
     $isRecur = FALSE;
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $recurContributionId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_id, 'contribution_recur_id');
         if ($recurContributionId && !CRM_Member_BAO_Membership::isSubscriptionCancelled($this->_id)) {
             $isRecur = TRUE;
             if (CRM_Member_BAO_Membership::isCancelSubscriptionSupported($this->_id)) {
                 $this->assign('cancelAutoRenew', CRM_Utils_System::url('civicrm/contribute/unsubscribe', "reset=1&mid={$this->_id}"));
             }
             foreach ($elements as $elem) {
                 $elem->freeze();
             }
         }
     }
     $this->assign('isRecur', $isRecur);
     $this->addFormRule(array('CRM_Member_Form_Membership', 'formRule'), $this);
     $mailingInfo = Civi::settings()->get('mailing_backend');
     $this->assign('isEmailEnabledForSite', $mailingInfo['outBound_option'] != 2);
     parent::buildQuickForm();
 }
示例#12
0
 /**
  * Get the tax amount (misnamed function).
  *
  * @param array $params
  * @param bool $isLineItem
  *
  * @return array
  */
 public static function checkTaxAmount($params, $isLineItem = FALSE)
 {
     $taxRates = CRM_Core_PseudoConstant::getTaxRates();
     // Update contribution.
     if (!empty($params['id'])) {
         // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update
         // there are no tax implications - early return.
         if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) {
             return $params;
         }
         if (empty($params['prevContribution'])) {
             $params['prevContribution'] = self::getOriginalContribution($params['id']);
         }
         foreach (array('total_amount', 'financial_type_id', 'fee_amount') as $field) {
             if (!isset($params[$field])) {
                 if ($field == 'total_amount' && $params['prevContribution']->tax_amount) {
                     // Tax amount gets added back on later....
                     $params['total_amount'] = $params['prevContribution']->total_amount - $params['prevContribution']->tax_amount;
                 } else {
                     $params[$field] = $params['prevContribution']->{$field};
                     if ($params[$field] != $params['prevContribution']->{$field}) {
                     }
                 }
             }
         }
         self::calculateMissingAmountParams($params, $params['id']);
         if (!array_key_exists($params['financial_type_id'], $taxRates)) {
             // Assign tax Amount on update of contribution
             if (!empty($params['prevContribution']->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 Contribution 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(CRM_Utils_Array::value('total_amount', $params), $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'] = CRM_Utils_Array::value('total_amount', $params) + $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;
 }
示例#13
0
 /**
  * Get line item purchase information.
  *
  * This function takes the input parameters and interprets out of it what has been purchased.
  *
  * @param $fields
  *   This is the output of the function CRM_Price_BAO_PriceSet::getSetDetail($priceSetID, FALSE, FALSE);
  *   And, it would make sense to introduce caching into that function and call it from here rather than
  *   require the $fields array which is passed from pillar to post around the form in order to pass it in here.
  * @param array $params
  *   Params reflecting form input e.g with fields 'price_5' => 7, 'price_8' => array(7, 8)
  * @param $lineItem
  *   Line item array to be altered.
  * @param string $component
  *   This parameter appears to only be relevant to determining whether memberships should be auto-renewed.
  *   (and is effectively a boolean for 'is_membership' which could be calculated from the line items.)
  */
 public static function processAmount($fields, &$params, &$lineItem, $component = '')
 {
     // using price set
     $totalPrice = $totalTax = 0;
     $radioLevel = $checkboxLevel = $selectLevel = $textLevel = array();
     if ($component) {
         $autoRenew = array();
         $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
     }
     foreach ($fields as $id => $field) {
         if (empty($params["price_{$id}"]) || empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL) {
             // skip if nothing was submitted for this field
             continue;
         }
         switch ($field['html_type']) {
             case 'Text':
                 $firstOption = reset($field['options']);
                 $params["price_{$id}"] = array($firstOption['id'] => $params["price_{$id}"]);
                 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
                 if (CRM_Utils_Array::value('tax_rate', $field['options'][key($field['options'])])) {
                     $lineItem = self::setLineItem($field, $lineItem, key($field['options']));
                     $totalTax += $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
                 }
                 if (CRM_Utils_Array::value('name', $field['options'][key($field['options'])]) == 'contribution_amount') {
                     $taxRates = CRM_Core_PseudoConstant::getTaxRates();
                     if (array_key_exists($params['financial_type_id'], $taxRates)) {
                         $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']];
                         $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($field['options'][key($field['options'])]['amount'], $field['options'][key($field['options'])]['tax_rate']);
                         $field['options'][key($field['options'])]['tax_amount'] = round($taxAmount['tax_amount'], 2);
                         $lineItem = self::setLineItem($field, $lineItem, key($field['options']));
                         $totalTax += $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
                     }
                 }
                 $totalPrice += $lineItem[$firstOption['id']]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[key($field['options'])]);
                 break;
             case 'Radio':
                 //special case if user select -none-
                 if ($params["price_{$id}"] <= 0) {
                     continue;
                 }
                 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
                 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
                 $optionLabel = CRM_Utils_Array::value('label', $field['options'][$optionValueId]);
                 $params['amount_priceset_level_radio'] = array();
                 $params['amount_priceset_level_radio'][$optionValueId] = $optionLabel;
                 if (isset($radioLevel)) {
                     $radioLevel = array_merge($radioLevel, array_keys($params['amount_priceset_level_radio']));
                 } else {
                     $radioLevel = array_keys($params['amount_priceset_level_radio']);
                 }
                 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
                 if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionValueId])) {
                     $lineItem = self::setLineItem($field, $lineItem, $optionValueId);
                     $totalTax += $field['options'][$optionValueId]['tax_amount'];
                     if (CRM_Utils_Array::value('field_title', $lineItem[$optionValueId]) == 'Membership Amount') {
                         $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
                     }
                 }
                 $totalPrice += $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionValueId]);
                 if ($component && isset($lineItem[$optionValueId]['auto_renew']) && is_numeric($lineItem[$optionValueId]['auto_renew'])) {
                     $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total'];
                 }
                 break;
             case 'Select':
                 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
                 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
                 $optionLabel = $field['options'][$optionValueId]['label'];
                 $params['amount_priceset_level_select'] = array();
                 $params['amount_priceset_level_select'][CRM_Utils_Array::key(1, $params["price_{$id}"])] = $optionLabel;
                 if (isset($selectLevel)) {
                     $selectLevel = array_merge($selectLevel, array_keys($params['amount_priceset_level_select']));
                 } else {
                     $selectLevel = array_keys($params['amount_priceset_level_select']);
                 }
                 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
                 if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionValueId])) {
                     $lineItem = self::setLineItem($field, $lineItem, $optionValueId);
                     $totalTax += $field['options'][$optionValueId]['tax_amount'];
                 }
                 $totalPrice += $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionValueId]);
                 if ($component && isset($lineItem[$optionValueId]['auto_renew']) && is_numeric($lineItem[$optionValueId]['auto_renew'])) {
                     $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total'];
                 }
                 break;
             case 'CheckBox':
                 $params['amount_priceset_level_checkbox'] = $optionIds = array();
                 foreach ($params["price_{$id}"] as $optionId => $option) {
                     $optionIds[] = $optionId;
                     $optionLabel = $field['options'][$optionId]['label'];
                     $params['amount_priceset_level_checkbox']["{$field['options'][$optionId]['id']}"] = $optionLabel;
                     if (isset($checkboxLevel)) {
                         $checkboxLevel = array_unique(array_merge($checkboxLevel, array_keys($params['amount_priceset_level_checkbox'])));
                     } else {
                         $checkboxLevel = array_keys($params['amount_priceset_level_checkbox']);
                     }
                 }
                 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
                 foreach ($optionIds as $optionId) {
                     if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionId])) {
                         $lineItem = self::setLineItem($field, $lineItem, $optionId);
                         $totalTax += $field['options'][$optionId]['tax_amount'];
                     }
                     $totalPrice += $lineItem[$optionId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionId]);
                     if ($component && isset($lineItem[$optionId]['auto_renew']) && is_numeric($lineItem[$optionId]['auto_renew'])) {
                         $autoRenew[$lineItem[$optionId]['auto_renew']] += $lineItem[$optionId]['line_total'];
                     }
                 }
                 break;
         }
     }
     $amount_level = array();
     $totalParticipant = 0;
     if (is_array($lineItem)) {
         foreach ($lineItem as $values) {
             $totalParticipant += $values['participant_count'];
             // This is a bit nasty. The logic of 'quick config' was because price set configuration was
             // (and still is) too difficult to replace the 'quick config' price set configuration on the contribution
             // page.
             //
             // However, because the quick config concept existed all sorts of logic was hung off it
             // and function behaviour sometimes depends on whether 'price set' is set - although actually it
             // is always set at the functional level. In this case we are dealing with the default 'quick config'
             // price set having a label of 'Contribution Amount' which could wind up creating a 'funny looking' label.
             // The correct answer is probably for it to have an empty label in the DB - the label is never shown so it is a
             // place holder.
             //
             // But, in the interests of being careful when capacity is low - avoiding the known default value
             // will get us by.
             // Crucially a test has been added so a better solution can be implemented later with some comfort.
             // @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it.
             if ($values['label'] != ts('Contribution Amount')) {
                 $amount_level[] = $values['label'] . ' - ' . (double) $values['qty'];
             }
         }
     }
     $displayParticipantCount = '';
     if ($totalParticipant > 0) {
         $displayParticipantCount = ' Participant Count -' . $totalParticipant;
     }
     // @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it.
     if (!empty($amount_level)) {
         $params['amount_level'] = CRM_Utils_Array::implodePadded($amount_level);
         if (!empty($displayParticipantCount)) {
             $params['amount_level'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amount_level) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
         }
     }
     $params['amount'] = CRM_Utils_Money::format($totalPrice, NULL, NULL, TRUE);
     $params['tax_amount'] = $totalTax;
     if ($component) {
         foreach ($autoRenew as $dontCare => $eachAmount) {
             if (!$eachAmount) {
                 unset($autoRenew[$dontCare]);
             }
         }
         if (count($autoRenew) > 1) {
             $params['autoRenew'] = $autoRenew;
         }
     }
 }
 public function testGetTaxRates()
 {
     $contact = $this->createLoggedInUser();
     $financialType = $this->callAPISuccess('financial_type', 'create', array('name' => 'Test taxable financial Type', 'is_reserved' => 0, 'is_active' => 1));
     $financialAccount = $this->callAPISuccess('financial_account', 'create', array('name' => 'Test Tax financial account ', 'contact_id' => $contact, 'financial_account_type_id' => 2, 'is_tax' => 1, 'tax_rate' => 5.0, 'is_reserved' => 0, 'is_active' => 1, 'is_default' => 0));
     $financialTypeId = $financialType['id'];
     $financialAccountId = $financialAccount['id'];
     $financialAccountParams = array('entity_table' => 'civicrm_financial_type', 'entity_id' => $financialTypeId, 'account_relationship' => 10, 'financial_account_id' => $financialAccountId);
     CRM_Financial_BAO_FinancialTypeAccount::add($financialAccountParams);
     $taxRates = CRM_Core_PseudoConstant::getTaxRates();
     $this->assertEquals('5.00', $taxRates[$financialType['id']]);
 }
示例#15
0
 /**
  * CRM-19126 Add test to verify when complete transaction is called tax amount is not changed
  */
 public function testCheckTaxAmount()
 {
     $contact = $this->createLoggedInUser();
     $financialType = $this->callAPISuccess('financial_type', 'create', array('name' => 'Test taxable financial Type', 'is_reserved' => 0, 'is_active' => 1));
     $financialAccount = $this->callAPISuccess('financial_account', 'create', array('name' => 'Test Tax financial account ', 'contact_id' => $contact, 'financial_account_type_id' => 2, 'is_tax' => 1, 'tax_rate' => 5.0, 'is_reserved' => 0, 'is_active' => 1, 'is_default' => 0));
     $financialTypeId = $financialType['id'];
     $financialAccountId = $financialAccount['id'];
     $financialAccountParams = array('entity_table' => 'civicrm_financial_type', 'entity_id' => $financialTypeId, 'account_relationship' => 10, 'financial_account_id' => $financialAccountId);
     CRM_Financial_BAO_FinancialTypeAccount::add($financialAccountParams);
     $taxRates = CRM_Core_PseudoConstant::getTaxRates();
     $params = array_merge($this->_params, array('contribution_status_id' => 2, 'financial_type_id' => $financialTypeId));
     $contribution = $this->callAPISuccess('contribution', 'create', $params);
     $contribution1 = $this->callAPISuccess('contribution', 'get', array('id' => $contribution['id'], 'return' => 'tax_amount', 'sequential' => 1));
     $this->callAPISuccess('contribution', 'completetransaction', array('id' => $contribution['id'], 'trxn_id' => '777788888', 'fee_amount' => '6.00'));
     $contribution2 = $this->callAPISuccess('contribution', 'get', array('id' => $contribution['id'], 'return' => array('tax_amount', 'fee_amount', 'net_amount'), 'sequential' => 1));
     $this->assertEquals($contribution1['values'][0]['tax_amount'], $contribution2['values'][0]['tax_amount']);
     $this->assertEquals('6.00', $contribution2['values'][0]['fee_amount']);
     $this->assertEquals('99.00', $contribution2['values'][0]['net_amount']);
 }