3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2020 |
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
110 * The pledge values if this contribution is associated with pledge
113 public $_pledgeValues;
115 public $_contributeMode = 'direct';
120 * Parameter with confusing name.
124 public $_compContext;
129 * Possible From email addresses
142 * Store the line items if price set used.
150 * @todo explain why we use lineItem & lineItems
159 public $_softCreditInfo;
161 protected $_formType;
164 * Array of the payment fields to be displayed in the payment fieldset (pane) in billingBlock.tpl
165 * this contains all the information to describe these fields from quickform. See CRM_Core_Form_Payment getPaymentFormFieldsMetadata
169 public $_paymentFields = [];
171 * Logged in user's email.
184 * Price set as an array
194 public $userDisplayName;
197 * Status message to be shown to the user.
201 protected $statusMessage = [];
204 * Status message title to be shown to the user.
206 * Generally the payment processor message title is 'Complete' and offline is 'Saved'
207 * although this might not be a good fit with the broad range of processors.
211 protected $statusMessageTitle;
216 * Max row count for soft credits. The value here is +1 the actual number of
219 public $_softCreditItemCount = 11;
222 * Explicitly declare the form context.
224 public function getDefaultContext() {
229 * Set variables up before form is built.
231 public function preProcess() {
232 // Check permission for action.
233 if (!CRM_Core_Permission
::checkActionPermission('CiviContribute', $this->_action
)) {
234 // @todo replace with throw new CRM_Core_Exception().
235 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
238 parent
::preProcess();
240 $this->_formType
= CRM_Utils_Array
::value('formType', $_GET);
243 $this->_priceSetId
= CRM_Utils_Array
::value('priceSetId', $_GET);
244 $this->set('priceSetId', $this->_priceSetId
);
245 $this->assign('priceSetId', $this->_priceSetId
);
247 // Get the pledge payment id
248 $this->_ppID
= CRM_Utils_Request
::retrieve('ppid', 'Positive', $this);
250 $this->assign('action', $this->_action
);
252 // Get the contribution id if update
253 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive');
254 if (!empty($this->_id
)) {
255 $this->assignPaymentInfoBlock();
256 $this->assign('contribID', $this->_id
);
257 $this->assign('isUsePaymentBlock', TRUE);
260 $this->_context
= CRM_Utils_Request
::retrieve('context', 'Alphanumeric', $this);
261 $this->assign('context', $this->_context
);
263 $this->_compId
= CRM_Utils_Request
::retrieve('compId', 'Positive', $this);
265 $this->_compContext
= CRM_Utils_Request
::retrieve('compContext', 'String', $this);
267 //set the contribution mode.
268 $this->_mode
= CRM_Utils_Request
::retrieve('mode', 'Alphanumeric', $this);
270 $this->assign('contributionMode', $this->_mode
);
271 if ($this->_action
& CRM_Core_Action
::DELETE
) {
275 $this->_fromEmails
= CRM_Core_BAO_Email
::getFromEmail();
277 if (in_array('CiviPledge', CRM_Core_Config
::singleton()->enableComponents
) && !$this->_formType
) {
278 $this->preProcessPledge();
282 $this->showRecordLinkMesssage($this->_id
);
286 // Current contribution id.
288 $this->assignPremiumProduct($this->_id
);
289 $this->buildValuesAndAssignOnline_Note_Type($this->_id
, $this->_values
);
292 // when custom data is included in this page
293 if (!empty($_POST['hidden_custom'])) {
294 $this->applyCustomData('Contribution', CRM_Utils_Array
::value('financial_type_id', $_POST), $this->_id
);
297 $this->_lineItems
= [];
299 if (!empty($this->_compId
) && $this->_compContext
== 'participant') {
300 $this->assign('compId', $this->_compId
);
301 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_compId
);
304 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution', 1, TRUE, TRUE);
307 empty($lineItem) ?
NULL : $this->_lineItems
[] = $lineItem;
310 $this->assign('lineItem', empty($lineItem) ?
FALSE : [$lineItem]);
313 if ($this->_mode
&& $this->_id
) {
314 $this->_payNow
= TRUE;
315 $this->assign('payNow', $this->_payNow
);
316 CRM_Utils_System
::setTitle(ts('Pay with Credit Card'));
318 elseif ($this->_mode
) {
319 $this->setPageTitle($this->_ppID ?
ts('Credit Card Pledge Payment') : ts('Credit Card Contribution'));
322 $this->setPageTitle($this->_ppID ?
ts('Pledge Payment') : ts('Contribution'));
327 * Set default values.
331 public function setDefaultValues() {
332 $defaults = $this->_values
;
334 // Set defaults for pledge payment.
336 $defaults['total_amount'] = CRM_Utils_Array
::value('scheduled_amount', $this->_pledgeValues
['pledgePayment']);
337 $defaults['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $this->_pledgeValues
);
338 $defaults['currency'] = CRM_Utils_Array
::value('currency', $this->_pledgeValues
);
339 $defaults['option_type'] = 1;
342 if ($this->_action
& CRM_Core_Action
::DELETE
) {
346 $defaults['frequency_interval'] = 1;
347 $defaults['frequency_unit'] = 'month';
349 // Set soft credit defaults.
350 CRM_Contribute_Form_SoftCredit
::setDefaultValues($defaults, $this);
353 // @todo - remove this function as the parent does it too.
354 $config = CRM_Core_Config
::singleton();
355 // Set default country from config if no country set.
356 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
357 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry
;
360 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
361 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince
;
364 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID
);
365 $defaults = array_merge($defaults, $billingDefaults);
369 $this->_contactID
= $defaults['contact_id'];
371 elseif ($this->_contactID
) {
372 $defaults['contact_id'] = $this->_contactID
;
375 // Set $newCredit variable in template to control whether link to credit card mode is included.
376 $this->assign('newCredit', CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments());
378 // Fix the display of the monetary value, CRM-4038.
379 if (isset($defaults['total_amount'])) {
380 $total_value = $defaults['total_amount'];
381 $defaults['total_amount'] = CRM_Utils_Money
::format($total_value, NULL, '%a');
382 if (!empty($defaults['tax_amount'])) {
383 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
384 if (!(CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails))) {
385 $defaults['total_amount'] = CRM_Utils_Money
::format($total_value - $defaults['tax_amount'], NULL, '%a');
390 $amountFields = ['non_deductible_amount', 'fee_amount'];
391 foreach ($amountFields as $amt) {
392 if (isset($defaults[$amt])) {
393 $defaults[$amt] = CRM_Utils_Money
::format($defaults[$amt], NULL, '%a');
397 if ($this->_contributionType
) {
398 $defaults['financial_type_id'] = $this->_contributionType
;
401 if (empty($defaults['payment_instrument_id'])) {
402 $defaults['payment_instrument_id'] = $this->getDefaultPaymentInstrumentId();
405 if (!empty($defaults['is_test'])) {
406 $this->assign('is_test', TRUE);
409 $this->assign('showOption', TRUE);
410 // For Premium section.
411 if ($this->_premiumID
) {
412 $this->assign('showOption', FALSE);
413 $options = isset($this->_options
[$this->_productDAO
->product_id
]) ?
$this->_options
[$this->_productDAO
->product_id
] : "";
415 $this->assign('showOption', TRUE);
417 $options_key = CRM_Utils_Array
::key($this->_productDAO
->product_option
, $options);
419 $defaults['product_name'] = [$this->_productDAO
->product_id
, trim($options_key)];
422 $defaults['product_name'] = [$this->_productDAO
->product_id
];
424 if ($this->_productDAO
->fulfilled_date
) {
425 $defaults['fulfilled_date'] = $this->_productDAO
->fulfilled_date
;
429 if (isset($this->userEmail
)) {
430 $this->assign('email', $this->userEmail
);
433 if (!empty($defaults['is_pay_later'])) {
434 $this->assign('is_pay_later', TRUE);
436 $this->assign('contribution_status_id', CRM_Utils_Array
::value('contribution_status_id', $defaults));
437 if (!empty($defaults['contribution_status_id']) && in_array(
438 CRM_Contribute_PseudoConstant
::contributionStatus($defaults['contribution_status_id'], 'name'),
439 // Historically not 'Cancelled' hence not using CRM_Contribute_BAO_Contribution::isContributionStatusNegative.
440 ['Refunded', 'Chargeback']
442 $defaults['refund_trxn_id'] = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionTrxnID($this->_id
);
445 $defaults['refund_trxn_id'] = isset($defaults['trxn_id']) ?
$defaults['trxn_id'] : NULL;
448 if (!$this->_id
&& empty($defaults['receive_date'])) {
449 $defaults['receive_date'] = date('Y-m-d H:i:s');
452 $currency = CRM_Utils_Array
::value('currency', $defaults);
453 $this->assign('currency', $currency);
454 // Hack to get currency info to the js layer. CRM-11440.
455 CRM_Utils_Money
::format(1);
456 $this->assign('currencySymbol', CRM_Utils_Array
::value($currency, CRM_Utils_Money
::$_currencySymbols));
457 $this->assign('totalAmount', CRM_Utils_Array
::value('total_amount', $defaults));
459 // Inherit campaign from pledge.
460 if ($this->_ppID
&& !empty($this->_pledgeValues
['campaign_id'])) {
461 $defaults['campaign_id'] = $this->_pledgeValues
['campaign_id'];
464 $this->_defaults
= $defaults;
469 * Build the form object.
471 public function buildQuickForm() {
473 $this->add('hidden', 'id', $this->_id
);
476 if ($this->_action
& CRM_Core_Action
::DELETE
) {
480 'name' => ts('Delete'),
481 'spacing' => ' ',
486 'name' => ts('Cancel'),
492 // FIXME: This probably needs to be done in preprocess
493 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()
494 && $this->_action
& CRM_Core_Action
::UPDATE
495 && CRM_Utils_Array
::value('financial_type_id', $this->_values
)
497 $financialTypeID = CRM_Contribute_PseudoConstant
::financialType($this->_values
['financial_type_id']);
498 CRM_Financial_BAO_FinancialType
::checkPermissionedLineItems($this->_id
, 'edit');
499 if (!CRM_Core_Permission
::check('edit contributions of type ' . $financialTypeID)) {
500 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
505 //tax rate from financialType
506 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant
::getTaxRates()));
507 $this->assign('currencies', json_encode(CRM_Core_OptionGroup
::values('currencies_enabled')));
509 // build price set form.
510 $buildPriceSet = FALSE;
511 $invoicing = CRM_Invoicing_Utils
::isInvoicingEnabled();
512 $this->assign('invoicing', $invoicing);
514 $buildRecurBlock = FALSE;
516 // display tax amount on edit contribution page
517 if ($invoicing && $this->_action
& CRM_Core_Action
::UPDATE
&& isset($this->_values
['tax_amount'])) {
518 $this->assign('totalTaxAmount', $this->_values
['tax_amount']);
521 if (empty($this->_lineItems
) &&
522 ($this->_priceSetId ||
!empty($_POST['price_set_id']))
524 $buildPriceSet = TRUE;
525 $getOnlyPriceSetElements = TRUE;
526 if (!$this->_priceSetId
) {
527 $this->_priceSetId
= $_POST['price_set_id'];
528 $getOnlyPriceSetElements = FALSE;
531 $this->set('priceSetId', $this->_priceSetId
);
532 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
534 // get only price set form elements.
535 if ($getOnlyPriceSetElements) {
539 // use to build form during form rule.
540 $this->assign('buildPriceSet', $buildPriceSet);
542 $defaults = $this->_values
;
543 $additionalDetailFields = [
547 'non_deductible_amount',
550 foreach ($additionalDetailFields as $key) {
551 if (!empty($defaults[$key])) {
552 $defaults['hidden_AdditionalDetail'] = 1;
557 if ($this->_productDAO
) {
558 if ($this->_productDAO
->product_id
) {
559 $defaults['hidden_Premium'] = 1;
563 if ($this->_noteID
&&
564 !CRM_Utils_System
::isNull($this->_values
['note'])
566 $defaults['hidden_AdditionalDetail'] = 1;
570 if (empty($this->_payNow
)) {
571 $paneNames[ts('Additional Details')] = 'AdditionalDetail';
574 //Add Premium pane only if Premium is exists.
575 $dao = new CRM_Contribute_DAO_Product();
578 if ($dao->find(TRUE) && empty($this->_payNow
)) {
579 $paneNames[ts('Premium Information')] = 'Premium';
582 $this->payment_instrument_id
= CRM_Utils_Array
::value('payment_instrument_id', $defaults, $this->getDefaultPaymentInstrumentId());
583 if (CRM_Core_Payment_Form
::buildPaymentForm($this, $this->_paymentProcessor
, FALSE, TRUE, $this->payment_instrument_id
) == TRUE) {
584 if (!empty($this->_recurPaymentProcessors
)) {
585 $buildRecurBlock = TRUE;
587 // ppID denotes a pledge payment.
588 foreach ($this->_paymentProcessors
as $processor) {
589 if (!empty($processor['is_recur']) && !empty($processor['object']) && $processor['object']->supports('recurContributionsForPledges')) {
590 $buildRecurBlock = TRUE;
593 $buildRecurBlock = FALSE;
596 if ($buildRecurBlock) {
597 CRM_Contribute_Form_Contribution_Main
::buildRecur($this);
598 $this->setDefaults(['is_recur' => 0]);
599 $this->assign('buildRecurBlock', TRUE);
603 $this->addPaymentProcessorSelect(FALSE, $buildRecurBlock);
605 foreach ($paneNames as $name => $type) {
606 $allPanes[$name] = $this->generatePane($type, $defaults);
609 $qfKey = $this->controller
->_key
;
610 $this->assign('qfKey', $qfKey);
611 $this->assign('allPanes', $allPanes);
613 $this->addFormRule(['CRM_Contribute_Form_Contribution', 'formRule'], $this);
615 if ($this->_formType
) {
616 $this->assign('formType', $this->_formType
);
620 $this->applyFilter('__ALL__', 'trim');
622 //need to assign custom data type and subtype to the template
623 $this->assign('customDataType', 'Contribution');
624 $this->assign('customDataSubType', $this->_contributionType
);
625 $this->assign('entityID', $this->_id
);
627 $contactField = $this->addEntityRef('contact_id', ts('Contributor'), ['create' => TRUE], TRUE);
628 if ($this->_context
!= 'standalone') {
629 $contactField->freeze();
632 $attributes = CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Contribution');
634 // Check permissions for financial type first
635 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes, $this->_action
);
636 if (empty($financialTypes)) {
637 CRM_Core_Error
::statusBounce(ts('You do not have all the permissions needed for this page.'));
639 $financialType = $this->add('select', 'financial_type_id',
640 ts('Financial Type'),
641 ['' => ts('- select -')] +
$financialTypes,
643 ['onChange' => "CRM.buildCustomData( 'Contribution', this.value );"]
646 $paymentInstrument = FALSE;
648 // payment_instrument isn't required in edit and will not be present when payment block is enabled.
649 $required = $this->_id ?
FALSE : TRUE;
650 $checkPaymentID = array_search('Check', CRM_Contribute_PseudoConstant
::paymentInstrument('name'));
651 $paymentInstrument = $this->add('select', 'payment_instrument_id',
652 ts('Payment Method'),
653 ['' => ts('- select -')] + CRM_Contribute_PseudoConstant
::paymentInstrument(),
654 $required, ['onChange' => "return showHideByValue('payment_instrument_id','{$checkPaymentID}','checkNumber','table-row','select',false);"]
658 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), ['class' => 'twelve'] +
$attributes['trxn_id']);
660 //add receipt for offline contribution
661 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
663 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
665 $component = 'contribution';
666 $componentDetails = [];
668 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
669 if (!empty($componentDetails['membership'])) {
670 $component = 'membership';
672 elseif (!empty($componentDetails['participant'])) {
673 $component = 'participant';
677 $component = 'pledge';
679 $status = CRM_Contribute_BAO_Contribution_Utils
::getContributionStatuses($component, $this->_id
);
681 // define the status IDs that show the cancellation info, see CRM-17589
682 $cancelInfo_show_ids = [];
683 foreach (array_keys($status) as $status_id) {
684 if (CRM_Contribute_BAO_Contribution
::isContributionStatusNegative($status_id)) {
685 $cancelInfo_show_ids[] = "'$status_id'";
688 $this->assign('cancelInfo_show_ids', implode(',', $cancelInfo_show_ids));
690 $statusElement = $this->add('select', 'contribution_status_id',
691 ts('Contribution Status'),
696 $currencyFreeze = FALSE;
697 if (!empty($this->_payNow
) && ($this->_action
& CRM_Core_Action
::UPDATE
)) {
698 $statusElement->freeze();
699 $currencyFreeze = TRUE;
700 $attributes['total_amount']['readonly'] = TRUE;
703 // CRM-16189, add Revenue Recognition Date
704 if (Civi
::settings()->get('deferred_revenue_enabled')) {
705 $revenueDate = $this->add('date', 'revenue_recognition_date', ts('Revenue Recognition Date'), CRM_Core_SelectValues
::date(NULL, 'M Y', NULL, 5));
706 if ($this->_id
&& !CRM_Contribute_BAO_Contribution
::allowUpdateRevenueRecognitionDate($this->_id
)) {
707 $revenueDate->freeze();
712 $this->addField('receive_date', ['entity' => 'contribution'], !$this->_mode
, FALSE);
713 $this->addField('receipt_date', ['entity' => 'contribution'], FALSE, FALSE);
714 $this->addField('cancel_date', ['entity' => 'contribution', 'label' => ts('Cancelled / Refunded Date')], FALSE, FALSE);
716 if ($this->_online
) {
717 $this->assign('hideCalender', TRUE);
720 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
723 if (empty($this->_lineItems
)) {
724 $buildPriceSet = FALSE;
725 $priceSets = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute');
726 if (!empty($priceSets) && !$this->_ppID
) {
727 $buildPriceSet = TRUE;
730 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
731 // and if we already have line items for that participant. CRM-5095
732 if ($buildPriceSet && $this->_id
) {
733 $pledgePaymentId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
738 if ($pledgePaymentId) {
739 $buildPriceSet = FALSE;
741 if ($participantID = CRM_Utils_Array
::value('participant', $componentDetails)) {
742 $participantLI = CRM_Price_BAO_LineItem
::getLineItems($participantID);
743 if (!CRM_Utils_System
::isNull($participantLI)) {
744 $buildPriceSet = FALSE;
749 $hasPriceSets = FALSE;
750 if ($buildPriceSet) {
751 $hasPriceSets = TRUE;
752 // CRM-16451: set financial type of 'Price Set' in back office contribution
753 // instead of selecting manually
754 $financialTypeIds = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute', 'financial_type_id');
755 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
757 '' => ts('Choose price set'),
759 NULL, ['onchange' => "buildAmount( this.value, " . json_encode($financialTypeIds) . ");"]
761 if ($this->_online
&& !($this->_action
& CRM_Core_Action
::UPDATE
)) {
765 $this->assign('hasPriceSets', $hasPriceSets);
766 if (!($this->_action
& CRM_Core_Action
::UPDATE
)) {
767 if ($this->_online ||
$this->_ppID
) {
768 $attributes['total_amount'] = array_merge($attributes['total_amount'], [
770 'style' => "background-color:#EBECE4",
773 '1' => ts('Adjust Pledge Payment Schedule?'),
774 '2' => ts('Adjust Total Pledge Amount?'),
776 $this->addRadio('option_type',
782 $currencyFreeze = TRUE;
786 $totalAmount = $this->addMoney('total_amount',
788 ($hasPriceSets) ?
FALSE : TRUE,
789 $attributes['total_amount'],
790 TRUE, 'currency', NULL, $currencyFreeze
794 $this->add('text', 'source', ts('Source'), CRM_Utils_Array
::value('source', $attributes));
796 // CRM-7362 --add campaigns.
797 CRM_Campaign_BAO_Campaign
::addCampaign($this, CRM_Utils_Array
::value('campaign_id', $this->_values
));
799 if (empty($this->_payNow
)) {
800 CRM_Contribute_Form_SoftCredit
::buildQuickForm($this);
805 $js = ['onclick' => "return verify( );"];
808 $mailingInfo = Civi
::settings()->get('mailing_backend');
809 $this->assign('outBound_option', $mailingInfo['outBound_option']);
814 'name' => ts('Save'),
820 'name' => ts('Save and New'),
826 'name' => ts('Cancel'),
830 // if contribution is related to membership or participant freeze Financial Type, Amount
832 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
833 $isCancelledStatus = ($this->_values
['contribution_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Cancelled'));
835 if (!empty($componentDetails['membership']) ||
836 !empty($componentDetails['participant']) ||
837 // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
838 // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
842 $totalAmount->freeze();
843 $this->getElement('currency')->freeze();
845 if ($isCancelledStatus) {
846 $paymentInstrument->freeze();
849 $financialType->freeze();
850 $this->assign('freezeFinancialType', TRUE);
854 if ($this->_action
& CRM_Core_Action
::VIEW
) {
862 * @param array $fields
863 * The input form values.
864 * @param array $files
865 * The uploaded files if any.
869 * true if no errors, else array of errors
871 public static function formRule($fields, $files, $self) {
873 // Check for Credit Card Contribution.
875 if (empty($fields['payment_processor_id'])) {
876 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
879 // validate payment instrument (e.g. credit card number)
880 CRM_Core_Payment_Form
::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, NULL);
884 // Do the amount validations.
885 if (empty($fields['total_amount']) && empty($self->_lineItems
)) {
886 if ($priceSetId = CRM_Utils_Array
::value('price_set_id', $fields)) {
887 CRM_Price_BAO_PriceField
::priceSetValidation($priceSetId, $fields, $errors);
891 $softErrors = CRM_Contribute_Form_SoftCredit
::formRule($fields, $errors, $self);
893 //CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
894 CRM_Contribute_BAO_ContributionRecur
::validateRecurContribution($fields, $files, $self, $errors);
896 // Form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
897 if (($self->_action
& CRM_Core_Action
::UPDATE
)
899 && $self->_values
['contribution_status_id'] != $fields['contribution_status_id']
901 CRM_Contribute_BAO_Contribution
::checkStatusValidation($self->_values
, $fields, $errors);
903 // CRM-16015, add form-rule to restrict change of financial type if using price field of different financial type
904 if (($self->_action
& CRM_Core_Action
::UPDATE
)
906 && $self->_values
['financial_type_id'] != $fields['financial_type_id']
908 CRM_Contribute_BAO_Contribution
::checkFinancialTypeChange(NULL, $self->_id
, $errors);
910 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
911 if (!empty($fields['fee_amount']) && !empty($fields['financial_type_id']) && $financialType = CRM_Contribute_BAO_Contribution
::validateFinancialType($fields['financial_type_id'])) {
912 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
915 // $trxn_id must be unique CRM-13919
916 if (!empty($fields['trxn_id'])) {
917 $queryParams = [1 => [$fields['trxn_id'], 'String']];
918 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
920 $queryParams[2] = [(int) $self->_id
, 'Integer'];
921 $query .= ' and id !=%2';
923 $tCnt = CRM_Core_DAO
::singleValueQuery($query, $queryParams);
925 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', [1 => $fields['trxn_id']]);
928 if (!empty($fields['revenue_recognition_date'])
929 && count(array_filter($fields['revenue_recognition_date'])) == 1
931 $errors['revenue_recognition_date'] = ts('Month and Year are required field for Revenue Recognition.');
935 CRM_Financial_BAO_FinancialAccount
::checkFinancialTypeHasDeferred($fields, $self->_id
, $self->_priceSet
['fields']);
937 catch (CRM_Core_Exception
$e) {
938 $errors['financial_type_id'] = ' ';
939 $errors['_qf_default'] = $e->getMessage();
941 $errors = array_merge($errors, $softErrors);
946 * Process the form submission.
948 public function postProcess() {
949 if ($this->_action
& CRM_Core_Action
::DELETE
) {
950 CRM_Contribute_BAO_Contribution
::deleteContribution($this->_id
);
951 CRM_Core_Session
::singleton()->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
952 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
956 // Get the submitted form values.
957 $submittedValues = $this->controller
->exportValues($this->_name
);
960 $contribution = $this->submit($submittedValues, $this->_action
, $this->_ppID
);
962 catch (PaymentProcessorException
$e) {
963 // Set the contribution mode.
964 $urlParams = "action=add&cid={$this->_contactID}";
966 $urlParams .= "&mode={$this->_mode}";
968 if (!empty($this->_ppID
)) {
969 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
972 CRM_Core_Error
::statusBounce($e->getMessage(), $urlParams, ts('Payment Processor Error'));
974 $session = CRM_Core_Session
::singleton();
975 $buttonName = $this->controller
->getButtonName();
976 if ($this->_context
== 'standalone') {
977 if ($buttonName == $this->getButtonName('upload', 'new')) {
978 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contribute/add',
979 'reset=1&action=add&context=standalone'
983 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
984 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
988 elseif ($this->_context
== 'contribution' && $this->_mode
&& $buttonName == $this->getButtonName('upload', 'new')) {
989 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
990 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
993 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
994 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
995 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
999 //store contribution ID if not yet set (on create)
1000 if (empty($this->_id
) && !empty($contribution->id
)) {
1001 $this->_id
= $contribution->id
;
1003 if (!empty($this->_id
) && CRM_Core_Permission
::access('CiviMember')) {
1004 $membershipPaymentCount = civicrm_api3('MembershipPayment', 'getCount', ['contribution_id' => $this->_id
]);
1005 if ($membershipPaymentCount) {
1006 $this->ajaxResponse
['updateTabs']['#tab_member'] = CRM_Contact_BAO_Contact
::getCountComponent('membership', $this->_contactID
);
1009 if (!empty($this->_id
) && CRM_Core_Permission
::access('CiviEvent')) {
1010 $participantPaymentCount = civicrm_api3('ParticipantPayment', 'getCount', ['contribution_id' => $this->_id
]);
1011 if ($participantPaymentCount) {
1012 $this->ajaxResponse
['updateTabs']['#tab_participant'] = CRM_Contact_BAO_Contact
::getCountComponent('participant', $this->_contactID
);
1018 * Process credit card payment.
1020 * @param array $submittedValues
1021 * @param array $lineItem
1023 * @param int $contactID
1026 * @return bool|\CRM_Contribute_DAO_Contribution
1028 * @throws \CRM_Core_Exception
1029 * @throws \Civi\Payment\Exception\PaymentProcessorException
1030 * @throws \CiviCRM_API3_Exception
1032 protected function processCreditCard($submittedValues, $lineItem, $contactID) {
1033 $isTest = ($this->_mode
== 'test') ?
1 : 0;
1034 // CRM-12680 set $_lineItem if its not set
1035 // @todo - I don't believe this would ever BE set. I can't find anywhere in the code.
1036 // It would be better to pass line item out to functions than $this->_lineItem as
1037 // we don't know what is being changed where.
1038 if (empty($this->_lineItem
) && !empty($lineItem)) {
1039 $this->_lineItem
= $lineItem;
1042 $this->_paymentObject
= Civi\Payment\System
::singleton()->getById($submittedValues['payment_processor_id']);
1043 $this->_paymentProcessor
= $this->_paymentObject
->getPaymentProcessor();
1045 // Set source if not set
1046 if (empty($submittedValues['source'])) {
1047 $userID = CRM_Core_Session
::singleton()->get('userID');
1048 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1051 $submittedValues['source'] = ts('Submit Credit Card Payment by: %1', [1 => $userSortName]);
1054 $params = $submittedValues;
1055 $this->_params
= array_merge($this->_params
, $submittedValues);
1057 // Mapping requiring documentation.
1058 $this->_params
['payment_processor'] = $submittedValues['payment_processor_id'];
1060 $now = date('YmdHis');
1062 $this->_contributorEmail
= $this->userEmail
;
1063 $this->_contributorContactID
= $contactID;
1064 $this->processBillingAddress();
1065 if (!empty($params['source'])) {
1066 unset($params['source']);
1069 $this->_params
['amount'] = $this->_params
['total_amount'];
1070 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
1071 // function to get correct amount level consistently. Remove setting of the amount level in
1072 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
1073 // to cover all variants.
1074 $this->_params
['amount_level'] = 0;
1075 $this->_params
['description'] = ts("Contribution submitted by a staff person using contributor's credit card");
1076 $this->_params
['currencyID'] = CRM_Utils_Array
::value('currency',
1078 CRM_Core_Config
::singleton()->defaultCurrency
1081 $this->_params
['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $params);
1082 $this->_params
['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $params);
1083 $this->_params
['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $params);
1085 //Add common data to formatted params
1086 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
1088 if (empty($this->_params
['invoice_id'])) {
1089 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
1092 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
1095 // At this point we've created a contact and stored its address etc
1096 // all the payment processors expect the name and address to be in the
1097 // so we copy stuff over to first_name etc.
1098 $paymentParams = $this->_params
;
1099 $paymentParams['contactID'] = $contactID;
1100 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
1102 $financialType = new CRM_Financial_DAO_FinancialType();
1103 $financialType->id
= $params['financial_type_id'];
1104 $financialType->find(TRUE);
1106 // Add some financial type details to the params list
1107 // if folks need to use it.
1108 $paymentParams['contributionType_name'] = $this->_params
['contributionType_name'] = $financialType->name
;
1109 $paymentParams['contributionPageID'] = NULL;
1111 if (!empty($this->_params
['is_email_receipt'])) {
1112 $paymentParams['email'] = $this->userEmail
;
1113 $paymentParams['is_email_receipt'] = 1;
1116 $paymentParams['is_email_receipt'] = 0;
1117 $this->_params
['is_email_receipt'] = 0;
1119 if (!empty($this->_params
['receive_date'])) {
1120 $paymentParams['receive_date'] = $this->_params
['receive_date'];
1123 if (!empty($this->_params
['is_email_receipt'])) {
1124 $this->_params
['receipt_date'] = $now;
1127 $this->set('params', $this->_params
);
1129 $this->assign('receive_date', $this->_params
['receive_date']);
1131 // Result has all the stuff we need
1132 // lets archive it to a financial transaction
1133 if ($financialType->is_deductible
) {
1134 $this->assign('is_deductible', TRUE);
1135 $this->set('is_deductible', TRUE);
1137 $contributionParams = [
1138 'id' => CRM_Utils_Array
::value('contribution_id', $this->_params
),
1139 'contact_id' => $contactID,
1140 'line_item' => $lineItem,
1141 'is_test' => $isTest,
1142 'campaign_id' => CRM_Utils_Array
::value('campaign_id', $this->_params
),
1143 'contribution_page_id' => CRM_Utils_Array
::value('contribution_page_id', $this->_params
),
1144 'source' => CRM_Utils_Array
::value('source', $paymentParams, CRM_Utils_Array
::value('description', $paymentParams)),
1145 'thankyou_date' => CRM_Utils_Array
::value('thankyou_date', $this->_params
),
1147 $contributionParams['payment_instrument_id'] = $this->_paymentProcessor
['payment_instrument_id'];
1149 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processFormContribution($this,
1152 $contributionParams,
1156 CRM_Utils_Array
::value('is_recur', $this->_params
)
1159 $paymentParams['contributionID'] = $contribution->id
;
1160 $paymentParams['contributionTypeID'] = $contribution->financial_type_id
;
1161 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
1162 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1164 if ($paymentParams['amount'] > 0.0) {
1165 // force a re-get of the payment processor in case the form changed it, CRM-7179
1166 // NOTE - I expect this is obsolete.
1167 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
1169 $completeStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
1170 $result = $payment->doPayment($paymentParams, 'contribute');
1171 $this->assign('trxn_id', $result['trxn_id']);
1172 $contribution->trxn_id
= $result['trxn_id'];
1173 /* Our scenarios here are
1174 * 1) the payment failed & an Exception should have been thrown
1175 * 2) the payment succeeded but the payment is not immediate (for example a recurring payment
1176 * with a delayed start)
1177 * 3) the payment succeeded with an immediate payment.
1179 * The doPayment function ensures that payment_status_id is always set
1180 * as historically we have had to guess from the context - ie doDirectPayment
1181 * = error or success, unless it is a recurring contribution in which case it is pending.
1183 if ($result['payment_status_id'] == $completeStatusId) {
1185 civicrm_api3('contribution', 'completetransaction', [
1186 'id' => $contribution->id
,
1187 'trxn_id' => $result['trxn_id'],
1188 'payment_processor_id' => $this->_paymentProcessor
['id'],
1189 'is_transactional' => FALSE,
1190 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $result),
1191 'card_type_id' => CRM_Utils_Array
::value('card_type_id', $paymentParams),
1192 'pan_truncation' => CRM_Utils_Array
::value('pan_truncation', $paymentParams),
1193 'is_email_receipt' => FALSE,
1195 // This has now been set to 1 in the DB - declare it here also
1196 $contribution->contribution_status_id
= 1;
1198 catch (CiviCRM_API3_Exception
$e) {
1199 if ($e->getErrorCode() != 'contribution_completed') {
1200 throw new CRM_Core_Exception('Failed to update contribution in database');
1205 // Save the trxn_id.
1206 $contribution->save();
1209 catch (PaymentProcessorException
$e) {
1210 CRM_Contribute_BAO_Contribution
::failPayment($contribution->id
, $paymentParams['contactID'], $e->getMessage());
1211 throw new PaymentProcessorException($e->getMessage());
1214 // Send receipt mail.
1215 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1216 if ($contribution->id
&& !empty($this->_params
['is_email_receipt'])) {
1217 $this->_params
['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $result);
1218 $this->_params
['contact_id'] = $contactID;
1219 $this->_params
['contribution_id'] = $contribution->id
;
1220 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $this->_params
, TRUE)) {
1221 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1225 return $contribution;
1229 * Generate the data to construct a snippet based pane.
1231 * This form also assigns the showAdditionalInfo var based on historical code.
1232 * This appears to mean 'there is a pane to show'.
1234 * @param string $type
1235 * Type of Pane - this is generally used to determine the function name used to build it
1236 * - e.g CreditCard, AdditionalDetail
1237 * @param array $defaults
1240 * We aim to further refactor & simplify this but currently
1242 * - should additional info be shown?
1244 protected function generatePane($type, $defaults) {
1245 $urlParams = "snippet=4&formType={$type}";
1247 $urlParams .= "&mode={$this->_mode}";
1251 if ($type == 'CreditCard' ||
1252 $type == 'DirectDebit'
1258 'url' => CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams),
1263 // See if we need to include this paneName in the current form.
1264 if ($this->_formType
== $type ||
!empty($_POST["hidden_{$type}"]) ||
1265 CRM_Utils_Array
::value("hidden_{$type}", $defaults)
1267 $this->assign('showAdditionalInfo', TRUE);
1268 $pane['open'] = 'true';
1271 if ($type == 'CreditCard' ||
$type == 'DirectDebit') {
1272 // @todo would be good to align tpl name with form name...
1273 // @todo document why this hidden variable is required.
1274 $this->add('hidden', 'hidden_' . $type, 1);
1278 $additionalInfoFormFunction = 'build' . $type;
1279 CRM_Contribute_Form_AdditionalInfo
::$additionalInfoFormFunction($this);
1285 * Wrapper for unit testing the post process submit function.
1287 * (If we expose through api we can get default additions 'for free').
1289 * @param array $params
1290 * @param int $action
1291 * @param string|null $creditCardMode
1293 * @return CRM_Contribute_BAO_Contribution
1295 * @throws \CRM_Core_Exception
1296 * @throws \CiviCRM_API3_Exception
1297 * @throws \Civi\Payment\Exception\PaymentProcessorException
1299 public function testSubmit($params, $action, $creditCardMode = NULL) {
1301 'soft_credit_contact_id' => [],
1302 'receive_date' => date('Y-m-d H:i:s'),
1303 'receipt_date' => '',
1304 'cancel_date' => '',
1305 'hidden_Premium' => 1,
1308 if (!empty($params['id'])) {
1309 $existingContribution = civicrm_api3('contribution', 'getsingle', [
1310 'id' => $params['id'],
1312 $this->_id
= $params['id'];
1313 $this->_values
= $existingContribution;
1314 if (CRM_Contribute_BAO_Contribution
::checkContributeSettings('invoicing')) {
1315 $this->_values
['tax_amount'] = civicrm_api3('contribution', 'getvalue', [
1316 'id' => $params['id'],
1317 'return' => 'tax_amount',
1322 $existingContribution = [];
1325 $this->_defaults
['contribution_status_id'] = CRM_Utils_Array
::value('contribution_status_id',
1326 $existingContribution
1329 $this->_defaults
['total_amount'] = CRM_Utils_Array
::value('total_amount',
1330 $existingContribution
1333 if ($creditCardMode) {
1334 $this->_mode
= $creditCardMode;
1337 // Required because processCreditCard calls set method on this.
1338 $_SERVER['REQUEST_METHOD'] = 'GET';
1339 $this->controller
= new CRM_Core_Controller();
1341 CRM_Contribute_Form_AdditionalInfo
::buildPremium($this);
1343 $this->_fields
= [];
1344 return $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array
::value('pledge_payment_id', $params));
1349 * @param array $submittedValues
1351 * @param int $action
1353 * - CRM_Core_Action::UPDATE
1355 * @param $pledgePaymentID
1357 * @return \CRM_Contribute_BAO_Contribution
1359 * @throws \CRM_Core_Exception
1360 * @throws \CiviCRM_API3_Exception
1361 * @throws \Civi\Payment\Exception\PaymentProcessorException
1363 protected function submit($submittedValues, $action, $pledgePaymentID) {
1364 $pId = $contribution = $isRelatedId = FALSE;
1365 $this->_params
= $submittedValues;
1366 $this->beginPostProcess();
1367 // reassign submitted form values if the any information is formatted via beginPostProcess
1368 $submittedValues = $this->_params
;
1370 if (!empty($submittedValues['price_set_id']) && $action & CRM_Core_Action
::UPDATE
) {
1371 $line = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution');
1372 $lineID = key($line);
1373 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array
::value('price_field_id', $line[$lineID]), 'price_set_id');
1374 $quickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1375 // Why do we do this? Seems like a like a wrapper for old functionality - but single line price sets & quick
1376 // config should be treated the same.
1378 CRM_Price_BAO_LineItem
::deleteLineItems($this->_id
, 'civicrm_contribution');
1382 // Process price set and get total amount and line items.
1384 $priceSetId = CRM_Utils_Array
::value('price_set_id', $submittedValues);
1385 if (empty($priceSetId) && !$this->_id
) {
1386 $this->_priceSetId
= $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1387 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
1388 $fieldID = key($this->_priceSet
['fields']);
1389 $fieldValueId = key($this->_priceSet
['fields'][$fieldID]['options']);
1390 $this->_priceSet
['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1391 $submittedValues['price_' . $fieldID] = 1;
1394 // Every contribution has a price-set - the only reason it shouldn't be set is if we are dealing with
1395 // quick config (very very arguably) & yet we see that this could still be quick config so this should be understood
1396 // as a point of fragility rather than a logical 'if' clause.
1398 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
1399 $submittedValues, $lineItem[$priceSetId], NULL, $priceSetId);
1400 // Unset tax amount for offline 'is_quick_config' contribution.
1401 // @todo WHY - quick config was conceived as a quick way to configure contribution forms.
1402 // this is an example of 'other' functionality being hung off it.
1403 if ($this->_priceSet
['is_quick_config'] &&
1404 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant
::getTaxRates())
1406 unset($submittedValues['tax_amount']);
1408 $submittedValues['total_amount'] = CRM_Utils_Array
::value('amount', $submittedValues);
1412 if ($this->_compId
) {
1413 if ($this->_context
== 'participant') {
1414 $pId = $this->_compId
;
1416 elseif ($this->_context
== 'membership') {
1417 $isRelatedId = TRUE;
1420 $pId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id
, 'participant_id', 'contribution_id');
1424 $contributionDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1425 if (array_key_exists('membership', $contributionDetails)) {
1426 $isRelatedId = TRUE;
1428 elseif (array_key_exists('participant', $contributionDetails)) {
1429 $pId = $contributionDetails['participant'];
1432 if (!empty($this->_payNow
)) {
1433 $this->_params
['contribution_id'] = $this->_id
;
1437 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id
) {
1438 // CRM-10117 update the line items for participants.
1439 // @todo - if we are completing a contribution then the api call
1440 // civicrm_api3('Contribution', 'completetransaction') should take care of
1441 // all associated updates rather than replicating them on the form layer.
1443 $entityTable = 'participant';
1445 $isRelatedId = FALSE;
1446 $participantParams = [
1447 'fee_amount' => $submittedValues['total_amount'],
1450 CRM_Event_BAO_Participant
::add($participantParams);
1451 if (empty($this->_lineItems
)) {
1452 $this->_lineItems
[] = CRM_Price_BAO_LineItem
::getLineItems($entityID, 'participant', TRUE);
1456 $entityTable = 'contribution';
1457 $entityID = $this->_id
;
1460 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, $entityTable, FALSE, TRUE, $isRelatedId);
1461 foreach (array_keys($lineItems) as $id) {
1462 $lineItems[$id]['id'] = $id;
1464 $itemId = key($lineItems);
1465 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1466 $this->_priceSetId
= CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1469 // @todo see above - new functionality has been inappropriately added to the quick config concept
1470 // and new functionality has been added onto the form layer rather than the BAO :-(
1471 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1472 //CRM-16833: Ensure tax is applied only once for membership conribution, when status changed.(e.g Pending to Completed).
1473 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1474 if (!(CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails))) {
1475 if (!($this->_action
& CRM_Core_Action
::UPDATE
&& (($this->_defaults
['contribution_status_id'] != $submittedValues['contribution_status_id'])))) {
1476 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule
::cleanMoney(CRM_Utils_Array
::value('total_amount', $submittedValues));
1480 // Update line total and total amount with tax on edit.
1481 $financialItemsId = CRM_Core_PseudoConstant
::getTaxRates();
1482 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1483 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1486 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1487 $submittedValues['tax_amount'] = 'null';
1489 if ($lineItems[$itemId]['tax_rate']) {
1490 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total'];
1491 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] +
$lineItems[$itemId]['tax_amount'];
1492 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1495 // CRM-10117 update the line items for participants.
1496 if (!empty($lineItems[$itemId]['price_field_id'])) {
1497 $lineItem[$this->_priceSetId
] = $lineItems;
1502 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1505 //CRM-11529 for quick config back office transactions
1506 //when financial_type_id is passed in form, update the
1507 //line items with the financial type selected in form
1508 // NOTE that this IS still a legitimate use of 'quick-config' for contributions under the current DB but
1509 // we should look at having a price field per contribution type & then there would be little reason
1510 // for the back-office contribution form postProcess to know if it is a quick-config form.
1511 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array
::value($this->_priceSetId
, $lineItem)
1513 foreach ($lineItem[$this->_priceSetId
] as &$values) {
1514 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1518 if (!isset($submittedValues['total_amount'])) {
1519 $submittedValues['total_amount'] = CRM_Utils_Array
::value('total_amount', $this->_values
);
1520 // Avoid tax amount deduction on edit form and keep it original, because this will lead to error described in CRM-20676
1522 $submittedValues['total_amount'] -= CRM_Utils_Array
::value('tax_amount', $this->_values
, 0);
1525 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
1527 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
1528 if ($this->_id
&& count($isEmpty) == 1 && key($isEmpty) == NULL) {
1529 civicrm_api3('ContributionSoft', 'get', ['contribution_id' => $this->_id
, 'pcp_id' => NULL, 'api.ContributionSoft.delete' => 1]);
1532 // set the contact, when contact is selected
1533 if (!empty($submittedValues['contact_id'])) {
1534 $this->_contactID
= $submittedValues['contact_id'];
1537 $formValues = $submittedValues;
1539 // Credit Card Contribution.
1541 $paramsSetByPaymentProcessingSubsystem = [
1543 'payment_instrument_id',
1544 'contribution_status_id',
1548 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1549 if (isset($formValues[$key])) {
1550 unset($formValues[$key]);
1553 $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID
);
1554 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1555 $formValues[$key] = $contribution->$key;
1559 // Offline Contribution.
1560 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1562 // get the required field value only.
1565 'contact_id' => $this->_contactID
,
1566 'currency' => $this->getCurrency($submittedValues),
1567 'skipCleanMoney' => TRUE,
1571 //format soft-credit/pcp param first
1572 CRM_Contribute_BAO_ContributionSoft
::formatSoftCreditParams($submittedValues, $this);
1573 $params = array_merge($params, $submittedValues);
1576 'financial_type_id',
1577 'contribution_status_id',
1578 'payment_instrument_id',
1585 foreach ($fields as $f) {
1586 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1589 $params['revenue_recognition_date'] = NULL;
1590 if (!empty($formValues['revenue_recognition_date'])
1591 && count(array_filter($formValues['revenue_recognition_date'])) == 2
1593 $params['revenue_recognition_date'] = CRM_Utils_Date
::processDate(
1594 '01-' . implode('-', $formValues['revenue_recognition_date'])
1598 if (!empty($formValues['is_email_receipt'])) {
1599 $params['receipt_date'] = date("Y-m-d");
1602 if (CRM_Contribute_BAO_Contribution
::isContributionStatusNegative($params['contribution_status_id'])
1604 if (CRM_Utils_System
::isNull(CRM_Utils_Array
::value('cancel_date', $params))) {
1605 $params['cancel_date'] = date('YmdHis');
1609 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1612 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1613 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1614 if ($params['contribution_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending')) {
1615 $params['is_pay_later'] = 1;
1617 elseif ($params['contribution_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed')) {
1618 $params['is_pay_later'] = 0;
1621 // Add Additional common information to formatted params.
1622 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($formValues, $params, $this);
1624 $params['contribution_mode'] = 'participant';
1625 $params['participant_id'] = $pId;
1626 $params['skipLineItem'] = 1;
1628 elseif ($isRelatedId) {
1629 $params['contribution_mode'] = 'membership';
1631 $params['line_item'] = $lineItem;
1632 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array
::value('id', $this->_paymentProcessor
);
1633 $params['tax_amount'] = CRM_Utils_Array
::value('tax_amount', $submittedValues, CRM_Utils_Array
::value('tax_amount', $this->_values
));
1634 //create contribution.
1635 if ($isQuickConfig) {
1636 $params['is_quick_config'] = 1;
1638 $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
1640 // we are already handling note below, so to avoid duplicate notes against $contribution
1641 if (!empty($params['note']) && !empty($submittedValues['note'])) {
1642 unset($params['note']);
1644 $contribution = CRM_Contribute_BAO_Contribution
::create($params);
1646 // process associated membership / participant, CRM-4395
1647 if ($contribution->id
&& $action & CRM_Core_Action
::UPDATE
) {
1648 $this->statusMessage
[] = CRM_Contribute_BAO_Contribution
::transitionComponentWithReturnMessage($contribution->id
,
1649 $contribution->contribution_status_id
,
1650 CRM_Utils_Array
::value('contribution_status_id',
1653 $contribution->receive_date
1657 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1659 $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
1661 //send receipt mail.
1662 if ($contribution->id
&& !empty($formValues['is_email_receipt'])) {
1663 $formValues['contact_id'] = $this->_contactID
;
1664 $formValues['contribution_id'] = $contribution->id
;
1666 $formValues +
= CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
);
1668 // to get 'from email id' for send receipt
1669 $this->fromEmailId
= CRM_Utils_Array
::value('from_email_address', $formValues);
1670 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $formValues)) {
1671 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1675 $this->statusMessageTitle
= ts('Saved');
1679 if ($contribution->id
&& isset($formValues['product_name'][0])) {
1680 CRM_Contribute_Form_AdditionalInfo
::processPremium($submittedValues, $contribution->id
,
1681 $this->_premiumID
, $this->_options
1685 if ($contribution->id
&& array_key_exists('note', $submittedValues)) {
1686 CRM_Contribute_Form_AdditionalInfo
::processNote($submittedValues, $this->_contactID
, $contribution->id
, $this->_noteID
);
1689 CRM_Core_Session
::setStatus(implode(' ', $this->statusMessage
), $this->statusMessageTitle
, 'success');
1691 CRM_Contribute_BAO_Contribution
::updateRelatedPledge(
1695 (CRM_Utils_Array
::value('option_type', $formValues) == 2) ?
TRUE : FALSE,
1696 $formValues['total_amount'],
1697 CRM_Utils_Array
::value('total_amount', $this->_defaults
),
1698 $formValues['contribution_status_id'],
1699 CRM_Utils_Array
::value('contribution_status_id', $this->_defaults
)
1701 return $contribution;
1705 * Assign tax calculations to contribution receipts.
1707 * @param array $submittedValues
1708 * @param int $action
1709 * @param array $lineItem
1711 protected function invoicingPostProcessHook($submittedValues, $action, $lineItem) {
1713 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
1714 if (empty($invoiceSettings['invoicing'])) {
1718 $getTaxDetails = FALSE;
1720 foreach ($lineItem as $key => $value) {
1721 foreach ($value as $v) {
1722 if (isset($taxRate[(string) CRM_Utils_Array
::value('tax_rate', $v)])) {
1723 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $v);
1726 if (isset($v['tax_rate'])) {
1727 $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $v);
1728 $getTaxDetails = TRUE;
1734 if ($action & CRM_Core_Action
::UPDATE
) {
1735 if (isset($submittedValues['tax_amount'])) {
1736 $totalTaxAmount = $submittedValues['tax_amount'];
1739 $totalTaxAmount = $this->_values
['tax_amount'];
1741 $this->assign('totalTaxAmount', $totalTaxAmount);
1742 $this->assign('dataArray', $taxRate);
1745 if (!empty($submittedValues['price_set_id'])) {
1746 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1747 $this->assign('getTaxDetails', $getTaxDetails);
1748 $this->assign('dataArray', $taxRate);
1749 $this->assign('taxTerm', CRM_Utils_Array
::value('tax_term', $invoiceSettings));
1752 $this->assign('totalTaxAmount', CRM_Utils_Array
::value('tax_amount', $submittedValues));
1758 * Calculate non deductible amount.
1761 * if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1762 * if non_deductible_amount does NOT exist - then calculate it depending on:
1763 * $financialType->is_deductible and whether there is a product (premium).
1766 * @param $formValues
1770 protected function calculateNonDeductibleAmount($params, $formValues) {
1771 if (!empty($params['non_deductible_amount'])) {
1772 return $params['non_deductible_amount'];
1775 $priceSetId = CRM_Utils_Array
::value('price_set_id', $params);
1776 // return non-deductible amount if it is set at the price field option level
1777 if ($priceSetId && !empty($params['line_item'])) {
1778 $nonDeductibleAmount = CRM_Price_BAO_PriceSet
::getNonDeductibleAmountFromPriceSet($priceSetId, $params['line_item']);
1779 if (!empty($nonDeductibleAmount)) {
1780 return $nonDeductibleAmount;
1784 $financialType = new CRM_Financial_DAO_FinancialType();
1785 $financialType->id
= $params['financial_type_id'];
1786 $financialType->find(TRUE);
1788 if ($financialType->is_deductible
) {
1790 if (isset($formValues['product_name'][0])) {
1791 $selectProduct = $formValues['product_name'][0];
1793 // if there is a product - compare the value to the contribution amount
1794 if (isset($selectProduct)) {
1795 $productDAO = new CRM_Contribute_DAO_Product();
1796 $productDAO->id
= $selectProduct;
1797 $productDAO->find(TRUE);
1798 // product value exceeds contribution amount
1799 if ($params['total_amount'] < $productDAO->price
) {
1800 return $params['total_amount'];
1802 // product value does NOT exceed contribution amount
1804 return $productDAO->price
;
1807 // contribution is deductible - but there is no product
1812 // contribution is NOT deductible
1814 return $params['total_amount'];