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) {
1028 $contribution = FALSE;
1030 $isTest = ($this->_mode
== 'test') ?
1 : 0;
1031 // CRM-12680 set $_lineItem if its not set
1032 // @todo - I don't believe this would ever BE set. I can't find anywhere in the code.
1033 // It would be better to pass line item out to functions than $this->_lineItem as
1034 // we don't know what is being changed where.
1035 if (empty($this->_lineItem
) && !empty($lineItem)) {
1036 $this->_lineItem
= $lineItem;
1039 $this->_paymentObject
= Civi\Payment\System
::singleton()->getById($submittedValues['payment_processor_id']);
1040 $this->_paymentProcessor
= $this->_paymentObject
->getPaymentProcessor();
1042 // Set source if not set
1043 if (empty($submittedValues['source'])) {
1044 $userID = CRM_Core_Session
::singleton()->get('userID');
1045 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1048 $submittedValues['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
1051 $params = $this->_params
= $submittedValues;
1053 // Mapping requiring documentation.
1054 $this->_params
['payment_processor'] = $submittedValues['payment_processor_id'];
1056 $now = date('YmdHis');
1059 // we need to retrieve email address
1060 if ($this->_context
== 'standalone' && !empty($submittedValues['is_email_receipt'])) {
1061 list($this->userDisplayName
,
1063 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contactID);
1064 $this->assign('displayName', $this->userDisplayName
);
1067 // Set email for primary location.
1068 $fields['email-Primary'] = 1;
1069 $params['email-Primary'] = $this->userEmail
;
1071 // now set the values for the billing location.
1072 foreach (array_keys($this->_fields
) as $name) {
1076 // also add location name to the array
1077 $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);
1079 $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
1080 $fields["address_name-{$this->_bltID}"] = 1;
1082 $nameFields = array('first_name', 'middle_name', 'last_name');
1083 foreach ($nameFields as $name) {
1085 if (array_key_exists("billing_$name", $params)) {
1086 $params[$name] = $params["billing_{$name}"];
1087 $params['preserveDBName'] = TRUE;
1091 if (!empty($params['source'])) {
1092 unset($params['source']);
1094 CRM_Contact_BAO_Contact
::createProfileContact($params, $fields,
1097 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
1103 // add all the additional payment params we need
1104 if (!empty($this->_params
["billing_state_province_id-{$this->_bltID}"])) {
1105 $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}"]);
1107 if (!empty($this->_params
["billing_country_id-{$this->_bltID}"])) {
1108 $this->_params
["country-{$this->_bltID}"] = $this->_params
["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant
::countryIsoCode($this->_params
["billing_country_id-{$this->_bltID}"]);
1111 if (in_array('credit_card_exp_date', array_keys($this->_paymentFields
))) {
1112 $this->_params
['year'] = CRM_Core_Payment_Form
::getCreditCardExpirationYear($this->_params
);
1113 $this->_params
['month'] = CRM_Core_Payment_Form
::getCreditCardExpirationMonth($this->_params
);
1116 $this->_params
['ip_address'] = CRM_Utils_System
::ipAddress();
1117 $this->_params
['amount'] = $this->_params
['total_amount'];
1118 $this->_params
['amount_level'] = 0;
1119 $this->_params
['description'] = ts('Office Credit Card contribution');
1120 $this->_params
['currencyID'] = CRM_Utils_Array
::value('currency',
1122 CRM_Core_Config
::singleton()->defaultCurrency
1125 if (!empty($this->_params
['receive_date'])) {
1126 $this->_params
['receive_date'] = CRM_Utils_Date
::processDate($this->_params
['receive_date'], $this->_params
['receive_date_time']);
1129 if (!empty($params['soft_credit_to'])) {
1130 $this->_params
['soft_credit_to'] = $params['soft_credit_to'];
1131 $this->_params
['pcp_made_through_id'] = $params['pcp_made_through_id'];
1134 $this->_params
['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $params);
1135 $this->_params
['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $params);
1136 $this->_params
['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $params);
1138 //Add common data to formatted params
1139 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
1141 if (empty($this->_params
['invoice_id'])) {
1142 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
1145 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
1148 // At this point we've created a contact and stored its address etc
1149 // all the payment processors expect the name and address to be in the
1150 // so we copy stuff over to first_name etc.
1151 $paymentParams = $this->_params
;
1152 $paymentParams['contactID'] = $contactID;
1153 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
1155 $financialType = new CRM_Financial_DAO_FinancialType();
1156 $financialType->id
= $params['financial_type_id'];
1158 // Add some financial type details to the params list
1159 // if folks need to use it.
1160 $paymentParams['contributionType_name'] = $this->_params
['contributionType_name'] = $financialType->name
;
1161 $paymentParams['contributionPageID'] = NULL;
1163 if (!empty($this->_params
['is_email_receipt'])) {
1164 $paymentParams['email'] = $this->userEmail
;
1165 $paymentParams['is_email_receipt'] = 1;
1168 $paymentParams['is_email_receipt'] = 0;
1169 $this->_params
['is_email_receipt'] = 0;
1171 if (!empty($this->_params
['receive_date'])) {
1172 $paymentParams['receive_date'] = $this->_params
['receive_date'];
1175 $this->_params
['receive_date'] = $now;
1177 if (!empty($this->_params
['is_email_receipt'])) {
1178 $this->_params
['receipt_date'] = $now;
1181 $this->_params
['receipt_date'] = CRM_Utils_Date
::processDate($this->_params
['receipt_date'],
1182 $params['receipt_date_time'], TRUE
1186 $this->set('params', $this->_params
);
1188 $this->assign('receive_date', $this->_params
['receive_date']);
1190 // Result has all the stuff we need
1191 // lets archive it to a financial transaction
1192 if ($financialType->is_deductible
) {
1193 $this->assign('is_deductible', TRUE);
1194 $this->set('is_deductible', TRUE);
1197 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processFormContribution($this,
1209 $paymentParams['contributionID'] = $contribution->id
;
1210 $paymentParams['contributionTypeID'] = $contribution->financial_type_id
;
1211 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
1212 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1214 if ($paymentParams['amount'] > 0.0) {
1215 // force a re-get of the payment processor in case the form changed it, CRM-7179
1216 // NOTE - I expect this is not obsolete.
1217 $payment = CRM_Core_Payment
::singleton($this->_mode
, $this->_paymentProcessor
, $this, TRUE);
1219 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id');
1220 $result = $payment->doPayment($paymentParams, 'contribute');
1221 $this->assign('trxn_id', $result['trxn_id']);
1222 $contribution->trxn_id
= $result['trxn_id'];
1223 /* Our scenarios here are
1224 * 1) the payment failed & an Exception should have been thrown
1225 * 2) the payment succeeded but the payment is not immediate (for example a recurring payment
1226 * with a delayed start)
1227 * 3) the payment succeeded with an immediate payment.
1229 * The doPayment function ensures that contribution_status_id is always set
1230 * as historically we have had to guess from the context - ie doDirectPayment
1231 * = error or success, unless it is a recurring contribution in which case it is pending.
1233 if (!isset($result['contribution_status_id']) ||
$result['contribution_status_id'] ==
1234 array_search('Completed', $statuses)) {
1235 civicrm_api3('contribution', 'completetransaction', array('id' => $contribution->id
, 'trxn_id' => $result['trxn_id']));
1238 // Save the trxn_id.
1239 $contribution->save();
1242 catch (PaymentProcessorException
$e) {
1243 CRM_Contribute_BAO_Contribution
::failPayment($contribution->id
, $paymentParams['contactID'], $e->getMessage());
1244 throw new PaymentProcessorException($e->getMessage());
1247 // Send receipt mail.
1248 if ($contribution->id
&& !empty($this->_params
['is_email_receipt'])) {
1249 $this->_params
['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $result);
1250 $this->_params
['contact_id'] = $contactID;
1251 $this->_params
['contribution_id'] = $contribution->id
;
1252 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $this->_params
, TRUE)) {
1253 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1257 return $contribution;
1261 * Generate the data to construct a snippet based pane.
1263 * This form also assigns the showAdditionalInfo var based on historical code.
1264 * This appears to mean 'there is a pane to show'.
1266 * @param string $type
1267 * Type of Pane - this is generally used to determine the function name used to build it
1268 * - e.g CreditCard, AdditionalDetail
1269 * @param array $defaults
1272 * We aim to further refactor & simplify this but currently
1274 * - should additional info be shown?
1276 protected function generatePane($type, $defaults) {
1277 $urlParams = "snippet=4&formType={$type}";
1279 $urlParams .= "&mode={$this->_mode}";
1283 if ($type == 'CreditCard' ||
1284 $type == 'DirectDebit'
1290 'url' => CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams),
1295 // See if we need to include this paneName in the current form.
1296 if ($this->_formType
== $type ||
!empty($_POST["hidden_{$type}"]) ||
1297 CRM_Utils_Array
::value("hidden_{$type}", $defaults)
1299 $this->assign('showAdditionalInfo', TRUE);
1300 $pane['open'] = 'true';
1303 if ($type == 'CreditCard' ||
$type == 'DirectDebit') {
1304 // @todo would be good to align tpl name with form name...
1305 // @todo document why this hidden variable is required.
1306 $this->add('hidden', 'hidden_' . $type, 1);
1310 $additionalInfoFormFunction = 'build' . $type;
1311 CRM_Contribute_Form_AdditionalInfo
::$additionalInfoFormFunction($this);
1317 * Wrapper for unit testing the post process submit function.
1319 * (If we expose through api we can get default additions 'for free').
1321 * @param array $params
1322 * @param int $action
1323 * @param string|null $creditCardMode
1325 * @throws \CiviCRM_API3_Exception
1327 public function testSubmit($params, $action, $creditCardMode = NULL) {
1329 'soft_credit_contact_id' => array(),
1330 'receipt_date' => '',
1331 'receipt_date_time' => '',
1332 'cancel_date' => '',
1333 'cancel_date_time' => '',
1334 'hidden_Premium' => 1,
1336 if (!empty($params['id'])) {
1337 $existingContribution = civicrm_api3('contribution', 'getsingle', array(
1338 'id' => $params['id'],
1340 $this->_id
= $params['id'];
1343 $existingContribution = array();
1346 $this->_defaults
['contribution_status_id'] = CRM_Utils_Array
::value('contribution_status_id',
1347 $existingContribution
1350 $this->_defaults
['total_amount'] = CRM_Utils_Array
::value('total_amount',
1351 $existingContribution
1354 if ($creditCardMode) {
1355 $this->_mode
= $creditCardMode;
1358 // Required because processCreditCard calls set method on this.
1359 $_SERVER['REQUEST_METHOD'] = 'GET';
1360 $this->controller
= new CRM_Core_Controller();
1362 CRM_Contribute_Form_AdditionalInfo
::buildPremium($this);
1364 $this->_fields
= array();
1365 $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array
::value('pledge_payment_id', $params));
1370 * @param array $submittedValues
1372 * @param int $action
1374 * - CRM_Core_Action::UPDATE
1376 * @param $pledgePaymentID
1379 * @throws \Exception
1381 protected function submit($submittedValues, $action, $pledgePaymentID) {
1382 $softParams = $softIDs = array();
1383 $pId = $contribution = $isRelatedId = FALSE;
1385 if (!empty($submittedValues['price_set_id']) && $action & CRM_Core_Action
::UPDATE
) {
1386 $line = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution');
1387 $lineID = key($line);
1388 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array
::value('price_field_id', $line[$lineID]), 'price_set_id');
1389 $quickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1391 CRM_Price_BAO_LineItem
::deleteLineItems($this->_id
, 'civicrm_contribution');
1395 // Process price set and get total amount and line items.
1396 $lineItem = array();
1397 $priceSetId = CRM_Utils_Array
::value('price_set_id', $submittedValues);
1398 if (empty($priceSetId) && !$this->_id
) {
1399 $this->_priceSetId
= $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1400 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
1401 $fieldID = key($this->_priceSet
['fields']);
1402 $fieldValueId = key($this->_priceSet
['fields'][$fieldID]['options']);
1403 $this->_priceSet
['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1404 $submittedValues['price_' . $fieldID] = 1;
1408 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
1409 $submittedValues, $lineItem[$priceSetId]);
1411 // Unset tax amount for offline 'is_quick_config' contribution.
1412 if ($this->_priceSet
['is_quick_config'] &&
1413 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant
::getTaxRates())
1415 unset($submittedValues['tax_amount']);
1417 $submittedValues['total_amount'] = CRM_Utils_Array
::value('amount', $submittedValues);
1420 if ($this->_compId
) {
1421 if ($this->_context
== 'participant') {
1422 $pId = $this->_compId
;
1424 elseif ($this->_context
== 'membership') {
1425 $isRelatedId = TRUE;
1428 $pId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id
, 'participant_id', 'contribution_id');
1432 $contributionDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1433 if (array_key_exists('membership', $contributionDetails)) {
1434 $isRelatedId = TRUE;
1436 elseif (array_key_exists('participant', $contributionDetails)) {
1437 $pId = $contributionDetails['participant'];
1441 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id
) {
1442 // CRM-10117 update the line items for participants.
1444 $entityTable = 'participant';
1446 $isRelatedId = FALSE;
1447 $participantParams = array(
1448 'fee_amount' => $submittedValues['total_amount'],
1451 CRM_Event_BAO_Participant
::add($participantParams);
1452 if (empty($this->_lineItems
)) {
1453 $this->_lineItems
[] = CRM_Price_BAO_LineItem
::getLineItems($entityID, 'participant', 1);
1457 $entityTable = 'contribution';
1458 $entityID = $this->_id
;
1461 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, $entityTable, NULL, TRUE, $isRelatedId);
1462 foreach (array_keys($lineItems) as $id) {
1463 $lineItems[$id]['id'] = $id;
1465 $itemId = key($lineItems);
1466 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1467 $this->_priceSetId
= CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1470 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1471 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule
::cleanMoney(CRM_Utils_Array
::value('total_amount', $submittedValues));
1473 // Update line total and total amount with tax on edit.
1474 $financialItemsId = CRM_Core_PseudoConstant
::getTaxRates();
1475 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1476 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1479 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1480 $submittedValues['tax_amount'] = 'null';
1482 if ($lineItems[$itemId]['tax_rate']) {
1483 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total'];
1484 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] +
$lineItems[$itemId]['tax_amount'];
1485 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1488 // CRM-10117 update the line items for participants.
1489 if (!empty($lineItems[$itemId]['price_field_id'])) {
1490 $lineItem[$this->_priceSetId
] = $lineItems;
1495 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1498 //CRM-11529 for quick config back office transactions
1499 //when financial_type_id is passed in form, update the
1500 //line items with the financial type selected in form
1501 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array
::value($this->_priceSetId
, $lineItem)
1503 foreach ($lineItem[$this->_priceSetId
] as &$values) {
1504 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1508 if (!isset($submittedValues['total_amount'])) {
1509 $submittedValues['total_amount'] = CRM_Utils_Array
::value('total_amount', $this->_values
);
1511 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
1513 if (!empty($submittedValues['pcp_made_through_id'])) {
1516 'pcp_made_through_id',
1517 'pcp_display_in_roll',
1518 'pcp_roll_nickname',
1519 'pcp_personal_note',
1521 foreach ($fields as $f) {
1522 $pcp[$f] = CRM_Utils_Array
::value($f, $submittedValues);
1526 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
1527 if ($this->_id
&& count($isEmpty) == 1 && key($isEmpty) == NULL) {
1528 //Delete existing soft credit records if soft credit list is empty on update
1529 CRM_Contribute_BAO_ContributionSoft
::del(array('contribution_id' => $this->_id
));
1532 //build soft credit params
1533 foreach ($submittedValues['soft_credit_contact_id'] as $key => $val) {
1534 if ($val && $submittedValues['soft_credit_amount'][$key]) {
1535 $softParams[$key]['contact_id'] = $val;
1536 $softParams[$key]['amount'] = CRM_Utils_Rule
::cleanMoney($submittedValues['soft_credit_amount'][$key]);
1537 $softParams[$key]['soft_credit_type_id'] = $submittedValues['soft_credit_type'][$key];
1538 if (!empty($submittedValues['soft_credit_id'][$key])) {
1539 $softIDs[] = $softParams[$key]['id'] = $submittedValues['soft_credit_id'][$key];
1545 // set the contact, when contact is selected
1546 if (!empty($submittedValues['contact_id'])) {
1547 $this->_contactID
= $submittedValues['contact_id'];
1549 $formValues = $submittedValues;
1551 // Credit Card Contribution.
1553 $paramsSetByPaymentProcessingSubsystem = array(
1555 'payment_instrument_id',
1556 'contribution_status_id',
1560 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1561 if (isset($formValues[$key])) {
1562 unset($formValues[$key]);
1565 $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID
);
1566 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1567 $formValues[$key] = $contribution->$key;
1571 // Offline Contribution.
1572 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1574 // get the required field value only.
1576 $params = $ids = array();
1578 $params['contact_id'] = $this->_contactID
;
1579 $params['currency'] = $this->getCurrency($submittedValues);
1582 'financial_type_id',
1583 'contribution_status_id',
1584 'payment_instrument_id',
1589 foreach ($fields as $f) {
1590 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1594 $params['pcp'] = $pcp;
1596 if (!empty($softParams)) {
1597 $params['soft_credit'] = $softParams;
1598 $params['soft_credit_ids'] = $softIDs;
1601 // CRM-5740 if priceset is used, no need to cleanup money.
1603 $params['skipCleanMoney'] = 1;
1612 foreach ($dates as $d) {
1613 $params[$d] = CRM_Utils_Date
::processDate($formValues[$d], $formValues[$d . '_time'], TRUE);
1616 if (!empty($formValues['is_email_receipt'])) {
1617 $params['receipt_date'] = date("Y-m-d");
1620 if ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Cancelled', 'name')
1621 ||
$params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name')
1623 if (CRM_Utils_System
::isNull(CRM_Utils_Array
::value('cancel_date', $params))) {
1624 $params['cancel_date'] = date('Y-m-d');
1628 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1631 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1632 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1633 if ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Pending', 'name')) {
1634 $params['is_pay_later'] = 1;
1636 elseif ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name')) {
1637 $params['is_pay_later'] = 0;
1640 $ids['contribution'] = $params['id'] = $this->_id
;
1642 // Add Additional common information to formatted params.
1643 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($formValues, $params, $this);
1645 $params['contribution_mode'] = 'participant';
1646 $params['participant_id'] = $pId;
1647 $params['skipLineItem'] = 1;
1649 elseif ($isRelatedId) {
1650 $params['contribution_mode'] = 'membership';
1652 $params['line_item'] = $lineItem;
1653 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array
::value('id', $this->_paymentProcessor
);
1654 if (isset($submittedValues['tax_amount'])) {
1655 $params['tax_amount'] = $submittedValues['tax_amount'];
1657 //create contribution.
1658 if ($isQuickConfig) {
1659 $params['is_quick_config'] = 1;
1661 $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
1663 $contribution = CRM_Contribute_BAO_Contribution
::create($params, $ids);
1665 // process associated membership / participant, CRM-4395
1666 if ($contribution->id
&& $action & CRM_Core_Action
::UPDATE
) {
1667 $this->statusMessage
[] = $this->updateRelatedComponent($contribution->id
,
1668 $contribution->contribution_status_id
,
1669 CRM_Utils_Array
::value('contribution_status_id',
1672 $contribution->receive_date
1676 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1678 $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
1680 //send receipt mail.
1681 if ($contribution->id
&& !empty($formValues['is_email_receipt'])) {
1682 $formValues['contact_id'] = $this->_contactID
;
1683 $formValues['contribution_id'] = $contribution->id
;
1685 $formValues +
= CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
);
1687 // to get 'from email id' for send receipt
1688 $this->fromEmailId
= $formValues['from_email_address'];
1689 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $formValues)) {
1690 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1694 $this->statusMessageTitle
= ts('Saved');
1698 if ($contribution->id
&& !empty($formValues['product_name'][0])) {
1699 CRM_Contribute_Form_AdditionalInfo
::processPremium($submittedValues, $contribution->id
,
1700 $this->_premiumID
, $this->_options
1704 if ($contribution->id
&& isset($submittedValues['note'])) {
1705 CRM_Contribute_Form_AdditionalInfo
::processNote($submittedValues, $this->_contactID
, $contribution->id
, $this->_noteID
);
1708 CRM_Core_Session
::setStatus(implode(' ', $this->statusMessage
), $this->statusMessageTitle
, 'success');
1710 CRM_Contribute_BAO_Contribution
::updateRelatedPledge(
1714 (CRM_Utils_Array
::value('option_type', $formValues) == 2) ?
TRUE : FALSE,
1715 $formValues['total_amount'],
1716 CRM_Utils_Array
::value('total_amount', $this->_defaults
),
1717 $formValues['contribution_status_id'],
1718 CRM_Utils_Array
::value('contribution_status_id', $this->_defaults
)
1720 return $contribution;
1724 * Assign tax calculations to contribution receipts.
1726 * @param array $submittedValues
1727 * @param int $action
1728 * @param array $lineItem
1730 protected function invoicingPostProcessHook($submittedValues, $action, $lineItem) {
1732 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
1733 if (!CRM_Utils_Array
::value('invoicing', $invoiceSettings)) {
1737 $getTaxDetails = FALSE;
1738 if ($action & CRM_Core_Action
::ADD
) {
1741 elseif ($action & CRM_Core_Action
::UPDATE
) {
1742 $line = $this->_lineItems
;
1744 foreach ($line as $key => $value) {
1745 foreach ($value as $v) {
1746 if (isset($taxRate[(string) CRM_Utils_Array
::value('tax_rate', $v)])) {
1747 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $v);
1750 if (isset($v['tax_rate'])) {
1751 $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $v);
1752 $getTaxDetails = TRUE;
1758 if ($action & CRM_Core_Action
::UPDATE
) {
1759 if (isset($submittedValues['tax_amount'])) {
1760 $totalTaxAmount = $submittedValues['tax_amount'];
1763 $totalTaxAmount = $this->_values
['tax_amount'];
1765 $this->assign('totalTaxAmount', $totalTaxAmount);
1766 $this->assign('dataArray', $taxRate);
1769 if (!empty($submittedValues['price_set_id'])) {
1770 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1771 $this->assign('getTaxDetails', $getTaxDetails);
1772 $this->assign('dataArray', $taxRate);
1773 $this->assign('taxTerm', CRM_Utils_Array
::value('tax_term', $invoiceSettings));
1776 $this->assign('totalTaxAmount', CRM_Utils_Array
::value('tax_amount', $submittedValues));
1782 * Calculate non deductible amount.
1785 * if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1786 * if non_deductible_amount does NOT exist - then calculate it depending on:
1787 * $financialType->is_deductible and whether there is a product (premium).
1790 * @param $formValues
1794 protected function calculateNonDeductibleAmount($params, $formValues) {
1795 if (!empty($params['non_deductible_amount'])) {
1796 return $params['non_deductible_amount'];
1798 if (empty($params['non_deductible_amount'])) {
1799 $contributionType = new CRM_Financial_DAO_FinancialType();
1800 $contributionType->id
= $params['financial_type_id'];
1802 if ($contributionType->is_deductible
) {
1804 if (isset($formValues['product_name'][0])) {
1805 $selectProduct = $formValues['product_name'][0];
1807 // if there is a product - compare the value to the contribution amount
1808 if (isset($selectProduct)) {
1809 $productDAO = new CRM_Contribute_DAO_Product();
1810 $productDAO->id
= $selectProduct;
1811 $productDAO->find(TRUE);
1812 // product value exceeds contribution amount
1813 if ($params['total_amount'] < $productDAO->price
) {
1814 return $params['total_amount'];
1816 // product value does NOT exceed contribution amount
1818 return $productDAO->price
;
1821 // contribution is deductible - but there is no product
1826 // contribution is NOT deductible
1828 return $params['total_amount'];