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 ($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 (!empty($defaults['contribution_status_id'])
446 && ('Template' === CRM_Contribute_PseudoConstant
::contributionStatus($defaults['contribution_status_id'], 'name'))
448 $this->getElement('contribution_status_id')->freeze();
451 if (!$this->_id
&& empty($defaults['receive_date'])) {
452 $defaults['receive_date'] = date('Y-m-d H:i:s');
455 $currency = $defaults['currency'] ??
NULL;
456 $this->assign('currency', $currency);
457 // Hack to get currency info to the js layer. CRM-11440.
458 CRM_Utils_Money
::format(1);
459 $this->assign('currencySymbol', CRM_Utils_Array
::value($currency, CRM_Utils_Money
::$_currencySymbols));
460 $this->assign('totalAmount', CRM_Utils_Array
::value('total_amount', $defaults));
462 // Inherit campaign from pledge.
463 if ($this->_ppID
&& !empty($this->_pledgeValues
['campaign_id'])) {
464 $defaults['campaign_id'] = $this->_pledgeValues
['campaign_id'];
467 $this->_defaults
= $defaults;
472 * Build the form object.
474 * @throws \CiviCRM_API3_Exception
475 * @throws \CRM_Core_Exception
476 * @throws \API_Exception
478 public function buildQuickForm() {
480 $this->add('hidden', 'id', $this->_id
);
483 if ($this->_action
& CRM_Core_Action
::DELETE
) {
487 'name' => ts('Delete'),
488 'spacing' => ' ',
493 'name' => ts('Cancel'),
499 // FIXME: This probably needs to be done in preprocess
500 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()
501 && $this->_action
& CRM_Core_Action
::UPDATE
502 && !empty($this->_values
['financial_type_id'])
504 $financialTypeID = CRM_Contribute_PseudoConstant
::financialType($this->_values
['financial_type_id']);
505 CRM_Financial_BAO_FinancialType
::checkPermissionedLineItems($this->_id
, 'edit');
506 if (!CRM_Core_Permission
::check('edit contributions of type ' . $financialTypeID)) {
507 CRM_Core_Error
::statusBounce(ts('You do not have permission to access this page.'));
512 //tax rate from financialType
513 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant
::getTaxRates()));
514 $this->assign('currencies', json_encode(CRM_Core_OptionGroup
::values('currencies_enabled')));
516 // build price set form.
517 $buildPriceSet = FALSE;
518 $invoicing = CRM_Invoicing_Utils
::isInvoicingEnabled();
519 $this->assign('invoicing', CRM_Invoicing_Utils
::isInvoicingEnabled());
520 // This is a probably-deprecated approach to partial payments - assign here
521 // & if true it will be overwritten.
522 $this->assign('payNow', FALSE);
523 $buildRecurBlock = FALSE;
525 if (empty($this->_lineItems
) &&
526 ($this->_priceSetId ||
!empty($_POST['price_set_id']))
528 $buildPriceSet = TRUE;
529 $getOnlyPriceSetElements = TRUE;
530 if (!$this->_priceSetId
) {
531 $this->_priceSetId
= $_POST['price_set_id'];
532 $getOnlyPriceSetElements = FALSE;
535 $this->set('priceSetId', $this->_priceSetId
);
536 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
538 // get only price set form elements.
539 if ($getOnlyPriceSetElements) {
543 // use to build form during form rule.
544 $this->assign('buildPriceSet', $buildPriceSet);
546 $defaults = $this->_values
;
547 $additionalDetailFields = [
551 'non_deductible_amount',
554 foreach ($additionalDetailFields as $key) {
555 if (!empty($defaults[$key])) {
556 $defaults['hidden_AdditionalDetail'] = 1;
561 if ($this->_productDAO
) {
562 if ($this->_productDAO
->product_id
) {
563 $defaults['hidden_Premium'] = 1;
567 if ($this->_noteID
&&
568 !CRM_Utils_System
::isNull($this->_values
['note'])
570 $defaults['hidden_AdditionalDetail'] = 1;
574 if (empty($this->_payNow
)) {
575 $paneNames[ts('Additional Details')] = 'AdditionalDetail';
578 //Add Premium pane only if Premium is exists.
579 $dao = new CRM_Contribute_DAO_Product();
582 if ($dao->find(TRUE) && empty($this->_payNow
)) {
583 $paneNames[ts('Premium Information')] = 'Premium';
586 $this->payment_instrument_id
= CRM_Utils_Array
::value('payment_instrument_id', $defaults, $this->getDefaultPaymentInstrumentId());
587 CRM_Core_Payment_Form
::buildPaymentForm($this, $this->_paymentProcessor
, FALSE, TRUE, $this->payment_instrument_id
);
588 if (!empty($this->_recurPaymentProcessors
)) {
589 $buildRecurBlock = TRUE;
591 // ppID denotes a pledge payment.
592 foreach ($this->_paymentProcessors
as $processor) {
593 if (!empty($processor['is_recur']) && !empty($processor['object']) && $processor['object']->supports('recurContributionsForPledges')) {
594 $buildRecurBlock = TRUE;
597 $buildRecurBlock = FALSE;
600 if ($buildRecurBlock) {
601 CRM_Contribute_Form_Contribution_Main
::buildRecur($this);
602 $this->setDefaults(['is_recur' => 0]);
603 $this->assign('buildRecurBlock', TRUE);
606 $this->addPaymentProcessorSelect(FALSE, $buildRecurBlock);
608 foreach ($paneNames as $name => $type) {
609 $allPanes[$name] = $this->generatePane($type, $defaults);
612 $qfKey = $this->controller
->_key
;
613 $this->assign('qfKey', $qfKey);
614 $this->assign('allPanes', $allPanes);
616 $this->addFormRule(['CRM_Contribute_Form_Contribution', 'formRule'], $this);
617 $this->assign('formType', $this->_formType
);
619 if ($this->_formType
) {
623 $this->applyFilter('__ALL__', 'trim');
625 //need to assign custom data type and subtype to the template
626 $this->assign('customDataType', 'Contribution');
627 $this->assign('customDataSubType', $this->getFinancialTypeID());
628 $this->assign('entityID', $this->_id
);
630 $contactField = $this->addEntityRef('contact_id', ts('Contributor'), ['create' => TRUE, 'api' => ['extra' => ['email']]], TRUE);
631 if ($this->_context
!== 'standalone') {
632 $contactField->freeze();
635 $attributes = CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Contribution');
637 // Check permissions for financial type first
638 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes, $this->_action
);
639 if (empty($financialTypes)) {
640 CRM_Core_Error
::statusBounce(ts('You do not have all the permissions needed for this page.'));
642 $financialType = $this->add('select', 'financial_type_id',
643 ts('Financial Type'),
644 ['' => ts('- select -')] +
$financialTypes,
646 ['onChange' => "CRM.buildCustomData( 'Contribution', this.value );"]
649 $paymentInstrument = FALSE;
651 // payment_instrument isn't required in edit and will not be present when payment block is enabled.
652 $required = !$this->_id
;
653 $checkPaymentID = array_search('Check', CRM_Contribute_BAO_Contribution
::buildOptions('payment_instrument_id', 'validate'));
654 $paymentInstrument = $this->add('select', 'payment_instrument_id',
655 ts('Payment Method'),
656 ['' => ts('- select -')] + CRM_Contribute_BAO_Contribution
::buildOptions('payment_instrument_id', 'create'),
657 $required, ['onChange' => "return showHideByValue('payment_instrument_id','{$checkPaymentID}','checkNumber','table-row','select',false);"]
661 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), ['class' => 'twelve'] +
$attributes['trxn_id']);
663 //add receipt for offline contribution
664 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
666 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
668 $componentDetails = [];
670 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
672 $status = $this->getAvailableContributionStatuses();
674 // define the status IDs that show the cancellation info, see CRM-17589
675 $cancelInfo_show_ids = [];
676 foreach (array_keys($status) as $status_id) {
677 if (CRM_Contribute_BAO_Contribution
::isContributionStatusNegative($status_id)) {
678 $cancelInfo_show_ids[] = "'$status_id'";
681 $this->assign('cancelInfo_show_ids', implode(',', $cancelInfo_show_ids));
683 $statusElement = $this->add('select', 'contribution_status_id',
684 ts('Contribution Status'),
689 $currencyFreeze = FALSE;
690 if (!empty($this->_payNow
) && ($this->_action
& CRM_Core_Action
::UPDATE
)) {
691 $statusElement->freeze();
692 $currencyFreeze = TRUE;
693 $attributes['total_amount']['readonly'] = TRUE;
696 // CRM-16189, add Revenue Recognition Date
697 if (Civi
::settings()->get('deferred_revenue_enabled')) {
698 $revenueDate = $this->add('datepicker', 'revenue_recognition_date', ts('Revenue Recognition Date'), [], FALSE, ['time' => FALSE]);
699 if ($this->_id
&& !CRM_Contribute_BAO_Contribution
::allowUpdateRevenueRecognitionDate($this->_id
)) {
700 $revenueDate->freeze();
704 // If contribution is a template receive date is not required
705 $receiveDateRequired = !$this->_values
['is_template'];
707 $this->addField('receive_date', ['entity' => 'contribution'], $receiveDateRequired, FALSE);
708 $this->addField('receipt_date', ['entity' => 'contribution'], FALSE, FALSE);
709 $this->addField('cancel_date', ['entity' => 'contribution', 'label' => ts('Cancelled / Refunded Date')], FALSE, FALSE);
711 if ($this->_online
) {
712 $this->assign('hideCalender', TRUE);
715 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
718 if (empty($this->_lineItems
)) {
719 $buildPriceSet = FALSE;
720 $priceSets = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute');
721 if (!empty($priceSets) && !$this->_ppID
) {
722 $buildPriceSet = TRUE;
725 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
726 // and if we already have line items for that participant. CRM-5095
727 if ($buildPriceSet && $this->_id
) {
728 $pledgePaymentId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
733 if ($pledgePaymentId) {
734 $buildPriceSet = FALSE;
736 if ($participantID = CRM_Utils_Array
::value('participant', $componentDetails)) {
737 $participantLI = CRM_Price_BAO_LineItem
::getLineItems($participantID);
738 if (!CRM_Utils_System
::isNull($participantLI)) {
739 $buildPriceSet = FALSE;
744 $hasPriceSets = FALSE;
745 if ($buildPriceSet) {
746 $hasPriceSets = TRUE;
747 // CRM-16451: set financial type of 'Price Set' in back office contribution
748 // instead of selecting manually
749 $financialTypeIds = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute', 'financial_type_id');
750 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
752 '' => ts('Choose price set'),
754 NULL, ['onchange' => "buildAmount( this.value, " . json_encode($financialTypeIds) . ");"]
756 if ($this->_online
&& !($this->_action
& CRM_Core_Action
::UPDATE
)) {
760 $this->assign('hasPriceSets', $hasPriceSets);
761 if (!($this->_action
& CRM_Core_Action
::UPDATE
)) {
762 if ($this->_online ||
$this->_ppID
) {
763 $attributes['total_amount'] = array_merge($attributes['total_amount'], [
765 'style' => "background-color:#EBECE4",
768 '1' => ts('Adjust Pledge Payment Schedule?'),
769 '2' => ts('Adjust Total Pledge Amount?'),
771 $this->addRadio('option_type',
777 $currencyFreeze = TRUE;
781 $totalAmount = $this->addMoney('total_amount',
784 $attributes['total_amount'],
785 TRUE, 'currency', NULL, $currencyFreeze
789 $this->add('text', 'source', ts('Source'), CRM_Utils_Array
::value('source', $attributes));
791 // CRM-7362 --add campaigns.
792 CRM_Campaign_BAO_Campaign
::addCampaign($this, CRM_Utils_Array
::value('campaign_id', $this->_values
));
794 if (empty($this->_payNow
)) {
795 CRM_Contribute_Form_SoftCredit
::buildQuickForm($this);
800 $js = ['onclick' => "return verify( );"];
803 $mailingInfo = Civi
::settings()->get('mailing_backend');
804 $this->assign('outBound_option', $mailingInfo['outBound_option']);
809 'name' => ts('Save'),
815 'name' => ts('Save and New'),
821 'name' => ts('Cancel'),
825 // if contribution is related to membership or participant freeze Financial Type, Amount
827 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
828 $isCancelledStatus = ($this->_values
['contribution_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Cancelled'));
830 if (!empty($componentDetails['membership']) ||
831 !empty($componentDetails['participant']) ||
832 // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
833 // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
837 $totalAmount->freeze();
838 $this->getElement('currency')->freeze();
840 if ($isCancelledStatus) {
841 $paymentInstrument->freeze();
844 $financialType->freeze();
845 $this->assign('freezeFinancialType', TRUE);
849 if ($this->_action
& CRM_Core_Action
::VIEW
) {
857 * @param array $fields
858 * The input form values.
859 * @param array $files
860 * The uploaded files if any.
864 * true if no errors, else array of errors
866 public static function formRule($fields, $files, $self) {
868 // Check for Credit Card Contribution.
870 if (empty($fields['payment_processor_id'])) {
871 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
874 // validate payment instrument (e.g. credit card number)
875 CRM_Core_Payment_Form
::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, NULL);
879 // Do the amount validations.
880 if (empty($fields['total_amount']) && empty($self->_lineItems
)) {
881 if ($priceSetId = CRM_Utils_Array
::value('price_set_id', $fields)) {
882 CRM_Price_BAO_PriceField
::priceSetValidation($priceSetId, $fields, $errors);
886 $softErrors = CRM_Contribute_Form_SoftCredit
::formRule($fields, $errors, $self);
888 //CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
889 CRM_Contribute_BAO_ContributionRecur
::validateRecurContribution($fields, $files, $self, $errors);
891 // Form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
892 if (($self->_action
& CRM_Core_Action
::UPDATE
)
894 && $self->_values
['contribution_status_id'] != $fields['contribution_status_id']
895 && $self->_values
['is_template'] != 1
897 CRM_Contribute_BAO_Contribution
::checkStatusValidation($self->_values
, $fields, $errors);
899 // CRM-16015, add form-rule to restrict change of financial type if using price field of different financial type
900 if (($self->_action
& CRM_Core_Action
::UPDATE
)
902 && $self->_values
['financial_type_id'] != $fields['financial_type_id']
904 CRM_Contribute_BAO_Contribution
::checkFinancialTypeChange(NULL, $self->_id
, $errors);
906 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
907 if (!empty($fields['fee_amount']) && !empty($fields['financial_type_id']) && $financialType = CRM_Contribute_BAO_Contribution
::validateFinancialType($fields['financial_type_id'])) {
908 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
911 // $trxn_id must be unique CRM-13919
912 if (!empty($fields['trxn_id'])) {
913 $queryParams = [1 => [$fields['trxn_id'], 'String']];
914 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
916 $queryParams[2] = [(int) $self->_id
, 'Integer'];
917 $query .= ' and id !=%2';
919 $tCnt = CRM_Core_DAO
::singleValueQuery($query, $queryParams);
921 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', [1 => $fields['trxn_id']]);
925 $order = new CRM_Financial_BAO_Order();
926 $order->setPriceSelectionFromUnfilteredInput($fields);
927 if (isset($fields['total_amount'])) {
928 $order->setOverrideTotalAmount((float) CRM_Utils_Rule
::cleanMoney($fields['total_amount']));
930 $lineItems = $order->getLineItems();
932 CRM_Financial_BAO_FinancialAccount
::checkFinancialTypeHasDeferred($fields, $self->_id
, $lineItems);
934 catch (CRM_Core_Exception
$e) {
935 $errors['financial_type_id'] = ' ';
936 $errors['_qf_default'] = $e->getMessage();
938 $errors = array_merge($errors, $softErrors);
943 * Process the form submission.
945 public function postProcess() {
946 if ($this->_action
& CRM_Core_Action
::DELETE
) {
947 CRM_Contribute_BAO_Contribution
::deleteContribution($this->_id
);
948 CRM_Core_Session
::singleton()->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
949 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
953 // Get the submitted form values.
954 $submittedValues = $this->controller
->exportValues($this->_name
);
955 if ($this->_values
['is_template']) {
956 // If we are a template contribution we don't allow the contribution_status_id to be set
957 // on the form but we need it for the submit function.
958 $submittedValues['is_template'] = $this->_values
['is_template'];
959 $submittedValues['contribution_status_id'] = $this->_values
['contribution_status_id'];
963 $contribution = $this->submit($submittedValues, $this->_action
, $this->_ppID
);
965 catch (PaymentProcessorException
$e) {
966 // Set the contribution mode.
967 $urlParams = "action=add&cid={$this->_contactID}";
969 $urlParams .= "&mode={$this->_mode}";
971 if (!empty($this->_ppID
)) {
972 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
975 CRM_Core_Error
::statusBounce($e->getMessage(), $urlParams, ts('Payment Processor Error'));
977 $this->setUserContext();
979 //store contribution ID if not yet set (on create)
980 if (empty($this->_id
) && !empty($contribution->id
)) {
981 $this->_id
= $contribution->id
;
983 if (!empty($this->_id
) && CRM_Core_Permission
::access('CiviMember')) {
984 $membershipPaymentCount = civicrm_api3('MembershipPayment', 'getCount', ['contribution_id' => $this->_id
]);
985 if ($membershipPaymentCount) {
986 $this->ajaxResponse
['updateTabs']['#tab_member'] = CRM_Contact_BAO_Contact
::getCountComponent('membership', $this->_contactID
);
989 if (!empty($this->_id
) && CRM_Core_Permission
::access('CiviEvent')) {
990 $participantPaymentCount = civicrm_api3('ParticipantPayment', 'getCount', ['contribution_id' => $this->_id
]);
991 if ($participantPaymentCount) {
992 $this->ajaxResponse
['updateTabs']['#tab_participant'] = CRM_Contact_BAO_Contact
::getCountComponent('participant', $this->_contactID
);
998 * Process credit card payment.
1000 * @param array $submittedValues
1001 * @param array $lineItem
1003 * @param int $contactID
1006 * @return bool|\CRM_Contribute_DAO_Contribution
1008 * @throws \CRM_Core_Exception
1009 * @throws \Civi\Payment\Exception\PaymentProcessorException
1010 * @throws \CiviCRM_API3_Exception
1012 protected function processCreditCard($submittedValues, $lineItem, $contactID) {
1013 $isTest = ($this->_mode
== 'test') ?
1 : 0;
1014 // CRM-12680 set $_lineItem if its not set
1015 // @todo - I don't believe this would ever BE set. I can't find anywhere in the code.
1016 // It would be better to pass line item out to functions than $this->_lineItem as
1017 // we don't know what is being changed where.
1018 if (empty($this->_lineItem
) && !empty($lineItem)) {
1019 $this->_lineItem
= $lineItem;
1022 $this->_paymentObject
= Civi\Payment\System
::singleton()->getById($submittedValues['payment_processor_id']);
1023 $this->_paymentProcessor
= $this->_paymentObject
->getPaymentProcessor();
1025 // Set source if not set
1026 if (empty($submittedValues['source'])) {
1027 $userID = CRM_Core_Session
::singleton()->get('userID');
1028 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1031 $submittedValues['source'] = ts('Submit Credit Card Payment by: %1', [1 => $userSortName]);
1034 $params = $submittedValues;
1035 $this->_params
= array_merge($this->_params
, $submittedValues);
1037 // Mapping requiring documentation.
1038 $this->_params
['payment_processor'] = $submittedValues['payment_processor_id'];
1040 $now = date('YmdHis');
1042 $this->_contributorEmail
= $this->userEmail
;
1043 $this->_contributorContactID
= $contactID;
1044 $this->processBillingAddress();
1045 if (!empty($params['source'])) {
1046 unset($params['source']);
1049 $this->_params
['amount'] = $this->_params
['total_amount'];
1050 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
1051 // function to get correct amount level consistently. Remove setting of the amount level in
1052 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
1053 // to cover all variants.
1054 $this->_params
['amount_level'] = 0;
1055 $this->_params
['description'] = ts("Contribution submitted by a staff person using contributor's credit card");
1056 $this->_params
['currencyID'] = CRM_Utils_Array
::value('currency',
1058 CRM_Core_Config
::singleton()->defaultCurrency
1061 $this->_params
['pcp_display_in_roll'] = $params['pcp_display_in_roll'] ??
NULL;
1062 $this->_params
['pcp_roll_nickname'] = $params['pcp_roll_nickname'] ??
NULL;
1063 $this->_params
['pcp_personal_note'] = $params['pcp_personal_note'] ??
NULL;
1065 //Add common data to formatted params
1066 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
1068 if (empty($this->_params
['invoice_id'])) {
1069 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
1072 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
1075 // At this point we've created a contact and stored its address etc
1076 // all the payment processors expect the name and address to be in the
1077 // so we copy stuff over to first_name etc.
1078 $paymentParams = $this->_params
;
1079 $paymentParams['contactID'] = $contactID;
1080 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
1082 $financialType = new CRM_Financial_DAO_FinancialType();
1083 $financialType->id
= $params['financial_type_id'];
1084 $financialType->find(TRUE);
1086 // Add some financial type details to the params list
1087 // if folks need to use it.
1088 $paymentParams['contributionType_name'] = $this->_params
['contributionType_name'] = $financialType->name
;
1089 $paymentParams['contributionPageID'] = NULL;
1091 if (!empty($this->_params
['is_email_receipt'])) {
1092 $paymentParams['email'] = $this->userEmail
;
1093 $paymentParams['is_email_receipt'] = 1;
1096 $paymentParams['is_email_receipt'] = 0;
1097 $this->_params
['is_email_receipt'] = 0;
1099 if (!empty($this->_params
['receive_date'])) {
1100 $paymentParams['receive_date'] = $this->_params
['receive_date'];
1103 if (!empty($this->_params
['is_email_receipt'])) {
1104 $this->_params
['receipt_date'] = $now;
1107 $this->set('params', $this->_params
);
1108 // It actually makes no sense that we would set receive_date in params
1109 // for credit card payments....
1110 $this->assign('receive_date', $this->_params
['receive_date'] ??
date('Y-m-d H:i:s'));
1112 // Result has all the stuff we need
1113 // lets archive it to a financial transaction
1114 if ($financialType->is_deductible
) {
1115 $this->assign('is_deductible', TRUE);
1116 $this->set('is_deductible', TRUE);
1118 $contributionParams = [
1119 'id' => $this->_params
['contribution_id'] ??
NULL,
1120 'contact_id' => $contactID,
1121 'line_item' => $lineItem,
1122 'is_test' => $isTest,
1123 'campaign_id' => $this->_params
['campaign_id'] ??
NULL,
1124 'contribution_page_id' => $this->_params
['contribution_page_id'] ??
NULL,
1125 'source' => CRM_Utils_Array
::value('source', $paymentParams, CRM_Utils_Array
::value('description', $paymentParams)),
1126 'thankyou_date' => $this->_params
['thankyou_date'] ??
NULL,
1128 $contributionParams['payment_instrument_id'] = $this->_paymentProcessor
['payment_instrument_id'];
1130 $contribution = $this->processFormContribution(
1133 $contributionParams,
1137 CRM_Utils_Array
::value('is_recur', $this->_params
)
1140 $paymentParams['contributionID'] = $contribution->id
;
1141 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
1142 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1144 if ($paymentParams['amount'] > 0.0) {
1145 // force a re-get of the payment processor in case the form changed it, CRM-7179
1146 // NOTE - I expect this is obsolete.
1147 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
1149 $completeStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
1150 $result = $payment->doPayment($paymentParams, 'contribute');
1151 $this->assign('trxn_id', $result['trxn_id']);
1152 $contribution->trxn_id
= $result['trxn_id'];
1153 /* Our scenarios here are
1154 * 1) the payment failed & an Exception should have been thrown
1155 * 2) the payment succeeded but the payment is not immediate (for example a recurring payment
1156 * with a delayed start)
1157 * 3) the payment succeeded with an immediate payment.
1159 * The doPayment function ensures that payment_status_id is always set
1160 * as historically we have had to guess from the context - ie doDirectPayment
1161 * = error or success, unless it is a recurring contribution in which case it is pending.
1163 if ($result['payment_status_id'] == $completeStatusId) {
1165 civicrm_api3('contribution', 'completetransaction', [
1166 'id' => $contribution->id
,
1167 'trxn_id' => $result['trxn_id'],
1168 'payment_processor_id' => $this->_paymentProcessor
['id'],
1169 'is_transactional' => FALSE,
1170 'fee_amount' => $result['fee_amount'] ??
NULL,
1171 'card_type_id' => $paymentParams['card_type_id'] ??
NULL,
1172 'pan_truncation' => $paymentParams['pan_truncation'] ??
NULL,
1173 'is_email_receipt' => FALSE,
1175 // This has now been set to 1 in the DB - declare it here also
1176 $contribution->contribution_status_id
= 1;
1178 catch (CiviCRM_API3_Exception
$e) {
1179 if ($e->getErrorCode() != 'contribution_completed') {
1180 \Civi
::log()->error('CRM_Contribute_Form_Contribution::processCreditCard CiviCRM_API3_Exception: ' . $e->getMessage());
1181 throw new CRM_Core_Exception('Failed to update contribution in database');
1186 // Save the trxn_id.
1187 $contribution->save();
1190 catch (PaymentProcessorException
$e) {
1191 CRM_Contribute_BAO_Contribution
::failPayment($contribution->id
, $paymentParams['contactID'], $e->getMessage());
1192 throw new PaymentProcessorException($e->getMessage());
1195 // Send receipt mail.
1196 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1197 if ($contribution->id
&& !empty($this->_params
['is_email_receipt'])) {
1198 $this->_params
['trxn_id'] = $result['trxn_id'] ??
NULL;
1199 $this->_params
['contact_id'] = $contactID;
1200 $this->_params
['contribution_id'] = $contribution->id
;
1201 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $this->_params
, TRUE)) {
1202 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1206 return $contribution;
1210 * Process the contribution.
1212 * @todo - this form is a copy of the previously shared code on the front
1213 * end form - not all aspects of the code will be relevant to this form.
1215 * @param array $params
1216 * @param array $result
1217 * @param array $contributionParams
1218 * Parameters to be passed to contribution create action.
1219 * This differs from params in that we are currently adding params to it and 1) ensuring they are being
1220 * passed consistently & 2) documenting them here.
1225 * - contribution_page_id
1228 * - thankyou_date (not all forms will set this)
1230 * @param CRM_Financial_DAO_FinancialType $financialType
1231 * @param bool $online
1232 * Is the form a front end form? If so set a bunch of unpredictable things that should be passed in from the form.
1234 * @param int $billingLocationID
1235 * ID of billing location type.
1236 * @param bool $isRecur
1237 * Is this recurring?
1239 * @return \CRM_Contribute_DAO_Contribution
1241 * @throws \CRM_Core_Exception
1242 * @throws \CiviCRM_API3_Exception
1244 protected function processFormContribution(
1247 $contributionParams,
1254 $transaction = new CRM_Core_Transaction();
1255 $contactID = $contributionParams['contact_id'];
1257 $isEmailReceipt = !empty($form->_values
['is_email_receipt']);
1258 $isSeparateMembershipPayment = !empty($params['separate_membership_payment']);
1259 $pledgeID = !empty($params['pledge_id']) ?
$params['pledge_id'] : $form->_values
['pledge_id'] ??
NULL;
1260 if (!$isSeparateMembershipPayment && !empty($form->_values
['pledge_block_id']) &&
1261 (!empty($params['is_pledge']) ||
$pledgeID)) {
1268 // add these values for the recurringContrib function ,CRM-10188
1269 $params['financial_type_id'] = $financialType->id
;
1271 $contributionParams['address_id'] = CRM_Contribute_BAO_Contribution
::createAddress($params, $billingLocationID);
1273 //@todo - this is being set from the form to resolve CRM-10188 - an
1274 // eNotice caused by it not being set @ the front end
1275 // however, we then get it being over-written with null for backend contributions
1276 // a better fix would be to set the values in the respective forms rather than require
1277 // a function being shared by two forms to deal with their respective values
1278 // moving it to the BAO & not taking the $form as a param would make sense here.
1279 if (!isset($params['is_email_receipt']) && $isEmailReceipt) {
1280 $params['is_email_receipt'] = $isEmailReceipt;
1282 $params['is_recur'] = $isRecur;
1283 $params['payment_instrument_id'] = $contributionParams['payment_instrument_id'] ??
NULL;
1284 $recurringContributionID = CRM_Contribute_Form_Contribution_Confirm
::processRecurringContribution($form, $params, $contactID, $financialType);
1286 $now = date('YmdHis');
1287 $receiptDate = $params['receipt_date'] ??
NULL;
1288 if ($isEmailReceipt) {
1289 $receiptDate = $now;
1292 if (isset($params['amount'])) {
1293 $contributionParams = array_merge(CRM_Contribute_Form_Contribution_Confirm
::getContributionParams(
1294 $params, $financialType->id
,
1295 $result, $receiptDate,
1296 $recurringContributionID), $contributionParams
1298 $contributionParams['non_deductible_amount'] = CRM_Contribute_Form_Contribution_Confirm
::getNonDeductibleAmount($params, $financialType, FALSE, $form);
1299 $contributionParams['skipCleanMoney'] = TRUE;
1300 // @todo this is the wrong place for this - it should be done as close to form submission
1302 $contributionParams['total_amount'] = $params['amount'];
1304 $contribution = CRM_Contribute_BAO_Contribution
::add($contributionParams);
1306 if (Civi
::settings()->get('invoicing')) {
1308 // @todo - interrogate the line items passed in on the params array.
1309 // No reason to assume line items will be set on the form.
1310 foreach ($form->_lineItem
as $lineItemKey => $lineItemValue) {
1311 foreach ($lineItemValue as $key => $value) {
1312 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
1313 if (isset($dataArray[$value['tax_rate']])) {
1314 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] +
$value['tax_amount'];
1317 $dataArray[$value['tax_rate']] = $value['tax_amount'];
1322 $smarty = CRM_Core_Smarty
::singleton();
1323 $smarty->assign('dataArray', $dataArray);
1324 $smarty->assign('totalTaxAmount', $params['tax_amount'] ??
NULL);
1327 // lets store it in the form variable so postProcess hook can get to this and use it
1328 $form->_contributionID
= $contribution->id
;
1331 // process soft credit / pcp params first
1332 CRM_Contribute_BAO_ContributionSoft
::formatSoftCreditParams($params, $form);
1334 //CRM-13981, processing honor contact into soft-credit contribution
1335 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
1338 $form = CRM_Contribute_Form_Contribution_Confirm
::handlePledge($form, $params, $contributionParams, $pledgeID, $contribution, $isEmailReceipt);
1341 if ($online && $contribution) {
1342 CRM_Core_BAO_CustomValueTable
::postProcess($params,
1343 'civicrm_contribution',
1348 elseif ($contribution) {
1349 //handle custom data.
1350 $params['contribution_id'] = $contribution->id
;
1351 if (!empty($params['custom']) &&
1352 is_array($params['custom'])
1354 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
1358 if ($contribution && !empty($params['contribution_note'])) {
1360 'entity_table' => 'civicrm_contribution',
1361 'note' => $params['contribution_note'],
1362 'entity_id' => $contribution->id
,
1363 'contact_id' => $contribution->contact_id
,
1366 CRM_Core_BAO_Note
::add($noteParams, []);
1369 //create contribution activity w/ individual and target
1370 //activity w/ organisation contact id when onbelf, CRM-4027
1372 $targetContactID = NULL;
1373 if (!empty($params['onbehalf_contact_id'])) {
1375 'source_contact_id' => $params['onbehalf_contact_id'],
1376 'on_behalf' => TRUE,
1378 $targetContactID = $contribution->contact_id
;
1381 // create an activity record
1382 if ($contribution) {
1383 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Contribution', $targetContactID, $actParams);
1386 $transaction->commit();
1387 return $contribution;
1391 * Generate the data to construct a snippet based pane.
1393 * This form also assigns the showAdditionalInfo var based on historical code.
1394 * This appears to mean 'there is a pane to show'.
1396 * @param string $type
1397 * Type of Pane - this is generally used to determine the function name used to build it
1398 * - e.g CreditCard, AdditionalDetail
1399 * @param array $defaults
1402 * We aim to further refactor & simplify this but currently
1404 * - should additional info be shown?
1406 protected function generatePane($type, $defaults) {
1407 $urlParams = "snippet=4&formType={$type}";
1409 $urlParams .= "&mode={$this->_mode}";
1413 if ($type == 'CreditCard' ||
1414 $type == 'DirectDebit'
1420 'url' => CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams),
1425 // See if we need to include this paneName in the current form.
1426 if ($this->_formType
== $type ||
!empty($_POST["hidden_{$type}"]) ||
1427 !empty($defaults["hidden_{$type}"])
1429 $this->assign('showAdditionalInfo', TRUE);
1430 $pane['open'] = 'true';
1433 if ($type == 'CreditCard' ||
$type == 'DirectDebit') {
1434 // @todo would be good to align tpl name with form name...
1435 // @todo document why this hidden variable is required.
1436 $this->add('hidden', 'hidden_' . $type, 1);
1440 $additionalInfoFormFunction = 'build' . $type;
1441 CRM_Contribute_Form_AdditionalInfo
::$additionalInfoFormFunction($this);
1447 * Wrapper for unit testing the post process submit function.
1449 * (If we expose through api we can get default additions 'for free').
1451 * @param array $params
1452 * @param int $action
1453 * @param string|null $creditCardMode
1455 * @return CRM_Contribute_BAO_Contribution
1457 * @throws \CRM_Core_Exception
1458 * @throws \CiviCRM_API3_Exception
1459 * @throws \Civi\Payment\Exception\PaymentProcessorException
1461 public function testSubmit($params, $action, $creditCardMode = NULL) {
1463 'soft_credit_contact_id' => [],
1464 'receive_date' => date('Y-m-d H:i:s'),
1465 'receipt_date' => '',
1466 'cancel_date' => '',
1467 'hidden_Premium' => 1,
1470 if (!empty($params['id'])) {
1471 $existingContribution = civicrm_api3('contribution', 'getsingle', [
1472 'id' => $params['id'],
1474 $this->_id
= $params['id'];
1475 $this->_values
= $existingContribution;
1476 if (CRM_Invoicing_Utils
::isInvoicingEnabled()) {
1477 $this->_values
['tax_amount'] = civicrm_api3('contribution', 'getvalue', [
1478 'id' => $params['id'],
1479 'return' => 'tax_amount',
1484 $existingContribution = [];
1487 $this->_defaults
['contribution_status_id'] = CRM_Utils_Array
::value('contribution_status_id',
1488 $existingContribution
1491 $this->_defaults
['total_amount'] = CRM_Utils_Array
::value('total_amount',
1492 $existingContribution
1495 if ($creditCardMode) {
1496 $this->_mode
= $creditCardMode;
1499 // Required because processCreditCard calls set method on this.
1500 $_SERVER['REQUEST_METHOD'] = 'GET';
1501 $this->controller
= new CRM_Core_Controller();
1503 CRM_Contribute_Form_AdditionalInfo
::buildPremium($this);
1505 $this->_fields
= [];
1506 return $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array
::value('pledge_payment_id', $params));
1511 * @param array $submittedValues
1513 * @param int $action
1515 * - CRM_Core_Action::UPDATE
1517 * @param $pledgePaymentID
1519 * @return \CRM_Contribute_BAO_Contribution
1521 * @throws \CRM_Core_Exception
1522 * @throws \CiviCRM_API3_Exception
1523 * @throws \Civi\Payment\Exception\PaymentProcessorException
1525 protected function submit($submittedValues, $action, $pledgePaymentID) {
1526 $pId = $contribution = $isRelatedId = FALSE;
1527 $this->_params
= $submittedValues;
1528 $this->beginPostProcess();
1529 // reassign submitted form values if the any information is formatted via beginPostProcess
1530 $submittedValues = $this->_params
;
1532 if ($this->getPriceSetID() && $action & CRM_Core_Action
::UPDATE
) {
1533 $line = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution');
1534 $lineID = key($line);
1535 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array
::value('price_field_id', $line[$lineID]), 'price_set_id');
1536 $quickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1537 // Why do we do this? Seems like a like a wrapper for old functionality - but single line price sets & quick
1538 // config should be treated the same.
1540 CRM_Price_BAO_LineItem
::deleteLineItems($this->_id
, 'civicrm_contribution');
1544 // Process price set and get total amount and line items.
1546 $priceSetId = $submittedValues['price_set_id'] ??
NULL;
1547 if (!$this->getPriceSetID() && !$this->_id
) {
1548 $this->_priceSetId
= $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1549 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
1550 $fieldID = key($this->_priceSet
['fields']);
1551 $fieldValueId = key($this->_priceSet
['fields'][$fieldID]['options']);
1552 $this->_priceSet
['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1553 $submittedValues['price_' . $fieldID] = 1;
1556 // Every contribution has a price-set - the only reason it shouldn't be set is if we are dealing with
1557 // quick config (very very arguably) & yet we see that this could still be quick config so this should be understood
1558 // as a point of fragility rather than a logical 'if' clause.
1560 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
1561 $submittedValues, $lineItem[$priceSetId], $priceSetId);
1562 // Unset tax amount for offline 'is_quick_config' contribution.
1563 // @todo WHY - quick config was conceived as a quick way to configure contribution forms.
1564 // this is an example of 'other' functionality being hung off it.
1565 if ($this->_priceSet
['is_quick_config'] &&
1566 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant
::getTaxRates())
1568 unset($submittedValues['tax_amount']);
1570 $submittedValues['total_amount'] = $submittedValues['amount'] ??
NULL;
1574 if ($this->_compId
) {
1575 if ($this->_context
== 'participant') {
1576 $pId = $this->_compId
;
1578 elseif ($this->_context
== 'membership') {
1579 $isRelatedId = TRUE;
1582 $pId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id
, 'participant_id', 'contribution_id');
1586 $contributionDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1587 if (array_key_exists('membership', $contributionDetails)) {
1588 $isRelatedId = TRUE;
1590 elseif (array_key_exists('participant', $contributionDetails)) {
1591 $pId = $contributionDetails['participant'];
1594 if (!empty($this->_payNow
)) {
1595 $this->_params
['contribution_id'] = $this->_id
;
1599 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id
) {
1600 // CRM-10117 update the line items for participants.
1601 // @todo - if we are completing a contribution then the api call
1602 // civicrm_api3('Contribution', 'completetransaction') should take care of
1603 // all associated updates rather than replicating them on the form layer.
1605 $entityTable = 'participant';
1607 $isRelatedId = FALSE;
1608 $participantParams = [
1609 'fee_amount' => $submittedValues['total_amount'],
1612 CRM_Event_BAO_Participant
::add($participantParams);
1613 if (empty($this->_lineItems
)) {
1614 $this->_lineItems
[] = CRM_Price_BAO_LineItem
::getLineItems($entityID, 'participant', TRUE);
1618 $entityTable = 'contribution';
1619 $entityID = $this->_id
;
1622 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, $entityTable, FALSE, TRUE, $isRelatedId);
1623 foreach (array_keys($lineItems) as $id) {
1624 $lineItems[$id]['id'] = $id;
1626 $itemId = key($lineItems);
1627 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1628 $this->_priceSetId
= CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1631 // @todo see above - new functionality has been inappropriately added to the quick config concept
1632 // and new functionality has been added onto the form layer rather than the BAO :-(
1633 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1634 //CRM-16833: Ensure tax is applied only once for membership conribution, when status changed.(e.g Pending to Completed).
1635 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1636 if (empty($componentDetails['membership']) && empty($componentDetails['participant'])) {
1637 if (!($this->_action
& CRM_Core_Action
::UPDATE
&& (($this->_defaults
['contribution_status_id'] != $submittedValues['contribution_status_id'])))) {
1638 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule
::cleanMoney(CRM_Utils_Array
::value('total_amount', $submittedValues));
1642 // Update line total and total amount with tax on edit.
1643 $financialItemsId = CRM_Core_PseudoConstant
::getTaxRates();
1644 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1645 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1648 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1649 $submittedValues['tax_amount'] = 0;
1651 if ($lineItems[$itemId]['tax_rate']) {
1652 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total'];
1653 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] +
$lineItems[$itemId]['tax_amount'];
1654 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1657 // CRM-10117 update the line items for participants.
1658 if (!empty($lineItems[$itemId]['price_field_id'])) {
1659 $lineItem[$this->_priceSetId
] = $lineItems;
1664 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1667 //CRM-11529 for quick config back office transactions
1668 //when financial_type_id is passed in form, update the
1669 //line items with the financial type selected in form
1670 // NOTE that this IS still a legitimate use of 'quick-config' for contributions under the current DB but
1671 // we should look at having a price field per contribution type & then there would be little reason
1672 // for the back-office contribution form postProcess to know if it is a quick-config form.
1673 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && !empty($lineItem[$this->_priceSetId
])
1675 foreach ($lineItem[$this->_priceSetId
] as &$values) {
1676 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1680 if (!isset($submittedValues['total_amount'])) {
1681 $submittedValues['total_amount'] = $this->_values
['total_amount'] ??
NULL;
1682 // Avoid tax amount deduction on edit form and keep it original, because this will lead to error described in CRM-20676
1684 $submittedValues['total_amount'] -= CRM_Utils_Array
::value('tax_amount', $this->_values
, 0);
1687 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
1689 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id'] ??
[]));
1690 if ($this->_id
&& count($isEmpty) == 1 && key($isEmpty) == NULL) {
1691 civicrm_api3('ContributionSoft', 'get', ['contribution_id' => $this->_id
, 'pcp_id' => ['IS NULL' => 1], 'api.ContributionSoft.delete' => 1]);
1694 // set the contact, when contact is selected
1695 if (!empty($submittedValues['contact_id'])) {
1696 $this->_contactID
= $submittedValues['contact_id'];
1699 $formValues = $submittedValues;
1701 // Credit Card Contribution.
1703 $paramsSetByPaymentProcessingSubsystem = [
1705 'payment_instrument_id',
1706 'contribution_status_id',
1710 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1711 if (isset($formValues[$key])) {
1712 unset($formValues[$key]);
1715 $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID
);
1716 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1717 $formValues[$key] = $contribution->$key;
1721 // Offline Contribution.
1722 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1724 // get the required field value only.
1727 'contact_id' => $this->_contactID
,
1728 'currency' => $this->getCurrency($submittedValues),
1729 'skipCleanMoney' => TRUE,
1733 //format soft-credit/pcp param first
1734 CRM_Contribute_BAO_ContributionSoft
::formatSoftCreditParams($submittedValues, $this);
1735 $params = array_merge($params, $submittedValues);
1738 'financial_type_id',
1739 'contribution_status_id',
1740 'payment_instrument_id',
1747 foreach ($fields as $f) {
1748 $params[$f] = $formValues[$f] ??
NULL;
1751 $params['revenue_recognition_date'] = NULL;
1752 if (!empty($formValues['revenue_recognition_date'])) {
1753 $params['revenue_recognition_date'] = $formValues['revenue_recognition_date'];
1756 if (!empty($formValues['is_email_receipt'])) {
1757 $params['receipt_date'] = date("Y-m-d");
1760 if (CRM_Contribute_BAO_Contribution
::isContributionStatusNegative($params['contribution_status_id'])
1762 if (CRM_Utils_System
::isNull(CRM_Utils_Array
::value('cancel_date', $params))) {
1763 $params['cancel_date'] = date('YmdHis');
1767 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1770 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1771 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1772 if ($params['contribution_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending')) {
1773 $params['is_pay_later'] = 1;
1775 elseif ($params['contribution_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed')) {
1776 // @todo - if the contribution is new then it should be Pending status & then we use
1777 // Payment.create to update to Completed.
1778 $params['is_pay_later'] = 0;
1781 // Add Additional common information to formatted params.
1782 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($formValues, $params, $this);
1784 $params['contribution_mode'] = 'participant';
1785 $params['participant_id'] = $pId;
1786 $params['skipLineItem'] = 1;
1788 $params['line_item'] = $lineItem;
1789 $params['payment_processor_id'] = $params['payment_processor'] = $this->_paymentProcessor
['id'] ??
NULL;
1790 $params['tax_amount'] = CRM_Utils_Array
::value('tax_amount', $submittedValues, CRM_Utils_Array
::value('tax_amount', $this->_values
));
1791 //create contribution.
1792 if ($isQuickConfig) {
1793 $params['is_quick_config'] = 1;
1795 $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
1797 // we are already handling note below, so to avoid duplicate notes against $contribution
1798 if (!empty($params['note']) && !empty($submittedValues['note'])) {
1799 unset($params['note']);
1801 $contribution = CRM_Contribute_BAO_Contribution
::create($params);
1803 // process associated membership / participant, CRM-4395
1804 if ($contribution->id
&& $action & CRM_Core_Action
::UPDATE
) {
1805 // @todo use Payment.create to do this, remove transitioncomponents function
1806 // if contribution is being created with a completed status it should be
1807 // created pending & then Payment.create adds the payment
1808 CRM_Contribute_BAO_Contribution
::transitionComponents([
1809 'contribution_id' => $contribution->id
,
1810 'contribution_status_id' => $contribution->contribution_status_id
,
1811 'previous_contribution_status_id' => $this->_values
['contribution_status_id'] ??
NULL,
1812 'receive_date' => $contribution->receive_date
,
1816 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1818 $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
1820 //send receipt mail.
1821 if ($contribution->id
&& !empty($formValues['is_email_receipt'])) {
1822 $formValues['contact_id'] = $this->_contactID
;
1823 $formValues['contribution_id'] = $contribution->id
;
1825 $formValues +
= CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
);
1827 // to get 'from email id' for send receipt
1828 $this->fromEmailId
= $formValues['from_email_address'] ??
NULL;
1829 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $formValues)) {
1830 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1834 $this->statusMessageTitle
= ts('Saved');
1838 if ($contribution->id
&& isset($formValues['product_name'][0])) {
1839 CRM_Contribute_Form_AdditionalInfo
::processPremium($submittedValues, $contribution->id
,
1840 $this->_premiumID
, $this->_options
1844 if ($contribution->id
&& array_key_exists('note', $submittedValues)) {
1845 CRM_Contribute_Form_AdditionalInfo
::processNote($submittedValues, $this->_contactID
, $contribution->id
, $this->_noteID
);
1848 CRM_Core_Session
::setStatus(implode(' ', $this->statusMessage
), $this->statusMessageTitle
, 'success');
1850 CRM_Contribute_BAO_Contribution
::updateRelatedPledge(
1854 ($formValues['option_type'] ??
0) == 2,
1855 $formValues['total_amount'],
1856 CRM_Utils_Array
::value('total_amount', $this->_defaults
),
1857 $formValues['contribution_status_id'],
1858 CRM_Utils_Array
::value('contribution_status_id', $this->_defaults
)
1860 return $contribution;
1864 * Assign tax calculations to contribution receipts.
1866 * @param array $submittedValues
1867 * @param int $action
1868 * @param array $lineItem
1870 protected function invoicingPostProcessHook($submittedValues, $action, $lineItem) {
1871 if (!Civi
::settings()->get('invoicing')) {
1875 $getTaxDetails = FALSE;
1877 foreach ($lineItem as $key => $value) {
1878 foreach ($value as $v) {
1879 if (isset($taxRate[(string) CRM_Utils_Array
::value('tax_rate', $v)])) {
1880 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $v);
1883 if (isset($v['tax_rate'])) {
1884 $taxRate[(string) $v['tax_rate']] = $v['tax_amount'] ??
NULL;
1885 $getTaxDetails = TRUE;
1891 if ($action & CRM_Core_Action
::UPDATE
) {
1892 if (isset($submittedValues['tax_amount'])) {
1893 $totalTaxAmount = $submittedValues['tax_amount'];
1896 $totalTaxAmount = $this->_values
['tax_amount'];
1898 $this->assign('totalTaxAmount', $totalTaxAmount);
1899 $this->assign('dataArray', $taxRate);
1902 if (!empty($submittedValues['price_set_id'])) {
1903 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1904 $this->assign('getTaxDetails', $getTaxDetails);
1905 $this->assign('dataArray', $taxRate);
1906 $this->assign('taxTerm', Civi
::settings()->get('tax_term'));
1909 $this->assign('totalTaxAmount', CRM_Utils_Array
::value('tax_amount', $submittedValues));
1915 * Calculate non deductible amount.
1917 * @see https://issues.civicrm.org/jira/browse/CRM-11956
1918 * if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1919 * if non_deductible_amount does NOT exist - then calculate it depending on:
1920 * $financialType->is_deductible and whether there is a product (premium).
1923 * @param $formValues
1927 protected function calculateNonDeductibleAmount($params, $formValues) {
1928 if (!empty($params['non_deductible_amount'])) {
1929 return $params['non_deductible_amount'];
1932 $priceSetId = $params['price_set_id'] ??
NULL;
1933 // return non-deductible amount if it is set at the price field option level
1934 if ($priceSetId && !empty($params['line_item'])) {
1935 $nonDeductibleAmount = CRM_Price_BAO_PriceSet
::getNonDeductibleAmountFromPriceSet($priceSetId, $params['line_item']);
1936 if (!empty($nonDeductibleAmount)) {
1937 return $nonDeductibleAmount;
1941 $financialType = new CRM_Financial_DAO_FinancialType();
1942 $financialType->id
= $params['financial_type_id'];
1943 $financialType->find(TRUE);
1945 if ($financialType->is_deductible
) {
1947 if (isset($formValues['product_name'][0])) {
1948 $selectProduct = $formValues['product_name'][0];
1950 // if there is a product - compare the value to the contribution amount
1951 if (isset($selectProduct)) {
1952 $productDAO = new CRM_Contribute_DAO_Product();
1953 $productDAO->id
= $selectProduct;
1954 $productDAO->find(TRUE);
1955 // product value exceeds contribution amount
1956 if ($params['total_amount'] < $productDAO->price
) {
1957 return $params['total_amount'];
1959 // product value does NOT exceed contribution amount
1961 return $productDAO->price
;
1964 // contribution is deductible - but there is no product
1969 // contribution is NOT deductible
1971 return $params['total_amount'];
1978 * Get the financial Type ID for the contribution either from the submitted values or from the contribution values if possible.
1980 * This is important for dev/core#1728 - ie ensure that if we are returned to the form for a form
1981 * error that any custom fields based on the selected financial type are loaded.
1985 protected function getFinancialTypeID() {
1986 if (!empty($this->_submitValues
['financial_type_id'])) {
1987 return $this->_submitValues
['financial_type_id'];
1989 if (!empty($this->_values
['financial_type_id'])) {
1990 return $this->_values
['financial_type_id'];
1995 * Set context in session
1997 public function setUserContext(): void
{
1998 $session = CRM_Core_Session
::singleton();
1999 $buttonName = $this->controller
->getButtonName();
2000 if ($this->_context
== 'standalone') {
2001 if ($buttonName == $this->getButtonName('upload', 'new')) {
2002 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contribute/add',
2003 'reset=1&action=add&context=standalone'
2007 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
2008 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
2012 elseif ($this->_context
== 'contribution' && $this->_mode
&& $buttonName == $this->getButtonName('upload', 'new')) {
2013 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
2014 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
2017 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
2018 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
2019 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
2025 * Get the contribution ID.
2029 protected function getContributionID(): ?
int {
2034 * Get the selected contribution status.
2036 * @return string|null
2038 * @throws \API_Exception
2040 protected function getPreviousContributionStatus(): ?
string {
2041 if (!$this->getContributionID()) {
2044 if (!$this->previousContributionStatus
) {
2045 $this->previousContributionStatus
= Contribution
::get(FALSE)
2046 ->addWhere('id', '=', $this->getContributionID())
2047 ->addSelect('contribution_status_id:name')
2049 ->first()['contribution_status_id:name'];
2051 return $this->previousContributionStatus
;
2055 * Get the contribution statuses available on the form.
2057 * @todo - this needs work - some returned options are invalid or do
2058 * not create good financial entities. Probably the only reason we don't just
2059 * return CRM_Contribute_BAO_Contribution_Utils::getPendingCompleteFailedAndCancelledStatuses();
2060 * is that it might exclude the current status of the contribution.
2063 * @throws \API_Exception
2065 protected function getAvailableContributionStatuses(): array {
2066 if (!$this->getPreviousContributionStatus()) {
2067 return CRM_Contribute_BAO_Contribution_Utils
::getPendingCompleteFailedAndCancelledStatuses();
2069 $statusNames = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id', 'validate');
2070 $statusNamesToUnset = array_diff([
2071 // For records which represent a data template for a recurring
2072 // contribution that may not yet have a payment. This status should not
2073 // be available from forms. 'Template' contributions should only be created
2074 // in conjunction with a ContributionRecur record, and should have their
2075 // is_template field set to 1. This status excludes them from reports
2076 // that are still ignorant of the is_template field.
2080 ], [$this->getPreviousContributionStatus()]);
2081 switch ($this->getPreviousContributionStatus()) {
2083 // [CRM-17498] Removing unsupported status change options.
2084 $statusNamesToUnset = array_merge($statusNamesToUnset, [
2093 $statusNamesToUnset = array_merge($statusNamesToUnset, [
2101 $statusNamesToUnset = array_merge($statusNamesToUnset, [
2108 $statusNamesToUnset = array_merge($statusNamesToUnset, [
2119 foreach ($statusNamesToUnset as $name) {
2120 unset($statusNames[CRM_Utils_Array
::key($name, $statusNames)]);
2123 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id');
2125 foreach ($statuses as $statusID => $label) {
2126 if (!array_key_exists($statusID, $statusNames)) {
2127 unset($statuses[$statusID]);
2135 * Get the price set ID.
2137 * Note that the function currently returns NULL if not submitted
2138 * but will over time be fixed to always return an ID.
2142 protected function getPriceSetID() {
2143 return $this->getSubmittedValue('price_set_id');