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 (in_array('CiviPledge', CRM_Core_Config
::singleton()->enableComponents
) && !$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
);
284 // when custom data is included in this page
285 if (!empty($_POST['hidden_custom'])) {
286 $this->applyCustomData('Contribution', $this->getFinancialTypeID(), $this->_id
);
289 if (!empty($this->_values
['is_template'])) {
290 $this->assign('is_template', TRUE);
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 // display tax amount on edit contribution page
520 if ($invoicing && $this->_action
& CRM_Core_Action
::UPDATE
&& isset($this->_values
['tax_amount'])) {
521 $this->assign('totalTaxAmount', $this->_values
['tax_amount']);
524 if (empty($this->_lineItems
) &&
525 ($this->_priceSetId ||
!empty($_POST['price_set_id']))
527 $buildPriceSet = TRUE;
528 $getOnlyPriceSetElements = TRUE;
529 if (!$this->_priceSetId
) {
530 $this->_priceSetId
= $_POST['price_set_id'];
531 $getOnlyPriceSetElements = FALSE;
534 $this->set('priceSetId', $this->_priceSetId
);
535 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
537 // get only price set form elements.
538 if ($getOnlyPriceSetElements) {
542 // use to build form during form rule.
543 $this->assign('buildPriceSet', $buildPriceSet);
545 $defaults = $this->_values
;
546 $additionalDetailFields = [
550 'non_deductible_amount',
553 foreach ($additionalDetailFields as $key) {
554 if (!empty($defaults[$key])) {
555 $defaults['hidden_AdditionalDetail'] = 1;
560 if ($this->_productDAO
) {
561 if ($this->_productDAO
->product_id
) {
562 $defaults['hidden_Premium'] = 1;
566 if ($this->_noteID
&&
567 !CRM_Utils_System
::isNull($this->_values
['note'])
569 $defaults['hidden_AdditionalDetail'] = 1;
573 if (empty($this->_payNow
)) {
574 $paneNames[ts('Additional Details')] = 'AdditionalDetail';
577 //Add Premium pane only if Premium is exists.
578 $dao = new CRM_Contribute_DAO_Product();
581 if ($dao->find(TRUE) && empty($this->_payNow
)) {
582 $paneNames[ts('Premium Information')] = 'Premium';
585 $this->payment_instrument_id
= CRM_Utils_Array
::value('payment_instrument_id', $defaults, $this->getDefaultPaymentInstrumentId());
586 CRM_Core_Payment_Form
::buildPaymentForm($this, $this->_paymentProcessor
, FALSE, TRUE, $this->payment_instrument_id
);
587 if (!empty($this->_recurPaymentProcessors
)) {
588 $buildRecurBlock = TRUE;
590 // ppID denotes a pledge payment.
591 foreach ($this->_paymentProcessors
as $processor) {
592 if (!empty($processor['is_recur']) && !empty($processor['object']) && $processor['object']->supports('recurContributionsForPledges')) {
593 $buildRecurBlock = TRUE;
596 $buildRecurBlock = FALSE;
599 if ($buildRecurBlock) {
600 CRM_Contribute_Form_Contribution_Main
::buildRecur($this);
601 $this->setDefaults(['is_recur' => 0]);
602 $this->assign('buildRecurBlock', TRUE);
605 $this->addPaymentProcessorSelect(FALSE, $buildRecurBlock);
607 foreach ($paneNames as $name => $type) {
608 $allPanes[$name] = $this->generatePane($type, $defaults);
611 $qfKey = $this->controller
->_key
;
612 $this->assign('qfKey', $qfKey);
613 $this->assign('allPanes', $allPanes);
615 $this->addFormRule(['CRM_Contribute_Form_Contribution', 'formRule'], $this);
617 if ($this->_formType
) {
618 $this->assign('formType', $this->_formType
);
622 $this->applyFilter('__ALL__', 'trim');
624 //need to assign custom data type and subtype to the template
625 $this->assign('customDataType', 'Contribution');
626 $this->assign('customDataSubType', $this->getFinancialTypeID());
627 $this->assign('entityID', $this->_id
);
629 $contactField = $this->addEntityRef('contact_id', ts('Contributor'), ['create' => TRUE, 'api' => ['extra' => ['email']]], TRUE);
630 if ($this->_context
!== 'standalone') {
631 $contactField->freeze();
634 $attributes = CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Contribution');
636 // Check permissions for financial type first
637 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes, $this->_action
);
638 if (empty($financialTypes)) {
639 CRM_Core_Error
::statusBounce(ts('You do not have all the permissions needed for this page.'));
641 $financialType = $this->add('select', 'financial_type_id',
642 ts('Financial Type'),
643 ['' => ts('- select -')] +
$financialTypes,
645 ['onChange' => "CRM.buildCustomData( 'Contribution', this.value );"]
648 $paymentInstrument = FALSE;
650 // payment_instrument isn't required in edit and will not be present when payment block is enabled.
651 $required = !$this->_id
;
652 $checkPaymentID = array_search('Check', CRM_Contribute_BAO_Contribution
::buildOptions('payment_instrument_id', 'validate'));
653 $paymentInstrument = $this->add('select', 'payment_instrument_id',
654 ts('Payment Method'),
655 ['' => ts('- select -')] + CRM_Contribute_BAO_Contribution
::buildOptions('payment_instrument_id', 'create'),
656 $required, ['onChange' => "return showHideByValue('payment_instrument_id','{$checkPaymentID}','checkNumber','table-row','select',false);"]
660 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), ['class' => 'twelve'] +
$attributes['trxn_id']);
662 //add receipt for offline contribution
663 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
665 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
667 $componentDetails = [];
669 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
671 $status = CRM_Contribute_BAO_Contribution_Utils
::getContributionStatuses('contribution', $this->getPreviousContributionStatus());
673 // define the status IDs that show the cancellation info, see CRM-17589
674 $cancelInfo_show_ids = [];
675 foreach (array_keys($status) as $status_id) {
676 if (CRM_Contribute_BAO_Contribution
::isContributionStatusNegative($status_id)) {
677 $cancelInfo_show_ids[] = "'$status_id'";
680 $this->assign('cancelInfo_show_ids', implode(',', $cancelInfo_show_ids));
682 $statusElement = $this->add('select', 'contribution_status_id',
683 ts('Contribution Status'),
688 $currencyFreeze = FALSE;
689 if (!empty($this->_payNow
) && ($this->_action
& CRM_Core_Action
::UPDATE
)) {
690 $statusElement->freeze();
691 $currencyFreeze = TRUE;
692 $attributes['total_amount']['readonly'] = TRUE;
695 // CRM-16189, add Revenue Recognition Date
696 if (Civi
::settings()->get('deferred_revenue_enabled')) {
697 $revenueDate = $this->add('datepicker', 'revenue_recognition_date', ts('Revenue Recognition Date'), [], FALSE, ['time' => FALSE]);
698 if ($this->_id
&& !CRM_Contribute_BAO_Contribution
::allowUpdateRevenueRecognitionDate($this->_id
)) {
699 $revenueDate->freeze();
704 $this->addField('receive_date', ['entity' => 'contribution'], !$this->_mode
, FALSE);
705 $this->addField('receipt_date', ['entity' => 'contribution'], FALSE, FALSE);
706 $this->addField('cancel_date', ['entity' => 'contribution', 'label' => ts('Cancelled / Refunded Date')], FALSE, FALSE);
708 if ($this->_online
) {
709 $this->assign('hideCalender', TRUE);
712 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
715 if (empty($this->_lineItems
)) {
716 $buildPriceSet = FALSE;
717 $priceSets = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute');
718 if (!empty($priceSets) && !$this->_ppID
) {
719 $buildPriceSet = TRUE;
722 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
723 // and if we already have line items for that participant. CRM-5095
724 if ($buildPriceSet && $this->_id
) {
725 $pledgePaymentId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
730 if ($pledgePaymentId) {
731 $buildPriceSet = FALSE;
733 if ($participantID = CRM_Utils_Array
::value('participant', $componentDetails)) {
734 $participantLI = CRM_Price_BAO_LineItem
::getLineItems($participantID);
735 if (!CRM_Utils_System
::isNull($participantLI)) {
736 $buildPriceSet = FALSE;
741 $hasPriceSets = FALSE;
742 if ($buildPriceSet) {
743 $hasPriceSets = TRUE;
744 // CRM-16451: set financial type of 'Price Set' in back office contribution
745 // instead of selecting manually
746 $financialTypeIds = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute', 'financial_type_id');
747 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
749 '' => ts('Choose price set'),
751 NULL, ['onchange' => "buildAmount( this.value, " . json_encode($financialTypeIds) . ");"]
753 if ($this->_online
&& !($this->_action
& CRM_Core_Action
::UPDATE
)) {
757 $this->assign('hasPriceSets', $hasPriceSets);
758 if (!($this->_action
& CRM_Core_Action
::UPDATE
)) {
759 if ($this->_online ||
$this->_ppID
) {
760 $attributes['total_amount'] = array_merge($attributes['total_amount'], [
762 'style' => "background-color:#EBECE4",
765 '1' => ts('Adjust Pledge Payment Schedule?'),
766 '2' => ts('Adjust Total Pledge Amount?'),
768 $this->addRadio('option_type',
774 $currencyFreeze = TRUE;
778 $totalAmount = $this->addMoney('total_amount',
781 $attributes['total_amount'],
782 TRUE, 'currency', NULL, $currencyFreeze
786 $this->add('text', 'source', ts('Source'), CRM_Utils_Array
::value('source', $attributes));
788 // CRM-7362 --add campaigns.
789 CRM_Campaign_BAO_Campaign
::addCampaign($this, CRM_Utils_Array
::value('campaign_id', $this->_values
));
791 if (empty($this->_payNow
)) {
792 CRM_Contribute_Form_SoftCredit
::buildQuickForm($this);
797 $js = ['onclick' => "return verify( );"];
800 $mailingInfo = Civi
::settings()->get('mailing_backend');
801 $this->assign('outBound_option', $mailingInfo['outBound_option']);
806 'name' => ts('Save'),
812 'name' => ts('Save and New'),
818 'name' => ts('Cancel'),
822 // if contribution is related to membership or participant freeze Financial Type, Amount
824 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
825 $isCancelledStatus = ($this->_values
['contribution_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Cancelled'));
827 if (!empty($componentDetails['membership']) ||
828 !empty($componentDetails['participant']) ||
829 // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
830 // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
834 $totalAmount->freeze();
835 $this->getElement('currency')->freeze();
837 if ($isCancelledStatus) {
838 $paymentInstrument->freeze();
841 $financialType->freeze();
842 $this->assign('freezeFinancialType', TRUE);
846 if ($this->_action
& CRM_Core_Action
::VIEW
) {
854 * @param array $fields
855 * The input form values.
856 * @param array $files
857 * The uploaded files if any.
861 * true if no errors, else array of errors
863 public static function formRule($fields, $files, $self) {
865 // Check for Credit Card Contribution.
867 if (empty($fields['payment_processor_id'])) {
868 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
871 // validate payment instrument (e.g. credit card number)
872 CRM_Core_Payment_Form
::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, NULL);
876 // Do the amount validations.
877 if (empty($fields['total_amount']) && empty($self->_lineItems
)) {
878 if ($priceSetId = CRM_Utils_Array
::value('price_set_id', $fields)) {
879 CRM_Price_BAO_PriceField
::priceSetValidation($priceSetId, $fields, $errors);
883 $softErrors = CRM_Contribute_Form_SoftCredit
::formRule($fields, $errors, $self);
885 //CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
886 CRM_Contribute_BAO_ContributionRecur
::validateRecurContribution($fields, $files, $self, $errors);
888 // Form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
889 if (($self->_action
& CRM_Core_Action
::UPDATE
)
891 && $self->_values
['contribution_status_id'] != $fields['contribution_status_id']
893 CRM_Contribute_BAO_Contribution
::checkStatusValidation($self->_values
, $fields, $errors);
895 // CRM-16015, add form-rule to restrict change of financial type if using price field of different financial type
896 if (($self->_action
& CRM_Core_Action
::UPDATE
)
898 && $self->_values
['financial_type_id'] != $fields['financial_type_id']
900 CRM_Contribute_BAO_Contribution
::checkFinancialTypeChange(NULL, $self->_id
, $errors);
902 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
903 if (!empty($fields['fee_amount']) && !empty($fields['financial_type_id']) && $financialType = CRM_Contribute_BAO_Contribution
::validateFinancialType($fields['financial_type_id'])) {
904 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
907 // $trxn_id must be unique CRM-13919
908 if (!empty($fields['trxn_id'])) {
909 $queryParams = [1 => [$fields['trxn_id'], 'String']];
910 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
912 $queryParams[2] = [(int) $self->_id
, 'Integer'];
913 $query .= ' and id !=%2';
915 $tCnt = CRM_Core_DAO
::singleValueQuery($query, $queryParams);
917 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', [1 => $fields['trxn_id']]);
921 $order = new CRM_Financial_BAO_Order();
922 $order->setPriceSelectionFromUnfilteredInput($fields);
923 if (isset($fields['total_amount'])) {
924 $order->setOverrideTotalAmount((float) CRM_Utils_Rule
::cleanMoney($fields['total_amount']));
926 $lineItems = $order->getLineItems();
928 CRM_Financial_BAO_FinancialAccount
::checkFinancialTypeHasDeferred($fields, $self->_id
, $lineItems);
930 catch (CRM_Core_Exception
$e) {
931 $errors['financial_type_id'] = ' ';
932 $errors['_qf_default'] = $e->getMessage();
934 $errors = array_merge($errors, $softErrors);
939 * Process the form submission.
941 public function postProcess() {
942 if ($this->_action
& CRM_Core_Action
::DELETE
) {
943 CRM_Contribute_BAO_Contribution
::deleteContribution($this->_id
);
944 CRM_Core_Session
::singleton()->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
945 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
949 // Get the submitted form values.
950 $submittedValues = $this->controller
->exportValues($this->_name
);
953 $contribution = $this->submit($submittedValues, $this->_action
, $this->_ppID
);
955 catch (PaymentProcessorException
$e) {
956 // Set the contribution mode.
957 $urlParams = "action=add&cid={$this->_contactID}";
959 $urlParams .= "&mode={$this->_mode}";
961 if (!empty($this->_ppID
)) {
962 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
965 CRM_Core_Error
::statusBounce($e->getMessage(), $urlParams, ts('Payment Processor Error'));
967 $this->setUserContext();
969 //store contribution ID if not yet set (on create)
970 if (empty($this->_id
) && !empty($contribution->id
)) {
971 $this->_id
= $contribution->id
;
973 if (!empty($this->_id
) && CRM_Core_Permission
::access('CiviMember')) {
974 $membershipPaymentCount = civicrm_api3('MembershipPayment', 'getCount', ['contribution_id' => $this->_id
]);
975 if ($membershipPaymentCount) {
976 $this->ajaxResponse
['updateTabs']['#tab_member'] = CRM_Contact_BAO_Contact
::getCountComponent('membership', $this->_contactID
);
979 if (!empty($this->_id
) && CRM_Core_Permission
::access('CiviEvent')) {
980 $participantPaymentCount = civicrm_api3('ParticipantPayment', 'getCount', ['contribution_id' => $this->_id
]);
981 if ($participantPaymentCount) {
982 $this->ajaxResponse
['updateTabs']['#tab_participant'] = CRM_Contact_BAO_Contact
::getCountComponent('participant', $this->_contactID
);
988 * Process credit card payment.
990 * @param array $submittedValues
991 * @param array $lineItem
993 * @param int $contactID
996 * @return bool|\CRM_Contribute_DAO_Contribution
998 * @throws \CRM_Core_Exception
999 * @throws \Civi\Payment\Exception\PaymentProcessorException
1000 * @throws \CiviCRM_API3_Exception
1002 protected function processCreditCard($submittedValues, $lineItem, $contactID) {
1003 $isTest = ($this->_mode
== 'test') ?
1 : 0;
1004 // CRM-12680 set $_lineItem if its not set
1005 // @todo - I don't believe this would ever BE set. I can't find anywhere in the code.
1006 // It would be better to pass line item out to functions than $this->_lineItem as
1007 // we don't know what is being changed where.
1008 if (empty($this->_lineItem
) && !empty($lineItem)) {
1009 $this->_lineItem
= $lineItem;
1012 $this->_paymentObject
= Civi\Payment\System
::singleton()->getById($submittedValues['payment_processor_id']);
1013 $this->_paymentProcessor
= $this->_paymentObject
->getPaymentProcessor();
1015 // Set source if not set
1016 if (empty($submittedValues['source'])) {
1017 $userID = CRM_Core_Session
::singleton()->get('userID');
1018 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1021 $submittedValues['source'] = ts('Submit Credit Card Payment by: %1', [1 => $userSortName]);
1024 $params = $submittedValues;
1025 $this->_params
= array_merge($this->_params
, $submittedValues);
1027 // Mapping requiring documentation.
1028 $this->_params
['payment_processor'] = $submittedValues['payment_processor_id'];
1030 $now = date('YmdHis');
1032 $this->_contributorEmail
= $this->userEmail
;
1033 $this->_contributorContactID
= $contactID;
1034 $this->processBillingAddress();
1035 if (!empty($params['source'])) {
1036 unset($params['source']);
1039 $this->_params
['amount'] = $this->_params
['total_amount'];
1040 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
1041 // function to get correct amount level consistently. Remove setting of the amount level in
1042 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
1043 // to cover all variants.
1044 $this->_params
['amount_level'] = 0;
1045 $this->_params
['description'] = ts("Contribution submitted by a staff person using contributor's credit card");
1046 $this->_params
['currencyID'] = CRM_Utils_Array
::value('currency',
1048 CRM_Core_Config
::singleton()->defaultCurrency
1051 $this->_params
['pcp_display_in_roll'] = $params['pcp_display_in_roll'] ??
NULL;
1052 $this->_params
['pcp_roll_nickname'] = $params['pcp_roll_nickname'] ??
NULL;
1053 $this->_params
['pcp_personal_note'] = $params['pcp_personal_note'] ??
NULL;
1055 //Add common data to formatted params
1056 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
1058 if (empty($this->_params
['invoice_id'])) {
1059 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
1062 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
1065 // At this point we've created a contact and stored its address etc
1066 // all the payment processors expect the name and address to be in the
1067 // so we copy stuff over to first_name etc.
1068 $paymentParams = $this->_params
;
1069 $paymentParams['contactID'] = $contactID;
1070 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
1072 $financialType = new CRM_Financial_DAO_FinancialType();
1073 $financialType->id
= $params['financial_type_id'];
1074 $financialType->find(TRUE);
1076 // Add some financial type details to the params list
1077 // if folks need to use it.
1078 $paymentParams['contributionType_name'] = $this->_params
['contributionType_name'] = $financialType->name
;
1079 $paymentParams['contributionPageID'] = NULL;
1081 if (!empty($this->_params
['is_email_receipt'])) {
1082 $paymentParams['email'] = $this->userEmail
;
1083 $paymentParams['is_email_receipt'] = 1;
1086 $paymentParams['is_email_receipt'] = 0;
1087 $this->_params
['is_email_receipt'] = 0;
1089 if (!empty($this->_params
['receive_date'])) {
1090 $paymentParams['receive_date'] = $this->_params
['receive_date'];
1093 if (!empty($this->_params
['is_email_receipt'])) {
1094 $this->_params
['receipt_date'] = $now;
1097 $this->set('params', $this->_params
);
1098 // It actually makes no sense that we would set receive_date in params
1099 // for credit card payments....
1100 $this->assign('receive_date', $this->_params
['receive_date'] ??
date('Y-m-d H:i:s'));
1102 // Result has all the stuff we need
1103 // lets archive it to a financial transaction
1104 if ($financialType->is_deductible
) {
1105 $this->assign('is_deductible', TRUE);
1106 $this->set('is_deductible', TRUE);
1108 $contributionParams = [
1109 'id' => $this->_params
['contribution_id'] ??
NULL,
1110 'contact_id' => $contactID,
1111 'line_item' => $lineItem,
1112 'is_test' => $isTest,
1113 'campaign_id' => $this->_params
['campaign_id'] ??
NULL,
1114 'contribution_page_id' => $this->_params
['contribution_page_id'] ??
NULL,
1115 'source' => CRM_Utils_Array
::value('source', $paymentParams, CRM_Utils_Array
::value('description', $paymentParams)),
1116 'thankyou_date' => $this->_params
['thankyou_date'] ??
NULL,
1118 $contributionParams['payment_instrument_id'] = $this->_paymentProcessor
['payment_instrument_id'];
1120 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processFormContribution($this,
1123 $contributionParams,
1127 CRM_Utils_Array
::value('is_recur', $this->_params
)
1130 $paymentParams['contributionID'] = $contribution->id
;
1131 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
1132 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1134 if ($paymentParams['amount'] > 0.0) {
1135 // force a re-get of the payment processor in case the form changed it, CRM-7179
1136 // NOTE - I expect this is obsolete.
1137 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
1139 $completeStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
1140 $result = $payment->doPayment($paymentParams, 'contribute');
1141 $this->assign('trxn_id', $result['trxn_id']);
1142 $contribution->trxn_id
= $result['trxn_id'];
1143 /* Our scenarios here are
1144 * 1) the payment failed & an Exception should have been thrown
1145 * 2) the payment succeeded but the payment is not immediate (for example a recurring payment
1146 * with a delayed start)
1147 * 3) the payment succeeded with an immediate payment.
1149 * The doPayment function ensures that payment_status_id is always set
1150 * as historically we have had to guess from the context - ie doDirectPayment
1151 * = error or success, unless it is a recurring contribution in which case it is pending.
1153 if ($result['payment_status_id'] == $completeStatusId) {
1155 civicrm_api3('contribution', 'completetransaction', [
1156 'id' => $contribution->id
,
1157 'trxn_id' => $result['trxn_id'],
1158 'payment_processor_id' => $this->_paymentProcessor
['id'],
1159 'is_transactional' => FALSE,
1160 'fee_amount' => $result['fee_amount'] ??
NULL,
1161 'card_type_id' => $paymentParams['card_type_id'] ??
NULL,
1162 'pan_truncation' => $paymentParams['pan_truncation'] ??
NULL,
1163 'is_email_receipt' => FALSE,
1165 // This has now been set to 1 in the DB - declare it here also
1166 $contribution->contribution_status_id
= 1;
1168 catch (CiviCRM_API3_Exception
$e) {
1169 if ($e->getErrorCode() != 'contribution_completed') {
1170 \Civi
::log()->error('CRM_Contribute_Form_Contribution::processCreditCard CiviCRM_API3_Exception: ' . $e->getMessage());
1171 throw new CRM_Core_Exception('Failed to update contribution in database');
1176 // Save the trxn_id.
1177 $contribution->save();
1180 catch (PaymentProcessorException
$e) {
1181 CRM_Contribute_BAO_Contribution
::failPayment($contribution->id
, $paymentParams['contactID'], $e->getMessage());
1182 throw new PaymentProcessorException($e->getMessage());
1185 // Send receipt mail.
1186 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1187 if ($contribution->id
&& !empty($this->_params
['is_email_receipt'])) {
1188 $this->_params
['trxn_id'] = $result['trxn_id'] ??
NULL;
1189 $this->_params
['contact_id'] = $contactID;
1190 $this->_params
['contribution_id'] = $contribution->id
;
1191 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $this->_params
, TRUE)) {
1192 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1196 return $contribution;
1200 * Generate the data to construct a snippet based pane.
1202 * This form also assigns the showAdditionalInfo var based on historical code.
1203 * This appears to mean 'there is a pane to show'.
1205 * @param string $type
1206 * Type of Pane - this is generally used to determine the function name used to build it
1207 * - e.g CreditCard, AdditionalDetail
1208 * @param array $defaults
1211 * We aim to further refactor & simplify this but currently
1213 * - should additional info be shown?
1215 protected function generatePane($type, $defaults) {
1216 $urlParams = "snippet=4&formType={$type}";
1218 $urlParams .= "&mode={$this->_mode}";
1222 if ($type == 'CreditCard' ||
1223 $type == 'DirectDebit'
1229 'url' => CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams),
1234 // See if we need to include this paneName in the current form.
1235 if ($this->_formType
== $type ||
!empty($_POST["hidden_{$type}"]) ||
1236 !empty($defaults["hidden_{$type}"])
1238 $this->assign('showAdditionalInfo', TRUE);
1239 $pane['open'] = 'true';
1242 if ($type == 'CreditCard' ||
$type == 'DirectDebit') {
1243 // @todo would be good to align tpl name with form name...
1244 // @todo document why this hidden variable is required.
1245 $this->add('hidden', 'hidden_' . $type, 1);
1249 $additionalInfoFormFunction = 'build' . $type;
1250 CRM_Contribute_Form_AdditionalInfo
::$additionalInfoFormFunction($this);
1256 * Wrapper for unit testing the post process submit function.
1258 * (If we expose through api we can get default additions 'for free').
1260 * @param array $params
1261 * @param int $action
1262 * @param string|null $creditCardMode
1264 * @return CRM_Contribute_BAO_Contribution
1266 * @throws \CRM_Core_Exception
1267 * @throws \CiviCRM_API3_Exception
1268 * @throws \Civi\Payment\Exception\PaymentProcessorException
1270 public function testSubmit($params, $action, $creditCardMode = NULL) {
1272 'soft_credit_contact_id' => [],
1273 'receive_date' => date('Y-m-d H:i:s'),
1274 'receipt_date' => '',
1275 'cancel_date' => '',
1276 'hidden_Premium' => 1,
1279 if (!empty($params['id'])) {
1280 $existingContribution = civicrm_api3('contribution', 'getsingle', [
1281 'id' => $params['id'],
1283 $this->_id
= $params['id'];
1284 $this->_values
= $existingContribution;
1285 if (CRM_Invoicing_Utils
::isInvoicingEnabled()) {
1286 $this->_values
['tax_amount'] = civicrm_api3('contribution', 'getvalue', [
1287 'id' => $params['id'],
1288 'return' => 'tax_amount',
1293 $existingContribution = [];
1296 $this->_defaults
['contribution_status_id'] = CRM_Utils_Array
::value('contribution_status_id',
1297 $existingContribution
1300 $this->_defaults
['total_amount'] = CRM_Utils_Array
::value('total_amount',
1301 $existingContribution
1304 if ($creditCardMode) {
1305 $this->_mode
= $creditCardMode;
1308 // Required because processCreditCard calls set method on this.
1309 $_SERVER['REQUEST_METHOD'] = 'GET';
1310 $this->controller
= new CRM_Core_Controller();
1312 CRM_Contribute_Form_AdditionalInfo
::buildPremium($this);
1314 $this->_fields
= [];
1315 return $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array
::value('pledge_payment_id', $params));
1320 * @param array $submittedValues
1322 * @param int $action
1324 * - CRM_Core_Action::UPDATE
1326 * @param $pledgePaymentID
1328 * @return \CRM_Contribute_BAO_Contribution
1330 * @throws \CRM_Core_Exception
1331 * @throws \CiviCRM_API3_Exception
1332 * @throws \Civi\Payment\Exception\PaymentProcessorException
1334 protected function submit($submittedValues, $action, $pledgePaymentID) {
1335 $pId = $contribution = $isRelatedId = FALSE;
1336 $this->_params
= $submittedValues;
1337 $this->beginPostProcess();
1338 // reassign submitted form values if the any information is formatted via beginPostProcess
1339 $submittedValues = $this->_params
;
1341 if (!empty($submittedValues['price_set_id']) && $action & CRM_Core_Action
::UPDATE
) {
1342 $line = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution');
1343 $lineID = key($line);
1344 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array
::value('price_field_id', $line[$lineID]), 'price_set_id');
1345 $quickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1346 // Why do we do this? Seems like a like a wrapper for old functionality - but single line price sets & quick
1347 // config should be treated the same.
1349 CRM_Price_BAO_LineItem
::deleteLineItems($this->_id
, 'civicrm_contribution');
1353 // Process price set and get total amount and line items.
1355 $priceSetId = $submittedValues['price_set_id'] ??
NULL;
1356 if (empty($priceSetId) && !$this->_id
) {
1357 $this->_priceSetId
= $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1358 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
1359 $fieldID = key($this->_priceSet
['fields']);
1360 $fieldValueId = key($this->_priceSet
['fields'][$fieldID]['options']);
1361 $this->_priceSet
['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1362 $submittedValues['price_' . $fieldID] = 1;
1365 // Every contribution has a price-set - the only reason it shouldn't be set is if we are dealing with
1366 // quick config (very very arguably) & yet we see that this could still be quick config so this should be understood
1367 // as a point of fragility rather than a logical 'if' clause.
1369 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
1370 $submittedValues, $lineItem[$priceSetId], $priceSetId);
1371 // Unset tax amount for offline 'is_quick_config' contribution.
1372 // @todo WHY - quick config was conceived as a quick way to configure contribution forms.
1373 // this is an example of 'other' functionality being hung off it.
1374 if ($this->_priceSet
['is_quick_config'] &&
1375 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant
::getTaxRates())
1377 unset($submittedValues['tax_amount']);
1379 $submittedValues['total_amount'] = $submittedValues['amount'] ??
NULL;
1383 if ($this->_compId
) {
1384 if ($this->_context
== 'participant') {
1385 $pId = $this->_compId
;
1387 elseif ($this->_context
== 'membership') {
1388 $isRelatedId = TRUE;
1391 $pId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id
, 'participant_id', 'contribution_id');
1395 $contributionDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1396 if (array_key_exists('membership', $contributionDetails)) {
1397 $isRelatedId = TRUE;
1399 elseif (array_key_exists('participant', $contributionDetails)) {
1400 $pId = $contributionDetails['participant'];
1403 if (!empty($this->_payNow
)) {
1404 $this->_params
['contribution_id'] = $this->_id
;
1408 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id
) {
1409 // CRM-10117 update the line items for participants.
1410 // @todo - if we are completing a contribution then the api call
1411 // civicrm_api3('Contribution', 'completetransaction') should take care of
1412 // all associated updates rather than replicating them on the form layer.
1414 $entityTable = 'participant';
1416 $isRelatedId = FALSE;
1417 $participantParams = [
1418 'fee_amount' => $submittedValues['total_amount'],
1421 CRM_Event_BAO_Participant
::add($participantParams);
1422 if (empty($this->_lineItems
)) {
1423 $this->_lineItems
[] = CRM_Price_BAO_LineItem
::getLineItems($entityID, 'participant', TRUE);
1427 $entityTable = 'contribution';
1428 $entityID = $this->_id
;
1431 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, $entityTable, FALSE, TRUE, $isRelatedId);
1432 foreach (array_keys($lineItems) as $id) {
1433 $lineItems[$id]['id'] = $id;
1435 $itemId = key($lineItems);
1436 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1437 $this->_priceSetId
= CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1440 // @todo see above - new functionality has been inappropriately added to the quick config concept
1441 // and new functionality has been added onto the form layer rather than the BAO :-(
1442 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1443 //CRM-16833: Ensure tax is applied only once for membership conribution, when status changed.(e.g Pending to Completed).
1444 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1445 if (empty($componentDetails['membership']) && empty($componentDetails['participant'])) {
1446 if (!($this->_action
& CRM_Core_Action
::UPDATE
&& (($this->_defaults
['contribution_status_id'] != $submittedValues['contribution_status_id'])))) {
1447 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule
::cleanMoney(CRM_Utils_Array
::value('total_amount', $submittedValues));
1451 // Update line total and total amount with tax on edit.
1452 $financialItemsId = CRM_Core_PseudoConstant
::getTaxRates();
1453 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1454 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1457 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1458 $submittedValues['tax_amount'] = 0;
1460 if ($lineItems[$itemId]['tax_rate']) {
1461 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total'];
1462 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] +
$lineItems[$itemId]['tax_amount'];
1463 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1466 // CRM-10117 update the line items for participants.
1467 if (!empty($lineItems[$itemId]['price_field_id'])) {
1468 $lineItem[$this->_priceSetId
] = $lineItems;
1473 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1476 //CRM-11529 for quick config back office transactions
1477 //when financial_type_id is passed in form, update the
1478 //line items with the financial type selected in form
1479 // NOTE that this IS still a legitimate use of 'quick-config' for contributions under the current DB but
1480 // we should look at having a price field per contribution type & then there would be little reason
1481 // for the back-office contribution form postProcess to know if it is a quick-config form.
1482 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && !empty($lineItem[$this->_priceSetId
])
1484 foreach ($lineItem[$this->_priceSetId
] as &$values) {
1485 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1489 if (!isset($submittedValues['total_amount'])) {
1490 $submittedValues['total_amount'] = $this->_values
['total_amount'] ??
NULL;
1491 // Avoid tax amount deduction on edit form and keep it original, because this will lead to error described in CRM-20676
1493 $submittedValues['total_amount'] -= CRM_Utils_Array
::value('tax_amount', $this->_values
, 0);
1496 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
1498 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id'] ??
[]));
1499 if ($this->_id
&& count($isEmpty) == 1 && key($isEmpty) == NULL) {
1500 civicrm_api3('ContributionSoft', 'get', ['contribution_id' => $this->_id
, 'pcp_id' => ['IS NULL' => 1], 'api.ContributionSoft.delete' => 1]);
1503 // set the contact, when contact is selected
1504 if (!empty($submittedValues['contact_id'])) {
1505 $this->_contactID
= $submittedValues['contact_id'];
1508 $formValues = $submittedValues;
1510 // Credit Card Contribution.
1512 $paramsSetByPaymentProcessingSubsystem = [
1514 'payment_instrument_id',
1515 'contribution_status_id',
1519 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1520 if (isset($formValues[$key])) {
1521 unset($formValues[$key]);
1524 $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID
);
1525 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1526 $formValues[$key] = $contribution->$key;
1530 // Offline Contribution.
1531 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1533 // get the required field value only.
1536 'contact_id' => $this->_contactID
,
1537 'currency' => $this->getCurrency($submittedValues),
1538 'skipCleanMoney' => TRUE,
1542 //format soft-credit/pcp param first
1543 CRM_Contribute_BAO_ContributionSoft
::formatSoftCreditParams($submittedValues, $this);
1544 $params = array_merge($params, $submittedValues);
1547 'financial_type_id',
1548 'contribution_status_id',
1549 'payment_instrument_id',
1556 foreach ($fields as $f) {
1557 $params[$f] = $formValues[$f] ??
NULL;
1560 $params['revenue_recognition_date'] = NULL;
1561 if (!empty($formValues['revenue_recognition_date'])) {
1562 $params['revenue_recognition_date'] = $formValues['revenue_recognition_date'];
1565 if (!empty($formValues['is_email_receipt'])) {
1566 $params['receipt_date'] = date("Y-m-d");
1569 if (CRM_Contribute_BAO_Contribution
::isContributionStatusNegative($params['contribution_status_id'])
1571 if (CRM_Utils_System
::isNull(CRM_Utils_Array
::value('cancel_date', $params))) {
1572 $params['cancel_date'] = date('YmdHis');
1576 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1579 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1580 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1581 if ($params['contribution_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending')) {
1582 $params['is_pay_later'] = 1;
1584 elseif ($params['contribution_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed')) {
1585 // @todo - if the contribution is new then it should be Pending status & then we use
1586 // Payment.create to update to Completed.
1587 $params['is_pay_later'] = 0;
1590 // Add Additional common information to formatted params.
1591 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($formValues, $params, $this);
1593 $params['contribution_mode'] = 'participant';
1594 $params['participant_id'] = $pId;
1595 $params['skipLineItem'] = 1;
1597 $params['line_item'] = $lineItem;
1598 $params['payment_processor_id'] = $params['payment_processor'] = $this->_paymentProcessor
['id'] ??
NULL;
1599 $params['tax_amount'] = CRM_Utils_Array
::value('tax_amount', $submittedValues, CRM_Utils_Array
::value('tax_amount', $this->_values
));
1600 //create contribution.
1601 if ($isQuickConfig) {
1602 $params['is_quick_config'] = 1;
1604 $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
1606 // we are already handling note below, so to avoid duplicate notes against $contribution
1607 if (!empty($params['note']) && !empty($submittedValues['note'])) {
1608 unset($params['note']);
1610 $contribution = CRM_Contribute_BAO_Contribution
::create($params);
1612 // process associated membership / participant, CRM-4395
1613 if ($contribution->id
&& $action & CRM_Core_Action
::UPDATE
) {
1614 // @todo use Payment.create to do this, remove transitioncomponents function
1615 // if contribution is being created with a completed status it should be
1616 // created pending & then Payment.create adds the payment
1617 CRM_Contribute_BAO_Contribution
::transitionComponents([
1618 'contribution_id' => $contribution->id
,
1619 'contribution_status_id' => $contribution->contribution_status_id
,
1620 'previous_contribution_status_id' => $this->_values
['contribution_status_id'] ??
NULL,
1621 'receive_date' => $contribution->receive_date
,
1625 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1627 $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
1629 //send receipt mail.
1630 if ($contribution->id
&& !empty($formValues['is_email_receipt'])) {
1631 $formValues['contact_id'] = $this->_contactID
;
1632 $formValues['contribution_id'] = $contribution->id
;
1634 $formValues +
= CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
);
1636 // to get 'from email id' for send receipt
1637 $this->fromEmailId
= $formValues['from_email_address'] ??
NULL;
1638 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $formValues)) {
1639 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1643 $this->statusMessageTitle
= ts('Saved');
1647 if ($contribution->id
&& isset($formValues['product_name'][0])) {
1648 CRM_Contribute_Form_AdditionalInfo
::processPremium($submittedValues, $contribution->id
,
1649 $this->_premiumID
, $this->_options
1653 if ($contribution->id
&& array_key_exists('note', $submittedValues)) {
1654 CRM_Contribute_Form_AdditionalInfo
::processNote($submittedValues, $this->_contactID
, $contribution->id
, $this->_noteID
);
1657 CRM_Core_Session
::setStatus(implode(' ', $this->statusMessage
), $this->statusMessageTitle
, 'success');
1659 CRM_Contribute_BAO_Contribution
::updateRelatedPledge(
1663 ($formValues['option_type'] ??
0) == 2,
1664 $formValues['total_amount'],
1665 CRM_Utils_Array
::value('total_amount', $this->_defaults
),
1666 $formValues['contribution_status_id'],
1667 CRM_Utils_Array
::value('contribution_status_id', $this->_defaults
)
1669 return $contribution;
1673 * Assign tax calculations to contribution receipts.
1675 * @param array $submittedValues
1676 * @param int $action
1677 * @param array $lineItem
1679 protected function invoicingPostProcessHook($submittedValues, $action, $lineItem) {
1680 if (!Civi
::settings()->get('invoicing')) {
1684 $getTaxDetails = FALSE;
1686 foreach ($lineItem as $key => $value) {
1687 foreach ($value as $v) {
1688 if (isset($taxRate[(string) CRM_Utils_Array
::value('tax_rate', $v)])) {
1689 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $v);
1692 if (isset($v['tax_rate'])) {
1693 $taxRate[(string) $v['tax_rate']] = $v['tax_amount'] ??
NULL;
1694 $getTaxDetails = TRUE;
1700 if ($action & CRM_Core_Action
::UPDATE
) {
1701 if (isset($submittedValues['tax_amount'])) {
1702 $totalTaxAmount = $submittedValues['tax_amount'];
1705 $totalTaxAmount = $this->_values
['tax_amount'];
1707 $this->assign('totalTaxAmount', $totalTaxAmount);
1708 $this->assign('dataArray', $taxRate);
1711 if (!empty($submittedValues['price_set_id'])) {
1712 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1713 $this->assign('getTaxDetails', $getTaxDetails);
1714 $this->assign('dataArray', $taxRate);
1715 $this->assign('taxTerm', Civi
::settings()->get('tax_term'));
1718 $this->assign('totalTaxAmount', CRM_Utils_Array
::value('tax_amount', $submittedValues));
1724 * Calculate non deductible amount.
1726 * @see https://issues.civicrm.org/jira/browse/CRM-11956
1727 * if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1728 * if non_deductible_amount does NOT exist - then calculate it depending on:
1729 * $financialType->is_deductible and whether there is a product (premium).
1732 * @param $formValues
1736 protected function calculateNonDeductibleAmount($params, $formValues) {
1737 if (!empty($params['non_deductible_amount'])) {
1738 return $params['non_deductible_amount'];
1741 $priceSetId = $params['price_set_id'] ??
NULL;
1742 // return non-deductible amount if it is set at the price field option level
1743 if ($priceSetId && !empty($params['line_item'])) {
1744 $nonDeductibleAmount = CRM_Price_BAO_PriceSet
::getNonDeductibleAmountFromPriceSet($priceSetId, $params['line_item']);
1745 if (!empty($nonDeductibleAmount)) {
1746 return $nonDeductibleAmount;
1750 $financialType = new CRM_Financial_DAO_FinancialType();
1751 $financialType->id
= $params['financial_type_id'];
1752 $financialType->find(TRUE);
1754 if ($financialType->is_deductible
) {
1756 if (isset($formValues['product_name'][0])) {
1757 $selectProduct = $formValues['product_name'][0];
1759 // if there is a product - compare the value to the contribution amount
1760 if (isset($selectProduct)) {
1761 $productDAO = new CRM_Contribute_DAO_Product();
1762 $productDAO->id
= $selectProduct;
1763 $productDAO->find(TRUE);
1764 // product value exceeds contribution amount
1765 if ($params['total_amount'] < $productDAO->price
) {
1766 return $params['total_amount'];
1768 // product value does NOT exceed contribution amount
1770 return $productDAO->price
;
1773 // contribution is deductible - but there is no product
1778 // contribution is NOT deductible
1780 return $params['total_amount'];
1787 * Get the financial Type ID for the contribution either from the submitted values or from the contribution values if possible.
1789 * This is important for dev/core#1728 - ie ensure that if we are returned to the form for a form
1790 * error that any custom fields based on the selected financial type are loaded.
1794 protected function getFinancialTypeID() {
1795 if (!empty($this->_submitValues
['financial_type_id'])) {
1796 return $this->_submitValues
['financial_type_id'];
1798 if (!empty($this->_values
['financial_type_id'])) {
1799 return $this->_values
['financial_type_id'];
1804 * Set context in session
1806 public function setUserContext(): void
{
1807 $session = CRM_Core_Session
::singleton();
1808 $buttonName = $this->controller
->getButtonName();
1809 if ($this->_context
== 'standalone') {
1810 if ($buttonName == $this->getButtonName('upload', 'new')) {
1811 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contribute/add',
1812 'reset=1&action=add&context=standalone'
1816 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
1817 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1821 elseif ($this->_context
== 'contribution' && $this->_mode
&& $buttonName == $this->getButtonName('upload', 'new')) {
1822 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
1823 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
1826 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1827 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
1828 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
1834 * Get the contribution ID.
1838 protected function getContributionID(): ?
int {
1843 * Get the selected contribution status.
1845 * @return string|null
1847 * @throws \API_Exception
1849 protected function getPreviousContributionStatus(): ?
string {
1850 if (!$this->getContributionID()) {
1853 if (!$this->previousContributionStatus
) {
1854 $this->previousContributionStatus
= Contribution
::get(FALSE)
1855 ->addWhere('id', '=', $this->getContributionID())
1856 ->addSelect('contribution_status_id:name')
1858 ->first()['contribution_status_id:name'];
1860 return $this->previousContributionStatus
;