/** * Add or update a plege payment. Pledge Payment API doesn't actually add a pledge * if the request is to 'create' and 'id' is not passed in * the oldest pledge with no associated contribution is updated * * @todo possibly add ability to add payment if there are less payments than pledge installments * @todo possibily add ability to recalc dates if the schedule is changed * * @param array $params input parameters * {@getfields PledgePayment_create} * @example PledgePaymentCreate.php * * @return array API Result * @static void * @access public */ function civicrm_api3_pledge_payment_create($params) { $paymentParams = $params; if (empty($params['id']) && !CRM_Utils_Array::value('option.create_new', $params)) { $paymentDetails = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($params['pledge_id']); if (empty($paymentDetails)) { return civicrm_api3_create_error("There are no unmatched payment on this pledge. Pass in the pledge_payment id to specify one or 'option.create_new' to create one"); } elseif (is_array($paymentDetails)) { $paymentParams = array_merge($params, $paymentDetails); } } $dao = CRM_Pledge_BAO_PledgePayment::add($paymentParams); _civicrm_api3_object_to_array($dao, $result[$dao->id]); //update pledge status CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($params['pledge_id']); return civicrm_api3_create_success($result, $params, 'pledge_payment', 'create', $dao); }
/** * Update related pledge payment payments. * * This function has been refactored out of the back office contribution form and may * still overlap with other functions. * * @param string $action * @param int $pledgePaymentID * @param int $contributionID * @param bool $adjustTotalAmount * @param float $total_amount * @param float $original_total_amount * @param int $contribution_status_id * @param int $original_contribution_status_id */ public static function updateRelatedPledge($action, $pledgePaymentID, $contributionID, $adjustTotalAmount, $total_amount, $original_total_amount, $contribution_status_id, $original_contribution_status_id) { if (!$pledgePaymentID || $action & CRM_Core_Action::ADD && !$contributionID) { return; } if ($pledgePaymentID) { //store contribution id in payment record. CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID); } else { $pledgePaymentID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $contributionID, 'id', 'contribution_id'); } $pledgeID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $contributionID, 'pledge_id', 'contribution_id'); $updatePledgePaymentStatus = FALSE; // If either the status or the amount has changed we update the pledge status. if ($action & CRM_Core_Action::ADD) { $updatePledgePaymentStatus = TRUE; } elseif ($action & CRM_Core_Action::UPDATE && ($original_contribution_status_id != $contribution_status_id || $original_total_amount != $total_amount)) { $updatePledgePaymentStatus = TRUE; } if ($updatePledgePaymentStatus) { CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, array($pledgePaymentID), $contribution_status_id, NULL, $total_amount, $adjustTotalAmount); } }
/** * 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 contribution records. * * @param array $params * Associated array of submitted values. * * * @return void */ 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"); } } $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]); //unset amount level since we always use quick config price set 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 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; CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $value); } } } return TRUE; }
/** * Process the contribution * * @param $form * @param $params * @param $result * @param $contactID * @param $contributionType * @param bool $deductibleMode * @param bool $pending * @param bool $online * * @return CRM_Contribute_DAO_Contribution * @access public */ static function processContribution(&$form, $params, $result, $contactID, $contributionType, $deductibleMode = TRUE, $pending = FALSE, $online = TRUE) { $transaction = new CRM_Core_Transaction(); $className = get_class($form); $recurringContributionID = NULL; // add these values for the recurringContrib function ,CRM-10188 $params['financial_type_id'] = $contributionType->id; //@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'])) { $params['is_email_receipt'] = CRM_Utils_Array::value('is_email_receipt', $form->_values); } $recurringContributionID = self::processRecurringContribution($form, $params, $contactID, $contributionType, $online); $config = CRM_Core_Config::singleton(); // CRM-11885 // if non_deductible_amount exists i.e. Additional Details fieldset was opened [and staff typed something] -> keep it. if (isset($params['non_deductible_amount']) && !empty($params['non_deductible_amount'])) { $nonDeductibleAmount = $params['non_deductible_amount']; } else { //if ($contributionType->is_deductible && $deductibleMode) { if ($contributionType->is_deductible) { if ($online && isset($params['selectProduct'])) { $selectProduct = CRM_Utils_Array::value('selectProduct', $params); } if (!$online && isset($params['product_name'][0])) { $selectProduct = $params['product_name'][0]; } // if there is a product - compare the value to the contribution amount if (isset($selectProduct) && $selectProduct != 'no_thanks') { $productDAO = new CRM_Contribute_DAO_Product(); $productDAO->id = $selectProduct; $productDAO->find(TRUE); // product value exceeds contribution amount if ($params['amount'] < $productDAO->price) { $nonDeductibleAmount = $params['amount']; } else { $nonDeductibleAmount = $productDAO->price; } } else { $nonDeductibleAmount = '0.00'; } } else { $nonDeductibleAmount = $params['amount']; } } $now = date('YmdHis'); $receiptDate = CRM_Utils_Array::value('receipt_date', $params); if (!empty($form->_values['is_email_receipt'])) { $receiptDate = $now; } //get the contrib page id. $campaignId = $contributionPageId = NULL; if ($online) { $contributionPageId = $form->_id; $campaignId = CRM_Utils_Array::value('campaign_id', $params); if (!array_key_exists('campaign_id', $params)) { $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values); } } else { //also for offline we do support - CRM-7290 $contributionPageId = CRM_Utils_Array::value('contribution_page_id', $params); $campaignId = CRM_Utils_Array::value('campaign_id', $params); } // first create the contribution record $contribParams = array('contact_id' => $contactID, 'financial_type_id' => $contributionType->id, 'contribution_page_id' => $contributionPageId, 'receive_date' => CRM_Utils_Array::value('receive_date', $params) ? CRM_Utils_Date::processDate($params['receive_date']) : date('YmdHis'), 'non_deductible_amount' => $nonDeductibleAmount, 'total_amount' => $params['amount'], 'amount_level' => CRM_Utils_Array::value('amount_level', $params), 'invoice_id' => $params['invoiceID'], 'currency' => $params['currencyID'], 'source' => !$online || !empty($params['source']) ? CRM_Utils_Array::value('source', $params) : CRM_Utils_Array::value('description', $params), 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0), 'cancel_reason' => CRM_Utils_Array::value('cancel_reason', $params, 0), 'cancel_date' => isset($params['cancel_date']) ? CRM_Utils_Date::format($params['cancel_date']) : NULL, 'thankyou_date' => isset($params['thankyou_date']) ? CRM_Utils_Date::format($params['thankyou_date']) : NULL, 'campaign_id' => $campaignId); if (!$online && isset($params['thankyou_date'])) { $contribParams['thankyou_date'] = $params['thankyou_date']; } if (!$online || $form->_values['is_monetary']) { 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, 'trxn_result_code' => CRM_Utils_Array::value('trxn_result_code', $result), 'payment_processor' => CRM_Utils_Array::value('payment_processor', $result)); } if ($recurringContributionID) { $contribParams['contribution_recur_id'] = $recurringContributionID; } $contribParams['contribution_status_id'] = $pending ? 2 : 1; $contribParams['is_test'] = 0; if ($form->_mode == 'test') { $contribParams['is_test'] = 1; } $ids = array(); if (isset($contribParams['invoice_id'])) { $contribID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contribParams['invoice_id'], 'id', 'invoice_id'); if (isset($contribID)) { $ids['contribution'] = $contribID; $contribParams['id'] = $contribID; } } //create an contribution address if ($form->_contributeMode != 'notify' && empty($params['is_pay_later']) && !empty($form->_values['is_monetary'])) { $contribParams['address_id'] = CRM_Contribute_BAO_Contribution::createAddress($params, $form->_bltID); } // CRM-4038: for non-en_US locales, CRM_Contribute_BAO_Contribution::add() expects localised amounts $contribParams['non_deductible_amount'] = trim(CRM_Utils_Money::format($contribParams['non_deductible_amount'], ' ')); $contribParams['total_amount'] = trim(CRM_Utils_Money::format($contribParams['total_amount'], ' ')); // Prepare soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin. if (!empty($params['pcp_made_through_id']) || !empty($params['soft_credit_to'])) { // if its due to pcp if (!empty($params['pcp_made_through_id'])) { $contribSoftContactId = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $params['pcp_made_through_id'], 'contact_id'); } else { $contribSoftContactId = CRM_Utils_Array::value('soft_credit_to', $params); } // Pass these details onto with the contribution to make them // available at hook_post_process, CRM-8908 $contribParams['soft_credit_to'] = $params['soft_credit_to'] = $contribSoftContactId; } if (isset($params['amount'])) { $contribParams['line_item'] = $form->_lineItem; //add contribution record $contribution = CRM_Contribute_BAO_Contribution::add($contribParams, $ids); 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; } //CRM-13981, processing honor contact into soft-credit contribution CRM_Contact_Form_ProfileContact::postProcess($form); // process soft credit / pcp pages CRM_Contribute_Form_Contribution_Confirm::processPcpSoft($params, $contribution); //handle pledge stuff. if (empty($form->_params['separate_membership_payment']) && !empty($form->_values['pledge_block_id']) && (!empty($form->_params['is_pledge']) || !empty($form->_values['pledge_id']))) { if (!empty($form->_values['pledge_id'])) { //when user doing pledge payments. //update the schedule when payment(s) are made foreach ($form->_params['pledge_amount'] as $paymentId => $dontCare) { $scheduledAmount = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $paymentId, 'scheduled_amount', 'id'); $pledgePaymentParams = array('id' => $paymentId, 'contribution_id' => $contribution->id, 'status_id' => $contribution->contribution_status_id, 'actual_amount' => $scheduledAmount); CRM_Pledge_BAO_PledgePayment::add($pledgePaymentParams); } //update pledge status according to the new payment statuses CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($form->_values['pledge_id']); } 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'] = $campaignId; $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($form->_params, CRM_Core_DAO::$_nullArray, '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-' . $form->_bltID); return $contribution; }
/** * Process the form submission. * * * @return void */ public function postProcess() { //get the submitted form values. $formValues = $this->controller->exportValues($this->_name); $params = array(); $formValues['scheduled_date'] = CRM_Utils_Date::processDate($formValues['scheduled_date']); $params['scheduled_date'] = CRM_Utils_Date::format($formValues['scheduled_date']); $params['currency'] = CRM_Utils_Array::value('currency', $formValues); $now = date('Ymd'); $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); if (CRM_Utils_Date::overdue(CRM_Utils_Date::customFormat($params['scheduled_date'], '%Y%m%d'), $now)) { $params['status_id'] = array_search('Overdue', $contributionStatus); } else { $params['status_id'] = array_search('Pending', $contributionStatus); } $params['id'] = $this->_id; $pledgeId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $params['id'], 'pledge_id'); CRM_Pledge_BAO_PledgePayment::add($params); $adjustTotalAmount = FALSE; if (CRM_Utils_Array::value('option_type', $formValues) == 2) { $adjustTotalAmount = TRUE; } $pledgeScheduledAmount = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $params['id'], 'scheduled_amount', 'id'); $oldestPaymentAmount = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId, 2); if ($oldestPaymentAmount['count'] != 1 && $oldestPaymentAmount['id'] == $params['id']) { $oldestPaymentAmount = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId); } if ($formValues['scheduled_amount'] - $pledgeScheduledAmount >= $oldestPaymentAmount['amount']) { $adjustTotalAmount = TRUE; } //update pledge status CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, array($params['id']), $params['status_id'], NULL, $formValues['scheduled_amount'], $adjustTotalAmount); $statusMsg = ts('Pledge Payment Schedule has been updated.'); CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success'); }
/** * Process pledge payments. * * @param array $formatted * * @return int */ public function processPledgePayments(&$formatted) { if (!empty($formatted['pledge_payment_id']) && !empty($formatted['pledge_id'])) { //get completed status $completeStatusID = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name'); //need to update payment record to map contribution_id CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $formatted['pledge_payment_id'], 'contribution_id', $formatted['contribution_id']); CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($formatted['pledge_id'], array($formatted['pledge_payment_id']), $completeStatusID, NULL, $formatted['total_amount']); return CRM_Contribute_Import_Parser::PLEDGE_PAYMENT; } }
/** * Function to process the form * * @access public * * @return None */ public function postProcess() { $session = CRM_Core_Session::singleton(); if ($this->_action & CRM_Core_Action::DELETE) { CRM_Contribute_BAO_Contribution::deleteContribution($this->_id); $session->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 (CRM_Utils_Array::value('price_set_id', $submittedValues) && $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_Field', CRM_Utils_Array::value('price_field_id', $line[$lineID]), 'price_set_id'); $quickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Set', $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 = $pId = NULL; $priceSetId = CRM_Utils_Array::value('price_set_id', $submittedValues); if (empty($priceSetId) && !$this->_id) { $this->_priceSetId = $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Set', 'default_contribution_amount', 'id', 'name'); $this->_priceSet = current(CRM_Price_BAO_Set::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_Set::processAmount($this->_priceSet['fields'], $submittedValues, $lineItem[$priceSetId]); $submittedValues['total_amount'] = CRM_Utils_Array::value('amount', $submittedValues); } if (!$priceSetId && CRM_Utils_Array::value('total_amount', $submittedValues) && $this->_id) { // 10117 update th line items for participants $pId = $this->_compId && $this->_context == 'participant' ? $this->_compId : CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'participant_id', 'contribution_id'); //CRM-10964 if ($pId) { $entityTable = 'participant'; $entityID = $pId; $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); $itemId = key($lineItems); $fieldType = NULL; if ($itemId && CRM_Utils_Array::value('price_field_id', $lineItems[$itemId])) { $fieldType = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Field', $lineItems[$itemId]['price_field_id'], 'html_type'); } $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value('total_amount', $submittedValues)); $lineItems[$itemId]['id'] = $itemId; // 10117 update th line items for participants $this->_priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Field', $lineItems[$itemId]['price_field_id'], 'price_set_id'); $lineItem[$this->_priceSetId] = $lineItems; } $isQuickConfig = 0; if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Set', $this->_priceSetId, 'is_quick_config')) { $isQuickConfig = 1; } if (!CRM_Utils_Array::value('total_amount', $submittedValues)) { $submittedValues['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_values); } $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE); if (CRM_Utils_Array::value('soft_credit_to', $submittedValues)) { $submittedValues['soft_credit_to'] = $submittedValues['soft_contact_id']; } // set the contact, when contact is selected if (CRM_Utils_Array::value('contact_select_id', $submittedValues)) { $this->_contactID = $submittedValues['contact_select_id'][1]; } $config = CRM_Core_Config::singleton(); //Credit Card Contribution. if ($this->_mode) { $unsetParams = array('trxn_id', 'payment_instrument_id', 'contribution_status_id', 'cancel_date', 'cancel_reason'); foreach ($unsetParams as $key) { if (isset($submittedValues[$key])) { unset($submittedValues[$key]); } } //Get the rquire fields value only. $params = $this->_params = $submittedValues; $this->_paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode); //get the payment processor id as per mode. $params['payment_processor_id'] = $this->_params['payment_processor_id'] = $submittedValues['payment_processor_id'] = $this->_paymentProcessor['id']; $now = date('YmdHis'); $fields = array(); // we need to retrieve email address if ($this->_context == 'standalone' && CRM_Utils_Array::value('is_email_receipt', $submittedValues)) { list($this->userDisplayName, $this->userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID); $this->assign('displayName', $this->userDisplayName); } //set email for primary location. $fields['email-Primary'] = 1; $params['email-Primary'] = $this->userEmail; // now set the values for the billing location. foreach ($this->_fields as $name => $dontCare) { $fields[$name] = 1; } // also add location name to the array $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params); $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]); $fields["address_name-{$this->_bltID}"] = 1; $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type'); $nameFields = array('first_name', 'middle_name', 'last_name'); foreach ($nameFields as $name) { $fields[$name] = 1; if (array_key_exists("billing_{$name}", $params)) { $params[$name] = $params["billing_{$name}"]; $params['preserveDBName'] = TRUE; } } if (CRM_Utils_Array::value('source', $params)) { unset($params['source']); } $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactID, NULL, NULL, $ctype); // add all the additioanl payment params we need $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]); $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]); if ($this->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_CREDIT_CARD) { $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'] = $this->_params['total_amount']; $this->_params['amount_level'] = 0; $this->_params['currencyID'] = CRM_Utils_Array::value('currency', $this->_params, $config->defaultCurrency); $this->_params['payment_action'] = 'Sale'; if (CRM_Utils_Array::value('receive_date', $this->_params)) { $this->_params['receive_date'] = CRM_Utils_Date::processDate($this->_params['receive_date'], $this->_params['receive_date_time']); } if (CRM_Utils_Array::value('soft_credit_to', $params)) { $this->_params['soft_credit_to'] = $params['soft_credit_to']; $this->_params['pcp_made_through_id'] = $params['pcp_made_through_id']; } $this->_params['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $params); $this->_params['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $params); $this->_params['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $params); //Add common data to formatted params CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params); if (empty($this->_params['invoice_id'])) { $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE)); } else { $this->_params['invoiceID'] = $this->_params['invoice_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->_contactID; CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE); $contributionType = new CRM_Contribute_DAO_ContributionType(); $contributionType->id = $params['contribution_type_id']; if (!$contributionType->find(TRUE)) { CRM_Core_Error::fatal('Could not find a system table'); } // add some contribution type details to the params list // if folks need to use it $paymentParams['contributionType_name'] = $this->_params['contributionType_name'] = $contributionType->name; $paymentParams['contributionType_accounting_code'] = $this->_params['contributionType_accounting_code'] = $contributionType->accounting_code; $paymentParams['contributionPageID'] = NULL; if (CRM_Utils_Array::value('is_email_receipt', $this->_params)) { $paymentParams['email'] = $this->userEmail; $paymentParams['is_email_receipt'] = 1; } else { $paymentParams['is_email_receipt'] = 0; $this->_params['is_email_receipt'] = 0; } if (CRM_Utils_Array::value('receive_date', $this->_params)) { $paymentParams['receive_date'] = $this->_params['receive_date']; } if (CRM_Utils_Array::value('receive_date', $this->_params)) { $paymentParams['receive_date'] = $this->_params['receive_date']; } $result = NULL; // For recurring contribution, create Contribution Record first. // Contribution ID, Recurring ID and Contact ID needed // When we get a callback from the payment processor, CRM-7115 if (CRM_Utils_Array::value('is_recur', $paymentParams)) { $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this, $this->_params, $result, $this->_contactID, $contributionType, FALSE, TRUE, FALSE); $paymentParams['contributionID'] = $contribution->id; $paymentParams['contributionTypeID'] = $contribution->contribution_type_id; $paymentParams['contributionPageID'] = $contribution->contribution_page_id; $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id; } if ($paymentParams['amount'] > 0.0) { // force a reget of the payment processor in case the form changed it, CRM-7179 $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this, TRUE); $result = $payment->doDirectPayment($paymentParams); } if (is_a($result, 'CRM_Core_Error')) { //make sure to cleanup db for recurring case. if (CRM_Utils_Array::value('contributionID', $paymentParams)) { CRM_Core_Error::debug_log_message(CRM_Core_Error::getMessages($result) . "contact id={$this->_contactID} (deleting contribution {$paymentParams['contributionID']}"); CRM_Contribute_BAO_Contribution::deleteContribution($paymentParams['contributionID']); } if (CRM_Utils_Array::value('contributionRecurID', $paymentParams)) { CRM_Core_Error::debug_log_message(CRM_Core_Error::getMessages($result) . "contact id={$this->_contactID} (deleting recurring contribution {$paymentParams['contributionRecurID']}"); CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']); } //set the contribution mode. $urlParams = "action=add&cid={$this->_contactID}"; if ($this->_mode) { $urlParams .= "&mode={$this->_mode}"; } if (!empty($this->_ppID)) { $urlParams .= "&context=pledge&ppid={$this->_ppID}"; } CRM_Core_Error::displaySessionError($result); CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/contribution', $urlParams)); } if ($result) { $this->_params = array_merge($this->_params, $result); } $this->_params['receive_date'] = $now; if (CRM_Utils_Array::value('is_email_receipt', $this->_params)) { $this->_params['receipt_date'] = $now; } else { $this->_params['receipt_date'] = CRM_Utils_Date::processDate($this->_params['receipt_date'], $params['receipt_date_time'], TRUE); } $this->set('params', $this->_params); $this->assign('trxn_id', $result['trxn_id']); $this->assign('receive_date', $this->_params['receive_date']); // result has all the stuff we need // lets archive it to a financial transaction if ($contributionType->is_deductible) { $this->assign('is_deductible', TRUE); $this->set('is_deductible', TRUE); } // set source if not set if (empty($this->_params['source'])) { $userID = $session->get('userID'); $userSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $userID, 'sort_name'); $this->_params['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName)); } // build custom data getFields array $customFieldsContributionType = CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE, CRM_Utils_Array::value('contribution_type_id', $params)); $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsContributionType, CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE, NULL, NULL, TRUE)); $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_id, 'Contribution'); if (!CRM_Utils_Array::value('is_recur', $paymentParams)) { $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this, $this->_params, $result, $this->_contactID, $contributionType, FALSE, FALSE, FALSE); } if ($this->_context != 'participant' && !$pId) { $entityID = $contribution->id; $entityTable = 'contribution'; } // process line items, until no previous line items. if (empty($this->_lineItems) && $entityID && !empty($lineItem)) { CRM_Contribute_Form_AdditionalInfo::processPriceSet($entityID, $lineItem, 'civicrm_' . $entityTable); } //send receipt mail. if ($contribution->id && CRM_Utils_Array::value('is_email_receipt', $this->_params)) { $this->_params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result); $this->_params['contact_id'] = $this->_contactID; $this->_params['contribution_id'] = $contribution->id; $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $this->_params, TRUE); } //process the note if ($contribution->id && isset($params['note'])) { CRM_Contribute_Form_AdditionalInfo::processNote($params, $contactID, $contribution->id, NULL); } //process premium if ($contribution->id && isset($params['product_name'][0])) { CRM_Contribute_Form_AdditionalInfo::processPremium($params, $contribution->id, NULL, $this->_options); } //update pledge payment status. if ($this->_ppID && $contribution->id) { //store contribution id in payment record. CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID, 'contribution_id', $contribution->id); CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($this->_pledgeID, array($this->_ppID), $contribution->contribution_status_id, NULL, $contribution->total_amount); } if ($contribution->id) { $statusMsg = ts('The contribution record has been processed.'); if (CRM_Utils_Array::value('is_email_receipt', $this->_params) && $sendReceipt) { $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.'); } CRM_Core_Session::setStatus($statusMsg); } //submit credit card contribution ends. } else { //Offline Contribution. $unsetParams = array('payment_processor_id', "email-{$this->_bltID}", 'hidden_buildCreditCard', 'hidden_buildDirectDebit', 'billing_first_name', 'billing_middle_name', 'billing_last_name', 'street_address-5', "city-{$this->_bltID}", "state_province_id-{$this->_bltID}", "postal_code-{$this->_bltID}", "country_id-{$this->_bltID}", 'credit_card_number', 'cvv2', 'credit_card_exp_date', 'credit_card_type'); foreach ($unsetParams as $key) { if (isset($submittedValues[$key])) { unset($submittedValues[$key]); } } // get the required field value only. $formValues = $submittedValues; $params = $ids = array(); $params['contact_id'] = $this->_contactID; // get current currency from DB or use default currency $currentCurrency = CRM_Utils_Array::value('currency', $this->_values, $config->defaultCurrency); // use submitted currency if present else use current currency $params['currency'] = CRM_Utils_Array::value('currency', $submittedValues, $currentCurrency); $fields = array('contribution_type_id', 'contribution_status_id', 'payment_instrument_id', 'cancel_reason', 'source', 'check_number', 'soft_credit_to', 'pcp_made_through_id', 'pcp_display_in_roll', 'pcp_roll_nickname', 'pcp_personal_note'); foreach ($fields as $f) { $params[$f] = CRM_Utils_Array::value($f, $formValues); } if ($softID = CRM_Utils_Array::value('softID', $this->_values)) { $params['softID'] = $softID; } //if priceset is used, no need to cleanup money //CRM-5740 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 (CRM_Utils_Array::value('is_email_receipt', $formValues)) { $params['receipt_date'] = date("Y-m-d"); } if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Cancelled', '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 if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) { $params['is_pay_later'] = 1; } $ids['contribution'] = $params['id'] = $this->_id; //Add Additional common information to formatted params CRM_Contribute_Form_AdditionalInfo::postProcessCommon($formValues, $params); //create contribution. $contribution = CRM_Contribute_BAO_Contribution::create($params, $ids); // 10117 update th line items for participants if ($this->_context != 'participant' && !$pId) { $entityID = $contribution->id; $entityTable = 'contribution'; } // process line items, until no previous line items. if (empty($this->_lineItems) && $entityID && !empty($lineItem)) { CRM_Contribute_Form_AdditionalInfo::processPriceSet($entityID, $lineItem, 'civicrm_' . $entityTable); } // 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)); } //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); } //send receipt mail. if ($contribution->id && CRM_Utils_Array::value('is_email_receipt', $formValues)) { $formValues['contact_id'] = $this->_contactID; $formValues['contribution_id'] = $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; } 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 (CRM_Utils_Array::value('is_email_receipt', $formValues) && $sendReceipt) { $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.'); } if ($relatedComponentStatusMsg) { $statusMsg .= ' ' . $relatedComponentStatusMsg; } CRM_Core_Session::setStatus($statusMsg, FALSE); //Offline Contribution ends. } $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}")); } }
/** * This function update contribution as well as related objects. */ static function transitionComponents($params, $processContributionObject = FALSE) { // get minimum required values. $contactId = CRM_Utils_Array::value('contact_id', $params); $componentId = CRM_Utils_Array::value('component_id', $params); $componentName = CRM_Utils_Array::value('componentName', $params); $contributionId = CRM_Utils_Array::value('contribution_id', $params); $contributionStatusId = CRM_Utils_Array::value('contribution_status_id', $params); // if we already processed contribution object pass previous status id. $previousContriStatusId = CRM_Utils_Array::value('previous_contribution_status_id', $params); $updateResult = array(); $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); // we process only ( Completed, Cancelled, or Failed ) contributions. if (!$contributionId || !in_array($contributionStatusId, array(array_search('Completed', $contributionStatuses), array_search('Cancelled', $contributionStatuses), array_search('Failed', $contributionStatuses)))) { return $updateResult; } if (!$componentName || !$componentId) { // get the related component details. $componentDetails = self::getComponentDetails($contributionId); } else { $componentDetails['contact_id'] = $contactId; $componentDetails['component'] = $componentName; if ($componentName == 'event') { $componentDetails['participant'] = $componentId; } else { $componentDetails['membership'] = $componentId; } } if (CRM_Utils_Array::value('contact_id', $componentDetails)) { $componentDetails['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'contact_id'); } // do check for required ids. if (!CRM_Utils_Array::value('membership', $componentDetails) && !CRM_Utils_Array::value('participant', $componentDetails) && !CRM_Utils_Array::value('pledge_payment', $componentDetails) || !CRM_Utils_Array::value('contact_id', $componentDetails)) { return $updateResult; } //now we are ready w/ required ids, start processing. $baseIPN = new CRM_Core_Payment_BaseIPN(); $input = $ids = $objects = array(); $input['component'] = CRM_Utils_Array::value('component', $componentDetails); $ids['contribution'] = $contributionId; $ids['contact'] = CRM_Utils_Array::value('contact_id', $componentDetails); $ids['membership'] = CRM_Utils_Array::value('membership', $componentDetails); $ids['participant'] = CRM_Utils_Array::value('participant', $componentDetails); $ids['event'] = CRM_Utils_Array::value('event', $componentDetails); $ids['pledge_payment'] = CRM_Utils_Array::value('pledge_payment', $componentDetails); $ids['contributionRecur'] = NULL; $ids['contributionPage'] = NULL; if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) { CRM_Core_Error::fatal(); } $memberships =& $objects['membership']; $participant =& $objects['participant']; $pledgePayment =& $objects['pledge_payment']; $contribution =& $objects['contribution']; if ($pledgePayment) { $pledgePaymentIDs = array(); foreach ($pledgePayment as $key => $object) { $pledgePaymentIDs[] = $object->id; } $pledgeID = $pledgePayment[0]->pledge_id; } $membershipStatuses = CRM_Member_PseudoConstant::membershipStatus(); if ($participant) { $participantStatuses = CRM_Event_PseudoConstant::participantStatus(); $oldStatus = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $participant->id, 'status_id'); } // we might want to process contribution object. $processContribution = FALSE; if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) { if (is_array($memberships)) { foreach ($memberships as $membership) { if ($membership) { $membership->status_id = array_search('Cancelled', $membershipStatuses); $membership->save(); $updateResult['updatedComponents']['CiviMember'] = $membership->status_id; if ($processContributionObject) { $processContribution = TRUE; } } } } if ($participant) { $updatedStatusId = array_search('Cancelled', $participantStatuses); CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE); $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId; if ($processContributionObject) { $processContribution = TRUE; } } if ($pledgePayment) { CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId); $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId; if ($processContributionObject) { $processContribution = TRUE; } } } elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) { if (is_array($memberships)) { foreach ($memberships as $membership) { if ($membership) { $membership->status_id = array_search('Expired', $membershipStatuses); $membership->save(); $updateResult['updatedComponents']['CiviMember'] = $membership->status_id; if ($processContributionObject) { $processContribution = TRUE; } } } } if ($participant) { $updatedStatusId = array_search('Cancelled', $participantStatuses); CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE); $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId; if ($processContributionObject) { $processContribution = TRUE; } } if ($pledgePayment) { CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId); $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId; if ($processContributionObject) { $processContribution = TRUE; } } } elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) { // only pending contribution related object processed. if ($previousContriStatusId && $previousContriStatusId != array_search('Pending', $contributionStatuses)) { // this is case when we already processed contribution object. return $updateResult; } elseif (!$previousContriStatusId && $contribution->contribution_status_id != array_search('Pending', $contributionStatuses)) { // this is case when we are going to process contribution object later. return $updateResult; } if (is_array($memberships)) { foreach ($memberships as $membership) { if ($membership) { $format = '%Y%m%d'; //CRM-4523 $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id, $membership->membership_type_id, $membership->is_test, $membership->id); // CRM-8141 update the membership type with the value recorded in log when membership created/renewed // this picks up membership type changes during renewals $sql = "\n SELECT membership_type_id\n FROM civicrm_membership_log\n WHERE membership_id={$membership->id}\n ORDER BY id DESC\n LIMIT 1;"; $dao = new CRM_Core_DAO(); $dao->query($sql); if ($dao->fetch()) { if (!empty($dao->membership_type_id)) { $membership->membership_type_id = $dao->membership_type_id; $membership->save(); } } // else fall back to using current membership type $dao->free(); // Figure out number of terms $numterms = 1; $lineitems = CRM_Price_BAO_LineItem::getLineItems($contributionId, 'contribution'); foreach ($lineitems as $lineitem) { if ($membership->membership_type_id == CRM_Utils_Array::value('membership_type_id', $lineitem)) { $numterms = CRM_Utils_Array::value('membership_num_terms', $lineitem); // in case membership_num_terms comes through as null or zero $numterms = $numterms >= 1 ? $numterms : 1; break; } } if ($currentMembership) { CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, NULL); $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, NULL, NULL, $numterms); $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format); } else { $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, NULL, NULL, NULL, $numterms); } //get the status for membership. $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], $dates['end_date'], $dates['join_date'], 'today', TRUE, $membership->membership_type_id, (array) $membership); $formattedParams = array('status_id' => CRM_Utils_Array::value('id', $calcStatus, array_search('Current', $membershipStatuses)), 'join_date' => CRM_Utils_Date::customFormat($dates['join_date'], $format), 'start_date' => CRM_Utils_Date::customFormat($dates['start_date'], $format), 'end_date' => CRM_Utils_Date::customFormat($dates['end_date'], $format)); CRM_Utils_Hook::pre('edit', 'Membership', $membership->id, $formattedParams); $membership->copyValues($formattedParams); $membership->save(); //updating the membership log $membershipLog = array(); $membershipLog = $formattedParams; $logStartDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('log_start_date', $dates), $format); $logStartDate = $logStartDate ? CRM_Utils_Date::isoToMysql($logStartDate) : $formattedParams['start_date']; $membershipLog['start_date'] = $logStartDate; $membershipLog['membership_id'] = $membership->id; $membershipLog['modified_id'] = $membership->contact_id; $membershipLog['modified_date'] = date('Ymd'); $membershipLog['membership_type_id'] = $membership->membership_type_id; CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray); //update related Memberships. CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formattedParams); $updateResult['membership_end_date'] = CRM_Utils_Date::customFormat($dates['end_date'], '%B %E%f, %Y'); $updateResult['updatedComponents']['CiviMember'] = $membership->status_id; if ($processContributionObject) { $processContribution = TRUE; } CRM_Utils_Hook::post('edit', 'Membership', $membership->id, $membership); } } } if ($participant) { $updatedStatusId = array_search('Registered', $participantStatuses); CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE); $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId; if ($processContributionObject) { $processContribution = TRUE; } } if ($pledgePayment) { CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId); $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId; if ($processContributionObject) { $processContribution = TRUE; } } } // process contribution object. if ($processContribution) { $contributionParams = array(); $fields = array('contact_id', 'total_amount', 'receive_date', 'is_test', 'campaign_id', 'payment_instrument_id', 'trxn_id', 'invoice_id', 'financial_type_id', 'contribution_status_id', 'non_deductible_amount', 'receipt_date', 'check_number'); foreach ($fields as $field) { if (!CRM_Utils_Array::value($field, $params)) { continue; } $contributionParams[$field] = $params[$field]; } $ids = array('contribution' => $contributionId); $contribution = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids); } return $updateResult; }
/** * Add or update a plege payment * * @param array $params (reference ) input parameters * * @return array (reference ) pledge_id of created or updated record * @static void * @access public */ function &civicrm_pledge_payment_create(&$params) { _civicrm_initialize(); //GAP - update doesn't recalculate payment dates on existing payment schedule - not the sure the code is in Civi to leverage if (empty($params)) { return civicrm_create_error(ts('No input parameters present')); } if (!is_array($params)) { return civicrm_create_error(ts('Input parameters is not an array')); } $error = _civicrm_pledgepayment_check_params($params); if (civicrm_error($error)) { return $error; } $values = array(); require_once 'CRM/Pledge/BAO/PledgePayment.php'; $error = _civicrm_pledgepayment_format_params($params, $values); if (civicrm_error($error)) { return $error; } $pledge = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($params['pledge_id']); $params['id'] = $pledge['id']; //params ID needs to be pledge payment ID // pledge payment isn't retrieved if only one exists - the status is not set correctly causing this so let's get it for now as a cludgey make it work // copied from getOldestPayment function if (!$params['id']) { $query = "\nSELECT civicrm_pledge_payment.id id, civicrm_pledge_payment.scheduled_amount amount\nFROM civicrm_pledge, civicrm_pledge_payment\nWHERE civicrm_pledge.id = civicrm_pledge_payment.pledge_id\n AND civicrm_pledge.id = %1\nLIMIT 0, 1 \n"; $params[1] = array($params['pledge_id'], 'Integer'); $payment = CRM_Core_DAO::executeQuery($query, $params); $paymentDetails = NULL; if ($payment->fetch()) { $params['id'] = $payment->id; } } CRM_Pledge_BAO_PledgePayment::add($params); //update pledge status CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($params['pledge_id']); return $errors; }
/** * Mark a pledge (and any outstanding payments) as cancelled. * * @param int $pledgeID */ public static function cancel($pledgeID) { $paymentIDs = self::findCancelablePayments($pledgeID); $status = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); $cancelled = array_search('Cancelled', $status); CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $paymentIDs, NULL, $cancelled, 0, FALSE, TRUE); }
public function updatePledgeStatus($sendReminders = FALSE) { // *** Uncomment the next line if you want automated reminders to be sent // $sendReminders = true; require_once 'CRM/Contribute/PseudoConstant.php'; $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); //unset statues that we never use for pledges foreach (array('Completed', 'Cancelled', 'Failed') as $statusKey) { if ($key = CRM_Utils_Array::key($statusKey, $allStatus)) { unset($allStatus[$key]); } } $statusIds = implode(',', array_keys($allStatus)); $updateCnt = 0; $query = "\nSELECT pledge.contact_id as contact_id,\n pledge.id as pledge_id,\n pledge.amount as amount,\n payment.scheduled_date as scheduled_date,\n pledge.create_date as create_date,\n payment.id as payment_id,\n pledge.contribution_page_id as contribution_page_id,\n payment.reminder_count as reminder_count,\n pledge.max_reminders as max_reminders,\n payment.reminder_date as reminder_date,\n pledge.initial_reminder_day as initial_reminder_day,\n pledge.additional_reminder_day as additional_reminder_day,\n pledge.status_id as pledge_status,\n payment.status_id as payment_status,\n pledge.is_test as is_test,\n pledge.campaign_id as campaign_id,\n SUM(payment.scheduled_amount) as amount_due,\n ( SELECT sum(civicrm_pledge_payment.actual_amount)\n FROM civicrm_pledge_payment\n WHERE civicrm_pledge_payment.status_id = 1\n AND civicrm_pledge_payment.pledge_id = pledge.id\n ) as amount_paid\n FROM civicrm_pledge pledge, civicrm_pledge_payment payment\n WHERE pledge.id = payment.pledge_id\n AND payment.status_id IN ( {$statusIds} ) AND pledge.status_id IN ( {$statusIds} )\n GROUP By payment.id\n "; $dao = CRM_Core_DAO::executeQuery($query); require_once 'CRM/Contact/BAO/Contact/Utils.php'; require_once 'CRM/Utils/Date.php'; $now = date('Ymd'); $pledgeDetails = $contactIds = $pledgePayments = $pledgeStatus = array(); while ($dao->fetch()) { $checksumValue = CRM_Contact_BAO_Contact_Utils::generateChecksum($dao->contact_id); $pledgeDetails[$dao->payment_id] = array('scheduled_date' => $dao->scheduled_date, 'amount_due' => $dao->amount_due, 'amount' => $dao->amount, 'amount_paid' => $dao->amount_paid, 'create_date' => $dao->create_date, 'contact_id' => $dao->contact_id, 'pledge_id' => $dao->pledge_id, 'checksumValue' => $checksumValue, 'contribution_page_id' => $dao->contribution_page_id, 'reminder_count' => $dao->reminder_count, 'max_reminders' => $dao->max_reminders, 'reminder_date' => $dao->reminder_date, 'initial_reminder_day' => $dao->initial_reminder_day, 'additional_reminder_day' => $dao->additional_reminder_day, 'pledge_status' => $dao->pledge_status, 'payment_status' => $dao->payment_status, 'is_test' => $dao->is_test, 'campaign_id' => $dao->campaign_id); $contactIds[$dao->contact_id] = $dao->contact_id; $pledgeStatus[$dao->pledge_id] = $dao->pledge_status; if (CRM_Utils_Date::overdue(CRM_Utils_Date::customFormat($dao->scheduled_date, '%Y%m%d'), $now) && $dao->payment_status != array_search('Overdue', $allStatus)) { $pledgePayments[$dao->pledge_id][$dao->payment_id] = $dao->payment_id; } } require_once 'CRM/Pledge/BAO/PledgePayment.php'; // process the updating script... foreach ($pledgePayments as $pledgeId => $paymentIds) { // 1. update the pledge /pledge payment status. returns new status when an update happens echo "<br />Checking if status update is needed for Pledge Id: {$pledgeId} (current status is {$allStatus[$pledgeStatus[$pledgeId]]})"; $newStatus = CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, $paymentIds, array_search('Overdue', $allStatus), NULL, 0, FALSE, TRUE); if ($newStatus != $pledgeStatus[$pledgeId]) { echo "<br />- status updated to: {$allStatus[$newStatus]}"; $updateCnt += 1; } } if ($sendReminders) { // retrieve domain tokens require_once 'CRM/Core/BAO/Domain.php'; require_once 'CRM/Core/SelectValues.php'; $domain = CRM_Core_BAO_Domain::getDomain(); $tokens = array('domain' => array('name', 'phone', 'address', 'email'), 'contact' => CRM_Core_SelectValues::contactTokens()); require_once 'CRM/Utils/Token.php'; $domainValues = array(); foreach ($tokens['domain'] as $token) { $domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain); } //get the domain email address, since we don't carry w/ object. require_once 'CRM/Core/BAO/Domain.php'; $domainValue = CRM_Core_BAO_Domain::getNameAndEmail(); $domainValues['email'] = $domainValue[1]; // retrieve contact tokens // this function does NOT return Deceased contacts since we don't want to send them email require_once 'CRM/Utils/Token.php'; list($contactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, NULL, FALSE, FALSE, NULL, $tokens, 'CRM_UpdatePledgeRecord'); // assign domain values to template $template = CRM_Core_Smarty::singleton(); $template->assign('domain', $domainValues); //set receipt from $receiptFrom = '"' . $domainValues['name'] . '" <' . $domainValues['email'] . '>'; foreach ($pledgeDetails as $paymentId => $details) { if (array_key_exists($details['contact_id'], $contactDetails)) { $contactId = $details['contact_id']; $pledgerName = $contactDetails[$contactId]['display_name']; } else { continue; } if (empty($details['reminder_date'])) { $nextReminderDate = new DateTime($details['scheduled_date']); $nextReminderDate->modify("-" . $details['initial_reminder_day'] . "day"); $nextReminderDate = $nextReminderDate->format("Ymd"); } else { $nextReminderDate = new DateTime($details['reminder_date']); $nextReminderDate->modify("+" . $details['additional_reminder_day'] . "day"); $nextReminderDate = $nextReminderDate->format("Ymd"); } if ($details['reminder_count'] < $details['max_reminders'] && $nextReminderDate <= $now) { $toEmail = $doNotEmail = $onHold = NULL; if (!empty($contactDetails[$contactId]['email'])) { $toEmail = $contactDetails[$contactId]['email']; } if (!empty($contactDetails[$contactId]['do_not_email'])) { $doNotEmail = $contactDetails[$contactId]['do_not_email']; } if (!empty($contactDetails[$contactId]['on_hold'])) { $onHold = $contactDetails[$contactId]['on_hold']; } // 2. send acknowledgement mail if ($toEmail && !($doNotEmail || $onHold)) { //assign value to template $template->assign('amount_paid', $details['amount_paid'] ? $details['amount_paid'] : 0); $template->assign('contact', $contactDetails[$contactId]); $template->assign('next_payment', $details['scheduled_date']); $template->assign('amount_due', $details['amount_due']); $template->assign('checksumValue', $details['checksumValue']); $template->assign('contribution_page_id', $details['contribution_page_id']); $template->assign('pledge_id', $details['pledge_id']); $template->assign('scheduled_payment_date', $details['scheduled_date']); $template->assign('amount', $details['amount']); $template->assign('create_date', $details['create_date']); require_once 'CRM/Core/BAO/MessageTemplate.php'; list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_pledge', 'valueName' => 'pledge_reminder', 'contactId' => $contactId, 'from' => $receiptFrom, 'toName' => $pledgerName, 'toEmail' => $toEmail)); // 3. update pledge payment details if ($mailSent) { CRM_Pledge_BAO_PledgePayment::updateReminderDetails($paymentId); $activityType = 'Pledge Reminder'; $activityParams = array('subject' => $subject, 'source_contact_id' => $contactId, 'source_record_id' => $paymentId, 'assignee_contact_id' => $contactId, 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type', $activityType, 'name'), 'activity_date_time' => CRM_Utils_Date::isoToMysql($now), 'due_date_time' => CRM_Utils_Date::isoToMysql($details['scheduled_date']), 'is_test' => $details['is_test'], 'status_id' => 2, 'campaign_id' => $details['campaign_id']); if (is_a(civicrm_api('activity', 'create', $activityParams), 'CRM_Core_Error')) { CRM_Core_Error::fatal("Failed creating Activity for acknowledgment"); } echo "<br />Payment reminder sent to: {$pledgerName} - {$toEmail}"; } } } } // end foreach on $pledgeDetails } // end if ( $sendReminders ) echo "<br />{$updateCnt} records updated."; }
/** * Process the contribution * * @return void * @access public */ static function processContribution(&$form, $params, $result, $contactID, $contributionType, $deductibleMode = TRUE, $pending = FALSE, $online = TRUE) { $transaction = new CRM_Core_Transaction(); $className = get_class($form); $honorCId = $recurringContributionID = NULL; if ($online && $form->get('honor_block_is_active')) { $honorCId = $form->createHonorContact(); } // add these values for the recurringContrib function ,CRM-10188 $params['contribution_type_id'] = $contributionType->id; $params['is_email_receipt'] = CRM_Utils_Array::value('is_email_receipt', $form->_values); $recurringContributionID = self::processRecurringContribution($form, $params, $contactID, $contributionType, $online); if (!$online && isset($params['honor_contact_id'])) { $honorCId = $params['honor_contact_id']; } $config = CRM_Core_Config::singleton(); if (!$online && isset($params['non_deductible_amount'])) { $nonDeductibleAmount = $params['non_deductible_amount']; } else { $nonDeductibleAmount = $params['amount']; } if ($online && $contributionType->is_deductible && $deductibleMode) { $selectProduct = CRM_Utils_Array::value('selectProduct', $params); if ($selectProduct && $selectProduct != 'no_thanks') { $productDAO = new CRM_Contribute_DAO_Product(); $productDAO->id = $selectProduct; $productDAO->find(TRUE); if ($params['amount'] < $productDAO->price) { $nonDeductibleAmount = $params['amount']; } else { $nonDeductibleAmount = $productDAO->price; } } else { $nonDeductibleAmount = '0.00'; } } $now = date('YmdHis'); $receiptDate = CRM_Utils_Array::value('receipt_date', $params); if (CRM_Utils_Array::value('is_email_receipt', $form->_values)) { $receiptDate = $now; } //get the contrib page id. $campaignId = $contributionPageId = NULL; if ($online) { $contributionPageId = $form->_id; $campaignId = CRM_Utils_Array::value('campaign_id', $params); if (!array_key_exists('campaign_id', $params)) { $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values); } } else { //also for offline we do support - CRM-7290 $contributionPageId = CRM_Utils_Array::value('contribution_page_id', $params); $campaignId = CRM_Utils_Array::value('campaign_id', $params); } // first create the contribution record $contribParams = array('contact_id' => $contactID, 'contribution_type_id' => $contributionType->id, 'contribution_page_id' => $contributionPageId, 'receive_date' => CRM_Utils_Array::value('receive_date', $params) ? CRM_Utils_Date::processDate($params['receive_date']) : date('YmdHis'), 'non_deductible_amount' => $nonDeductibleAmount, 'total_amount' => $params['amount'], 'amount_level' => CRM_Utils_Array::value('amount_level', $params), 'invoice_id' => $params['invoiceID'], 'currency' => $params['currencyID'], 'source' => !$online || CRM_Utils_Array::value('source', $params) ? CRM_Utils_Array::value('source', $params) : CRM_Utils_Array::value('description', $params), 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0), 'cancel_reason' => CRM_Utils_Array::value('cancel_reason', $params, 0), 'cancel_date' => isset($params['cancel_date']) ? CRM_Utils_Date::format($params['cancel_date']) : NULL, 'thankyou_date' => isset($params['thankyou_date']) ? CRM_Utils_Date::format($params['thankyou_date']) : NULL, 'campaign_id' => $campaignId); if (!$online && isset($params['thankyou_date'])) { $contribParams['thankyou_date'] = $params['thankyou_date']; } if (!$online || $form->_values['is_monetary']) { if (!CRM_Utils_Array::value('is_pay_later', $params)) { $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, 'trxn_result_code' => CRM_Utils_Array::value('trxn_result_code', $result), 'payment_processor' => CRM_Utils_Array::value('payment_processor', $result)); } if (isset($honorCId)) { $contribParams['honor_contact_id'] = $honorCId; $contribParams['honor_type_id'] = $params['honor_type_id']; } if ($recurringContributionID) { $contribParams['contribution_recur_id'] = $recurringContributionID; } $contribParams['contribution_status_id'] = $pending ? 2 : 1; $contribParams['is_test'] = 0; if ($form->_mode == 'test') { $contribParams['is_test'] = 1; } $ids = array(); if (isset($contribParams['invoice_id'])) { $contribID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contribParams['invoice_id'], 'id', 'invoice_id'); if (isset($contribID)) { $ids['contribution'] = $contribID; $contribParams['id'] = $contribID; } } //create an contribution address if ($form->_contributeMode != 'notify' && !CRM_Utils_Array::value('is_pay_later', $params) && CRM_Utils_Array::value('is_monetary', $form->_values)) { $contribParams['address_id'] = CRM_Contribute_BAO_Contribution::createAddress($params, $form->_bltID); } // CRM-4038: for non-en_US locales, CRM_Contribute_BAO_Contribution::add() expects localised amounts $contribParams['non_deductible_amount'] = trim(CRM_Utils_Money::format($contribParams['non_deductible_amount'], ' ')); $contribParams['total_amount'] = trim(CRM_Utils_Money::format($contribParams['total_amount'], ' ')); // Prepare soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin. if (CRM_Utils_Array::value('pcp_made_through_id', $params) || CRM_Utils_Array::value('soft_credit_to', $params)) { // if its due to pcp if (CRM_Utils_Array::value('pcp_made_through_id', $params)) { $contribSoftContactId = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $params['pcp_made_through_id'], 'contact_id'); } else { $contribSoftContactId = CRM_Utils_Array::value('soft_credit_to', $params); } // Pass these details onto with the contribution to make them // available at hook_post_process, CRM-8908 $contribParams['soft_credit_to'] = $params['soft_credit_to'] = $contribSoftContactId; } if ($params['amount']) { //add contribution record $contribution =& CRM_Contribute_BAO_Contribution::add($contribParams, $ids); } // process soft credit / pcp pages CRM_Contribute_Form_Contribution_Confirm::processPcpSoft($params, $contribution); // process price set, CRM-5095 if ($contribution && $contribution->id && $form->_priceSetId) { if (CRM_Utils_Array::value('is_quick_config', $form->_params)) { $temp = array(); foreach ($form->_lineItem as $key => $val) { foreach ($val as $k => $v) { if (CRM_Utils_Money::format($v['line_total']) == CRM_Utils_Money::format($contribution->total_amount)) { $temp[$key][$k] = $form->_lineItem[$key][$k]; CRM_Contribute_Form_AdditionalInfo::processPriceSet($contribution->id, $temp); } } } } elseif (!CRM_Utils_Array::value('is_quick_config', $form->_params)) { CRM_Contribute_Form_AdditionalInfo::processPriceSet($contribution->id, $form->_lineItem); } if (!$form->_separateMembershipPayment && CRM_Utils_Array::value('is_quick_config', $form->_params)) { $form->_lineItem = null; } } //handle pledge stuff. if (!CRM_Utils_Array::value('separate_membership_payment', $form->_params) && CRM_Utils_Array::value('pledge_block_id', $form->_values) && (CRM_Utils_Array::value('is_pledge', $form->_params) || CRM_Utils_Array::value('pledge_id', $form->_values))) { if (CRM_Utils_Array::value('pledge_id', $form->_values)) { //when user doing pledge payments. //update the schedule when payment(s) are made foreach ($form->_params['pledge_amount'] as $paymentId => $dontCare) { $scheduledAmount = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $paymentId, 'scheduled_amount', 'id'); $pledgePaymentParams = array('id' => $paymentId, 'contribution_id' => $contribution->id, 'status_id' => $contribution->contribution_status_id, 'actual_amount' => $scheduledAmount); CRM_Pledge_BAO_PledgePayment::add($pledgePaymentParams); } //update pledge status according to the new payment statuses CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($form->_values['pledge_id']); } 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['contribution_type_id'] = $contribution->contribution_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'] = $campaignId; $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($form->_params, CRM_Core_DAO::$_nullArray, 'civicrm_contribution', $contribution->id, 'Contribution'); } elseif ($contribution) { //handle custom data. $params['contribution_id'] = $contribution->id; if (CRM_Utils_Array::value('custom', $params) && is_array($params['custom']) && !is_a($contribution, 'CRM_Core_Error')) { CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id); } } if (isset($params['related_contact'])) { $contactID = $params['related_contact']; } elseif (isset($params['cms_contactID'])) { $contactID = $params['cms_contactID']; } CRM_Contribute_BAO_Contribution_Utils::createCMSUser($params, $contactID, 'email-' . $form->_bltID); // return if pending if ($pending) { return $contribution; } // next create the transaction record if ($contribution && (!$online || $form->_values['is_monetary']) && $result['trxn_id']) { $trxnParams = array('contribution_id' => $contribution->id, 'trxn_date' => $now, 'trxn_type' => 'Debit', 'total_amount' => $params['amount'], 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $params['amount']), 'currency' => $params['currencyID'], 'payment_processor' => $form->_paymentProcessor['payment_processor_type'], 'trxn_id' => $result['trxn_id'], 'trxn_result_code' => isset($result['trxn_result_code']) ? $result['trxn_result_code'] : FALSE); $trxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams); } //create contribution activity w/ individual and target //activity w/ organisation contact id when onbelf, CRM-4027 $targetContactID = NULL; if (CRM_Utils_Array::value('hidden_onbehalf_profile', $params)) { $targetContactID = $contribution->contact_id; $contribution->contact_id = $contactID; } // create an activity record if ($contribution) { CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID); } $transaction->commit(); return $contribution; }
/** * Process the contribution. * * @param CRM_Core_Form $form * @param array $params * @param array $result * @param int $contactID * @param CRM_Financial_DAO_FinancialType $financialType * @param bool $pending * @param bool $online * * @param bool $isTest * @param array $lineItems * * @param int $billingLocationID * ID of billing location type. * * @return \CRM_Contribute_DAO_Contribution * @throws \Exception */ public static function processFormContribution(&$form, $params, $result, $contactID, $financialType, $pending, $online, $isTest, $lineItems, $billingLocationID) { $transaction = new CRM_Core_Transaction(); $contribSoftContactId = $addressID = NULL; $contributeMode = $form->_contributeMode; $isMonetary = !empty($form->_values['is_monetary']); $isEmailReceipt = !empty($form->_values['is_email_receipt']); // How do these vary from params? These are currently passed to // - custom data function.... $formParams = $form->_params; $isSeparateMembershipPayment = empty($formParams['separate_membership_payment']) ? FALSE : TRUE; $pledgeID = empty($formParams['pledge_id']) ? NULL : $formParams['pledge_id']; if (!$isSeparateMembershipPayment && !empty($form->_values['pledge_block_id']) && (!empty($formParams['is_pledge']) || $pledgeID)) { $isPledge = TRUE; } else { $isPledge = FALSE; } // add these values for the recurringContrib function ,CRM-10188 $params['financial_type_id'] = $financialType->id; //create an contribution address if ($contributeMode != 'notify' && empty($params['is_pay_later']) && $isMonetary) { $addressID = 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; } $recurringContributionID = self::processRecurringContribution($form, $params, $contactID, $financialType, $online); $nonDeductibleAmount = self::getNonDeductibleAmount($params, $financialType, $online); $now = date('YmdHis'); $receiptDate = CRM_Utils_Array::value('receipt_date', $params); if ($isEmailReceipt) { $receiptDate = $now; } //get the contrib page id. $contributionPageId = NULL; if ($online) { $contributionPageId = $form->_id; $campaignId = CRM_Utils_Array::value('campaign_id', $params); if (!array_key_exists('campaign_id', $params)) { $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values); } } else { //also for offline we do support - CRM-7290 $contributionPageId = CRM_Utils_Array::value('contribution_page_id', $params); $campaignId = CRM_Utils_Array::value('campaign_id', $params); } // Prepare soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin. if (!empty($params['pcp_made_through_id']) || !empty($params['soft_credit_to'])) { // if its due to pcp if (!empty($params['pcp_made_through_id'])) { $contribSoftContactId = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $params['pcp_made_through_id'], 'contact_id'); } else { $contribSoftContactId = CRM_Utils_Array::value('soft_credit_to', $params); } // Pass these details onto with the contribution to make them // available at hook_post_process, CRM-8908 $params['soft_credit_to'] = $contribSoftContactId; } if (isset($params['amount'])) { $contribParams = self::getContributionParams($params, $contactID, $financialType->id, $online, $contributionPageId, $nonDeductibleAmount, $campaignId, $isMonetary, $pending, $result, $receiptDate, $recurringContributionID, $isTest, $addressID, $contribSoftContactId, $lineItems); $contribution = CRM_Contribute_BAO_Contribution::add($contribParams); $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) { $dataArray = array(); 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; } //CRM-13981, processing honor contact into soft-credit contribution CRM_Contact_Form_ProfileContact::postProcess($form); // process soft credit / pcp pages CRM_Contribute_Form_Contribution_Confirm::processPcpSoft($params, $contribution); //handle pledge stuff. if ($isPledge) { if ($pledgeID) { //when user doing pledge payments. //update the schedule when payment(s) are made foreach ($form->_params['pledge_amount'] as $paymentId => $dontCare) { $scheduledAmount = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $paymentId, 'scheduled_amount', 'id'); $pledgePaymentParams = array('id' => $paymentId, 'contribution_id' => $contribution->id, 'status_id' => $contribution->contribution_status_id, 'actual_amount' => $scheduledAmount); CRM_Pledge_BAO_PledgePayment::add($pledgePaymentParams); } //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'] = $campaignId; $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($form->_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; }
/** * Mark a pledge (and any outstanding payments) as cancelled. * * @param int $pledgeID */ public static function cancel($pledgeID) { $statuses = array_flip(CRM_Contribute_PseudoConstant::contributionStatus()); $paymentIDs = self::findCancelablePayments($pledgeID); CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $paymentIDs, NULL, $statuses['Cancelled'], 0, FALSE, TRUE); }
/** * Process credit card payment. * * @param array $submittedValues * @param array $lineItem * * @throws CRM_Core_Exception */ protected function processCreditCard($submittedValues, $lineItem) { $sendReceipt = $contribution = FALSE; $unsetParams = array('trxn_id', 'payment_instrument_id', 'contribution_status_id', 'cancel_date', 'cancel_reason'); foreach ($unsetParams as $key) { if (isset($submittedValues[$key])) { unset($submittedValues[$key]); } } $isTest = $this->_mode == 'test' ? 1 : 0; // CRM-12680 set $_lineItem if its not set if (empty($this->_lineItem) && !empty($lineItem)) { $this->_lineItem = $lineItem; } //Get the require fields value only. $params = $this->_params = $submittedValues; $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode); // Get the payment processor id as per mode. $this->_params['payment_processor'] = $params['payment_processor_id'] = $this->_params['payment_processor_id'] = $submittedValues['payment_processor_id'] = $this->_paymentProcessor['id']; $now = date('YmdHis'); $fields = array(); // we need to retrieve email address if ($this->_context == 'standalone' && !empty($submittedValues['is_email_receipt'])) { list($this->userDisplayName, $this->userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID); $this->assign('displayName', $this->userDisplayName); } // Set email for primary location. $fields['email-Primary'] = 1; $params['email-Primary'] = $this->userEmail; // now set the values for the billing location. foreach (array_keys($this->_fields) as $name) { $fields[$name] = 1; } // also add location name to the array $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params); $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]); $fields["address_name-{$this->_bltID}"] = 1; $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type'); $nameFields = array('first_name', 'middle_name', 'last_name'); foreach ($nameFields as $name) { $fields[$name] = 1; if (array_key_exists("billing_{$name}", $params)) { $params[$name] = $params["billing_{$name}"]; $params['preserveDBName'] = TRUE; } } if (!empty($params['source'])) { unset($params['source']); } $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactID, NULL, NULL, $ctype); // add all the additional payment params we need if (!empty($this->_params["billing_state_province_id-{$this->_bltID}"])) { $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}"]); } if (!empty($this->_params["billing_country_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}"]); } $legacyCreditCardExpiryCheck = FALSE; if ($this->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_CREDIT_CARD && !isset($this->_paymentFields)) { $legacyCreditCardExpiryCheck = TRUE; } if ($legacyCreditCardExpiryCheck || in_array('credit_card_exp_date', array_keys($this->_paymentFields))) { $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'] = $this->_params['total_amount']; $this->_params['amount_level'] = 0; $this->_params['description'] = ts('Office Credit Card contribution'); $this->_params['currencyID'] = CRM_Utils_Array::value('currency', $this->_params, CRM_Core_Config::singleton()->defaultCurrency); $this->_params['payment_action'] = 'Sale'; if (!empty($this->_params['receive_date'])) { $this->_params['receive_date'] = CRM_Utils_Date::processDate($this->_params['receive_date'], $this->_params['receive_date_time']); } if (!empty($params['soft_credit_to'])) { $this->_params['soft_credit_to'] = $params['soft_credit_to']; $this->_params['pcp_made_through_id'] = $params['pcp_made_through_id']; } $this->_params['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $params); $this->_params['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $params); $this->_params['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $params); //Add common data to formatted params CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params, $this); if (empty($this->_params['invoice_id'])) { $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE)); } else { $this->_params['invoiceID'] = $this->_params['invoice_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->_contactID; CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE); $contributionType = new CRM_Financial_DAO_FinancialType(); $contributionType->id = $params['financial_type_id']; // Add some financial type details to the params list // if folks need to use it. $paymentParams['contributionType_name'] = $this->_params['contributionType_name'] = $contributionType->name; $paymentParams['contributionPageID'] = NULL; if (!empty($this->_params['is_email_receipt'])) { $paymentParams['email'] = $this->userEmail; $paymentParams['is_email_receipt'] = 1; } else { $paymentParams['is_email_receipt'] = 0; $this->_params['is_email_receipt'] = 0; } if (!empty($this->_params['receive_date'])) { $paymentParams['receive_date'] = $this->_params['receive_date']; } // For recurring contribution, create Contribution Record first. // Contribution ID, Recurring ID and Contact ID needed // When we get a callback from the payment processor, CRM-7115 if (!empty($paymentParams['is_recur'])) { $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this, $this->_params, NULL, $this->_contactID, $contributionType, TRUE, FALSE, $isTest, $this->_lineItem); $paymentParams['contributionID'] = $contribution->id; $paymentParams['contributionTypeID'] = $contribution->financial_type_id; $paymentParams['contributionPageID'] = $contribution->contribution_page_id; $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id; } $result = array(); if ($paymentParams['amount'] > 0.0) { // force a re-get of the payment processor in case the form changed it, CRM-7179 $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this, TRUE); try { $result = $payment->doPayment($paymentParams, 'contribute'); } catch (CRM_Core_Exception $e) { $message = ts("Payment Processor Error message") . $e->getMessage(); $this->cleanupDBAfterPaymentFailure($paymentParams, $message); // Set the contribution mode. $urlParams = "action=add&cid={$this->_contactID}"; if ($this->_mode) { $urlParams .= "&mode={$this->_mode}"; } if (!empty($this->_ppID)) { $urlParams .= "&context=pledge&ppid={$this->_ppID}"; } CRM_Core_Error::statusBounce($message, $urlParams, ts('Payment Processor Error')); } } $this->_params = array_merge($this->_params, $result); $this->_params['receive_date'] = $now; if (!empty($this->_params['is_email_receipt'])) { $this->_params['receipt_date'] = $now; } else { $this->_params['receipt_date'] = CRM_Utils_Date::processDate($this->_params['receipt_date'], $params['receipt_date_time'], TRUE); } $this->set('params', $this->_params); $this->assign('trxn_id', $result['trxn_id']); $this->assign('receive_date', $this->_params['receive_date']); // Result has all the stuff we need // lets archive it to a financial transaction if ($contributionType->is_deductible) { $this->assign('is_deductible', TRUE); $this->set('is_deductible', TRUE); } // Set source if not set if (empty($this->_params['source'])) { $userID = CRM_Core_Session::singleton()->get('userID'); $userSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $userID, 'sort_name'); $this->_params['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName)); } // Build custom data getFields array $customFieldsContributionType = CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE, CRM_Utils_Array::value('financial_type_id', $params)); $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsContributionType, CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE, NULL, NULL, TRUE)); $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_id, 'Contribution'); if (empty($paymentParams['is_recur'])) { $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this, $this->_params, $result, $this->_contactID, $contributionType, FALSE, FALSE, $isTest, $this->_lineItem); } // Send receipt mail. if ($contribution->id && !empty($this->_params['is_email_receipt'])) { $this->_params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result); $this->_params['contact_id'] = $this->_contactID; $this->_params['contribution_id'] = $contribution->id; $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $this->_params, TRUE); } //process the note if ($contribution->id && isset($params['note'])) { CRM_Contribute_Form_AdditionalInfo::processNote($params, $contactID, $contribution->id, NULL); } //process premium if ($contribution->id && isset($params['product_name'][0])) { CRM_Contribute_Form_AdditionalInfo::processPremium($params, $contribution->id, NULL, $this->_options); } //update pledge payment status. if ($this->_ppID && $contribution->id) { // Store contribution id in payment record. CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID, 'contribution_id', $contribution->id); CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($this->_pledgeID, array($this->_ppID), $contribution->contribution_status_id, NULL, $contribution->total_amount); } if ($contribution->id) { $statusMsg = ts('The contribution record has been processed.'); if (!empty($this->_params['is_email_receipt']) && $sendReceipt) { $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.'); } CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success'); } }
function updateRecurLinkedPledge(&$contribution) { $returnProperties = array('id', 'pledge_id'); $paymentDetails = $paymentIDs = array(); if (CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $contribution->id, $paymentDetails, $returnProperties)) { foreach ($paymentDetails as $key => $value) { $paymentIDs[] = $value['id']; $pledgeId = $value['pledge_id']; } } else { //payment is not already linked - if it is linked with a pledge we need to create a link. // return if it is not recurring contribution if (!$contribution->contribution_recur_id) { return; } $relatedContributions = new CRM_Contribute_DAO_Contribution(); $relatedContributions->contribution_recur_id = $contribution->contribution_recur_id; $relatedContributions->find(); while ($relatedContributions->fetch()) { CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $relatedContributions->id, $paymentDetails, $returnProperties); } if (empty($paymentDetails)) { // payment is not linked with a pledge and neither are any other contributions on this return; } foreach ($paymentDetails as $key => $value) { $pledgeId = $value['pledge_id']; } // we have a pledge now we need to get the oldest unpaid payment $paymentDetails = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId); if (empty($paymentDetails['id'])) { // we can assume this pledge is now completed // return now so we don't create a core error & roll back return; } $paymentDetails['contribution_id'] = $contribution->id; $paymentDetails['status_id'] = $contribution->contribution_status_id; $paymentDetails['actual_amount'] = $contribution->total_amount; // put contribution against it $payment = CRM_Pledge_BAO_PledgePayment::add($paymentDetails); $paymentIDs[] = $payment->id; } // update pledge and corresponding payment statuses CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contribution->contribution_status_id, NULL, $contribution->total_amount); }
/** * This function is the main function that is called when the page loads, it decides the which action has to be taken for the page. * * return null * @access public */ function run() { $this->preProcess(); // check if we can process credit card registration $processors = CRM_Core_PseudoConstant::paymentProcessor(FALSE, FALSE, "billing_mode IN ( 1, 3 )"); if (count($processors) > 0) { $this->assign('newCredit', TRUE); } else { $this->assign('newCredit', FALSE); } $this->setContext(); if ($this->_action & CRM_Core_Action::VIEW) { $this->view(); } elseif ($this->_action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD | CRM_Core_Action::DELETE)) { $this->edit(); } elseif ($this->_action & CRM_Core_Action::DETACH) { CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($this->_id, NULL, NULL, array_search('Cancelled', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'))); $session = CRM_Core_Session::singleton(); $session->setStatus(ts('Pledge has been Cancelled and all scheduled (not completed) payments have been cancelled.<br />')); CRM_Utils_System::redirect($session->popUserContext()); } else { $this->browse(); } return parent::run(); }