3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
12 use Civi\Api4\Contribution
;
13 use Civi\Payment\Exception\PaymentProcessorException
;
16 * This class generates form components for processing a contribution.
18 class CRM_Contribute_Form_Contribution
extends CRM_Contribute_Form_AbstractEditPayment
{
20 * The id of the contribution that we are processing.
27 * The id of the premium that we are processing.
31 public $_premiumID = NULL;
34 * @var CRM_Contribute_DAO_ContributionProduct
36 public $_productDAO = NULL;
46 * The id of the contact associated with this contribution.
53 * The id of the pledge payment that we are processing.
60 * Is this contribution associated with an online.
61 * financial transaction
65 public $_online = FALSE;
68 * Stores all product options.
75 * Storage of parameters from form
82 * The contribution values if an existing contribution
88 * The pledge values if this contribution is associated with pledge
91 public $_pledgeValues;
93 public $_contributeMode = 'direct';
98 * Parameter with confusing name.
102 public $_compContext;
107 * Possible From email addresses
120 * Store the line items if price set used.
128 * @todo explain why we use lineItem & lineItems
137 public $_softCreditInfo;
139 protected $_formType;
142 * Array of the payment fields to be displayed in the payment fieldset (pane) in billingBlock.tpl
143 * this contains all the information to describe these fields from quickform. See CRM_Core_Form_Payment getPaymentFormFieldsMetadata
147 public $_paymentFields = [];
149 * Logged in user's email.
162 * Price set as an array
172 public $userDisplayName;
175 * Status message to be shown to the user.
179 protected $statusMessage = [];
182 * Status message title to be shown to the user.
184 * Generally the payment processor message title is 'Complete' and offline is 'Saved'
185 * although this might not be a good fit with the broad range of processors.
189 protected $statusMessageTitle;
194 * Max row count for soft credits. The value here is +1 the actual number of
197 public $_softCreditItemCount = 11;
202 public $submitOnce = TRUE;
205 * Status of contribution prior to edit.
209 protected $previousContributionStatus;
212 * Explicitly declare the form context.
214 public function getDefaultContext() {
219 * Set variables up before form is built.
221 * @throws \CRM_Core_Exception
222 * @throws \CiviCRM_API3_Exception
224 public function preProcess() {
225 // Check permission for action.
226 if (!CRM_Core_Permission
::checkActionPermission('CiviContribute', $this->_action
)) {
227 CRM_Core_Error
::statusBounce(ts('You do not have permission to access this page.'));
230 parent
::preProcess();
232 $this->_formType
= $_GET['formType'] ??
NULL;
235 $this->_priceSetId
= $_GET['priceSetId'] ??
NULL;
236 $this->set('priceSetId', $this->_priceSetId
);
237 $this->assign('priceSetId', $this->_priceSetId
);
239 // Get the pledge payment id
240 $this->_ppID
= CRM_Utils_Request
::retrieve('ppid', 'Positive', $this);
242 $this->assign('action', $this->_action
);
244 // Get the contribution id if update
245 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive');
246 $this->assign('isUsePaymentBlock', !empty($this->_id
));
247 if (!empty($this->_id
)) {
248 $this->assignPaymentInfoBlock();
249 $this->assign('contribID', $this->_id
);
252 $this->_context
= CRM_Utils_Request
::retrieve('context', 'Alphanumeric', $this);
253 $this->assign('context', $this->_context
);
255 $this->_compId
= CRM_Utils_Request
::retrieve('compId', 'Positive', $this);
257 $this->_compContext
= CRM_Utils_Request
::retrieve('compContext', 'String', $this);
259 //set the contribution mode.
260 $this->_mode
= CRM_Utils_Request
::retrieve('mode', 'Alphanumeric', $this);
262 $this->assign('contributionMode', $this->_mode
);
263 if ($this->_action
& CRM_Core_Action
::DELETE
) {
267 $this->_fromEmails
= CRM_Core_BAO_Email
::getFromEmail();
269 if (CRM_Core_Component
::isEnabled('CiviPledge') && !$this->_formType
) {
270 $this->preProcessPledge();
274 $this->showRecordLinkMesssage($this->_id
);
278 // Current contribution id.
280 $this->assignPremiumProduct($this->_id
);
281 $this->buildValuesAndAssignOnline_Note_Type($this->_id
, $this->_values
);
283 if (!isset($this->_values
['is_template'])) {
284 $this->_values
['is_template'] = FALSE;
286 $this->assign('is_template', $this->_values
['is_template']);
288 // when custom data is included in this page
289 if (!empty($_POST['hidden_custom'])) {
290 $this->applyCustomData('Contribution', $this->getFinancialTypeID(), $this->_id
);
293 $this->_lineItems
= [];
295 if (!empty($this->_compId
) && $this->_compContext
=== 'participant') {
296 $this->assign('compId', $this->_compId
);
297 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_compId
);
300 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution', 1, TRUE, TRUE);
303 empty($lineItem) ?
NULL : $this->_lineItems
[] = $lineItem;
306 $this->assign('lineItem', empty($lineItem) ?
FALSE : [$lineItem]);
309 if ($this->_mode
&& $this->_id
) {
310 $this->_payNow
= TRUE;
311 $this->assign('payNow', $this->_payNow
);
312 $this->setTitle(ts('Pay with Credit Card'));
314 elseif (!empty($this->_values
['is_template'])) {
315 $this->setPageTitle(ts('Template Contribution'));
317 elseif ($this->_mode
) {
318 $this->setPageTitle($this->_ppID ?
ts('Credit Card Pledge Payment') : ts('Credit Card Contribution'));
321 $this->setPageTitle($this->_ppID ?
ts('Pledge Payment') : ts('Contribution'));
326 * Set default values.
330 * @throws \CRM_Core_Exception
332 public function setDefaultValues() {
333 $defaults = $this->_values
;
335 // Set defaults for pledge payment.
337 $defaults['total_amount'] = $this->_pledgeValues
['pledgePayment']['scheduled_amount'] ??
NULL;
338 $defaults['financial_type_id'] = $this->_pledgeValues
['financial_type_id'] ??
NULL;
339 $defaults['currency'] = $this->_pledgeValues
['currency'] ??
NULL;
340 $defaults['option_type'] = 1;
343 if ($this->_action
& CRM_Core_Action
::DELETE
) {
347 $defaults['frequency_interval'] = 1;
348 $defaults['frequency_unit'] = 'month';
350 // Set soft credit defaults.
351 CRM_Contribute_Form_SoftCredit
::setDefaultValues($defaults, $this);
354 // @todo - remove this function as the parent does it too.
355 $config = CRM_Core_Config
::singleton();
356 // Set default country from config if no country set.
357 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
358 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry
;
361 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
362 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince
;
365 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID
);
366 $defaults = array_merge($defaults, $billingDefaults);
370 $this->_contactID
= $defaults['contact_id'];
372 elseif ($this->_contactID
) {
373 $defaults['contact_id'] = $this->_contactID
;
376 // Set $newCredit variable in template to control whether link to credit card mode is included.
377 $this->assign('newCredit', CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments());
379 // Fix the display of the monetary value, CRM-4038.
380 if (isset($defaults['total_amount'])) {
381 $total_value = $defaults['total_amount'];
382 $defaults['total_amount'] = CRM_Utils_Money
::formatLocaleNumericRoundedForDefaultCurrency($total_value);
383 if (!empty($defaults['tax_amount'])) {
384 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
385 if (empty($componentDetails['membership']) && empty($componentDetails['participant'])) {
386 $defaults['total_amount'] = CRM_Utils_Money
::formatLocaleNumericRoundedForDefaultCurrency($total_value - $defaults['tax_amount']);
391 $amountFields = ['non_deductible_amount', 'fee_amount'];
392 foreach ($amountFields as $amt) {
393 if (isset($defaults[$amt])) {
394 $defaults[$amt] = CRM_Utils_Money
::formatLocaleNumericRoundedForDefaultCurrency($defaults[$amt]);
398 if (empty($defaults['payment_instrument_id'])) {
399 $defaults['payment_instrument_id'] = $this->getDefaultPaymentInstrumentId();
402 if (!empty($defaults['is_test'])) {
403 $this->assign('is_test', TRUE);
406 $this->assign('showOption', TRUE);
407 // For Premium section.
408 if ($this->_premiumID
) {
409 $this->assign('showOption', FALSE);
410 $options = $this->_options
[$this->_productDAO
->product_id
] ??
"";
412 $this->assign('showOption', TRUE);
414 $options_key = CRM_Utils_Array
::key($this->_productDAO
->product_option
, $options);
416 $defaults['product_name'] = [$this->_productDAO
->product_id
, trim($options_key)];
419 $defaults['product_name'] = [$this->_productDAO
->product_id
];
421 if ($this->_productDAO
->fulfilled_date
) {
422 $defaults['fulfilled_date'] = $this->_productDAO
->fulfilled_date
;
426 if (isset($this->userEmail
)) {
427 $this->assign('email', $this->userEmail
);
430 if (!empty($defaults['is_pay_later'])) {
431 $this->assign('is_pay_later', TRUE);
433 $this->assign('contribution_status_id', CRM_Utils_Array
::value('contribution_status_id', $defaults));
434 if (!empty($defaults['contribution_status_id']) && in_array(
435 CRM_Contribute_PseudoConstant
::contributionStatus($defaults['contribution_status_id'], 'name'),
436 // Historically not 'Cancelled' hence not using CRM_Contribute_BAO_Contribution::isContributionStatusNegative.
437 ['Refunded', 'Chargeback']
439 $defaults['refund_trxn_id'] = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionTrxnID($this->_id
);
442 $defaults['refund_trxn_id'] = $defaults['trxn_id'] ??
NULL;
445 if (!$this->_id
&& empty($defaults['receive_date'])) {
446 $defaults['receive_date'] = date('Y-m-d H:i:s');
449 $currency = $defaults['currency'] ??
NULL;
450 $this->assign('currency', $currency);
451 // Hack to get currency info to the js layer. CRM-11440.
452 CRM_Utils_Money
::format(1);
453 $this->assign('currencySymbol', CRM_Utils_Array
::value($currency, CRM_Utils_Money
::$_currencySymbols));
454 $this->assign('totalAmount', CRM_Utils_Array
::value('total_amount', $defaults));
456 // Inherit campaign from pledge.
457 if ($this->_ppID
&& !empty($this->_pledgeValues
['campaign_id'])) {
458 $defaults['campaign_id'] = $this->_pledgeValues
['campaign_id'];
461 $this->_defaults
= $defaults;
466 * Build the form object.
468 * @throws \CiviCRM_API3_Exception
469 * @throws \CRM_Core_Exception
470 * @throws \API_Exception
472 public function buildQuickForm() {
474 $this->add('hidden', 'id', $this->_id
);
477 if ($this->_action
& CRM_Core_Action
::DELETE
) {
481 'name' => ts('Delete'),
482 'spacing' => ' ',
487 'name' => ts('Cancel'),
493 // FIXME: This probably needs to be done in preprocess
494 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()
495 && $this->_action
& CRM_Core_Action
::UPDATE
496 && !empty($this->_values
['financial_type_id'])
498 $financialTypeID = CRM_Contribute_PseudoConstant
::financialType($this->_values
['financial_type_id']);
499 CRM_Financial_BAO_FinancialType
::checkPermissionedLineItems($this->_id
, 'edit');
500 if (!CRM_Core_Permission
::check('edit contributions of type ' . $financialTypeID)) {
501 CRM_Core_Error
::statusBounce(ts('You do not have permission to access this page.'));
506 //tax rate from financialType
507 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant
::getTaxRates()));
508 $this->assign('currencies', json_encode(CRM_Core_OptionGroup
::values('currencies_enabled')));
510 // build price set form.
511 $buildPriceSet = FALSE;
512 $invoicing = CRM_Invoicing_Utils
::isInvoicingEnabled();
513 $this->assign('invoicing', CRM_Invoicing_Utils
::isInvoicingEnabled());
514 // This is a probably-deprecated approach to partial payments - assign here
515 // & if true it will be overwritten.
516 $this->assign('payNow', FALSE);
517 $buildRecurBlock = FALSE;
519 if (empty($this->_lineItems
) &&
520 ($this->_priceSetId ||
!empty($_POST['price_set_id']))
522 $buildPriceSet = TRUE;
523 $getOnlyPriceSetElements = TRUE;
524 if (!$this->_priceSetId
) {
525 $this->_priceSetId
= $_POST['price_set_id'];
526 $getOnlyPriceSetElements = FALSE;
529 $this->set('priceSetId', $this->_priceSetId
);
530 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
532 // get only price set form elements.
533 if ($getOnlyPriceSetElements) {
537 // use to build form during form rule.
538 $this->assign('buildPriceSet', $buildPriceSet);
540 $defaults = $this->_values
;
541 $additionalDetailFields = [
545 'non_deductible_amount',
548 foreach ($additionalDetailFields as $key) {
549 if (!empty($defaults[$key])) {
550 $defaults['hidden_AdditionalDetail'] = 1;
555 if ($this->_productDAO
) {
556 if ($this->_productDAO
->product_id
) {
557 $defaults['hidden_Premium'] = 1;
561 if ($this->_noteID
&&
562 !CRM_Utils_System
::isNull($this->_values
['note'])
564 $defaults['hidden_AdditionalDetail'] = 1;
568 if (empty($this->_payNow
)) {
569 $paneNames[ts('Additional Details')] = 'AdditionalDetail';
572 //Add Premium pane only if Premium is exists.
573 $dao = new CRM_Contribute_DAO_Product();
576 if ($dao->find(TRUE) && empty($this->_payNow
)) {
577 $paneNames[ts('Premium Information')] = 'Premium';
580 $this->payment_instrument_id
= CRM_Utils_Array
::value('payment_instrument_id', $defaults, $this->getDefaultPaymentInstrumentId());
581 CRM_Core_Payment_Form
::buildPaymentForm($this, $this->_paymentProcessor
, FALSE, TRUE, $this->payment_instrument_id
);
582 if (!empty($this->_recurPaymentProcessors
)) {
583 $buildRecurBlock = TRUE;
585 // ppID denotes a pledge payment.
586 foreach ($this->_paymentProcessors
as $processor) {
587 if (!empty($processor['is_recur']) && !empty($processor['object']) && $processor['object']->supports('recurContributionsForPledges')) {
588 $buildRecurBlock = TRUE;
591 $buildRecurBlock = FALSE;
594 if ($buildRecurBlock) {
595 CRM_Contribute_Form_Contribution_Main
::buildRecur($this);
596 $this->setDefaults(['is_recur' => 0]);
597 $this->assign('buildRecurBlock', TRUE);
600 $this->addPaymentProcessorSelect(FALSE, $buildRecurBlock);
602 foreach ($paneNames as $name => $type) {
603 $allPanes[$name] = $this->generatePane($type, $defaults);
606 $qfKey = $this->controller
->_key
;
607 $this->assign('qfKey', $qfKey);
608 $this->assign('allPanes', $allPanes);
610 $this->addFormRule(['CRM_Contribute_Form_Contribution', 'formRule'], $this);
611 $this->assign('formType', $this->_formType
);
613 if ($this->_formType
) {
617 $this->applyFilter('__ALL__', 'trim');
619 //need to assign custom data type and subtype to the template
620 $this->assign('customDataType', 'Contribution');
621 $this->assign('customDataSubType', $this->getFinancialTypeID());
622 $this->assign('entityID', $this->_id
);
624 $contactField = $this->addEntityRef('contact_id', ts('Contributor'), ['create' => TRUE, 'api' => ['extra' => ['email']]], TRUE);
625 if ($this->_context
!== 'standalone') {
626 $contactField->freeze();
629 $attributes = CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Contribution');
631 // Check permissions for financial type first
632 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes, $this->_action
);
633 if (empty($financialTypes)) {
634 CRM_Core_Error
::statusBounce(ts('You do not have all the permissions needed for this page.'));
636 $financialType = $this->add('select', 'financial_type_id',
637 ts('Financial Type'),
638 ['' => ts('- select -')] +
$financialTypes,
640 ['onChange' => "CRM.buildCustomData( 'Contribution', this.value );"]
643 $paymentInstrument = FALSE;
645 // payment_instrument isn't required in edit and will not be present when payment block is enabled.
646 $required = !$this->_id
;
647 $checkPaymentID = array_search('Check', CRM_Contribute_BAO_Contribution
::buildOptions('payment_instrument_id', 'validate'));
648 $paymentInstrument = $this->add('select', 'payment_instrument_id',
649 ts('Payment Method'),
650 ['' => ts('- select -')] + CRM_Contribute_BAO_Contribution
::buildOptions('payment_instrument_id', 'create'),
651 $required, ['onChange' => "return showHideByValue('payment_instrument_id','{$checkPaymentID}','checkNumber','table-row','select',false);"]
655 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), ['class' => 'twelve'] +
$attributes['trxn_id']);
657 //add receipt for offline contribution
658 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
660 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
662 $componentDetails = [];
664 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
666 $status = $this->getAvailableContributionStatuses();
668 // define the status IDs that show the cancellation info, see CRM-17589
669 $cancelInfo_show_ids = [];
670 foreach (array_keys($status) as $status_id) {
671 if (CRM_Contribute_BAO_Contribution
::isContributionStatusNegative($status_id)) {
672 $cancelInfo_show_ids[] = "'$status_id'";
675 $this->assign('cancelInfo_show_ids', implode(',', $cancelInfo_show_ids));
677 $statusElement = $this->add('select', 'contribution_status_id',
678 ts('Contribution Status'),
683 $currencyFreeze = FALSE;
684 if (!empty($this->_payNow
) && ($this->_action
& CRM_Core_Action
::UPDATE
)) {
685 $statusElement->freeze();
686 $currencyFreeze = TRUE;
687 $attributes['total_amount']['readonly'] = TRUE;
690 // CRM-16189, add Revenue Recognition Date
691 if (Civi
::settings()->get('deferred_revenue_enabled')) {
692 $revenueDate = $this->add('datepicker', 'revenue_recognition_date', ts('Revenue Recognition Date'), [], FALSE, ['time' => FALSE]);
693 if ($this->_id
&& !CRM_Contribute_BAO_Contribution
::allowUpdateRevenueRecognitionDate($this->_id
)) {
694 $revenueDate->freeze();
699 $this->addField('receive_date', ['entity' => 'contribution'], !$this->_mode
, FALSE);
700 $this->addField('receipt_date', ['entity' => 'contribution'], FALSE, FALSE);
701 $this->addField('cancel_date', ['entity' => 'contribution', 'label' => ts('Cancelled / Refunded Date')], FALSE, FALSE);
703 if ($this->_online
) {
704 $this->assign('hideCalender', TRUE);
707 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
710 if (empty($this->_lineItems
)) {
711 $buildPriceSet = FALSE;
712 $priceSets = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute');
713 if (!empty($priceSets) && !$this->_ppID
) {
714 $buildPriceSet = TRUE;
717 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
718 // and if we already have line items for that participant. CRM-5095
719 if ($buildPriceSet && $this->_id
) {
720 $pledgePaymentId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
725 if ($pledgePaymentId) {
726 $buildPriceSet = FALSE;
728 if ($participantID = CRM_Utils_Array
::value('participant', $componentDetails)) {
729 $participantLI = CRM_Price_BAO_LineItem
::getLineItems($participantID);
730 if (!CRM_Utils_System
::isNull($participantLI)) {
731 $buildPriceSet = FALSE;
736 $hasPriceSets = FALSE;
737 if ($buildPriceSet) {
738 $hasPriceSets = TRUE;
739 // CRM-16451: set financial type of 'Price Set' in back office contribution
740 // instead of selecting manually
741 $financialTypeIds = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute', 'financial_type_id');
742 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
744 '' => ts('Choose price set'),
746 NULL, ['onchange' => "buildAmount( this.value, " . json_encode($financialTypeIds) . ");"]
748 if ($this->_online
&& !($this->_action
& CRM_Core_Action
::UPDATE
)) {
752 $this->assign('hasPriceSets', $hasPriceSets);
753 if (!($this->_action
& CRM_Core_Action
::UPDATE
)) {
754 if ($this->_online ||
$this->_ppID
) {
755 $attributes['total_amount'] = array_merge($attributes['total_amount'], [
757 'style' => "background-color:#EBECE4",
760 '1' => ts('Adjust Pledge Payment Schedule?'),
761 '2' => ts('Adjust Total Pledge Amount?'),
763 $this->addRadio('option_type',
769 $currencyFreeze = TRUE;
773 $totalAmount = $this->addMoney('total_amount',
776 $attributes['total_amount'],
777 TRUE, 'currency', NULL, $currencyFreeze
781 $this->add('text', 'source', ts('Source'), CRM_Utils_Array
::value('source', $attributes));
783 // CRM-7362 --add campaigns.
784 CRM_Campaign_BAO_Campaign
::addCampaign($this, CRM_Utils_Array
::value('campaign_id', $this->_values
));
786 if (empty($this->_payNow
)) {
787 CRM_Contribute_Form_SoftCredit
::buildQuickForm($this);
792 $js = ['onclick' => "return verify( );"];
795 $mailingInfo = Civi
::settings()->get('mailing_backend');
796 $this->assign('outBound_option', $mailingInfo['outBound_option']);
801 'name' => ts('Save'),
807 'name' => ts('Save and New'),
813 'name' => ts('Cancel'),
817 // if contribution is related to membership or participant freeze Financial Type, Amount
819 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
820 $isCancelledStatus = ($this->_values
['contribution_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Cancelled'));
822 if (!empty($componentDetails['membership']) ||
823 !empty($componentDetails['participant']) ||
824 // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
825 // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
829 $totalAmount->freeze();
830 $this->getElement('currency')->freeze();
832 if ($isCancelledStatus) {
833 $paymentInstrument->freeze();
836 $financialType->freeze();
837 $this->assign('freezeFinancialType', TRUE);
841 if ($this->_action
& CRM_Core_Action
::VIEW
) {
849 * @param array $fields
850 * The input form values.
851 * @param array $files
852 * The uploaded files if any.
856 * true if no errors, else array of errors
858 public static function formRule($fields, $files, $self) {
860 // Check for Credit Card Contribution.
862 if (empty($fields['payment_processor_id'])) {
863 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
866 // validate payment instrument (e.g. credit card number)
867 CRM_Core_Payment_Form
::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, NULL);
871 // Do the amount validations.
872 if (empty($fields['total_amount']) && empty($self->_lineItems
)) {
873 if ($priceSetId = CRM_Utils_Array
::value('price_set_id', $fields)) {
874 CRM_Price_BAO_PriceField
::priceSetValidation($priceSetId, $fields, $errors);
878 $softErrors = CRM_Contribute_Form_SoftCredit
::formRule($fields, $errors, $self);
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 = [1 => [$fields['trxn_id'], 'String']];
905 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
907 $queryParams[2] = [(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.', [1 => $fields['trxn_id']]);
916 $order = new CRM_Financial_BAO_Order();
917 $order->setPriceSelectionFromUnfilteredInput($fields);
918 if (isset($fields['total_amount'])) {
919 $order->setOverrideTotalAmount((float) CRM_Utils_Rule
::cleanMoney($fields['total_amount']));
921 $lineItems = $order->getLineItems();
923 CRM_Financial_BAO_FinancialAccount
::checkFinancialTypeHasDeferred($fields, $self->_id
, $lineItems);
925 catch (CRM_Core_Exception
$e) {
926 $errors['financial_type_id'] = ' ';
927 $errors['_qf_default'] = $e->getMessage();
929 $errors = array_merge($errors, $softErrors);
934 * Process the form submission.
936 public function postProcess() {
937 if ($this->_action
& CRM_Core_Action
::DELETE
) {
938 CRM_Contribute_BAO_Contribution
::deleteContribution($this->_id
);
939 CRM_Core_Session
::singleton()->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
940 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
944 // Get the submitted form values.
945 $submittedValues = $this->controller
->exportValues($this->_name
);
948 $contribution = $this->submit($submittedValues, $this->_action
, $this->_ppID
);
950 catch (PaymentProcessorException
$e) {
951 // Set the contribution mode.
952 $urlParams = "action=add&cid={$this->_contactID}";
954 $urlParams .= "&mode={$this->_mode}";
956 if (!empty($this->_ppID
)) {
957 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
960 CRM_Core_Error
::statusBounce($e->getMessage(), $urlParams, ts('Payment Processor Error'));
962 $this->setUserContext();
964 //store contribution ID if not yet set (on create)
965 if (empty($this->_id
) && !empty($contribution->id
)) {
966 $this->_id
= $contribution->id
;
968 if (!empty($this->_id
) && CRM_Core_Permission
::access('CiviMember')) {
969 $membershipPaymentCount = civicrm_api3('MembershipPayment', 'getCount', ['contribution_id' => $this->_id
]);
970 if ($membershipPaymentCount) {
971 $this->ajaxResponse
['updateTabs']['#tab_member'] = CRM_Contact_BAO_Contact
::getCountComponent('membership', $this->_contactID
);
974 if (!empty($this->_id
) && CRM_Core_Permission
::access('CiviEvent')) {
975 $participantPaymentCount = civicrm_api3('ParticipantPayment', 'getCount', ['contribution_id' => $this->_id
]);
976 if ($participantPaymentCount) {
977 $this->ajaxResponse
['updateTabs']['#tab_participant'] = CRM_Contact_BAO_Contact
::getCountComponent('participant', $this->_contactID
);
983 * Process credit card payment.
985 * @param array $submittedValues
986 * @param array $lineItem
988 * @param int $contactID
991 * @return bool|\CRM_Contribute_DAO_Contribution
993 * @throws \CRM_Core_Exception
994 * @throws \Civi\Payment\Exception\PaymentProcessorException
995 * @throws \CiviCRM_API3_Exception
997 protected function processCreditCard($submittedValues, $lineItem, $contactID) {
998 $isTest = ($this->_mode
== 'test') ?
1 : 0;
999 // CRM-12680 set $_lineItem if its not set
1000 // @todo - I don't believe this would ever BE set. I can't find anywhere in the code.
1001 // It would be better to pass line item out to functions than $this->_lineItem as
1002 // we don't know what is being changed where.
1003 if (empty($this->_lineItem
) && !empty($lineItem)) {
1004 $this->_lineItem
= $lineItem;
1007 $this->_paymentObject
= Civi\Payment\System
::singleton()->getById($submittedValues['payment_processor_id']);
1008 $this->_paymentProcessor
= $this->_paymentObject
->getPaymentProcessor();
1010 // Set source if not set
1011 if (empty($submittedValues['source'])) {
1012 $userID = CRM_Core_Session
::singleton()->get('userID');
1013 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1016 $submittedValues['source'] = ts('Submit Credit Card Payment by: %1', [1 => $userSortName]);
1019 $params = $submittedValues;
1020 $this->_params
= array_merge($this->_params
, $submittedValues);
1022 // Mapping requiring documentation.
1023 $this->_params
['payment_processor'] = $submittedValues['payment_processor_id'];
1025 $now = date('YmdHis');
1027 $this->_contributorEmail
= $this->userEmail
;
1028 $this->_contributorContactID
= $contactID;
1029 $this->processBillingAddress();
1030 if (!empty($params['source'])) {
1031 unset($params['source']);
1034 $this->_params
['amount'] = $this->_params
['total_amount'];
1035 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
1036 // function to get correct amount level consistently. Remove setting of the amount level in
1037 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
1038 // to cover all variants.
1039 $this->_params
['amount_level'] = 0;
1040 $this->_params
['description'] = ts("Contribution submitted by a staff person using contributor's credit card");
1041 $this->_params
['currencyID'] = CRM_Utils_Array
::value('currency',
1043 CRM_Core_Config
::singleton()->defaultCurrency
1046 $this->_params
['pcp_display_in_roll'] = $params['pcp_display_in_roll'] ??
NULL;
1047 $this->_params
['pcp_roll_nickname'] = $params['pcp_roll_nickname'] ??
NULL;
1048 $this->_params
['pcp_personal_note'] = $params['pcp_personal_note'] ??
NULL;
1050 //Add common data to formatted params
1051 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
1053 if (empty($this->_params
['invoice_id'])) {
1054 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
1057 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
1060 // At this point we've created a contact and stored its address etc
1061 // all the payment processors expect the name and address to be in the
1062 // so we copy stuff over to first_name etc.
1063 $paymentParams = $this->_params
;
1064 $paymentParams['contactID'] = $contactID;
1065 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
1067 $financialType = new CRM_Financial_DAO_FinancialType();
1068 $financialType->id
= $params['financial_type_id'];
1069 $financialType->find(TRUE);
1071 // Add some financial type details to the params list
1072 // if folks need to use it.
1073 $paymentParams['contributionType_name'] = $this->_params
['contributionType_name'] = $financialType->name
;
1074 $paymentParams['contributionPageID'] = NULL;
1076 if (!empty($this->_params
['is_email_receipt'])) {
1077 $paymentParams['email'] = $this->userEmail
;
1078 $paymentParams['is_email_receipt'] = 1;
1081 $paymentParams['is_email_receipt'] = 0;
1082 $this->_params
['is_email_receipt'] = 0;
1084 if (!empty($this->_params
['receive_date'])) {
1085 $paymentParams['receive_date'] = $this->_params
['receive_date'];
1088 if (!empty($this->_params
['is_email_receipt'])) {
1089 $this->_params
['receipt_date'] = $now;
1092 $this->set('params', $this->_params
);
1093 // It actually makes no sense that we would set receive_date in params
1094 // for credit card payments....
1095 $this->assign('receive_date', $this->_params
['receive_date'] ??
date('Y-m-d H:i:s'));
1097 // Result has all the stuff we need
1098 // lets archive it to a financial transaction
1099 if ($financialType->is_deductible
) {
1100 $this->assign('is_deductible', TRUE);
1101 $this->set('is_deductible', TRUE);
1103 $contributionParams = [
1104 'id' => $this->_params
['contribution_id'] ??
NULL,
1105 'contact_id' => $contactID,
1106 'line_item' => $lineItem,
1107 'is_test' => $isTest,
1108 'campaign_id' => $this->_params
['campaign_id'] ??
NULL,
1109 'contribution_page_id' => $this->_params
['contribution_page_id'] ??
NULL,
1110 'source' => CRM_Utils_Array
::value('source', $paymentParams, CRM_Utils_Array
::value('description', $paymentParams)),
1111 'thankyou_date' => $this->_params
['thankyou_date'] ??
NULL,
1113 $contributionParams['payment_instrument_id'] = $this->_paymentProcessor
['payment_instrument_id'];
1115 $contribution = $this->processFormContribution(
1118 $contributionParams,
1122 CRM_Utils_Array
::value('is_recur', $this->_params
)
1125 $paymentParams['contributionID'] = $contribution->id
;
1126 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
1127 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1129 if ($paymentParams['amount'] > 0.0) {
1130 // force a re-get of the payment processor in case the form changed it, CRM-7179
1131 // NOTE - I expect this is obsolete.
1132 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
1134 $completeStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
1135 $result = $payment->doPayment($paymentParams, 'contribute');
1136 $this->assign('trxn_id', $result['trxn_id']);
1137 $contribution->trxn_id
= $result['trxn_id'];
1138 /* Our scenarios here are
1139 * 1) the payment failed & an Exception should have been thrown
1140 * 2) the payment succeeded but the payment is not immediate (for example a recurring payment
1141 * with a delayed start)
1142 * 3) the payment succeeded with an immediate payment.
1144 * The doPayment function ensures that payment_status_id is always set
1145 * as historically we have had to guess from the context - ie doDirectPayment
1146 * = error or success, unless it is a recurring contribution in which case it is pending.
1148 if ($result['payment_status_id'] == $completeStatusId) {
1150 civicrm_api3('contribution', 'completetransaction', [
1151 'id' => $contribution->id
,
1152 'trxn_id' => $result['trxn_id'],
1153 'payment_processor_id' => $this->_paymentProcessor
['id'],
1154 'is_transactional' => FALSE,
1155 'fee_amount' => $result['fee_amount'] ??
NULL,
1156 'card_type_id' => $paymentParams['card_type_id'] ??
NULL,
1157 'pan_truncation' => $paymentParams['pan_truncation'] ??
NULL,
1158 'is_email_receipt' => FALSE,
1160 // This has now been set to 1 in the DB - declare it here also
1161 $contribution->contribution_status_id
= 1;
1163 catch (CiviCRM_API3_Exception
$e) {
1164 if ($e->getErrorCode() != 'contribution_completed') {
1165 \Civi
::log()->error('CRM_Contribute_Form_Contribution::processCreditCard CiviCRM_API3_Exception: ' . $e->getMessage());
1166 throw new CRM_Core_Exception('Failed to update contribution in database');
1171 // Save the trxn_id.
1172 $contribution->save();
1175 catch (PaymentProcessorException
$e) {
1176 CRM_Contribute_BAO_Contribution
::failPayment($contribution->id
, $paymentParams['contactID'], $e->getMessage());
1177 throw new PaymentProcessorException($e->getMessage());
1180 // Send receipt mail.
1181 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1182 if ($contribution->id
&& !empty($this->_params
['is_email_receipt'])) {
1183 $this->_params
['trxn_id'] = $result['trxn_id'] ??
NULL;
1184 $this->_params
['contact_id'] = $contactID;
1185 $this->_params
['contribution_id'] = $contribution->id
;
1186 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $this->_params
, TRUE)) {
1187 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1191 return $contribution;
1195 * Process the contribution.
1197 * @todo - this form is a copy of the previously shared code on the front
1198 * end form - not all aspects of the code will be relevant to this form.
1200 * @param array $params
1201 * @param array $result
1202 * @param array $contributionParams
1203 * Parameters to be passed to contribution create action.
1204 * This differs from params in that we are currently adding params to it and 1) ensuring they are being
1205 * passed consistently & 2) documenting them here.
1210 * - contribution_page_id
1213 * - thankyou_date (not all forms will set this)
1215 * @param CRM_Financial_DAO_FinancialType $financialType
1216 * @param bool $online
1217 * Is the form a front end form? If so set a bunch of unpredictable things that should be passed in from the form.
1219 * @param int $billingLocationID
1220 * ID of billing location type.
1221 * @param bool $isRecur
1222 * Is this recurring?
1224 * @return \CRM_Contribute_DAO_Contribution
1226 * @throws \CRM_Core_Exception
1227 * @throws \CiviCRM_API3_Exception
1229 protected function processFormContribution(
1232 $contributionParams,
1239 $transaction = new CRM_Core_Transaction();
1240 $contactID = $contributionParams['contact_id'];
1242 $isEmailReceipt = !empty($form->_values
['is_email_receipt']);
1243 $isSeparateMembershipPayment = !empty($params['separate_membership_payment']);
1244 $pledgeID = !empty($params['pledge_id']) ?
$params['pledge_id'] : $form->_values
['pledge_id'] ??
NULL;
1245 if (!$isSeparateMembershipPayment && !empty($form->_values
['pledge_block_id']) &&
1246 (!empty($params['is_pledge']) ||
$pledgeID)) {
1253 // add these values for the recurringContrib function ,CRM-10188
1254 $params['financial_type_id'] = $financialType->id
;
1256 $contributionParams['address_id'] = CRM_Contribute_BAO_Contribution
::createAddress($params, $billingLocationID);
1258 //@todo - this is being set from the form to resolve CRM-10188 - an
1259 // eNotice caused by it not being set @ the front end
1260 // however, we then get it being over-written with null for backend contributions
1261 // a better fix would be to set the values in the respective forms rather than require
1262 // a function being shared by two forms to deal with their respective values
1263 // moving it to the BAO & not taking the $form as a param would make sense here.
1264 if (!isset($params['is_email_receipt']) && $isEmailReceipt) {
1265 $params['is_email_receipt'] = $isEmailReceipt;
1267 $params['is_recur'] = $isRecur;
1268 $params['payment_instrument_id'] = $contributionParams['payment_instrument_id'] ??
NULL;
1269 $recurringContributionID = CRM_Contribute_Form_Contribution_Confirm
::processRecurringContribution($form, $params, $contactID, $financialType);
1271 $now = date('YmdHis');
1272 $receiptDate = $params['receipt_date'] ??
NULL;
1273 if ($isEmailReceipt) {
1274 $receiptDate = $now;
1277 if (isset($params['amount'])) {
1278 $contributionParams = array_merge(CRM_Contribute_Form_Contribution_Confirm
::getContributionParams(
1279 $params, $financialType->id
,
1280 $result, $receiptDate,
1281 $recurringContributionID), $contributionParams
1283 $contributionParams['non_deductible_amount'] = CRM_Contribute_Form_Contribution_Confirm
::getNonDeductibleAmount($params, $financialType, FALSE, $form);
1284 $contributionParams['skipCleanMoney'] = TRUE;
1285 // @todo this is the wrong place for this - it should be done as close to form submission
1287 $contributionParams['total_amount'] = $params['amount'];
1289 $contribution = CRM_Contribute_BAO_Contribution
::add($contributionParams);
1291 if (Civi
::settings()->get('invoicing')) {
1293 // @todo - interrogate the line items passed in on the params array.
1294 // No reason to assume line items will be set on the form.
1295 foreach ($form->_lineItem
as $lineItemKey => $lineItemValue) {
1296 foreach ($lineItemValue as $key => $value) {
1297 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
1298 if (isset($dataArray[$value['tax_rate']])) {
1299 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] +
$value['tax_amount'];
1302 $dataArray[$value['tax_rate']] = $value['tax_amount'];
1307 $smarty = CRM_Core_Smarty
::singleton();
1308 $smarty->assign('dataArray', $dataArray);
1309 $smarty->assign('totalTaxAmount', $params['tax_amount'] ??
NULL);
1312 // lets store it in the form variable so postProcess hook can get to this and use it
1313 $form->_contributionID
= $contribution->id
;
1316 // process soft credit / pcp params first
1317 CRM_Contribute_BAO_ContributionSoft
::formatSoftCreditParams($params, $form);
1319 //CRM-13981, processing honor contact into soft-credit contribution
1320 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
1323 $form = CRM_Contribute_Form_Contribution_Confirm
::handlePledge($form, $params, $contributionParams, $pledgeID, $contribution, $isEmailReceipt);
1326 if ($online && $contribution) {
1327 CRM_Core_BAO_CustomValueTable
::postProcess($params,
1328 'civicrm_contribution',
1333 elseif ($contribution) {
1334 //handle custom data.
1335 $params['contribution_id'] = $contribution->id
;
1336 if (!empty($params['custom']) &&
1337 is_array($params['custom'])
1339 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
1343 if ($contribution && !empty($params['contribution_note'])) {
1345 'entity_table' => 'civicrm_contribution',
1346 'note' => $params['contribution_note'],
1347 'entity_id' => $contribution->id
,
1348 'contact_id' => $contribution->contact_id
,
1351 CRM_Core_BAO_Note
::add($noteParams, []);
1354 //create contribution activity w/ individual and target
1355 //activity w/ organisation contact id when onbelf, CRM-4027
1357 $targetContactID = NULL;
1358 if (!empty($params['onbehalf_contact_id'])) {
1360 'source_contact_id' => $params['onbehalf_contact_id'],
1361 'on_behalf' => TRUE,
1363 $targetContactID = $contribution->contact_id
;
1366 // create an activity record
1367 if ($contribution) {
1368 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Contribution', $targetContactID, $actParams);
1371 $transaction->commit();
1372 return $contribution;
1376 * Generate the data to construct a snippet based pane.
1378 * This form also assigns the showAdditionalInfo var based on historical code.
1379 * This appears to mean 'there is a pane to show'.
1381 * @param string $type
1382 * Type of Pane - this is generally used to determine the function name used to build it
1383 * - e.g CreditCard, AdditionalDetail
1384 * @param array $defaults
1387 * We aim to further refactor & simplify this but currently
1389 * - should additional info be shown?
1391 protected function generatePane($type, $defaults) {
1392 $urlParams = "snippet=4&formType={$type}";
1394 $urlParams .= "&mode={$this->_mode}";
1398 if ($type == 'CreditCard' ||
1399 $type == 'DirectDebit'
1405 'url' => CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams),
1410 // See if we need to include this paneName in the current form.
1411 if ($this->_formType
== $type ||
!empty($_POST["hidden_{$type}"]) ||
1412 !empty($defaults["hidden_{$type}"])
1414 $this->assign('showAdditionalInfo', TRUE);
1415 $pane['open'] = 'true';
1418 if ($type == 'CreditCard' ||
$type == 'DirectDebit') {
1419 // @todo would be good to align tpl name with form name...
1420 // @todo document why this hidden variable is required.
1421 $this->add('hidden', 'hidden_' . $type, 1);
1425 $additionalInfoFormFunction = 'build' . $type;
1426 CRM_Contribute_Form_AdditionalInfo
::$additionalInfoFormFunction($this);
1432 * Wrapper for unit testing the post process submit function.
1434 * (If we expose through api we can get default additions 'for free').
1436 * @param array $params
1437 * @param int $action
1438 * @param string|null $creditCardMode
1440 * @return CRM_Contribute_BAO_Contribution
1442 * @throws \CRM_Core_Exception
1443 * @throws \CiviCRM_API3_Exception
1444 * @throws \Civi\Payment\Exception\PaymentProcessorException
1446 public function testSubmit($params, $action, $creditCardMode = NULL) {
1448 'soft_credit_contact_id' => [],
1449 'receive_date' => date('Y-m-d H:i:s'),
1450 'receipt_date' => '',
1451 'cancel_date' => '',
1452 'hidden_Premium' => 1,
1455 if (!empty($params['id'])) {
1456 $existingContribution = civicrm_api3('contribution', 'getsingle', [
1457 'id' => $params['id'],
1459 $this->_id
= $params['id'];
1460 $this->_values
= $existingContribution;
1461 if (CRM_Invoicing_Utils
::isInvoicingEnabled()) {
1462 $this->_values
['tax_amount'] = civicrm_api3('contribution', 'getvalue', [
1463 'id' => $params['id'],
1464 'return' => 'tax_amount',
1469 $existingContribution = [];
1472 $this->_defaults
['contribution_status_id'] = CRM_Utils_Array
::value('contribution_status_id',
1473 $existingContribution
1476 $this->_defaults
['total_amount'] = CRM_Utils_Array
::value('total_amount',
1477 $existingContribution
1480 if ($creditCardMode) {
1481 $this->_mode
= $creditCardMode;
1484 // Required because processCreditCard calls set method on this.
1485 $_SERVER['REQUEST_METHOD'] = 'GET';
1486 $this->controller
= new CRM_Core_Controller();
1488 CRM_Contribute_Form_AdditionalInfo
::buildPremium($this);
1490 $this->_fields
= [];
1491 return $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array
::value('pledge_payment_id', $params));
1496 * @param array $submittedValues
1498 * @param int $action
1500 * - CRM_Core_Action::UPDATE
1502 * @param $pledgePaymentID
1504 * @return \CRM_Contribute_BAO_Contribution
1506 * @throws \CRM_Core_Exception
1507 * @throws \CiviCRM_API3_Exception
1508 * @throws \Civi\Payment\Exception\PaymentProcessorException
1510 protected function submit($submittedValues, $action, $pledgePaymentID) {
1511 $pId = $contribution = $isRelatedId = FALSE;
1512 $this->_params
= $submittedValues;
1513 $this->beginPostProcess();
1514 // reassign submitted form values if the any information is formatted via beginPostProcess
1515 $submittedValues = $this->_params
;
1517 if ($this->getPriceSetID() && $action & CRM_Core_Action
::UPDATE
) {
1518 $line = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution');
1519 $lineID = key($line);
1520 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array
::value('price_field_id', $line[$lineID]), 'price_set_id');
1521 $quickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1522 // Why do we do this? Seems like a like a wrapper for old functionality - but single line price sets & quick
1523 // config should be treated the same.
1525 CRM_Price_BAO_LineItem
::deleteLineItems($this->_id
, 'civicrm_contribution');
1529 // Process price set and get total amount and line items.
1531 $priceSetId = $submittedValues['price_set_id'] ??
NULL;
1532 if (!$this->getPriceSetID() && !$this->_id
) {
1533 $this->_priceSetId
= $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1534 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
1535 $fieldID = key($this->_priceSet
['fields']);
1536 $fieldValueId = key($this->_priceSet
['fields'][$fieldID]['options']);
1537 $this->_priceSet
['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1538 $submittedValues['price_' . $fieldID] = 1;
1541 // Every contribution has a price-set - the only reason it shouldn't be set is if we are dealing with
1542 // quick config (very very arguably) & yet we see that this could still be quick config so this should be understood
1543 // as a point of fragility rather than a logical 'if' clause.
1545 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
1546 $submittedValues, $lineItem[$priceSetId], $priceSetId);
1547 // Unset tax amount for offline 'is_quick_config' contribution.
1548 // @todo WHY - quick config was conceived as a quick way to configure contribution forms.
1549 // this is an example of 'other' functionality being hung off it.
1550 if ($this->_priceSet
['is_quick_config'] &&
1551 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant
::getTaxRates())
1553 unset($submittedValues['tax_amount']);
1555 $submittedValues['total_amount'] = $submittedValues['amount'] ??
NULL;
1559 if ($this->_compId
) {
1560 if ($this->_context
== 'participant') {
1561 $pId = $this->_compId
;
1563 elseif ($this->_context
== 'membership') {
1564 $isRelatedId = TRUE;
1567 $pId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id
, 'participant_id', 'contribution_id');
1571 $contributionDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1572 if (array_key_exists('membership', $contributionDetails)) {
1573 $isRelatedId = TRUE;
1575 elseif (array_key_exists('participant', $contributionDetails)) {
1576 $pId = $contributionDetails['participant'];
1579 if (!empty($this->_payNow
)) {
1580 $this->_params
['contribution_id'] = $this->_id
;
1584 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id
) {
1585 // CRM-10117 update the line items for participants.
1586 // @todo - if we are completing a contribution then the api call
1587 // civicrm_api3('Contribution', 'completetransaction') should take care of
1588 // all associated updates rather than replicating them on the form layer.
1590 $entityTable = 'participant';
1592 $isRelatedId = FALSE;
1593 $participantParams = [
1594 'fee_amount' => $submittedValues['total_amount'],
1597 CRM_Event_BAO_Participant
::add($participantParams);
1598 if (empty($this->_lineItems
)) {
1599 $this->_lineItems
[] = CRM_Price_BAO_LineItem
::getLineItems($entityID, 'participant', TRUE);
1603 $entityTable = 'contribution';
1604 $entityID = $this->_id
;
1607 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, $entityTable, FALSE, TRUE, $isRelatedId);
1608 foreach (array_keys($lineItems) as $id) {
1609 $lineItems[$id]['id'] = $id;
1611 $itemId = key($lineItems);
1612 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1613 $this->_priceSetId
= CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1616 // @todo see above - new functionality has been inappropriately added to the quick config concept
1617 // and new functionality has been added onto the form layer rather than the BAO :-(
1618 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1619 //CRM-16833: Ensure tax is applied only once for membership conribution, when status changed.(e.g Pending to Completed).
1620 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1621 if (empty($componentDetails['membership']) && empty($componentDetails['participant'])) {
1622 if (!($this->_action
& CRM_Core_Action
::UPDATE
&& (($this->_defaults
['contribution_status_id'] != $submittedValues['contribution_status_id'])))) {
1623 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule
::cleanMoney(CRM_Utils_Array
::value('total_amount', $submittedValues));
1627 // Update line total and total amount with tax on edit.
1628 $financialItemsId = CRM_Core_PseudoConstant
::getTaxRates();
1629 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1630 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1633 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1634 $submittedValues['tax_amount'] = 0;
1636 if ($lineItems[$itemId]['tax_rate']) {
1637 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total'];
1638 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] +
$lineItems[$itemId]['tax_amount'];
1639 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1642 // CRM-10117 update the line items for participants.
1643 if (!empty($lineItems[$itemId]['price_field_id'])) {
1644 $lineItem[$this->_priceSetId
] = $lineItems;
1649 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1652 //CRM-11529 for quick config back office transactions
1653 //when financial_type_id is passed in form, update the
1654 //line items with the financial type selected in form
1655 // NOTE that this IS still a legitimate use of 'quick-config' for contributions under the current DB but
1656 // we should look at having a price field per contribution type & then there would be little reason
1657 // for the back-office contribution form postProcess to know if it is a quick-config form.
1658 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && !empty($lineItem[$this->_priceSetId
])
1660 foreach ($lineItem[$this->_priceSetId
] as &$values) {
1661 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1665 if (!isset($submittedValues['total_amount'])) {
1666 $submittedValues['total_amount'] = $this->_values
['total_amount'] ??
NULL;
1667 // Avoid tax amount deduction on edit form and keep it original, because this will lead to error described in CRM-20676
1669 $submittedValues['total_amount'] -= CRM_Utils_Array
::value('tax_amount', $this->_values
, 0);
1672 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
1674 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id'] ??
[]));
1675 if ($this->_id
&& count($isEmpty) == 1 && key($isEmpty) == NULL) {
1676 civicrm_api3('ContributionSoft', 'get', ['contribution_id' => $this->_id
, 'pcp_id' => ['IS NULL' => 1], 'api.ContributionSoft.delete' => 1]);
1679 // set the contact, when contact is selected
1680 if (!empty($submittedValues['contact_id'])) {
1681 $this->_contactID
= $submittedValues['contact_id'];
1684 $formValues = $submittedValues;
1686 // Credit Card Contribution.
1688 $paramsSetByPaymentProcessingSubsystem = [
1690 'payment_instrument_id',
1691 'contribution_status_id',
1695 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1696 if (isset($formValues[$key])) {
1697 unset($formValues[$key]);
1700 $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID
);
1701 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1702 $formValues[$key] = $contribution->$key;
1706 // Offline Contribution.
1707 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1709 // get the required field value only.
1712 'contact_id' => $this->_contactID
,
1713 'currency' => $this->getCurrency($submittedValues),
1714 'skipCleanMoney' => TRUE,
1718 //format soft-credit/pcp param first
1719 CRM_Contribute_BAO_ContributionSoft
::formatSoftCreditParams($submittedValues, $this);
1720 $params = array_merge($params, $submittedValues);
1723 'financial_type_id',
1724 'contribution_status_id',
1725 'payment_instrument_id',
1732 foreach ($fields as $f) {
1733 $params[$f] = $formValues[$f] ??
NULL;
1736 $params['revenue_recognition_date'] = NULL;
1737 if (!empty($formValues['revenue_recognition_date'])) {
1738 $params['revenue_recognition_date'] = $formValues['revenue_recognition_date'];
1741 if (!empty($formValues['is_email_receipt'])) {
1742 $params['receipt_date'] = date("Y-m-d");
1745 if (CRM_Contribute_BAO_Contribution
::isContributionStatusNegative($params['contribution_status_id'])
1747 if (CRM_Utils_System
::isNull(CRM_Utils_Array
::value('cancel_date', $params))) {
1748 $params['cancel_date'] = date('YmdHis');
1752 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1755 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1756 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1757 if ($params['contribution_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending')) {
1758 $params['is_pay_later'] = 1;
1760 elseif ($params['contribution_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed')) {
1761 // @todo - if the contribution is new then it should be Pending status & then we use
1762 // Payment.create to update to Completed.
1763 $params['is_pay_later'] = 0;
1766 // Add Additional common information to formatted params.
1767 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($formValues, $params, $this);
1769 $params['contribution_mode'] = 'participant';
1770 $params['participant_id'] = $pId;
1771 $params['skipLineItem'] = 1;
1773 $params['line_item'] = $lineItem;
1774 $params['payment_processor_id'] = $params['payment_processor'] = $this->_paymentProcessor
['id'] ??
NULL;
1775 $params['tax_amount'] = CRM_Utils_Array
::value('tax_amount', $submittedValues, CRM_Utils_Array
::value('tax_amount', $this->_values
));
1776 //create contribution.
1777 if ($isQuickConfig) {
1778 $params['is_quick_config'] = 1;
1780 $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
1782 // we are already handling note below, so to avoid duplicate notes against $contribution
1783 if (!empty($params['note']) && !empty($submittedValues['note'])) {
1784 unset($params['note']);
1786 $contribution = CRM_Contribute_BAO_Contribution
::create($params);
1788 // process associated membership / participant, CRM-4395
1789 if ($contribution->id
&& $action & CRM_Core_Action
::UPDATE
) {
1790 // @todo use Payment.create to do this, remove transitioncomponents function
1791 // if contribution is being created with a completed status it should be
1792 // created pending & then Payment.create adds the payment
1793 CRM_Contribute_BAO_Contribution
::transitionComponents([
1794 'contribution_id' => $contribution->id
,
1795 'contribution_status_id' => $contribution->contribution_status_id
,
1796 'previous_contribution_status_id' => $this->_values
['contribution_status_id'] ??
NULL,
1797 'receive_date' => $contribution->receive_date
,
1801 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1803 $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
1805 //send receipt mail.
1806 if ($contribution->id
&& !empty($formValues['is_email_receipt'])) {
1807 $formValues['contact_id'] = $this->_contactID
;
1808 $formValues['contribution_id'] = $contribution->id
;
1810 $formValues +
= CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
);
1812 // to get 'from email id' for send receipt
1813 $this->fromEmailId
= $formValues['from_email_address'] ??
NULL;
1814 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $formValues)) {
1815 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1819 $this->statusMessageTitle
= ts('Saved');
1823 if ($contribution->id
&& isset($formValues['product_name'][0])) {
1824 CRM_Contribute_Form_AdditionalInfo
::processPremium($submittedValues, $contribution->id
,
1825 $this->_premiumID
, $this->_options
1829 if ($contribution->id
&& array_key_exists('note', $submittedValues)) {
1830 CRM_Contribute_Form_AdditionalInfo
::processNote($submittedValues, $this->_contactID
, $contribution->id
, $this->_noteID
);
1833 CRM_Core_Session
::setStatus(implode(' ', $this->statusMessage
), $this->statusMessageTitle
, 'success');
1835 CRM_Contribute_BAO_Contribution
::updateRelatedPledge(
1839 ($formValues['option_type'] ??
0) == 2,
1840 $formValues['total_amount'],
1841 CRM_Utils_Array
::value('total_amount', $this->_defaults
),
1842 $formValues['contribution_status_id'],
1843 CRM_Utils_Array
::value('contribution_status_id', $this->_defaults
)
1845 return $contribution;
1849 * Assign tax calculations to contribution receipts.
1851 * @param array $submittedValues
1852 * @param int $action
1853 * @param array $lineItem
1855 protected function invoicingPostProcessHook($submittedValues, $action, $lineItem) {
1856 if (!Civi
::settings()->get('invoicing')) {
1860 $getTaxDetails = FALSE;
1862 foreach ($lineItem as $key => $value) {
1863 foreach ($value as $v) {
1864 if (isset($taxRate[(string) CRM_Utils_Array
::value('tax_rate', $v)])) {
1865 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $v);
1868 if (isset($v['tax_rate'])) {
1869 $taxRate[(string) $v['tax_rate']] = $v['tax_amount'] ??
NULL;
1870 $getTaxDetails = TRUE;
1876 if ($action & CRM_Core_Action
::UPDATE
) {
1877 if (isset($submittedValues['tax_amount'])) {
1878 $totalTaxAmount = $submittedValues['tax_amount'];
1881 $totalTaxAmount = $this->_values
['tax_amount'];
1883 $this->assign('totalTaxAmount', $totalTaxAmount);
1884 $this->assign('dataArray', $taxRate);
1887 if (!empty($submittedValues['price_set_id'])) {
1888 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1889 $this->assign('getTaxDetails', $getTaxDetails);
1890 $this->assign('dataArray', $taxRate);
1891 $this->assign('taxTerm', Civi
::settings()->get('tax_term'));
1894 $this->assign('totalTaxAmount', CRM_Utils_Array
::value('tax_amount', $submittedValues));
1900 * Calculate non deductible amount.
1902 * @see https://issues.civicrm.org/jira/browse/CRM-11956
1903 * if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1904 * if non_deductible_amount does NOT exist - then calculate it depending on:
1905 * $financialType->is_deductible and whether there is a product (premium).
1908 * @param $formValues
1912 protected function calculateNonDeductibleAmount($params, $formValues) {
1913 if (!empty($params['non_deductible_amount'])) {
1914 return $params['non_deductible_amount'];
1917 $priceSetId = $params['price_set_id'] ??
NULL;
1918 // return non-deductible amount if it is set at the price field option level
1919 if ($priceSetId && !empty($params['line_item'])) {
1920 $nonDeductibleAmount = CRM_Price_BAO_PriceSet
::getNonDeductibleAmountFromPriceSet($priceSetId, $params['line_item']);
1921 if (!empty($nonDeductibleAmount)) {
1922 return $nonDeductibleAmount;
1926 $financialType = new CRM_Financial_DAO_FinancialType();
1927 $financialType->id
= $params['financial_type_id'];
1928 $financialType->find(TRUE);
1930 if ($financialType->is_deductible
) {
1932 if (isset($formValues['product_name'][0])) {
1933 $selectProduct = $formValues['product_name'][0];
1935 // if there is a product - compare the value to the contribution amount
1936 if (isset($selectProduct)) {
1937 $productDAO = new CRM_Contribute_DAO_Product();
1938 $productDAO->id
= $selectProduct;
1939 $productDAO->find(TRUE);
1940 // product value exceeds contribution amount
1941 if ($params['total_amount'] < $productDAO->price
) {
1942 return $params['total_amount'];
1944 // product value does NOT exceed contribution amount
1946 return $productDAO->price
;
1949 // contribution is deductible - but there is no product
1954 // contribution is NOT deductible
1956 return $params['total_amount'];
1963 * Get the financial Type ID for the contribution either from the submitted values or from the contribution values if possible.
1965 * This is important for dev/core#1728 - ie ensure that if we are returned to the form for a form
1966 * error that any custom fields based on the selected financial type are loaded.
1970 protected function getFinancialTypeID() {
1971 if (!empty($this->_submitValues
['financial_type_id'])) {
1972 return $this->_submitValues
['financial_type_id'];
1974 if (!empty($this->_values
['financial_type_id'])) {
1975 return $this->_values
['financial_type_id'];
1980 * Set context in session
1982 public function setUserContext(): void
{
1983 $session = CRM_Core_Session
::singleton();
1984 $buttonName = $this->controller
->getButtonName();
1985 if ($this->_context
== 'standalone') {
1986 if ($buttonName == $this->getButtonName('upload', 'new')) {
1987 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contribute/add',
1988 'reset=1&action=add&context=standalone'
1992 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
1993 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1997 elseif ($this->_context
== 'contribution' && $this->_mode
&& $buttonName == $this->getButtonName('upload', 'new')) {
1998 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
1999 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
2002 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
2003 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
2004 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
2010 * Get the contribution ID.
2014 protected function getContributionID(): ?
int {
2019 * Get the selected contribution status.
2021 * @return string|null
2023 * @throws \API_Exception
2025 protected function getPreviousContributionStatus(): ?
string {
2026 if (!$this->getContributionID()) {
2029 if (!$this->previousContributionStatus
) {
2030 $this->previousContributionStatus
= Contribution
::get(FALSE)
2031 ->addWhere('id', '=', $this->getContributionID())
2032 ->addSelect('contribution_status_id:name')
2034 ->first()['contribution_status_id:name'];
2036 return $this->previousContributionStatus
;
2040 * Get the contribution statuses available on the form.
2042 * @todo - this needs work - some returned options are invalid or do
2043 * not create good financial entities. Probably the only reason we don't just
2044 * return CRM_Contribute_BAO_Contribution_Utils::getPendingCompleteFailedAndCancelledStatuses();
2045 * is that it might exclude the current status of the contribution.
2048 * @throws \API_Exception
2050 protected function getAvailableContributionStatuses(): array {
2051 if (!$this->getPreviousContributionStatus()) {
2052 return CRM_Contribute_BAO_Contribution_Utils
::getPendingCompleteFailedAndCancelledStatuses();
2054 $statusNames = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id', 'validate');
2055 $statusNamesToUnset = array_diff([
2056 // For records which represent a data template for a recurring
2057 // contribution that may not yet have a payment. This status should not
2058 // be available from forms. 'Template' contributions should only be created
2059 // in conjunction with a ContributionRecur record, and should have their
2060 // is_template field set to 1. This status excludes them from reports
2061 // that are still ignorant of the is_template field.
2065 ], [$this->getPreviousContributionStatus()]);
2066 switch ($this->getPreviousContributionStatus()) {
2068 // [CRM-17498] Removing unsupported status change options.
2069 $statusNamesToUnset = array_merge($statusNamesToUnset, [
2078 $statusNamesToUnset = array_merge($statusNamesToUnset, [
2086 $statusNamesToUnset = array_merge($statusNamesToUnset, [
2093 $statusNamesToUnset = array_merge($statusNamesToUnset, [
2104 foreach ($statusNamesToUnset as $name) {
2105 unset($statusNames[CRM_Utils_Array
::key($name, $statusNames)]);
2108 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id');
2110 foreach ($statuses as $statusID => $label) {
2111 if (!array_key_exists($statusID, $statusNames)) {
2112 unset($statuses[$statusID]);
2120 * Get the price set ID.
2122 * Note that the function currently returns NULL if not submitted
2123 * but will over time be fixed to always return an ID.
2127 protected function getPriceSetID() {
2128 return $this->getSubmittedValue('price_set_id');