3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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;
158 * Array of the payment fields to be displayed in the payment fieldset (pane) in billingBlock.tpl
159 * this contains all the information to describe these fields from quickform. See CRM_Core_Form_Payment getPaymentFormFieldsMetadata
163 public $_paymentFields = array();
165 * Logged in user's email.
177 * Price set as an array
187 public $userDisplayName;
190 * Status message to be shown to the user.
194 protected $statusMessage = array();
197 * Status message title to be shown to the user.
199 * Generally the payment processor message title is 'Complete' and offline is 'Saved'
200 * although this might not be a good fit with the broad range of processors.
204 protected $statusMessageTitle;
207 * Explicitly declare the form context.
209 public function getDefaultContext() {
214 * Set variables up before form is built.
216 public function preProcess() {
217 // Check permission for action.
218 if (!CRM_Core_Permission
::checkActionPermission('CiviContribute', $this->_action
)) {
219 // @todo replace with throw new CRM_Core_Exception().
220 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
223 parent
::preProcess();
225 $this->_formType
= CRM_Utils_Array
::value('formType', $_GET);
228 $this->_priceSetId
= CRM_Utils_Array
::value('priceSetId', $_GET);
229 $this->set('priceSetId', $this->_priceSetId
);
230 $this->assign('priceSetId', $this->_priceSetId
);
232 // Get the pledge payment id
233 $this->_ppID
= CRM_Utils_Request
::retrieve('ppid', 'Positive', $this);
235 $this->assign('action', $this->_action
);
237 // Get the contribution id if update
238 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this);
239 if (!empty($this->_id
)) {
240 $this->assign('contribID', $this->_id
);
243 $this->_context
= CRM_Utils_Request
::retrieve('context', 'String', $this);
244 $this->assign('context', $this->_context
);
246 $this->_compId
= CRM_Utils_Request
::retrieve('compId', 'Positive', $this);
248 $this->_compContext
= CRM_Utils_Request
::retrieve('compContext', 'String', $this);
250 //set the contribution mode.
251 $this->_mode
= CRM_Utils_Request
::retrieve('mode', 'String', $this);
253 $this->assign('contributionMode', $this->_mode
);
254 if ($this->_action
& CRM_Core_Action
::DELETE
) {
258 $this->_fromEmails
= CRM_Core_BAO_Email
::getFromEmail();
260 if (in_array('CiviPledge', CRM_Core_Config
::singleton()->enableComponents
) && !$this->_formType
) {
261 $this->preProcessPledge();
265 $this->showRecordLinkMesssage($this->_id
);
267 $this->_values
= array();
269 // Current contribution id.
271 $this->assignPremiumProduct($this->_id
);
272 $this->buildValuesAndAssignOnline_Note_Type($this->_id
, $this->_values
);
275 // when custom data is included in this page
276 if (!empty($_POST['hidden_custom'])) {
277 $this->applyCustomData('Contribution', CRM_Utils_Array
::value('financial_type_id', $_POST), $this->_id
);
280 $this->_lineItems
= array();
282 if (!empty($this->_compId
) && $this->_compContext
== 'participant') {
283 $this->assign('compId', $this->_compId
);
284 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_compId
);
287 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution', 1, TRUE, TRUE);
290 empty($lineItem) ?
NULL : $this->_lineItems
[] = $lineItem;
293 $this->assign('lineItem', empty($lineItem) ?
FALSE : array($lineItem));
296 if ($this->_mode
&& $this->_id
) {
297 $this->_payNow
= TRUE;
298 $this->assign('payNow', $this->_payNow
);
299 CRM_Utils_System
::setTitle(ts('Pay with Credit Card'));
301 elseif ($this->_mode
) {
302 $this->setPageTitle($this->_ppID ?
ts('Credit Card Pledge Payment') : ts('Credit Card Contribution'));
305 $this->setPageTitle($this->_ppID ?
ts('Pledge Payment') : ts('Contribution'));
310 * Set default values.
314 public function setDefaultValues() {
315 $defaults = $this->_values
;
317 // Set defaults for pledge payment.
319 $defaults['total_amount'] = CRM_Utils_Array
::value('scheduled_amount', $this->_pledgeValues
['pledgePayment']);
320 $defaults['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $this->_pledgeValues
);
321 $defaults['currency'] = CRM_Utils_Array
::value('currency', $this->_pledgeValues
);
322 $defaults['option_type'] = 1;
325 if ($this->_action
& CRM_Core_Action
::DELETE
) {
329 $defaults['frequency_interval'] = 1;
330 $defaults['frequency_unit'] = 'month';
332 // Set soft credit defaults.
333 CRM_Contribute_Form_SoftCredit
::setDefaultValues($defaults, $this);
336 // @todo - remove this function as the parent does it too.
337 $config = CRM_Core_Config
::singleton();
338 // Set default country from config if no country set.
339 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
340 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry
;
343 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
344 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince
;
347 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID
);
348 $defaults = array_merge($defaults, $billingDefaults);
352 $this->_contactID
= $defaults['contact_id'];
355 // Set $newCredit variable in template to control whether link to credit card mode is included.
356 $this->assign('newCredit', CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments());
358 // Fix the display of the monetary value, CRM-4038.
359 if (isset($defaults['total_amount'])) {
360 if (!empty($defaults['tax_amount'])) {
361 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
362 if (!(CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails))) {
363 $defaults['total_amount'] = CRM_Utils_Money
::format($defaults['total_amount'] - $defaults['tax_amount'], NULL, '%a');
367 $defaults['total_amount'] = CRM_Utils_Money
::format($defaults['total_amount'], NULL, '%a');
371 $amountFields = array('non_deductible_amount', 'fee_amount', 'net_amount');
372 foreach ($amountFields as $amt) {
373 if (isset($defaults[$amt])) {
374 $defaults[$amt] = CRM_Utils_Money
::format($defaults[$amt], 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'] = $this->getDefaultPaymentInstrumentId();
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));
418 if (!empty($defaults['contribution_status_id']) && in_array(
419 CRM_Contribute_PseudoConstant
::contributionStatus($defaults['contribution_status_id'], 'name'),
420 // Historically not 'Cancelled' hence not using CRM_Contribute_BAO_Contribution::isContributionStatusNegative.
421 array('Refunded', 'Chargeback')
423 $defaults['refund_trxn_id'] = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionTrxnID($this->_id
);
426 $defaults['refund_trxn_id'] = isset($defaults['trxn_id']) ?
$defaults['trxn_id'] : NULL;
429 if (!$this->_id
&& empty($defaults['receive_date'])) {
430 $defaults['receive_date'] = date('Y-m-d H:i:s');
433 $currency = CRM_Utils_Array
::value('currency', $defaults);
434 $this->assign('currency', $currency);
435 // Hack to get currency info to the js layer. CRM-11440.
436 CRM_Utils_Money
::format(1);
437 $this->assign('currencySymbol', CRM_Utils_Array
::value($currency, CRM_Utils_Money
::$_currencySymbols));
438 $this->assign('totalAmount', CRM_Utils_Array
::value('total_amount', $defaults));
440 // Inherit campaign from pledge.
441 if ($this->_ppID
&& !empty($this->_pledgeValues
['campaign_id'])) {
442 $defaults['campaign_id'] = $this->_pledgeValues
['campaign_id'];
445 $this->_defaults
= $defaults;
450 * Build the form object.
452 public function buildQuickForm() {
453 if ($this->_action
& CRM_Core_Action
::DELETE
) {
454 $this->addButtons(array(
457 'name' => ts('Delete'),
458 'spacing' => ' ',
463 'name' => ts('Cancel'),
470 // FIXME: This probably needs to be done in preprocess
471 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()
472 && $this->_action
& CRM_Core_Action
::UPDATE
473 && CRM_Utils_Array
::value('financial_type_id', $this->_values
)
475 $financialTypeID = CRM_Contribute_PseudoConstant
::financialType($this->_values
['financial_type_id']);
476 CRM_Financial_BAO_FinancialType
::checkPermissionedLineItems($this->_id
, 'edit');
477 if (!CRM_Core_Permission
::check('edit contributions of type ' . $financialTypeID)) {
478 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
483 //tax rate from financialType
484 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant
::getTaxRates()));
485 $this->assign('currencies', json_encode(CRM_Core_OptionGroup
::values('currencies_enabled')));
487 // build price set form.
488 $buildPriceSet = FALSE;
489 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
490 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
491 $this->assign('invoicing', $invoicing);
493 $buildRecurBlock = FALSE;
495 // display tax amount on edit contribution page
496 if ($invoicing && $this->_action
& CRM_Core_Action
::UPDATE
&& isset($this->_values
['tax_amount'])) {
497 $this->assign('totalTaxAmount', $this->_values
['tax_amount']);
500 if (empty($this->_lineItems
) &&
501 ($this->_priceSetId ||
!empty($_POST['price_set_id']))
503 $buildPriceSet = TRUE;
504 $getOnlyPriceSetElements = TRUE;
505 if (!$this->_priceSetId
) {
506 $this->_priceSetId
= $_POST['price_set_id'];
507 $getOnlyPriceSetElements = FALSE;
510 $this->set('priceSetId', $this->_priceSetId
);
511 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
513 // get only price set form elements.
514 if ($getOnlyPriceSetElements) {
518 // use to build form during form rule.
519 $this->assign('buildPriceSet', $buildPriceSet);
521 $defaults = $this->_values
;
522 $additionalDetailFields = array(
526 'non_deductible_amount',
530 foreach ($additionalDetailFields as $key) {
531 if (!empty($defaults[$key])) {
532 $defaults['hidden_AdditionalDetail'] = 1;
537 if ($this->_productDAO
) {
538 if ($this->_productDAO
->product_id
) {
539 $defaults['hidden_Premium'] = 1;
543 if ($this->_noteID
&&
544 !CRM_Utils_System
::isNull($this->_values
['note'])
546 $defaults['hidden_AdditionalDetail'] = 1;
549 $paneNames = array();
550 if (empty($this->_payNow
)) {
551 $paneNames[ts('Additional Details')] = 'AdditionalDetail';
554 //Add Premium pane only if Premium is exists.
555 $dao = new CRM_Contribute_DAO_Product();
558 if ($dao->find(TRUE) && empty($this->_payNow
)) {
559 $paneNames[ts('Premium Information')] = 'Premium';
562 $this->payment_instrument_id
= CRM_Utils_Array
::value('payment_instrument_id', $defaults, $this->getDefaultPaymentInstrumentId());
563 if (CRM_Core_Payment_Form
::buildPaymentForm($this, $this->_paymentProcessor
, FALSE, TRUE, $this->payment_instrument_id
) == TRUE) {
564 if (!empty($this->_recurPaymentProcessors
)) {
565 $buildRecurBlock = TRUE;
567 // ppID denotes a pledge payment.
568 foreach ($this->_paymentProcessors
as $processor) {
569 if (!empty($processor['is_recur']) && !empty($processor['object']) && $processor['object']->supports('recurContributionsForPledges')) {
570 $buildRecurBlock = TRUE;
573 $buildRecurBlock = FALSE;
576 if ($buildRecurBlock) {
577 CRM_Contribute_Form_Contribution_Main
::buildRecur($this);
578 $this->setDefaults(array('is_recur' => 0));
579 $this->assign('buildRecurBlock', TRUE);
583 $this->addPaymentProcessorSelect(FALSE, $buildRecurBlock);
585 foreach ($paneNames as $name => $type) {
586 $allPanes[$name] = $this->generatePane($type, $defaults);
589 $qfKey = $this->controller
->_key
;
590 $this->assign('qfKey', $qfKey);
591 $this->assign('allPanes', $allPanes);
593 $this->addFormRule(array('CRM_Contribute_Form_Contribution', 'formRule'), $this);
595 if ($this->_formType
) {
596 $this->assign('formType', $this->_formType
);
600 $this->applyFilter('__ALL__', 'trim');
602 //need to assign custom data type and subtype to the template
603 $this->assign('customDataType', 'Contribution');
604 $this->assign('customDataSubType', $this->_contributionType
);
605 $this->assign('entityID', $this->_id
);
607 if ($this->_context
== 'standalone') {
608 $this->addEntityRef('contact_id', ts('Contact'), array(
610 'api' => array('extra' => array('email')),
614 $attributes = CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Contribution');
616 // Check permissions for financial type first
617 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes, $this->_action
);
618 if (empty($financialTypes)) {
619 CRM_Core_Error
::statusBounce(ts('You do not have all the permissions needed for this page.'));
621 $financialType = $this->add('select', 'financial_type_id',
622 ts('Financial Type'),
623 array('' => ts('- select -')) +
$financialTypes,
625 array('onChange' => "CRM.buildCustomData( 'Contribution', this.value );")
628 $paymentInstrument = FALSE;
630 $checkPaymentID = array_search('Check', CRM_Contribute_PseudoConstant
::paymentInstrument('name'));
631 $paymentInstrument = $this->add('select', 'payment_instrument_id',
632 ts('Payment Method'),
633 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::paymentInstrument(),
634 TRUE, array('onChange' => "return showHideByValue('payment_instrument_id','{$checkPaymentID}','checkNumber','table-row','select',false);")
638 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), array('class' => 'twelve') +
$attributes['trxn_id']);
640 //add receipt for offline contribution
641 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
643 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
645 $component = 'contribution';
647 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
648 if (CRM_Utils_Array
::value('membership', $componentDetails)) {
649 $component = 'membership';
651 elseif (CRM_Utils_Array
::value('participant', $componentDetails)) {
652 $component = 'participant';
656 $component = 'pledge';
658 $status = CRM_Contribute_BAO_Contribution_Utils
::getContributionStatuses($component, $this->_id
);
660 // define the status IDs that show the cancellation info, see CRM-17589
661 $cancelInfo_show_ids = array();
662 foreach (array_keys($status) as $status_id) {
663 if (CRM_Contribute_BAO_Contribution
::isContributionStatusNegative($status_id)) {
664 $cancelInfo_show_ids[] = "'$status_id'";
667 $this->assign('cancelInfo_show_ids', implode(',', $cancelInfo_show_ids));
669 $statusElement = $this->add('select', 'contribution_status_id',
670 ts('Contribution Status'),
675 $currencyFreeze = FALSE;
676 if (!empty($this->_payNow
) && ($this->_action
& CRM_Core_Action
::UPDATE
)) {
677 $statusElement->freeze();
678 $currencyFreeze = TRUE;
679 $attributes['total_amount']['readonly'] = TRUE;
682 // CRM-16189, add Revenue Recognition Date
683 if (CRM_Contribute_BAO_Contribution
::checkContributeSettings('deferred_revenue_enabled')) {
684 $revenueDate = $this->add('date', 'revenue_recognition_date', ts('Revenue Recognition Date'), CRM_Core_SelectValues
::date(NULL, 'M Y', NULL, 5));
685 if ($this->_id
&& !CRM_Contribute_BAO_Contribution
::allowUpdateRevenueRecognitionDate($this->_id
)) {
686 $revenueDate->freeze();
691 $this->addField('receive_date', array('entity' => 'contribution'), FALSE, FALSE);
692 $this->addField('receipt_date', array('entity' => 'contribution'), FALSE, FALSE);
693 $this->addField('cancel_date', array('entity' => 'contribution', 'label' => ts('Cancelled / Refunded Date')), FALSE, FALSE);
695 if ($this->_online
) {
696 $this->assign('hideCalender', TRUE);
699 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
702 if (empty($this->_lineItems
)) {
703 $buildPriceSet = FALSE;
704 $priceSets = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute');
705 if (!empty($priceSets) && !$this->_ppID
) {
706 $buildPriceSet = TRUE;
709 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
710 // and if we already have line items for that participant. CRM-5095
711 if ($buildPriceSet && $this->_id
) {
712 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
713 $pledgePaymentId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
718 if ($pledgePaymentId) {
719 $buildPriceSet = FALSE;
721 if ($participantID = CRM_Utils_Array
::value('participant', $componentDetails)) {
722 $participantLI = CRM_Price_BAO_LineItem
::getLineItems($participantID);
723 if (!CRM_Utils_System
::isNull($participantLI)) {
724 $buildPriceSet = FALSE;
729 $hasPriceSets = FALSE;
730 if ($buildPriceSet) {
731 $hasPriceSets = TRUE;
732 // CRM-16451: set financial type of 'Price Set' in back office contribution
733 // instead of selecting manually
734 $financialTypeIds = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute', 'financial_type_id');
735 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
737 '' => ts('Choose price set'),
739 NULL, array('onchange' => "buildAmount( this.value, " . json_encode($financialTypeIds) . ");")
741 if ($this->_online
&& !($this->_action
& CRM_Core_Action
::UPDATE
)) {
745 $this->assign('hasPriceSets', $hasPriceSets);
746 if (!($this->_action
& CRM_Core_Action
::UPDATE
)) {
747 if ($this->_online ||
$this->_ppID
) {
748 $attributes['total_amount'] = array_merge($attributes['total_amount'], array(
750 'style' => "background-color:#EBECE4",
752 $optionTypes = array(
753 '1' => ts('Adjust Pledge Payment Schedule?'),
754 '2' => ts('Adjust Total Pledge Amount?'),
756 $this->addRadio('option_type',
762 $currencyFreeze = TRUE;
766 $totalAmount = $this->addMoney('total_amount',
768 ($hasPriceSets) ?
FALSE : TRUE,
769 $attributes['total_amount'],
770 TRUE, 'currency', NULL, $currencyFreeze
774 $this->add('text', 'source', ts('Source'), CRM_Utils_Array
::value('source', $attributes));
776 // CRM-7362 --add campaigns.
777 CRM_Campaign_BAO_Campaign
::addCampaign($this, CRM_Utils_Array
::value('campaign_id', $this->_values
));
779 if (empty($this->_payNow
)) {
780 CRM_Contribute_Form_SoftCredit
::buildQuickForm($this);
785 $js = array('onclick' => "return verify( );");
788 $mailingInfo = Civi
::settings()->get('mailing_backend');
789 $this->assign('outBound_option', $mailingInfo['outBound_option']);
791 $this->addButtons(array(
794 'name' => ts('Save'),
800 'name' => ts('Save and New'),
806 'name' => ts('Cancel'),
811 // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
812 // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
813 if ($this->_id
&& ($this->_values
['contribution_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Cancelled'))) {
815 $totalAmount->freeze();
817 $paymentInstrument->freeze();
819 $financialType->freeze();
822 // if contribution is related to membership or participant freeze Financial Type, Amount
823 if ($this->_id
&& isset($this->_values
['tax_amount'])) {
824 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
825 if (CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails)) {
827 $totalAmount->freeze();
829 $financialType->freeze();
830 $this->assign('freezeFinancialType', TRUE);
834 if ($this->_action
& CRM_Core_Action
::VIEW
) {
842 * @param array $fields
843 * The input form values.
844 * @param array $files
845 * The uploaded files if any.
849 * true if no errors, else array of errors
851 public static function formRule($fields, $files, $self) {
853 // Check for Credit Card Contribution.
855 if (empty($fields['payment_processor_id'])) {
856 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
859 // validate payment instrument (e.g. credit card number)
860 CRM_Core_Payment_Form
::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, NULL);
864 // Do the amount validations.
865 if (empty($fields['total_amount']) && empty($self->_lineItems
)) {
866 if ($priceSetId = CRM_Utils_Array
::value('price_set_id', $fields)) {
867 CRM_Price_BAO_PriceField
::priceSetValidation($priceSetId, $fields, $errors);
871 $softErrors = CRM_Contribute_Form_SoftCredit
::formRule($fields, $errors, $self);
873 if (!empty($fields['total_amount']) && (!empty($fields['net_amount']) ||
!empty($fields['fee_amount']))) {
874 $sum = CRM_Utils_Rule
::cleanMoney($fields['net_amount']) + CRM_Utils_Rule
::cleanMoney($fields['fee_amount']);
875 if (CRM_Utils_Rule
::cleanMoney($fields['total_amount']) != $sum) {
876 $errors['total_amount'] = ts('The sum of fee amount and net amount must be equal to total amount');
880 //CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
881 CRM_Contribute_BAO_ContributionRecur
::validateRecurContribution($fields, $files, $self, $errors);
883 // Form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
884 if (($self->_action
& CRM_Core_Action
::UPDATE
)
886 && $self->_values
['contribution_status_id'] != $fields['contribution_status_id']
888 CRM_Contribute_BAO_Contribution
::checkStatusValidation($self->_values
, $fields, $errors);
890 // CRM-16015, add form-rule to restrict change of financial type if using price field of different financial type
891 if (($self->_action
& CRM_Core_Action
::UPDATE
)
893 && $self->_values
['financial_type_id'] != $fields['financial_type_id']
895 CRM_Contribute_BAO_Contribution
::checkFinancialTypeChange(NULL, $self->_id
, $errors);
897 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
898 if (!empty($fields['fee_amount']) && !empty($fields['financial_type_id']) && $financialType = CRM_Contribute_BAO_Contribution
::validateFinancialType($fields['financial_type_id'])) {
899 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
902 // $trxn_id must be unique CRM-13919
903 if (!empty($fields['trxn_id'])) {
904 $queryParams = array(1 => array($fields['trxn_id'], 'String'));
905 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
907 $queryParams[2] = array((int) $self->_id
, 'Integer');
908 $query .= ' and id !=%2';
910 $tCnt = CRM_Core_DAO
::singleValueQuery($query, $queryParams);
912 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', array(1 => $fields['trxn_id']));
915 if (!empty($fields['revenue_recognition_date'])
916 && count(array_filter($fields['revenue_recognition_date'])) == 1
918 $errors['revenue_recognition_date'] = ts('Month and Year are required field for Revenue Recognition.');
922 CRM_Financial_BAO_FinancialAccount
::checkFinancialTypeHasDeferred($fields, $self->_id
, $self->_priceSet
['fields']);
924 catch (CRM_Core_Exception
$e) {
925 $errors['financial_type_id'] = ' ';
926 $errors['_qf_default'] = $e->getMessage();
928 $errors = array_merge($errors, $softErrors);
933 * Process the form submission.
935 public function postProcess() {
936 if ($this->_action
& CRM_Core_Action
::DELETE
) {
937 CRM_Contribute_BAO_Contribution
::deleteContribution($this->_id
);
938 CRM_Core_Session
::singleton()->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
939 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
943 // Get the submitted form values.
944 $submittedValues = $this->controller
->exportValues($this->_name
);
947 $contribution = $this->submit($submittedValues, $this->_action
, $this->_ppID
);
949 catch (PaymentProcessorException
$e) {
950 // Set the contribution mode.
951 $urlParams = "action=add&cid={$this->_contactID}";
953 $urlParams .= "&mode={$this->_mode}";
955 if (!empty($this->_ppID
)) {
956 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
959 CRM_Core_Error
::statusBounce($e->getMessage(), $urlParams, ts('Payment Processor Error'));
961 $session = CRM_Core_Session
::singleton();
962 $buttonName = $this->controller
->getButtonName();
963 if ($this->_context
== 'standalone') {
964 if ($buttonName == $this->getButtonName('upload', 'new')) {
965 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contribute/add',
966 'reset=1&action=add&context=standalone'
970 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
971 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
975 elseif ($this->_context
== 'contribution' && $this->_mode
&& $buttonName == $this->getButtonName('upload', 'new')) {
976 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
977 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
980 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
981 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
982 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
986 //store contribution ID if not yet set (on create)
987 if (empty($this->_id
) && !empty($contribution->id
)) {
988 $this->_id
= $contribution->id
;
990 if (!empty($this->_id
) && CRM_Core_Permission
::access('CiviMember')) {
991 $membershipPaymentCount = civicrm_api3('MembershipPayment', 'getCount', array('contribution_id' => $this->_id
));
992 if ($membershipPaymentCount) {
993 $this->ajaxResponse
['updateTabs']['#tab_member'] = CRM_Contact_BAO_Contact
::getCountComponent('membership', $this->_contactID
);
996 if (!empty($this->_id
) && CRM_Core_Permission
::access('CiviEvent')) {
997 $participantPaymentCount = civicrm_api3('ParticipantPayment', 'getCount', array('contribution_id' => $this->_id
));
998 if ($participantPaymentCount) {
999 $this->ajaxResponse
['updateTabs']['#tab_participant'] = CRM_Contact_BAO_Contact
::getCountComponent('participant', $this->_contactID
);
1005 * Process credit card payment.
1007 * @param array $submittedValues
1008 * @param array $lineItem
1010 * @param int $contactID
1013 * @return bool|\CRM_Contribute_DAO_Contribution
1014 * @throws \CRM_Core_Exception
1015 * @throws \Civi\Payment\Exception\PaymentProcessorException
1017 protected function processCreditCard($submittedValues, $lineItem, $contactID) {
1018 $isTest = ($this->_mode
== 'test') ?
1 : 0;
1019 // CRM-12680 set $_lineItem if its not set
1020 // @todo - I don't believe this would ever BE set. I can't find anywhere in the code.
1021 // It would be better to pass line item out to functions than $this->_lineItem as
1022 // we don't know what is being changed where.
1023 if (empty($this->_lineItem
) && !empty($lineItem)) {
1024 $this->_lineItem
= $lineItem;
1027 $this->_paymentObject
= Civi\Payment\System
::singleton()->getById($submittedValues['payment_processor_id']);
1028 $this->_paymentProcessor
= $this->_paymentObject
->getPaymentProcessor();
1030 // Set source if not set
1031 if (empty($submittedValues['source'])) {
1032 $userID = CRM_Core_Session
::singleton()->get('userID');
1033 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1036 $submittedValues['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
1039 $params = $submittedValues;
1040 $this->_params
= array_merge($this->_params
, $submittedValues);
1042 // Mapping requiring documentation.
1043 $this->_params
['payment_processor'] = $submittedValues['payment_processor_id'];
1045 $now = date('YmdHis');
1047 // we need to retrieve email address
1048 if ($this->_context
== 'standalone' && !empty($submittedValues['is_email_receipt'])) {
1049 list($this->userDisplayName
,
1051 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contactID);
1052 $this->assign('displayName', $this->userDisplayName
);
1055 $this->_contributorEmail
= $this->userEmail
;
1056 $this->_contributorContactID
= $contactID;
1057 $this->processBillingAddress();
1058 if (!empty($params['source'])) {
1059 unset($params['source']);
1062 $this->_params
['amount'] = $this->_params
['total_amount'];
1063 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
1064 // function to get correct amount level consistently. Remove setting of the amount level in
1065 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
1066 // to cover all variants.
1067 $this->_params
['amount_level'] = 0;
1068 $this->_params
['description'] = ts("Contribution submitted by a staff person using contributor's credit card");
1069 $this->_params
['currencyID'] = CRM_Utils_Array
::value('currency',
1071 CRM_Core_Config
::singleton()->defaultCurrency
1074 $this->_params
['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $params);
1075 $this->_params
['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $params);
1076 $this->_params
['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $params);
1078 //Add common data to formatted params
1079 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
1081 if (empty($this->_params
['invoice_id'])) {
1082 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
1085 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
1088 // At this point we've created a contact and stored its address etc
1089 // all the payment processors expect the name and address to be in the
1090 // so we copy stuff over to first_name etc.
1091 $paymentParams = $this->_params
;
1092 $paymentParams['contactID'] = $contactID;
1093 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
1095 $financialType = new CRM_Financial_DAO_FinancialType();
1096 $financialType->id
= $params['financial_type_id'];
1097 $financialType->find(TRUE);
1099 // Add some financial type details to the params list
1100 // if folks need to use it.
1101 $paymentParams['contributionType_name'] = $this->_params
['contributionType_name'] = $financialType->name
;
1102 $paymentParams['contributionPageID'] = NULL;
1104 if (!empty($this->_params
['is_email_receipt'])) {
1105 $paymentParams['email'] = $this->userEmail
;
1106 $paymentParams['is_email_receipt'] = 1;
1109 $paymentParams['is_email_receipt'] = 0;
1110 $this->_params
['is_email_receipt'] = 0;
1112 if (!empty($this->_params
['receive_date'])) {
1113 $paymentParams['receive_date'] = $this->_params
['receive_date'];
1116 if (!empty($this->_params
['is_email_receipt'])) {
1117 $this->_params
['receipt_date'] = $now;
1120 $this->set('params', $this->_params
);
1122 $this->assign('receive_date', $this->_params
['receive_date']);
1124 // Result has all the stuff we need
1125 // lets archive it to a financial transaction
1126 if ($financialType->is_deductible
) {
1127 $this->assign('is_deductible', TRUE);
1128 $this->set('is_deductible', TRUE);
1130 $contributionParams = array(
1131 'id' => CRM_Utils_Array
::value('contribution_id', $this->_params
),
1132 'contact_id' => $contactID,
1133 'line_item' => $lineItem,
1134 'is_test' => $isTest,
1135 'campaign_id' => CRM_Utils_Array
::value('campaign_id', $this->_params
),
1136 'contribution_page_id' => CRM_Utils_Array
::value('contribution_page_id', $this->_params
),
1137 'source' => CRM_Utils_Array
::value('source', $paymentParams, CRM_Utils_Array
::value('description', $paymentParams)),
1138 'thankyou_date' => CRM_Utils_Array
::value('thankyou_date', $this->_params
),
1140 $contributionParams['payment_instrument_id'] = $this->_paymentProcessor
['payment_instrument_id'];
1142 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processFormContribution($this,
1145 $contributionParams,
1149 CRM_Utils_Array
::value('is_recur', $this->_params
)
1152 $paymentParams['contributionID'] = $contribution->id
;
1153 $paymentParams['contributionTypeID'] = $contribution->financial_type_id
;
1154 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
1155 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1157 if ($paymentParams['amount'] > 0.0) {
1158 // force a re-get of the payment processor in case the form changed it, CRM-7179
1159 // NOTE - I expect this is obsolete.
1160 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
1162 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id');
1163 $result = $payment->doPayment($paymentParams, 'contribute');
1164 $this->assign('trxn_id', $result['trxn_id']);
1165 $contribution->trxn_id
= $result['trxn_id'];
1166 /* Our scenarios here are
1167 * 1) the payment failed & an Exception should have been thrown
1168 * 2) the payment succeeded but the payment is not immediate (for example a recurring payment
1169 * with a delayed start)
1170 * 3) the payment succeeded with an immediate payment.
1172 * The doPayment function ensures that payment_status_id is always set
1173 * as historically we have had to guess from the context - ie doDirectPayment
1174 * = error or success, unless it is a recurring contribution in which case it is pending.
1176 if ($result['payment_status_id'] == array_search('Completed', $statuses)) {
1178 civicrm_api3('contribution', 'completetransaction', array(
1179 'id' => $contribution->id
,
1180 'trxn_id' => $result['trxn_id'],
1181 'payment_processor_id' => $this->_paymentProcessor
['id'],
1182 'is_transactional' => FALSE,
1183 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $result),
1184 'card_type_id' => CRM_Utils_Array
::value('card_type_id', $paymentParams),
1185 'pan_truncation' => CRM_Utils_Array
::value('pan_truncation', $paymentParams),
1186 'is_email_receipt' => FALSE,
1188 // This has now been set to 1 in the DB - declare it here also
1189 $contribution->contribution_status_id
= 1;
1191 catch (CiviCRM_API3_Exception
$e) {
1192 if ($e->getErrorCode() != 'contribution_completed') {
1193 throw new CRM_Core_Exception('Failed to update contribution in database');
1198 // Save the trxn_id.
1199 $contribution->save();
1202 catch (PaymentProcessorException
$e) {
1203 CRM_Contribute_BAO_Contribution
::failPayment($contribution->id
, $paymentParams['contactID'], $e->getMessage());
1204 throw new PaymentProcessorException($e->getMessage());
1207 // Send receipt mail.
1208 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1209 if ($contribution->id
&& !empty($this->_params
['is_email_receipt'])) {
1210 $this->_params
['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $result);
1211 $this->_params
['contact_id'] = $contactID;
1212 $this->_params
['contribution_id'] = $contribution->id
;
1213 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $this->_params
, TRUE)) {
1214 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1218 return $contribution;
1222 * Generate the data to construct a snippet based pane.
1224 * This form also assigns the showAdditionalInfo var based on historical code.
1225 * This appears to mean 'there is a pane to show'.
1227 * @param string $type
1228 * Type of Pane - this is generally used to determine the function name used to build it
1229 * - e.g CreditCard, AdditionalDetail
1230 * @param array $defaults
1233 * We aim to further refactor & simplify this but currently
1235 * - should additional info be shown?
1237 protected function generatePane($type, $defaults) {
1238 $urlParams = "snippet=4&formType={$type}";
1240 $urlParams .= "&mode={$this->_mode}";
1244 if ($type == 'CreditCard' ||
1245 $type == 'DirectDebit'
1251 'url' => CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams),
1256 // See if we need to include this paneName in the current form.
1257 if ($this->_formType
== $type ||
!empty($_POST["hidden_{$type}"]) ||
1258 CRM_Utils_Array
::value("hidden_{$type}", $defaults)
1260 $this->assign('showAdditionalInfo', TRUE);
1261 $pane['open'] = 'true';
1264 if ($type == 'CreditCard' ||
$type == 'DirectDebit') {
1265 // @todo would be good to align tpl name with form name...
1266 // @todo document why this hidden variable is required.
1267 $this->add('hidden', 'hidden_' . $type, 1);
1271 $additionalInfoFormFunction = 'build' . $type;
1272 CRM_Contribute_Form_AdditionalInfo
::$additionalInfoFormFunction($this);
1278 * Wrapper for unit testing the post process submit function.
1280 * (If we expose through api we can get default additions 'for free').
1282 * @param array $params
1283 * @param int $action
1284 * @param string|null $creditCardMode
1286 * @throws \CiviCRM_API3_Exception
1288 public function testSubmit($params, $action, $creditCardMode = NULL) {
1290 'soft_credit_contact_id' => array(),
1291 'receive_date' => date('Y-m-d H:i:s'),
1292 'receipt_date' => '',
1293 'cancel_date' => '',
1294 'hidden_Premium' => 1,
1297 if (!empty($params['id'])) {
1298 $existingContribution = civicrm_api3('contribution', 'getsingle', array(
1299 'id' => $params['id'],
1301 $this->_id
= $params['id'];
1302 $this->_values
= $existingContribution;
1303 if (CRM_Contribute_BAO_Contribution
::checkContributeSettings('invoicing')) {
1304 $this->_values
['tax_amount'] = civicrm_api3('contribution', 'getvalue', array(
1305 'id' => $params['id'],
1306 'return' => 'tax_amount',
1311 $existingContribution = array();
1314 $this->_defaults
['contribution_status_id'] = CRM_Utils_Array
::value('contribution_status_id',
1315 $existingContribution
1318 $this->_defaults
['total_amount'] = CRM_Utils_Array
::value('total_amount',
1319 $existingContribution
1322 if ($creditCardMode) {
1323 $this->_mode
= $creditCardMode;
1326 // Required because processCreditCard calls set method on this.
1327 $_SERVER['REQUEST_METHOD'] = 'GET';
1328 $this->controller
= new CRM_Core_Controller();
1330 CRM_Contribute_Form_AdditionalInfo
::buildPremium($this);
1332 $this->_fields
= array();
1333 return $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array
::value('pledge_payment_id', $params));
1338 * @param array $submittedValues
1340 * @param int $action
1342 * - CRM_Core_Action::UPDATE
1344 * @param $pledgePaymentID
1347 * @throws \Exception
1349 protected function submit($submittedValues, $action, $pledgePaymentID) {
1350 $pId = $contribution = $isRelatedId = FALSE;
1351 $this->_params
= $submittedValues;
1352 $this->beginPostProcess();
1353 // reassign submitted form values if the any information is formatted via beginPostProcess
1354 $submittedValues = $this->_params
;
1356 if (!empty($submittedValues['price_set_id']) && $action & CRM_Core_Action
::UPDATE
) {
1357 $line = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution');
1358 $lineID = key($line);
1359 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array
::value('price_field_id', $line[$lineID]), 'price_set_id');
1360 $quickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1361 // Why do we do this? Seems like a like a wrapper for old functionality - but single line price sets & quick
1362 // config should be treated the same.
1364 CRM_Price_BAO_LineItem
::deleteLineItems($this->_id
, 'civicrm_contribution');
1368 // Process price set and get total amount and line items.
1369 $lineItem = array();
1370 $priceSetId = CRM_Utils_Array
::value('price_set_id', $submittedValues);
1371 if (empty($priceSetId) && !$this->_id
) {
1372 $this->_priceSetId
= $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1373 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
1374 $fieldID = key($this->_priceSet
['fields']);
1375 $fieldValueId = key($this->_priceSet
['fields'][$fieldID]['options']);
1376 $this->_priceSet
['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1377 $submittedValues['price_' . $fieldID] = 1;
1380 // Every contribution has a price-set - the only reason it shouldn't be set is if we are dealing with
1381 // quick config (very very arguably) & yet we see that this could still be quick config so this should be understood
1382 // as a point of fragility rather than a logical 'if' clause.
1384 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
1385 $submittedValues, $lineItem[$priceSetId]);
1386 // Unset tax amount for offline 'is_quick_config' contribution.
1387 // @todo WHY - quick config was conceived as a quick way to configure contribution forms.
1388 // this is an example of 'other' functionality being hung off it.
1389 if ($this->_priceSet
['is_quick_config'] &&
1390 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant
::getTaxRates())
1392 unset($submittedValues['tax_amount']);
1394 // @todo - look to remove this line. I believe it relates to CRM-16460
1395 // and possibly contributes to fixing the issue described there but
1396 // would cause breakage for negative values in some cases.
1397 $submittedValues['total_amount'] = CRM_Utils_Array
::value('amount', $submittedValues);
1400 if ($this->_compId
) {
1401 if ($this->_context
== 'participant') {
1402 $pId = $this->_compId
;
1404 elseif ($this->_context
== 'membership') {
1405 $isRelatedId = TRUE;
1408 $pId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id
, 'participant_id', 'contribution_id');
1412 $contributionDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1413 if (array_key_exists('membership', $contributionDetails)) {
1414 $isRelatedId = TRUE;
1416 elseif (array_key_exists('participant', $contributionDetails)) {
1417 $pId = $contributionDetails['participant'];
1420 if (!empty($this->_payNow
)) {
1421 $this->_params
['contribution_id'] = $this->_id
;
1425 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id
) {
1426 // CRM-10117 update the line items for participants.
1427 // @todo - if we are completing a contribution then the api call
1428 // civicrm_api3('Contribution', 'completetransaction') should take care of
1429 // all associated updates rather than replicating them on the form layer.
1431 $entityTable = 'participant';
1433 $isRelatedId = FALSE;
1434 $participantParams = array(
1435 'fee_amount' => $submittedValues['total_amount'],
1438 CRM_Event_BAO_Participant
::add($participantParams);
1439 if (empty($this->_lineItems
)) {
1440 $this->_lineItems
[] = CRM_Price_BAO_LineItem
::getLineItems($entityID, 'participant', TRUE);
1444 $entityTable = 'contribution';
1445 $entityID = $this->_id
;
1448 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, $entityTable, FALSE, TRUE, $isRelatedId);
1449 foreach (array_keys($lineItems) as $id) {
1450 $lineItems[$id]['id'] = $id;
1452 $itemId = key($lineItems);
1453 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1454 $this->_priceSetId
= CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1457 // @todo see above - new functionality has been inappropriately added to the quick config concept
1458 // and new functionality has been added onto the form layer rather than the BAO :-(
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 // NOTE that this IS still a legitimate use of 'quick-config' for contributions under the current DB but
1497 // we should look at having a price field per contribution type & then there would be little reason
1498 // for the back-office contribution form postProcess to know if it is a quick-config form.
1499 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array
::value($this->_priceSetId
, $lineItem)
1501 foreach ($lineItem[$this->_priceSetId
] as &$values) {
1502 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1506 if (!isset($submittedValues['total_amount'])) {
1507 $submittedValues['total_amount'] = CRM_Utils_Array
::value('total_amount', $this->_values
);
1508 // Avoid tax amount deduction on edit form and keep it original, because this will lead to error described in CRM-20676
1510 $submittedValues['total_amount'] -= CRM_Utils_Array
::value('tax_amount', $this->_values
, 0);
1513 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
1515 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
1516 if ($this->_id
&& count($isEmpty) == 1 && key($isEmpty) == NULL) {
1517 civicrm_api3('ContributionSoft', 'get', array('contribution_id' => $this->_id
, 'pcp_id' => NULL, 'api.ContributionSoft.delete' => 1));
1520 // set the contact, when contact is selected
1521 if (!empty($submittedValues['contact_id'])) {
1522 $this->_contactID
= $submittedValues['contact_id'];
1525 $formValues = $submittedValues;
1527 // Credit Card Contribution.
1529 $paramsSetByPaymentProcessingSubsystem = array(
1531 'payment_instrument_id',
1532 'contribution_status_id',
1536 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1537 if (isset($formValues[$key])) {
1538 unset($formValues[$key]);
1541 $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID
);
1542 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1543 $formValues[$key] = $contribution->$key;
1547 // Offline Contribution.
1548 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1550 // get the required field value only.
1552 $params = $ids = array();
1554 $params['contact_id'] = $this->_contactID
;
1555 $params['currency'] = $this->getCurrency($submittedValues);
1557 //format soft-credit/pcp param first
1558 CRM_Contribute_BAO_ContributionSoft
::formatSoftCreditParams($submittedValues, $this);
1559 $params = array_merge($params, $submittedValues);
1562 'financial_type_id',
1563 'contribution_status_id',
1564 'payment_instrument_id',
1571 foreach ($fields as $f) {
1572 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1575 // CRM-5740 if priceset is used, no need to cleanup money.
1577 $params['skipCleanMoney'] = 1;
1579 $params['revenue_recognition_date'] = NULL;
1580 if (!empty($formValues['revenue_recognition_date'])
1581 && count(array_filter($formValues['revenue_recognition_date'])) == 2
1583 $params['revenue_recognition_date'] = CRM_Utils_Date
::processDate(
1584 '01-' . implode('-', $formValues['revenue_recognition_date'])
1588 if (!empty($formValues['is_email_receipt'])) {
1589 $params['receipt_date'] = date("Y-m-d");
1592 if (CRM_Contribute_BAO_Contribution
::isContributionStatusNegative($params['contribution_status_id'])
1594 if (CRM_Utils_System
::isNull(CRM_Utils_Array
::value('cancel_date', $params))) {
1595 $params['cancel_date'] = date('YmdHis');
1599 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1602 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1603 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1604 if ($params['contribution_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending')) {
1605 $params['is_pay_later'] = 1;
1607 elseif ($params['contribution_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed')) {
1608 $params['is_pay_later'] = 0;
1611 $ids['contribution'] = $params['id'] = $this->_id
;
1613 // Add Additional common information to formatted params.
1614 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($formValues, $params, $this);
1616 $params['contribution_mode'] = 'participant';
1617 $params['participant_id'] = $pId;
1618 $params['skipLineItem'] = 1;
1620 elseif ($isRelatedId) {
1621 $params['contribution_mode'] = 'membership';
1623 $params['line_item'] = $lineItem;
1624 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array
::value('id', $this->_paymentProcessor
);
1625 if (isset($submittedValues['tax_amount'])) {
1626 $params['tax_amount'] = $submittedValues['tax_amount'];
1628 //create contribution.
1629 if ($isQuickConfig) {
1630 $params['is_quick_config'] = 1;
1632 $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
1634 // we are already handling note below, so to avoid duplicate notes against $contribution
1635 if (!empty($params['note']) && !empty($submittedValues['note'])) {
1636 unset($params['note']);
1638 $contribution = CRM_Contribute_BAO_Contribution
::create($params, $ids);
1640 // process associated membership / participant, CRM-4395
1641 if ($contribution->id
&& $action & CRM_Core_Action
::UPDATE
) {
1642 $this->statusMessage
[] = CRM_Contribute_BAO_Contribution
::transitionComponentWithReturnMessage($contribution->id
,
1643 $contribution->contribution_status_id
,
1644 CRM_Utils_Array
::value('contribution_status_id',
1647 $contribution->receive_date
1651 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1653 $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
1655 //send receipt mail.
1656 if ($contribution->id
&& !empty($formValues['is_email_receipt'])) {
1657 $formValues['contact_id'] = $this->_contactID
;
1658 $formValues['contribution_id'] = $contribution->id
;
1660 $formValues +
= CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
);
1662 // to get 'from email id' for send receipt
1663 $this->fromEmailId
= CRM_Utils_Array
::value('from_email_address', $formValues);
1664 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $formValues)) {
1665 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1669 $this->statusMessageTitle
= ts('Saved');
1673 if ($contribution->id
&& isset($formValues['product_name'][0])) {
1674 CRM_Contribute_Form_AdditionalInfo
::processPremium($submittedValues, $contribution->id
,
1675 $this->_premiumID
, $this->_options
1679 if ($contribution->id
&& array_key_exists('note', $submittedValues)) {
1680 CRM_Contribute_Form_AdditionalInfo
::processNote($submittedValues, $this->_contactID
, $contribution->id
, $this->_noteID
);
1683 CRM_Core_Session
::setStatus(implode(' ', $this->statusMessage
), $this->statusMessageTitle
, 'success');
1685 CRM_Contribute_BAO_Contribution
::updateRelatedPledge(
1689 (CRM_Utils_Array
::value('option_type', $formValues) == 2) ?
TRUE : FALSE,
1690 $formValues['total_amount'],
1691 CRM_Utils_Array
::value('total_amount', $this->_defaults
),
1692 $formValues['contribution_status_id'],
1693 CRM_Utils_Array
::value('contribution_status_id', $this->_defaults
)
1695 return $contribution;
1699 * Assign tax calculations to contribution receipts.
1701 * @param array $submittedValues
1702 * @param int $action
1703 * @param array $lineItem
1705 protected function invoicingPostProcessHook($submittedValues, $action, $lineItem) {
1707 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
1708 if (!CRM_Utils_Array
::value('invoicing', $invoiceSettings)) {
1712 $getTaxDetails = FALSE;
1714 foreach ($lineItem as $key => $value) {
1715 foreach ($value as $v) {
1716 if (isset($taxRate[(string) CRM_Utils_Array
::value('tax_rate', $v)])) {
1717 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $v);
1720 if (isset($v['tax_rate'])) {
1721 $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $v);
1722 $getTaxDetails = TRUE;
1728 if ($action & CRM_Core_Action
::UPDATE
) {
1729 if (isset($submittedValues['tax_amount'])) {
1730 $totalTaxAmount = $submittedValues['tax_amount'];
1733 $totalTaxAmount = $this->_values
['tax_amount'];
1735 $this->assign('totalTaxAmount', $totalTaxAmount);
1736 $this->assign('dataArray', $taxRate);
1739 if (!empty($submittedValues['price_set_id'])) {
1740 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1741 $this->assign('getTaxDetails', $getTaxDetails);
1742 $this->assign('dataArray', $taxRate);
1743 $this->assign('taxTerm', CRM_Utils_Array
::value('tax_term', $invoiceSettings));
1746 $this->assign('totalTaxAmount', CRM_Utils_Array
::value('tax_amount', $submittedValues));
1752 * Calculate non deductible amount.
1755 * if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1756 * if non_deductible_amount does NOT exist - then calculate it depending on:
1757 * $financialType->is_deductible and whether there is a product (premium).
1760 * @param $formValues
1764 protected function calculateNonDeductibleAmount($params, $formValues) {
1765 if (!empty($params['non_deductible_amount'])) {
1766 return $params['non_deductible_amount'];
1769 $priceSetId = CRM_Utils_Array
::value('price_set_id', $params);
1770 // return non-deductible amount if it is set at the price field option level
1771 if ($priceSetId && !empty($params['line_item'])) {
1772 $nonDeductibleAmount = CRM_Price_BAO_PriceSet
::getNonDeductibleAmountFromPriceSet($priceSetId, $params['line_item']);
1773 if (!empty($nonDeductibleAmount)) {
1774 return $nonDeductibleAmount;
1778 $financialType = new CRM_Financial_DAO_FinancialType();
1779 $financialType->id
= $params['financial_type_id'];
1780 $financialType->find(TRUE);
1782 if ($financialType->is_deductible
) {
1784 if (isset($formValues['product_name'][0])) {
1785 $selectProduct = $formValues['product_name'][0];
1787 // if there is a product - compare the value to the contribution amount
1788 if (isset($selectProduct)) {
1789 $productDAO = new CRM_Contribute_DAO_Product();
1790 $productDAO->id
= $selectProduct;
1791 $productDAO->find(TRUE);
1792 // product value exceeds contribution amount
1793 if ($params['total_amount'] < $productDAO->price
) {
1794 return $params['total_amount'];
1796 // product value does NOT exceed contribution amount
1798 return $productDAO->price
;
1801 // contribution is deductible - but there is no product
1806 // contribution is NOT deductible
1808 return $params['total_amount'];