3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
28 use Civi\Payment\Exception\PaymentProcessorException
;
31 * This class generates form components for processing a contribution.
33 class CRM_Contribute_Form_Contribution
extends CRM_Contribute_Form_AbstractEditPayment
{
35 * The id of the contribution that we are processing.
42 * The id of the premium that we are processing.
46 public $_premiumID = NULL;
49 * @var CRM_Contribute_DAO_ContributionProduct
51 public $_productDAO = NULL;
61 * The id of the contact associated with this contribution.
68 * The id of the pledge payment that we are processing.
75 * Is this contribution associated with an online.
76 * financial transaction
80 public $_online = FALSE;
83 * Stores all product options.
90 * Storage of parameters from form
97 * Store the contribution Type ID
101 public $_contributionType;
104 * The contribution values if an existing contribution
110 * The pledge values if this contribution is associated with pledge
113 public $_pledgeValues;
115 public $_contributeMode = 'direct';
120 * Parameter with confusing name.
124 public $_compContext;
129 * Possible From email addresses
142 * Store the line items if price set used.
150 * @todo explain why we use lineItem & lineItems
159 public $_softCreditInfo;
161 protected $_formType;
164 * Array of the payment fields to be displayed in the payment fieldset (pane) in billingBlock.tpl
165 * this contains all the information to describe these fields from quickform. See CRM_Core_Form_Payment getPaymentFormFieldsMetadata
169 public $_paymentFields = [];
171 * Logged in user's email.
184 * Price set as an array
194 public $userDisplayName;
197 * Status message to be shown to the user.
201 protected $statusMessage = [];
204 * Status message title to be shown to the user.
206 * Generally the payment processor message title is 'Complete' and offline is 'Saved'
207 * although this might not be a good fit with the broad range of processors.
211 protected $statusMessageTitle;
216 * Max row count for soft credits. The value here is +1 the actual number of
219 public $_softCreditItemCount = 11;
222 * Explicitly declare the form context.
224 public function getDefaultContext() {
229 * Set variables up before form is built.
231 public function preProcess() {
232 // Check permission for action.
233 if (!CRM_Core_Permission
::checkActionPermission('CiviContribute', $this->_action
)) {
234 // @todo replace with throw new CRM_Core_Exception().
235 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
238 parent
::preProcess();
240 $this->_formType
= CRM_Utils_Array
::value('formType', $_GET);
243 $this->_priceSetId
= CRM_Utils_Array
::value('priceSetId', $_GET);
244 $this->set('priceSetId', $this->_priceSetId
);
245 $this->assign('priceSetId', $this->_priceSetId
);
247 // Get the pledge payment id
248 $this->_ppID
= CRM_Utils_Request
::retrieve('ppid', 'Positive', $this);
250 $this->assign('action', $this->_action
);
252 // Get the contribution id if update
253 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive');
254 if (!empty($this->_id
)) {
255 $this->assignPaymentInfoBlock();
256 $this->assign('contribID', $this->_id
);
257 $this->assign('isUsePaymentBlock', TRUE);
260 $this->_context
= CRM_Utils_Request
::retrieve('context', 'Alphanumeric', $this);
261 $this->assign('context', $this->_context
);
263 $this->_compId
= CRM_Utils_Request
::retrieve('compId', 'Positive', $this);
265 $this->_compContext
= CRM_Utils_Request
::retrieve('compContext', 'String', $this);
267 //set the contribution mode.
268 $this->_mode
= CRM_Utils_Request
::retrieve('mode', 'Alphanumeric', $this);
270 $this->assign('contributionMode', $this->_mode
);
271 if ($this->_action
& CRM_Core_Action
::DELETE
) {
275 $this->_fromEmails
= CRM_Core_BAO_Email
::getFromEmail();
277 if (in_array('CiviPledge', CRM_Core_Config
::singleton()->enableComponents
) && !$this->_formType
) {
278 $this->preProcessPledge();
282 $this->showRecordLinkMesssage($this->_id
);
286 // Current contribution id.
288 $this->assignPremiumProduct($this->_id
);
289 $this->buildValuesAndAssignOnline_Note_Type($this->_id
, $this->_values
);
292 // when custom data is included in this page
293 if (!empty($_POST['hidden_custom'])) {
294 $this->applyCustomData('Contribution', CRM_Utils_Array
::value('financial_type_id', $_POST), $this->_id
);
297 $this->_lineItems
= [];
299 if (!empty($this->_compId
) && $this->_compContext
== 'participant') {
300 $this->assign('compId', $this->_compId
);
301 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_compId
);
304 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution', 1, TRUE, TRUE);
307 empty($lineItem) ?
NULL : $this->_lineItems
[] = $lineItem;
310 $this->assign('lineItem', empty($lineItem) ?
FALSE : [$lineItem]);
313 if ($this->_mode
&& $this->_id
) {
314 $this->_payNow
= TRUE;
315 $this->assign('payNow', $this->_payNow
);
316 CRM_Utils_System
::setTitle(ts('Pay with Credit Card'));
318 elseif ($this->_mode
) {
319 $this->setPageTitle($this->_ppID ?
ts('Credit Card Pledge Payment') : ts('Credit Card Contribution'));
322 $this->setPageTitle($this->_ppID ?
ts('Pledge Payment') : ts('Contribution'));
327 * Set default values.
331 public function setDefaultValues() {
332 $defaults = $this->_values
;
334 // Set defaults for pledge payment.
336 $defaults['total_amount'] = CRM_Utils_Array
::value('scheduled_amount', $this->_pledgeValues
['pledgePayment']);
337 $defaults['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $this->_pledgeValues
);
338 $defaults['currency'] = CRM_Utils_Array
::value('currency', $this->_pledgeValues
);
339 $defaults['option_type'] = 1;
342 if ($this->_action
& CRM_Core_Action
::DELETE
) {
346 $defaults['frequency_interval'] = 1;
347 $defaults['frequency_unit'] = 'month';
349 // Set soft credit defaults.
350 CRM_Contribute_Form_SoftCredit
::setDefaultValues($defaults, $this);
353 // @todo - remove this function as the parent does it too.
354 $config = CRM_Core_Config
::singleton();
355 // Set default country from config if no country set.
356 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
357 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry
;
360 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
361 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince
;
364 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID
);
365 $defaults = array_merge($defaults, $billingDefaults);
369 $this->_contactID
= $defaults['contact_id'];
372 // Set $newCredit variable in template to control whether link to credit card mode is included.
373 $this->assign('newCredit', CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments());
375 // Fix the display of the monetary value, CRM-4038.
376 if (isset($defaults['total_amount'])) {
377 $total_value = $defaults['total_amount'];
378 $defaults['total_amount'] = CRM_Utils_Money
::format($total_value, NULL, '%a');
379 if (!empty($defaults['tax_amount'])) {
380 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
381 if (!(CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails))) {
382 $defaults['total_amount'] = CRM_Utils_Money
::format($total_value - $defaults['tax_amount'], NULL, '%a');
387 $amountFields = ['non_deductible_amount', 'fee_amount'];
388 foreach ($amountFields as $amt) {
389 if (isset($defaults[$amt])) {
390 $defaults[$amt] = CRM_Utils_Money
::format($defaults[$amt], NULL, '%a');
394 if ($this->_contributionType
) {
395 $defaults['financial_type_id'] = $this->_contributionType
;
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 = isset($this->_options
[$this->_productDAO
->product_id
]) ?
$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'] = isset($defaults['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 = CRM_Utils_Array
::value('currency', $defaults);
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 public function buildQuickForm() {
470 $this->add('hidden', 'id', $this->_id
);
473 if ($this->_action
& CRM_Core_Action
::DELETE
) {
477 'name' => ts('Delete'),
478 'spacing' => ' ',
483 'name' => ts('Cancel'),
489 // FIXME: This probably needs to be done in preprocess
490 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()
491 && $this->_action
& CRM_Core_Action
::UPDATE
492 && CRM_Utils_Array
::value('financial_type_id', $this->_values
)
494 $financialTypeID = CRM_Contribute_PseudoConstant
::financialType($this->_values
['financial_type_id']);
495 CRM_Financial_BAO_FinancialType
::checkPermissionedLineItems($this->_id
, 'edit');
496 if (!CRM_Core_Permission
::check('edit contributions of type ' . $financialTypeID)) {
497 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
502 //tax rate from financialType
503 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant
::getTaxRates()));
504 $this->assign('currencies', json_encode(CRM_Core_OptionGroup
::values('currencies_enabled')));
506 // build price set form.
507 $buildPriceSet = FALSE;
508 $invoicing = CRM_Invoicing_Utils
::isInvoicingEnabled();
509 $this->assign('invoicing', $invoicing);
511 $buildRecurBlock = FALSE;
513 // display tax amount on edit contribution page
514 if ($invoicing && $this->_action
& CRM_Core_Action
::UPDATE
&& isset($this->_values
['tax_amount'])) {
515 $this->assign('totalTaxAmount', $this->_values
['tax_amount']);
518 if (empty($this->_lineItems
) &&
519 ($this->_priceSetId ||
!empty($_POST['price_set_id']))
521 $buildPriceSet = TRUE;
522 $getOnlyPriceSetElements = TRUE;
523 if (!$this->_priceSetId
) {
524 $this->_priceSetId
= $_POST['price_set_id'];
525 $getOnlyPriceSetElements = FALSE;
528 $this->set('priceSetId', $this->_priceSetId
);
529 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
531 // get only price set form elements.
532 if ($getOnlyPriceSetElements) {
536 // use to build form during form rule.
537 $this->assign('buildPriceSet', $buildPriceSet);
539 $defaults = $this->_values
;
540 $additionalDetailFields = [
544 'non_deductible_amount',
547 foreach ($additionalDetailFields as $key) {
548 if (!empty($defaults[$key])) {
549 $defaults['hidden_AdditionalDetail'] = 1;
554 if ($this->_productDAO
) {
555 if ($this->_productDAO
->product_id
) {
556 $defaults['hidden_Premium'] = 1;
560 if ($this->_noteID
&&
561 !CRM_Utils_System
::isNull($this->_values
['note'])
563 $defaults['hidden_AdditionalDetail'] = 1;
567 if (empty($this->_payNow
)) {
568 $paneNames[ts('Additional Details')] = 'AdditionalDetail';
571 //Add Premium pane only if Premium is exists.
572 $dao = new CRM_Contribute_DAO_Product();
575 if ($dao->find(TRUE) && empty($this->_payNow
)) {
576 $paneNames[ts('Premium Information')] = 'Premium';
579 $this->payment_instrument_id
= CRM_Utils_Array
::value('payment_instrument_id', $defaults, $this->getDefaultPaymentInstrumentId());
580 if (CRM_Core_Payment_Form
::buildPaymentForm($this, $this->_paymentProcessor
, FALSE, TRUE, $this->payment_instrument_id
) == TRUE) {
581 if (!empty($this->_recurPaymentProcessors
)) {
582 $buildRecurBlock = TRUE;
584 // ppID denotes a pledge payment.
585 foreach ($this->_paymentProcessors
as $processor) {
586 if (!empty($processor['is_recur']) && !empty($processor['object']) && $processor['object']->supports('recurContributionsForPledges')) {
587 $buildRecurBlock = TRUE;
590 $buildRecurBlock = FALSE;
593 if ($buildRecurBlock) {
594 CRM_Contribute_Form_Contribution_Main
::buildRecur($this);
595 $this->setDefaults(['is_recur' => 0]);
596 $this->assign('buildRecurBlock', TRUE);
600 $this->addPaymentProcessorSelect(FALSE, $buildRecurBlock);
602 foreach ($paneNames as $name => $type) {
603 $allPanes[$name] = $this->generatePane($type, $defaults);
606 $qfKey = $this->controller
->_key
;
607 $this->assign('qfKey', $qfKey);
608 $this->assign('allPanes', $allPanes);
610 $this->addFormRule(['CRM_Contribute_Form_Contribution', 'formRule'], $this);
612 if ($this->_formType
) {
613 $this->assign('formType', $this->_formType
);
617 $this->applyFilter('__ALL__', 'trim');
619 //need to assign custom data type and subtype to the template
620 $this->assign('customDataType', 'Contribution');
621 $this->assign('customDataSubType', $this->_contributionType
);
622 $this->assign('entityID', $this->_id
);
624 if ($this->_context
== 'standalone') {
625 $this->addEntityRef('contact_id', ts('Contact'), [
627 'api' => ['extra' => ['email']],
631 $attributes = CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Contribution');
633 // Check permissions for financial type first
634 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes, $this->_action
);
635 if (empty($financialTypes)) {
636 CRM_Core_Error
::statusBounce(ts('You do not have all the permissions needed for this page.'));
638 $financialType = $this->add('select', 'financial_type_id',
639 ts('Financial Type'),
640 ['' => ts('- select -')] +
$financialTypes,
642 ['onChange' => "CRM.buildCustomData( 'Contribution', this.value );"]
645 $paymentInstrument = FALSE;
647 // payment_instrument isn't required in edit and will not be present when payment block is enabled.
648 $required = $this->_id ?
FALSE : TRUE;
649 $checkPaymentID = array_search('Check', CRM_Contribute_PseudoConstant
::paymentInstrument('name'));
650 $paymentInstrument = $this->add('select', 'payment_instrument_id',
651 ts('Payment Method'),
652 ['' => ts('- select -')] + CRM_Contribute_PseudoConstant
::paymentInstrument(),
653 $required, ['onChange' => "return showHideByValue('payment_instrument_id','{$checkPaymentID}','checkNumber','table-row','select',false);"]
657 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), ['class' => 'twelve'] +
$attributes['trxn_id']);
659 //add receipt for offline contribution
660 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
662 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
664 $component = 'contribution';
665 $componentDetails = [];
667 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
668 if (!empty($componentDetails['membership'])) {
669 $component = 'membership';
671 elseif (!empty($componentDetails['participant'])) {
672 $component = 'participant';
676 $component = 'pledge';
678 $status = CRM_Contribute_BAO_Contribution_Utils
::getContributionStatuses($component, $this->_id
);
680 // define the status IDs that show the cancellation info, see CRM-17589
681 $cancelInfo_show_ids = [];
682 foreach (array_keys($status) as $status_id) {
683 if (CRM_Contribute_BAO_Contribution
::isContributionStatusNegative($status_id)) {
684 $cancelInfo_show_ids[] = "'$status_id'";
687 $this->assign('cancelInfo_show_ids', implode(',', $cancelInfo_show_ids));
689 $statusElement = $this->add('select', 'contribution_status_id',
690 ts('Contribution Status'),
695 $currencyFreeze = FALSE;
696 if (!empty($this->_payNow
) && ($this->_action
& CRM_Core_Action
::UPDATE
)) {
697 $statusElement->freeze();
698 $currencyFreeze = TRUE;
699 $attributes['total_amount']['readonly'] = TRUE;
702 // CRM-16189, add Revenue Recognition Date
703 if (Civi
::settings()->get('deferred_revenue_enabled')) {
704 $revenueDate = $this->add('date', 'revenue_recognition_date', ts('Revenue Recognition Date'), CRM_Core_SelectValues
::date(NULL, 'M Y', NULL, 5));
705 if ($this->_id
&& !CRM_Contribute_BAO_Contribution
::allowUpdateRevenueRecognitionDate($this->_id
)) {
706 $revenueDate->freeze();
711 $this->addField('receive_date', ['entity' => 'contribution'], !$this->_mode
, FALSE);
712 $this->addField('receipt_date', ['entity' => 'contribution'], FALSE, FALSE);
713 $this->addField('cancel_date', ['entity' => 'contribution', 'label' => ts('Cancelled / Refunded Date')], FALSE, FALSE);
715 if ($this->_online
) {
716 $this->assign('hideCalender', TRUE);
719 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
722 if (empty($this->_lineItems
)) {
723 $buildPriceSet = FALSE;
724 $priceSets = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute');
725 if (!empty($priceSets) && !$this->_ppID
) {
726 $buildPriceSet = TRUE;
729 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
730 // and if we already have line items for that participant. CRM-5095
731 if ($buildPriceSet && $this->_id
) {
732 $pledgePaymentId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
737 if ($pledgePaymentId) {
738 $buildPriceSet = FALSE;
740 if ($participantID = CRM_Utils_Array
::value('participant', $componentDetails)) {
741 $participantLI = CRM_Price_BAO_LineItem
::getLineItems($participantID);
742 if (!CRM_Utils_System
::isNull($participantLI)) {
743 $buildPriceSet = FALSE;
748 $hasPriceSets = FALSE;
749 if ($buildPriceSet) {
750 $hasPriceSets = TRUE;
751 // CRM-16451: set financial type of 'Price Set' in back office contribution
752 // instead of selecting manually
753 $financialTypeIds = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute', 'financial_type_id');
754 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
756 '' => ts('Choose price set'),
758 NULL, ['onchange' => "buildAmount( this.value, " . json_encode($financialTypeIds) . ");"]
760 if ($this->_online
&& !($this->_action
& CRM_Core_Action
::UPDATE
)) {
764 $this->assign('hasPriceSets', $hasPriceSets);
765 if (!($this->_action
& CRM_Core_Action
::UPDATE
)) {
766 if ($this->_online ||
$this->_ppID
) {
767 $attributes['total_amount'] = array_merge($attributes['total_amount'], [
769 'style' => "background-color:#EBECE4",
772 '1' => ts('Adjust Pledge Payment Schedule?'),
773 '2' => ts('Adjust Total Pledge Amount?'),
775 $this->addRadio('option_type',
781 $currencyFreeze = TRUE;
785 $totalAmount = $this->addMoney('total_amount',
787 ($hasPriceSets) ?
FALSE : TRUE,
788 $attributes['total_amount'],
789 TRUE, 'currency', NULL, $currencyFreeze
793 $this->add('text', 'source', ts('Source'), CRM_Utils_Array
::value('source', $attributes));
795 // CRM-7362 --add campaigns.
796 CRM_Campaign_BAO_Campaign
::addCampaign($this, CRM_Utils_Array
::value('campaign_id', $this->_values
));
798 if (empty($this->_payNow
)) {
799 CRM_Contribute_Form_SoftCredit
::buildQuickForm($this);
804 $js = ['onclick' => "return verify( );"];
807 $mailingInfo = Civi
::settings()->get('mailing_backend');
808 $this->assign('outBound_option', $mailingInfo['outBound_option']);
813 'name' => ts('Save'),
819 'name' => ts('Save and New'),
825 'name' => ts('Cancel'),
829 // if contribution is related to membership or participant freeze Financial Type, Amount
831 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
832 $isCancelledStatus = ($this->_values
['contribution_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Cancelled'));
834 if (!empty($componentDetails['membership']) ||
835 !empty($componentDetails['participant']) ||
836 // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
837 // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
841 $totalAmount->freeze();
842 $this->getElement('currency')->freeze();
844 if ($isCancelledStatus) {
845 $paymentInstrument->freeze();
848 $financialType->freeze();
849 $this->assign('freezeFinancialType', TRUE);
853 if ($this->_action
& CRM_Core_Action
::VIEW
) {
861 * @param array $fields
862 * The input form values.
863 * @param array $files
864 * The uploaded files if any.
868 * true if no errors, else array of errors
870 public static function formRule($fields, $files, $self) {
872 // Check for Credit Card Contribution.
874 if (empty($fields['payment_processor_id'])) {
875 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
878 // validate payment instrument (e.g. credit card number)
879 CRM_Core_Payment_Form
::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, NULL);
883 // Do the amount validations.
884 if (empty($fields['total_amount']) && empty($self->_lineItems
)) {
885 if ($priceSetId = CRM_Utils_Array
::value('price_set_id', $fields)) {
886 CRM_Price_BAO_PriceField
::priceSetValidation($priceSetId, $fields, $errors);
890 $softErrors = CRM_Contribute_Form_SoftCredit
::formRule($fields, $errors, $self);
892 //CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
893 CRM_Contribute_BAO_ContributionRecur
::validateRecurContribution($fields, $files, $self, $errors);
895 // Form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
896 if (($self->_action
& CRM_Core_Action
::UPDATE
)
898 && $self->_values
['contribution_status_id'] != $fields['contribution_status_id']
900 CRM_Contribute_BAO_Contribution
::checkStatusValidation($self->_values
, $fields, $errors);
902 // CRM-16015, add form-rule to restrict change of financial type if using price field of different financial type
903 if (($self->_action
& CRM_Core_Action
::UPDATE
)
905 && $self->_values
['financial_type_id'] != $fields['financial_type_id']
907 CRM_Contribute_BAO_Contribution
::checkFinancialTypeChange(NULL, $self->_id
, $errors);
909 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
910 if (!empty($fields['fee_amount']) && !empty($fields['financial_type_id']) && $financialType = CRM_Contribute_BAO_Contribution
::validateFinancialType($fields['financial_type_id'])) {
911 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
914 // $trxn_id must be unique CRM-13919
915 if (!empty($fields['trxn_id'])) {
916 $queryParams = [1 => [$fields['trxn_id'], 'String']];
917 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
919 $queryParams[2] = [(int) $self->_id
, 'Integer'];
920 $query .= ' and id !=%2';
922 $tCnt = CRM_Core_DAO
::singleValueQuery($query, $queryParams);
924 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', [1 => $fields['trxn_id']]);
927 if (!empty($fields['revenue_recognition_date'])
928 && count(array_filter($fields['revenue_recognition_date'])) == 1
930 $errors['revenue_recognition_date'] = ts('Month and Year are required field for Revenue Recognition.');
934 CRM_Financial_BAO_FinancialAccount
::checkFinancialTypeHasDeferred($fields, $self->_id
, $self->_priceSet
['fields']);
936 catch (CRM_Core_Exception
$e) {
937 $errors['financial_type_id'] = ' ';
938 $errors['_qf_default'] = $e->getMessage();
940 $errors = array_merge($errors, $softErrors);
945 * Process the form submission.
947 public function postProcess() {
948 if ($this->_action
& CRM_Core_Action
::DELETE
) {
949 CRM_Contribute_BAO_Contribution
::deleteContribution($this->_id
);
950 CRM_Core_Session
::singleton()->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
951 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
955 // Get the submitted form values.
956 $submittedValues = $this->controller
->exportValues($this->_name
);
959 $contribution = $this->submit($submittedValues, $this->_action
, $this->_ppID
);
961 catch (PaymentProcessorException
$e) {
962 // Set the contribution mode.
963 $urlParams = "action=add&cid={$this->_contactID}";
965 $urlParams .= "&mode={$this->_mode}";
967 if (!empty($this->_ppID
)) {
968 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
971 CRM_Core_Error
::statusBounce($e->getMessage(), $urlParams, ts('Payment Processor Error'));
973 $session = CRM_Core_Session
::singleton();
974 $buttonName = $this->controller
->getButtonName();
975 if ($this->_context
== 'standalone') {
976 if ($buttonName == $this->getButtonName('upload', 'new')) {
977 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contribute/add',
978 'reset=1&action=add&context=standalone'
982 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
983 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
987 elseif ($this->_context
== 'contribution' && $this->_mode
&& $buttonName == $this->getButtonName('upload', 'new')) {
988 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
989 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
992 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
993 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
994 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
998 //store contribution ID if not yet set (on create)
999 if (empty($this->_id
) && !empty($contribution->id
)) {
1000 $this->_id
= $contribution->id
;
1002 if (!empty($this->_id
) && CRM_Core_Permission
::access('CiviMember')) {
1003 $membershipPaymentCount = civicrm_api3('MembershipPayment', 'getCount', ['contribution_id' => $this->_id
]);
1004 if ($membershipPaymentCount) {
1005 $this->ajaxResponse
['updateTabs']['#tab_member'] = CRM_Contact_BAO_Contact
::getCountComponent('membership', $this->_contactID
);
1008 if (!empty($this->_id
) && CRM_Core_Permission
::access('CiviEvent')) {
1009 $participantPaymentCount = civicrm_api3('ParticipantPayment', 'getCount', ['contribution_id' => $this->_id
]);
1010 if ($participantPaymentCount) {
1011 $this->ajaxResponse
['updateTabs']['#tab_participant'] = CRM_Contact_BAO_Contact
::getCountComponent('participant', $this->_contactID
);
1017 * Process credit card payment.
1019 * @param array $submittedValues
1020 * @param array $lineItem
1022 * @param int $contactID
1025 * @return bool|\CRM_Contribute_DAO_Contribution
1027 * @throws \CRM_Core_Exception
1028 * @throws \Civi\Payment\Exception\PaymentProcessorException
1029 * @throws \CiviCRM_API3_Exception
1031 protected function processCreditCard($submittedValues, $lineItem, $contactID) {
1032 $isTest = ($this->_mode
== 'test') ?
1 : 0;
1033 // CRM-12680 set $_lineItem if its not set
1034 // @todo - I don't believe this would ever BE set. I can't find anywhere in the code.
1035 // It would be better to pass line item out to functions than $this->_lineItem as
1036 // we don't know what is being changed where.
1037 if (empty($this->_lineItem
) && !empty($lineItem)) {
1038 $this->_lineItem
= $lineItem;
1041 $this->_paymentObject
= Civi\Payment\System
::singleton()->getById($submittedValues['payment_processor_id']);
1042 $this->_paymentProcessor
= $this->_paymentObject
->getPaymentProcessor();
1044 // Set source if not set
1045 if (empty($submittedValues['source'])) {
1046 $userID = CRM_Core_Session
::singleton()->get('userID');
1047 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1050 $submittedValues['source'] = ts('Submit Credit Card Payment by: %1', [1 => $userSortName]);
1053 $params = $submittedValues;
1054 $this->_params
= array_merge($this->_params
, $submittedValues);
1056 // Mapping requiring documentation.
1057 $this->_params
['payment_processor'] = $submittedValues['payment_processor_id'];
1059 $now = date('YmdHis');
1061 $this->_contributorEmail
= $this->userEmail
;
1062 $this->_contributorContactID
= $contactID;
1063 $this->processBillingAddress();
1064 if (!empty($params['source'])) {
1065 unset($params['source']);
1068 $this->_params
['amount'] = $this->_params
['total_amount'];
1069 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
1070 // function to get correct amount level consistently. Remove setting of the amount level in
1071 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
1072 // to cover all variants.
1073 $this->_params
['amount_level'] = 0;
1074 $this->_params
['description'] = ts("Contribution submitted by a staff person using contributor's credit card");
1075 $this->_params
['currencyID'] = CRM_Utils_Array
::value('currency',
1077 CRM_Core_Config
::singleton()->defaultCurrency
1080 $this->_params
['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $params);
1081 $this->_params
['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $params);
1082 $this->_params
['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $params);
1084 //Add common data to formatted params
1085 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
1087 if (empty($this->_params
['invoice_id'])) {
1088 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
1091 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
1094 // At this point we've created a contact and stored its address etc
1095 // all the payment processors expect the name and address to be in the
1096 // so we copy stuff over to first_name etc.
1097 $paymentParams = $this->_params
;
1098 $paymentParams['contactID'] = $contactID;
1099 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
1101 $financialType = new CRM_Financial_DAO_FinancialType();
1102 $financialType->id
= $params['financial_type_id'];
1103 $financialType->find(TRUE);
1105 // Add some financial type details to the params list
1106 // if folks need to use it.
1107 $paymentParams['contributionType_name'] = $this->_params
['contributionType_name'] = $financialType->name
;
1108 $paymentParams['contributionPageID'] = NULL;
1110 if (!empty($this->_params
['is_email_receipt'])) {
1111 $paymentParams['email'] = $this->userEmail
;
1112 $paymentParams['is_email_receipt'] = 1;
1115 $paymentParams['is_email_receipt'] = 0;
1116 $this->_params
['is_email_receipt'] = 0;
1118 if (!empty($this->_params
['receive_date'])) {
1119 $paymentParams['receive_date'] = $this->_params
['receive_date'];
1122 if (!empty($this->_params
['is_email_receipt'])) {
1123 $this->_params
['receipt_date'] = $now;
1126 $this->set('params', $this->_params
);
1128 $this->assign('receive_date', $this->_params
['receive_date']);
1130 // Result has all the stuff we need
1131 // lets archive it to a financial transaction
1132 if ($financialType->is_deductible
) {
1133 $this->assign('is_deductible', TRUE);
1134 $this->set('is_deductible', TRUE);
1136 $contributionParams = [
1137 'id' => CRM_Utils_Array
::value('contribution_id', $this->_params
),
1138 'contact_id' => $contactID,
1139 'line_item' => $lineItem,
1140 'is_test' => $isTest,
1141 'campaign_id' => CRM_Utils_Array
::value('campaign_id', $this->_params
),
1142 'contribution_page_id' => CRM_Utils_Array
::value('contribution_page_id', $this->_params
),
1143 'source' => CRM_Utils_Array
::value('source', $paymentParams, CRM_Utils_Array
::value('description', $paymentParams)),
1144 'thankyou_date' => CRM_Utils_Array
::value('thankyou_date', $this->_params
),
1146 $contributionParams['payment_instrument_id'] = $this->_paymentProcessor
['payment_instrument_id'];
1148 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processFormContribution($this,
1151 $contributionParams,
1155 CRM_Utils_Array
::value('is_recur', $this->_params
)
1158 $paymentParams['contributionID'] = $contribution->id
;
1159 $paymentParams['contributionTypeID'] = $contribution->financial_type_id
;
1160 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
1161 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1163 if ($paymentParams['amount'] > 0.0) {
1164 // force a re-get of the payment processor in case the form changed it, CRM-7179
1165 // NOTE - I expect this is obsolete.
1166 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
1168 $completeStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
1169 $result = $payment->doPayment($paymentParams, 'contribute');
1170 $this->assign('trxn_id', $result['trxn_id']);
1171 $contribution->trxn_id
= $result['trxn_id'];
1172 /* Our scenarios here are
1173 * 1) the payment failed & an Exception should have been thrown
1174 * 2) the payment succeeded but the payment is not immediate (for example a recurring payment
1175 * with a delayed start)
1176 * 3) the payment succeeded with an immediate payment.
1178 * The doPayment function ensures that payment_status_id is always set
1179 * as historically we have had to guess from the context - ie doDirectPayment
1180 * = error or success, unless it is a recurring contribution in which case it is pending.
1182 if ($result['payment_status_id'] == $completeStatusId) {
1184 civicrm_api3('contribution', 'completetransaction', [
1185 'id' => $contribution->id
,
1186 'trxn_id' => $result['trxn_id'],
1187 'payment_processor_id' => $this->_paymentProcessor
['id'],
1188 'is_transactional' => FALSE,
1189 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $result),
1190 'card_type_id' => CRM_Utils_Array
::value('card_type_id', $paymentParams),
1191 'pan_truncation' => CRM_Utils_Array
::value('pan_truncation', $paymentParams),
1192 'is_email_receipt' => FALSE,
1194 // This has now been set to 1 in the DB - declare it here also
1195 $contribution->contribution_status_id
= 1;
1197 catch (CiviCRM_API3_Exception
$e) {
1198 if ($e->getErrorCode() != 'contribution_completed') {
1199 throw new CRM_Core_Exception('Failed to update contribution in database');
1204 // Save the trxn_id.
1205 $contribution->save();
1208 catch (PaymentProcessorException
$e) {
1209 CRM_Contribute_BAO_Contribution
::failPayment($contribution->id
, $paymentParams['contactID'], $e->getMessage());
1210 throw new PaymentProcessorException($e->getMessage());
1213 // Send receipt mail.
1214 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1215 if ($contribution->id
&& !empty($this->_params
['is_email_receipt'])) {
1216 $this->_params
['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $result);
1217 $this->_params
['contact_id'] = $contactID;
1218 $this->_params
['contribution_id'] = $contribution->id
;
1219 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $this->_params
, TRUE)) {
1220 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1224 return $contribution;
1228 * Generate the data to construct a snippet based pane.
1230 * This form also assigns the showAdditionalInfo var based on historical code.
1231 * This appears to mean 'there is a pane to show'.
1233 * @param string $type
1234 * Type of Pane - this is generally used to determine the function name used to build it
1235 * - e.g CreditCard, AdditionalDetail
1236 * @param array $defaults
1239 * We aim to further refactor & simplify this but currently
1241 * - should additional info be shown?
1243 protected function generatePane($type, $defaults) {
1244 $urlParams = "snippet=4&formType={$type}";
1246 $urlParams .= "&mode={$this->_mode}";
1250 if ($type == 'CreditCard' ||
1251 $type == 'DirectDebit'
1257 'url' => CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams),
1262 // See if we need to include this paneName in the current form.
1263 if ($this->_formType
== $type ||
!empty($_POST["hidden_{$type}"]) ||
1264 CRM_Utils_Array
::value("hidden_{$type}", $defaults)
1266 $this->assign('showAdditionalInfo', TRUE);
1267 $pane['open'] = 'true';
1270 if ($type == 'CreditCard' ||
$type == 'DirectDebit') {
1271 // @todo would be good to align tpl name with form name...
1272 // @todo document why this hidden variable is required.
1273 $this->add('hidden', 'hidden_' . $type, 1);
1277 $additionalInfoFormFunction = 'build' . $type;
1278 CRM_Contribute_Form_AdditionalInfo
::$additionalInfoFormFunction($this);
1284 * Wrapper for unit testing the post process submit function.
1286 * (If we expose through api we can get default additions 'for free').
1288 * @param array $params
1289 * @param int $action
1290 * @param string|null $creditCardMode
1292 * @return CRM_Contribute_BAO_Contribution
1294 * @throws \CRM_Core_Exception
1295 * @throws \CiviCRM_API3_Exception
1296 * @throws \Civi\Payment\Exception\PaymentProcessorException
1298 public function testSubmit($params, $action, $creditCardMode = NULL) {
1300 'soft_credit_contact_id' => [],
1301 'receive_date' => date('Y-m-d H:i:s'),
1302 'receipt_date' => '',
1303 'cancel_date' => '',
1304 'hidden_Premium' => 1,
1307 if (!empty($params['id'])) {
1308 $existingContribution = civicrm_api3('contribution', 'getsingle', [
1309 'id' => $params['id'],
1311 $this->_id
= $params['id'];
1312 $this->_values
= $existingContribution;
1313 if (CRM_Contribute_BAO_Contribution
::checkContributeSettings('invoicing')) {
1314 $this->_values
['tax_amount'] = civicrm_api3('contribution', 'getvalue', [
1315 'id' => $params['id'],
1316 'return' => 'tax_amount',
1321 $existingContribution = [];
1324 $this->_defaults
['contribution_status_id'] = CRM_Utils_Array
::value('contribution_status_id',
1325 $existingContribution
1328 $this->_defaults
['total_amount'] = CRM_Utils_Array
::value('total_amount',
1329 $existingContribution
1332 if ($creditCardMode) {
1333 $this->_mode
= $creditCardMode;
1336 // Required because processCreditCard calls set method on this.
1337 $_SERVER['REQUEST_METHOD'] = 'GET';
1338 $this->controller
= new CRM_Core_Controller();
1340 CRM_Contribute_Form_AdditionalInfo
::buildPremium($this);
1342 $this->_fields
= [];
1343 return $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array
::value('pledge_payment_id', $params));
1348 * @param array $submittedValues
1350 * @param int $action
1352 * - CRM_Core_Action::UPDATE
1354 * @param $pledgePaymentID
1356 * @return \CRM_Contribute_BAO_Contribution
1358 * @throws \CRM_Core_Exception
1359 * @throws \CiviCRM_API3_Exception
1360 * @throws \Civi\Payment\Exception\PaymentProcessorException
1362 protected function submit($submittedValues, $action, $pledgePaymentID) {
1363 $pId = $contribution = $isRelatedId = FALSE;
1364 $this->_params
= $submittedValues;
1365 $this->beginPostProcess();
1366 // reassign submitted form values if the any information is formatted via beginPostProcess
1367 $submittedValues = $this->_params
;
1369 if (!empty($submittedValues['price_set_id']) && $action & CRM_Core_Action
::UPDATE
) {
1370 $line = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution');
1371 $lineID = key($line);
1372 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array
::value('price_field_id', $line[$lineID]), 'price_set_id');
1373 $quickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1374 // Why do we do this? Seems like a like a wrapper for old functionality - but single line price sets & quick
1375 // config should be treated the same.
1377 CRM_Price_BAO_LineItem
::deleteLineItems($this->_id
, 'civicrm_contribution');
1381 // Process price set and get total amount and line items.
1383 $priceSetId = CRM_Utils_Array
::value('price_set_id', $submittedValues);
1384 if (empty($priceSetId) && !$this->_id
) {
1385 $this->_priceSetId
= $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1386 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
1387 $fieldID = key($this->_priceSet
['fields']);
1388 $fieldValueId = key($this->_priceSet
['fields'][$fieldID]['options']);
1389 $this->_priceSet
['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1390 $submittedValues['price_' . $fieldID] = 1;
1393 // Every contribution has a price-set - the only reason it shouldn't be set is if we are dealing with
1394 // quick config (very very arguably) & yet we see that this could still be quick config so this should be understood
1395 // as a point of fragility rather than a logical 'if' clause.
1397 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
1398 $submittedValues, $lineItem[$priceSetId], NULL, $priceSetId);
1399 // Unset tax amount for offline 'is_quick_config' contribution.
1400 // @todo WHY - quick config was conceived as a quick way to configure contribution forms.
1401 // this is an example of 'other' functionality being hung off it.
1402 if ($this->_priceSet
['is_quick_config'] &&
1403 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant
::getTaxRates())
1405 unset($submittedValues['tax_amount']);
1407 $submittedValues['total_amount'] = CRM_Utils_Array
::value('amount', $submittedValues);
1411 if ($this->_compId
) {
1412 if ($this->_context
== 'participant') {
1413 $pId = $this->_compId
;
1415 elseif ($this->_context
== 'membership') {
1416 $isRelatedId = TRUE;
1419 $pId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id
, 'participant_id', 'contribution_id');
1423 $contributionDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1424 if (array_key_exists('membership', $contributionDetails)) {
1425 $isRelatedId = TRUE;
1427 elseif (array_key_exists('participant', $contributionDetails)) {
1428 $pId = $contributionDetails['participant'];
1431 if (!empty($this->_payNow
)) {
1432 $this->_params
['contribution_id'] = $this->_id
;
1436 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id
) {
1437 // CRM-10117 update the line items for participants.
1438 // @todo - if we are completing a contribution then the api call
1439 // civicrm_api3('Contribution', 'completetransaction') should take care of
1440 // all associated updates rather than replicating them on the form layer.
1442 $entityTable = 'participant';
1444 $isRelatedId = FALSE;
1445 $participantParams = [
1446 'fee_amount' => $submittedValues['total_amount'],
1449 CRM_Event_BAO_Participant
::add($participantParams);
1450 if (empty($this->_lineItems
)) {
1451 $this->_lineItems
[] = CRM_Price_BAO_LineItem
::getLineItems($entityID, 'participant', TRUE);
1455 $entityTable = 'contribution';
1456 $entityID = $this->_id
;
1459 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, $entityTable, FALSE, TRUE, $isRelatedId);
1460 foreach (array_keys($lineItems) as $id) {
1461 $lineItems[$id]['id'] = $id;
1463 $itemId = key($lineItems);
1464 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1465 $this->_priceSetId
= CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1468 // @todo see above - new functionality has been inappropriately added to the quick config concept
1469 // and new functionality has been added onto the form layer rather than the BAO :-(
1470 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1471 //CRM-16833: Ensure tax is applied only once for membership conribution, when status changed.(e.g Pending to Completed).
1472 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1473 if (!(CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails))) {
1474 if (!($this->_action
& CRM_Core_Action
::UPDATE
&& (($this->_defaults
['contribution_status_id'] != $submittedValues['contribution_status_id'])))) {
1475 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule
::cleanMoney(CRM_Utils_Array
::value('total_amount', $submittedValues));
1479 // Update line total and total amount with tax on edit.
1480 $financialItemsId = CRM_Core_PseudoConstant
::getTaxRates();
1481 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1482 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1485 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1486 $submittedValues['tax_amount'] = 'null';
1488 if ($lineItems[$itemId]['tax_rate']) {
1489 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total'];
1490 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] +
$lineItems[$itemId]['tax_amount'];
1491 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1494 // CRM-10117 update the line items for participants.
1495 if (!empty($lineItems[$itemId]['price_field_id'])) {
1496 $lineItem[$this->_priceSetId
] = $lineItems;
1501 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1504 //CRM-11529 for quick config back office transactions
1505 //when financial_type_id is passed in form, update the
1506 //line items with the financial type selected in form
1507 // NOTE that this IS still a legitimate use of 'quick-config' for contributions under the current DB but
1508 // we should look at having a price field per contribution type & then there would be little reason
1509 // for the back-office contribution form postProcess to know if it is a quick-config form.
1510 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array
::value($this->_priceSetId
, $lineItem)
1512 foreach ($lineItem[$this->_priceSetId
] as &$values) {
1513 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1517 if (!isset($submittedValues['total_amount'])) {
1518 $submittedValues['total_amount'] = CRM_Utils_Array
::value('total_amount', $this->_values
);
1519 // Avoid tax amount deduction on edit form and keep it original, because this will lead to error described in CRM-20676
1521 $submittedValues['total_amount'] -= CRM_Utils_Array
::value('tax_amount', $this->_values
, 0);
1524 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
1526 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
1527 if ($this->_id
&& count($isEmpty) == 1 && key($isEmpty) == NULL) {
1528 civicrm_api3('ContributionSoft', 'get', ['contribution_id' => $this->_id
, 'pcp_id' => NULL, 'api.ContributionSoft.delete' => 1]);
1531 // set the contact, when contact is selected
1532 if (!empty($submittedValues['contact_id'])) {
1533 $this->_contactID
= $submittedValues['contact_id'];
1536 $formValues = $submittedValues;
1538 // Credit Card Contribution.
1540 $paramsSetByPaymentProcessingSubsystem = [
1542 'payment_instrument_id',
1543 'contribution_status_id',
1547 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1548 if (isset($formValues[$key])) {
1549 unset($formValues[$key]);
1552 $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID
);
1553 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1554 $formValues[$key] = $contribution->$key;
1558 // Offline Contribution.
1559 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1561 // get the required field value only.
1564 'contact_id' => $this->_contactID
,
1565 'currency' => $this->getCurrency($submittedValues),
1566 'skipCleanMoney' => TRUE,
1570 //format soft-credit/pcp param first
1571 CRM_Contribute_BAO_ContributionSoft
::formatSoftCreditParams($submittedValues, $this);
1572 $params = array_merge($params, $submittedValues);
1575 'financial_type_id',
1576 'contribution_status_id',
1577 'payment_instrument_id',
1584 foreach ($fields as $f) {
1585 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1588 $params['revenue_recognition_date'] = NULL;
1589 if (!empty($formValues['revenue_recognition_date'])
1590 && count(array_filter($formValues['revenue_recognition_date'])) == 2
1592 $params['revenue_recognition_date'] = CRM_Utils_Date
::processDate(
1593 '01-' . implode('-', $formValues['revenue_recognition_date'])
1597 if (!empty($formValues['is_email_receipt'])) {
1598 $params['receipt_date'] = date("Y-m-d");
1601 if (CRM_Contribute_BAO_Contribution
::isContributionStatusNegative($params['contribution_status_id'])
1603 if (CRM_Utils_System
::isNull(CRM_Utils_Array
::value('cancel_date', $params))) {
1604 $params['cancel_date'] = date('YmdHis');
1608 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1611 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1612 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1613 if ($params['contribution_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending')) {
1614 $params['is_pay_later'] = 1;
1616 elseif ($params['contribution_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed')) {
1617 $params['is_pay_later'] = 0;
1620 // Add Additional common information to formatted params.
1621 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($formValues, $params, $this);
1623 $params['contribution_mode'] = 'participant';
1624 $params['participant_id'] = $pId;
1625 $params['skipLineItem'] = 1;
1627 elseif ($isRelatedId) {
1628 $params['contribution_mode'] = 'membership';
1630 $params['line_item'] = $lineItem;
1631 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array
::value('id', $this->_paymentProcessor
);
1632 $params['tax_amount'] = CRM_Utils_Array
::value('tax_amount', $submittedValues, CRM_Utils_Array
::value('tax_amount', $this->_values
));
1633 //create contribution.
1634 if ($isQuickConfig) {
1635 $params['is_quick_config'] = 1;
1637 $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
1639 // we are already handling note below, so to avoid duplicate notes against $contribution
1640 if (!empty($params['note']) && !empty($submittedValues['note'])) {
1641 unset($params['note']);
1643 $contribution = CRM_Contribute_BAO_Contribution
::create($params);
1645 // process associated membership / participant, CRM-4395
1646 if ($contribution->id
&& $action & CRM_Core_Action
::UPDATE
) {
1647 $this->statusMessage
[] = CRM_Contribute_BAO_Contribution
::transitionComponentWithReturnMessage($contribution->id
,
1648 $contribution->contribution_status_id
,
1649 CRM_Utils_Array
::value('contribution_status_id',
1652 $contribution->receive_date
1656 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1658 $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
1660 //send receipt mail.
1661 if ($contribution->id
&& !empty($formValues['is_email_receipt'])) {
1662 $formValues['contact_id'] = $this->_contactID
;
1663 $formValues['contribution_id'] = $contribution->id
;
1665 $formValues +
= CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
);
1667 // to get 'from email id' for send receipt
1668 $this->fromEmailId
= CRM_Utils_Array
::value('from_email_address', $formValues);
1669 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $formValues)) {
1670 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1674 $this->statusMessageTitle
= ts('Saved');
1678 if ($contribution->id
&& isset($formValues['product_name'][0])) {
1679 CRM_Contribute_Form_AdditionalInfo
::processPremium($submittedValues, $contribution->id
,
1680 $this->_premiumID
, $this->_options
1684 if ($contribution->id
&& array_key_exists('note', $submittedValues)) {
1685 CRM_Contribute_Form_AdditionalInfo
::processNote($submittedValues, $this->_contactID
, $contribution->id
, $this->_noteID
);
1688 CRM_Core_Session
::setStatus(implode(' ', $this->statusMessage
), $this->statusMessageTitle
, 'success');
1690 CRM_Contribute_BAO_Contribution
::updateRelatedPledge(
1694 (CRM_Utils_Array
::value('option_type', $formValues) == 2) ?
TRUE : FALSE,
1695 $formValues['total_amount'],
1696 CRM_Utils_Array
::value('total_amount', $this->_defaults
),
1697 $formValues['contribution_status_id'],
1698 CRM_Utils_Array
::value('contribution_status_id', $this->_defaults
)
1700 return $contribution;
1704 * Assign tax calculations to contribution receipts.
1706 * @param array $submittedValues
1707 * @param int $action
1708 * @param array $lineItem
1710 protected function invoicingPostProcessHook($submittedValues, $action, $lineItem) {
1712 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
1713 if (empty($invoiceSettings['invoicing'])) {
1717 $getTaxDetails = FALSE;
1719 foreach ($lineItem as $key => $value) {
1720 foreach ($value as $v) {
1721 if (isset($taxRate[(string) CRM_Utils_Array
::value('tax_rate', $v)])) {
1722 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $v);
1725 if (isset($v['tax_rate'])) {
1726 $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $v);
1727 $getTaxDetails = TRUE;
1733 if ($action & CRM_Core_Action
::UPDATE
) {
1734 if (isset($submittedValues['tax_amount'])) {
1735 $totalTaxAmount = $submittedValues['tax_amount'];
1738 $totalTaxAmount = $this->_values
['tax_amount'];
1740 $this->assign('totalTaxAmount', $totalTaxAmount);
1741 $this->assign('dataArray', $taxRate);
1744 if (!empty($submittedValues['price_set_id'])) {
1745 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1746 $this->assign('getTaxDetails', $getTaxDetails);
1747 $this->assign('dataArray', $taxRate);
1748 $this->assign('taxTerm', CRM_Utils_Array
::value('tax_term', $invoiceSettings));
1751 $this->assign('totalTaxAmount', CRM_Utils_Array
::value('tax_amount', $submittedValues));
1757 * Calculate non deductible amount.
1760 * if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1761 * if non_deductible_amount does NOT exist - then calculate it depending on:
1762 * $financialType->is_deductible and whether there is a product (premium).
1765 * @param $formValues
1769 protected function calculateNonDeductibleAmount($params, $formValues) {
1770 if (!empty($params['non_deductible_amount'])) {
1771 return $params['non_deductible_amount'];
1774 $priceSetId = CRM_Utils_Array
::value('price_set_id', $params);
1775 // return non-deductible amount if it is set at the price field option level
1776 if ($priceSetId && !empty($params['line_item'])) {
1777 $nonDeductibleAmount = CRM_Price_BAO_PriceSet
::getNonDeductibleAmountFromPriceSet($priceSetId, $params['line_item']);
1778 if (!empty($nonDeductibleAmount)) {
1779 return $nonDeductibleAmount;
1783 $financialType = new CRM_Financial_DAO_FinancialType();
1784 $financialType->id
= $params['financial_type_id'];
1785 $financialType->find(TRUE);
1787 if ($financialType->is_deductible
) {
1789 if (isset($formValues['product_name'][0])) {
1790 $selectProduct = $formValues['product_name'][0];
1792 // if there is a product - compare the value to the contribution amount
1793 if (isset($selectProduct)) {
1794 $productDAO = new CRM_Contribute_DAO_Product();
1795 $productDAO->id
= $selectProduct;
1796 $productDAO->find(TRUE);
1797 // product value exceeds contribution amount
1798 if ($params['total_amount'] < $productDAO->price
) {
1799 return $params['total_amount'];
1801 // product value does NOT exceed contribution amount
1803 return $productDAO->price
;
1806 // contribution is deductible - but there is no product
1811 // contribution is NOT deductible
1813 return $params['total_amount'];