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 (CRM_Utils_Array
::value('membership', $componentDetails)) {
669 $component = 'membership';
671 elseif (CRM_Utils_Array
::value('participant', $componentDetails)) {
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 (CRM_Utils_Array
::value('membership', $componentDetails) ||
835 CRM_Utils_Array
::value('participant', $componentDetails) ||
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
1026 * @throws \CRM_Core_Exception
1027 * @throws \Civi\Payment\Exception\PaymentProcessorException
1029 protected function processCreditCard($submittedValues, $lineItem, $contactID) {
1030 $isTest = ($this->_mode
== 'test') ?
1 : 0;
1031 // CRM-12680 set $_lineItem if its not set
1032 // @todo - I don't believe this would ever BE set. I can't find anywhere in the code.
1033 // It would be better to pass line item out to functions than $this->_lineItem as
1034 // we don't know what is being changed where.
1035 if (empty($this->_lineItem
) && !empty($lineItem)) {
1036 $this->_lineItem
= $lineItem;
1039 $this->_paymentObject
= Civi\Payment\System
::singleton()->getById($submittedValues['payment_processor_id']);
1040 $this->_paymentProcessor
= $this->_paymentObject
->getPaymentProcessor();
1042 // Set source if not set
1043 if (empty($submittedValues['source'])) {
1044 $userID = CRM_Core_Session
::singleton()->get('userID');
1045 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1048 $submittedValues['source'] = ts('Submit Credit Card Payment by: %1', [1 => $userSortName]);
1051 $params = $submittedValues;
1052 $this->_params
= array_merge($this->_params
, $submittedValues);
1054 // Mapping requiring documentation.
1055 $this->_params
['payment_processor'] = $submittedValues['payment_processor_id'];
1057 $now = date('YmdHis');
1059 $this->_contributorEmail
= $this->userEmail
;
1060 $this->_contributorContactID
= $contactID;
1061 $this->processBillingAddress();
1062 if (!empty($params['source'])) {
1063 unset($params['source']);
1066 $this->_params
['amount'] = $this->_params
['total_amount'];
1067 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
1068 // function to get correct amount level consistently. Remove setting of the amount level in
1069 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
1070 // to cover all variants.
1071 $this->_params
['amount_level'] = 0;
1072 $this->_params
['description'] = ts("Contribution submitted by a staff person using contributor's credit card");
1073 $this->_params
['currencyID'] = CRM_Utils_Array
::value('currency',
1075 CRM_Core_Config
::singleton()->defaultCurrency
1078 $this->_params
['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $params);
1079 $this->_params
['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $params);
1080 $this->_params
['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $params);
1082 //Add common data to formatted params
1083 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
1085 if (empty($this->_params
['invoice_id'])) {
1086 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
1089 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
1092 // At this point we've created a contact and stored its address etc
1093 // all the payment processors expect the name and address to be in the
1094 // so we copy stuff over to first_name etc.
1095 $paymentParams = $this->_params
;
1096 $paymentParams['contactID'] = $contactID;
1097 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
1099 $financialType = new CRM_Financial_DAO_FinancialType();
1100 $financialType->id
= $params['financial_type_id'];
1101 $financialType->find(TRUE);
1103 // Add some financial type details to the params list
1104 // if folks need to use it.
1105 $paymentParams['contributionType_name'] = $this->_params
['contributionType_name'] = $financialType->name
;
1106 $paymentParams['contributionPageID'] = NULL;
1108 if (!empty($this->_params
['is_email_receipt'])) {
1109 $paymentParams['email'] = $this->userEmail
;
1110 $paymentParams['is_email_receipt'] = 1;
1113 $paymentParams['is_email_receipt'] = 0;
1114 $this->_params
['is_email_receipt'] = 0;
1116 if (!empty($this->_params
['receive_date'])) {
1117 $paymentParams['receive_date'] = $this->_params
['receive_date'];
1120 if (!empty($this->_params
['is_email_receipt'])) {
1121 $this->_params
['receipt_date'] = $now;
1124 $this->set('params', $this->_params
);
1126 $this->assign('receive_date', $this->_params
['receive_date']);
1128 // Result has all the stuff we need
1129 // lets archive it to a financial transaction
1130 if ($financialType->is_deductible
) {
1131 $this->assign('is_deductible', TRUE);
1132 $this->set('is_deductible', TRUE);
1134 $contributionParams = [
1135 'id' => CRM_Utils_Array
::value('contribution_id', $this->_params
),
1136 'contact_id' => $contactID,
1137 'line_item' => $lineItem,
1138 'is_test' => $isTest,
1139 'campaign_id' => CRM_Utils_Array
::value('campaign_id', $this->_params
),
1140 'contribution_page_id' => CRM_Utils_Array
::value('contribution_page_id', $this->_params
),
1141 'source' => CRM_Utils_Array
::value('source', $paymentParams, CRM_Utils_Array
::value('description', $paymentParams)),
1142 'thankyou_date' => CRM_Utils_Array
::value('thankyou_date', $this->_params
),
1144 $contributionParams['payment_instrument_id'] = $this->_paymentProcessor
['payment_instrument_id'];
1146 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processFormContribution($this,
1149 $contributionParams,
1153 CRM_Utils_Array
::value('is_recur', $this->_params
)
1156 $paymentParams['contributionID'] = $contribution->id
;
1157 $paymentParams['contributionTypeID'] = $contribution->financial_type_id
;
1158 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
1159 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1161 if ($paymentParams['amount'] > 0.0) {
1162 // force a re-get of the payment processor in case the form changed it, CRM-7179
1163 // NOTE - I expect this is obsolete.
1164 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
1166 $completeStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
1167 $result = $payment->doPayment($paymentParams, 'contribute');
1168 $this->assign('trxn_id', $result['trxn_id']);
1169 $contribution->trxn_id
= $result['trxn_id'];
1170 /* Our scenarios here are
1171 * 1) the payment failed & an Exception should have been thrown
1172 * 2) the payment succeeded but the payment is not immediate (for example a recurring payment
1173 * with a delayed start)
1174 * 3) the payment succeeded with an immediate payment.
1176 * The doPayment function ensures that payment_status_id is always set
1177 * as historically we have had to guess from the context - ie doDirectPayment
1178 * = error or success, unless it is a recurring contribution in which case it is pending.
1180 if ($result['payment_status_id'] == $completeStatusId) {
1182 civicrm_api3('contribution', 'completetransaction', [
1183 'id' => $contribution->id
,
1184 'trxn_id' => $result['trxn_id'],
1185 'payment_processor_id' => $this->_paymentProcessor
['id'],
1186 'is_transactional' => FALSE,
1187 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $result),
1188 'card_type_id' => CRM_Utils_Array
::value('card_type_id', $paymentParams),
1189 'pan_truncation' => CRM_Utils_Array
::value('pan_truncation', $paymentParams),
1190 'is_email_receipt' => FALSE,
1192 // This has now been set to 1 in the DB - declare it here also
1193 $contribution->contribution_status_id
= 1;
1195 catch (CiviCRM_API3_Exception
$e) {
1196 if ($e->getErrorCode() != 'contribution_completed') {
1197 throw new CRM_Core_Exception('Failed to update contribution in database');
1202 // Save the trxn_id.
1203 $contribution->save();
1206 catch (PaymentProcessorException
$e) {
1207 CRM_Contribute_BAO_Contribution
::failPayment($contribution->id
, $paymentParams['contactID'], $e->getMessage());
1208 throw new PaymentProcessorException($e->getMessage());
1211 // Send receipt mail.
1212 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1213 if ($contribution->id
&& !empty($this->_params
['is_email_receipt'])) {
1214 $this->_params
['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $result);
1215 $this->_params
['contact_id'] = $contactID;
1216 $this->_params
['contribution_id'] = $contribution->id
;
1217 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $this->_params
, TRUE)) {
1218 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1222 return $contribution;
1226 * Generate the data to construct a snippet based pane.
1228 * This form also assigns the showAdditionalInfo var based on historical code.
1229 * This appears to mean 'there is a pane to show'.
1231 * @param string $type
1232 * Type of Pane - this is generally used to determine the function name used to build it
1233 * - e.g CreditCard, AdditionalDetail
1234 * @param array $defaults
1237 * We aim to further refactor & simplify this but currently
1239 * - should additional info be shown?
1241 protected function generatePane($type, $defaults) {
1242 $urlParams = "snippet=4&formType={$type}";
1244 $urlParams .= "&mode={$this->_mode}";
1248 if ($type == 'CreditCard' ||
1249 $type == 'DirectDebit'
1255 'url' => CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams),
1260 // See if we need to include this paneName in the current form.
1261 if ($this->_formType
== $type ||
!empty($_POST["hidden_{$type}"]) ||
1262 CRM_Utils_Array
::value("hidden_{$type}", $defaults)
1264 $this->assign('showAdditionalInfo', TRUE);
1265 $pane['open'] = 'true';
1268 if ($type == 'CreditCard' ||
$type == 'DirectDebit') {
1269 // @todo would be good to align tpl name with form name...
1270 // @todo document why this hidden variable is required.
1271 $this->add('hidden', 'hidden_' . $type, 1);
1275 $additionalInfoFormFunction = 'build' . $type;
1276 CRM_Contribute_Form_AdditionalInfo
::$additionalInfoFormFunction($this);
1282 * Wrapper for unit testing the post process submit function.
1284 * (If we expose through api we can get default additions 'for free').
1286 * @param array $params
1287 * @param int $action
1288 * @param string|null $creditCardMode
1290 * @throws \CiviCRM_API3_Exception
1292 public function testSubmit($params, $action, $creditCardMode = NULL) {
1294 'soft_credit_contact_id' => [],
1295 'receive_date' => date('Y-m-d H:i:s'),
1296 'receipt_date' => '',
1297 'cancel_date' => '',
1298 'hidden_Premium' => 1,
1301 if (!empty($params['id'])) {
1302 $existingContribution = civicrm_api3('contribution', 'getsingle', [
1303 'id' => $params['id'],
1305 $this->_id
= $params['id'];
1306 $this->_values
= $existingContribution;
1307 if (CRM_Contribute_BAO_Contribution
::checkContributeSettings('invoicing')) {
1308 $this->_values
['tax_amount'] = civicrm_api3('contribution', 'getvalue', [
1309 'id' => $params['id'],
1310 'return' => 'tax_amount',
1315 $existingContribution = [];
1318 $this->_defaults
['contribution_status_id'] = CRM_Utils_Array
::value('contribution_status_id',
1319 $existingContribution
1322 $this->_defaults
['total_amount'] = CRM_Utils_Array
::value('total_amount',
1323 $existingContribution
1326 if ($creditCardMode) {
1327 $this->_mode
= $creditCardMode;
1330 // Required because processCreditCard calls set method on this.
1331 $_SERVER['REQUEST_METHOD'] = 'GET';
1332 $this->controller
= new CRM_Core_Controller();
1334 CRM_Contribute_Form_AdditionalInfo
::buildPremium($this);
1336 $this->_fields
= [];
1337 return $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array
::value('pledge_payment_id', $params));
1342 * @param array $submittedValues
1344 * @param int $action
1346 * - CRM_Core_Action::UPDATE
1348 * @param $pledgePaymentID
1351 * @throws \Exception
1353 protected function submit($submittedValues, $action, $pledgePaymentID) {
1354 $pId = $contribution = $isRelatedId = FALSE;
1355 $this->_params
= $submittedValues;
1356 $this->beginPostProcess();
1357 // reassign submitted form values if the any information is formatted via beginPostProcess
1358 $submittedValues = $this->_params
;
1360 if (!empty($submittedValues['price_set_id']) && $action & CRM_Core_Action
::UPDATE
) {
1361 $line = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution');
1362 $lineID = key($line);
1363 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array
::value('price_field_id', $line[$lineID]), 'price_set_id');
1364 $quickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1365 // Why do we do this? Seems like a like a wrapper for old functionality - but single line price sets & quick
1366 // config should be treated the same.
1368 CRM_Price_BAO_LineItem
::deleteLineItems($this->_id
, 'civicrm_contribution');
1372 // Process price set and get total amount and line items.
1374 $priceSetId = CRM_Utils_Array
::value('price_set_id', $submittedValues);
1375 if (empty($priceSetId) && !$this->_id
) {
1376 $this->_priceSetId
= $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1377 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
1378 $fieldID = key($this->_priceSet
['fields']);
1379 $fieldValueId = key($this->_priceSet
['fields'][$fieldID]['options']);
1380 $this->_priceSet
['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1381 $submittedValues['price_' . $fieldID] = 1;
1384 // Every contribution has a price-set - the only reason it shouldn't be set is if we are dealing with
1385 // quick config (very very arguably) & yet we see that this could still be quick config so this should be understood
1386 // as a point of fragility rather than a logical 'if' clause.
1388 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
1389 $submittedValues, $lineItem[$priceSetId], NULL, $priceSetId);
1390 // Unset tax amount for offline 'is_quick_config' contribution.
1391 // @todo WHY - quick config was conceived as a quick way to configure contribution forms.
1392 // this is an example of 'other' functionality being hung off it.
1393 if ($this->_priceSet
['is_quick_config'] &&
1394 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant
::getTaxRates())
1396 unset($submittedValues['tax_amount']);
1398 $submittedValues['total_amount'] = CRM_Utils_Array
::value('amount', $submittedValues);
1402 if ($this->_compId
) {
1403 if ($this->_context
== 'participant') {
1404 $pId = $this->_compId
;
1406 elseif ($this->_context
== 'membership') {
1407 $isRelatedId = TRUE;
1410 $pId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id
, 'participant_id', 'contribution_id');
1414 $contributionDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1415 if (array_key_exists('membership', $contributionDetails)) {
1416 $isRelatedId = TRUE;
1418 elseif (array_key_exists('participant', $contributionDetails)) {
1419 $pId = $contributionDetails['participant'];
1422 if (!empty($this->_payNow
)) {
1423 $this->_params
['contribution_id'] = $this->_id
;
1427 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id
) {
1428 // CRM-10117 update the line items for participants.
1429 // @todo - if we are completing a contribution then the api call
1430 // civicrm_api3('Contribution', 'completetransaction') should take care of
1431 // all associated updates rather than replicating them on the form layer.
1433 $entityTable = 'participant';
1435 $isRelatedId = FALSE;
1436 $participantParams = [
1437 'fee_amount' => $submittedValues['total_amount'],
1440 CRM_Event_BAO_Participant
::add($participantParams);
1441 if (empty($this->_lineItems
)) {
1442 $this->_lineItems
[] = CRM_Price_BAO_LineItem
::getLineItems($entityID, 'participant', TRUE);
1446 $entityTable = 'contribution';
1447 $entityID = $this->_id
;
1450 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, $entityTable, FALSE, TRUE, $isRelatedId);
1451 foreach (array_keys($lineItems) as $id) {
1452 $lineItems[$id]['id'] = $id;
1454 $itemId = key($lineItems);
1455 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1456 $this->_priceSetId
= CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1459 // @todo see above - new functionality has been inappropriately added to the quick config concept
1460 // and new functionality has been added onto the form layer rather than the BAO :-(
1461 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1462 //CRM-16833: Ensure tax is applied only once for membership conribution, when status changed.(e.g Pending to Completed).
1463 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1464 if (!(CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails))) {
1465 if (!($this->_action
& CRM_Core_Action
::UPDATE
&& (($this->_defaults
['contribution_status_id'] != $submittedValues['contribution_status_id'])))) {
1466 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule
::cleanMoney(CRM_Utils_Array
::value('total_amount', $submittedValues));
1470 // Update line total and total amount with tax on edit.
1471 $financialItemsId = CRM_Core_PseudoConstant
::getTaxRates();
1472 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1473 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1476 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1477 $submittedValues['tax_amount'] = 'null';
1479 if ($lineItems[$itemId]['tax_rate']) {
1480 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total'];
1481 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] +
$lineItems[$itemId]['tax_amount'];
1482 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1485 // CRM-10117 update the line items for participants.
1486 if (!empty($lineItems[$itemId]['price_field_id'])) {
1487 $lineItem[$this->_priceSetId
] = $lineItems;
1492 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1495 //CRM-11529 for quick config back office transactions
1496 //when financial_type_id is passed in form, update the
1497 //line items with the financial type selected in form
1498 // NOTE that this IS still a legitimate use of 'quick-config' for contributions under the current DB but
1499 // we should look at having a price field per contribution type & then there would be little reason
1500 // for the back-office contribution form postProcess to know if it is a quick-config form.
1501 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array
::value($this->_priceSetId
, $lineItem)
1503 foreach ($lineItem[$this->_priceSetId
] as &$values) {
1504 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1508 if (!isset($submittedValues['total_amount'])) {
1509 $submittedValues['total_amount'] = CRM_Utils_Array
::value('total_amount', $this->_values
);
1510 // Avoid tax amount deduction on edit form and keep it original, because this will lead to error described in CRM-20676
1512 $submittedValues['total_amount'] -= CRM_Utils_Array
::value('tax_amount', $this->_values
, 0);
1515 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
1517 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
1518 if ($this->_id
&& count($isEmpty) == 1 && key($isEmpty) == NULL) {
1519 civicrm_api3('ContributionSoft', 'get', ['contribution_id' => $this->_id
, 'pcp_id' => NULL, 'api.ContributionSoft.delete' => 1]);
1522 // set the contact, when contact is selected
1523 if (!empty($submittedValues['contact_id'])) {
1524 $this->_contactID
= $submittedValues['contact_id'];
1527 $formValues = $submittedValues;
1529 // Credit Card Contribution.
1531 $paramsSetByPaymentProcessingSubsystem = [
1533 'payment_instrument_id',
1534 'contribution_status_id',
1538 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1539 if (isset($formValues[$key])) {
1540 unset($formValues[$key]);
1543 $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID
);
1544 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1545 $formValues[$key] = $contribution->$key;
1549 // Offline Contribution.
1550 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1552 // get the required field value only.
1555 'contact_id' => $this->_contactID
,
1556 'currency' => $this->getCurrency($submittedValues),
1557 'skipCleanMoney' => TRUE,
1561 //format soft-credit/pcp param first
1562 CRM_Contribute_BAO_ContributionSoft
::formatSoftCreditParams($submittedValues, $this);
1563 $params = array_merge($params, $submittedValues);
1566 'financial_type_id',
1567 'contribution_status_id',
1568 'payment_instrument_id',
1575 foreach ($fields as $f) {
1576 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1579 $params['revenue_recognition_date'] = NULL;
1580 if (!empty($formValues['revenue_recognition_date'])
1581 && count(array_filter($formValues['revenue_recognition_date'])) == 2
1583 $params['revenue_recognition_date'] = CRM_Utils_Date
::processDate(
1584 '01-' . implode('-', $formValues['revenue_recognition_date'])
1588 if (!empty($formValues['is_email_receipt'])) {
1589 $params['receipt_date'] = date("Y-m-d");
1592 if (CRM_Contribute_BAO_Contribution
::isContributionStatusNegative($params['contribution_status_id'])
1594 if (CRM_Utils_System
::isNull(CRM_Utils_Array
::value('cancel_date', $params))) {
1595 $params['cancel_date'] = date('YmdHis');
1599 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1602 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1603 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1604 if ($params['contribution_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending')) {
1605 $params['is_pay_later'] = 1;
1607 elseif ($params['contribution_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed')) {
1608 $params['is_pay_later'] = 0;
1611 // Add Additional common information to formatted params.
1612 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($formValues, $params, $this);
1614 $params['contribution_mode'] = 'participant';
1615 $params['participant_id'] = $pId;
1616 $params['skipLineItem'] = 1;
1618 elseif ($isRelatedId) {
1619 $params['contribution_mode'] = 'membership';
1621 $params['line_item'] = $lineItem;
1622 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array
::value('id', $this->_paymentProcessor
);
1623 $params['tax_amount'] = CRM_Utils_Array
::value('tax_amount', $submittedValues, CRM_Utils_Array
::value('tax_amount', $this->_values
));
1624 //create contribution.
1625 if ($isQuickConfig) {
1626 $params['is_quick_config'] = 1;
1628 $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
1630 // we are already handling note below, so to avoid duplicate notes against $contribution
1631 if (!empty($params['note']) && !empty($submittedValues['note'])) {
1632 unset($params['note']);
1634 $contribution = CRM_Contribute_BAO_Contribution
::create($params);
1636 // process associated membership / participant, CRM-4395
1637 if ($contribution->id
&& $action & CRM_Core_Action
::UPDATE
) {
1638 $this->statusMessage
[] = CRM_Contribute_BAO_Contribution
::transitionComponentWithReturnMessage($contribution->id
,
1639 $contribution->contribution_status_id
,
1640 CRM_Utils_Array
::value('contribution_status_id',
1643 $contribution->receive_date
1647 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1649 $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
1651 //send receipt mail.
1652 if ($contribution->id
&& !empty($formValues['is_email_receipt'])) {
1653 $formValues['contact_id'] = $this->_contactID
;
1654 $formValues['contribution_id'] = $contribution->id
;
1656 $formValues +
= CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
);
1658 // to get 'from email id' for send receipt
1659 $this->fromEmailId
= CRM_Utils_Array
::value('from_email_address', $formValues);
1660 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $formValues)) {
1661 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1665 $this->statusMessageTitle
= ts('Saved');
1669 if ($contribution->id
&& isset($formValues['product_name'][0])) {
1670 CRM_Contribute_Form_AdditionalInfo
::processPremium($submittedValues, $contribution->id
,
1671 $this->_premiumID
, $this->_options
1675 if ($contribution->id
&& array_key_exists('note', $submittedValues)) {
1676 CRM_Contribute_Form_AdditionalInfo
::processNote($submittedValues, $this->_contactID
, $contribution->id
, $this->_noteID
);
1679 CRM_Core_Session
::setStatus(implode(' ', $this->statusMessage
), $this->statusMessageTitle
, 'success');
1681 CRM_Contribute_BAO_Contribution
::updateRelatedPledge(
1685 (CRM_Utils_Array
::value('option_type', $formValues) == 2) ?
TRUE : FALSE,
1686 $formValues['total_amount'],
1687 CRM_Utils_Array
::value('total_amount', $this->_defaults
),
1688 $formValues['contribution_status_id'],
1689 CRM_Utils_Array
::value('contribution_status_id', $this->_defaults
)
1691 return $contribution;
1695 * Assign tax calculations to contribution receipts.
1697 * @param array $submittedValues
1698 * @param int $action
1699 * @param array $lineItem
1701 protected function invoicingPostProcessHook($submittedValues, $action, $lineItem) {
1703 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
1704 if (!CRM_Utils_Array
::value('invoicing', $invoiceSettings)) {
1708 $getTaxDetails = FALSE;
1710 foreach ($lineItem as $key => $value) {
1711 foreach ($value as $v) {
1712 if (isset($taxRate[(string) CRM_Utils_Array
::value('tax_rate', $v)])) {
1713 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $v);
1716 if (isset($v['tax_rate'])) {
1717 $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $v);
1718 $getTaxDetails = TRUE;
1724 if ($action & CRM_Core_Action
::UPDATE
) {
1725 if (isset($submittedValues['tax_amount'])) {
1726 $totalTaxAmount = $submittedValues['tax_amount'];
1729 $totalTaxAmount = $this->_values
['tax_amount'];
1731 $this->assign('totalTaxAmount', $totalTaxAmount);
1732 $this->assign('dataArray', $taxRate);
1735 if (!empty($submittedValues['price_set_id'])) {
1736 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1737 $this->assign('getTaxDetails', $getTaxDetails);
1738 $this->assign('dataArray', $taxRate);
1739 $this->assign('taxTerm', CRM_Utils_Array
::value('tax_term', $invoiceSettings));
1742 $this->assign('totalTaxAmount', CRM_Utils_Array
::value('tax_amount', $submittedValues));
1748 * Calculate non deductible amount.
1751 * if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1752 * if non_deductible_amount does NOT exist - then calculate it depending on:
1753 * $financialType->is_deductible and whether there is a product (premium).
1756 * @param $formValues
1760 protected function calculateNonDeductibleAmount($params, $formValues) {
1761 if (!empty($params['non_deductible_amount'])) {
1762 return $params['non_deductible_amount'];
1765 $priceSetId = CRM_Utils_Array
::value('price_set_id', $params);
1766 // return non-deductible amount if it is set at the price field option level
1767 if ($priceSetId && !empty($params['line_item'])) {
1768 $nonDeductibleAmount = CRM_Price_BAO_PriceSet
::getNonDeductibleAmountFromPriceSet($priceSetId, $params['line_item']);
1769 if (!empty($nonDeductibleAmount)) {
1770 return $nonDeductibleAmount;
1774 $financialType = new CRM_Financial_DAO_FinancialType();
1775 $financialType->id
= $params['financial_type_id'];
1776 $financialType->find(TRUE);
1778 if ($financialType->is_deductible
) {
1780 if (isset($formValues['product_name'][0])) {
1781 $selectProduct = $formValues['product_name'][0];
1783 // if there is a product - compare the value to the contribution amount
1784 if (isset($selectProduct)) {
1785 $productDAO = new CRM_Contribute_DAO_Product();
1786 $productDAO->id
= $selectProduct;
1787 $productDAO->find(TRUE);
1788 // product value exceeds contribution amount
1789 if ($params['total_amount'] < $productDAO->price
) {
1790 return $params['total_amount'];
1792 // product value does NOT exceed contribution amount
1794 return $productDAO->price
;
1797 // contribution is deductible - but there is no product
1802 // contribution is NOT deductible
1804 return $params['total_amount'];