3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
28 use Civi\Payment\Exception\PaymentProcessorException
;
31 * This class generates form components for processing a contribution.
33 class CRM_Contribute_Form_Contribution
extends CRM_Contribute_Form_AbstractEditPayment
{
35 * The id of the contribution that we are processing.
42 * The id of the premium that we are processing.
46 public $_premiumID = NULL;
49 * @var CRM_Contribute_DAO_ContributionProduct
51 public $_productDAO = NULL;
61 * The id of the contact associated with this contribution.
68 * The id of the pledge payment that we are processing.
75 * Is this contribution associated with an online.
76 * financial transaction
80 public $_online = FALSE;
83 * Stores all product options.
90 * Storage of parameters from form
97 * Store the contribution Type ID
101 public $_contributionType;
104 * The contribution values if an existing contribution
109 * The pledge values if this contribution is associated with pledge
111 public $_pledgeValues;
113 public $_contributeMode = 'direct';
118 * Parameter with confusing name.
122 public $_compContext;
127 * Possible From email addresses
139 * Store the line items if price set used.
145 * @todo explain why we use lineItem & lineItems
151 * @var array soft credit info
153 public $_softCreditInfo;
155 protected $_formType;
157 public $_honoreeProfileType;
160 * Array of the payment fields to be displayed in the payment fieldset (pane) in billingBlock.tpl
161 * this contains all the information to describe these fields from quickform. See CRM_Core_Form_Payment getPaymentFormFieldsMetadata
165 public $_paymentFields = array();
167 * Logged in user's email.
179 * Price set as an array
186 * @todo can we define this a as protected? can we define higher up the chain
196 public $userDisplayName;
199 * Status message to be shown to the user.
203 protected $statusMessage = array();
206 * Status message title to be shown to the user.
208 * Generally the payment processor message title is 'Complete' and offline is 'Saved'
209 * although this might not be a good fit with the broad range of processors.
213 protected $statusMessageTitle;
216 * Set variables up before form is built.
218 public function preProcess() {
219 // Check permission for action.
220 if (!CRM_Core_Permission
::checkActionPermission('CiviContribute', $this->_action
)) {
221 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
224 parent
::preProcess();
226 $this->_formType
= CRM_Utils_Array
::value('formType', $_GET);
229 $this->_priceSetId
= CRM_Utils_Array
::value('priceSetId', $_GET);
230 $this->set('priceSetId', $this->_priceSetId
);
231 $this->assign('priceSetId', $this->_priceSetId
);
233 // Get the pledge payment id
234 $this->_ppID
= CRM_Utils_Request
::retrieve('ppid', 'Positive', $this);
236 $this->assign('action', $this->_action
);
238 // Get the contribution id if update
239 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this);
240 if (!empty($this->_id
)) {
241 $this->assign('contribID', $this->_id
);
244 $this->_context
= CRM_Utils_Request
::retrieve('context', 'String', $this);
245 $this->assign('context', $this->_context
);
247 $this->_compId
= CRM_Utils_Request
::retrieve('compId', 'Positive', $this);
249 $this->_compContext
= CRM_Utils_Request
::retrieve('compContext', 'String', $this);
251 //set the contribution mode.
252 $this->_mode
= CRM_Utils_Request
::retrieve('mode', 'String', $this);
254 $this->assign('contributionMode', $this->_mode
);
255 if ($this->_action
& CRM_Core_Action
::DELETE
) {
259 $this->assign('showCheckNumber', TRUE);
261 $this->_fromEmails
= CRM_Core_BAO_Email
::getFromEmail();
262 $this->assignPaymentRelatedVariables();
264 if (in_array('CiviPledge', CRM_Core_Config
::singleton()->enableComponents
) && !$this->_formType
) {
265 $this->preProcessPledge();
269 $this->showRecordLinkMesssage($this->_id
);
271 $this->_values
= array();
273 // Current contribution id.
275 $this->assignPremiumProduct($this->_id
);
276 $this->buildValuesAndAssignOnline_Note_Type($this->_id
, $this->_values
);
279 // when custom data is included in this page
280 if (!empty($_POST['hidden_custom'])) {
281 $this->applyCustomData('Contribution', CRM_Utils_Array
::value('financial_type_id', $_POST), $this->_id
);
284 $this->_lineItems
= array();
286 if (!empty($this->_compId
) && $this->_compContext
== 'participant') {
287 $this->assign('compId', $this->_compId
);
288 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_compId
);
291 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution', 1, TRUE, TRUE);
293 empty($lineItem) ?
NULL : $this->_lineItems
[] = $lineItem;
296 $this->assign('lineItem', empty($this->_lineItems
) ?
FALSE : $this->_lineItems
);
300 CRM_Financial_Form_Payment
::addCreditCardJs();
301 $this->setPageTitle($this->_ppID ?
ts('Credit Card Pledge Payment') : ts('Credit Card Contribution'));
304 $this->setPageTitle($this->_ppID ?
ts('Pledge Payment') : ts('Contribution'));
308 CRM_Contribute_Form_SoftCredit
::preprocess($this);
313 * Set default values.
317 public function setDefaultValues() {
319 $defaults = $this->_values
;
321 // Set defaults for pledge payment.
323 $defaults['total_amount'] = CRM_Utils_Array
::value('scheduled_amount', $this->_pledgeValues
['pledgePayment']);
324 $defaults['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $this->_pledgeValues
);
325 $defaults['currency'] = CRM_Utils_Array
::value('currency', $this->_pledgeValues
);
326 $defaults['option_type'] = 1;
329 if ($this->_action
& CRM_Core_Action
::DELETE
) {
333 $defaults['frequency_interval'] = 1;
334 $defaults['frequency_unit'] = 'month';
336 // Set soft credit defaults.
337 CRM_Contribute_Form_SoftCredit
::setDefaultValues($defaults, $this);
340 $config = CRM_Core_Config
::singleton();
341 // Set default country from config if no country set.
342 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
343 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry
;
346 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
347 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince
;
350 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID
);
351 $defaults = array_merge($defaults, $billingDefaults);
355 $this->_contactID
= $defaults['contact_id'];
358 // Set $newCredit variable in template to control whether link to credit card mode is included.
359 $this->assign('newCredit', CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments());
361 // Fix the display of the monetary value, CRM-4038.
362 if (isset($defaults['total_amount'])) {
363 if (!empty($defaults['tax_amount'])) {
364 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
365 if (!(CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails))) {
366 $defaults['total_amount'] = CRM_Utils_Money
::format($defaults['total_amount'] - $defaults['tax_amount'], NULL, '%a');
370 $defaults['total_amount'] = CRM_Utils_Money
::format($defaults['total_amount'], NULL, '%a');
374 if (isset($defaults['non_deductible_amount'])) {
375 $defaults['non_deductible_amount'] = CRM_Utils_Money
::format($defaults['non_deductible_amount'], NULL, '%a');
378 if (isset($defaults['fee_amount'])) {
379 $defaults['fee_amount'] = CRM_Utils_Money
::format($defaults['fee_amount'], NULL, '%a');
382 if (isset($defaults['net_amount'])) {
383 $defaults['net_amount'] = CRM_Utils_Money
::format($defaults['net_amount'], NULL, '%a');
386 if ($this->_contributionType
) {
387 $defaults['financial_type_id'] = $this->_contributionType
;
390 if (empty($defaults['payment_instrument_id'])) {
391 $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup
::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
394 if (!empty($defaults['is_test'])) {
395 $this->assign('is_test', TRUE);
398 $this->assign('showOption', TRUE);
399 // For Premium section.
400 if ($this->_premiumID
) {
401 $this->assign('showOption', FALSE);
402 $options = isset($this->_options
[$this->_productDAO
->product_id
]) ?
$this->_options
[$this->_productDAO
->product_id
] : "";
404 $this->assign('showOption', TRUE);
406 $options_key = CRM_Utils_Array
::key($this->_productDAO
->product_option
, $options);
408 $defaults['product_name'] = array($this->_productDAO
->product_id
, trim($options_key));
411 $defaults['product_name'] = array($this->_productDAO
->product_id
);
413 if ($this->_productDAO
->fulfilled_date
) {
414 list($defaults['fulfilled_date']) = CRM_Utils_Date
::setDateDefaults($this->_productDAO
->fulfilled_date
);
418 if (isset($this->userEmail
)) {
419 $this->assign('email', $this->userEmail
);
422 if (!empty($defaults['is_pay_later'])) {
423 $this->assign('is_pay_later', TRUE);
425 $this->assign('contribution_status_id', CRM_Utils_Array
::value('contribution_status_id', $defaults));
433 foreach ($dates as $key) {
434 if (!empty($defaults[$key])) {
435 list($defaults[$key], $defaults[$key . '_time'])
436 = CRM_Utils_Date
::setDateDefaults(CRM_Utils_Array
::value($key, $defaults), 'activityDateTime');
440 if (!$this->_id
&& empty($defaults['receive_date'])) {
441 list($defaults['receive_date'],
442 $defaults['receive_date_time']
443 ) = CRM_Utils_Date
::setDateDefaults(NULL, 'activityDateTime');
446 $this->assign('receive_date', CRM_Utils_Date
::processDate(CRM_Utils_Array
::value('receive_date', $defaults),
447 CRM_Utils_Array
::value('receive_date_time', $defaults)
449 $currency = CRM_Utils_Array
::value('currency', $defaults);
450 $this->assign('currency', $currency);
451 // Hack to get currency info to the js layer. CRM-11440.
452 CRM_Utils_Money
::format(1);
453 $this->assign('currencySymbol', CRM_Utils_Array
::value($currency, CRM_Utils_Money
::$_currencySymbols));
454 $this->assign('totalAmount', CRM_Utils_Array
::value('total_amount', $defaults));
456 // Inherit campaign from pledge.
457 if ($this->_ppID
&& !empty($this->_pledgeValues
['campaign_id'])) {
458 $defaults['campaign_id'] = $this->_pledgeValues
['campaign_id'];
461 $this->_defaults
= $defaults;
466 * Build the form object.
468 public function buildQuickForm() {
472 //tax rate from financialType
473 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant
::getTaxRates()));
474 $this->assign('currencies', json_encode(CRM_Core_OptionGroup
::values('currencies_enabled')));
476 // build price set form.
477 $buildPriceSet = FALSE;
478 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
479 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
480 $this->assign('invoicing', $invoicing);
482 // display tax amount on edit contribution page
483 if ($invoicing && $this->_action
& CRM_Core_Action
::UPDATE
&& isset($this->_values
['tax_amount'])) {
484 $this->assign('totalTaxAmount', $this->_values
['tax_amount']);
487 if (empty($this->_lineItems
) &&
488 ($this->_priceSetId ||
!empty($_POST['price_set_id']))
490 $buildPriceSet = TRUE;
491 $getOnlyPriceSetElements = TRUE;
492 if (!$this->_priceSetId
) {
493 $this->_priceSetId
= $_POST['price_set_id'];
494 $getOnlyPriceSetElements = FALSE;
497 $this->set('priceSetId', $this->_priceSetId
);
498 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
500 // get only price set form elements.
501 if ($getOnlyPriceSetElements) {
505 // use to build form during form rule.
506 $this->assign('buildPriceSet', $buildPriceSet);
508 $defaults = $this->_values
;
509 $additionalDetailFields = array(
513 'non_deductible_amount',
517 foreach ($additionalDetailFields as $key) {
518 if (!empty($defaults[$key])) {
519 $defaults['hidden_AdditionalDetail'] = 1;
524 if ($this->_productDAO
) {
525 if ($this->_productDAO
->product_id
) {
526 $defaults['hidden_Premium'] = 1;
530 if ($this->_noteID
&&
531 isset($this->_values
['note'])
533 $defaults['hidden_AdditionalDetail'] = 1;
537 ts('Additional Details') => 'AdditionalDetail',
540 //Add Premium pane only if Premium is exists.
541 $dao = new CRM_Contribute_DAO_Product();
544 if ($dao->find(TRUE)) {
545 $paneNames[ts('Premium Information')] = 'Premium';
549 if (CRM_Core_Payment_Form
::buildPaymentForm($this, $this->_paymentProcessor
, FALSE, TRUE) == TRUE) {
550 if (!empty($this->_recurPaymentProcessors
)) {
551 CRM_Contribute_Form_Contribution_Main
::buildRecur($this);
552 $this->setDefaults(array('is_recur' => 0));
553 $this->assign('buildRecurBlock', TRUE);
554 $recurJs = array('onChange' => "buildRecurBlock( this.value ); return false;");
559 foreach ($paneNames as $name => $type) {
560 $allPanes[$name] = $this->generatePane($type, $defaults);
563 $qfKey = $this->controller
->_key
;
564 $this->assign('qfKey', $qfKey);
565 $this->assign('allPanes', $allPanes);
567 $this->addFormRule(array('CRM_Contribute_Form_Contribution', 'formRule'), $this);
569 if ($this->_formType
) {
570 $this->assign('formType', $this->_formType
);
574 $this->applyFilter('__ALL__', 'trim');
576 if ($this->_action
& CRM_Core_Action
::DELETE
) {
577 $this->addButtons(array(
580 'name' => ts('Delete'),
581 'spacing' => ' ',
586 'name' => ts('Cancel'),
593 //need to assign custom data type and subtype to the template
594 $this->assign('customDataType', 'Contribution');
595 $this->assign('customDataSubType', $this->_contributionType
);
596 $this->assign('entityID', $this->_id
);
598 if ($this->_context
== 'standalone') {
599 $this->addEntityRef('contact_id', ts('Contact'), array(
601 'api' => array('extra' => array('email')),
605 $attributes = CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Contribution');
607 $financialType = $this->add('select', 'financial_type_id',
608 ts('Financial Type'),
609 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::financialType(),
611 array('onChange' => "CRM.buildCustomData( 'Contribution', this.value );")
613 $paymentInstrument = FALSE;
615 $paymentInstrument = $this->add('select', 'payment_instrument_id',
617 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::paymentInstrument(),
618 TRUE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
622 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), array('class' => 'twelve') +
$attributes['trxn_id']);
624 //add receipt for offline contribution
625 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
627 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
629 $status = CRM_Contribute_PseudoConstant
::contributionStatus();
631 // suppressing contribution statuses that are NOT relevant to pledges (CRM-5169)
632 $statusName = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
639 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
642 elseif ((!$this->_ppID
&& $this->_id
) ||
!$this->_id
) {
643 $suppressFlag = FALSE;
645 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
646 if (CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails)) {
647 $suppressFlag = TRUE;
650 if (!$suppressFlag) {
655 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
659 unset($status[CRM_Utils_Array
::key('Overdue', $statusName)]);
664 $contributionStatus = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_id
, 'contribution_status_id');
665 $name = CRM_Utils_Array
::value($contributionStatus, $statusName);
670 unset($status[CRM_Utils_Array
::key('In Progress', $statusName)]);
671 unset($status[CRM_Utils_Array
::key('Pending', $statusName)]);
672 unset($status[CRM_Utils_Array
::key('Failed', $statusName)]);
677 unset($status[CRM_Utils_Array
::key('Refunded', $statusName)]);
688 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
694 unset($status[CRM_Utils_Array
::key('Refunded', $statusName)]);
697 $this->add('select', 'contribution_status_id',
698 ts('Contribution Status'),
704 $this->addDateTime('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
706 if ($this->_online
) {
707 $this->assign('hideCalender', TRUE);
709 $checkNumber = $this->add('text', 'check_number', ts('Check Number'), $attributes['check_number']);
711 $this->addDateTime('receipt_date', ts('Receipt Date'), FALSE, array('formatType' => 'activityDateTime'));
712 $this->addDateTime('cancel_date', ts('Cancelled / Refunded Date'), FALSE, array('formatType' => 'activityDateTime'));
714 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
716 $element = $this->add('select',
717 'payment_processor_id',
718 ts('Payment Processor'),
724 if ($this->_online
) {
729 if (empty($this->_lineItems
)) {
730 $buildPriceSet = FALSE;
731 $priceSets = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute');
732 if (!empty($priceSets) && !$this->_ppID
) {
733 $buildPriceSet = TRUE;
736 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
737 // and if we already have line items for that participant. CRM-5095
738 if ($buildPriceSet && $this->_id
) {
739 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
740 $pledgePaymentId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
745 if ($pledgePaymentId) {
746 $buildPriceSet = FALSE;
748 if ($participantID = CRM_Utils_Array
::value('participant', $componentDetails)) {
749 $participantLI = CRM_Price_BAO_LineItem
::getLineItems($participantID);
750 if (!CRM_Utils_System
::isNull($participantLI)) {
751 $buildPriceSet = FALSE;
756 $hasPriceSets = FALSE;
757 if ($buildPriceSet) {
758 $hasPriceSets = TRUE;
759 // CRM-16451: set financial type of 'Price Set' in back office contribution
760 // instead of selecting manually
761 $financialTypeIds = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute', 'financial_type_id');
762 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
764 '' => ts('Choose price set'),
766 NULL, array('onchange' => "buildAmount( this.value, " . json_encode($financialTypeIds) . ");")
768 if ($this->_online
&& !($this->_action
& CRM_Core_Action
::UPDATE
)) {
772 $this->assign('hasPriceSets', $hasPriceSets);
773 $currencyFreeze = FALSE;
774 if (!($this->_action
& CRM_Core_Action
::UPDATE
)) {
775 if ($this->_online ||
$this->_ppID
) {
776 $attributes['total_amount'] = array_merge($attributes['total_amount'], array(
778 'style' => "background-color:#EBECE4",
780 $optionTypes = array(
781 '1' => ts('Adjust Pledge Payment Schedule?'),
782 '2' => ts('Adjust Total Pledge Amount?'),
784 $this->addRadio('option_type',
790 $currencyFreeze = TRUE;
794 $totalAmount = $this->addMoney('total_amount',
796 ($hasPriceSets) ?
FALSE : TRUE,
797 $attributes['total_amount'],
798 TRUE, 'currency', NULL, $currencyFreeze
802 $this->add('text', 'source', ts('Source'), CRM_Utils_Array
::value('source', $attributes));
804 // CRM-7362 --add campaigns.
805 CRM_Campaign_BAO_Campaign
::addCampaign($this, CRM_Utils_Array
::value('campaign_id', $this->_values
));
807 CRM_Contribute_Form_SoftCredit
::buildQuickForm($this);
811 $js = array('onclick' => "return verify( );");
814 $mailingInfo = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
817 $this->assign('outBound_option', $mailingInfo['outBound_option']);
819 $this->addButtons(array(
822 'name' => ts('Save'),
828 'name' => ts('Save and New'),
834 'name' => ts('Cancel'),
839 // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
840 // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
841 if ($this->_id
&& $this->_values
['contribution_status_id'] == array_search('Cancelled', $statusName)) {
843 $totalAmount->freeze();
845 $checkNumber->freeze();
846 $paymentInstrument->freeze();
848 $financialType->freeze();
851 // if contribution is related to membership or participant freeze Financial Type, Amount
852 if ($this->_id
&& isset($this->_values
['tax_amount'])) {
853 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
854 if (CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails)) {
856 $totalAmount->freeze();
858 $financialType->freeze();
859 $this->assign('freezeFinancialType', TRUE);
863 if ($this->_action
& CRM_Core_Action
::VIEW
) {
871 * @param array $fields
872 * The input form values.
873 * @param array $files
874 * The uploaded files if any.
878 * true if no errors, else array of errors
880 public static function formRule($fields, $files, $self) {
883 // Check for Credit Card Contribution.
885 if (empty($fields['payment_processor_id'])) {
886 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
889 // validate payment instrument (e.g. credit card number)
890 CRM_Core_Payment_Form
::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, $self);
894 // Do the amount validations.
895 if (empty($fields['total_amount']) && empty($self->_lineItems
)) {
896 if ($priceSetId = CRM_Utils_Array
::value('price_set_id', $fields)) {
897 CRM_Price_BAO_PriceField
::priceSetValidation($priceSetId, $fields, $errors);
901 $softErrors = CRM_Contribute_Form_SoftCredit
::formRule($fields, $errors, $self);
903 if (!empty($fields['total_amount']) && (!empty($fields['net_amount']) ||
!empty($fields['fee_amount']))) {
904 $sum = CRM_Utils_Rule
::cleanMoney($fields['net_amount']) + CRM_Utils_Rule
::cleanMoney($fields['fee_amount']);
905 // For taxable contribution we need to deduct taxable amount from
906 // (net amount + fee amount) before comparing it with total amount
907 if (!empty($self->_values
['tax_amount'])) {
908 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($self->_id
);
909 if (!(CRM_Utils_Array
::value('membership', $componentDetails) ||
910 CRM_Utils_Array
::value('participant', $componentDetails))
912 $sum = CRM_Utils_Money
::format($sum - $self->_values
['tax_amount'], NULL, '%a');
915 if (CRM_Utils_Rule
::cleanMoney($fields['total_amount']) != $sum) {
916 $errors['total_amount'] = ts('The sum of fee amount and net amount must be equal to total amount');
920 //CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
921 CRM_Contribute_BAO_ContributionRecur
::validateRecurContribution($fields, $files, $self, $errors);
923 // Form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
924 if ($self->_id
&& $self->_values
['contribution_status_id'] != $fields['contribution_status_id']) {
925 CRM_Contribute_BAO_Contribution
::checkStatusValidation($self->_values
, $fields, $errors);
927 // CRM-16015, add form-rule to restrict change of financial type if using price field of different financial type
928 if ($self->_id
&& $self->_values
['financial_type_id'] != $fields['financial_type_id']) {
929 CRM_Contribute_BAO_Contribution
::checkFinancialTypeChange(NULL, $self->_id
, $errors);
931 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
932 if (!empty($fields['fee_amount']) && !empty($fields['financial_type_id']) && $financialType = CRM_Contribute_BAO_Contribution
::validateFinancialType($fields['financial_type_id'])) {
933 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
936 // $trxn_id must be unique CRM-13919
937 if (!empty($fields['trxn_id'])) {
938 $queryParams = array(1 => array($fields['trxn_id'], 'String'));
939 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
941 $queryParams[2] = array((int) $self->_id
, 'Integer');
942 $query .= ' and id !=%2';
944 $tCnt = CRM_Core_DAO
::singleValueQuery($query, $queryParams);
946 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', array(1 => $fields['trxn_id']));
950 $errors = array_merge($errors, $softErrors);
955 * Process the form submission.
957 public function postProcess() {
958 if ($this->_action
& CRM_Core_Action
::DELETE
) {
959 CRM_Contribute_BAO_Contribution
::deleteContribution($this->_id
);
960 CRM_Core_Session
::singleton()->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
961 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
965 $submittedValues = $this->controller
->exportValues($this->_name
);
968 // Get the submitted form values.
969 $contribution = $this->submit($submittedValues, $this->_action
, $this->_ppID
);
971 catch (PaymentProcessorException
$e) {
972 // Set the contribution mode.
973 $urlParams = "action=add&cid={$this->_contactID}";
975 $urlParams .= "&mode={$this->_mode}";
977 if (!empty($this->_ppID
)) {
978 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
981 CRM_Core_Error
::statusBounce($e->getMessage(), $urlParams, ts('Payment Processor Error'));
983 $session = CRM_Core_Session
::singleton();
984 $buttonName = $this->controller
->getButtonName();
985 if ($this->_context
== 'standalone') {
986 if ($buttonName == $this->getButtonName('upload', 'new')) {
987 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contribute/add',
988 'reset=1&action=add&context=standalone'
992 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
993 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
997 elseif ($this->_context
== 'contribution' && $this->_mode
&& $buttonName == $this->getButtonName('upload', 'new')) {
998 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
999 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
1002 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1003 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
1004 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
1008 //store contribution ID if not yet set (on create)
1009 if (empty($this->_id
) && !empty($contribution->id
)) {
1010 $this->_id
= $contribution->id
;
1015 * Process credit card payment.
1017 * @param array $submittedValues
1018 * @param array $lineItem
1020 * @param int $contactID
1023 * @return bool|\CRM_Contribute_DAO_Contribution
1024 * @throws \CiviCRM_API3_Exception
1025 * @throws \Civi\Payment\Exception\PaymentProcessorException
1027 protected function processCreditCard($submittedValues, $lineItem, $contactID) {
1029 $isTest = ($this->_mode
== 'test') ?
1 : 0;
1030 // CRM-12680 set $_lineItem if its not set
1031 // @todo - I don't believe this would ever BE set. I can't find anywhere in the code.
1032 // It would be better to pass line item out to functions than $this->_lineItem as
1033 // we don't know what is being changed where.
1034 if (empty($this->_lineItem
) && !empty($lineItem)) {
1035 $this->_lineItem
= $lineItem;
1038 $this->_paymentObject
= Civi\Payment\System
::singleton()->getById($submittedValues['payment_processor_id']);
1039 $this->_paymentProcessor
= $this->_paymentObject
->getPaymentProcessor();
1041 // Set source if not set
1042 if (empty($submittedValues['source'])) {
1043 $userID = CRM_Core_Session
::singleton()->get('userID');
1044 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1047 $submittedValues['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
1050 $params = $this->_params
= $submittedValues;
1052 // Mapping requiring documentation.
1053 $this->_params
['payment_processor'] = $submittedValues['payment_processor_id'];
1055 $now = date('YmdHis');
1058 // we need to retrieve email address
1059 if ($this->_context
== 'standalone' && !empty($submittedValues['is_email_receipt'])) {
1060 list($this->userDisplayName
,
1062 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contactID);
1063 $this->assign('displayName', $this->userDisplayName
);
1066 // Set email for primary location.
1067 $fields['email-Primary'] = 1;
1068 $params['email-Primary'] = $this->userEmail
;
1070 // now set the values for the billing location.
1071 foreach (array_keys($this->_fields
) as $name) {
1075 // also add location name to the array
1076 $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);
1078 $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
1079 $fields["address_name-{$this->_bltID}"] = 1;
1081 $nameFields = array('first_name', 'middle_name', 'last_name');
1082 foreach ($nameFields as $name) {
1084 if (array_key_exists("billing_$name", $params)) {
1085 $params[$name] = $params["billing_{$name}"];
1086 $params['preserveDBName'] = TRUE;
1090 if (!empty($params['source'])) {
1091 unset($params['source']);
1093 CRM_Contact_BAO_Contact
::createProfileContact($params, $fields,
1096 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
1102 // add all the additional payment params we need
1103 if (!empty($this->_params
["billing_state_province_id-{$this->_bltID}"])) {
1104 $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}"]);
1106 if (!empty($this->_params
["billing_country_id-{$this->_bltID}"])) {
1107 $this->_params
["country-{$this->_bltID}"] = $this->_params
["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant
::countryIsoCode($this->_params
["billing_country_id-{$this->_bltID}"]);
1110 if (in_array('credit_card_exp_date', array_keys($this->_paymentFields
))) {
1111 $this->_params
['year'] = CRM_Core_Payment_Form
::getCreditCardExpirationYear($this->_params
);
1112 $this->_params
['month'] = CRM_Core_Payment_Form
::getCreditCardExpirationMonth($this->_params
);
1115 $this->_params
['ip_address'] = CRM_Utils_System
::ipAddress();
1116 $this->_params
['amount'] = $this->_params
['total_amount'];
1117 $this->_params
['amount_level'] = 0;
1118 $this->_params
['description'] = ts('Office Credit Card contribution');
1119 $this->_params
['currencyID'] = CRM_Utils_Array
::value('currency',
1121 CRM_Core_Config
::singleton()->defaultCurrency
1124 if (!empty($this->_params
['receive_date'])) {
1125 $this->_params
['receive_date'] = CRM_Utils_Date
::processDate($this->_params
['receive_date'], $this->_params
['receive_date_time']);
1128 if (!empty($params['soft_credit_to'])) {
1129 $this->_params
['soft_credit_to'] = $params['soft_credit_to'];
1130 $this->_params
['pcp_made_through_id'] = $params['pcp_made_through_id'];
1133 $this->_params
['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $params);
1134 $this->_params
['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $params);
1135 $this->_params
['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $params);
1137 //Add common data to formatted params
1138 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
1140 if (empty($this->_params
['invoice_id'])) {
1141 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
1144 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
1147 // At this point we've created a contact and stored its address etc
1148 // all the payment processors expect the name and address to be in the
1149 // so we copy stuff over to first_name etc.
1150 $paymentParams = $this->_params
;
1151 $paymentParams['contactID'] = $contactID;
1152 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
1154 $financialType = new CRM_Financial_DAO_FinancialType();
1155 $financialType->id
= $params['financial_type_id'];
1157 // Add some financial type details to the params list
1158 // if folks need to use it.
1159 $paymentParams['contributionType_name'] = $this->_params
['contributionType_name'] = $financialType->name
;
1160 $paymentParams['contributionPageID'] = NULL;
1162 if (!empty($this->_params
['is_email_receipt'])) {
1163 $paymentParams['email'] = $this->userEmail
;
1164 $paymentParams['is_email_receipt'] = 1;
1167 $paymentParams['is_email_receipt'] = 0;
1168 $this->_params
['is_email_receipt'] = 0;
1170 if (!empty($this->_params
['receive_date'])) {
1171 $paymentParams['receive_date'] = $this->_params
['receive_date'];
1174 $this->_params
['receive_date'] = $now;
1176 if (!empty($this->_params
['is_email_receipt'])) {
1177 $this->_params
['receipt_date'] = $now;
1180 $this->_params
['receipt_date'] = CRM_Utils_Date
::processDate($this->_params
['receipt_date'],
1181 $params['receipt_date_time'], TRUE
1185 $this->set('params', $this->_params
);
1187 $this->assign('receive_date', $this->_params
['receive_date']);
1189 // Result has all the stuff we need
1190 // lets archive it to a financial transaction
1191 if ($financialType->is_deductible
) {
1192 $this->assign('is_deductible', TRUE);
1193 $this->set('is_deductible', TRUE);
1196 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processFormContribution($this,
1208 $paymentParams['contributionID'] = $contribution->id
;
1209 $paymentParams['contributionTypeID'] = $contribution->financial_type_id
;
1210 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
1211 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1213 if ($paymentParams['amount'] > 0.0) {
1214 // force a re-get of the payment processor in case the form changed it, CRM-7179
1215 // NOTE - I expect this is not obsolete.
1216 $payment = CRM_Core_Payment
::singleton($this->_mode
, $this->_paymentProcessor
, $this, TRUE);
1218 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id');
1219 $result = $payment->doPayment($paymentParams, 'contribute');
1220 $this->assign('trxn_id', $result['trxn_id']);
1221 $contribution->trxn_id
= $result['trxn_id'];
1222 /* Our scenarios here are
1223 * 1) the payment failed & an Exception should have been thrown
1224 * 2) the payment succeeded but the payment is not immediate (for example a recurring payment
1225 * with a delayed start)
1226 * 3) the payment succeeded with an immediate payment.
1228 * The doPayment function ensures that payment_status_id is always set
1229 * as historically we have had to guess from the context - ie doDirectPayment
1230 * = error or success, unless it is a recurring contribution in which case it is pending.
1232 if ($result['payment_status_id'] == array_search('Completed', $statuses)) {
1233 civicrm_api3('contribution', 'completetransaction', array('id' => $contribution->id
, 'trxn_id' => $result['trxn_id']));
1236 // Save the trxn_id.
1237 $contribution->save();
1240 catch (PaymentProcessorException
$e) {
1241 CRM_Contribute_BAO_Contribution
::failPayment($contribution->id
, $paymentParams['contactID'], $e->getMessage());
1242 throw new PaymentProcessorException($e->getMessage());
1245 // Send receipt mail.
1246 if ($contribution->id
&& !empty($this->_params
['is_email_receipt'])) {
1247 $this->_params
['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $result);
1248 $this->_params
['contact_id'] = $contactID;
1249 $this->_params
['contribution_id'] = $contribution->id
;
1250 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $this->_params
, TRUE)) {
1251 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1255 return $contribution;
1259 * Generate the data to construct a snippet based pane.
1261 * This form also assigns the showAdditionalInfo var based on historical code.
1262 * This appears to mean 'there is a pane to show'.
1264 * @param string $type
1265 * Type of Pane - this is generally used to determine the function name used to build it
1266 * - e.g CreditCard, AdditionalDetail
1267 * @param array $defaults
1270 * We aim to further refactor & simplify this but currently
1272 * - should additional info be shown?
1274 protected function generatePane($type, $defaults) {
1275 $urlParams = "snippet=4&formType={$type}";
1277 $urlParams .= "&mode={$this->_mode}";
1281 if ($type == 'CreditCard' ||
1282 $type == 'DirectDebit'
1288 'url' => CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams),
1293 // See if we need to include this paneName in the current form.
1294 if ($this->_formType
== $type ||
!empty($_POST["hidden_{$type}"]) ||
1295 CRM_Utils_Array
::value("hidden_{$type}", $defaults)
1297 $this->assign('showAdditionalInfo', TRUE);
1298 $pane['open'] = 'true';
1301 if ($type == 'CreditCard' ||
$type == 'DirectDebit') {
1302 // @todo would be good to align tpl name with form name...
1303 // @todo document why this hidden variable is required.
1304 $this->add('hidden', 'hidden_' . $type, 1);
1308 $additionalInfoFormFunction = 'build' . $type;
1309 CRM_Contribute_Form_AdditionalInfo
::$additionalInfoFormFunction($this);
1315 * Wrapper for unit testing the post process submit function.
1317 * (If we expose through api we can get default additions 'for free').
1319 * @param array $params
1320 * @param int $action
1321 * @param string|null $creditCardMode
1323 * @throws \CiviCRM_API3_Exception
1325 public function testSubmit($params, $action, $creditCardMode = NULL) {
1327 'soft_credit_contact_id' => array(),
1328 'receipt_date' => '',
1329 'receipt_date_time' => '',
1330 'cancel_date' => '',
1331 'cancel_date_time' => '',
1332 'hidden_Premium' => 1,
1335 if (!empty($params['id'])) {
1336 $existingContribution = civicrm_api3('contribution', 'getsingle', array(
1337 'id' => $params['id'],
1339 $this->_id
= $params['id'];
1342 $existingContribution = array();
1345 $this->_defaults
['contribution_status_id'] = CRM_Utils_Array
::value('contribution_status_id',
1346 $existingContribution
1349 $this->_defaults
['total_amount'] = CRM_Utils_Array
::value('total_amount',
1350 $existingContribution
1353 if ($creditCardMode) {
1354 $this->_mode
= $creditCardMode;
1357 // Required because processCreditCard calls set method on this.
1358 $_SERVER['REQUEST_METHOD'] = 'GET';
1359 $this->controller
= new CRM_Core_Controller();
1361 CRM_Contribute_Form_AdditionalInfo
::buildPremium($this);
1363 $this->_fields
= array();
1364 $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array
::value('pledge_payment_id', $params));
1369 * @param array $submittedValues
1371 * @param int $action
1373 * - CRM_Core_Action::UPDATE
1375 * @param $pledgePaymentID
1378 * @throws \Exception
1380 protected function submit($submittedValues, $action, $pledgePaymentID) {
1381 $softParams = $softIDs = array();
1382 $pId = $contribution = $isRelatedId = FALSE;
1384 if (!empty($submittedValues['price_set_id']) && $action & CRM_Core_Action
::UPDATE
) {
1385 $line = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution');
1386 $lineID = key($line);
1387 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array
::value('price_field_id', $line[$lineID]), 'price_set_id');
1388 $quickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1390 CRM_Price_BAO_LineItem
::deleteLineItems($this->_id
, 'civicrm_contribution');
1394 // Process price set and get total amount and line items.
1395 $lineItem = array();
1396 $priceSetId = CRM_Utils_Array
::value('price_set_id', $submittedValues);
1397 if (empty($priceSetId) && !$this->_id
) {
1398 $this->_priceSetId
= $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1399 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
1400 $fieldID = key($this->_priceSet
['fields']);
1401 $fieldValueId = key($this->_priceSet
['fields'][$fieldID]['options']);
1402 $this->_priceSet
['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1403 $submittedValues['price_' . $fieldID] = 1;
1407 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
1408 $submittedValues, $lineItem[$priceSetId]);
1410 // Unset tax amount for offline 'is_quick_config' contribution.
1411 if ($this->_priceSet
['is_quick_config'] &&
1412 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant
::getTaxRates())
1414 unset($submittedValues['tax_amount']);
1416 $submittedValues['total_amount'] = CRM_Utils_Array
::value('amount', $submittedValues);
1419 if ($this->_compId
) {
1420 if ($this->_context
== 'participant') {
1421 $pId = $this->_compId
;
1423 elseif ($this->_context
== 'membership') {
1424 $isRelatedId = TRUE;
1427 $pId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id
, 'participant_id', 'contribution_id');
1431 $contributionDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1432 if (array_key_exists('membership', $contributionDetails)) {
1433 $isRelatedId = TRUE;
1435 elseif (array_key_exists('participant', $contributionDetails)) {
1436 $pId = $contributionDetails['participant'];
1440 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id
) {
1441 // CRM-10117 update the line items for participants.
1443 $entityTable = 'participant';
1445 $isRelatedId = FALSE;
1446 $participantParams = array(
1447 'fee_amount' => $submittedValues['total_amount'],
1450 CRM_Event_BAO_Participant
::add($participantParams);
1451 if (empty($this->_lineItems
)) {
1452 $this->_lineItems
[] = CRM_Price_BAO_LineItem
::getLineItems($entityID, 'participant', 1);
1456 $entityTable = 'contribution';
1457 $entityID = $this->_id
;
1460 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, $entityTable, NULL, TRUE, $isRelatedId);
1461 foreach (array_keys($lineItems) as $id) {
1462 $lineItems[$id]['id'] = $id;
1464 $itemId = key($lineItems);
1465 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1466 $this->_priceSetId
= CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1469 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1470 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule
::cleanMoney(CRM_Utils_Array
::value('total_amount', $submittedValues));
1472 // Update line total and total amount with tax on edit.
1473 $financialItemsId = CRM_Core_PseudoConstant
::getTaxRates();
1474 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1475 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1478 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1479 $submittedValues['tax_amount'] = 'null';
1481 if ($lineItems[$itemId]['tax_rate']) {
1482 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total'];
1483 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] +
$lineItems[$itemId]['tax_amount'];
1484 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1487 // CRM-10117 update the line items for participants.
1488 if (!empty($lineItems[$itemId]['price_field_id'])) {
1489 $lineItem[$this->_priceSetId
] = $lineItems;
1494 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1497 //CRM-11529 for quick config back office transactions
1498 //when financial_type_id is passed in form, update the
1499 //line items with the financial type selected in form
1500 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array
::value($this->_priceSetId
, $lineItem)
1502 foreach ($lineItem[$this->_priceSetId
] as &$values) {
1503 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1507 if (!isset($submittedValues['total_amount'])) {
1508 $submittedValues['total_amount'] = CRM_Utils_Array
::value('total_amount', $this->_values
);
1510 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
1512 if (!empty($submittedValues['pcp_made_through_id'])) {
1515 'pcp_made_through_id',
1516 'pcp_display_in_roll',
1517 'pcp_roll_nickname',
1518 'pcp_personal_note',
1520 foreach ($fields as $f) {
1521 $pcp[$f] = CRM_Utils_Array
::value($f, $submittedValues);
1525 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
1526 if ($this->_id
&& count($isEmpty) == 1 && key($isEmpty) == NULL) {
1527 //Delete existing soft credit records if soft credit list is empty on update
1528 CRM_Contribute_BAO_ContributionSoft
::del(array('contribution_id' => $this->_id
));
1531 //build soft credit params
1532 foreach ($submittedValues['soft_credit_contact_id'] as $key => $val) {
1533 if ($val && $submittedValues['soft_credit_amount'][$key]) {
1534 $softParams[$key]['contact_id'] = $val;
1535 $softParams[$key]['amount'] = CRM_Utils_Rule
::cleanMoney($submittedValues['soft_credit_amount'][$key]);
1536 $softParams[$key]['soft_credit_type_id'] = $submittedValues['soft_credit_type'][$key];
1537 if (!empty($submittedValues['soft_credit_id'][$key])) {
1538 $softIDs[] = $softParams[$key]['id'] = $submittedValues['soft_credit_id'][$key];
1544 // set the contact, when contact is selected
1545 if (!empty($submittedValues['contact_id'])) {
1546 $this->_contactID
= $submittedValues['contact_id'];
1548 $formValues = $submittedValues;
1550 // Credit Card Contribution.
1552 $paramsSetByPaymentProcessingSubsystem = array(
1554 'payment_instrument_id',
1555 'contribution_status_id',
1559 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1560 if (isset($formValues[$key])) {
1561 unset($formValues[$key]);
1564 $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID
);
1565 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1566 $formValues[$key] = $contribution->$key;
1570 // Offline Contribution.
1571 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1573 // get the required field value only.
1575 $params = $ids = array();
1577 $params['contact_id'] = $this->_contactID
;
1578 $params['currency'] = $this->getCurrency($submittedValues);
1581 'financial_type_id',
1582 'contribution_status_id',
1583 'payment_instrument_id',
1588 foreach ($fields as $f) {
1589 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1593 $params['pcp'] = $pcp;
1595 $params['soft_credit'] = !empty($softParams) ?
$softParams : array();
1596 $params['soft_credit_ids'] = !empty($softIDs) ?
$softIDs : array();
1598 // CRM-5740 if priceset is used, no need to cleanup money.
1600 $params['skipCleanMoney'] = 1;
1609 foreach ($dates as $d) {
1610 $params[$d] = CRM_Utils_Date
::processDate($formValues[$d], $formValues[$d . '_time'], TRUE);
1613 if (!empty($formValues['is_email_receipt'])) {
1614 $params['receipt_date'] = date("Y-m-d");
1617 if ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Cancelled', 'name')
1618 ||
$params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name')
1620 if (CRM_Utils_System
::isNull(CRM_Utils_Array
::value('cancel_date', $params))) {
1621 $params['cancel_date'] = date('Y-m-d');
1625 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1628 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1629 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1630 if ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Pending', 'name')) {
1631 $params['is_pay_later'] = 1;
1633 elseif ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name')) {
1634 $params['is_pay_later'] = 0;
1637 $ids['contribution'] = $params['id'] = $this->_id
;
1639 // Add Additional common information to formatted params.
1640 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($formValues, $params, $this);
1642 $params['contribution_mode'] = 'participant';
1643 $params['participant_id'] = $pId;
1644 $params['skipLineItem'] = 1;
1646 elseif ($isRelatedId) {
1647 $params['contribution_mode'] = 'membership';
1649 $params['line_item'] = $lineItem;
1650 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array
::value('id', $this->_paymentProcessor
);
1651 if (isset($submittedValues['tax_amount'])) {
1652 $params['tax_amount'] = $submittedValues['tax_amount'];
1654 //create contribution.
1655 if ($isQuickConfig) {
1656 $params['is_quick_config'] = 1;
1658 $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
1660 $contribution = CRM_Contribute_BAO_Contribution
::create($params, $ids);
1662 // process associated membership / participant, CRM-4395
1663 if ($contribution->id
&& $action & CRM_Core_Action
::UPDATE
) {
1664 $this->statusMessage
[] = $this->updateRelatedComponent($contribution->id
,
1665 $contribution->contribution_status_id
,
1666 CRM_Utils_Array
::value('contribution_status_id',
1669 $contribution->receive_date
1673 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1675 $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
1677 //send receipt mail.
1678 if ($contribution->id
&& !empty($formValues['is_email_receipt'])) {
1679 $formValues['contact_id'] = $this->_contactID
;
1680 $formValues['contribution_id'] = $contribution->id
;
1682 $formValues +
= CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
);
1684 // to get 'from email id' for send receipt
1685 $this->fromEmailId
= $formValues['from_email_address'];
1686 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $formValues)) {
1687 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1691 $this->statusMessageTitle
= ts('Saved');
1695 if ($contribution->id
&& !empty($formValues['product_name'][0])) {
1696 CRM_Contribute_Form_AdditionalInfo
::processPremium($submittedValues, $contribution->id
,
1697 $this->_premiumID
, $this->_options
1701 if ($contribution->id
&& isset($submittedValues['note'])) {
1702 CRM_Contribute_Form_AdditionalInfo
::processNote($submittedValues, $this->_contactID
, $contribution->id
, $this->_noteID
);
1705 CRM_Core_Session
::setStatus(implode(' ', $this->statusMessage
), $this->statusMessageTitle
, 'success');
1707 CRM_Contribute_BAO_Contribution
::updateRelatedPledge(
1711 (CRM_Utils_Array
::value('option_type', $formValues) == 2) ?
TRUE : FALSE,
1712 $formValues['total_amount'],
1713 CRM_Utils_Array
::value('total_amount', $this->_defaults
),
1714 $formValues['contribution_status_id'],
1715 CRM_Utils_Array
::value('contribution_status_id', $this->_defaults
)
1717 return $contribution;
1721 * Assign tax calculations to contribution receipts.
1723 * @param array $submittedValues
1724 * @param int $action
1725 * @param array $lineItem
1727 protected function invoicingPostProcessHook($submittedValues, $action, $lineItem) {
1729 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
1730 if (!CRM_Utils_Array
::value('invoicing', $invoiceSettings)) {
1734 $getTaxDetails = FALSE;
1735 if ($action & CRM_Core_Action
::ADD
) {
1738 elseif ($action & CRM_Core_Action
::UPDATE
) {
1739 $line = $this->_lineItems
;
1741 foreach ($line as $key => $value) {
1742 foreach ($value as $v) {
1743 if (isset($taxRate[(string) CRM_Utils_Array
::value('tax_rate', $v)])) {
1744 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $v);
1747 if (isset($v['tax_rate'])) {
1748 $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $v);
1749 $getTaxDetails = TRUE;
1755 if ($action & CRM_Core_Action
::UPDATE
) {
1756 if (isset($submittedValues['tax_amount'])) {
1757 $totalTaxAmount = $submittedValues['tax_amount'];
1760 $totalTaxAmount = $this->_values
['tax_amount'];
1762 $this->assign('totalTaxAmount', $totalTaxAmount);
1763 $this->assign('dataArray', $taxRate);
1766 if (!empty($submittedValues['price_set_id'])) {
1767 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1768 $this->assign('getTaxDetails', $getTaxDetails);
1769 $this->assign('dataArray', $taxRate);
1770 $this->assign('taxTerm', CRM_Utils_Array
::value('tax_term', $invoiceSettings));
1773 $this->assign('totalTaxAmount', CRM_Utils_Array
::value('tax_amount', $submittedValues));
1779 * Calculate non deductible amount.
1782 * if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1783 * if non_deductible_amount does NOT exist - then calculate it depending on:
1784 * $financialType->is_deductible and whether there is a product (premium).
1787 * @param $formValues
1791 protected function calculateNonDeductibleAmount($params, $formValues) {
1792 if (!empty($params['non_deductible_amount'])) {
1793 return $params['non_deductible_amount'];
1795 if (empty($params['non_deductible_amount'])) {
1796 $contributionType = new CRM_Financial_DAO_FinancialType();
1797 $contributionType->id
= $params['financial_type_id'];
1799 if ($contributionType->is_deductible
) {
1801 if (isset($formValues['product_name'][0])) {
1802 $selectProduct = $formValues['product_name'][0];
1804 // if there is a product - compare the value to the contribution amount
1805 if (isset($selectProduct)) {
1806 $productDAO = new CRM_Contribute_DAO_Product();
1807 $productDAO->id
= $selectProduct;
1808 $productDAO->find(TRUE);
1809 // product value exceeds contribution amount
1810 if ($params['total_amount'] < $productDAO->price
) {
1811 return $params['total_amount'];
1813 // product value does NOT exceed contribution amount
1815 return $productDAO->price
;
1818 // contribution is deductible - but there is no product
1823 // contribution is NOT deductible
1825 return $params['total_amount'];