/** * Deletes an existing Soft Credit. * * @param array $params */ function civicrm_api3_contribution_soft_delete($params) { // Non standard BAO - we have to write custom code to cope. $result = CRM_Contribute_BAO_ContributionSoft::del(array('id' => $params['id'])); if (!$result) { throw new API_Exception('Cannot delete contributionSoft ' . $params['id']); } civicrm_api3_create_success(TRUE); }
/** * Get Soft credit to list in DT */ public static function getSoftContributionRows() { $requiredParameters = array('cid' => 'Integer', 'context' => 'String'); $optionalParameters = array('entityID' => 'Integer', 'isTest' => 'Integer'); $params = CRM_Core_Page_AJAX::defaultSortAndPagerParams(); $params += CRM_Core_Page_AJAX::validateParams($requiredParameters, $optionalParameters); $softCreditList = CRM_Contribute_BAO_ContributionSoft::getSoftContributionSelector($params); if (!empty($_GET['is_unit_test'])) { return $softCreditList; } CRM_Utils_JSON::output($softCreditList); }
/** * Function used to build form element for soft credit block * * @param object $form form object * @access public * * @return void */ static function buildQuickForm(&$form) { $prefix = 'soft_credit_'; // by default generate 5 blocks $item_count = 6; $showSoftCreditRow = 2; $showCreateNew = TRUE; if ($form->_action & CRM_Core_Action::UPDATE) { $form->_softCreditInfo = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($form->_id, TRUE); if (!empty($form->_softCreditInfo['soft_credit'])) { $showSoftCreditRow = count($form->_softCreditInfo['soft_credit']); $showSoftCreditRow++; $showCreateNew = FALSE; } } for ($rowNumber = 1; $rowNumber <= $item_count; $rowNumber++) { CRM_Contact_Form_NewContact::buildQuickForm($form, $rowNumber, NULL, FALSE, $prefix); $form->addMoney("{$prefix}amount[{$rowNumber}]", ts('Amount'), FALSE, NULL, FALSE); if (!empty($form->_softCreditInfo['soft_credit'][$rowNumber]['soft_credit_id'])) { $form->add('hidden', "{$prefix}id[{$rowNumber}]", $form->_softCreditInfo['soft_credit'][$rowNumber]['soft_credit_id']); } } // CRM-7368 allow user to set or edit PCP link for contributions $siteHasPCPs = CRM_Contribute_PseudoConstant::pcPage(); if (!CRM_Utils_Array::crmIsEmptyArray($siteHasPCPs)) { $form->assign('siteHasPCPs', 1); $pcpDataUrl = CRM_Utils_System::url('civicrm/ajax/rest', 'className=CRM_Contact_Page_AJAX&fnName=getPCPList&json=1&context=contact&reset=1', FALSE, NULL, FALSE); $form->assign('pcpDataUrl', $pcpDataUrl); $form->addElement('text', 'pcp_made_through', ts('Credit to a Personal Campaign Page')); $form->addElement('hidden', 'pcp_made_through_id', '', array('id' => 'pcp_made_through_id')); $form->addElement('checkbox', 'pcp_display_in_roll', ts('Display in Honor Roll?'), NULL); $form->addElement('text', 'pcp_roll_nickname', ts('Name (for Honor Roll)')); $form->addElement('textarea', 'pcp_personal_note', ts('Personal Note (for Honor Roll)')); } $form->assign('showSoftCreditRow', $showSoftCreditRow); $form->assign('rowCount', $item_count); $form->assign('showCreateNew', $showCreateNew); // Tell tpl to hide soft credit field if contribution is linked directly to a PCP Page if (CRM_Utils_Array::value('pcp_made_through_id', $form->_values)) { $form->assign('pcpLinked', 1); } }
/** * Process the form submission. * * * @return void */ public function postProcess() { if ($this->_action & CRM_Core_Action::DELETE) { CRM_Member_BAO_Membership::del($this->_id); return; } $allMemberStatus = CRM_Member_PseudoConstant::membershipStatus(); $allContributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(); $isTest = $this->_mode == 'test' ? 1 : 0; $lineItems = NULL; if (!empty($this->_lineItem)) { $lineItems = $this->_lineItem; } $config = CRM_Core_Config::singleton(); // get the submitted form values. $this->_params = $formValues = $this->controller->exportValues($this->_name); $this->convertDateFieldsToMySQL($formValues); $params = $softParams = $ids = array(); $membershipTypeValues = array(); foreach ($this->_memTypeSelected as $memType) { $membershipTypeValues[$memType]['membership_type_id'] = $memType; } //take the required membership recur values. if ($this->_mode && !empty($this->_params['auto_renew'])) { $params['is_recur'] = $this->_params['is_recur'] = $formValues['is_recur'] = TRUE; $mapping = array('frequency_interval' => 'duration_interval', 'frequency_unit' => 'duration_unit'); $count = 0; foreach ($this->_memTypeSelected as $memType) { $recurMembershipTypeValues = CRM_Utils_Array::value($memType, $this->_recurMembershipTypes, array()); foreach ($mapping as $mapVal => $mapParam) { $membershipTypeValues[$memType][$mapVal] = CRM_Utils_Array::value($mapParam, $recurMembershipTypeValues); if (!$count) { $this->_params[$mapVal] = $formValues[$mapVal] = CRM_Utils_Array::value($mapParam, $recurMembershipTypeValues); } } $count++; } } // process price set and get total amount and line items. $lineItem = array(); $priceSetId = NULL; if (!($priceSetId = CRM_Utils_Array::value('price_set_id', $formValues))) { CRM_Member_BAO_Membership::createLineItems($this, $formValues['membership_type_id'], $priceSetId); } $isQuickConfig = 0; if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) { $isQuickConfig = 1; } $termsByType = array(); if ($priceSetId) { CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $this->_params, $lineItem[$priceSetId]); if (CRM_Utils_Array::value('tax_amount', $this->_params)) { $params['tax_amount'] = $this->_params['tax_amount']; } $params['total_amount'] = CRM_Utils_Array::value('amount', $this->_params); $submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $formValues); if (!empty($lineItem[$priceSetId])) { foreach ($lineItem[$priceSetId] as &$li) { if (!empty($li['membership_type_id'])) { if (!empty($li['membership_num_terms'])) { $termsByType[$li['membership_type_id']] = $li['membership_num_terms']; } } ///CRM-11529 for quick config backoffice transactions //when financial_type_id is passed in form, update the //lineitems with the financial type selected in form if ($isQuickConfig && $submittedFinancialType) { $li['financial_type_id'] = $submittedFinancialType; } } } } $this->storeContactFields($formValues); $params['contact_id'] = $this->_contactID; $fields = array('status_id', 'source', 'is_override', 'campaign_id'); foreach ($fields as $f) { $params[$f] = CRM_Utils_Array::value($f, $formValues); } // fix for CRM-3724 // when is_override false ignore is_admin statuses during membership // status calculation. similarly we did fix for import in CRM-3570. if (empty($params['is_override'])) { $params['exclude_is_admin'] = TRUE; } // process date params to mysql date format. $dateTypes = array('join_date' => 'joinDate', 'start_date' => 'startDate', 'end_date' => 'endDate'); foreach ($dateTypes as $dateField => $dateVariable) { ${$dateVariable} = CRM_Utils_Date::processDate($formValues[$dateField]); } $memTypeNumTerms = empty($termsByType) ? CRM_Utils_Array::value('num_terms', $formValues) : NULL; $calcDates = array(); foreach ($this->_memTypeSelected as $memType) { if (empty($memTypeNumTerms)) { $memTypeNumTerms = CRM_Utils_Array::value($memType, $termsByType, 1); } $calcDates[$memType] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($memType, $joinDate, $startDate, $endDate, $memTypeNumTerms); } foreach ($calcDates as $memType => $calcDate) { foreach (array_keys($dateTypes) as $d) { //first give priority to form values then calDates. $date = CRM_Utils_Array::value($d, $formValues); if (!$date) { $date = CRM_Utils_Array::value($d, $calcDate); } $membershipTypeValues[$memType][$d] = CRM_Utils_Date::processDate($date); //$params[$d] = CRM_Utils_Date::processDate( $date ); } } // max related memberships - take from form or inherit from membership type foreach ($this->_memTypeSelected as $memType) { if (array_key_exists('max_related', $formValues)) { $membershipTypeValues[$memType]['max_related'] = CRM_Utils_Array::value('max_related', $formValues); } } if ($this->_id) { $ids['membership'] = $params['id'] = $this->_id; } $session = CRM_Core_Session::singleton(); $ids['userId'] = $session->get('userID'); // membership type custom data foreach ($this->_memTypeSelected as $memType) { $customFields = CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, $memType); $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, NULL, NULL, TRUE)); $membershipTypeValues[$memType]['custom'] = CRM_Core_BAO_CustomField::postProcess($formValues, $customFields, $this->_id, 'Membership'); } foreach ($this->_memTypeSelected as $memType) { $membershipTypes[$memType] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $memType); } $membershipType = implode(', ', $membershipTypes); // Retrieve the name and email of the current user - this will be the FROM for the receipt email list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($ids['userId']); //CRM-13981, allow different person as a soft-contributor of chosen type if ($this->_contributorContactID != $this->_contactID) { $params['contribution_contact_id'] = $this->_contributorContactID; if (!empty($this->_params['soft_credit_type_id'])) { $softParams['soft_credit_type_id'] = $this->_params['soft_credit_type_id']; $softParams['contact_id'] = $this->_contactID; } } if (!empty($formValues['record_contribution'])) { $recordContribution = array('total_amount', 'financial_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'check_number', 'campaign_id', 'receive_date'); foreach ($recordContribution as $f) { $params[$f] = CRM_Utils_Array::value($f, $formValues); } if (!$this->_onlinePendingContributionId) { if (empty($formValues['source'])) { $params['contribution_source'] = ts('%1 Membership: Offline signup (by %2)', array(1 => $membershipType, 2 => $userName)); } else { $params['contribution_source'] = $formValues['source']; } } if (empty($params['is_override']) && CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'))) { $params['status_id'] = array_search('Pending', $allMemberStatus); $params['skipStatusCal'] = TRUE; $params['is_pay_later'] = 1; $this->assign('is_pay_later', 1); } if (!empty($formValues['send_receipt'])) { $params['receipt_date'] = CRM_Utils_Array::value('receive_date', $formValues); } //insert financial type name in receipt. $formValues['contributionType_name'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $formValues['financial_type_id']); } // process line items, until no previous line items. if (!empty($lineItem)) { $params['lineItems'] = $lineItem; $params['processPriceSet'] = TRUE; } $createdMemberships = array(); if ($this->_mode) { if (empty($formValues['total_amount']) && !$priceSetId) { // if total amount not provided minimum for membership type is used $params['total_amount'] = $formValues['total_amount'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $formValues['membership_type_id'][1], 'minimum_fee'); } else { $params['total_amount'] = CRM_Utils_Array::value('total_amount', $formValues, 0); } if ($priceSetId && !$isQuickConfig) { $params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'financial_type_id'); } else { $params['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $formValues); } $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($formValues['payment_processor_id'], $this->_mode); //get the payment processor id as per mode. $params['payment_processor_id'] = $this->_params['payment_processor_id'] = $formValues['payment_processor_id'] = $this->_paymentProcessor['id']; $now = date('YmdHis'); $fields = array(); // set email for primary location. $fields['email-Primary'] = 1; $formValues['email-5'] = $formValues['email-Primary'] = $this->_memberEmail; $params['register_date'] = $now; // now set the values for the billing location. foreach ($this->_fields as $name => $dontCare) { $fields[$name] = 1; } // also add location name to the array $formValues["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_middle_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_last_name', $formValues); $formValues["address_name-{$this->_bltID}"] = trim($formValues["address_name-{$this->_bltID}"]); $fields["address_name-{$this->_bltID}"] = 1; //ensure we don't over-write the payer's email with the member's email if ($this->_contributorContactID == $this->_contactID) { $fields["email-{$this->_bltID}"] = 1; } $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type'); $nameFields = array('first_name', 'middle_name', 'last_name'); foreach ($nameFields as $name) { $fields[$name] = 1; if (array_key_exists("billing_{$name}", $formValues)) { $formValues[$name] = $formValues["billing_{$name}"]; $formValues['preserveDBName'] = TRUE; } } if ($this->_contributorContactID == $this->_contactID) { //see CRM-12869 for discussion of why we don't do this for separate payee payments CRM_Contact_BAO_Contact::createProfileContact($formValues, $fields, $this->_contributorContactID, NULL, NULL, $ctype); } // add all the additional payment params we need $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]); $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]); $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params); $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params); $this->_params['ip_address'] = CRM_Utils_System::ipAddress(); $this->_params['amount'] = $params['total_amount']; $this->_params['currencyID'] = $config->defaultCurrency; $this->_params['description'] = ts('Office Credit Card Membership Signup Contribution'); $this->_params['payment_action'] = 'Sale'; $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE)); $this->_params['financial_type_id'] = $params['financial_type_id']; // at this point we've created a contact and stored its address etc // all the payment processors expect the name and address to be in the // so we copy stuff over to first_name etc. $paymentParams = $this->_params; $paymentParams['contactID'] = $this->_contributorContactID; //CRM-10377 if payment is by an alternate contact then we need to set that person // as the contact in the payment params if ($this->_contributorContactID != $this->_contactID) { if (!empty($this->_params['soft_credit_type_id'])) { $softParams['contact_id'] = $params['contact_id']; $softParams['soft_credit_type_id'] = $this->_params['soft_credit_type_id']; } } if (!empty($this->_params['send_receipt'])) { $paymentParams['email'] = $this->_contributorEmail; } CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE); // CRM-7137 -for recurring membership, // we do need contribution and recuring records. $result = NULL; if (!empty($paymentParams['is_recur'])) { $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'); } $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this, $paymentParams, $result, $this->_contributorContactID, $contributionType, TRUE, FALSE, $isTest, $lineItems); //create new soft-credit record, CRM-13981 if ($softParams) { $softParams['contribution_id'] = $contribution->id; $softParams['currency'] = $contribution->currency; $softParams['amount'] = $contribution->total_amount; CRM_Contribute_BAO_ContributionSoft::add($softParams); } $paymentParams['contactID'] = $this->_contactID; $paymentParams['contributionID'] = $contribution->id; $paymentParams['contributionTypeID'] = $contribution->financial_type_id; $paymentParams['contributionPageID'] = $contribution->contribution_page_id; $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id; $ids['contribution'] = $contribution->id; $params['contribution_recur_id'] = $paymentParams['contributionRecurID']; } if ($params['total_amount'] > 0.0) { $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this); $result = $payment->doDirectPayment($paymentParams); } if (is_a($result, 'CRM_Core_Error')) { //make sure to cleanup db for recurring case. if (!empty($paymentParams['contributionID'])) { CRM_Contribute_BAO_Contribution::deleteContribution($paymentParams['contributionID']); } if (!empty($paymentParams['contributionRecurID'])) { CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']); } CRM_Core_Error::displaySessionError($result); CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=add&cid={$this->_contactID}&context=&mode={$this->_mode}")); } if ($result) { $this->_params = array_merge($this->_params, $result); //assign amount to template if payment was successful $this->assign('amount', $params['total_amount']); } // if the payment processor returns a contribution_status_id -> use it! if (isset($result['contribution_status_id'])) { $result['payment_status_id'] = $result['contribution_status_id']; } if (isset($result['payment_status_id'])) { // CRM-16737 $result['contribution_status_id'] is deprecated in favour // of payment_status_id as the payment processor only knows whether the payment is complete // not whether payment completes the contribution $params['contribution_status_id'] = $result['payment_status_id']; } else { $params['contribution_status_id'] = !empty($paymentParams['is_recur']) ? 2 : 1; } if ($params['contribution_status_id'] != array_search('Completed', $allContributionStatus)) { $params['status_id'] = array_search('Pending', $allMemberStatus); $params['skipStatusCal'] = TRUE; // unset send-receipt option, since receipt will be sent when ipn is received. unset($this->_params['send_receipt'], $formValues['send_receipt']); //as membership is pending set dates to null. $memberDates = array('join_date' => 'joinDate', 'start_date' => 'startDate', 'end_date' => 'endDate'); foreach ($memberDates as $dp => $dv) { ${$dv} = NULL; foreach ($this->_memTypeSelected as $memType) { $membershipTypeValues[$memType][$dv] = NULL; } } } $params['receive_date'] = $now; $params['invoice_id'] = $this->_params['invoiceID']; $params['contribution_source'] = ts('%1 Membership Signup: Credit card or direct debit (by %2)', array(1 => $membershipType, 2 => $userName)); $params['source'] = $formValues['source'] ? $formValues['source'] : $params['contribution_source']; $params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result); $params['payment_instrument_id'] = 1; $params['is_test'] = $this->_mode == 'live' ? 0 : 1; if (!empty($this->_params['send_receipt'])) { $params['receipt_date'] = $now; } else { $params['receipt_date'] = NULL; } $this->set('params', $this->_params); $this->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $result)); $this->assign('receive_date', CRM_Utils_Date::mysqlToIso($params['receive_date'])); // required for creating membership for related contacts $params['action'] = $this->_action; //create membership record. $count = 0; foreach ($this->_memTypeSelected as $memType) { if ($count && ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))) { $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution; } $membershipParams = array_merge($membershipTypeValues[$memType], $params); //CRM-15366 if (!empty($softParams) && empty($paymentParams['is_recur'])) { $membershipParams['soft_credit'] = $softParams; } if (!empty($paymentParams['is_recur']) && CRM_Utils_Array::value('payment_status_id', $result) == 1) { // CRM-16993 we have a situation where line items have already been created. unset($membershipParams['lineItems']); } $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids); $params['contribution'] = CRM_Utils_Array::value('contribution', $membershipParams); unset($params['lineItems']); $this->_membershipIDs[] = $membership->id; $createdMemberships[$memType] = $membership; $count++; } } else { $params['action'] = $this->_action; if ($this->_onlinePendingContributionId && !empty($formValues['record_contribution'])) { // update membership as well as contribution object, CRM-4395 $params['contribution_id'] = $this->_onlinePendingContributionId; $params['componentId'] = $params['id']; $params['componentName'] = 'contribute'; $result = CRM_Contribute_BAO_Contribution::transitionComponents($params, TRUE); if (!empty($result) && !empty($params['contribution_id'])) { $lineItem = array(); $lineItems = CRM_Price_BAO_LineItem::getLineItems($params['contribution_id'], 'contribution', NULL, TRUE, TRUE); $itemId = key($lineItems); $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id'); $fieldType = NULL; if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) { $fieldType = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'html_type'); } $lineItems[$itemId]['unit_price'] = $params['total_amount']; $lineItems[$itemId]['line_total'] = $params['total_amount']; $lineItems[$itemId]['id'] = $itemId; $lineItem[$priceSetId] = $lineItems; $contributionBAO = new CRM_Contribute_BAO_Contribution(); $contributionBAO->id = $params['contribution_id']; $contributionBAO->contact_id = $params['contact_id']; $contributionBAO->find(); CRM_Price_BAO_LineItem::processPriceSet($params['contribution_id'], $lineItem, $contributionBAO, 'civicrm_membership'); //create new soft-credit record, CRM-13981 if ($softParams) { $softParams['contribution_id'] = $params['contribution_id']; while ($contributionBAO->fetch()) { $softParams['currency'] = $contributionBAO->currency; $softParams['amount'] = $contributionBAO->total_amount; } CRM_Contribute_BAO_ContributionSoft::add($softParams); } } //carry updated membership object. $membership = new CRM_Member_DAO_Membership(); $membership->id = $this->_id; $membership->find(TRUE); $cancelled = TRUE; if ($membership->end_date) { //display end date w/ status message. $endDate = $membership->end_date; if (!in_array($membership->status_id, array(array_search('Cancelled', CRM_Member_PseudoConstant::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)), array_search('Expired', CRM_Member_PseudoConstant::membershipStatus())))) { $cancelled = FALSE; } } // suppress form values in template. $this->assign('cancelled', $cancelled); // FIX ME: need to recheck this // here we might updated dates, so get from object. foreach ($calcDates[$membership->membership_type_id] as $date => &$val) { if ($membership->{$date}) { $val = $membership->{$date}; } } $createdMemberships[] = $membership; } else { $count = 0; foreach ($this->_memTypeSelected as $memType) { if ($count && !empty($formValues['record_contribution']) && ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))) { $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution; } $membershipParams = array_merge($params, $membershipTypeValues[$memType]); if (!empty($formValues['int_amount'])) { $init_amount = array(); foreach ($formValues as $key => $value) { if (strstr($key, 'txt-price')) { $init_amount[$key] = $value; } } $membershipParams['init_amount'] = $init_amount; } if (!empty($softParams)) { $membershipParams['soft_credit'] = $softParams; } $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids); $params['contribution'] = CRM_Utils_Array::value('contribution', $membershipParams); unset($params['lineItems']); $this->_membershipIDs[] = $membership->id; $createdMemberships[$memType] = $membership; $count++; } } } if (!empty($lineItem[$priceSetId])) { $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings'); $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings); $taxAmount = FALSE; $totalTaxAmount = 0; foreach ($lineItem[$priceSetId] as &$priceFieldOp) { if (!empty($priceFieldOp['membership_type_id'])) { $priceFieldOp['start_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'] ? CRM_Utils_Date::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'], '%B %E%f, %Y') : '-'; $priceFieldOp['end_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'] ? CRM_Utils_Date::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'], '%B %E%f, %Y') : '-'; } else { $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A'; } if ($invoicing && isset($priceFieldOp['tax_amount'])) { $taxAmount = TRUE; $totalTaxAmount += $priceFieldOp['tax_amount']; } } if ($invoicing) { $dataArray = array(); foreach ($lineItem[$priceSetId] as $key => $value) { if (isset($value['tax_amount']) && isset($value['tax_rate'])) { if (isset($dataArray[$value['tax_rate']])) { $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value); } else { $dataArray[$value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value); } } } if ($taxAmount) { $this->assign('totalTaxAmount', $totalTaxAmount); $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings)); } $this->assign('dataArray', $dataArray); } } $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE); $receiptSend = FALSE; $contributionId = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id); $membershipIds = $this->_membershipIDs; if ($contributionId && !empty($membershipIds)) { $contributionDetails = CRM_Contribute_BAO_Contribution::getContributionDetails(CRM_Export_Form_Select::MEMBER_EXPORT, $this->_membershipIDs); if ($contributionDetails[$membership->id]['contribution_status'] == 'Completed') { $receiptSend = TRUE; } } if (!empty($formValues['send_receipt']) && $receiptSend) { $formValues['contact_id'] = $this->_contactID; $formValues['contribution_id'] = $contributionId; // send email receipt $mailSend = self::emailReceipt($this, $formValues, $membership); } if ($this->_action & CRM_Core_Action::UPDATE) { //end date can be modified by hooks, so if end date is set then use it. $endDate = $membership->end_date ? $membership->end_date : $endDate; $statusMsg = ts('Membership for %1 has been updated.', array(1 => $this->_memberDisplayName)); if ($endDate && $endDate !== 'null') { $endDate = CRM_Utils_Date::customFormat($endDate); $statusMsg .= ' ' . ts('The membership End Date is %1.', array(1 => $endDate)); } if ($receiptSend) { $statusMsg .= ' ' . ts('A confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail)); } } elseif ($this->_action & CRM_Core_Action::ADD) { // FIX ME: fix status messages $statusMsg = array(); foreach ($membershipTypes as $memType => $membershipType) { $statusMsg[$memType] = ts('%1 membership for %2 has been added.', array(1 => $membershipType, 2 => $this->_memberDisplayName)); $membership = $createdMemberships[$memType]; $memEndDate = $membership->end_date ? $membership->end_date : $endDate; //get the end date from calculated dates. if (!$memEndDate && empty($params['is_recur'])) { $memEndDate = CRM_Utils_Array::value('end_date', $calcDates[$memType]); } if ($memEndDate && $memEndDate !== 'null') { $memEndDate = CRM_Utils_Date::customFormat($memEndDate); $statusMsg[$memType] .= ' ' . ts('The new membership End Date is %1.', array(1 => $memEndDate)); } } $statusMsg = implode('<br/>', $statusMsg); if ($receiptSend && !empty($mailSend)) { $statusMsg .= ' ' . ts('A membership confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail)); } } // finally set membership id if already not set if (!$this->_id) { $this->_id = $membership->id; } CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success'); $buttonName = $this->controller->getButtonName(); if ($this->_context == 'standalone') { if ($buttonName == $this->getButtonName('upload', 'new')) { $session->replaceUserContext(CRM_Utils_System::url('civicrm/member/add', 'reset=1&action=add&context=standalone')); } else { $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=member")); } } elseif ($buttonName == $this->getButtonName('upload', 'new')) { $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=add&context=membership&cid={$this->_contactID}")); } }
/** * Set the default values. */ public function setDefaultValues() { // check if the user is registered and we have a contact ID $contactID = $this->getContactID(); if (!empty($contactID)) { $fields = array(); $removeCustomFieldTypes = array('Contribution', 'Membership'); $contribFields = CRM_Contribute_BAO_Contribution::getContributionFields(); // remove component related fields foreach ($this->_fields as $name => $dontCare) { //don't set custom data Used for Contribution (CRM-1344) if (substr($name, 0, 7) == 'custom_') { $id = substr($name, 7); if (!CRM_Core_BAO_CustomGroup::checkCustomField($id, $removeCustomFieldTypes)) { continue; } // ignore component fields } elseif (array_key_exists($name, $contribFields) || substr($name, 0, 11) == 'membership_' || substr($name, 0, 13) == 'contribution_') { continue; } $fields[$name] = 1; } if (!empty($fields)) { CRM_Core_BAO_UFGroup::setProfileDefaults($contactID, $fields, $this->_defaults); } $billingDefaults = $this->getProfileDefaults('Billing', $contactID); $this->_defaults = array_merge($this->_defaults, $billingDefaults); } if (!empty($this->_ccid) && !empty($this->_pendingAmount)) { $this->_defaults['total_amount'] = CRM_Utils_Money::format($this->_pendingAmount, NULL, '%a'); } /* * hack to simplify credit card entry for testing * * $this->_defaults['credit_card_type'] = 'Visa'; * $this->_defaults['amount'] = 168; * $this->_defaults['credit_card_number'] = '4111111111111111'; * $this->_defaults['cvv2'] = '000'; * $this->_defaults['credit_card_exp_date'] = array('Y' => date('Y')+1, 'M' => '05'); * // hack to simplify direct debit entry for testing * $this->_defaults['account_holder'] = 'Max Müller'; * $this->_defaults['bank_account_number'] = '12345678'; * $this->_defaults['bank_identification_number'] = '12030000'; * $this->_defaults['bank_name'] = 'Bankname'; */ //build set default for pledge overdue payment. if (!empty($this->_values['pledge_id'])) { //used to record completed pledge payment ids used later for honor default $completedContributionIds = array(); $pledgePayments = CRM_Pledge_BAO_PledgePayment::getPledgePayments($this->_values['pledge_id']); $paymentAmount = 0; $duePayment = FALSE; foreach ($pledgePayments as $payId => $value) { if ($value['status'] == 'Overdue') { $this->_defaults['pledge_amount'][$payId] = 1; $paymentAmount += $value['scheduled_amount']; } elseif (!$duePayment && $value['status'] == 'Pending') { $this->_defaults['pledge_amount'][$payId] = 1; $paymentAmount += $value['scheduled_amount']; $duePayment = TRUE; } elseif ($value['status'] == 'Completed' && $value['contribution_id']) { $completedContributionIds[] = $value['contribution_id']; } } $this->_defaults['price_' . $this->_priceSetId] = $paymentAmount; if (count($completedContributionIds)) { $softCredit = array(); foreach ($completedContributionIds as $id) { $softCredit = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($id); } if (isset($softCredit['soft_credit'])) { $this->_defaults['soft_credit_type_id'] = $softCredit['soft_credit'][1]['soft_credit_type']; //since honoree profile fieldname of fields are prefixed with 'honor' //we need to reformat the fieldname to append prefix during setting default values CRM_Core_BAO_UFGroup::setProfileDefaults($softCredit['soft_credit'][1]['contact_id'], CRM_Core_BAO_UFGroup::getFields($this->_honoreeProfileId), $defaults); foreach ($defaults as $fieldName => $value) { $this->_defaults['honor[' . $fieldName . ']'] = $value; } } } } elseif (!empty($this->_values['pledge_block_id'])) { //set default to one time contribution. $this->_defaults['is_pledge'] = 0; } // to process Custom data that are appended to URL $getDefaults = CRM_Core_BAO_CustomGroup::extractGetParams($this, "'Contact', 'Individual', 'Contribution'"); $this->_defaults = array_merge($this->_defaults, $getDefaults); $config = CRM_Core_Config::singleton(); // set default country from config if no country set if (empty($this->_defaults["billing_country_id-{$this->_bltID}"])) { $this->_defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry; } // set default state/province from config if no state/province set if (empty($this->_defaults["billing_state_province_id-{$this->_bltID}"])) { $this->_defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince; } $entityId = $memtypeID = NULL; if ($this->_priceSetId) { if ($this->_useForMember && !empty($this->_currentMemberships) || $this->_defaultMemTypeId) { $selectedCurrentMemTypes = array(); foreach ($this->_priceSet['fields'] as $key => $val) { foreach ($val['options'] as $keys => $values) { $opMemTypeId = CRM_Utils_Array::value('membership_type_id', $values); $priceFieldName = 'price_' . $values['price_field_id']; $priceFieldValue = CRM_Price_BAO_PriceSet::getPriceFieldValueFromURL($this, $priceFieldName); if (!empty($priceFieldValue)) { CRM_Price_BAO_PriceSet::setDefaultPriceSetField($priceFieldName, $priceFieldValue, $val['html_type'], $this->_defaults); // break here to prevent overwriting of default due to 'is_default' // option configuration or setting of current membership or // membership for related organization. // The value sent via URL get's higher priority. break; } elseif ($opMemTypeId && in_array($opMemTypeId, $this->_currentMemberships) && !in_array($opMemTypeId, $selectedCurrentMemTypes)) { CRM_Price_BAO_PriceSet::setDefaultPriceSetField($priceFieldName, $keys, $val['html_type'], $this->_defaults); $memtypeID = $selectedCurrentMemTypes[] = $values['membership_type_id']; } elseif (!empty($values['is_default']) && !$opMemTypeId && (!isset($this->_defaults[$priceFieldName]) || $val['html_type'] == 'CheckBox' && !isset($this->_defaults[$priceFieldName][$keys]))) { CRM_Price_BAO_PriceSet::setDefaultPriceSetField($priceFieldName, $keys, $val['html_type'], $this->_defaults); $memtypeID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $this->_defaults[$priceFieldName], 'membership_type_id'); } } } $entityId = CRM_Utils_Array::value('id', CRM_Member_BAO_Membership::getContactMembership($contactID, $memtypeID, NULL)); } else { CRM_Price_BAO_PriceSet::setDefaultPriceSet($this, $this->_defaults); } } //set custom field defaults set by admin if value is not set if (!empty($this->_fields)) { //load default campaign from page. if (array_key_exists('contribution_campaign_id', $this->_fields)) { $this->_defaults['contribution_campaign_id'] = CRM_Utils_Array::value('campaign_id', $this->_values); } //set custom field defaults foreach ($this->_fields as $name => $field) { if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) { if (!isset($this->_defaults[$name])) { CRM_Core_BAO_CustomField::setProfileDefaults($customFieldID, $name, $this->_defaults, $entityId, CRM_Profile_Form::MODE_REGISTER); } } } } if (!empty($this->_paymentProcessors)) { foreach ($this->_paymentProcessors as $pid => $value) { if (!empty($value['is_default'])) { $this->_defaults['payment_processor_id'] = $pid; } } } return $this->_defaults; }
/** * Apply variables for message to smarty template - this function is part of analysing what is in the huge * function & breaking it down into manageable chunks. Eventually it will be refactored into something else * Note we send directly from this function in some cases because it is only partly refactored * Don't call this function directly as the signature will change * * @param $values * @param $input * @param CRM_Core_SMARTY $template * @param bool $recur * @param bool $returnMessageText * * @return mixed */ public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) { $template->assign('first_name', $this->_relatedObjects['contact']->first_name); $template->assign('last_name', $this->_relatedObjects['contact']->last_name); $template->assign('displayName', $this->_relatedObjects['contact']->display_name); if (!empty($values['lineItem']) && !empty($this->_relatedObjects['membership'])) { $template->assign('useForMember', TRUE); } //assign honor information to receipt message $softRecord = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($this->id); if (isset($softRecord['soft_credit'])) { //if id of contribution page is present if (!empty($values['id'])) { $values['honor'] = array('honor_profile_values' => array(), 'honor_profile_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'), 'honor_id' => $softRecord['soft_credit'][1]['contact_id']); $softCreditTypes = CRM_Core_OptionGroup::values('soft_credit_type'); $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']); $template->assign('honor_block_is_active', CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id')); } else { //offline contribution $softCreditTypes = $softCredits = array(); foreach ($softRecord['soft_credit'] as $key => $softCredit) { $softCreditTypes[$key] = $softCredit['soft_credit_type_label']; $softCredits[$key] = array('Name' => $softCredit['contact_name'], 'Amount' => CRM_Utils_Money::format($softCredit['amount'], $softCredit['currency'])); } $template->assign('softCreditTypes', $softCreditTypes); $template->assign('softCredits', $softCredits); } } $dao = new CRM_Contribute_DAO_ContributionProduct(); $dao->contribution_id = $this->id; if ($dao->find(TRUE)) { $premiumId = $dao->product_id; $template->assign('option', $dao->product_option); $productDAO = new CRM_Contribute_DAO_Product(); $productDAO->id = $premiumId; $productDAO->find(TRUE); $template->assign('selectPremium', TRUE); $template->assign('product_name', $productDAO->name); $template->assign('price', $productDAO->price); $template->assign('sku', $productDAO->sku); } $template->assign('title', CRM_Utils_Array::value('title', $values)); $amount = CRM_Utils_Array::value('total_amount', $input, CRM_Utils_Array::value('amount', $input), NULL); if (empty($amount) && isset($this->total_amount)) { $amount = $this->total_amount; } $template->assign('amount', $amount); // add the new contribution values if (strtolower($this->_component) == 'contribute') { //PCP Info $softDAO = new CRM_Contribute_DAO_ContributionSoft(); $softDAO->contribution_id = $this->id; if ($softDAO->find(TRUE)) { $template->assign('pcpBlock', TRUE); $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll); $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname); $template->assign('pcp_personal_note', $softDAO->pcp_personal_note); //assign the pcp page title for email subject $pcpDAO = new CRM_PCP_DAO_PCP(); $pcpDAO->id = $softDAO->pcp_id; if ($pcpDAO->find(TRUE)) { $template->assign('title', $pcpDAO->title); } } } if ($this->financial_type_id) { $values['financial_type_id'] = $this->financial_type_id; } $template->assign('trxn_id', $this->trxn_id); $template->assign('receive_date', CRM_Utils_Date::mysqlToIso($this->receive_date)); $template->assign('contributeMode', 'notify'); $template->assign('action', $this->is_test ? 1024 : 1); $template->assign('receipt_text', CRM_Utils_Array::value('receipt_text', $values)); $template->assign('is_monetary', 1); $template->assign('is_recur', (bool) $recur); $template->assign('currency', $this->currency); $template->assign('address', CRM_Utils_Address::format($input)); if (!empty($values['customGroup'])) { $template->assign('customGroup', $values['customGroup']); } if ($this->_component == 'event') { $template->assign('title', $values['event']['title']); $participantRoles = CRM_Event_PseudoConstant::participantRole(); $viewRoles = array(); foreach (explode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_relatedObjects['participant']->role_id) as $k => $v) { $viewRoles[] = $participantRoles[$v]; } $values['event']['participant_role'] = implode(', ', $viewRoles); $template->assign('event', $values['event']); $template->assign('participant', $values['participant']); $template->assign('location', $values['location']); $template->assign('customPre', $values['custom_pre_id']); $template->assign('customPost', $values['custom_post_id']); $isTest = FALSE; if ($this->_relatedObjects['participant']->is_test) { $isTest = TRUE; } $values['params'] = array(); //to get email of primary participant. $primaryEmail = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects['participant']->contact_id, 'email', 'contact_id'); $primaryAmount[] = array('label' => $this->_relatedObjects['participant']->fee_level . ' - ' . $primaryEmail, 'amount' => $this->_relatedObjects['participant']->fee_amount); //build an array of cId/pId of participants $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, NULL, $this->_relatedObjects['contact']->id, $isTest, TRUE); unset($additionalIDs[$this->_relatedObjects['participant']->id]); //send receipt to additional participant if exists if (count($additionalIDs)) { $template->assign('isPrimary', 0); $template->assign('customProfile', NULL); //set additionalParticipant true $values['params']['additionalParticipant'] = TRUE; foreach ($additionalIDs as $pId => $cId) { $amount = array(); //to change the status pending to completed $additional = new CRM_Event_DAO_Participant(); $additional->id = $pId; $additional->contact_id = $cId; $additional->find(TRUE); $additional->register_date = $this->_relatedObjects['participant']->register_date; $additional->status_id = 1; $additionalParticipantInfo = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id, 'email', 'contact_id'); //if additional participant dont have email //use display name. if (!$additionalParticipantInfo) { $additionalParticipantInfo = CRM_Contact_BAO_Contact::displayName($additional->contact_id); } $amount[0] = array('label' => $additional->fee_level, 'amount' => $additional->fee_amount); $primaryAmount[] = array('label' => $additional->fee_level . ' - ' . $additionalParticipantInfo, 'amount' => $additional->fee_amount); $additional->save(); $additional->free(); $template->assign('amount', $amount); CRM_Event_BAO_Event::sendMail($cId, $values, $pId, $isTest, $returnMessageText); } } //build an array of custom profile and assigning it to template $customProfile = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, $values, NULL, $isTest); if (count($customProfile)) { $template->assign('customProfile', $customProfile); } // for primary contact $values['params']['additionalParticipant'] = FALSE; $template->assign('isPrimary', 1); $template->assign('amount', $primaryAmount); $template->assign('register_date', CRM_Utils_Date::isoToMysql($this->_relatedObjects['participant']->register_date)); if ($this->payment_instrument_id) { $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument(); $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id]); } // carry paylater, since we did not created billing, // so need to pull email from primary location, CRM-4395 $values['params']['is_pay_later'] = $this->_relatedObjects['participant']->is_pay_later; } return $template; }
/** * Function used to save pcp / soft credit entry * This is used by contribution and also event pcps * * @param array $params associated array * @param object $contribution contribution object * * @static * @access public */ static function processPcpSoft(&$params, &$contribution) { //add soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin. if (!empty($params['soft_credit_to'])) { $contribSoftParams = array(); foreach (array('pcp_display_in_roll', 'pcp_roll_nickname', 'pcp_personal_note', 'amount') as $val) { if (!empty($params[$val])) { $contribSoftParams[$val] = $params[$val]; } } $contribSoftParams['contact_id'] = $params['soft_credit_to']; // add contribution id $contribSoftParams['contribution_id'] = $contribution->id; // add pcp id $contribSoftParams['pcp_id'] = $params['pcp_made_through_id']; $contribSoftParams['soft_credit_type_id'] = CRM_Core_OptionGroup::getValue('soft_credit_type', 'pcp', 'name'); $softContribution = CRM_Contribute_BAO_ContributionSoft::add($contribSoftParams); } }
/** * Retrieve a set of contributions. * * @param array $params * Input parameters. * * @return array * Array of contributions, if error an array with an error id and error message */ function civicrm_api3_contribution_get($params) { $mode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE; $returnProperties = CRM_Contribute_BAO_Query::defaultReturnProperties($mode); $contributions = _civicrm_api3_get_using_query_object('Contribution', $params, array(), NULL, $mode, $returnProperties); foreach ($contributions as $id => $contribution) { $softContribution = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($id, TRUE); $contributions[$id] = array_merge($contribution, $softContribution); // format soft credit for backward compatibility _civicrm_api3_format_soft_credit($contributions[$id]); } return civicrm_api3_create_success($contributions, $params, 'Contribution', 'get'); }
/** * Set variables up before form is built. * * @return void */ public function preProcess() { $id = $this->get('id'); $values = $ids = array(); $params = array('id' => $id); $context = CRM_Utils_Request::retrieve('context', 'String', $this); $this->assign('context', $context); CRM_Contribute_BAO_Contribution::getValues($params, $values, $ids); CRM_Contribute_BAO_Contribution::resolveDefaults($values); $cancelledStatus = TRUE; $status = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); if (CRM_Utils_Array::value('contribution_status_id', $values) == array_search('Cancelled', $status)) { $cancelledStatus = FALSE; } $this->assign('cancelledStatus', $cancelledStatus); if (!empty($values['contribution_page_id'])) { $contribPages = CRM_Contribute_PseudoConstant::contributionPage(NULL, TRUE); $values['contribution_page_title'] = CRM_Utils_Array::value(CRM_Utils_Array::value('contribution_page_id', $values), $contribPages); } // get recieved into i.e to_financial_account_id from last trxn $financialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($values['contribution_id'], 'DESC'); $values['to_financial_account'] = ''; if (!empty($financialTrxnId['financialTrxnId'])) { $values['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $financialTrxnId['financialTrxnId'], 'to_financial_account_id'); if ($values['to_financial_account_id']) { $values['to_financial_account'] = CRM_Contribute_PseudoConstant::financialAccount($values['to_financial_account_id']); } $values['payment_processor_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $financialTrxnId['financialTrxnId'], 'payment_processor_id'); if ($values['payment_processor_id']) { $values['payment_processor_name'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessor', $values['payment_processor_id'], 'name'); } } if (!empty($values['contribution_recur_id'])) { $sql = "SELECT installments, frequency_interval, frequency_unit FROM civicrm_contribution_recur WHERE id = %1"; $params = array(1 => array($values['contribution_recur_id'], 'Integer')); $dao = CRM_Core_DAO::executeQuery($sql, $params); if ($dao->fetch()) { $values['recur_installments'] = $dao->installments; $values['recur_frequency_unit'] = $dao->frequency_unit; $values['recur_frequency_interval'] = $dao->frequency_interval; } } $groupTree = CRM_Core_BAO_CustomGroup::getTree('Contribution', $this, $id, 0, CRM_Utils_Array::value('financial_type_id', $values)); CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree); $premiumId = NULL; if ($id) { $dao = new CRM_Contribute_DAO_ContributionProduct(); $dao->contribution_id = $id; if ($dao->find(TRUE)) { $premiumId = $dao->id; $productID = $dao->product_id; } } if ($premiumId) { $productDAO = new CRM_Contribute_DAO_Product(); $productDAO->id = $productID; $productDAO->find(TRUE); $this->assign('premium', $productDAO->name); $this->assign('option', $dao->product_option); $this->assign('fulfilled', $dao->fulfilled_date); } // Get Note $noteValue = CRM_Core_BAO_Note::getNote(CRM_Utils_Array::value('id', $values), 'civicrm_contribution'); $values['note'] = array_values($noteValue); // show billing address location details, if exists if (!empty($values['address_id'])) { $addressParams = array('id' => CRM_Utils_Array::value('address_id', $values)); $addressDetails = CRM_Core_BAO_Address::getValues($addressParams, FALSE, 'id'); $addressDetails = array_values($addressDetails); $values['billing_address'] = $addressDetails[0]['display']; } //assign soft credit record if exists. $SCRecords = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($values['contribution_id'], TRUE); if (!empty($SCRecords['soft_credit'])) { $this->assign('softContributions', $SCRecords['soft_credit']); unset($SCRecords['soft_credit']); } //assign pcp record if exists foreach ($SCRecords as $name => $value) { $this->assign($name, $value); } $lineItems = array(); if ($id) { $lineItem = CRM_Price_BAO_LineItem::getLineItems($id, 'contribution', 1, TRUE, TRUE); if (!empty($lineItem)) { $lineItems[] = $lineItem; } } $this->assign('lineItem', empty($lineItems) ? FALSE : $lineItems); $values['totalAmount'] = $values['total_amount']; //do check for campaigns if ($campaignId = CRM_Utils_Array::value('campaign_id', $values)) { $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId); $values['campaign'] = $campaigns[$campaignId]; } // assign values to the template $this->assign($values); $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings'); $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings); $this->assign('invoicing', $invoicing); if ($invoicing && isset($values['tax_amount'])) { $this->assign('totalTaxAmount', $values['tax_amount']); } $displayName = CRM_Contact_BAO_Contact::displayName($values['contact_id']); $this->assign('displayName', $displayName); // Check if this is default domain contact CRM-10482 if (CRM_Contact_BAO_Contact::checkDomainContact($values['contact_id'])) { $displayName .= ' (' . ts('default organization') . ')'; } // omitting contactImage from title for now since the summary overlay css doesn't work outside of our crm-container CRM_Utils_System::setTitle(ts('View Contribution from') . ' ' . $displayName); // add viewed contribution to recent items list $url = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=view&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"); $title = $displayName . ' - (' . CRM_Utils_Money::format($values['total_amount']) . ' ' . ' - ' . $values['financial_type'] . ')'; $recentOther = array(); if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::UPDATE)) { $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=update&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"); } if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::DELETE)) { $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=delete&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"); } CRM_Utils_Recent::add($title, $url, $values['id'], 'Contribution', $values['contact_id'], NULL, $recentOther); }
/** * Build the form object. * * @return void */ public function buildQuickForm() { $this->assignToTemplate(); $productID = $this->get('productID'); $option = $this->get('option'); $membershipTypeID = $this->get('membershipTypeID'); $this->assign('receiptFromEmail', CRM_Utils_Array::value('receipt_from_email', $this->_values)); if ($productID) { CRM_Contribute_BAO_Premium::buildPremiumBlock($this, $this->_id, FALSE, $productID, $option); } if ($this->_priceSetId && !CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) { $this->assign('lineItem', $this->_lineItem); } else { if (is_array($membershipTypeID)) { $membershipTypeID = current($membershipTypeID); } $this->assign('is_quick_config', 1); $this->_params['is_quick_config'] = 1; } $this->assign('priceSetID', $this->_priceSetId); $this->assign('useForMember', $this->get('useForMember')); $params = $this->_params; $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) { $getTaxDetails = FALSE; $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings); foreach ($this->_lineItem as $key => $value) { foreach ($value as $v) { if (isset($v['tax_rate'])) { if ($v['tax_rate'] != '') { $getTaxDetails = TRUE; } } } } $this->assign('getTaxDetails', $getTaxDetails); $this->assign('taxTerm', $taxTerm); $this->assign('totalTaxAmount', $params['tax_amount']); } if ($this->_honor_block_is_active && !empty($params['soft_credit_type_id'])) { $honorName = NULL; $softCreditTypes = CRM_Core_OptionGroup::values("soft_credit_type", FALSE); $this->assign('honor_block_is_active', $this->_honor_block_is_active); $this->assign('soft_credit_type', $softCreditTypes[$params['soft_credit_type_id']]); CRM_Contribute_BAO_ContributionSoft::formatHonoreeProfileFields($this, $params['honor'], $params['honoree_profile_id']); $fieldTypes = array('Contact'); $fieldTypes[] = CRM_Core_BAO_UFGroup::getContactType($params['honoree_profile_id']); $this->buildCustom($params['honoree_profile_id'], 'honoreeProfileFields', TRUE, 'honor', $fieldTypes); } $qParams = "reset=1&id={$this->_id}"; //pcp elements if ($this->_pcpId) { $qParams .= "&pcpId={$this->_pcpId}"; $this->assign('pcpBlock', TRUE); foreach (array('pcp_display_in_roll', 'pcp_is_anonymous', 'pcp_roll_nickname', 'pcp_personal_note') as $val) { if (!empty($this->_params[$val])) { $this->assign($val, $this->_params[$val]); } } } $this->assign('qParams', $qParams); if ($membershipTypeID) { $transactionID = $this->get('membership_trx_id'); $membershipAmount = $this->get('membership_amount'); $renewalMode = $this->get('renewal_mode'); $this->assign('membership_trx_id', $transactionID); $this->assign('membership_amount', $membershipAmount); $this->assign('renewal_mode', $renewalMode); $this->buildMembershipBlock($this->_membershipContactID, FALSE, $membershipTypeID, TRUE, NULL); if (!empty($params['auto_renew'])) { $this->assign('auto_renew', TRUE); } } $this->_separateMembershipPayment = $this->get('separateMembershipPayment'); $this->assign("is_separate_payment", $this->_separateMembershipPayment); $this->buildCustom($this->_values['custom_pre_id'], 'customPre', TRUE); $this->buildCustom($this->_values['custom_post_id'], 'customPost', TRUE); if (!empty($params['hidden_onbehalf_profile'])) { $ufJoinParams = array('module' => 'onBehalf', 'entity_table' => 'civicrm_contribution_page', 'entity_id' => $this->_id); $OnBehalfProfile = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams); $profileId = $OnBehalfProfile[0]; $fieldTypes = array('Contact', 'Organization'); $contactSubType = CRM_Contact_BAO_ContactType::subTypes('Organization'); $fieldTypes = array_merge($fieldTypes, $contactSubType); if (is_array($this->_membershipBlock) && !empty($this->_membershipBlock)) { $fieldTypes = array_merge($fieldTypes, array('Membership')); } else { $fieldTypes = array_merge($fieldTypes, array('Contribution')); } $this->buildCustom($profileId, 'onbehalfProfile', TRUE, 'onbehalf', $fieldTypes); } $this->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $this->_params)); $this->assign('receive_date', CRM_Utils_Date::mysqlToIso(CRM_Utils_Array::value('receive_date', $this->_params))); $defaults = array(); $fields = array(); foreach ($this->_fields as $name => $dontCare) { if ($name != 'onbehalf' || $name != 'honor') { $fields[$name] = 1; } } $fields['state_province'] = $fields['country'] = $fields['email'] = 1; $contact = $this->_params = $this->controller->exportValues('Main'); foreach ($fields as $name => $dontCare) { if (isset($contact[$name])) { $defaults[$name] = $contact[$name]; if (substr($name, 0, 7) == 'custom_') { $timeField = "{$name}_time"; if (isset($contact[$timeField])) { $defaults[$timeField] = $contact[$timeField]; } } elseif (in_array($name, array('addressee', 'email_greeting', 'postal_greeting')) && !empty($contact[$name . '_custom'])) { $defaults[$name . '_custom'] = $contact[$name . '_custom']; } } } $this->_submitValues = array_merge($this->_submitValues, $defaults); $this->setDefaults($defaults); $values['entity_id'] = $this->_id; $values['entity_table'] = 'civicrm_contribution_page'; CRM_Friend_BAO_Friend::retrieve($values, $data); $tellAFriend = FALSE; if ($this->_pcpId) { if ($this->_pcpBlock['is_tellfriend_enabled']) { $this->assign('friendText', ts('Tell a Friend')); $subUrl = "eid={$this->_pcpId}&blockId={$this->_pcpBlock['id']}&pcomponent=pcp"; $tellAFriend = TRUE; } } elseif (!empty($data['is_active'])) { $friendText = $data['title']; $this->assign('friendText', $friendText); $subUrl = "eid={$this->_id}&pcomponent=contribute"; $tellAFriend = TRUE; } if ($tellAFriend) { if ($this->_action & CRM_Core_Action::PREVIEW) { $url = CRM_Utils_System::url("civicrm/friend", "reset=1&action=preview&{$subUrl}"); } else { $url = CRM_Utils_System::url("civicrm/friend", "reset=1&{$subUrl}"); } $this->assign('friendURL', $url); } $this->freeze(); // can we blow away the session now to prevent hackery // CRM-9491 $this->controller->reset(); }
/** * @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; }
/** * called when action is browse. * */ public function browse() { // add annual contribution $annual = array(); list($annual['count'], $annual['amount'], $annual['avg']) = CRM_Contribute_BAO_Contribution::annual($this->_contactId); $this->assign('annual', $annual); $controller = new CRM_Core_Controller_Simple('CRM_Contribute_Form_Search', ts('Contributions'), $this->_action, FALSE, FALSE, TRUE); $controller->setEmbedded(TRUE); $controller->reset(); $controller->set('cid', $this->_contactId); $controller->set('crid', $this->_crid); $controller->set('context', 'contribution'); $controller->set('limit', 50); $controller->process(); $controller->run(); // add recurring block $action = array_sum(array_keys($this->recurLinks())); $params = CRM_Contribute_BAO_ContributionRecur::getRecurContributions($this->_contactId); // Get all backoffice payment processors $backOfficePaymentProcessors = CRM_Financial_BAO_PaymentProcessor::getPaymentProcessors(array('BackOffice')); if (!empty($params)) { foreach ($params as $ids => $recur) { $action = array_sum(array_keys($this->recurLinks($ids))); // no action allowed if it's not active $params[$ids]['is_active'] = $recur['contribution_status_id'] != 3; // Get payment processor name $paymentProcessorDetails = CRM_Financial_BAO_PaymentProcessor::getPayment($params[$ids]['payment_processor_id'], 'live'); $params[$ids]['payment_processor_name'] = $paymentProcessorDetails['name']; $details = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($params[$ids]['id'], 'recur'); $hideUpdate = $details->membership_id & $details->auto_renew; if ($hideUpdate) { $action -= CRM_Core_Action::UPDATE; } $links = self::recurLinks($ids); // Disable Edit/Delete link if no back office support if (!array_key_exists($recur['payment_processor_id'], $backOfficePaymentProcessors)) { unset($links[2]); unset($links[8]); } // Remove cancel link for already cancelled recurring records if ($recur['contribution_status_id'] == 3) { unset($links[64]); } $params[$ids]['action'] = CRM_Core_Action::formLink($links, $action, array('cid' => $this->_contactId, 'crid' => $ids, 'cxt' => 'contribution'), ts('more'), FALSE, 'contribution.selector.recurring', 'Contribution', $ids); } // assign vars to templates $this->assign('action', $this->_action); $this->assign('recurRows', $params); $this->assign('recur', TRUE); } //enable/disable soft credit records for test contribution $isTest = 0; if (CRM_Utils_Request::retrieve('isTest', 'Positive', $this)) { $isTest = 1; } $this->assign('isTest', $isTest); $softCreditList = CRM_Contribute_BAO_ContributionSoft::getSoftContributionList($this->_contactId, NULL, $isTest); if (!empty($softCreditList)) { $softCreditTotals = array(); list($softCreditTotals['amount'], $softCreditTotals['avg'], $softCreditTotals['currency']) = CRM_Contribute_BAO_ContributionSoft::getSoftContributionTotals($this->_contactId, $isTest); $this->assign('softCredit', TRUE); $this->assign('softCreditRows', $softCreditList); $this->assign('softCreditTotals', $softCreditTotals); } if ($this->_contactId) { $displayName = CRM_Contact_BAO_Contact::displayName($this->_contactId); $this->assign('displayName', $displayName); $this->ajaxResponse['tabCount'] = CRM_Contribute_BAO_ContributionRecur::contributionRecurCount($this->_contactId); } }
/** * Deletes an existing Soft Credit * * @param array $params * * @example ContributionSoftDelete.php Standard Delete Example * * @return boolean | error true if successfull, error otherwise * {@getfields contribution_soft_delete} * @access public */ function civicrm_api3_contribution_soft_delete($params) { // non standard BAO - we have to write custom code to cope CRM_Contribute_BAO_ContributionSoft::del(array('id' => $params['id'])); }
/** * Process the soft contribution and/or link to personal campaign page. * * @param array $params * @param object $contribution CRM_Contribute_DAO_Contribution * */ public static function processSoftContribution($params, $contribution) { //retrieve existing soft-credit and pcp id(s) if any against $contribution $softIDs = self::getSoftCreditIds($contribution->id); $pcpId = self::getSoftCreditIds($contribution->id, TRUE); if ($pcp = CRM_Utils_Array::value('pcp', $params)) { $softParams = array(); $softParams['id'] = $pcpId ? $pcpId : NULL; $softParams['contribution_id'] = $contribution->id; $softParams['pcp_id'] = $pcp['pcp_made_through_id']; $softParams['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $pcp['pcp_made_through_id'], 'contact_id'); $softParams['currency'] = $contribution->currency; $softParams['amount'] = $contribution->total_amount; $softParams['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $pcp); $softParams['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $pcp); $softParams['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $pcp); $softParams['soft_credit_type_id'] = CRM_Core_OptionGroup::getValue('soft_credit_type', 'pcp', 'name'); $contributionSoft = self::add($softParams); //Send notification to owner for PCP if ($contributionSoft->pcp_id && empty($pcpId)) { CRM_Contribute_Form_Contribution_Confirm::pcpNotifyOwner($contribution, $contributionSoft); } } elseif (array_key_exists('pcp', $params) && $pcpId) { $deleteParams = array('id' => $pcpId); CRM_Contribute_BAO_ContributionSoft::del($deleteParams); } if (isset($params['soft_credit'])) { $softParams = $params['soft_credit']; foreach ($softParams as $softParam) { if (!empty($softIDs)) { $key = key($softIDs); $softParam['id'] = $softIDs[$key]; unset($softIDs[$key]); } $softParam['contribution_id'] = $contribution->id; $softParam['currency'] = $contribution->currency; //case during Contribution Import when we assign soft contribution amount as contribution's total_amount by default if (empty($softParam['amount'])) { $softParam['amount'] = $contribution->total_amount; } CRM_Contribute_BAO_ContributionSoft::add($softParam); } // delete any extra soft-credit while updating back-office contribution foreach ((array) $softIDs as $softID) { if (!in_array($softID, $params['soft_credit_ids'])) { $deleteParams = array('id' => $softID); CRM_Contribute_BAO_ContributionSoft::del($deleteParams); } } } }
/** * @param $form * @param array $params Parameters from the form. */ public static function postProcess($form, $params) { if (!empty($form->_honor_block_is_active) && !empty($params['soft_credit_type_id'])) { $honorId = NULL; //check if there is any duplicate contact $profileContactType = CRM_Core_BAO_UFGroup::getContactType($params['honoree_profile_id']); $dedupeParams = CRM_Dedupe_Finder::formatParams($params['honor'], $profileContactType); $dedupeParams['check_permission'] = FALSE; $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $profileContactType); if (count($ids)) { $honorId = CRM_Utils_Array::value(0, $ids); } $honorId = CRM_Contact_BAO_Contact::createProfileContact($params['honor'], CRM_Core_DAO::$_nullArray, $honorId, NULL, $params['honoree_profile_id']); $softParams = array(); $softParams['contribution_id'] = $form->_contributionID; $softParams['contact_id'] = $honorId; $softParams['soft_credit_type_id'] = $params['soft_credit_type_id']; $contribution = new CRM_Contribute_DAO_Contribution(); $contribution->id = $form->_contributionID; $contribution->find(); while ($contribution->fetch()) { $softParams['currency'] = $contribution->currency; $softParams['amount'] = $contribution->total_amount; } CRM_Contribute_BAO_ContributionSoft::add($softParams); if (CRM_Utils_Array::value('is_email_receipt', $form->_values)) { $form->_values['honor'] = array('soft_credit_type' => CRM_Utils_Array::value($params['soft_credit_type_id'], CRM_Core_OptionGroup::values("soft_credit_type")), 'honor_id' => $honorId, 'honor_profile_id' => $params['honoree_profile_id'], 'honor_profile_values' => $params['honor']); } } }
/** * Retrieve a set of contributions. * * @param array $params * Input parameters. * * @return array * Array of contributions, if error an array with an error id and error message */ function civicrm_api3_contribution_get($params) { $mode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE; list($dao, $query) = _civicrm_api3_get_query_object($params, $mode, 'Contribution'); $contribution = array(); while ($dao->fetch()) { //CRM-8662 $contribution_details = $query->store($dao); $softContribution = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($dao->contribution_id, TRUE); $contribution[$dao->contribution_id] = array_merge($contribution_details, $softContribution); // format soft credit for backward compatibility _civicrm_api3_format_soft_credit($contribution[$dao->contribution_id]); } return civicrm_api3_create_success($contribution, $params, 'Contribution', 'get', $dao); }
/** * 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; } }
/** * Function used to build form element for soft credit block. * * @param CRM_Core_Form $form * * @return void */ public static function buildQuickForm(&$form) { if (!empty($form->_honor_block_is_active)) { $ufJoinDAO = new CRM_Core_DAO_UFJoin(); $ufJoinDAO->module = 'soft_credit'; $ufJoinDAO->entity_id = $form->_id; if ($ufJoinDAO->find(TRUE)) { $jsonData = CRM_Contribute_BAO_ContributionPage::formatMultilingualHonorParams($ufJoinDAO->module_data, TRUE); if ($jsonData) { foreach (array('honor_block_title', 'honor_block_text') as $name) { $form->assign($name, $jsonData[$name]); } $softCreditTypes = CRM_Core_OptionGroup::values("soft_credit_type", FALSE); // radio button for Honor Type foreach ($jsonData['soft_credit_types'] as $value) { $honorTypes[$value] = $form->createElement('radio', NULL, NULL, $softCreditTypes[$value], $value); } $form->addGroup($honorTypes, 'soft_credit_type_id', NULL)->setAttribute('allowClear', TRUE); } } return $form; } // by default generate 10 blocks $item_count = 11; $showSoftCreditRow = 2; if ($form->getAction() & CRM_Core_Action::UPDATE) { $form->_softCreditInfo = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($form->_id, TRUE); } elseif (!empty($form->_pledgeID)) { //Check and select most recent completed contrubtion and use it to retrieve //soft-credit information to use as default for current pledge payment, CRM-13981 $pledgePayments = CRM_Pledge_BAO_PledgePayment::getPledgePayments($form->_pledgeID); foreach ($pledgePayments as $id => $record) { if ($record['contribution_id']) { $softCredits = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($record['contribution_id'], TRUE); if ($record['status'] == 'Completed' && count($softCredits) > 0) { $form->_softCreditInfo = $softCredits; } } } } if (property_exists($form, "_softCreditInfo")) { if (!empty($form->_softCreditInfo['soft_credit'])) { $showSoftCreditRow = count($form->_softCreditInfo['soft_credit']); $showSoftCreditRow++; } } for ($rowNumber = 1; $rowNumber <= $item_count; $rowNumber++) { $form->addEntityRef("soft_credit_contact_id[{$rowNumber}]", ts('Contact'), array('create' => TRUE)); $form->addMoney("soft_credit_amount[{$rowNumber}]", ts('Amount'), FALSE, NULL, FALSE); $form->addSelect("soft_credit_type[{$rowNumber}]", array('entity' => 'contribution_soft', 'field' => 'soft_credit_type_id', 'label' => ts('Type'))); if (!empty($form->_softCreditInfo['soft_credit'][$rowNumber]['soft_credit_id'])) { $form->add('hidden', "soft_credit_id[{$rowNumber}]", $form->_softCreditInfo['soft_credit'][$rowNumber]['soft_credit_id']); } } // CRM-7368 allow user to set or edit PCP link for contributions $siteHasPCPs = CRM_Contribute_PseudoConstant::pcPage(); if (!CRM_Utils_Array::crmIsEmptyArray($siteHasPCPs)) { $form->assign('siteHasPCPs', 1); // Fixme: Not a true entityRef field. Relies on PCP.js.tpl $form->add('text', 'pcp_made_through_id', ts('Credit to a Personal Campaign Page'), array('class' => 'twenty', 'placeholder' => ts('- select -'))); // stores the label $form->add('hidden', 'pcp_made_through'); $form->addElement('checkbox', 'pcp_display_in_roll', ts('Display in Honor Roll?'), NULL); $form->addElement('text', 'pcp_roll_nickname', ts('Name (for Honor Roll)')); $form->addElement('textarea', 'pcp_personal_note', ts('Personal Note (for Honor Roll)')); } $form->assign('showSoftCreditRow', $showSoftCreditRow); $form->assign('rowCount', $item_count); $form->addElement('hidden', 'sct_default_id', CRM_Core_OptionGroup::getDefaultValue("soft_credit_type"), array('id' => 'sct_default_id')); }
/** * Create honor-contact method */ public function testcreateAndGetHonorContact() { $firstName = 'John_' . substr(sha1(rand()), 0, 7); $lastName = 'Smith_' . substr(sha1(rand()), 0, 7); $email = "{$firstName}.{$lastName}@example.com"; //Get profile id of name honoree_individual used to create profileContact $honoreeProfileId = NULL; $ufGroupDAO = new CRM_Core_DAO_UFGroup(); $ufGroupDAO->name = 'honoree_individual'; if ($ufGroupDAO->find(TRUE)) { $honoreeProfileId = $ufGroupDAO->id; } $params = array('prefix_id' => 3, 'first_name' => $firstName, 'last_name' => $lastName, 'email-1' => $email); $softParam = array('soft_credit_type_id' => 1); $honoreeContactId = CRM_Contact_BAO_Contact::createProfileContact($params, CRM_Core_DAO::$_nullArray, NULL, NULL, $honoreeProfileId); $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $honoreeContactId, 'first_name', 'id', $firstName, 'Database check for created honor contact record.'); //create contribution on behalf of honary. $contactId = Contact::createIndividual(); $softParam['contact_id'] = $honoreeContactId; $ids = array('contribution' => NULL); $param = array('contact_id' => $contactId, 'currency' => 'USD', 'financial_type_id' => 4, 'contribution_status_id' => 1, 'receive_date' => date('Ymd'), 'total_amount' => 66); $contribution = CRM_Contribute_BAO_Contribution::create($param, $ids); $id = $contribution->id; $softParam['contribution_id'] = $id; $softParam['currency'] = $contribution->currency; $softParam['amount'] = $contribution->total_amount; //Create Soft Contribution for honoree contact CRM_Contribute_BAO_ContributionSoft::add($softParam); $this->assertDBCompareValue('CRM_Contribute_DAO_ContributionSoft', $id, 'contact_id', 'contribution_id', $honoreeContactId, 'Check DB for honor contact of the contribution'); //get honorary information $getHonorContact = CRM_Contribute_BAO_Contribution::getHonorContacts($honoreeContactId); $this->assertEquals(array($id => array('honor_type' => 'In Honor of', 'honorId' => $id, 'display_name' => 'John Doe', 'type' => 'Event Fee', 'type_id' => '4', 'amount' => '$ 66.00', 'source' => NULL, 'receive_date' => date('Y-m-d 00:00:00'), 'contribution_status' => 'Completed')), $getHonorContact); $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $honoreeContactId, 'first_name', 'id', $firstName, 'Database check for created honor contact record.'); //get annual contribution information $annual = CRM_Contribute_BAO_Contribution::annual($contactId); $config = CRM_Core_Config::singleton(); $currencySymbol = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_Currency', $config->defaultCurrency, 'symbol', 'name'); $this->assertDBCompareValue('CRM_Contribute_DAO_Contribution', $id, 'total_amount', 'id', ltrim($annual[2], $currencySymbol), 'Check DB for total amount of the contribution'); //Delete honor contact Contact::delete($honoreeContactId); //Delete Contribution record $this->contributionDelete($contribution->id); //Delete contributor contact Contact::delete($contactId); }
/** * takes an associative array and creates a contribution object * * @param array $params (reference ) an assoc array of name/value pairs * @param array $ids the array that holds all the db ids * * @return object CRM_Contribute_BAO_Contribution object * @access public * @static */ static function &create(&$params, $ids = array()) { $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date'); foreach ($dateFields as $df) { if (isset($params[$df])) { $params[$df] = CRM_Utils_Date::isoToMysql($params[$df]); } } $transaction = new CRM_Core_Transaction(); $contribution = self::add($params, $ids); if (is_a($contribution, 'CRM_Core_Error')) { $transaction->rollback(); return $contribution; } $params['contribution_id'] = $contribution->id; if (CRM_Utils_Array::value('custom', $params) && is_array($params['custom'])) { CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id); } $session = CRM_Core_Session::singleton(); if (CRM_Utils_Array::value('note', $params)) { $noteParams = array('entity_table' => 'civicrm_contribution', 'note' => $params['note'], 'entity_id' => $contribution->id, 'contact_id' => $session->get('userID'), 'modified_date' => date('Ymd')); if (!$noteParams['contact_id']) { $noteParams['contact_id'] = $params['contact_id']; } CRM_Core_BAO_Note::add($noteParams); } // make entry in batch entity batch table if (CRM_Utils_Array::value('batch_id', $params)) { // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params $titleFields = array('contact_id', 'total_amount', 'currency', 'financial_type_id'); $retrieveRequired = 0; foreach ($titleFields as $titleField) { if (!isset($contribution->{$titleField})) { $retrieveRequired = 1; break; } } if ($retrieveRequired == 1) { $contribution->find(TRUE); } } // check if activity record exist for this contribution, if // not add activity $activity = new CRM_Activity_DAO_Activity(); $activity->source_record_id = $contribution->id; $activity->activity_type_id = CRM_Core_OptionGroup::getValue('activity_type', 'Contribution', 'name'); if (!$activity->find(TRUE)) { CRM_Activity_BAO_Activity::addActivity($contribution, 'Offline'); } else { // CRM-13237 : if activity record found, update it with campaign id of contribution CRM_Core_DAO::setFieldValue('CRM_Activity_BAO_Activity', $activity->id, 'campaign_id', $contribution->campaign_id); } // Handle soft credit and / or link to personal campaign page list($type, $softIDs) = CRM_Contribute_BAO_ContributionSoft::getSoftCreditType($contribution->id); if ($pcp = CRM_Utils_Array::value('pcp', $params)) { if (!empty($type) && $type == 'soft') { $deleteParams = array('contribution_id' => $contribution->id); CRM_Contribute_BAO_ContributionSoft::del($deleteParams); } $softParams = array(); $softParams['contribution_id'] = $contribution->id; $softParams['pcp_id'] = $pcp['pcp_made_through_id']; $softParams['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $pcp['pcp_made_through_id'], 'contact_id'); $softParams['currency'] = $contribution->currency; $softParams['amount'] = $contribution->total_amount; $softParams['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $pcp); $softParams['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $pcp); $softParams['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $pcp); CRM_Contribute_BAO_ContributionSoft::add($softParams); } elseif (CRM_Utils_Array::value('soft_credit', $params)) { $softParams = $params['soft_credit']; if (!empty($softIDs)) { foreach ($softIDs as $softID) { if (!in_array($softID, $params['soft_credit_ids'])) { $deleteParams = array('id' => $softID); CRM_Contribute_BAO_ContributionSoft::del($deleteParams); } } } foreach ($softParams as $softParam) { $softParam['contribution_id'] = $contribution->id; $softParam['currency'] = $contribution->currency; $softParam['pcp_id'] = 'null'; $softParam['pcp_display_in_roll'] = 'null'; $softParam['pcp_roll_nickname'] = 'null'; $softParam['pcp_personal_note'] = 'NULL'; CRM_Contribute_BAO_ContributionSoft::add($softParam); } } $transaction->commit(); // do not add to recent items for import, CRM-4399 if (!CRM_Utils_Array::value('skipRecentView', $params)) { $url = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"); // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params $titleFields = array('contact_id', 'total_amount', 'currency', 'financial_type_id'); $retrieveRequired = 0; foreach ($titleFields as $titleField) { if (!isset($contribution->{$titleField})) { $retrieveRequired = 1; break; } } if ($retrieveRequired == 1) { $contribution->find(TRUE); } $contributionTypes = CRM_Contribute_PseudoConstant::financialType(); $title = CRM_Contact_BAO_Contact::displayName($contribution->contact_id) . ' - (' . CRM_Utils_Money::format($contribution->total_amount, $contribution->currency) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id] . ')'; $recentOther = array(); if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::UPDATE)) { $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"); } if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::DELETE)) { $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"); } // add the recently created Contribution CRM_Utils_Recent::add($title, $url, $contribution->id, 'Contribution', $contribution->contact_id, NULL, $recentOther); } return $contribution; }
/** * Handle the values in import mode. * * @param int $onDuplicate * The code for what action to take on duplicates. * @param array $values * The array of values belonging to this line. * * @return bool * the result of this processing */ public function import($onDuplicate, &$values) { // first make sure this is a valid line $response = $this->summary($values); if ($response != CRM_Import_Parser::VALID) { return $response; } $params =& $this->getActiveFieldParams(); $formatted = array('version' => 3); // don't add to recent items, CRM-4399 $formatted['skipRecentView'] = TRUE; //for date-Formats $session = CRM_Core_Session::singleton(); $dateType = $session->get('dateTypes'); $customDataType = !empty($params['contact_type']) ? $params['contact_type'] : 'Contribution'; $customFields = CRM_Core_BAO_CustomField::getFields($customDataType); //CRM-10994 if (isset($params['total_amount']) && $params['total_amount'] == 0) { $params['total_amount'] = '0.00'; } foreach ($params as $key => $val) { if ($val) { switch ($key) { case 'receive_date': case 'cancel_date': case 'receipt_date': case 'thankyou_date': $params[$key] = CRM_Utils_Date::formatDate($params[$key], $dateType); break; case 'pledge_payment': $params[$key] = CRM_Utils_String::strtobool($val); break; } if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) { if ($customFields[$customFieldID]['data_type'] == 'Date') { CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key); unset($params[$key]); } elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') { $params[$key] = CRM_Utils_String::strtoboolstr($val); } } } } //date-Format part ends static $indieFields = NULL; if ($indieFields == NULL) { $tempIndieFields = CRM_Contribute_DAO_Contribution::import(); $indieFields = $tempIndieFields; } $paramValues = array(); foreach ($params as $key => $field) { if ($field == NULL || $field === '') { continue; } $paramValues[$key] = $field; } //import contribution record according to select contact type if ($onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP && (!empty($paramValues['contribution_contact_id']) || !empty($paramValues['external_identifier']))) { $paramValues['contact_type'] = $this->_contactType; } elseif ($onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE && (!empty($paramValues['contribution_id']) || !empty($values['trxn_id']) || !empty($paramValues['invoice_id']))) { $paramValues['contact_type'] = $this->_contactType; } elseif (!empty($params['soft_credit'])) { $paramValues['contact_type'] = $this->_contactType; } elseif (!empty($paramValues['pledge_payment'])) { $paramValues['contact_type'] = $this->_contactType; } //need to pass $onDuplicate to check import mode. if (!empty($paramValues['pledge_payment'])) { $paramValues['onDuplicate'] = $onDuplicate; } require_once 'CRM/Utils/DeprecatedUtils.php'; $formatError = _civicrm_api3_deprecated_formatted_param($paramValues, $formatted, TRUE, $onDuplicate); if ($formatError) { array_unshift($values, $formatError['error_message']); if (CRM_Utils_Array::value('error_data', $formatError) == 'soft_credit') { return CRM_Contribute_Import_Parser::SOFT_CREDIT_ERROR; } elseif (CRM_Utils_Array::value('error_data', $formatError) == 'pledge_payment') { return CRM_Contribute_Import_Parser::PLEDGE_PAYMENT_ERROR; } return CRM_Import_Parser::ERROR; } if ($onDuplicate != CRM_Import_Parser::DUPLICATE_UPDATE) { $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, NULL, 'Contribution'); } else { //fix for CRM-2219 - Update Contribution // onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE if (!empty($paramValues['invoice_id']) || !empty($paramValues['trxn_id']) || !empty($paramValues['contribution_id'])) { $dupeIds = array('id' => CRM_Utils_Array::value('contribution_id', $paramValues), 'trxn_id' => CRM_Utils_Array::value('trxn_id', $paramValues), 'invoice_id' => CRM_Utils_Array::value('invoice_id', $paramValues)); $ids['contribution'] = CRM_Contribute_BAO_Contribution::checkDuplicateIds($dupeIds); if ($ids['contribution']) { $formatted['id'] = $ids['contribution']; $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, $formatted['id'], 'Contribution'); //process note if (!empty($paramValues['note'])) { $noteID = array(); $contactID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $ids['contribution'], 'contact_id'); $daoNote = new CRM_Core_BAO_Note(); $daoNote->entity_table = 'civicrm_contribution'; $daoNote->entity_id = $ids['contribution']; if ($daoNote->find(TRUE)) { $noteID['id'] = $daoNote->id; } $noteParams = array('entity_table' => 'civicrm_contribution', 'note' => $paramValues['note'], 'entity_id' => $ids['contribution'], 'contact_id' => $contactID); CRM_Core_BAO_Note::add($noteParams, $noteID); unset($formatted['note']); } //need to check existing soft credit contribution, CRM-3968 if (!empty($formatted['soft_credit'])) { $dupeSoftCredit = array('contact_id' => $formatted['soft_credit'], 'contribution_id' => $ids['contribution']); //Delete all existing soft Contribution from contribution_soft table for pcp_id is_null $existingSoftCredit = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($dupeSoftCredit['contribution_id']); if (isset($existingSoftCredit['soft_credit']) && !empty($existingSoftCredit['soft_credit'])) { foreach ($existingSoftCredit['soft_credit'] as $key => $existingSoftCreditValues) { if (!empty($existingSoftCreditValues['soft_credit_id'])) { $deleteParams = array('id' => $existingSoftCreditValues['soft_credit_id'], 'pcp_id' => NULL); CRM_Contribute_BAO_ContributionSoft::del($deleteParams); } } } } $newContribution = CRM_Contribute_BAO_Contribution::create($formatted, $ids); $this->_newContributions[] = $newContribution->id; //return soft valid since we need to show how soft credits were added if (!empty($formatted['soft_credit'])) { return CRM_Contribute_Import_Parser::SOFT_CREDIT; } // process pledge payment assoc w/ the contribution return self::processPledgePayments($formatted); return CRM_Import_Parser::VALID; } else { $labels = array('id' => 'Contribution ID', 'trxn_id' => 'Transaction ID', 'invoice_id' => 'Invoice ID'); foreach ($dupeIds as $k => $v) { if ($v) { $errorMsg[] = "{$labels[$k]} {$v}"; } } $errorMsg = implode(' AND ', $errorMsg); array_unshift($values, 'Matching Contribution record not found for ' . $errorMsg . '. Row was skipped.'); return CRM_Import_Parser::ERROR; } } } if ($this->_contactIdIndex < 0) { // set the contact type if its not set if (!isset($paramValues['contact_type'])) { $paramValues['contact_type'] = $this->_contactType; } $paramValues['version'] = 3; //retrieve contact id using contact dedupe rule require_once 'CRM/Utils/DeprecatedUtils.php'; $error = _civicrm_api3_deprecated_check_contact_dedupe($paramValues); if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) { $matchedIDs = explode(',', $error['error_message']['params'][0]); if (count($matchedIDs) > 1) { array_unshift($values, 'Multiple matching contact records detected for this row. The contribution was not imported'); return CRM_Import_Parser::ERROR; } else { $cid = $matchedIDs[0]; $formatted['contact_id'] = $cid; $newContribution = civicrm_api('contribution', 'create', $formatted); if (civicrm_error($newContribution)) { if (is_array($newContribution['error_message'])) { array_unshift($values, $newContribution['error_message']['message']); if ($newContribution['error_message']['params'][0]) { return CRM_Import_Parser::DUPLICATE; } } else { array_unshift($values, $newContribution['error_message']); return CRM_Import_Parser::ERROR; } } $this->_newContributions[] = $newContribution['id']; $formatted['contribution_id'] = $newContribution['id']; //return soft valid since we need to show how soft credits were added if (!empty($formatted['soft_credit'])) { return CRM_Contribute_Import_Parser::SOFT_CREDIT; } // process pledge payment assoc w/ the contribution return self::processPledgePayments($formatted); return CRM_Import_Parser::VALID; } } else { // Using new Dedupe rule. $ruleParams = array('contact_type' => $this->_contactType, 'used' => 'Unsupervised'); $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams); $disp = NULL; foreach ($fieldsArray as $value) { if (array_key_exists(trim($value), $params)) { $paramValue = $params[trim($value)]; if (is_array($paramValue)) { $disp .= $params[trim($value)][0][trim($value)] . " "; } else { $disp .= $params[trim($value)] . " "; } } } if (!empty($params['external_identifier'])) { if ($disp) { $disp .= "AND {$params['external_identifier']}"; } else { $disp = $params['external_identifier']; } } array_unshift($values, 'No matching Contact found for (' . $disp . ')'); return CRM_Import_Parser::ERROR; } } else { if (!empty($paramValues['external_identifier'])) { $checkCid = new CRM_Contact_DAO_Contact(); $checkCid->external_identifier = $paramValues['external_identifier']; $checkCid->find(TRUE); if ($checkCid->id != $formatted['contact_id']) { array_unshift($values, 'Mismatch of External ID:' . $paramValues['external_identifier'] . ' and Contact Id:' . $formatted['contact_id']); return CRM_Import_Parser::ERROR; } } $newContribution = civicrm_api('contribution', 'create', $formatted); if (civicrm_error($newContribution)) { if (is_array($newContribution['error_message'])) { array_unshift($values, $newContribution['error_message']['message']); if ($newContribution['error_message']['params'][0]) { return CRM_Import_Parser::DUPLICATE; } } else { array_unshift($values, $newContribution['error_message']); return CRM_Import_Parser::ERROR; } } $this->_newContributions[] = $newContribution['id']; $formatted['contribution_id'] = $newContribution['id']; //return soft valid since we need to show how soft credits were added if (!empty($formatted['soft_credit'])) { return CRM_Contribute_Import_Parser::SOFT_CREDIT; } // process pledge payment assoc w/ the contribution return self::processPledgePayments($formatted); return CRM_Import_Parser::VALID; } }
/** * Send the emails. * * @param int $contactID * Contact id. * @param array $values * Associated array of fields. * @param bool $isTest * If in test mode. * @param bool $returnMessageText * Return the message text instead of sending the mail. * * @param null $fieldTypes * * @return void */ public static function sendMail($contactID, $values, $isTest = FALSE, $returnMessageText = FALSE, $fieldTypes = NULL) { $gIds = $params = array(); $email = NULL; if (isset($values['custom_pre_id'])) { $preProfileType = CRM_Core_BAO_UFField::getProfileType($values['custom_pre_id']); if ($preProfileType == 'Membership' && !empty($values['membership_id'])) { $params['custom_pre_id'] = array(array('member_id', '=', $values['membership_id'], 0, 0)); } elseif ($preProfileType == 'Contribution' && !empty($values['contribution_id'])) { $params['custom_pre_id'] = array(array('contribution_id', '=', $values['contribution_id'], 0, 0)); } $gIds['custom_pre_id'] = $values['custom_pre_id']; } if (isset($values['custom_post_id'])) { $postProfileType = CRM_Core_BAO_UFField::getProfileType($values['custom_post_id']); if ($postProfileType == 'Membership' && !empty($values['membership_id'])) { $params['custom_post_id'] = array(array('member_id', '=', $values['membership_id'], 0, 0)); } elseif ($postProfileType == 'Contribution' && !empty($values['contribution_id'])) { $params['custom_post_id'] = array(array('contribution_id', '=', $values['contribution_id'], 0, 0)); } $gIds['custom_post_id'] = $values['custom_post_id']; } if (!empty($values['is_for_organization'])) { if (!empty($values['membership_id'])) { $params['onbehalf_profile'] = array(array('member_id', '=', $values['membership_id'], 0, 0)); } elseif (!empty($values['contribution_id'])) { $params['onbehalf_profile'] = array(array('contribution_id', '=', $values['contribution_id'], 0, 0)); } } //check whether it is a test drive if ($isTest && !empty($params['custom_pre_id'])) { $params['custom_pre_id'][] = array('contribution_test', '=', 1, 0, 0); } if ($isTest && !empty($params['custom_post_id'])) { $params['custom_post_id'][] = array('contribution_test', '=', 1, 0, 0); } if (!$returnMessageText && !empty($gIds)) { //send notification email if field values are set (CRM-1941) foreach ($gIds as $key => $gId) { if ($gId) { $email = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify'); if ($email) { $val = CRM_Core_BAO_UFGroup::checkFieldsEmptyValues($gId, $contactID, CRM_Utils_Array::value($key, $params), TRUE); CRM_Core_BAO_UFGroup::commonSendMail($contactID, $val); } } } } if (!empty($values['is_email_receipt']) || !empty($values['onbehalf_dupe_alert']) || $returnMessageText) { $template = CRM_Core_Smarty::singleton(); // get the billing location type if (!array_key_exists('related_contact', $values)) { $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate'); $billingLocationTypeId = array_search('Billing', $locationTypes); } else { // presence of related contact implies onbehalf of org case, // where location type is set to default. $locType = CRM_Core_BAO_LocationType::getDefault(); $billingLocationTypeId = $locType->id; } if (!array_key_exists('related_contact', $values)) { list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID, FALSE, $billingLocationTypeId); } // get primary location email if no email exist( for billing location). if (!$email) { list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID); } if (empty($displayName)) { list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID); } //for display profile need to get individual contact id, //hence get it from related_contact if on behalf of org true CRM-3767 //CRM-5001 Contribution/Membership:: On Behalf of Organization, //If profile GROUP contain the Individual type then consider the //profile is of Individual ( including the custom data of membership/contribution ) //IF Individual type not present in profile then it is consider as Organization data. $userID = $contactID; if ($preID = CRM_Utils_Array::value('custom_pre_id', $values)) { if (!empty($values['related_contact'])) { $preProfileTypes = CRM_Core_BAO_UFGroup::profileGroups($preID); //@todo - following line should not refer to undefined $postProfileTypes? figure out way to test if (in_array('Individual', $preProfileTypes) || in_array('Contact', $postProfileTypes)) { //Take Individual contact ID $userID = CRM_Utils_Array::value('related_contact', $values); } } self::buildCustomDisplay($preID, 'customPre', $userID, $template, $params['custom_pre_id']); } $userID = $contactID; if ($postID = CRM_Utils_Array::value('custom_post_id', $values)) { if (!empty($values['related_contact'])) { $postProfileTypes = CRM_Core_BAO_UFGroup::profileGroups($postID); if (in_array('Individual', $postProfileTypes) || in_array('Contact', $postProfileTypes)) { //Take Individual contact ID $userID = CRM_Utils_Array::value('related_contact', $values); } } self::buildCustomDisplay($postID, 'customPost', $userID, $template, $params['custom_post_id']); } if (isset($values['honor'])) { $honorValues = $values['honor']; CRM_Contribute_BAO_ContributionSoft::formatHonoreeProfileFields($template, $honorValues['honor_profile_values'], $honorValues['honor_profile_id'], $honorValues['honor_id']); } $title = isset($values['title']) ? $values['title'] : CRM_Contribute_PseudoConstant::contributionPage($values['contribution_page_id']); // set email in the template here $tplParams = array('email' => $email, 'receiptFromEmail' => CRM_Utils_Array::value('receipt_from_email', $values), 'contactID' => $contactID, 'displayName' => $displayName, 'contributionID' => CRM_Utils_Array::value('contribution_id', $values), 'contributionOtherID' => CRM_Utils_Array::value('contribution_other_id', $values), 'lineItem' => CRM_Utils_Array::value('lineItem', $values), 'priceSetID' => CRM_Utils_Array::value('priceSetID', $values), 'title' => $title, 'isShare' => CRM_Utils_Array::value('is_share', $values), 'thankyou_title' => CRM_Utils_Array::value('thankyou_title', $values)); if ($contributionTypeId = CRM_Utils_Array::value('financial_type_id', $values)) { $tplParams['contributionTypeId'] = $contributionTypeId; $tplParams['contributionTypeName'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $contributionTypeId); } if ($contributionPageId = CRM_Utils_Array::value('id', $values)) { $tplParams['contributionPageId'] = $contributionPageId; } // address required during receipt processing (pdf and email receipt) if ($displayAddress = CRM_Utils_Array::value('address', $values)) { $tplParams['address'] = $displayAddress; } // CRM-6976 $originalCCReceipt = CRM_Utils_Array::value('cc_receipt', $values); // cc to related contacts of contributor OR the one who // signs up. Is used for cases like - on behalf of // contribution / signup ..etc if (array_key_exists('related_contact', $values)) { list($ccDisplayName, $ccEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($values['related_contact']); $ccMailId = "{$ccDisplayName} <{$ccEmail}>"; //@todo - this is the only place in this function where $values is altered - but I can't find any evidence it is used $values['cc_receipt'] = !empty($values['cc_receipt']) ? $values['cc_receipt'] . ',' . $ccMailId : $ccMailId; // reset primary-email in the template $tplParams['email'] = $ccEmail; $tplParams['onBehalfName'] = $displayName; $tplParams['onBehalfEmail'] = $email; $ufJoinParams = array('module' => 'onBehalf', 'entity_table' => 'civicrm_contribution_page', 'entity_id' => $values['id']); $OnBehalfProfile = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams); $profileId = $OnBehalfProfile[0]; $userID = $contactID; self::buildCustomDisplay($profileId, 'onBehalfProfile', $userID, $template, $params['onbehalf_profile'], $fieldTypes); } // use either the contribution or membership receipt, based on whether it’s a membership-related contrib or not $sendTemplateParams = array('groupName' => !empty($values['isMembership']) ? 'msg_tpl_workflow_membership' : 'msg_tpl_workflow_contribution', 'valueName' => !empty($values['isMembership']) ? 'membership_online_receipt' : 'contribution_online_receipt', 'contactId' => $contactID, 'tplParams' => $tplParams, 'isTest' => $isTest, 'PDFFilename' => 'receipt.pdf'); if ($returnMessageText) { list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams); return array('subject' => $subject, 'body' => $message, 'to' => $displayName, 'html' => $html); } if ($values['is_email_receipt']) { $sendTemplateParams['from'] = CRM_Utils_Array::value('receipt_from_name', $values) . ' <' . $values['receipt_from_email'] . '>'; $sendTemplateParams['toName'] = $displayName; $sendTemplateParams['toEmail'] = $email; $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_receipt', $values); $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_receipt', $values); //send email with pdf invoice $template = CRM_Core_Smarty::singleton(); $taxAmt = $template->get_template_vars('dataArray'); $prefixValue = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings'); $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue); if (count($taxAmt) > 0 && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) { $sendTemplateParams['isEmailPdf'] = TRUE; $sendTemplateParams['contributionId'] = $values['contribution_id']; } list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams); } // send duplicate alert, if dupe match found during on-behalf-of processing. if (!empty($values['onbehalf_dupe_alert'])) { $sendTemplateParams['groupName'] = 'msg_tpl_workflow_contribution'; $sendTemplateParams['valueName'] = 'contribution_dupalert'; $sendTemplateParams['from'] = ts('Automatically Generated') . " <{$values['receipt_from_email']}>"; $sendTemplateParams['toName'] = CRM_Utils_Array::value('receipt_from_name', $values); $sendTemplateParams['toEmail'] = CRM_Utils_Array::value('receipt_from_email', $values); $sendTemplateParams['tplParams']['onBehalfID'] = $contactID; $sendTemplateParams['tplParams']['receiptMessage'] = $message; // fix cc and reset back to original, CRM-6976 $sendTemplateParams['cc'] = $originalCCReceipt; CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams); } } }
/** * Process the contribution. * * @param CRM_Core_Form $form * @param array $params * @param array $result * @param array $contributionParams * Parameters to be passed to contribution create action. * This differs from params in that we are currently adding params to it and 1) ensuring they are being * passed consistently & 2) documenting them here. * - contact_id * - line_item * - is_test * - campaign_id * - contribution_page_id * - source * - payment_type_id * - thankyou_date (not all forms will set this) * * @param CRM_Financial_DAO_FinancialType $financialType * @param bool $online * Is the form a front end form? If so set a bunch of unpredictable things that should be passed in from the form. * * @param int $billingLocationID * ID of billing location type. * @param bool $isRecur * Is this recurring? * * @return \CRM_Contribute_DAO_Contribution * @throws \Exception */ public static function processFormContribution(&$form, $params, $result, $contributionParams, $financialType, $online, $billingLocationID, $isRecur) { $transaction = new CRM_Core_Transaction(); $contactID = $contributionParams['contact_id']; $isEmailReceipt = !empty($form->_values['is_email_receipt']); $isSeparateMembershipPayment = empty($params['separate_membership_payment']) ? FALSE : TRUE; $pledgeID = !empty($params['pledge_id']) ? $params['pledge_id'] : CRM_Utils_Array::value('pledge_id', $form->_values); if (!$isSeparateMembershipPayment && !empty($form->_values['pledge_block_id']) && (!empty($params['is_pledge']) || $pledgeID)) { $isPledge = TRUE; } else { $isPledge = FALSE; } // add these values for the recurringContrib function ,CRM-10188 $params['financial_type_id'] = $financialType->id; $contributionParams['address_id'] = CRM_Contribute_BAO_Contribution::createAddress($params, $billingLocationID); //@todo - this is being set from the form to resolve CRM-10188 - an // eNotice caused by it not being set @ the front end // however, we then get it being over-written with null for backend contributions // a better fix would be to set the values in the respective forms rather than require // a function being shared by two forms to deal with their respective values // moving it to the BAO & not taking the $form as a param would make sense here. if (!isset($params['is_email_receipt']) && $isEmailReceipt) { $params['is_email_receipt'] = $isEmailReceipt; } $params['is_recur'] = $isRecur; $recurringContributionID = self::processRecurringContribution($form, $params, $contactID, $financialType); $nonDeductibleAmount = self::getNonDeductibleAmount($params, $financialType, $online); $now = date('YmdHis'); $receiptDate = CRM_Utils_Array::value('receipt_date', $params); if ($isEmailReceipt) { $receiptDate = $now; } if (isset($params['amount'])) { $contributionParams = array_merge(self::getContributionParams($params, $financialType->id, $nonDeductibleAmount, TRUE, $result, $receiptDate, $recurringContributionID), $contributionParams); $contribution = CRM_Contribute_BAO_Contribution::add($contributionParams); $invoiceSettings = Civi::settings()->get('contribution_invoice_settings'); $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings); if ($invoicing) { $dataArray = array(); // @todo - interrogate the line items passed in on the params array. // No reason to assume line items will be set on the form. foreach ($form->_lineItem as $lineItemKey => $lineItemValue) { foreach ($lineItemValue as $key => $value) { if (isset($value['tax_amount']) && isset($value['tax_rate'])) { if (isset($dataArray[$value['tax_rate']])) { $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value); } else { $dataArray[$value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value); } } } } $smarty = CRM_Core_Smarty::singleton(); $smarty->assign('dataArray', $dataArray); $smarty->assign('totalTaxAmount', $params['tax_amount']); } if (is_a($contribution, 'CRM_Core_Error')) { $message = CRM_Core_Error::getMessages($contribution); CRM_Core_Error::fatal($message); } // lets store it in the form variable so postProcess hook can get to this and use it $form->_contributionID = $contribution->id; } // process soft credit / pcp params first CRM_Contribute_BAO_ContributionSoft::formatSoftCreditParams($params, $form); //CRM-13981, processing honor contact into soft-credit contribution CRM_Contribute_BAO_ContributionSoft::processSoftContribution($params, $contribution); //handle pledge stuff. if ($isPledge) { if ($pledgeID) { //when user doing pledge payments. //update the schedule when payment(s) are made $amount = $params['amount']; $pledgePaymentParams = array(); foreach ($params['pledge_amount'] as $paymentId => $dontCare) { $scheduledAmount = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $paymentId, 'scheduled_amount', 'id'); $pledgePayment = $amount >= $scheduledAmount ? $scheduledAmount : $amount; if ($pledgePayment > 0) { $pledgePaymentParams[] = array('id' => $paymentId, 'contribution_id' => $contribution->id, 'status_id' => $contribution->contribution_status_id, 'actual_amount' => $pledgePayment); $amount -= $pledgePayment; } } if ($amount > 0 && count($pledgePaymentParams)) { $pledgePaymentParams[count($pledgePaymentParams) - 1]['actual_amount'] += $amount; } foreach ($pledgePaymentParams as $p) { CRM_Pledge_BAO_PledgePayment::add($p); } //update pledge status according to the new payment statuses CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID); } else { //when user creating pledge record. $pledgeParams = array(); $pledgeParams['contact_id'] = $contribution->contact_id; $pledgeParams['installment_amount'] = $pledgeParams['actual_amount'] = $contribution->total_amount; $pledgeParams['contribution_id'] = $contribution->id; $pledgeParams['contribution_page_id'] = $contribution->contribution_page_id; $pledgeParams['financial_type_id'] = $contribution->financial_type_id; $pledgeParams['frequency_interval'] = $params['pledge_frequency_interval']; $pledgeParams['installments'] = $params['pledge_installments']; $pledgeParams['frequency_unit'] = $params['pledge_frequency_unit']; if ($pledgeParams['frequency_unit'] == 'month') { $pledgeParams['frequency_day'] = intval(date("d")); } else { $pledgeParams['frequency_day'] = 1; } $pledgeParams['create_date'] = $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date("Ymd"); $pledgeParams['status_id'] = $contribution->contribution_status_id; $pledgeParams['max_reminders'] = $form->_values['max_reminders']; $pledgeParams['initial_reminder_day'] = $form->_values['initial_reminder_day']; $pledgeParams['additional_reminder_day'] = $form->_values['additional_reminder_day']; $pledgeParams['is_test'] = $contribution->is_test; $pledgeParams['acknowledge_date'] = date('Ymd'); $pledgeParams['original_installment_amount'] = $pledgeParams['installment_amount']; //inherit campaign from contirb page. $pledgeParams['campaign_id'] = CRM_Utils_Array::value('campaign_id', $contributionParams); $pledge = CRM_Pledge_BAO_Pledge::create($pledgeParams); $form->_params['pledge_id'] = $pledge->id; //send acknowledgment email. only when pledge is created if ($pledge->id) { //build params to send acknowledgment. $pledgeParams['id'] = $pledge->id; $pledgeParams['receipt_from_name'] = $form->_values['receipt_from_name']; $pledgeParams['receipt_from_email'] = $form->_values['receipt_from_email']; //scheduled amount will be same as installment_amount. $pledgeParams['scheduled_amount'] = $pledgeParams['installment_amount']; //get total pledge amount. $pledgeParams['total_pledge_amount'] = $pledge->amount; CRM_Pledge_BAO_Pledge::sendAcknowledgment($form, $pledgeParams); } } } if ($online && $contribution) { CRM_Core_BAO_CustomValueTable::postProcess($params, 'civicrm_contribution', $contribution->id, 'Contribution'); } elseif ($contribution) { //handle custom data. $params['contribution_id'] = $contribution->id; if (!empty($params['custom']) && is_array($params['custom']) && !is_a($contribution, 'CRM_Core_Error')) { CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id); } } // Save note if ($contribution && !empty($params['contribution_note'])) { $noteParams = array('entity_table' => 'civicrm_contribution', 'note' => $params['contribution_note'], 'entity_id' => $contribution->id, 'contact_id' => $contribution->contact_id, 'modified_date' => date('Ymd')); CRM_Core_BAO_Note::add($noteParams, array()); } if (isset($params['related_contact'])) { $contactID = $params['related_contact']; } elseif (isset($params['cms_contactID'])) { $contactID = $params['cms_contactID']; } //create contribution activity w/ individual and target //activity w/ organisation contact id when onbelf, CRM-4027 $targetContactID = NULL; if (!empty($params['hidden_onbehalf_profile'])) { $targetContactID = $contribution->contact_id; $contribution->contact_id = $contactID; } // create an activity record if ($contribution) { CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID); } $transaction->commit(); // CRM-13074 - create the CMSUser after the transaction is completed as it // is not appropriate to delete a valid contribution if a user create problem occurs CRM_Contribute_BAO_Contribution_Utils::createCMSUser($params, $contactID, 'email-' . $billingLocationID); return $contribution; }
/** * Process the contribution. * * @param CRM_Core_Form $form * @param array $params * @param array $result * @param int $contactID * @param bool $pending * @param bool $isAdditionalAmount * * @return \CRM_Contribute_BAO_Contribution */ public static function processContribution(&$form, $params, $result, $contactID, $pending = FALSE, $isAdditionalAmount = FALSE) { $transaction = new CRM_Core_Transaction(); $now = date('YmdHis'); $receiptDate = NULL; if (!empty($form->_values['event']['is_email_confirm'])) { $receiptDate = $now; } //CRM-4196 if ($isAdditionalAmount) { $params['amount_level'] = $params['amount_level'] . ts(' (multiple participants)') . CRM_Core_DAO::VALUE_SEPARATOR; } $contribParams = array('contact_id' => $contactID, 'financial_type_id' => !empty($form->_values['event']['financial_type_id']) ? $form->_values['event']['financial_type_id'] : $params['financial_type_id'], 'receive_date' => $now, 'total_amount' => $params['amount'], 'tax_amount' => $params['tax_amount'], 'amount_level' => $params['amount_level'], 'invoice_id' => $params['invoiceID'], 'currency' => $params['currencyID'], 'source' => !empty($params['participant_source']) ? $params['participant_source'] : $params['description'], 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0), 'campaign_id' => CRM_Utils_Array::value('campaign_id', $params)); if (empty($params['is_pay_later'])) { $contribParams['payment_instrument_id'] = 1; } if (!$pending && $result) { $contribParams += array('fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $params['amount']), 'trxn_id' => $result['trxn_id'], 'receipt_date' => $receiptDate); } $allStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); $contribParams['contribution_status_id'] = array_search('Completed', $allStatuses); if ($pending) { $contribParams['contribution_status_id'] = array_search('Pending', $allStatuses); } $contribParams['is_test'] = 0; if ($form->_action & CRM_Core_Action::PREVIEW || CRM_Utils_Array::value('mode', $params) == 'test') { $contribParams['is_test'] = 1; } $contribID = NULL; if (!empty($contribParams['invoice_id'])) { $contribID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contribParams['invoice_id'], 'id', 'invoice_id'); } $ids = array(); if ($contribID) { $ids['contribution'] = $contribID; $contribParams['id'] = $contribID; } if (CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled')) { $eventStartDate = CRM_Utils_Array::value('start_date', CRM_Utils_Array::value('event', $form->_values)); if ($eventStartDate) { $contribParams['revenue_recognition_date'] = date('Ymd', strtotime($eventStartDate)); } } //create an contribution address // The concept of contributeMode is deprecated. Elsewhere we use the function processBillingAddress() - although // currently that is only inherited by back-office forms. if ($form->_contributeMode != 'notify' && empty($params['is_pay_later'])) { $contribParams['address_id'] = CRM_Contribute_BAO_Contribution::createAddress($params, $form->_bltID); } $contribParams['payment_processor'] = CRM_Utils_Array::value('payment_processor', $params); $contribParams['skipLineItem'] = 1; // create contribution record $contribution = CRM_Contribute_BAO_Contribution::add($contribParams, $ids); // CRM-11124 CRM_Event_BAO_Participant::createDiscountTrxn($form->_eventId, $contribParams, NULL, CRM_Price_BAO_PriceSet::parseFirstPriceSetValueIDFromParams($params)); // process soft credit / pcp pages if (!empty($params['pcp_made_through_id'])) { CRM_Contribute_BAO_ContributionSoft::formatSoftCreditParams($params, $form); CRM_Contribute_BAO_ContributionSoft::processSoftContribution($params, $contribution); } $transaction->commit(); return $contribution; }
/** * @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; }
/** * Submit function. * * This is also accessed by unit tests. * * @param array $formValues * * @return array */ public function submit($formValues) { $isTest = $this->_mode == 'test' ? 1 : 0; $joinDate = $startDate = $endDate = NULL; $membershipTypes = $membership = $calcDate = array(); $membershipType = NULL; $mailSend = FALSE; $formValues = $this->setPriceSetParameters($formValues); $params = $softParams = $ids = array(); $allMemberStatus = CRM_Member_PseudoConstant::membershipStatus(); $allContributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(); if ($this->_id) { $ids['membership'] = $params['id'] = $this->_id; } $ids['userId'] = CRM_Core_Session::singleton()->get('userID'); // Set variables that we normally get from context. // In form mode these are set in preProcess. //TODO: set memberships, fixme $this->setContextVariables($formValues); $this->_memTypeSelected = self::getSelectedMemberships($this->_priceSet, $formValues); if (empty($formValues['financial_type_id'])) { $formValues['financial_type_id'] = $this->_priceSet['financial_type_id']; } $config = CRM_Core_Config::singleton(); $this->convertDateFieldsToMySQL($formValues); $membershipTypeValues = array(); foreach ($this->_memTypeSelected as $memType) { $membershipTypeValues[$memType]['membership_type_id'] = $memType; } //take the required membership recur values. if ($this->_mode && !empty($formValues['auto_renew'])) { $params['is_recur'] = $formValues['is_recur'] = TRUE; $mapping = array('frequency_interval' => 'duration_interval', 'frequency_unit' => 'duration_unit'); $count = 0; foreach ($this->_memTypeSelected as $memType) { $recurMembershipTypeValues = CRM_Utils_Array::value($memType, $this->_recurMembershipTypes, array()); foreach ($mapping as $mapVal => $mapParam) { $membershipTypeValues[$memType][$mapVal] = CRM_Utils_Array::value($mapParam, $recurMembershipTypeValues); if (!$count) { $formValues[$mapVal] = CRM_Utils_Array::value($mapParam, $recurMembershipTypeValues); } } $count++; } } $isQuickConfig = $this->_priceSet['is_quick_config']; $termsByType = array(); $lineItem = array($this->_priceSetId => array()); CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $formValues, $lineItem[$this->_priceSetId]); if (CRM_Utils_Array::value('tax_amount', $formValues)) { $params['tax_amount'] = $formValues['tax_amount']; } $params['total_amount'] = CRM_Utils_Array::value('amount', $formValues); $submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $formValues); if (!empty($lineItem[$this->_priceSetId])) { foreach ($lineItem[$this->_priceSetId] as &$li) { if (!empty($li['membership_type_id'])) { if (!empty($li['membership_num_terms'])) { $termsByType[$li['membership_type_id']] = $li['membership_num_terms']; } } ///CRM-11529 for quick config backoffice transactions //when financial_type_id is passed in form, update the //lineitems with the financial type selected in form if ($isQuickConfig && $submittedFinancialType) { $li['financial_type_id'] = $submittedFinancialType; } } } $this->storeContactFields($formValues); $params['contact_id'] = $this->_contactID; $fields = array('status_id', 'source', 'is_override', 'campaign_id'); foreach ($fields as $f) { $params[$f] = CRM_Utils_Array::value($f, $formValues); } // fix for CRM-3724 // when is_override false ignore is_admin statuses during membership // status calculation. similarly we did fix for import in CRM-3570. if (empty($params['is_override'])) { $params['exclude_is_admin'] = TRUE; } // process date params to mysql date format. $dateTypes = array('join_date' => 'joinDate', 'start_date' => 'startDate', 'end_date' => 'endDate'); foreach ($dateTypes as $dateField => $dateVariable) { ${$dateVariable} = CRM_Utils_Date::processDate($formValues[$dateField]); } $memTypeNumTerms = empty($termsByType) ? CRM_Utils_Array::value('num_terms', $formValues) : NULL; $calcDates = array(); foreach ($this->_memTypeSelected as $memType) { if (empty($memTypeNumTerms)) { $memTypeNumTerms = CRM_Utils_Array::value($memType, $termsByType, 1); } $calcDates[$memType] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($memType, $joinDate, $startDate, $endDate, $memTypeNumTerms); } foreach ($calcDates as $memType => $calcDate) { foreach (array_keys($dateTypes) as $d) { //first give priority to form values then calDates. $date = CRM_Utils_Array::value($d, $formValues); if (!$date) { $date = CRM_Utils_Array::value($d, $calcDate); } $membershipTypeValues[$memType][$d] = CRM_Utils_Date::processDate($date); } } // max related memberships - take from form or inherit from membership type foreach ($this->_memTypeSelected as $memType) { if (array_key_exists('max_related', $formValues)) { $membershipTypeValues[$memType]['max_related'] = CRM_Utils_Array::value('max_related', $formValues); } $membershipTypeValues[$memType]['custom'] = CRM_Core_BAO_CustomField::postProcess($formValues, $this->_id, 'Membership'); $membershipTypes[$memType] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $memType); } $membershipType = implode(', ', $membershipTypes); // Retrieve the name and email of the current user - this will be the FROM for the receipt email list($userName) = CRM_Contact_BAO_Contact_Location::getEmailDetails($ids['userId']); //CRM-13981, allow different person as a soft-contributor of chosen type if ($this->_contributorContactID != $this->_contactID) { $params['contribution_contact_id'] = $this->_contributorContactID; if (!empty($formValues['soft_credit_type_id'])) { $softParams['soft_credit_type_id'] = $formValues['soft_credit_type_id']; $softParams['contact_id'] = $this->_contactID; } } if (!empty($formValues['record_contribution'])) { $recordContribution = array('total_amount', 'financial_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'check_number', 'campaign_id', 'receive_date'); foreach ($recordContribution as $f) { $params[$f] = CRM_Utils_Array::value($f, $formValues); } if (!$this->_onlinePendingContributionId) { if (empty($formValues['source'])) { $params['contribution_source'] = ts('%1 Membership: Offline signup (by %2)', array(1 => $membershipType, 2 => $userName)); } else { $params['contribution_source'] = $formValues['source']; } } if (empty($params['is_override']) && CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'))) { $params['status_id'] = array_search('Pending', $allMemberStatus); $params['skipStatusCal'] = TRUE; $params['is_pay_later'] = 1; $this->assign('is_pay_later', 1); } if (!empty($formValues['send_receipt'])) { $params['receipt_date'] = CRM_Utils_Array::value('receive_date', $formValues); } //insert financial type name in receipt. $formValues['contributionType_name'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $formValues['financial_type_id']); } // process line items, until no previous line items. if (!empty($lineItem)) { $params['lineItems'] = $lineItem; $params['processPriceSet'] = TRUE; } $createdMemberships = array(); if ($this->_mode) { $params['total_amount'] = CRM_Utils_Array::value('total_amount', $formValues, 0); if (!$isQuickConfig) { $params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'financial_type_id'); } else { $params['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $formValues); } $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($formValues['payment_processor_id'], $this->_mode); //get the payment processor id as per mode. $params['payment_processor_id'] = $formValues['payment_processor_id'] = $this->_paymentProcessor['id']; $now = date('YmdHis'); $fields = array(); // set email for primary location. $fields['email-Primary'] = 1; $formValues['email-5'] = $formValues['email-Primary'] = $this->_memberEmail; $params['register_date'] = $now; // now set the values for the billing location. foreach ($this->_fields as $name => $dontCare) { $fields[$name] = 1; } // also add location name to the array $formValues["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_middle_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_last_name', $formValues); $formValues["address_name-{$this->_bltID}"] = trim($formValues["address_name-{$this->_bltID}"]); $fields["address_name-{$this->_bltID}"] = 1; //ensure we don't over-write the payer's email with the member's email if ($this->_contributorContactID == $this->_contactID) { $fields["email-{$this->_bltID}"] = 1; } $nameFields = array('first_name', 'middle_name', 'last_name'); foreach ($nameFields as $name) { $fields[$name] = 1; if (array_key_exists("billing_{$name}", $formValues)) { $formValues[$name] = $formValues["billing_{$name}"]; $formValues['preserveDBName'] = TRUE; } } if ($this->_contributorContactID == $this->_contactID) { //see CRM-12869 for discussion of why we don't do this for separate payee payments CRM_Contact_BAO_Contact::createProfileContact($formValues, $fields, $this->_contributorContactID, NULL, NULL, CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type')); } // add all the additional payment params we need $formValues["state_province-{$this->_bltID}"] = $formValues["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($formValues["billing_state_province_id-{$this->_bltID}"]); $formValues["country-{$this->_bltID}"] = $formValues["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($formValues["billing_country_id-{$this->_bltID}"]); $formValues['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($formValues); $formValues['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($formValues); $formValues['ip_address'] = CRM_Utils_System::ipAddress(); $formValues['amount'] = $params['total_amount']; $formValues['currencyID'] = $config->defaultCurrency; $formValues['description'] = ts("Contribution submitted by a staff person using member's credit card for signup"); $formValues['invoiceID'] = md5(uniqid(rand(), TRUE)); $formValues['financial_type_id'] = $params['financial_type_id']; // at this point we've created a contact and stored its address etc // all the payment processors expect the name and address to be in the // so we copy stuff over to first_name etc. $paymentParams = $formValues; $paymentParams['contactID'] = $this->_contributorContactID; //CRM-10377 if payment is by an alternate contact then we need to set that person // as the contact in the payment params if ($this->_contributorContactID != $this->_contactID) { if (!empty($formValues['soft_credit_type_id'])) { $softParams['contact_id'] = $params['contact_id']; $softParams['soft_credit_type_id'] = $formValues['soft_credit_type_id']; } } if (!empty($formValues['send_receipt'])) { $paymentParams['email'] = $this->_contributorEmail; } CRM_Core_Payment_Form::mapParams($this->_bltID, $formValues, $paymentParams, TRUE); // CRM-7137 -for recurring membership, // we do need contribution and recurring records. $result = NULL; if (!empty($paymentParams['is_recur'])) { $financialType = new CRM_Financial_DAO_FinancialType(); $financialType->id = $params['financial_type_id']; $financialType->find(TRUE); $this->_params = $formValues; $contribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution($this, $paymentParams, NULL, array('contact_id' => $this->_contributorContactID, 'line_item' => $lineItem, 'is_test' => $isTest, 'campaign_id' => CRM_Utils_Array::value('campaign_id', $paymentParams), 'contribution_page_id' => CRM_Utils_Array::value('contribution_page_id', $formValues), 'source' => CRM_Utils_Array::value('source', $paymentParams, CRM_Utils_Array::value('description', $paymentParams)), 'thankyou_date' => CRM_Utils_Array::value('thankyou_date', $paymentParams), 'payment_instrument_id' => $this->_paymentProcessor['payment_instrument_id']), $financialType, TRUE, FALSE, $this->_bltID); //create new soft-credit record, CRM-13981 if ($softParams) { $softParams['contribution_id'] = $contribution->id; $softParams['currency'] = $contribution->currency; $softParams['amount'] = $contribution->total_amount; CRM_Contribute_BAO_ContributionSoft::add($softParams); } $paymentParams['contactID'] = $this->_contactID; $paymentParams['contributionID'] = $contribution->id; $paymentParams['contributionTypeID'] = $contribution->financial_type_id; $paymentParams['contributionPageID'] = $contribution->contribution_page_id; $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id; $ids['contribution'] = $contribution->id; $params['contribution_recur_id'] = $paymentParams['contributionRecurID']; } if ($params['total_amount'] > 0.0) { $payment = $this->_paymentProcessor['object']; try { $result = $payment->doPayment($paymentParams); $formValues = array_merge($formValues, $result); // Assign amount to template if payment was successful. $this->assign('amount', $params['total_amount']); } catch (PaymentProcessorException $e) { if (!empty($paymentParams['contributionID'])) { CRM_Contribute_BAO_Contribution::failPayment($paymentParams['contributionID'], $this->_contactID, $e->getMessage()); } if (!empty($paymentParams['contributionRecurID'])) { CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']); } CRM_Core_Error::displaySessionError($result); CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=add&cid={$this->_contactID}&context=&mode={$this->_mode}")); } } if ($formValues['payment_status_id'] != array_search('Completed', $allContributionStatus)) { $params['status_id'] = array_search('Pending', $allMemberStatus); $params['skipStatusCal'] = TRUE; // unset send-receipt option, since receipt will be sent when ipn is received. unset($formValues['send_receipt'], $formValues['send_receipt']); //as membership is pending set dates to null. $memberDates = array('join_date' => 'joinDate', 'start_date' => 'startDate', 'end_date' => 'endDate'); foreach ($memberDates as $dv) { ${$dv} = NULL; foreach ($this->_memTypeSelected as $memType) { $membershipTypeValues[$memType][$dv] = NULL; } } } $params['receive_date'] = $now; $params['invoice_id'] = $formValues['invoiceID']; $params['contribution_source'] = ts('%1 Membership Signup: Credit card or direct debit (by %2)', array(1 => $membershipType, 2 => $userName)); $params['source'] = $formValues['source'] ? $formValues['source'] : $params['contribution_source']; $params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result); $params['payment_instrument_id'] = 1; $params['is_test'] = $this->_mode == 'live' ? 0 : 1; if (!empty($formValues['send_receipt'])) { $params['receipt_date'] = $now; } else { $params['receipt_date'] = NULL; } $this->set('params', $formValues); $this->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $result)); $this->assign('receive_date', CRM_Utils_Date::mysqlToIso($params['receive_date'])); // required for creating membership for related contacts $params['action'] = $this->_action; //create membership record. $count = 0; foreach ($this->_memTypeSelected as $memType) { if ($count && ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))) { $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution; } $membershipParams = array_merge($membershipTypeValues[$memType], $params); //CRM-15366 if (!empty($softParams) && empty($paymentParams['is_recur'])) { $membershipParams['soft_credit'] = $softParams; } // This is required to trigger the recording of the membership contribution in the // CRM_Member_BAO_Membership::Create function. // @todo stop setting this & 'teach' the create function to respond to something // appropriate as part of our 2-step always create the pending contribution & then finally add the payment // process - // @see http://wiki.civicrm.org/confluence/pages/viewpage.action?pageId=261062657#Payments&AccountsRoadmap-Movetowardsalwaysusinga2-steppaymentprocess $membershipParams['contribution_status_id'] = CRM_Utils_Array::value('payment_status_id', $result); if (!empty($paymentParams['is_recur'])) { // The earlier process created the line items (although we want to get rid of the earlier one in favour // of a single path! unset($membershipParams['lineItems']); } $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids); $params['contribution'] = CRM_Utils_Array::value('contribution', $membershipParams); unset($params['lineItems']); $this->_membershipIDs[] = $membership->id; $createdMemberships[$memType] = $membership; $count++; } } else { $params['action'] = $this->_action; if ($this->_onlinePendingContributionId && !empty($formValues['record_contribution'])) { // update membership as well as contribution object, CRM-4395 $params['contribution_id'] = $this->_onlinePendingContributionId; $params['componentId'] = $params['id']; $params['componentName'] = 'contribute'; $result = CRM_Contribute_BAO_Contribution::transitionComponents($params, TRUE); if (!empty($result) && !empty($params['contribution_id'])) { $lineItem = array(); $lineItems = CRM_Price_BAO_LineItem::getLineItems($params['contribution_id'], 'contribution', NULL, TRUE, TRUE); $itemId = key($lineItems); $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id'); $lineItems[$itemId]['unit_price'] = $params['total_amount']; $lineItems[$itemId]['line_total'] = $params['total_amount']; $lineItems[$itemId]['id'] = $itemId; $lineItem[$priceSetId] = $lineItems; $contributionBAO = new CRM_Contribute_BAO_Contribution(); $contributionBAO->id = $params['contribution_id']; $contributionBAO->contact_id = $params['contact_id']; $contributionBAO->find(); CRM_Price_BAO_LineItem::processPriceSet($params['contribution_id'], $lineItem, $contributionBAO, 'civicrm_membership'); //create new soft-credit record, CRM-13981 if ($softParams) { $softParams['contribution_id'] = $params['contribution_id']; while ($contributionBAO->fetch()) { $softParams['currency'] = $contributionBAO->currency; $softParams['amount'] = $contributionBAO->total_amount; } CRM_Contribute_BAO_ContributionSoft::add($softParams); } } //carry updated membership object. $membership = new CRM_Member_DAO_Membership(); $membership->id = $this->_id; $membership->find(TRUE); $cancelled = TRUE; if ($membership->end_date) { //display end date w/ status message. $endDate = $membership->end_date; if (!in_array($membership->status_id, array(array_search('Cancelled', CRM_Member_PseudoConstant::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)), array_search('Expired', CRM_Member_PseudoConstant::membershipStatus())))) { $cancelled = FALSE; } } // suppress form values in template. $this->assign('cancelled', $cancelled); $createdMemberships[] = $membership; } else { $count = 0; foreach ($this->_memTypeSelected as $memType) { if ($count && !empty($formValues['record_contribution']) && ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))) { $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution; } $membershipParams = array_merge($params, $membershipTypeValues[$memType]); if (!empty($formValues['int_amount'])) { $init_amount = array(); foreach ($formValues as $key => $value) { if (strstr($key, 'txt-price')) { $init_amount[$key] = $value; } } $membershipParams['init_amount'] = $init_amount; } if (!empty($softParams)) { $membershipParams['soft_credit'] = $softParams; } $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids); $params['contribution'] = CRM_Utils_Array::value('contribution', $membershipParams); unset($params['lineItems']); $this->_membershipIDs[] = $membership->id; $createdMemberships[$memType] = $membership; $count++; } } } if (!empty($lineItem[$this->_priceSetId])) { $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings'); $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings); $taxAmount = FALSE; $totalTaxAmount = 0; foreach ($lineItem[$this->_priceSetId] as &$priceFieldOp) { if (!empty($priceFieldOp['membership_type_id'])) { $priceFieldOp['start_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'] ? CRM_Utils_Date::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'], '%B %E%f, %Y') : '-'; $priceFieldOp['end_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'] ? CRM_Utils_Date::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'], '%B %E%f, %Y') : '-'; } else { $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A'; } if ($invoicing && isset($priceFieldOp['tax_amount'])) { $taxAmount = TRUE; $totalTaxAmount += $priceFieldOp['tax_amount']; } } if ($invoicing) { $dataArray = array(); foreach ($lineItem[$this->_priceSetId] as $key => $value) { if (isset($value['tax_amount']) && isset($value['tax_rate'])) { if (isset($dataArray[$value['tax_rate']])) { $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value); } else { $dataArray[$value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value); } } } if ($taxAmount) { $this->assign('totalTaxAmount', $totalTaxAmount); $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings)); } $this->assign('dataArray', $dataArray); } } $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE); $receiptSend = FALSE; $contributionId = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id); $membershipIds = $this->_membershipIDs; if ($contributionId && !empty($membershipIds)) { $contributionDetails = CRM_Contribute_BAO_Contribution::getContributionDetails(CRM_Export_Form_Select::MEMBER_EXPORT, $this->_membershipIDs); if ($contributionDetails[$membership->id]['contribution_status'] == 'Completed') { $receiptSend = TRUE; } } if (!empty($formValues['send_receipt']) && $receiptSend) { $formValues['contact_id'] = $this->_contactID; $formValues['contribution_id'] = $contributionId; // We really don't need a distinct receipt_text_signup vs receipt_text_renewal as they are // handled in the receipt. But by setting one we avoid breaking templates for now // although at some point we should switch in the templates. $formValues['receipt_text_signup'] = $formValues['receipt_text']; // send email receipt $mailSend = self::emailReceipt($this, $formValues, $membership); } // finally set membership id if already not set if (!$this->_id) { $this->_id = $membership->id; } $isRecur = CRM_Utils_Array::value('is_recur', $params); $this->setStatusMessage($membership, $endDate, $receiptSend, $membershipTypes, $createdMemberships, $isRecur, $calcDates, $mailSend); return $createdMemberships; }
/** * This function is called when action is browse * * return null * @access public */ function browse() { CRM_Core_Resources::singleton()->addScriptFile('civicrm', 'js/crm.livePage.js'); // add annual contribution $annual = array(); list($annual['count'], $annual['amount'], $annual['avg']) = CRM_Contribute_BAO_Contribution::annual($this->_contactId); $this->assign('annual', $annual); $controller = new CRM_Core_Controller_Simple('CRM_Contribute_Form_Search', ts('Contributions'), $this->_action, FALSE, FALSE, TRUE); $controller->setEmbedded(TRUE); $controller->reset(); $controller->set('cid', $this->_contactId); $controller->set('crid', $this->_crid); $controller->set('context', 'Search'); $controller->set('limit', 50); $controller->process(); $controller->run(); // add recurring block $action = array_sum(array_keys($this->recurLinks())); $params = CRM_Contribute_BAO_ContributionRecur::getRecurContributions($this->_contactId); if (!empty($params)) { foreach ($params as $ids => $recur) { $action = array_sum(array_keys($this->recurLinks($ids))); // no action allowed if it's not active $params[$ids]['is_active'] = $recur['contribution_status_id'] != 3; if ($params[$ids]['is_active']) { $details = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($params[$ids]['id'], 'recur'); $hideUpdate = $details->membership_id & $details->auto_renew; if ($hideUpdate) { $action -= CRM_Core_Action::UPDATE; } $params[$ids]['action'] = CRM_Core_Action::formLink(self::recurLinks($ids), $action, array('cid' => $this->_contactId, 'crid' => $ids, 'cxt' => 'contribution'), ts('more'), FALSE, 'contribution.selector.recurring', 'Contribution', $ids); } } // assign vars to templates $this->assign('action', $this->_action); $this->assign('recurRows', $params); $this->assign('recur', TRUE); } //enable/disable soft credit records for test contribution $isTest = 0; if (CRM_Utils_Request::retrieve('isTest', 'Positive', $this)) { $isTest = 1; } $this->assign('isTest', $isTest); $softCreditList = CRM_Contribute_BAO_ContributionSoft::getSoftContributionList($this->_contactId, $isTest); if (!empty($softCreditList)) { $softCreditTotals = array(); list($softCreditTotals['amount'], $softCreditTotals['avg'], $softCreditTotals['currency']) = CRM_Contribute_BAO_ContributionSoft::getSoftContributionTotals($this->_contactId, $isTest); $this->assign('softCredit', TRUE); $this->assign('softCreditRows', $softCreditList); $this->assign('softCreditTotals', $softCreditTotals); } if ($this->_contactId) { $displayName = CRM_Contact_BAO_Contact::displayName($this->_contactId); $this->assign('displayName', $displayName); $this->ajaxResponse['tabCount'] = CRM_Contact_BAO_Contact::getCountComponent('contribution', $this->_contactId); } }
/** * the main function that is called when the page loads, it decides the which action has to be taken for the page. * * @return null */ public function run() { $this->preProcess(); // check if we can process credit card membership $newCredit = CRM_Core_Config::isEnabledBackOfficeCreditCardPayments(); $this->assign('newCredit', $newCredit); if ($newCredit) { $this->_isPaymentProcessor = TRUE; } else { $this->_isPaymentProcessor = FALSE; } // Only show credit card membership signup if user has CiviContribute permission if (CRM_Core_Permission::access('CiviContribute')) { $this->_accessContribution = TRUE; $this->assign('accessContribution', TRUE); //show associated soft credit when contribution payment is paid by different person if ($this->_id && $this->_contactId) { $filter = " AND cc.id IN (SELECT contribution_id FROM civicrm_membership_payment WHERE membership_id = {$this->_id})"; $softCreditList = CRM_Contribute_BAO_ContributionSoft::getSoftContributionList($this->_contactId, $filter); if (!empty($softCreditList)) { $this->assign('softCredit', TRUE); $this->assign('softCreditRows', $softCreditList); } } } else { $this->_accessContribution = FALSE; $this->assign('accessContribution', FALSE); $this->assign('softCredit', FALSE); } if ($this->_action & CRM_Core_Action::VIEW) { $this->view(); } elseif ($this->_action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD | CRM_Core_Action::DELETE | CRM_Core_Action::RENEW)) { self::setContext($this); $this->edit(); } else { self::setContext($this); $this->browse(); } return parent::run(); }
/** * Record contribution record associated with membership. * * @param array $params * Array of submitted params. * @param array $ids * (param in process of being removed - try to use params) array of ids. * * @return CRM_Contribute_BAO_Contribution */ public static function recordMembershipContribution(&$params, $ids = array()) { $membershipId = $params['membership_id']; $contributionParams = array(); $config = CRM_Core_Config::singleton(); $contributionParams['currency'] = $config->defaultCurrency; $contributionParams['receipt_date'] = CRM_Utils_Array::value('receipt_date', $params) ? $params['receipt_date'] : 'null'; $contributionParams['source'] = CRM_Utils_Array::value('contribution_source', $params); $contributionParams['non_deductible_amount'] = 'null'; $contributionParams['payment_processor'] = CRM_Utils_Array::value('payment_processor_id', $params); $contributionSoftParams = CRM_Utils_Array::value('soft_credit', $params); $recordContribution = array('contact_id', 'fee_amount', 'total_amount', 'receive_date', 'financial_type_id', 'payment_instrument_id', 'trxn_id', 'invoice_id', 'is_test', 'contribution_status_id', 'check_number', 'campaign_id', 'is_pay_later', 'membership_id', 'tax_amount', 'skipLineItem', 'contribution_recur_id'); foreach ($recordContribution as $f) { $contributionParams[$f] = CRM_Utils_Array::value($f, $params); } // make entry in batch entity batch table if (!empty($params['batch_id'])) { $contributionParams['batch_id'] = $params['batch_id']; } if (!empty($params['contribution_contact_id'])) { // deal with possibility of a different person paying for contribution $contributionParams['contact_id'] = $params['contribution_contact_id']; } if (!empty($params['processPriceSet']) && !empty($params['lineItems'])) { $contributionParams['line_item'] = CRM_Utils_Array::value('lineItems', $params, NULL); } $contribution = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids); //CRM-13981, create new soft-credit record as to record payment from different person for this membership if (!empty($contributionSoftParams)) { if (!empty($params['batch_id'])) { foreach ($contributionSoftParams as $contributionSoft) { $contributionSoft['contribution_id'] = $contribution->id; $contributionSoft['currency'] = $contribution->currency; CRM_Contribute_BAO_ContributionSoft::add($contributionSoft); } } else { $contributionSoftParams['contribution_id'] = $contribution->id; $contributionSoftParams['currency'] = $contribution->currency; $contributionSoftParams['amount'] = $contribution->total_amount; CRM_Contribute_BAO_ContributionSoft::add($contributionSoftParams); } } // store contribution id $params['contribution_id'] = $contribution->id; //insert payment record for this membership if (empty($ids['contribution']) || !empty($params['is_recur'])) { CRM_Member_BAO_MembershipPayment::create(array('membership_id' => $membershipId, 'contribution_id' => $contribution->id)); } return $contribution; }
/** * Process contribution records. * * @param array $params * Associated array of submitted values. * * @return bool */ private function processContribution(&$params) { $dates = array('receive_date', 'receipt_date', 'thankyou_date', 'cancel_date'); // get the price set associated with offline contribution record. $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name'); $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId)); $priceFieldID = CRM_Price_BAO_PriceSet::getOnlyPriceFieldID($this->_priceSet); $priceFieldValueID = CRM_Price_BAO_PriceSet::getOnlyPriceFieldValueID($this->_priceSet); if (isset($params['field'])) { foreach ($params['field'] as $key => $value) { // if contact is not selected we should skip the row if (empty($params['primary_contact_id'][$key])) { continue; } $value['contact_id'] = CRM_Utils_Array::value($key, $params['primary_contact_id']); // update contact information $this->updateContactInfo($value); //build soft credit params if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) { $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key]; $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]); //CRM-15350: if soft-credit-type profile field is disabled or removed then //we choose configured SCT default value if (!empty($params['soft_credit_type'][$key])) { $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key]; } else { $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_OptionGroup::getDefaultValue("soft_credit_type"); } } // Build PCP params if (!empty($params['pcp_made_through_id'][$key])) { $value['pcp']['pcp_made_through_id'] = $params['pcp_made_through_id'][$key]; $value['pcp']['pcp_display_in_roll'] = !empty($params['pcp_display_in_roll'][$key]); if (!empty($params['pcp_roll_nickname'][$key])) { $value['pcp']['pcp_roll_nickname'] = $params['pcp_roll_nickname'][$key]; } if (!empty($params['pcp_personal_note'][$key])) { $value['pcp']['pcp_personal_note'] = $params['pcp_personal_note'][$key]; } } $value['custom'] = CRM_Core_BAO_CustomField::postProcess($value, NULL, 'Contribution'); foreach ($dates as $val) { if (!empty($value[$val])) { $value[$val] = CRM_Utils_Date::processDate($value[$val], $value[$val . '_time'], TRUE); } } if (!empty($value['send_receipt'])) { $value['receipt_date'] = date('Y-m-d His'); } // these translations & date handling are required because we are calling BAO directly rather than the api $fieldTranslations = array('financial_type' => 'financial_type_id', 'payment_instrument' => 'payment_instrument_id', 'contribution_source' => 'source', 'contribution_note' => 'note'); foreach ($fieldTranslations as $formField => $baoField) { if (isset($value[$formField])) { $value[$baoField] = $value[$formField]; } unset($value[$formField]); } $params['actualBatchTotal'] += $value['total_amount']; $value['batch_id'] = $this->_batchId; $value['skipRecentView'] = TRUE; // build line item params $this->_priceSet['fields'][$priceFieldID]['options'][$priceFieldValueID]['amount'] = $value['total_amount']; $value['price_' . $priceFieldID] = 1; $lineItem = array(); CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $value, $lineItem[$priceSetId]); // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel // function to get correct amount level consistently. Remove setting of the amount level in // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest // to cover all variants. unset($value['amount_level']); //CRM-11529 for back office transactions //when financial_type_id is passed in form, update the //line items with the financial type selected in form // @todo - create a price set or price field per financial type & simply choose the appropriate // price field rather than working around the fact that each price_field is supposed to have a financial // type & we are allowing that to be overridden. if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) { foreach ($lineItem[$priceSetId] as &$values) { $values['financial_type_id'] = $value['financial_type_id']; } } $value['line_item'] = $lineItem; //finally call contribution create for all the magic $contribution = CRM_Contribute_BAO_Contribution::create($value, CRM_Core_DAO::$_nullArray); $batchTypes = CRM_Core_Pseudoconstant::get('CRM_Batch_DAO_Batch', 'type_id', array('flip' => 1), 'validate'); if (!empty($this->_batchInfo['type_id']) && $this->_batchInfo['type_id'] == $batchTypes['Pledge Payment']) { $adjustTotalAmount = FALSE; if (isset($params['option_type'][$key])) { if ($params['option_type'][$key] == 2) { $adjustTotalAmount = TRUE; } } $pledgeId = $params['open_pledges'][$key]; if (is_numeric($pledgeId)) { $result = CRM_Pledge_BAO_PledgePayment::getPledgePayments($pledgeId); $pledgePaymentId = 0; foreach ($result as $key => $values) { if ($values['status'] != 'Completed') { $pledgePaymentId = $values['id']; break; } } CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentId, 'contribution_id', $contribution->id); CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, array($pledgePaymentId), $contribution->contribution_status_id, NULL, $contribution->total_amount, $adjustTotalAmount); } } //process premiums if (!empty($value['product_name'])) { if ($value['product_name'][0] > 0) { list($products, $options) = CRM_Contribute_BAO_Premium::getPremiumProductInfo(); $value['hidden_Premium'] = 1; $value['product_option'] = CRM_Utils_Array::value($value['product_name'][1], $options[$value['product_name'][0]]); $premiumParams = array('product_id' => $value['product_name'][0], 'contribution_id' => $contribution->id, 'product_option' => $value['product_option'], 'quantity' => 1); CRM_Contribute_BAO_Contribution::addPremium($premiumParams); } } // end of premium //send receipt mail. if ($contribution->id && !empty($value['send_receipt'])) { // add the domain email id $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail(); $domainEmail = "{$domainEmail['0']} <{$domainEmail['1']}>"; $value['from_email_address'] = $domainEmail; $value['contribution_id'] = $contribution->id; if (!empty($value['soft_credit'])) { $value = array_merge($value, CRM_Contribute_BAO_ContributionSoft::getSoftContribution($contribution->id)); } CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $value); } } } return TRUE; }