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\Payment\Exception\PaymentProcessorException
;
15 * This class generates form components for processing a contribution.
17 class CRM_Contribute_Form_Contribution
extends CRM_Contribute_Form_AbstractEditPayment
{
19 * The id of the contribution that we are processing.
26 * The id of the premium that we are processing.
30 public $_premiumID = NULL;
33 * @var CRM_Contribute_DAO_ContributionProduct
35 public $_productDAO = NULL;
45 * The id of the contact associated with this contribution.
52 * The id of the pledge payment that we are processing.
59 * Is this contribution associated with an online.
60 * financial transaction
64 public $_online = FALSE;
67 * Stores all product options.
74 * Storage of parameters from form
81 * Store the contribution Type ID
85 public $_contributionType;
88 * The contribution values if an existing contribution
94 * The pledge values if this contribution is associated with pledge
97 public $_pledgeValues;
99 public $_contributeMode = 'direct';
104 * Parameter with confusing name.
108 public $_compContext;
113 * Possible From email addresses
126 * Store the line items if price set used.
134 * @todo explain why we use lineItem & lineItems
143 public $_softCreditInfo;
145 protected $_formType;
148 * Array of the payment fields to be displayed in the payment fieldset (pane) in billingBlock.tpl
149 * this contains all the information to describe these fields from quickform. See CRM_Core_Form_Payment getPaymentFormFieldsMetadata
153 public $_paymentFields = [];
155 * Logged in user's email.
168 * Price set as an array
178 public $userDisplayName;
181 * Status message to be shown to the user.
185 protected $statusMessage = [];
188 * Status message title to be shown to the user.
190 * Generally the payment processor message title is 'Complete' and offline is 'Saved'
191 * although this might not be a good fit with the broad range of processors.
195 protected $statusMessageTitle;
200 * Max row count for soft credits. The value here is +1 the actual number of
203 public $_softCreditItemCount = 11;
206 * Explicitly declare the form context.
208 public function getDefaultContext() {
213 * Set variables up before form is built.
215 * @throws \CRM_Core_Exception
216 * @throws \CiviCRM_API3_Exception
218 public function preProcess() {
219 // Check permission for action.
220 if (!CRM_Core_Permission
::checkActionPermission('CiviContribute', $this->_action
)) {
221 CRM_Core_Error
::statusBounce(ts('You do not have permission to access this page.'));
224 parent
::preProcess();
226 $this->_formType
= $_GET['formType'] ??
NULL;
229 $this->_priceSetId
= $_GET['priceSetId'] ??
NULL;
230 $this->set('priceSetId', $this->_priceSetId
);
231 $this->assign('priceSetId', $this->_priceSetId
);
233 // Get the pledge payment id
234 $this->_ppID
= CRM_Utils_Request
::retrieve('ppid', 'Positive', $this);
236 $this->assign('action', $this->_action
);
238 // Get the contribution id if update
239 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive');
240 if (!empty($this->_id
)) {
241 $this->assignPaymentInfoBlock();
242 $this->assign('contribID', $this->_id
);
243 $this->assign('isUsePaymentBlock', TRUE);
246 $this->_context
= CRM_Utils_Request
::retrieve('context', 'Alphanumeric', $this);
247 $this->assign('context', $this->_context
);
249 $this->_compId
= CRM_Utils_Request
::retrieve('compId', 'Positive', $this);
251 $this->_compContext
= CRM_Utils_Request
::retrieve('compContext', 'String', $this);
253 //set the contribution mode.
254 $this->_mode
= CRM_Utils_Request
::retrieve('mode', 'Alphanumeric', $this);
256 $this->assign('contributionMode', $this->_mode
);
257 if ($this->_action
& CRM_Core_Action
::DELETE
) {
261 $this->_fromEmails
= CRM_Core_BAO_Email
::getFromEmail();
263 if (in_array('CiviPledge', CRM_Core_Config
::singleton()->enableComponents
) && !$this->_formType
) {
264 $this->preProcessPledge();
268 $this->showRecordLinkMesssage($this->_id
);
272 // Current contribution id.
274 $this->assignPremiumProduct($this->_id
);
275 $this->buildValuesAndAssignOnline_Note_Type($this->_id
, $this->_values
);
278 // when custom data is included in this page
279 if (!empty($_POST['hidden_custom'])) {
280 $this->applyCustomData('Contribution', CRM_Utils_Array
::value('financial_type_id', $_POST), $this->_id
);
283 $this->_lineItems
= [];
285 if (!empty($this->_compId
) && $this->_compContext
=== 'participant') {
286 $this->assign('compId', $this->_compId
);
287 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_compId
);
290 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution', 1, TRUE, TRUE);
293 empty($lineItem) ?
NULL : $this->_lineItems
[] = $lineItem;
296 $this->assign('lineItem', empty($lineItem) ?
FALSE : [$lineItem]);
299 if ($this->_mode
&& $this->_id
) {
300 $this->_payNow
= TRUE;
301 $this->assign('payNow', $this->_payNow
);
302 CRM_Utils_System
::setTitle(ts('Pay with Credit Card'));
304 elseif ($this->_mode
) {
305 $this->setPageTitle($this->_ppID ?
ts('Credit Card Pledge Payment') : ts('Credit Card Contribution'));
308 $this->setPageTitle($this->_ppID ?
ts('Pledge Payment') : ts('Contribution'));
313 * Set default values.
317 * @throws \CRM_Core_Exception
319 public function setDefaultValues() {
320 $defaults = $this->_values
;
322 // Set defaults for pledge payment.
324 $defaults['total_amount'] = $this->_pledgeValues
['pledgePayment']['scheduled_amount'] ??
NULL;
325 $defaults['financial_type_id'] = $this->_pledgeValues
['financial_type_id'] ??
NULL;
326 $defaults['currency'] = $this->_pledgeValues
['currency'] ??
NULL;
327 $defaults['option_type'] = 1;
330 if ($this->_action
& CRM_Core_Action
::DELETE
) {
334 $defaults['frequency_interval'] = 1;
335 $defaults['frequency_unit'] = 'month';
337 // Set soft credit defaults.
338 CRM_Contribute_Form_SoftCredit
::setDefaultValues($defaults, $this);
341 // @todo - remove this function as the parent does it too.
342 $config = CRM_Core_Config
::singleton();
343 // Set default country from config if no country set.
344 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
345 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry
;
348 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
349 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince
;
352 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID
);
353 $defaults = array_merge($defaults, $billingDefaults);
357 $this->_contactID
= $defaults['contact_id'];
359 elseif ($this->_contactID
) {
360 $defaults['contact_id'] = $this->_contactID
;
363 // Set $newCredit variable in template to control whether link to credit card mode is included.
364 $this->assign('newCredit', CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments());
366 // Fix the display of the monetary value, CRM-4038.
367 if (isset($defaults['total_amount'])) {
368 $total_value = $defaults['total_amount'];
369 $defaults['total_amount'] = CRM_Utils_Money
::format($total_value, NULL, '%a');
370 if (!empty($defaults['tax_amount'])) {
371 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
372 if (empty($componentDetails['membership']) && empty($componentDetails['participant'])) {
373 $defaults['total_amount'] = CRM_Utils_Money
::format($total_value - $defaults['tax_amount'], NULL, '%a');
378 $amountFields = ['non_deductible_amount', 'fee_amount'];
379 foreach ($amountFields as $amt) {
380 if (isset($defaults[$amt])) {
381 $defaults[$amt] = CRM_Utils_Money
::format($defaults[$amt], NULL, '%a');
385 if ($this->_contributionType
) {
386 $defaults['financial_type_id'] = $this->_contributionType
;
389 if (empty($defaults['payment_instrument_id'])) {
390 $defaults['payment_instrument_id'] = $this->getDefaultPaymentInstrumentId();
393 if (!empty($defaults['is_test'])) {
394 $this->assign('is_test', TRUE);
397 $this->assign('showOption', TRUE);
398 // For Premium section.
399 if ($this->_premiumID
) {
400 $this->assign('showOption', FALSE);
401 $options = $this->_options
[$this->_productDAO
->product_id
] ??
"";
403 $this->assign('showOption', TRUE);
405 $options_key = CRM_Utils_Array
::key($this->_productDAO
->product_option
, $options);
407 $defaults['product_name'] = [$this->_productDAO
->product_id
, trim($options_key)];
410 $defaults['product_name'] = [$this->_productDAO
->product_id
];
412 if ($this->_productDAO
->fulfilled_date
) {
413 $defaults['fulfilled_date'] = $this->_productDAO
->fulfilled_date
;
417 if (isset($this->userEmail
)) {
418 $this->assign('email', $this->userEmail
);
421 if (!empty($defaults['is_pay_later'])) {
422 $this->assign('is_pay_later', TRUE);
424 $this->assign('contribution_status_id', CRM_Utils_Array
::value('contribution_status_id', $defaults));
425 if (!empty($defaults['contribution_status_id']) && in_array(
426 CRM_Contribute_PseudoConstant
::contributionStatus($defaults['contribution_status_id'], 'name'),
427 // Historically not 'Cancelled' hence not using CRM_Contribute_BAO_Contribution::isContributionStatusNegative.
428 ['Refunded', 'Chargeback']
430 $defaults['refund_trxn_id'] = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionTrxnID($this->_id
);
433 $defaults['refund_trxn_id'] = $defaults['trxn_id'] ??
NULL;
436 if (!$this->_id
&& empty($defaults['receive_date'])) {
437 $defaults['receive_date'] = date('Y-m-d H:i:s');
440 $currency = $defaults['currency'] ??
NULL;
441 $this->assign('currency', $currency);
442 // Hack to get currency info to the js layer. CRM-11440.
443 CRM_Utils_Money
::format(1);
444 $this->assign('currencySymbol', CRM_Utils_Array
::value($currency, CRM_Utils_Money
::$_currencySymbols));
445 $this->assign('totalAmount', CRM_Utils_Array
::value('total_amount', $defaults));
447 // Inherit campaign from pledge.
448 if ($this->_ppID
&& !empty($this->_pledgeValues
['campaign_id'])) {
449 $defaults['campaign_id'] = $this->_pledgeValues
['campaign_id'];
452 $this->_defaults
= $defaults;
457 * Build the form object.
459 * @throws \CiviCRM_API3_Exception
460 * @throws \CRM_Core_Exception
462 public function buildQuickForm() {
464 $this->add('hidden', 'id', $this->_id
);
467 if ($this->_action
& CRM_Core_Action
::DELETE
) {
471 'name' => ts('Delete'),
472 'spacing' => ' ',
477 'name' => ts('Cancel'),
483 // FIXME: This probably needs to be done in preprocess
484 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()
485 && $this->_action
& CRM_Core_Action
::UPDATE
486 && !empty($this->_values
['financial_type_id'])
488 $financialTypeID = CRM_Contribute_PseudoConstant
::financialType($this->_values
['financial_type_id']);
489 CRM_Financial_BAO_FinancialType
::checkPermissionedLineItems($this->_id
, 'edit');
490 if (!CRM_Core_Permission
::check('edit contributions of type ' . $financialTypeID)) {
491 CRM_Core_Error
::statusBounce(ts('You do not have permission to access this page.'));
496 //tax rate from financialType
497 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant
::getTaxRates()));
498 $this->assign('currencies', json_encode(CRM_Core_OptionGroup
::values('currencies_enabled')));
500 // build price set form.
501 $buildPriceSet = FALSE;
502 $invoicing = CRM_Invoicing_Utils
::isInvoicingEnabled();
503 $this->assign('invoicing', $invoicing);
505 $buildRecurBlock = FALSE;
507 // display tax amount on edit contribution page
508 if ($invoicing && $this->_action
& CRM_Core_Action
::UPDATE
&& isset($this->_values
['tax_amount'])) {
509 $this->assign('totalTaxAmount', $this->_values
['tax_amount']);
512 if (empty($this->_lineItems
) &&
513 ($this->_priceSetId ||
!empty($_POST['price_set_id']))
515 $buildPriceSet = TRUE;
516 $getOnlyPriceSetElements = TRUE;
517 if (!$this->_priceSetId
) {
518 $this->_priceSetId
= $_POST['price_set_id'];
519 $getOnlyPriceSetElements = FALSE;
522 $this->set('priceSetId', $this->_priceSetId
);
523 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
525 // get only price set form elements.
526 if ($getOnlyPriceSetElements) {
530 // use to build form during form rule.
531 $this->assign('buildPriceSet', $buildPriceSet);
533 $defaults = $this->_values
;
534 $additionalDetailFields = [
538 'non_deductible_amount',
541 foreach ($additionalDetailFields as $key) {
542 if (!empty($defaults[$key])) {
543 $defaults['hidden_AdditionalDetail'] = 1;
548 if ($this->_productDAO
) {
549 if ($this->_productDAO
->product_id
) {
550 $defaults['hidden_Premium'] = 1;
554 if ($this->_noteID
&&
555 !CRM_Utils_System
::isNull($this->_values
['note'])
557 $defaults['hidden_AdditionalDetail'] = 1;
561 if (empty($this->_payNow
)) {
562 $paneNames[ts('Additional Details')] = 'AdditionalDetail';
565 //Add Premium pane only if Premium is exists.
566 $dao = new CRM_Contribute_DAO_Product();
569 if ($dao->find(TRUE) && empty($this->_payNow
)) {
570 $paneNames[ts('Premium Information')] = 'Premium';
573 $this->payment_instrument_id
= CRM_Utils_Array
::value('payment_instrument_id', $defaults, $this->getDefaultPaymentInstrumentId());
574 if (CRM_Core_Payment_Form
::buildPaymentForm($this, $this->_paymentProcessor
, FALSE, TRUE, $this->payment_instrument_id
) == TRUE) {
575 if (!empty($this->_recurPaymentProcessors
)) {
576 $buildRecurBlock = TRUE;
578 // ppID denotes a pledge payment.
579 foreach ($this->_paymentProcessors
as $processor) {
580 if (!empty($processor['is_recur']) && !empty($processor['object']) && $processor['object']->supports('recurContributionsForPledges')) {
581 $buildRecurBlock = TRUE;
584 $buildRecurBlock = FALSE;
587 if ($buildRecurBlock) {
588 CRM_Contribute_Form_Contribution_Main
::buildRecur($this);
589 $this->setDefaults(['is_recur' => 0]);
590 $this->assign('buildRecurBlock', TRUE);
594 $this->addPaymentProcessorSelect(FALSE, $buildRecurBlock);
596 foreach ($paneNames as $name => $type) {
597 $allPanes[$name] = $this->generatePane($type, $defaults);
600 $qfKey = $this->controller
->_key
;
601 $this->assign('qfKey', $qfKey);
602 $this->assign('allPanes', $allPanes);
604 $this->addFormRule(['CRM_Contribute_Form_Contribution', 'formRule'], $this);
606 if ($this->_formType
) {
607 $this->assign('formType', $this->_formType
);
611 $this->applyFilter('__ALL__', 'trim');
613 //need to assign custom data type and subtype to the template
614 $this->assign('customDataType', 'Contribution');
615 $this->assign('customDataSubType', $this->_contributionType
);
616 $this->assign('entityID', $this->_id
);
618 $contactField = $this->addEntityRef('contact_id', ts('Contributor'), ['create' => TRUE, 'api' => ['extra' => ['email']]], TRUE);
619 if ($this->_context
!== 'standalone') {
620 $contactField->freeze();
623 $attributes = CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Contribution');
625 // Check permissions for financial type first
626 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes, $this->_action
);
627 if (empty($financialTypes)) {
628 CRM_Core_Error
::statusBounce(ts('You do not have all the permissions needed for this page.'));
630 $financialType = $this->add('select', 'financial_type_id',
631 ts('Financial Type'),
632 ['' => ts('- select -')] +
$financialTypes,
634 ['onChange' => "CRM.buildCustomData( 'Contribution', this.value );"]
637 $paymentInstrument = FALSE;
639 // payment_instrument isn't required in edit and will not be present when payment block is enabled.
640 $required = !$this->_id
;
641 $checkPaymentID = array_search('Check', CRM_Contribute_PseudoConstant
::paymentInstrument('name'));
642 $paymentInstrument = $this->add('select', 'payment_instrument_id',
643 ts('Payment Method'),
644 ['' => ts('- select -')] + CRM_Contribute_PseudoConstant
::paymentInstrument(),
645 $required, ['onChange' => "return showHideByValue('payment_instrument_id','{$checkPaymentID}','checkNumber','table-row','select',false);"]
649 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), ['class' => 'twelve'] +
$attributes['trxn_id']);
651 //add receipt for offline contribution
652 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
654 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
656 $component = 'contribution';
657 $componentDetails = [];
659 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
660 if (!empty($componentDetails['membership'])) {
661 $component = 'membership';
663 elseif (!empty($componentDetails['participant'])) {
664 $component = 'participant';
668 $component = 'pledge';
670 $status = CRM_Contribute_BAO_Contribution_Utils
::getContributionStatuses($component, $this->_id
);
672 // define the status IDs that show the cancellation info, see CRM-17589
673 $cancelInfo_show_ids = [];
674 foreach (array_keys($status) as $status_id) {
675 if (CRM_Contribute_BAO_Contribution
::isContributionStatusNegative($status_id)) {
676 $cancelInfo_show_ids[] = "'$status_id'";
679 $this->assign('cancelInfo_show_ids', implode(',', $cancelInfo_show_ids));
681 $statusElement = $this->add('select', 'contribution_status_id',
682 ts('Contribution Status'),
687 $currencyFreeze = FALSE;
688 if (!empty($this->_payNow
) && ($this->_action
& CRM_Core_Action
::UPDATE
)) {
689 $statusElement->freeze();
690 $currencyFreeze = TRUE;
691 $attributes['total_amount']['readonly'] = TRUE;
694 // CRM-16189, add Revenue Recognition Date
695 if (Civi
::settings()->get('deferred_revenue_enabled')) {
696 $revenueDate = $this->add('date', 'revenue_recognition_date', ts('Revenue Recognition Date'), CRM_Core_SelectValues
::date(NULL, 'M Y', NULL, 5));
697 if ($this->_id
&& !CRM_Contribute_BAO_Contribution
::allowUpdateRevenueRecognitionDate($this->_id
)) {
698 $revenueDate->freeze();
703 $this->addField('receive_date', ['entity' => 'contribution'], !$this->_mode
, FALSE);
704 $this->addField('receipt_date', ['entity' => 'contribution'], FALSE, FALSE);
705 $this->addField('cancel_date', ['entity' => 'contribution', 'label' => ts('Cancelled / Refunded Date')], FALSE, FALSE);
707 if ($this->_online
) {
708 $this->assign('hideCalender', TRUE);
711 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
714 if (empty($this->_lineItems
)) {
715 $buildPriceSet = FALSE;
716 $priceSets = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute');
717 if (!empty($priceSets) && !$this->_ppID
) {
718 $buildPriceSet = TRUE;
721 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
722 // and if we already have line items for that participant. CRM-5095
723 if ($buildPriceSet && $this->_id
) {
724 $pledgePaymentId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
729 if ($pledgePaymentId) {
730 $buildPriceSet = FALSE;
732 if ($participantID = CRM_Utils_Array
::value('participant', $componentDetails)) {
733 $participantLI = CRM_Price_BAO_LineItem
::getLineItems($participantID);
734 if (!CRM_Utils_System
::isNull($participantLI)) {
735 $buildPriceSet = FALSE;
740 $hasPriceSets = FALSE;
741 if ($buildPriceSet) {
742 $hasPriceSets = TRUE;
743 // CRM-16451: set financial type of 'Price Set' in back office contribution
744 // instead of selecting manually
745 $financialTypeIds = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute', 'financial_type_id');
746 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
748 '' => ts('Choose price set'),
750 NULL, ['onchange' => "buildAmount( this.value, " . json_encode($financialTypeIds) . ");"]
752 if ($this->_online
&& !($this->_action
& CRM_Core_Action
::UPDATE
)) {
756 $this->assign('hasPriceSets', $hasPriceSets);
757 if (!($this->_action
& CRM_Core_Action
::UPDATE
)) {
758 if ($this->_online ||
$this->_ppID
) {
759 $attributes['total_amount'] = array_merge($attributes['total_amount'], [
761 'style' => "background-color:#EBECE4",
764 '1' => ts('Adjust Pledge Payment Schedule?'),
765 '2' => ts('Adjust Total Pledge Amount?'),
767 $this->addRadio('option_type',
773 $currencyFreeze = TRUE;
777 $totalAmount = $this->addMoney('total_amount',
780 $attributes['total_amount'],
781 TRUE, 'currency', NULL, $currencyFreeze
785 $this->add('text', 'source', ts('Source'), CRM_Utils_Array
::value('source', $attributes));
787 // CRM-7362 --add campaigns.
788 CRM_Campaign_BAO_Campaign
::addCampaign($this, CRM_Utils_Array
::value('campaign_id', $this->_values
));
790 if (empty($this->_payNow
)) {
791 CRM_Contribute_Form_SoftCredit
::buildQuickForm($this);
796 $js = ['onclick' => "return verify( );"];
799 $mailingInfo = Civi
::settings()->get('mailing_backend');
800 $this->assign('outBound_option', $mailingInfo['outBound_option']);
805 'name' => ts('Save'),
811 'name' => ts('Save and New'),
817 'name' => ts('Cancel'),
821 // if contribution is related to membership or participant freeze Financial Type, Amount
823 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
824 $isCancelledStatus = ($this->_values
['contribution_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Cancelled'));
826 if (!empty($componentDetails['membership']) ||
827 !empty($componentDetails['participant']) ||
828 // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
829 // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
833 $totalAmount->freeze();
834 $this->getElement('currency')->freeze();
836 if ($isCancelledStatus) {
837 $paymentInstrument->freeze();
840 $financialType->freeze();
841 $this->assign('freezeFinancialType', TRUE);
845 if ($this->_action
& CRM_Core_Action
::VIEW
) {
853 * @param array $fields
854 * The input form values.
855 * @param array $files
856 * The uploaded files if any.
860 * true if no errors, else array of errors
862 public static function formRule($fields, $files, $self) {
864 // Check for Credit Card Contribution.
866 if (empty($fields['payment_processor_id'])) {
867 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
870 // validate payment instrument (e.g. credit card number)
871 CRM_Core_Payment_Form
::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, NULL);
875 // Do the amount validations.
876 if (empty($fields['total_amount']) && empty($self->_lineItems
)) {
877 if ($priceSetId = CRM_Utils_Array
::value('price_set_id', $fields)) {
878 CRM_Price_BAO_PriceField
::priceSetValidation($priceSetId, $fields, $errors);
882 $softErrors = CRM_Contribute_Form_SoftCredit
::formRule($fields, $errors, $self);
884 //CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
885 CRM_Contribute_BAO_ContributionRecur
::validateRecurContribution($fields, $files, $self, $errors);
887 // Form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
888 if (($self->_action
& CRM_Core_Action
::UPDATE
)
890 && $self->_values
['contribution_status_id'] != $fields['contribution_status_id']
892 CRM_Contribute_BAO_Contribution
::checkStatusValidation($self->_values
, $fields, $errors);
894 // CRM-16015, add form-rule to restrict change of financial type if using price field of different financial type
895 if (($self->_action
& CRM_Core_Action
::UPDATE
)
897 && $self->_values
['financial_type_id'] != $fields['financial_type_id']
899 CRM_Contribute_BAO_Contribution
::checkFinancialTypeChange(NULL, $self->_id
, $errors);
901 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
902 if (!empty($fields['fee_amount']) && !empty($fields['financial_type_id']) && $financialType = CRM_Contribute_BAO_Contribution
::validateFinancialType($fields['financial_type_id'])) {
903 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
906 // $trxn_id must be unique CRM-13919
907 if (!empty($fields['trxn_id'])) {
908 $queryParams = [1 => [$fields['trxn_id'], 'String']];
909 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
911 $queryParams[2] = [(int) $self->_id
, 'Integer'];
912 $query .= ' and id !=%2';
914 $tCnt = CRM_Core_DAO
::singleValueQuery($query, $queryParams);
916 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', [1 => $fields['trxn_id']]);
919 if (!empty($fields['revenue_recognition_date'])
920 && count(array_filter($fields['revenue_recognition_date'])) == 1
922 $errors['revenue_recognition_date'] = ts('Month and Year are required field for Revenue Recognition.');
926 CRM_Financial_BAO_FinancialAccount
::checkFinancialTypeHasDeferred($fields, $self->_id
, $self->_priceSet
['fields']);
928 catch (CRM_Core_Exception
$e) {
929 $errors['financial_type_id'] = ' ';
930 $errors['_qf_default'] = $e->getMessage();
932 $errors = array_merge($errors, $softErrors);
937 * Process the form submission.
939 public function postProcess() {
940 if ($this->_action
& CRM_Core_Action
::DELETE
) {
941 CRM_Contribute_BAO_Contribution
::deleteContribution($this->_id
);
942 CRM_Core_Session
::singleton()->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
943 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
947 // Get the submitted form values.
948 $submittedValues = $this->controller
->exportValues($this->_name
);
951 $contribution = $this->submit($submittedValues, $this->_action
, $this->_ppID
);
953 catch (PaymentProcessorException
$e) {
954 // Set the contribution mode.
955 $urlParams = "action=add&cid={$this->_contactID}";
957 $urlParams .= "&mode={$this->_mode}";
959 if (!empty($this->_ppID
)) {
960 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
963 CRM_Core_Error
::statusBounce($e->getMessage(), $urlParams, ts('Payment Processor Error'));
965 $session = CRM_Core_Session
::singleton();
966 $buttonName = $this->controller
->getButtonName();
967 if ($this->_context
== 'standalone') {
968 if ($buttonName == $this->getButtonName('upload', 'new')) {
969 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contribute/add',
970 'reset=1&action=add&context=standalone'
974 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
975 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
979 elseif ($this->_context
== 'contribution' && $this->_mode
&& $buttonName == $this->getButtonName('upload', 'new')) {
980 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
981 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
984 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
985 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
986 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
990 //store contribution ID if not yet set (on create)
991 if (empty($this->_id
) && !empty($contribution->id
)) {
992 $this->_id
= $contribution->id
;
994 if (!empty($this->_id
) && CRM_Core_Permission
::access('CiviMember')) {
995 $membershipPaymentCount = civicrm_api3('MembershipPayment', 'getCount', ['contribution_id' => $this->_id
]);
996 if ($membershipPaymentCount) {
997 $this->ajaxResponse
['updateTabs']['#tab_member'] = CRM_Contact_BAO_Contact
::getCountComponent('membership', $this->_contactID
);
1000 if (!empty($this->_id
) && CRM_Core_Permission
::access('CiviEvent')) {
1001 $participantPaymentCount = civicrm_api3('ParticipantPayment', 'getCount', ['contribution_id' => $this->_id
]);
1002 if ($participantPaymentCount) {
1003 $this->ajaxResponse
['updateTabs']['#tab_participant'] = CRM_Contact_BAO_Contact
::getCountComponent('participant', $this->_contactID
);
1009 * Process credit card payment.
1011 * @param array $submittedValues
1012 * @param array $lineItem
1014 * @param int $contactID
1017 * @return bool|\CRM_Contribute_DAO_Contribution
1019 * @throws \CRM_Core_Exception
1020 * @throws \Civi\Payment\Exception\PaymentProcessorException
1021 * @throws \CiviCRM_API3_Exception
1023 protected function processCreditCard($submittedValues, $lineItem, $contactID) {
1024 $isTest = ($this->_mode
== 'test') ?
1 : 0;
1025 // CRM-12680 set $_lineItem if its not set
1026 // @todo - I don't believe this would ever BE set. I can't find anywhere in the code.
1027 // It would be better to pass line item out to functions than $this->_lineItem as
1028 // we don't know what is being changed where.
1029 if (empty($this->_lineItem
) && !empty($lineItem)) {
1030 $this->_lineItem
= $lineItem;
1033 $this->_paymentObject
= Civi\Payment\System
::singleton()->getById($submittedValues['payment_processor_id']);
1034 $this->_paymentProcessor
= $this->_paymentObject
->getPaymentProcessor();
1036 // Set source if not set
1037 if (empty($submittedValues['source'])) {
1038 $userID = CRM_Core_Session
::singleton()->get('userID');
1039 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1042 $submittedValues['source'] = ts('Submit Credit Card Payment by: %1', [1 => $userSortName]);
1045 $params = $submittedValues;
1046 $this->_params
= array_merge($this->_params
, $submittedValues);
1048 // Mapping requiring documentation.
1049 $this->_params
['payment_processor'] = $submittedValues['payment_processor_id'];
1051 $now = date('YmdHis');
1053 $this->_contributorEmail
= $this->userEmail
;
1054 $this->_contributorContactID
= $contactID;
1055 $this->processBillingAddress();
1056 if (!empty($params['source'])) {
1057 unset($params['source']);
1060 $this->_params
['amount'] = $this->_params
['total_amount'];
1061 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
1062 // function to get correct amount level consistently. Remove setting of the amount level in
1063 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
1064 // to cover all variants.
1065 $this->_params
['amount_level'] = 0;
1066 $this->_params
['description'] = ts("Contribution submitted by a staff person using contributor's credit card");
1067 $this->_params
['currencyID'] = CRM_Utils_Array
::value('currency',
1069 CRM_Core_Config
::singleton()->defaultCurrency
1072 $this->_params
['pcp_display_in_roll'] = $params['pcp_display_in_roll'] ??
NULL;
1073 $this->_params
['pcp_roll_nickname'] = $params['pcp_roll_nickname'] ??
NULL;
1074 $this->_params
['pcp_personal_note'] = $params['pcp_personal_note'] ??
NULL;
1076 //Add common data to formatted params
1077 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
1079 if (empty($this->_params
['invoice_id'])) {
1080 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
1083 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
1086 // At this point we've created a contact and stored its address etc
1087 // all the payment processors expect the name and address to be in the
1088 // so we copy stuff over to first_name etc.
1089 $paymentParams = $this->_params
;
1090 $paymentParams['contactID'] = $contactID;
1091 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
1093 $financialType = new CRM_Financial_DAO_FinancialType();
1094 $financialType->id
= $params['financial_type_id'];
1095 $financialType->find(TRUE);
1097 // Add some financial type details to the params list
1098 // if folks need to use it.
1099 $paymentParams['contributionType_name'] = $this->_params
['contributionType_name'] = $financialType->name
;
1100 $paymentParams['contributionPageID'] = NULL;
1102 if (!empty($this->_params
['is_email_receipt'])) {
1103 $paymentParams['email'] = $this->userEmail
;
1104 $paymentParams['is_email_receipt'] = 1;
1107 $paymentParams['is_email_receipt'] = 0;
1108 $this->_params
['is_email_receipt'] = 0;
1110 if (!empty($this->_params
['receive_date'])) {
1111 $paymentParams['receive_date'] = $this->_params
['receive_date'];
1114 if (!empty($this->_params
['is_email_receipt'])) {
1115 $this->_params
['receipt_date'] = $now;
1118 $this->set('params', $this->_params
);
1120 $this->assign('receive_date', $this->_params
['receive_date']);
1122 // Result has all the stuff we need
1123 // lets archive it to a financial transaction
1124 if ($financialType->is_deductible
) {
1125 $this->assign('is_deductible', TRUE);
1126 $this->set('is_deductible', TRUE);
1128 $contributionParams = [
1129 'id' => $this->_params
['contribution_id'] ??
NULL,
1130 'contact_id' => $contactID,
1131 'line_item' => $lineItem,
1132 'is_test' => $isTest,
1133 'campaign_id' => $this->_params
['campaign_id'] ??
NULL,
1134 'contribution_page_id' => $this->_params
['contribution_page_id'] ??
NULL,
1135 'source' => CRM_Utils_Array
::value('source', $paymentParams, CRM_Utils_Array
::value('description', $paymentParams)),
1136 'thankyou_date' => $this->_params
['thankyou_date'] ??
NULL,
1138 $contributionParams['payment_instrument_id'] = $this->_paymentProcessor
['payment_instrument_id'];
1140 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processFormContribution($this,
1143 $contributionParams,
1147 CRM_Utils_Array
::value('is_recur', $this->_params
)
1150 $paymentParams['contributionID'] = $contribution->id
;
1151 $paymentParams['contributionTypeID'] = $contribution->financial_type_id
;
1152 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
1153 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1155 if ($paymentParams['amount'] > 0.0) {
1156 // force a re-get of the payment processor in case the form changed it, CRM-7179
1157 // NOTE - I expect this is obsolete.
1158 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
1160 $completeStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
1161 $result = $payment->doPayment($paymentParams, 'contribute');
1162 $this->assign('trxn_id', $result['trxn_id']);
1163 $contribution->trxn_id
= $result['trxn_id'];
1164 /* Our scenarios here are
1165 * 1) the payment failed & an Exception should have been thrown
1166 * 2) the payment succeeded but the payment is not immediate (for example a recurring payment
1167 * with a delayed start)
1168 * 3) the payment succeeded with an immediate payment.
1170 * The doPayment function ensures that payment_status_id is always set
1171 * as historically we have had to guess from the context - ie doDirectPayment
1172 * = error or success, unless it is a recurring contribution in which case it is pending.
1174 if ($result['payment_status_id'] == $completeStatusId) {
1176 civicrm_api3('contribution', 'completetransaction', [
1177 'id' => $contribution->id
,
1178 'trxn_id' => $result['trxn_id'],
1179 'payment_processor_id' => $this->_paymentProcessor
['id'],
1180 'is_transactional' => FALSE,
1181 'fee_amount' => $result['fee_amount'] ??
NULL,
1182 'card_type_id' => $paymentParams['card_type_id'] ??
NULL,
1183 'pan_truncation' => $paymentParams['pan_truncation'] ??
NULL,
1184 'is_email_receipt' => FALSE,
1186 // This has now been set to 1 in the DB - declare it here also
1187 $contribution->contribution_status_id
= 1;
1189 catch (CiviCRM_API3_Exception
$e) {
1190 if ($e->getErrorCode() != 'contribution_completed') {
1191 throw new CRM_Core_Exception('Failed to update contribution in database');
1196 // Save the trxn_id.
1197 $contribution->save();
1200 catch (PaymentProcessorException
$e) {
1201 CRM_Contribute_BAO_Contribution
::failPayment($contribution->id
, $paymentParams['contactID'], $e->getMessage());
1202 throw new PaymentProcessorException($e->getMessage());
1205 // Send receipt mail.
1206 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1207 if ($contribution->id
&& !empty($this->_params
['is_email_receipt'])) {
1208 $this->_params
['trxn_id'] = $result['trxn_id'] ??
NULL;
1209 $this->_params
['contact_id'] = $contactID;
1210 $this->_params
['contribution_id'] = $contribution->id
;
1211 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $this->_params
, TRUE)) {
1212 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1216 return $contribution;
1220 * Generate the data to construct a snippet based pane.
1222 * This form also assigns the showAdditionalInfo var based on historical code.
1223 * This appears to mean 'there is a pane to show'.
1225 * @param string $type
1226 * Type of Pane - this is generally used to determine the function name used to build it
1227 * - e.g CreditCard, AdditionalDetail
1228 * @param array $defaults
1231 * We aim to further refactor & simplify this but currently
1233 * - should additional info be shown?
1235 protected function generatePane($type, $defaults) {
1236 $urlParams = "snippet=4&formType={$type}";
1238 $urlParams .= "&mode={$this->_mode}";
1242 if ($type == 'CreditCard' ||
1243 $type == 'DirectDebit'
1249 'url' => CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams),
1254 // See if we need to include this paneName in the current form.
1255 if ($this->_formType
== $type ||
!empty($_POST["hidden_{$type}"]) ||
1256 !empty($defaults["hidden_{$type}"])
1258 $this->assign('showAdditionalInfo', TRUE);
1259 $pane['open'] = 'true';
1262 if ($type == 'CreditCard' ||
$type == 'DirectDebit') {
1263 // @todo would be good to align tpl name with form name...
1264 // @todo document why this hidden variable is required.
1265 $this->add('hidden', 'hidden_' . $type, 1);
1269 $additionalInfoFormFunction = 'build' . $type;
1270 CRM_Contribute_Form_AdditionalInfo
::$additionalInfoFormFunction($this);
1276 * Wrapper for unit testing the post process submit function.
1278 * (If we expose through api we can get default additions 'for free').
1280 * @param array $params
1281 * @param int $action
1282 * @param string|null $creditCardMode
1284 * @return CRM_Contribute_BAO_Contribution
1286 * @throws \CRM_Core_Exception
1287 * @throws \CiviCRM_API3_Exception
1288 * @throws \Civi\Payment\Exception\PaymentProcessorException
1290 public function testSubmit($params, $action, $creditCardMode = NULL) {
1292 'soft_credit_contact_id' => [],
1293 'receive_date' => date('Y-m-d H:i:s'),
1294 'receipt_date' => '',
1295 'cancel_date' => '',
1296 'hidden_Premium' => 1,
1299 if (!empty($params['id'])) {
1300 $existingContribution = civicrm_api3('contribution', 'getsingle', [
1301 'id' => $params['id'],
1303 $this->_id
= $params['id'];
1304 $this->_values
= $existingContribution;
1305 if (CRM_Invoicing_Utils
::isInvoicingEnabled()) {
1306 $this->_values
['tax_amount'] = civicrm_api3('contribution', 'getvalue', [
1307 'id' => $params['id'],
1308 'return' => 'tax_amount',
1313 $existingContribution = [];
1316 $this->_defaults
['contribution_status_id'] = CRM_Utils_Array
::value('contribution_status_id',
1317 $existingContribution
1320 $this->_defaults
['total_amount'] = CRM_Utils_Array
::value('total_amount',
1321 $existingContribution
1324 if ($creditCardMode) {
1325 $this->_mode
= $creditCardMode;
1328 // Required because processCreditCard calls set method on this.
1329 $_SERVER['REQUEST_METHOD'] = 'GET';
1330 $this->controller
= new CRM_Core_Controller();
1332 CRM_Contribute_Form_AdditionalInfo
::buildPremium($this);
1334 $this->_fields
= [];
1335 return $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array
::value('pledge_payment_id', $params));
1340 * @param array $submittedValues
1342 * @param int $action
1344 * - CRM_Core_Action::UPDATE
1346 * @param $pledgePaymentID
1348 * @return \CRM_Contribute_BAO_Contribution
1350 * @throws \CRM_Core_Exception
1351 * @throws \CiviCRM_API3_Exception
1352 * @throws \Civi\Payment\Exception\PaymentProcessorException
1354 protected function submit($submittedValues, $action, $pledgePaymentID) {
1355 $pId = $contribution = $isRelatedId = FALSE;
1356 $this->_params
= $submittedValues;
1357 $this->beginPostProcess();
1358 // reassign submitted form values if the any information is formatted via beginPostProcess
1359 $submittedValues = $this->_params
;
1361 if (!empty($submittedValues['price_set_id']) && $action & CRM_Core_Action
::UPDATE
) {
1362 $line = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution');
1363 $lineID = key($line);
1364 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array
::value('price_field_id', $line[$lineID]), 'price_set_id');
1365 $quickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1366 // Why do we do this? Seems like a like a wrapper for old functionality - but single line price sets & quick
1367 // config should be treated the same.
1369 CRM_Price_BAO_LineItem
::deleteLineItems($this->_id
, 'civicrm_contribution');
1373 // Process price set and get total amount and line items.
1375 $priceSetId = $submittedValues['price_set_id'] ??
NULL;
1376 if (empty($priceSetId) && !$this->_id
) {
1377 $this->_priceSetId
= $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1378 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
1379 $fieldID = key($this->_priceSet
['fields']);
1380 $fieldValueId = key($this->_priceSet
['fields'][$fieldID]['options']);
1381 $this->_priceSet
['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1382 $submittedValues['price_' . $fieldID] = 1;
1385 // Every contribution has a price-set - the only reason it shouldn't be set is if we are dealing with
1386 // quick config (very very arguably) & yet we see that this could still be quick config so this should be understood
1387 // as a point of fragility rather than a logical 'if' clause.
1389 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
1390 $submittedValues, $lineItem[$priceSetId], $priceSetId);
1391 // Unset tax amount for offline 'is_quick_config' contribution.
1392 // @todo WHY - quick config was conceived as a quick way to configure contribution forms.
1393 // this is an example of 'other' functionality being hung off it.
1394 if ($this->_priceSet
['is_quick_config'] &&
1395 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant
::getTaxRates())
1397 unset($submittedValues['tax_amount']);
1399 $submittedValues['total_amount'] = $submittedValues['amount'] ??
NULL;
1403 if ($this->_compId
) {
1404 if ($this->_context
== 'participant') {
1405 $pId = $this->_compId
;
1407 elseif ($this->_context
== 'membership') {
1408 $isRelatedId = TRUE;
1411 $pId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id
, 'participant_id', 'contribution_id');
1415 $contributionDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1416 if (array_key_exists('membership', $contributionDetails)) {
1417 $isRelatedId = TRUE;
1419 elseif (array_key_exists('participant', $contributionDetails)) {
1420 $pId = $contributionDetails['participant'];
1423 if (!empty($this->_payNow
)) {
1424 $this->_params
['contribution_id'] = $this->_id
;
1428 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id
) {
1429 // CRM-10117 update the line items for participants.
1430 // @todo - if we are completing a contribution then the api call
1431 // civicrm_api3('Contribution', 'completetransaction') should take care of
1432 // all associated updates rather than replicating them on the form layer.
1434 $entityTable = 'participant';
1436 $isRelatedId = FALSE;
1437 $participantParams = [
1438 'fee_amount' => $submittedValues['total_amount'],
1441 CRM_Event_BAO_Participant
::add($participantParams);
1442 if (empty($this->_lineItems
)) {
1443 $this->_lineItems
[] = CRM_Price_BAO_LineItem
::getLineItems($entityID, 'participant', TRUE);
1447 $entityTable = 'contribution';
1448 $entityID = $this->_id
;
1451 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, $entityTable, FALSE, TRUE, $isRelatedId);
1452 foreach (array_keys($lineItems) as $id) {
1453 $lineItems[$id]['id'] = $id;
1455 $itemId = key($lineItems);
1456 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1457 $this->_priceSetId
= CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1460 // @todo see above - new functionality has been inappropriately added to the quick config concept
1461 // and new functionality has been added onto the form layer rather than the BAO :-(
1462 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1463 //CRM-16833: Ensure tax is applied only once for membership conribution, when status changed.(e.g Pending to Completed).
1464 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1465 if (empty($componentDetails['membership']) && empty($componentDetails['participant'])) {
1466 if (!($this->_action
& CRM_Core_Action
::UPDATE
&& (($this->_defaults
['contribution_status_id'] != $submittedValues['contribution_status_id'])))) {
1467 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule
::cleanMoney(CRM_Utils_Array
::value('total_amount', $submittedValues));
1471 // Update line total and total amount with tax on edit.
1472 $financialItemsId = CRM_Core_PseudoConstant
::getTaxRates();
1473 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1474 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1477 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1478 $submittedValues['tax_amount'] = 'null';
1480 if ($lineItems[$itemId]['tax_rate']) {
1481 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total'];
1482 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] +
$lineItems[$itemId]['tax_amount'];
1483 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1486 // CRM-10117 update the line items for participants.
1487 if (!empty($lineItems[$itemId]['price_field_id'])) {
1488 $lineItem[$this->_priceSetId
] = $lineItems;
1493 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1496 //CRM-11529 for quick config back office transactions
1497 //when financial_type_id is passed in form, update the
1498 //line items with the financial type selected in form
1499 // NOTE that this IS still a legitimate use of 'quick-config' for contributions under the current DB but
1500 // we should look at having a price field per contribution type & then there would be little reason
1501 // for the back-office contribution form postProcess to know if it is a quick-config form.
1502 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && !empty($lineItem[$this->_priceSetId
])
1504 foreach ($lineItem[$this->_priceSetId
] as &$values) {
1505 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1509 if (!isset($submittedValues['total_amount'])) {
1510 $submittedValues['total_amount'] = $this->_values
['total_amount'] ??
NULL;
1511 // Avoid tax amount deduction on edit form and keep it original, because this will lead to error described in CRM-20676
1513 $submittedValues['total_amount'] -= CRM_Utils_Array
::value('tax_amount', $this->_values
, 0);
1516 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
1518 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
1519 if ($this->_id
&& count($isEmpty) == 1 && key($isEmpty) == NULL) {
1520 civicrm_api3('ContributionSoft', 'get', ['contribution_id' => $this->_id
, 'pcp_id' => NULL, 'api.ContributionSoft.delete' => 1]);
1523 // set the contact, when contact is selected
1524 if (!empty($submittedValues['contact_id'])) {
1525 $this->_contactID
= $submittedValues['contact_id'];
1528 $formValues = $submittedValues;
1530 // Credit Card Contribution.
1532 $paramsSetByPaymentProcessingSubsystem = [
1534 'payment_instrument_id',
1535 'contribution_status_id',
1539 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1540 if (isset($formValues[$key])) {
1541 unset($formValues[$key]);
1544 $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID
);
1545 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1546 $formValues[$key] = $contribution->$key;
1550 // Offline Contribution.
1551 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1553 // get the required field value only.
1556 'contact_id' => $this->_contactID
,
1557 'currency' => $this->getCurrency($submittedValues),
1558 'skipCleanMoney' => TRUE,
1562 //format soft-credit/pcp param first
1563 CRM_Contribute_BAO_ContributionSoft
::formatSoftCreditParams($submittedValues, $this);
1564 $params = array_merge($params, $submittedValues);
1567 'financial_type_id',
1568 'contribution_status_id',
1569 'payment_instrument_id',
1576 foreach ($fields as $f) {
1577 $params[$f] = $formValues[$f] ??
NULL;
1580 $params['revenue_recognition_date'] = NULL;
1581 if (!empty($formValues['revenue_recognition_date'])
1582 && count(array_filter($formValues['revenue_recognition_date'])) == 2
1584 $params['revenue_recognition_date'] = CRM_Utils_Date
::processDate(
1585 '01-' . implode('-', $formValues['revenue_recognition_date'])
1589 if (!empty($formValues['is_email_receipt'])) {
1590 $params['receipt_date'] = date("Y-m-d");
1593 if (CRM_Contribute_BAO_Contribution
::isContributionStatusNegative($params['contribution_status_id'])
1595 if (CRM_Utils_System
::isNull(CRM_Utils_Array
::value('cancel_date', $params))) {
1596 $params['cancel_date'] = date('YmdHis');
1600 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1603 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1604 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1605 if ($params['contribution_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending')) {
1606 $params['is_pay_later'] = 1;
1608 elseif ($params['contribution_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed')) {
1609 $params['is_pay_later'] = 0;
1612 // Add Additional common information to formatted params.
1613 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($formValues, $params, $this);
1615 $params['contribution_mode'] = 'participant';
1616 $params['participant_id'] = $pId;
1617 $params['skipLineItem'] = 1;
1619 elseif ($isRelatedId) {
1620 $params['contribution_mode'] = 'membership';
1622 $params['line_item'] = $lineItem;
1623 $params['payment_processor_id'] = $params['payment_processor'] = $this->_paymentProcessor
['id'] ??
NULL;
1624 $params['tax_amount'] = CRM_Utils_Array
::value('tax_amount', $submittedValues, CRM_Utils_Array
::value('tax_amount', $this->_values
));
1625 //create contribution.
1626 if ($isQuickConfig) {
1627 $params['is_quick_config'] = 1;
1629 $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
1631 // we are already handling note below, so to avoid duplicate notes against $contribution
1632 if (!empty($params['note']) && !empty($submittedValues['note'])) {
1633 unset($params['note']);
1635 $contribution = CRM_Contribute_BAO_Contribution
::create($params);
1637 // process associated membership / participant, CRM-4395
1638 if ($contribution->id
&& $action & CRM_Core_Action
::UPDATE
) {
1639 $this->statusMessage
[] = CRM_Contribute_BAO_Contribution
::transitionComponentWithReturnMessage($contribution->id
,
1640 $contribution->contribution_status_id
,
1641 CRM_Utils_Array
::value('contribution_status_id',
1644 $contribution->receive_date
1648 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1650 $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
1652 //send receipt mail.
1653 if ($contribution->id
&& !empty($formValues['is_email_receipt'])) {
1654 $formValues['contact_id'] = $this->_contactID
;
1655 $formValues['contribution_id'] = $contribution->id
;
1657 $formValues +
= CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
);
1659 // to get 'from email id' for send receipt
1660 $this->fromEmailId
= $formValues['from_email_address'] ??
NULL;
1661 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $formValues)) {
1662 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1666 $this->statusMessageTitle
= ts('Saved');
1670 if ($contribution->id
&& isset($formValues['product_name'][0])) {
1671 CRM_Contribute_Form_AdditionalInfo
::processPremium($submittedValues, $contribution->id
,
1672 $this->_premiumID
, $this->_options
1676 if ($contribution->id
&& array_key_exists('note', $submittedValues)) {
1677 CRM_Contribute_Form_AdditionalInfo
::processNote($submittedValues, $this->_contactID
, $contribution->id
, $this->_noteID
);
1680 CRM_Core_Session
::setStatus(implode(' ', $this->statusMessage
), $this->statusMessageTitle
, 'success');
1682 CRM_Contribute_BAO_Contribution
::updateRelatedPledge(
1686 ($formValues['option_type'] ??
0) == 2,
1687 $formValues['total_amount'],
1688 CRM_Utils_Array
::value('total_amount', $this->_defaults
),
1689 $formValues['contribution_status_id'],
1690 CRM_Utils_Array
::value('contribution_status_id', $this->_defaults
)
1692 return $contribution;
1696 * Assign tax calculations to contribution receipts.
1698 * @param array $submittedValues
1699 * @param int $action
1700 * @param array $lineItem
1702 protected function invoicingPostProcessHook($submittedValues, $action, $lineItem) {
1704 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
1705 if (empty($invoiceSettings['invoicing'])) {
1709 $getTaxDetails = FALSE;
1711 foreach ($lineItem as $key => $value) {
1712 foreach ($value as $v) {
1713 if (isset($taxRate[(string) CRM_Utils_Array
::value('tax_rate', $v)])) {
1714 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $v);
1717 if (isset($v['tax_rate'])) {
1718 $taxRate[(string) $v['tax_rate']] = $v['tax_amount'] ??
NULL;
1719 $getTaxDetails = TRUE;
1725 if ($action & CRM_Core_Action
::UPDATE
) {
1726 if (isset($submittedValues['tax_amount'])) {
1727 $totalTaxAmount = $submittedValues['tax_amount'];
1730 $totalTaxAmount = $this->_values
['tax_amount'];
1732 $this->assign('totalTaxAmount', $totalTaxAmount);
1733 $this->assign('dataArray', $taxRate);
1736 if (!empty($submittedValues['price_set_id'])) {
1737 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1738 $this->assign('getTaxDetails', $getTaxDetails);
1739 $this->assign('dataArray', $taxRate);
1740 $this->assign('taxTerm', Civi
::settings()->get('tax_term'));
1743 $this->assign('totalTaxAmount', CRM_Utils_Array
::value('tax_amount', $submittedValues));
1749 * Calculate non deductible amount.
1752 * if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1753 * if non_deductible_amount does NOT exist - then calculate it depending on:
1754 * $financialType->is_deductible and whether there is a product (premium).
1757 * @param $formValues
1761 protected function calculateNonDeductibleAmount($params, $formValues) {
1762 if (!empty($params['non_deductible_amount'])) {
1763 return $params['non_deductible_amount'];
1766 $priceSetId = $params['price_set_id'] ??
NULL;
1767 // return non-deductible amount if it is set at the price field option level
1768 if ($priceSetId && !empty($params['line_item'])) {
1769 $nonDeductibleAmount = CRM_Price_BAO_PriceSet
::getNonDeductibleAmountFromPriceSet($priceSetId, $params['line_item']);
1770 if (!empty($nonDeductibleAmount)) {
1771 return $nonDeductibleAmount;
1775 $financialType = new CRM_Financial_DAO_FinancialType();
1776 $financialType->id
= $params['financial_type_id'];
1777 $financialType->find(TRUE);
1779 if ($financialType->is_deductible
) {
1781 if (isset($formValues['product_name'][0])) {
1782 $selectProduct = $formValues['product_name'][0];
1784 // if there is a product - compare the value to the contribution amount
1785 if (isset($selectProduct)) {
1786 $productDAO = new CRM_Contribute_DAO_Product();
1787 $productDAO->id
= $selectProduct;
1788 $productDAO->find(TRUE);
1789 // product value exceeds contribution amount
1790 if ($params['total_amount'] < $productDAO->price
) {
1791 return $params['total_amount'];
1793 // product value does NOT exceed contribution amount
1795 return $productDAO->price
;
1798 // contribution is deductible - but there is no product
1803 // contribution is NOT deductible
1805 return $params['total_amount'];