3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
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
189 public $userDisplayName;
192 * Status message to be shown to the user.
196 protected $statusMessage = array();
199 * Status message title to be shown to the user.
201 * Generally the payment processor message title is 'Complete' and offline is 'Saved'
202 * although this might not be a good fit with the broad range of processors.
206 protected $statusMessageTitle;
209 * Set variables up before form is built.
211 public function preProcess() {
212 // Check permission for action.
213 if (!CRM_Core_Permission
::checkActionPermission('CiviContribute', $this->_action
)) {
214 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
217 parent
::preProcess();
219 $this->_formType
= CRM_Utils_Array
::value('formType', $_GET);
222 $this->_priceSetId
= CRM_Utils_Array
::value('priceSetId', $_GET);
223 $this->set('priceSetId', $this->_priceSetId
);
224 $this->assign('priceSetId', $this->_priceSetId
);
226 // Get the pledge payment id
227 $this->_ppID
= CRM_Utils_Request
::retrieve('ppid', 'Positive', $this);
229 $this->assign('action', $this->_action
);
231 // Get the contribution id if update
232 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this);
233 if (!empty($this->_id
)) {
234 $this->assign('contribID', $this->_id
);
237 $this->_context
= CRM_Utils_Request
::retrieve('context', 'String', $this);
238 $this->assign('context', $this->_context
);
240 $this->_compId
= CRM_Utils_Request
::retrieve('compId', 'Positive', $this);
242 $this->_compContext
= CRM_Utils_Request
::retrieve('compContext', 'String', $this);
244 //set the contribution mode.
245 $this->_mode
= CRM_Utils_Request
::retrieve('mode', 'String', $this);
247 $this->assign('contributionMode', $this->_mode
);
248 if ($this->_action
& CRM_Core_Action
::DELETE
) {
252 $this->assign('showCheckNumber', TRUE);
254 $this->_fromEmails
= CRM_Core_BAO_Email
::getFromEmail();
255 $this->assignPaymentRelatedVariables();
257 if (in_array('CiviPledge', CRM_Core_Config
::singleton()->enableComponents
) && !$this->_formType
) {
258 $this->preProcessPledge();
262 $this->showRecordLinkMesssage($this->_id
);
264 $this->_values
= array();
266 // Current contribution id.
268 $this->assignPremiumProduct($this->_id
);
269 $this->buildValuesAndAssignOnline_Note_Type($this->_id
, $this->_values
);
272 // when custom data is included in this page
273 if (!empty($_POST['hidden_custom'])) {
274 $this->applyCustomData('Contribution', CRM_Utils_Array
::value('financial_type_id', $_POST), $this->_id
);
277 $this->_lineItems
= array();
279 if (!empty($this->_compId
) && $this->_compContext
== 'participant') {
280 $this->assign('compId', $this->_compId
);
281 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_compId
);
284 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution', 1, TRUE, TRUE);
286 empty($lineItem) ?
NULL : $this->_lineItems
[] = $lineItem;
289 $this->assign('lineItem', empty($this->_lineItems
) ?
FALSE : $this->_lineItems
);
293 $this->setPageTitle($this->_ppID ?
ts('Credit Card Pledge Payment') : ts('Credit Card Contribution'));
296 $this->setPageTitle($this->_ppID ?
ts('Pledge Payment') : ts('Contribution'));
300 CRM_Contribute_Form_SoftCredit
::preprocess($this);
305 * Set default values.
309 public function setDefaultValues() {
311 $defaults = $this->_values
;
313 // Set defaults for pledge payment.
315 $defaults['total_amount'] = CRM_Utils_Array
::value('scheduled_amount', $this->_pledgeValues
['pledgePayment']);
316 $defaults['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $this->_pledgeValues
);
317 $defaults['currency'] = CRM_Utils_Array
::value('currency', $this->_pledgeValues
);
318 $defaults['option_type'] = 1;
321 if ($this->_action
& CRM_Core_Action
::DELETE
) {
325 $defaults['frequency_interval'] = 1;
326 $defaults['frequency_unit'] = 'month';
328 // Set soft credit defaults.
329 CRM_Contribute_Form_SoftCredit
::setDefaultValues($defaults, $this);
332 $config = CRM_Core_Config
::singleton();
333 // Set default country from config if no country set.
334 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
335 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry
;
338 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
339 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince
;
342 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID
);
343 $defaults = array_merge($defaults, $billingDefaults);
347 $this->_contactID
= $defaults['contact_id'];
350 // Set $newCredit variable in template to control whether link to credit card mode is included.
351 $this->assign('newCredit', CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments());
353 // Fix the display of the monetary value, CRM-4038.
354 if (isset($defaults['total_amount'])) {
355 if (!empty($defaults['tax_amount'])) {
356 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
357 if (!(CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails))) {
358 $defaults['total_amount'] = CRM_Utils_Money
::format($defaults['total_amount'] - $defaults['tax_amount'], NULL, '%a');
362 $defaults['total_amount'] = CRM_Utils_Money
::format($defaults['total_amount'], NULL, '%a');
366 if (isset($defaults['non_deductible_amount'])) {
367 $defaults['non_deductible_amount'] = CRM_Utils_Money
::format($defaults['non_deductible_amount'], NULL, '%a');
370 if (isset($defaults['fee_amount'])) {
371 $defaults['fee_amount'] = CRM_Utils_Money
::format($defaults['fee_amount'], NULL, '%a');
374 if (isset($defaults['net_amount'])) {
375 $defaults['net_amount'] = CRM_Utils_Money
::format($defaults['net_amount'], NULL, '%a');
378 if ($this->_contributionType
) {
379 $defaults['financial_type_id'] = $this->_contributionType
;
382 if (empty($defaults['payment_instrument_id'])) {
383 $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup
::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
386 if (!empty($defaults['is_test'])) {
387 $this->assign('is_test', TRUE);
390 $this->assign('showOption', TRUE);
391 // For Premium section.
392 if ($this->_premiumID
) {
393 $this->assign('showOption', FALSE);
394 $options = isset($this->_options
[$this->_productDAO
->product_id
]) ?
$this->_options
[$this->_productDAO
->product_id
] : "";
396 $this->assign('showOption', TRUE);
398 $options_key = CRM_Utils_Array
::key($this->_productDAO
->product_option
, $options);
400 $defaults['product_name'] = array($this->_productDAO
->product_id
, trim($options_key));
403 $defaults['product_name'] = array($this->_productDAO
->product_id
);
405 if ($this->_productDAO
->fulfilled_date
) {
406 list($defaults['fulfilled_date']) = CRM_Utils_Date
::setDateDefaults($this->_productDAO
->fulfilled_date
);
410 if (isset($this->userEmail
)) {
411 $this->assign('email', $this->userEmail
);
414 if (!empty($defaults['is_pay_later'])) {
415 $this->assign('is_pay_later', TRUE);
417 $this->assign('contribution_status_id', CRM_Utils_Array
::value('contribution_status_id', $defaults));
425 foreach ($dates as $key) {
426 if (!empty($defaults[$key])) {
427 list($defaults[$key], $defaults[$key . '_time'])
428 = CRM_Utils_Date
::setDateDefaults(CRM_Utils_Array
::value($key, $defaults), 'activityDateTime');
432 if (!$this->_id
&& empty($defaults['receive_date'])) {
433 list($defaults['receive_date'],
434 $defaults['receive_date_time']
435 ) = CRM_Utils_Date
::setDateDefaults(NULL, 'activityDateTime');
438 $this->assign('receive_date', CRM_Utils_Date
::processDate(CRM_Utils_Array
::value('receive_date', $defaults),
439 CRM_Utils_Array
::value('receive_date_time', $defaults)
441 $currency = CRM_Utils_Array
::value('currency', $defaults);
442 $this->assign('currency', $currency);
443 // Hack to get currency info to the js layer. CRM-11440.
444 CRM_Utils_Money
::format(1);
445 $this->assign('currencySymbol', CRM_Utils_Array
::value($currency, CRM_Utils_Money
::$_currencySymbols));
446 $this->assign('totalAmount', CRM_Utils_Array
::value('total_amount', $defaults));
448 // Inherit campaign from pledge.
449 if ($this->_ppID
&& !empty($this->_pledgeValues
['campaign_id'])) {
450 $defaults['campaign_id'] = $this->_pledgeValues
['campaign_id'];
453 $this->_defaults
= $defaults;
458 * Build the form object.
460 public function buildQuickForm() {
464 //tax rate from financialType
465 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant
::getTaxRates()));
466 $this->assign('currencies', json_encode(CRM_Core_OptionGroup
::values('currencies_enabled')));
468 // build price set form.
469 $buildPriceSet = FALSE;
470 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
471 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
472 $this->assign('invoicing', $invoicing);
474 // display tax amount on edit contribution page
475 if ($invoicing && $this->_action
& CRM_Core_Action
::UPDATE
&& isset($this->_values
['tax_amount'])) {
476 $this->assign('totalTaxAmount', $this->_values
['tax_amount']);
479 if (empty($this->_lineItems
) &&
480 ($this->_priceSetId ||
!empty($_POST['price_set_id']))
482 $buildPriceSet = TRUE;
483 $getOnlyPriceSetElements = TRUE;
484 if (!$this->_priceSetId
) {
485 $this->_priceSetId
= $_POST['price_set_id'];
486 $getOnlyPriceSetElements = FALSE;
489 $this->set('priceSetId', $this->_priceSetId
);
490 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
492 // get only price set form elements.
493 if ($getOnlyPriceSetElements) {
497 // use to build form during form rule.
498 $this->assign('buildPriceSet', $buildPriceSet);
500 $defaults = $this->_values
;
501 $additionalDetailFields = array(
505 'non_deductible_amount',
509 foreach ($additionalDetailFields as $key) {
510 if (!empty($defaults[$key])) {
511 $defaults['hidden_AdditionalDetail'] = 1;
516 if ($this->_productDAO
) {
517 if ($this->_productDAO
->product_id
) {
518 $defaults['hidden_Premium'] = 1;
522 if ($this->_noteID
&&
523 isset($this->_values
['note'])
525 $defaults['hidden_AdditionalDetail'] = 1;
529 ts('Additional Details') => 'AdditionalDetail',
532 //Add Premium pane only if Premium is exists.
533 $dao = new CRM_Contribute_DAO_Product();
536 if ($dao->find(TRUE)) {
537 $paneNames[ts('Premium Information')] = 'Premium';
541 if (CRM_Core_Payment_Form
::buildPaymentForm($this, $this->_paymentProcessor
, FALSE, TRUE) == TRUE) {
542 if (!empty($this->_recurPaymentProcessors
)) {
543 $buildRecurBlock = TRUE;
545 // ppID denotes a pledge payment.
546 foreach ($this->_paymentProcessors
as $processor) {
547 if (!empty($processor['is_recur']) && !empty($processor['object']) && $processor['object']->supports('recurContributionsForPledges')) {
548 $buildRecurBlock = TRUE;
551 $buildRecurBlock = FALSE;
554 if ($buildRecurBlock) {
555 CRM_Contribute_Form_Contribution_Main
::buildRecur($this);
556 $this->setDefaults(array('is_recur' => 0));
557 $this->assign('buildRecurBlock', TRUE);
558 $recurJs = array('onChange' => "buildRecurBlock( this.value ); return false;");
564 foreach ($paneNames as $name => $type) {
565 $allPanes[$name] = $this->generatePane($type, $defaults);
568 $qfKey = $this->controller
->_key
;
569 $this->assign('qfKey', $qfKey);
570 $this->assign('allPanes', $allPanes);
572 $this->addFormRule(array('CRM_Contribute_Form_Contribution', 'formRule'), $this);
574 if ($this->_formType
) {
575 $this->assign('formType', $this->_formType
);
579 $this->applyFilter('__ALL__', 'trim');
581 if ($this->_action
& CRM_Core_Action
::DELETE
) {
582 $this->addButtons(array(
585 'name' => ts('Delete'),
586 'spacing' => ' ',
591 'name' => ts('Cancel'),
598 //need to assign custom data type and subtype to the template
599 $this->assign('customDataType', 'Contribution');
600 $this->assign('customDataSubType', $this->_contributionType
);
601 $this->assign('entityID', $this->_id
);
603 if ($this->_context
== 'standalone') {
604 $this->addEntityRef('contact_id', ts('Contact'), array(
606 'api' => array('extra' => array('email')),
610 $attributes = CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Contribution');
612 $financialType = $this->add('select', 'financial_type_id',
613 ts('Financial Type'),
614 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::financialType(),
616 array('onChange' => "CRM.buildCustomData( 'Contribution', this.value );")
618 $paymentInstrument = FALSE;
620 $paymentInstrument = $this->add('select', 'payment_instrument_id',
621 ts('Payment Method'),
622 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::paymentInstrument(),
623 TRUE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
627 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), array('class' => 'twelve') +
$attributes['trxn_id']);
629 //add receipt for offline contribution
630 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
632 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
634 $status = CRM_Contribute_PseudoConstant
::contributionStatus();
636 // suppressing contribution statuses that are NOT relevant to pledges (CRM-5169)
637 $statusName = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
644 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
647 elseif ((!$this->_ppID
&& $this->_id
) ||
!$this->_id
) {
648 $suppressFlag = FALSE;
650 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
651 if (CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails)) {
652 $suppressFlag = TRUE;
655 if (!$suppressFlag) {
660 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
664 unset($status[CRM_Utils_Array
::key('Overdue', $statusName)]);
669 $contributionStatus = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_id
, 'contribution_status_id');
670 $name = CRM_Utils_Array
::value($contributionStatus, $statusName);
675 unset($status[CRM_Utils_Array
::key('In Progress', $statusName)]);
676 unset($status[CRM_Utils_Array
::key('Pending', $statusName)]);
677 unset($status[CRM_Utils_Array
::key('Failed', $statusName)]);
682 unset($status[CRM_Utils_Array
::key('Refunded', $statusName)]);
693 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
699 unset($status[CRM_Utils_Array
::key('Refunded', $statusName)]);
702 $this->add('select', 'contribution_status_id',
703 ts('Contribution Status'),
709 $this->addDateTime('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
711 if ($this->_online
) {
712 $this->assign('hideCalender', TRUE);
714 $checkNumber = $this->add('text', 'check_number', ts('Check Number'), $attributes['check_number']);
716 $this->addDateTime('receipt_date', ts('Receipt Date'), FALSE, array('formatType' => 'activityDateTime'));
717 $this->addDateTime('cancel_date', ts('Cancelled / Refunded Date'), FALSE, array('formatType' => 'activityDateTime'));
719 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
721 $element = $this->add('select',
722 'payment_processor_id',
723 ts('Payment Processor'),
729 if ($this->_online
) {
734 if (empty($this->_lineItems
)) {
735 $buildPriceSet = FALSE;
736 $priceSets = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute');
737 if (!empty($priceSets) && !$this->_ppID
) {
738 $buildPriceSet = TRUE;
741 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
742 // and if we already have line items for that participant. CRM-5095
743 if ($buildPriceSet && $this->_id
) {
744 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
745 $pledgePaymentId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
750 if ($pledgePaymentId) {
751 $buildPriceSet = FALSE;
753 if ($participantID = CRM_Utils_Array
::value('participant', $componentDetails)) {
754 $participantLI = CRM_Price_BAO_LineItem
::getLineItems($participantID);
755 if (!CRM_Utils_System
::isNull($participantLI)) {
756 $buildPriceSet = FALSE;
761 $hasPriceSets = FALSE;
762 if ($buildPriceSet) {
763 $hasPriceSets = TRUE;
764 // CRM-16451: set financial type of 'Price Set' in back office contribution
765 // instead of selecting manually
766 $financialTypeIds = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute', 'financial_type_id');
767 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
769 '' => ts('Choose price set'),
771 NULL, array('onchange' => "buildAmount( this.value, " . json_encode($financialTypeIds) . ");")
773 if ($this->_online
&& !($this->_action
& CRM_Core_Action
::UPDATE
)) {
777 $this->assign('hasPriceSets', $hasPriceSets);
778 $currencyFreeze = FALSE;
779 if (!($this->_action
& CRM_Core_Action
::UPDATE
)) {
780 if ($this->_online ||
$this->_ppID
) {
781 $attributes['total_amount'] = array_merge($attributes['total_amount'], array(
783 'style' => "background-color:#EBECE4",
785 $optionTypes = array(
786 '1' => ts('Adjust Pledge Payment Schedule?'),
787 '2' => ts('Adjust Total Pledge Amount?'),
789 $this->addRadio('option_type',
795 $currencyFreeze = TRUE;
799 $totalAmount = $this->addMoney('total_amount',
801 ($hasPriceSets) ?
FALSE : TRUE,
802 $attributes['total_amount'],
803 TRUE, 'currency', NULL, $currencyFreeze
807 $this->add('text', 'source', ts('Source'), CRM_Utils_Array
::value('source', $attributes));
809 // CRM-7362 --add campaigns.
810 CRM_Campaign_BAO_Campaign
::addCampaign($this, CRM_Utils_Array
::value('campaign_id', $this->_values
));
812 CRM_Contribute_Form_SoftCredit
::buildQuickForm($this);
816 $js = array('onclick' => "return verify( );");
819 $mailingInfo = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
822 $this->assign('outBound_option', $mailingInfo['outBound_option']);
824 $this->addButtons(array(
827 'name' => ts('Save'),
833 'name' => ts('Save and New'),
839 'name' => ts('Cancel'),
844 // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
845 // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
846 if ($this->_id
&& $this->_values
['contribution_status_id'] == array_search('Cancelled', $statusName)) {
848 $totalAmount->freeze();
850 $checkNumber->freeze();
851 $paymentInstrument->freeze();
853 $financialType->freeze();
856 // if contribution is related to membership or participant freeze Financial Type, Amount
857 if ($this->_id
&& isset($this->_values
['tax_amount'])) {
858 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
859 if (CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails)) {
861 $totalAmount->freeze();
863 $financialType->freeze();
864 $this->assign('freezeFinancialType', TRUE);
868 if ($this->_action
& CRM_Core_Action
::VIEW
) {
876 * @param array $fields
877 * The input form values.
878 * @param array $files
879 * The uploaded files if any.
883 * true if no errors, else array of errors
885 public static function formRule($fields, $files, $self) {
887 // Check for Credit Card Contribution.
889 if (empty($fields['payment_processor_id'])) {
890 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
893 // validate payment instrument (e.g. credit card number)
894 CRM_Core_Payment_Form
::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, $self);
898 // Do the amount validations.
899 if (empty($fields['total_amount']) && empty($self->_lineItems
)) {
900 if ($priceSetId = CRM_Utils_Array
::value('price_set_id', $fields)) {
901 CRM_Price_BAO_PriceField
::priceSetValidation($priceSetId, $fields, $errors);
905 $softErrors = CRM_Contribute_Form_SoftCredit
::formRule($fields, $errors, $self);
907 if (!empty($fields['total_amount']) && (!empty($fields['net_amount']) ||
!empty($fields['fee_amount']))) {
908 $sum = CRM_Utils_Rule
::cleanMoney($fields['net_amount']) + CRM_Utils_Rule
::cleanMoney($fields['fee_amount']);
909 // For taxable contribution we need to deduct taxable amount from
910 // (net amount + fee amount) before comparing it with total amount
911 if (!empty($self->_values
['tax_amount'])) {
912 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($self->_id
);
913 if (!(CRM_Utils_Array
::value('membership', $componentDetails) ||
914 CRM_Utils_Array
::value('participant', $componentDetails))
916 $sum = CRM_Utils_Money
::format($sum - $self->_values
['tax_amount'], NULL, '%a');
919 if (CRM_Utils_Rule
::cleanMoney($fields['total_amount']) != $sum) {
920 $errors['total_amount'] = ts('The sum of fee amount and net amount must be equal to total amount');
924 //CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
925 CRM_Contribute_BAO_ContributionRecur
::validateRecurContribution($fields, $files, $self, $errors);
927 // Form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
928 if (($self->_action
& CRM_Core_Action
::UPDATE
)
930 && $self->_values
['contribution_status_id'] != $fields['contribution_status_id']
932 CRM_Contribute_BAO_Contribution
::checkStatusValidation($self->_values
, $fields, $errors);
934 // CRM-16015, add form-rule to restrict change of financial type if using price field of different financial type
935 if (($self->_action
& CRM_Core_Action
::UPDATE
)
937 && $self->_values
['financial_type_id'] != $fields['financial_type_id']
939 CRM_Contribute_BAO_Contribution
::checkFinancialTypeChange(NULL, $self->_id
, $errors);
941 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
942 if (!empty($fields['fee_amount']) && !empty($fields['financial_type_id']) && $financialType = CRM_Contribute_BAO_Contribution
::validateFinancialType($fields['financial_type_id'])) {
943 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
946 // $trxn_id must be unique CRM-13919
947 if (!empty($fields['trxn_id'])) {
948 $queryParams = array(1 => array($fields['trxn_id'], 'String'));
949 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
951 $queryParams[2] = array((int) $self->_id
, 'Integer');
952 $query .= ' and id !=%2';
954 $tCnt = CRM_Core_DAO
::singleValueQuery($query, $queryParams);
956 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', array(1 => $fields['trxn_id']));
960 $errors = array_merge($errors, $softErrors);
965 * Process the form submission.
967 public function postProcess() {
968 if ($this->_action
& CRM_Core_Action
::DELETE
) {
969 CRM_Contribute_BAO_Contribution
::deleteContribution($this->_id
);
970 CRM_Core_Session
::singleton()->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
971 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
975 // Get the submitted form values.
976 $submittedValues = $this->controller
->exportValues($this->_name
);
979 $contribution = $this->submit($submittedValues, $this->_action
, $this->_ppID
);
981 catch (PaymentProcessorException
$e) {
982 // Set the contribution mode.
983 $urlParams = "action=add&cid={$this->_contactID}";
985 $urlParams .= "&mode={$this->_mode}";
987 if (!empty($this->_ppID
)) {
988 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
991 CRM_Core_Error
::statusBounce($e->getMessage(), $urlParams, ts('Payment Processor Error'));
993 $session = CRM_Core_Session
::singleton();
994 $buttonName = $this->controller
->getButtonName();
995 if ($this->_context
== 'standalone') {
996 if ($buttonName == $this->getButtonName('upload', 'new')) {
997 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contribute/add',
998 'reset=1&action=add&context=standalone'
1002 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
1003 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1007 elseif ($this->_context
== 'contribution' && $this->_mode
&& $buttonName == $this->getButtonName('upload', 'new')) {
1008 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
1009 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
1012 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1013 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
1014 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
1018 //store contribution ID if not yet set (on create)
1019 if (empty($this->_id
) && !empty($contribution->id
)) {
1020 $this->_id
= $contribution->id
;
1025 * Process credit card payment.
1027 * @param array $submittedValues
1028 * @param array $lineItem
1030 * @param int $contactID
1033 * @return bool|\CRM_Contribute_DAO_Contribution
1034 * @throws \CRM_Core_Exception
1035 * @throws \Civi\Payment\Exception\PaymentProcessorException
1037 protected function processCreditCard($submittedValues, $lineItem, $contactID) {
1038 $isTest = ($this->_mode
== 'test') ?
1 : 0;
1039 // CRM-12680 set $_lineItem if its not set
1040 // @todo - I don't believe this would ever BE set. I can't find anywhere in the code.
1041 // It would be better to pass line item out to functions than $this->_lineItem as
1042 // we don't know what is being changed where.
1043 if (empty($this->_lineItem
) && !empty($lineItem)) {
1044 $this->_lineItem
= $lineItem;
1047 $this->_paymentObject
= Civi\Payment\System
::singleton()->getById($submittedValues['payment_processor_id']);
1048 $this->_paymentProcessor
= $this->_paymentObject
->getPaymentProcessor();
1050 // Set source if not set
1051 if (empty($submittedValues['source'])) {
1052 $userID = CRM_Core_Session
::singleton()->get('userID');
1053 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1056 $submittedValues['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
1059 $params = $submittedValues;
1060 $this->_params
= array_merge($this->_params
, $submittedValues);
1062 // Mapping requiring documentation.
1063 $this->_params
['payment_processor'] = $submittedValues['payment_processor_id'];
1065 $now = date('YmdHis');
1067 // we need to retrieve email address
1068 if ($this->_context
== 'standalone' && !empty($submittedValues['is_email_receipt'])) {
1069 list($this->userDisplayName
,
1071 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contactID);
1072 $this->assign('displayName', $this->userDisplayName
);
1075 $this->_contributorEmail
= $this->userEmail
;
1076 $this->_contributorContactID
= $contactID;
1077 $this->processBillingAddress();
1078 if (!empty($params['source'])) {
1079 unset($params['source']);
1082 $this->_params
['amount'] = $this->_params
['total_amount'];
1083 $this->_params
['amount_level'] = 0;
1084 $this->_params
['description'] = ts("Contribution submitted by a staff person using contributor's credit card");
1085 $this->_params
['currencyID'] = CRM_Utils_Array
::value('currency',
1087 CRM_Core_Config
::singleton()->defaultCurrency
1090 if (!empty($this->_params
['receive_date'])) {
1091 $this->_params
['receive_date'] = CRM_Utils_Date
::processDate($this->_params
['receive_date'], $this->_params
['receive_date_time']);
1094 $this->_params
['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $params);
1095 $this->_params
['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $params);
1096 $this->_params
['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $params);
1098 //Add common data to formatted params
1099 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
1101 if (empty($this->_params
['invoice_id'])) {
1102 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
1105 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
1108 // At this point we've created a contact and stored its address etc
1109 // all the payment processors expect the name and address to be in the
1110 // so we copy stuff over to first_name etc.
1111 $paymentParams = $this->_params
;
1112 $paymentParams['contactID'] = $contactID;
1113 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
1115 $financialType = new CRM_Financial_DAO_FinancialType();
1116 $financialType->id
= $params['financial_type_id'];
1118 // Add some financial type details to the params list
1119 // if folks need to use it.
1120 $paymentParams['contributionType_name'] = $this->_params
['contributionType_name'] = $financialType->name
;
1121 $paymentParams['contributionPageID'] = NULL;
1123 if (!empty($this->_params
['is_email_receipt'])) {
1124 $paymentParams['email'] = $this->userEmail
;
1125 $paymentParams['is_email_receipt'] = 1;
1128 $paymentParams['is_email_receipt'] = 0;
1129 $this->_params
['is_email_receipt'] = 0;
1131 if (!empty($this->_params
['receive_date'])) {
1132 $paymentParams['receive_date'] = $this->_params
['receive_date'];
1135 $this->_params
['receive_date'] = $now;
1137 if (!empty($this->_params
['is_email_receipt'])) {
1138 $this->_params
['receipt_date'] = $now;
1141 $this->_params
['receipt_date'] = CRM_Utils_Date
::processDate($this->_params
['receipt_date'],
1142 $params['receipt_date_time'], TRUE
1146 $this->set('params', $this->_params
);
1148 $this->assign('receive_date', $this->_params
['receive_date']);
1150 // Result has all the stuff we need
1151 // lets archive it to a financial transaction
1152 if ($financialType->is_deductible
) {
1153 $this->assign('is_deductible', TRUE);
1154 $this->set('is_deductible', TRUE);
1156 $contributionParams = array(
1157 'contact_id' => $contactID,
1158 'line_item' => $lineItem,
1159 'is_test' => $isTest,
1160 'campaign_id' => CRM_Utils_Array
::value('campaign_id', $this->_params
),
1161 'contribution_page_id' => CRM_Utils_Array
::value('contribution_page_id', $this->_params
),
1162 'source' => CRM_Utils_Array
::value('source', $paymentParams, CRM_Utils_Array
::value('description', $paymentParams)),
1163 'thankyou_date' => CRM_Utils_Array
::value('thankyou_date', $this->_params
),
1166 if (empty($paymentParams['is_pay_later'])) {
1167 // @todo look up payment_instrument_id on payment processor table.
1168 $contributionParams['payment_instrument_id'] = 1;
1171 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processFormContribution($this,
1174 $contributionParams,
1180 $paymentParams['contributionID'] = $contribution->id
;
1181 $paymentParams['contributionTypeID'] = $contribution->financial_type_id
;
1182 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
1183 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1185 if ($paymentParams['amount'] > 0.0) {
1186 // force a re-get of the payment processor in case the form changed it, CRM-7179
1187 // NOTE - I expect this is obsolete.
1188 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
1190 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id');
1191 $result = $payment->doPayment($paymentParams, 'contribute');
1192 $this->assign('trxn_id', $result['trxn_id']);
1193 $contribution->trxn_id
= $result['trxn_id'];
1194 /* Our scenarios here are
1195 * 1) the payment failed & an Exception should have been thrown
1196 * 2) the payment succeeded but the payment is not immediate (for example a recurring payment
1197 * with a delayed start)
1198 * 3) the payment succeeded with an immediate payment.
1200 * The doPayment function ensures that payment_status_id is always set
1201 * as historically we have had to guess from the context - ie doDirectPayment
1202 * = error or success, unless it is a recurring contribution in which case it is pending.
1204 if ($result['payment_status_id'] == array_search('Completed', $statuses)) {
1206 civicrm_api3('contribution', 'completetransaction', array(
1207 'id' => $contribution->id
,
1208 'trxn_id' => $result['trxn_id'],
1209 'payment_processor_id' => $this->_paymentProcessor
['id'],
1210 'is_transactional' => FALSE,
1211 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $result),
1213 // This has now been set to 1 in the DB - declare it here also
1214 $contribution->contribution_status_id
= 1;
1216 catch (CiviCRM_API3_Exception
$e) {
1217 if ($e->getErrorCode() != 'contribution_completed') {
1218 throw new CRM_Core_Exception('Failed to update contribution in database');
1223 // Save the trxn_id.
1224 $contribution->save();
1227 catch (PaymentProcessorException
$e) {
1228 CRM_Contribute_BAO_Contribution
::failPayment($contribution->id
, $paymentParams['contactID'], $e->getMessage());
1229 throw new PaymentProcessorException($e->getMessage());
1232 // Send receipt mail.
1233 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1234 if ($contribution->id
&& !empty($this->_params
['is_email_receipt'])) {
1235 $this->_params
['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $result);
1236 $this->_params
['contact_id'] = $contactID;
1237 $this->_params
['contribution_id'] = $contribution->id
;
1238 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $this->_params
, TRUE)) {
1239 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1243 return $contribution;
1247 * Generate the data to construct a snippet based pane.
1249 * This form also assigns the showAdditionalInfo var based on historical code.
1250 * This appears to mean 'there is a pane to show'.
1252 * @param string $type
1253 * Type of Pane - this is generally used to determine the function name used to build it
1254 * - e.g CreditCard, AdditionalDetail
1255 * @param array $defaults
1258 * We aim to further refactor & simplify this but currently
1260 * - should additional info be shown?
1262 protected function generatePane($type, $defaults) {
1263 $urlParams = "snippet=4&formType={$type}";
1265 $urlParams .= "&mode={$this->_mode}";
1269 if ($type == 'CreditCard' ||
1270 $type == 'DirectDebit'
1276 'url' => CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams),
1281 // See if we need to include this paneName in the current form.
1282 if ($this->_formType
== $type ||
!empty($_POST["hidden_{$type}"]) ||
1283 CRM_Utils_Array
::value("hidden_{$type}", $defaults)
1285 $this->assign('showAdditionalInfo', TRUE);
1286 $pane['open'] = 'true';
1289 if ($type == 'CreditCard' ||
$type == 'DirectDebit') {
1290 // @todo would be good to align tpl name with form name...
1291 // @todo document why this hidden variable is required.
1292 $this->add('hidden', 'hidden_' . $type, 1);
1296 $additionalInfoFormFunction = 'build' . $type;
1297 CRM_Contribute_Form_AdditionalInfo
::$additionalInfoFormFunction($this);
1303 * Wrapper for unit testing the post process submit function.
1305 * (If we expose through api we can get default additions 'for free').
1307 * @param array $params
1308 * @param int $action
1309 * @param string|null $creditCardMode
1311 * @throws \CiviCRM_API3_Exception
1313 public function testSubmit($params, $action, $creditCardMode = NULL) {
1315 'soft_credit_contact_id' => array(),
1316 'receipt_date' => '',
1317 'receipt_date_time' => '',
1318 'cancel_date' => '',
1319 'cancel_date_time' => '',
1320 'hidden_Premium' => 1,
1323 if (!empty($params['id'])) {
1324 $existingContribution = civicrm_api3('contribution', 'getsingle', array(
1325 'id' => $params['id'],
1327 $this->_id
= $params['id'];
1330 $existingContribution = array();
1333 $this->_defaults
['contribution_status_id'] = CRM_Utils_Array
::value('contribution_status_id',
1334 $existingContribution
1337 $this->_defaults
['total_amount'] = CRM_Utils_Array
::value('total_amount',
1338 $existingContribution
1341 if ($creditCardMode) {
1342 $this->_mode
= $creditCardMode;
1345 // Required because processCreditCard calls set method on this.
1346 $_SERVER['REQUEST_METHOD'] = 'GET';
1347 $this->controller
= new CRM_Core_Controller();
1349 CRM_Contribute_Form_AdditionalInfo
::buildPremium($this);
1351 $this->_fields
= array();
1352 $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array
::value('pledge_payment_id', $params));
1357 * @param array $submittedValues
1359 * @param int $action
1361 * - CRM_Core_Action::UPDATE
1363 * @param $pledgePaymentID
1366 * @throws \Exception
1368 protected function submit($submittedValues, $action, $pledgePaymentID) {
1369 $softParams = $softIDs = array();
1370 $pId = $contribution = $isRelatedId = FALSE;
1371 $this->_params
= $submittedValues;
1372 $this->beginPostProcess();
1374 if (!empty($submittedValues['price_set_id']) && $action & CRM_Core_Action
::UPDATE
) {
1375 $line = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution');
1376 $lineID = key($line);
1377 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array
::value('price_field_id', $line[$lineID]), 'price_set_id');
1378 $quickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1380 CRM_Price_BAO_LineItem
::deleteLineItems($this->_id
, 'civicrm_contribution');
1384 // Process price set and get total amount and line items.
1385 $lineItem = array();
1386 $priceSetId = CRM_Utils_Array
::value('price_set_id', $submittedValues);
1387 if (empty($priceSetId) && !$this->_id
) {
1388 $this->_priceSetId
= $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1389 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
1390 $fieldID = key($this->_priceSet
['fields']);
1391 $fieldValueId = key($this->_priceSet
['fields'][$fieldID]['options']);
1392 $this->_priceSet
['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1393 $submittedValues['price_' . $fieldID] = 1;
1397 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
1398 $submittedValues, $lineItem[$priceSetId]);
1400 // Unset tax amount for offline 'is_quick_config' contribution.
1401 if ($this->_priceSet
['is_quick_config'] &&
1402 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant
::getTaxRates())
1404 unset($submittedValues['tax_amount']);
1406 $submittedValues['total_amount'] = CRM_Utils_Array
::value('amount', $submittedValues);
1409 if ($this->_compId
) {
1410 if ($this->_context
== 'participant') {
1411 $pId = $this->_compId
;
1413 elseif ($this->_context
== 'membership') {
1414 $isRelatedId = TRUE;
1417 $pId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id
, 'participant_id', 'contribution_id');
1421 $contributionDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1422 if (array_key_exists('membership', $contributionDetails)) {
1423 $isRelatedId = TRUE;
1425 elseif (array_key_exists('participant', $contributionDetails)) {
1426 $pId = $contributionDetails['participant'];
1430 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id
) {
1431 // CRM-10117 update the line items for participants.
1433 $entityTable = 'participant';
1435 $isRelatedId = FALSE;
1436 $participantParams = array(
1437 'fee_amount' => $submittedValues['total_amount'],
1440 CRM_Event_BAO_Participant
::add($participantParams);
1441 if (empty($this->_lineItems
)) {
1442 $this->_lineItems
[] = CRM_Price_BAO_LineItem
::getLineItems($entityID, 'participant', 1);
1446 $entityTable = 'contribution';
1447 $entityID = $this->_id
;
1450 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, $entityTable, NULL, TRUE, $isRelatedId);
1451 foreach (array_keys($lineItems) as $id) {
1452 $lineItems[$id]['id'] = $id;
1454 $itemId = key($lineItems);
1455 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1456 $this->_priceSetId
= CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1459 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1460 //CRM-16833: Ensure tax is applied only once for membership conribution, when status changed.(e.g Pending to Completed).
1461 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1462 if (!CRM_Utils_Array
::value('membership', $componentDetails) ||
!CRM_Utils_Array
::value('participant', $componentDetails)) {
1463 if (!($this->_action
& CRM_Core_Action
::UPDATE
&& (($this->_defaults
['contribution_status_id'] != $submittedValues['contribution_status_id'])))) {
1464 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule
::cleanMoney(CRM_Utils_Array
::value('total_amount', $submittedValues));
1468 // Update line total and total amount with tax on edit.
1469 $financialItemsId = CRM_Core_PseudoConstant
::getTaxRates();
1470 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1471 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1474 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1475 $submittedValues['tax_amount'] = 'null';
1477 if ($lineItems[$itemId]['tax_rate']) {
1478 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total'];
1479 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] +
$lineItems[$itemId]['tax_amount'];
1480 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1483 // CRM-10117 update the line items for participants.
1484 if (!empty($lineItems[$itemId]['price_field_id'])) {
1485 $lineItem[$this->_priceSetId
] = $lineItems;
1490 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1493 //CRM-11529 for quick config back office transactions
1494 //when financial_type_id is passed in form, update the
1495 //line items with the financial type selected in form
1496 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array
::value($this->_priceSetId
, $lineItem)
1498 foreach ($lineItem[$this->_priceSetId
] as &$values) {
1499 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1503 if (!isset($submittedValues['total_amount'])) {
1504 $submittedValues['total_amount'] = CRM_Utils_Array
::value('total_amount', $this->_values
);
1506 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
1508 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
1509 if ($this->_id
&& count($isEmpty) == 1 && key($isEmpty) == NULL) {
1510 //Delete existing soft credit records if soft credit list is empty on update
1511 CRM_Contribute_BAO_ContributionSoft
::del(array('contribution_id' => $this->_id
, 'pcp_id' => 0));
1514 // set the contact, when contact is selected
1515 if (!empty($submittedValues['contact_id'])) {
1516 $this->_contactID
= $submittedValues['contact_id'];
1519 $formValues = $submittedValues;
1521 // Credit Card Contribution.
1523 $paramsSetByPaymentProcessingSubsystem = array(
1525 'payment_instrument_id',
1526 'contribution_status_id',
1530 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1531 if (isset($formValues[$key])) {
1532 unset($formValues[$key]);
1535 $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID
);
1536 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1537 $formValues[$key] = $contribution->$key;
1541 // Offline Contribution.
1542 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1544 // get the required field value only.
1546 $params = $ids = array();
1548 $params['contact_id'] = $this->_contactID
;
1549 $params['currency'] = $this->getCurrency($submittedValues);
1551 //format soft-credit/pcp param first
1552 CRM_Contribute_BAO_ContributionSoft
::formatSoftCreditParams($submittedValues, $this);
1553 $params = array_merge($params, $submittedValues);
1556 'financial_type_id',
1557 'contribution_status_id',
1558 'payment_instrument_id',
1563 foreach ($fields as $f) {
1564 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1567 // CRM-5740 if priceset is used, no need to cleanup money.
1569 $params['skipCleanMoney'] = 1;
1578 foreach ($dates as $d) {
1579 $params[$d] = CRM_Utils_Date
::processDate($formValues[$d], $formValues[$d . '_time'], TRUE);
1582 if (!empty($formValues['is_email_receipt'])) {
1583 $params['receipt_date'] = date("Y-m-d");
1586 if ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Cancelled', 'name')
1587 ||
$params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name')
1589 if (CRM_Utils_System
::isNull(CRM_Utils_Array
::value('cancel_date', $params))) {
1590 $params['cancel_date'] = date('Y-m-d');
1594 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1597 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1598 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1599 if ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Pending', 'name')) {
1600 $params['is_pay_later'] = 1;
1602 elseif ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name')) {
1603 $params['is_pay_later'] = 0;
1606 $ids['contribution'] = $params['id'] = $this->_id
;
1608 // Add Additional common information to formatted params.
1609 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($formValues, $params, $this);
1611 $params['contribution_mode'] = 'participant';
1612 $params['participant_id'] = $pId;
1613 $params['skipLineItem'] = 1;
1615 elseif ($isRelatedId) {
1616 $params['contribution_mode'] = 'membership';
1618 $params['line_item'] = $lineItem;
1619 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array
::value('id', $this->_paymentProcessor
);
1620 if (isset($submittedValues['tax_amount'])) {
1621 $params['tax_amount'] = $submittedValues['tax_amount'];
1623 //create contribution.
1624 if ($isQuickConfig) {
1625 $params['is_quick_config'] = 1;
1627 $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
1629 $contribution = CRM_Contribute_BAO_Contribution
::create($params, $ids);
1631 // process associated membership / participant, CRM-4395
1632 if ($contribution->id
&& $action & CRM_Core_Action
::UPDATE
) {
1633 $this->statusMessage
[] = $this->updateRelatedComponent($contribution->id
,
1634 $contribution->contribution_status_id
,
1635 CRM_Utils_Array
::value('contribution_status_id',
1638 $contribution->receive_date
1642 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1644 $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
1646 //send receipt mail.
1647 if ($contribution->id
&& !empty($formValues['is_email_receipt'])) {
1648 $formValues['contact_id'] = $this->_contactID
;
1649 $formValues['contribution_id'] = $contribution->id
;
1651 $formValues +
= CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
);
1653 // to get 'from email id' for send receipt
1654 $this->fromEmailId
= $formValues['from_email_address'];
1655 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $formValues)) {
1656 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1660 $this->statusMessageTitle
= ts('Saved');
1664 if ($contribution->id
&& !empty($formValues['product_name'][0])) {
1665 CRM_Contribute_Form_AdditionalInfo
::processPremium($submittedValues, $contribution->id
,
1666 $this->_premiumID
, $this->_options
1670 if ($contribution->id
&& isset($submittedValues['note'])) {
1671 CRM_Contribute_Form_AdditionalInfo
::processNote($submittedValues, $this->_contactID
, $contribution->id
, $this->_noteID
);
1674 CRM_Core_Session
::setStatus(implode(' ', $this->statusMessage
), $this->statusMessageTitle
, 'success');
1676 CRM_Contribute_BAO_Contribution
::updateRelatedPledge(
1680 (CRM_Utils_Array
::value('option_type', $formValues) == 2) ?
TRUE : FALSE,
1681 $formValues['total_amount'],
1682 CRM_Utils_Array
::value('total_amount', $this->_defaults
),
1683 $formValues['contribution_status_id'],
1684 CRM_Utils_Array
::value('contribution_status_id', $this->_defaults
)
1686 return $contribution;
1690 * Assign tax calculations to contribution receipts.
1692 * @param array $submittedValues
1693 * @param int $action
1694 * @param array $lineItem
1696 protected function invoicingPostProcessHook($submittedValues, $action, $lineItem) {
1698 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
1699 if (!CRM_Utils_Array
::value('invoicing', $invoiceSettings)) {
1703 $getTaxDetails = FALSE;
1704 if ($action & CRM_Core_Action
::ADD
) {
1707 elseif ($action & CRM_Core_Action
::UPDATE
) {
1708 $line = $this->_lineItems
;
1710 foreach ($line as $key => $value) {
1711 foreach ($value as $v) {
1712 if (isset($taxRate[(string) CRM_Utils_Array
::value('tax_rate', $v)])) {
1713 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $v);
1716 if (isset($v['tax_rate'])) {
1717 $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $v);
1718 $getTaxDetails = TRUE;
1724 if ($action & CRM_Core_Action
::UPDATE
) {
1725 if (isset($submittedValues['tax_amount'])) {
1726 $totalTaxAmount = $submittedValues['tax_amount'];
1729 $totalTaxAmount = $this->_values
['tax_amount'];
1731 $this->assign('totalTaxAmount', $totalTaxAmount);
1732 $this->assign('dataArray', $taxRate);
1735 if (!empty($submittedValues['price_set_id'])) {
1736 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1737 $this->assign('getTaxDetails', $getTaxDetails);
1738 $this->assign('dataArray', $taxRate);
1739 $this->assign('taxTerm', CRM_Utils_Array
::value('tax_term', $invoiceSettings));
1742 $this->assign('totalTaxAmount', CRM_Utils_Array
::value('tax_amount', $submittedValues));
1748 * Calculate non deductible amount.
1751 * if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1752 * if non_deductible_amount does NOT exist - then calculate it depending on:
1753 * $financialType->is_deductible and whether there is a product (premium).
1756 * @param $formValues
1760 protected function calculateNonDeductibleAmount($params, $formValues) {
1761 if (!empty($params['non_deductible_amount'])) {
1762 return $params['non_deductible_amount'];
1765 $financialType = new CRM_Financial_DAO_FinancialType();
1766 $financialType->id
= $params['financial_type_id'];
1768 if ($financialType->is_deductible
) {
1770 if (isset($formValues['product_name'][0])) {
1771 $selectProduct = $formValues['product_name'][0];
1773 // if there is a product - compare the value to the contribution amount
1774 if (isset($selectProduct)) {
1775 $productDAO = new CRM_Contribute_DAO_Product();
1776 $productDAO->id
= $selectProduct;
1777 $productDAO->find(TRUE);
1778 // product value exceeds contribution amount
1779 if ($params['total_amount'] < $productDAO->price
) {
1780 return $params['total_amount'];
1782 // product value does NOT exceed contribution amount
1784 return $productDAO->price
;
1787 // contribution is deductible - but there is no product
1792 // contribution is NOT deductible
1794 return $params['total_amount'];