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
109 * The pledge values if this contribution is associated with pledge
111 public $_pledgeValues;
113 public $_contributeMode = 'direct';
118 * Parameter with confusing name.
122 public $_compContext;
127 * Possible From email addresses
139 * Store the line items if price set used.
145 * @todo explain why we use lineItem & lineItems
151 * @var array soft credit info
153 public $_softCreditInfo;
155 protected $_formType;
158 * Array of the payment fields to be displayed in the payment fieldset (pane) in billingBlock.tpl
159 * this contains all the information to describe these fields from quickform. See CRM_Core_Form_Payment getPaymentFormFieldsMetadata
163 public $_paymentFields = array();
165 * Logged in user's email.
177 * Price set as an array
187 public $userDisplayName;
190 * Status message to be shown to the user.
194 protected $statusMessage = array();
197 * Status message title to be shown to the user.
199 * Generally the payment processor message title is 'Complete' and offline is 'Saved'
200 * although this might not be a good fit with the broad range of processors.
204 protected $statusMessageTitle;
209 * Max row count for soft credits. The value here is +1 the actual number of
212 public $_softCreditItemCount = 11;
215 * Explicitly declare the form context.
217 public function getDefaultContext() {
222 * Set variables up before form is built.
224 public function preProcess() {
225 // Check permission for action.
226 if (!CRM_Core_Permission
::checkActionPermission('CiviContribute', $this->_action
)) {
227 // @todo replace with throw new CRM_Core_Exception().
228 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
231 parent
::preProcess();
233 $this->_formType
= CRM_Utils_Array
::value('formType', $_GET);
236 $this->_priceSetId
= CRM_Utils_Array
::value('priceSetId', $_GET);
237 $this->set('priceSetId', $this->_priceSetId
);
238 $this->assign('priceSetId', $this->_priceSetId
);
240 // Get the pledge payment id
241 $this->_ppID
= CRM_Utils_Request
::retrieve('ppid', 'Positive', $this);
243 $this->assign('action', $this->_action
);
245 // Get the contribution id if update
246 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this);
247 if (!empty($this->_id
)) {
248 $this->assignPaymentInfoBlock();
249 $this->assign('contribID', $this->_id
);
250 $this->assign('isUsePaymentBlock', TRUE);
253 $this->_context
= CRM_Utils_Request
::retrieve('context', 'Alphanumeric', $this);
254 $this->assign('context', $this->_context
);
256 $this->_compId
= CRM_Utils_Request
::retrieve('compId', 'Positive', $this);
258 $this->_compContext
= CRM_Utils_Request
::retrieve('compContext', 'String', $this);
260 //set the contribution mode.
261 $this->_mode
= CRM_Utils_Request
::retrieve('mode', 'Alphanumeric', $this);
263 $this->assign('contributionMode', $this->_mode
);
264 if ($this->_action
& CRM_Core_Action
::DELETE
) {
268 $this->_fromEmails
= CRM_Core_BAO_Email
::getFromEmail();
270 if (in_array('CiviPledge', CRM_Core_Config
::singleton()->enableComponents
) && !$this->_formType
) {
271 $this->preProcessPledge();
275 $this->showRecordLinkMesssage($this->_id
);
277 $this->_values
= array();
279 // Current contribution id.
281 $this->assignPremiumProduct($this->_id
);
282 $this->buildValuesAndAssignOnline_Note_Type($this->_id
, $this->_values
);
285 // when custom data is included in this page
286 if (!empty($_POST['hidden_custom'])) {
287 $this->applyCustomData('Contribution', CRM_Utils_Array
::value('financial_type_id', $_POST), $this->_id
);
290 $this->_lineItems
= array();
292 if (!empty($this->_compId
) && $this->_compContext
== 'participant') {
293 $this->assign('compId', $this->_compId
);
294 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_compId
);
297 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution', 1, TRUE, TRUE);
300 empty($lineItem) ?
NULL : $this->_lineItems
[] = $lineItem;
303 $this->assign('lineItem', empty($lineItem) ?
FALSE : array($lineItem));
306 if ($this->_mode
&& $this->_id
) {
307 $this->_payNow
= TRUE;
308 $this->assign('payNow', $this->_payNow
);
309 CRM_Utils_System
::setTitle(ts('Pay with Credit Card'));
311 elseif ($this->_mode
) {
312 $this->setPageTitle($this->_ppID ?
ts('Credit Card Pledge Payment') : ts('Credit Card Contribution'));
315 $this->setPageTitle($this->_ppID ?
ts('Pledge Payment') : ts('Contribution'));
320 * Set default values.
324 public function setDefaultValues() {
325 $defaults = $this->_values
;
327 // Set defaults for pledge payment.
329 $defaults['total_amount'] = CRM_Utils_Array
::value('scheduled_amount', $this->_pledgeValues
['pledgePayment']);
330 $defaults['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $this->_pledgeValues
);
331 $defaults['currency'] = CRM_Utils_Array
::value('currency', $this->_pledgeValues
);
332 $defaults['option_type'] = 1;
335 if ($this->_action
& CRM_Core_Action
::DELETE
) {
339 $defaults['frequency_interval'] = 1;
340 $defaults['frequency_unit'] = 'month';
342 // Set soft credit defaults.
343 CRM_Contribute_Form_SoftCredit
::setDefaultValues($defaults, $this);
346 // @todo - remove this function as the parent does it too.
347 $config = CRM_Core_Config
::singleton();
348 // Set default country from config if no country set.
349 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
350 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry
;
353 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
354 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince
;
357 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID
);
358 $defaults = array_merge($defaults, $billingDefaults);
362 $this->_contactID
= $defaults['contact_id'];
365 // Set $newCredit variable in template to control whether link to credit card mode is included.
366 $this->assign('newCredit', CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments());
368 // Fix the display of the monetary value, CRM-4038.
369 if (isset($defaults['total_amount'])) {
370 $total_value = $defaults['total_amount'];
371 $defaults['total_amount'] = CRM_Utils_Money
::format($total_value, NULL, '%a');
372 if (!empty($defaults['tax_amount'])) {
373 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
374 if (!(CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails))) {
375 $defaults['total_amount'] = CRM_Utils_Money
::format($total_value - $defaults['tax_amount'], NULL, '%a');
380 $amountFields = array('non_deductible_amount', 'fee_amount');
381 foreach ($amountFields as $amt) {
382 if (isset($defaults[$amt])) {
383 $defaults[$amt] = CRM_Utils_Money
::format($defaults[$amt], NULL, '%a');
387 if ($this->_contributionType
) {
388 $defaults['financial_type_id'] = $this->_contributionType
;
391 if (empty($defaults['payment_instrument_id'])) {
392 $defaults['payment_instrument_id'] = $this->getDefaultPaymentInstrumentId();
395 if (!empty($defaults['is_test'])) {
396 $this->assign('is_test', TRUE);
399 $this->assign('showOption', TRUE);
400 // For Premium section.
401 if ($this->_premiumID
) {
402 $this->assign('showOption', FALSE);
403 $options = isset($this->_options
[$this->_productDAO
->product_id
]) ?
$this->_options
[$this->_productDAO
->product_id
] : "";
405 $this->assign('showOption', TRUE);
407 $options_key = CRM_Utils_Array
::key($this->_productDAO
->product_option
, $options);
409 $defaults['product_name'] = array($this->_productDAO
->product_id
, trim($options_key));
412 $defaults['product_name'] = array($this->_productDAO
->product_id
);
414 if ($this->_productDAO
->fulfilled_date
) {
415 list($defaults['fulfilled_date']) = CRM_Utils_Date
::setDateDefaults($this->_productDAO
->fulfilled_date
);
419 if (isset($this->userEmail
)) {
420 $this->assign('email', $this->userEmail
);
423 if (!empty($defaults['is_pay_later'])) {
424 $this->assign('is_pay_later', TRUE);
426 $this->assign('contribution_status_id', CRM_Utils_Array
::value('contribution_status_id', $defaults));
427 if (!empty($defaults['contribution_status_id']) && in_array(
428 CRM_Contribute_PseudoConstant
::contributionStatus($defaults['contribution_status_id'], 'name'),
429 // Historically not 'Cancelled' hence not using CRM_Contribute_BAO_Contribution::isContributionStatusNegative.
430 array('Refunded', 'Chargeback')
432 $defaults['refund_trxn_id'] = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionTrxnID($this->_id
);
435 $defaults['refund_trxn_id'] = isset($defaults['trxn_id']) ?
$defaults['trxn_id'] : NULL;
438 if (!$this->_id
&& empty($defaults['receive_date'])) {
439 $defaults['receive_date'] = date('Y-m-d H:i:s');
442 $currency = CRM_Utils_Array
::value('currency', $defaults);
443 $this->assign('currency', $currency);
444 // Hack to get currency info to the js layer. CRM-11440.
445 CRM_Utils_Money
::format(1);
446 $this->assign('currencySymbol', CRM_Utils_Array
::value($currency, CRM_Utils_Money
::$_currencySymbols));
447 $this->assign('totalAmount', CRM_Utils_Array
::value('total_amount', $defaults));
449 // Inherit campaign from pledge.
450 if ($this->_ppID
&& !empty($this->_pledgeValues
['campaign_id'])) {
451 $defaults['campaign_id'] = $this->_pledgeValues
['campaign_id'];
454 $this->_defaults
= $defaults;
459 * Build the form object.
461 public function buildQuickForm() {
462 if ($this->_action
& CRM_Core_Action
::DELETE
) {
463 $this->addButtons(array(
466 'name' => ts('Delete'),
467 'spacing' => ' ',
472 'name' => ts('Cancel'),
479 // FIXME: This probably needs to be done in preprocess
480 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()
481 && $this->_action
& CRM_Core_Action
::UPDATE
482 && CRM_Utils_Array
::value('financial_type_id', $this->_values
)
484 $financialTypeID = CRM_Contribute_PseudoConstant
::financialType($this->_values
['financial_type_id']);
485 CRM_Financial_BAO_FinancialType
::checkPermissionedLineItems($this->_id
, 'edit');
486 if (!CRM_Core_Permission
::check('edit contributions of type ' . $financialTypeID)) {
487 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
492 //tax rate from financialType
493 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant
::getTaxRates()));
494 $this->assign('currencies', json_encode(CRM_Core_OptionGroup
::values('currencies_enabled')));
496 // build price set form.
497 $buildPriceSet = FALSE;
498 $invoicing = CRM_Invoicing_Utils
::isInvoicingEnabled();
499 $this->assign('invoicing', $invoicing);
501 $buildRecurBlock = FALSE;
503 // display tax amount on edit contribution page
504 if ($invoicing && $this->_action
& CRM_Core_Action
::UPDATE
&& isset($this->_values
['tax_amount'])) {
505 $this->assign('totalTaxAmount', $this->_values
['tax_amount']);
508 if (empty($this->_lineItems
) &&
509 ($this->_priceSetId ||
!empty($_POST['price_set_id']))
511 $buildPriceSet = TRUE;
512 $getOnlyPriceSetElements = TRUE;
513 if (!$this->_priceSetId
) {
514 $this->_priceSetId
= $_POST['price_set_id'];
515 $getOnlyPriceSetElements = FALSE;
518 $this->set('priceSetId', $this->_priceSetId
);
519 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
521 // get only price set form elements.
522 if ($getOnlyPriceSetElements) {
526 // use to build form during form rule.
527 $this->assign('buildPriceSet', $buildPriceSet);
529 $defaults = $this->_values
;
530 $additionalDetailFields = array(
534 'non_deductible_amount',
537 foreach ($additionalDetailFields as $key) {
538 if (!empty($defaults[$key])) {
539 $defaults['hidden_AdditionalDetail'] = 1;
544 if ($this->_productDAO
) {
545 if ($this->_productDAO
->product_id
) {
546 $defaults['hidden_Premium'] = 1;
550 if ($this->_noteID
&&
551 !CRM_Utils_System
::isNull($this->_values
['note'])
553 $defaults['hidden_AdditionalDetail'] = 1;
556 $paneNames = array();
557 if (empty($this->_payNow
)) {
558 $paneNames[ts('Additional Details')] = 'AdditionalDetail';
561 //Add Premium pane only if Premium is exists.
562 $dao = new CRM_Contribute_DAO_Product();
565 if ($dao->find(TRUE) && empty($this->_payNow
)) {
566 $paneNames[ts('Premium Information')] = 'Premium';
569 $this->payment_instrument_id
= CRM_Utils_Array
::value('payment_instrument_id', $defaults, $this->getDefaultPaymentInstrumentId());
570 if (CRM_Core_Payment_Form
::buildPaymentForm($this, $this->_paymentProcessor
, FALSE, TRUE, $this->payment_instrument_id
) == TRUE) {
571 if (!empty($this->_recurPaymentProcessors
)) {
572 $buildRecurBlock = TRUE;
574 // ppID denotes a pledge payment.
575 foreach ($this->_paymentProcessors
as $processor) {
576 if (!empty($processor['is_recur']) && !empty($processor['object']) && $processor['object']->supports('recurContributionsForPledges')) {
577 $buildRecurBlock = TRUE;
580 $buildRecurBlock = FALSE;
583 if ($buildRecurBlock) {
584 CRM_Contribute_Form_Contribution_Main
::buildRecur($this);
585 $this->setDefaults(array('is_recur' => 0));
586 $this->assign('buildRecurBlock', TRUE);
590 $this->addPaymentProcessorSelect(FALSE, $buildRecurBlock);
592 foreach ($paneNames as $name => $type) {
593 $allPanes[$name] = $this->generatePane($type, $defaults);
596 $qfKey = $this->controller
->_key
;
597 $this->assign('qfKey', $qfKey);
598 $this->assign('allPanes', $allPanes);
600 $this->addFormRule(array('CRM_Contribute_Form_Contribution', 'formRule'), $this);
602 if ($this->_formType
) {
603 $this->assign('formType', $this->_formType
);
607 $this->applyFilter('__ALL__', 'trim');
609 //need to assign custom data type and subtype to the template
610 $this->assign('customDataType', 'Contribution');
611 $this->assign('customDataSubType', $this->_contributionType
);
612 $this->assign('entityID', $this->_id
);
614 if ($this->_context
== 'standalone') {
615 $this->addEntityRef('contact_id', ts('Contact'), array(
617 'api' => array('extra' => array('email')),
621 $attributes = CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Contribution');
623 // Check permissions for financial type first
624 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes, $this->_action
);
625 if (empty($financialTypes)) {
626 CRM_Core_Error
::statusBounce(ts('You do not have all the permissions needed for this page.'));
628 $financialType = $this->add('select', 'financial_type_id',
629 ts('Financial Type'),
630 array('' => ts('- select -')) +
$financialTypes,
632 array('onChange' => "CRM.buildCustomData( 'Contribution', this.value );")
635 $paymentInstrument = FALSE;
637 // payment_instrument isn't required in edit and will not be present when payment block is enabled.
638 $required = $this->_id ?
FALSE : TRUE;
639 $checkPaymentID = array_search('Check', CRM_Contribute_PseudoConstant
::paymentInstrument('name'));
640 $paymentInstrument = $this->add('select', 'payment_instrument_id',
641 ts('Payment Method'),
642 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::paymentInstrument(),
643 $required, array('onChange' => "return showHideByValue('payment_instrument_id','{$checkPaymentID}','checkNumber','table-row','select',false);")
647 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), array('class' => 'twelve') +
$attributes['trxn_id']);
649 //add receipt for offline contribution
650 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
652 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
654 $component = 'contribution';
655 $componentDetails = [];
657 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
658 if (CRM_Utils_Array
::value('membership', $componentDetails)) {
659 $component = 'membership';
661 elseif (CRM_Utils_Array
::value('participant', $componentDetails)) {
662 $component = 'participant';
666 $component = 'pledge';
668 $status = CRM_Contribute_BAO_Contribution_Utils
::getContributionStatuses($component, $this->_id
);
670 // define the status IDs that show the cancellation info, see CRM-17589
671 $cancelInfo_show_ids = array();
672 foreach (array_keys($status) as $status_id) {
673 if (CRM_Contribute_BAO_Contribution
::isContributionStatusNegative($status_id)) {
674 $cancelInfo_show_ids[] = "'$status_id'";
677 $this->assign('cancelInfo_show_ids', implode(',', $cancelInfo_show_ids));
679 $statusElement = $this->add('select', 'contribution_status_id',
680 ts('Contribution Status'),
685 $currencyFreeze = FALSE;
686 if (!empty($this->_payNow
) && ($this->_action
& CRM_Core_Action
::UPDATE
)) {
687 $statusElement->freeze();
688 $currencyFreeze = TRUE;
689 $attributes['total_amount']['readonly'] = TRUE;
692 // CRM-16189, add Revenue Recognition Date
693 if (CRM_Contribute_BAO_Contribution
::checkContributeSettings('deferred_revenue_enabled')) {
694 $revenueDate = $this->add('date', 'revenue_recognition_date', ts('Revenue Recognition Date'), CRM_Core_SelectValues
::date(NULL, 'M Y', NULL, 5));
695 if ($this->_id
&& !CRM_Contribute_BAO_Contribution
::allowUpdateRevenueRecognitionDate($this->_id
)) {
696 $revenueDate->freeze();
701 $this->addField('receive_date', array('entity' => 'contribution'), !$this->_mode
, FALSE);
702 $this->addField('receipt_date', array('entity' => 'contribution'), FALSE, FALSE);
703 $this->addField('cancel_date', array('entity' => 'contribution', 'label' => ts('Cancelled / Refunded Date')), FALSE, FALSE);
705 if ($this->_online
) {
706 $this->assign('hideCalender', TRUE);
709 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
712 if (empty($this->_lineItems
)) {
713 $buildPriceSet = FALSE;
714 $priceSets = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute');
715 if (!empty($priceSets) && !$this->_ppID
) {
716 $buildPriceSet = TRUE;
719 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
720 // and if we already have line items for that participant. CRM-5095
721 if ($buildPriceSet && $this->_id
) {
722 $pledgePaymentId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
727 if ($pledgePaymentId) {
728 $buildPriceSet = FALSE;
730 if ($participantID = CRM_Utils_Array
::value('participant', $componentDetails)) {
731 $participantLI = CRM_Price_BAO_LineItem
::getLineItems($participantID);
732 if (!CRM_Utils_System
::isNull($participantLI)) {
733 $buildPriceSet = FALSE;
738 $hasPriceSets = FALSE;
739 if ($buildPriceSet) {
740 $hasPriceSets = TRUE;
741 // CRM-16451: set financial type of 'Price Set' in back office contribution
742 // instead of selecting manually
743 $financialTypeIds = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute', 'financial_type_id');
744 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
746 '' => ts('Choose price set'),
748 NULL, array('onchange' => "buildAmount( this.value, " . json_encode($financialTypeIds) . ");")
750 if ($this->_online
&& !($this->_action
& CRM_Core_Action
::UPDATE
)) {
754 $this->assign('hasPriceSets', $hasPriceSets);
755 if (!($this->_action
& CRM_Core_Action
::UPDATE
)) {
756 if ($this->_online ||
$this->_ppID
) {
757 $attributes['total_amount'] = array_merge($attributes['total_amount'], array(
759 'style' => "background-color:#EBECE4",
761 $optionTypes = array(
762 '1' => ts('Adjust Pledge Payment Schedule?'),
763 '2' => ts('Adjust Total Pledge Amount?'),
765 $this->addRadio('option_type',
771 $currencyFreeze = TRUE;
775 $totalAmount = $this->addMoney('total_amount',
777 ($hasPriceSets) ?
FALSE : TRUE,
778 $attributes['total_amount'],
779 TRUE, 'currency', NULL, $currencyFreeze
783 $this->add('text', 'source', ts('Source'), CRM_Utils_Array
::value('source', $attributes));
785 // CRM-7362 --add campaigns.
786 CRM_Campaign_BAO_Campaign
::addCampaign($this, CRM_Utils_Array
::value('campaign_id', $this->_values
));
788 if (empty($this->_payNow
)) {
789 CRM_Contribute_Form_SoftCredit
::buildQuickForm($this);
794 $js = array('onclick' => "return verify( );");
797 $mailingInfo = Civi
::settings()->get('mailing_backend');
798 $this->assign('outBound_option', $mailingInfo['outBound_option']);
800 $this->addButtons(array(
803 'name' => ts('Save'),
809 'name' => ts('Save and New'),
815 'name' => ts('Cancel'),
820 // if contribution is related to membership or participant freeze Financial Type, Amount
822 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
823 $isCancelledStatus = ($this->_values
['contribution_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Cancelled'));
825 if (CRM_Utils_Array
::value('membership', $componentDetails) ||
826 CRM_Utils_Array
::value('participant', $componentDetails) ||
827 // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
828 // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
832 $totalAmount->freeze();
833 $this->getElement('currency')->freeze();
835 if ($isCancelledStatus) {
836 $paymentInstrument->freeze();
839 $financialType->freeze();
840 $this->assign('freezeFinancialType', TRUE);
844 if ($this->_action
& CRM_Core_Action
::VIEW
) {
852 * @param array $fields
853 * The input form values.
854 * @param array $files
855 * The uploaded files if any.
859 * true if no errors, else array of errors
861 public static function formRule($fields, $files, $self) {
863 // Check for Credit Card Contribution.
865 if (empty($fields['payment_processor_id'])) {
866 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
869 // validate payment instrument (e.g. credit card number)
870 CRM_Core_Payment_Form
::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, NULL);
874 // Do the amount validations.
875 if (empty($fields['total_amount']) && empty($self->_lineItems
)) {
876 if ($priceSetId = CRM_Utils_Array
::value('price_set_id', $fields)) {
877 CRM_Price_BAO_PriceField
::priceSetValidation($priceSetId, $fields, $errors);
881 $softErrors = CRM_Contribute_Form_SoftCredit
::formRule($fields, $errors, $self);
883 //CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
884 CRM_Contribute_BAO_ContributionRecur
::validateRecurContribution($fields, $files, $self, $errors);
886 // Form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
887 if (($self->_action
& CRM_Core_Action
::UPDATE
)
889 && $self->_values
['contribution_status_id'] != $fields['contribution_status_id']
891 CRM_Contribute_BAO_Contribution
::checkStatusValidation($self->_values
, $fields, $errors);
893 // CRM-16015, add form-rule to restrict change of financial type if using price field of different financial type
894 if (($self->_action
& CRM_Core_Action
::UPDATE
)
896 && $self->_values
['financial_type_id'] != $fields['financial_type_id']
898 CRM_Contribute_BAO_Contribution
::checkFinancialTypeChange(NULL, $self->_id
, $errors);
900 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
901 if (!empty($fields['fee_amount']) && !empty($fields['financial_type_id']) && $financialType = CRM_Contribute_BAO_Contribution
::validateFinancialType($fields['financial_type_id'])) {
902 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
905 // $trxn_id must be unique CRM-13919
906 if (!empty($fields['trxn_id'])) {
907 $queryParams = array(1 => array($fields['trxn_id'], 'String'));
908 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
910 $queryParams[2] = array((int) $self->_id
, 'Integer');
911 $query .= ' and id !=%2';
913 $tCnt = CRM_Core_DAO
::singleValueQuery($query, $queryParams);
915 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', array(1 => $fields['trxn_id']));
918 if (!empty($fields['revenue_recognition_date'])
919 && count(array_filter($fields['revenue_recognition_date'])) == 1
921 $errors['revenue_recognition_date'] = ts('Month and Year are required field for Revenue Recognition.');
925 CRM_Financial_BAO_FinancialAccount
::checkFinancialTypeHasDeferred($fields, $self->_id
, $self->_priceSet
['fields']);
927 catch (CRM_Core_Exception
$e) {
928 $errors['financial_type_id'] = ' ';
929 $errors['_qf_default'] = $e->getMessage();
931 $errors = array_merge($errors, $softErrors);
936 * Process the form submission.
938 public function postProcess() {
939 if ($this->_action
& CRM_Core_Action
::DELETE
) {
940 CRM_Contribute_BAO_Contribution
::deleteContribution($this->_id
);
941 CRM_Core_Session
::singleton()->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
942 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
946 // Get the submitted form values.
947 $submittedValues = $this->controller
->exportValues($this->_name
);
950 $contribution = $this->submit($submittedValues, $this->_action
, $this->_ppID
);
952 catch (PaymentProcessorException
$e) {
953 // Set the contribution mode.
954 $urlParams = "action=add&cid={$this->_contactID}";
956 $urlParams .= "&mode={$this->_mode}";
958 if (!empty($this->_ppID
)) {
959 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
962 CRM_Core_Error
::statusBounce($e->getMessage(), $urlParams, ts('Payment Processor Error'));
964 $session = CRM_Core_Session
::singleton();
965 $buttonName = $this->controller
->getButtonName();
966 if ($this->_context
== 'standalone') {
967 if ($buttonName == $this->getButtonName('upload', 'new')) {
968 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contribute/add',
969 'reset=1&action=add&context=standalone'
973 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
974 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
978 elseif ($this->_context
== 'contribution' && $this->_mode
&& $buttonName == $this->getButtonName('upload', 'new')) {
979 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
980 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
983 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
984 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
985 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
989 //store contribution ID if not yet set (on create)
990 if (empty($this->_id
) && !empty($contribution->id
)) {
991 $this->_id
= $contribution->id
;
993 if (!empty($this->_id
) && CRM_Core_Permission
::access('CiviMember')) {
994 $membershipPaymentCount = civicrm_api3('MembershipPayment', 'getCount', array('contribution_id' => $this->_id
));
995 if ($membershipPaymentCount) {
996 $this->ajaxResponse
['updateTabs']['#tab_member'] = CRM_Contact_BAO_Contact
::getCountComponent('membership', $this->_contactID
);
999 if (!empty($this->_id
) && CRM_Core_Permission
::access('CiviEvent')) {
1000 $participantPaymentCount = civicrm_api3('ParticipantPayment', 'getCount', array('contribution_id' => $this->_id
));
1001 if ($participantPaymentCount) {
1002 $this->ajaxResponse
['updateTabs']['#tab_participant'] = CRM_Contact_BAO_Contact
::getCountComponent('participant', $this->_contactID
);
1008 * Process credit card payment.
1010 * @param array $submittedValues
1011 * @param array $lineItem
1013 * @param int $contactID
1016 * @return bool|\CRM_Contribute_DAO_Contribution
1017 * @throws \CRM_Core_Exception
1018 * @throws \Civi\Payment\Exception\PaymentProcessorException
1020 protected function processCreditCard($submittedValues, $lineItem, $contactID) {
1021 $isTest = ($this->_mode
== 'test') ?
1 : 0;
1022 // CRM-12680 set $_lineItem if its not set
1023 // @todo - I don't believe this would ever BE set. I can't find anywhere in the code.
1024 // It would be better to pass line item out to functions than $this->_lineItem as
1025 // we don't know what is being changed where.
1026 if (empty($this->_lineItem
) && !empty($lineItem)) {
1027 $this->_lineItem
= $lineItem;
1030 $this->_paymentObject
= Civi\Payment\System
::singleton()->getById($submittedValues['payment_processor_id']);
1031 $this->_paymentProcessor
= $this->_paymentObject
->getPaymentProcessor();
1033 // Set source if not set
1034 if (empty($submittedValues['source'])) {
1035 $userID = CRM_Core_Session
::singleton()->get('userID');
1036 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1039 $submittedValues['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
1042 $params = $submittedValues;
1043 $this->_params
= array_merge($this->_params
, $submittedValues);
1045 // Mapping requiring documentation.
1046 $this->_params
['payment_processor'] = $submittedValues['payment_processor_id'];
1048 $now = date('YmdHis');
1050 $this->_contributorEmail
= $this->userEmail
;
1051 $this->_contributorContactID
= $contactID;
1052 $this->processBillingAddress();
1053 if (!empty($params['source'])) {
1054 unset($params['source']);
1057 $this->_params
['amount'] = $this->_params
['total_amount'];
1058 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
1059 // function to get correct amount level consistently. Remove setting of the amount level in
1060 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
1061 // to cover all variants.
1062 $this->_params
['amount_level'] = 0;
1063 $this->_params
['description'] = ts("Contribution submitted by a staff person using contributor's credit card");
1064 $this->_params
['currencyID'] = CRM_Utils_Array
::value('currency',
1066 CRM_Core_Config
::singleton()->defaultCurrency
1069 $this->_params
['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $params);
1070 $this->_params
['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $params);
1071 $this->_params
['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $params);
1073 //Add common data to formatted params
1074 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
1076 if (empty($this->_params
['invoice_id'])) {
1077 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
1080 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
1083 // At this point we've created a contact and stored its address etc
1084 // all the payment processors expect the name and address to be in the
1085 // so we copy stuff over to first_name etc.
1086 $paymentParams = $this->_params
;
1087 $paymentParams['contactID'] = $contactID;
1088 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
1090 $financialType = new CRM_Financial_DAO_FinancialType();
1091 $financialType->id
= $params['financial_type_id'];
1092 $financialType->find(TRUE);
1094 // Add some financial type details to the params list
1095 // if folks need to use it.
1096 $paymentParams['contributionType_name'] = $this->_params
['contributionType_name'] = $financialType->name
;
1097 $paymentParams['contributionPageID'] = NULL;
1099 if (!empty($this->_params
['is_email_receipt'])) {
1100 $paymentParams['email'] = $this->userEmail
;
1101 $paymentParams['is_email_receipt'] = 1;
1104 $paymentParams['is_email_receipt'] = 0;
1105 $this->_params
['is_email_receipt'] = 0;
1107 if (!empty($this->_params
['receive_date'])) {
1108 $paymentParams['receive_date'] = $this->_params
['receive_date'];
1111 if (!empty($this->_params
['is_email_receipt'])) {
1112 $this->_params
['receipt_date'] = $now;
1115 $this->set('params', $this->_params
);
1117 $this->assign('receive_date', $this->_params
['receive_date']);
1119 // Result has all the stuff we need
1120 // lets archive it to a financial transaction
1121 if ($financialType->is_deductible
) {
1122 $this->assign('is_deductible', TRUE);
1123 $this->set('is_deductible', TRUE);
1125 $contributionParams = array(
1126 'id' => CRM_Utils_Array
::value('contribution_id', $this->_params
),
1127 'contact_id' => $contactID,
1128 'line_item' => $lineItem,
1129 'is_test' => $isTest,
1130 'campaign_id' => CRM_Utils_Array
::value('campaign_id', $this->_params
),
1131 'contribution_page_id' => CRM_Utils_Array
::value('contribution_page_id', $this->_params
),
1132 'source' => CRM_Utils_Array
::value('source', $paymentParams, CRM_Utils_Array
::value('description', $paymentParams)),
1133 'thankyou_date' => CRM_Utils_Array
::value('thankyou_date', $this->_params
),
1135 $contributionParams['payment_instrument_id'] = $this->_paymentProcessor
['payment_instrument_id'];
1137 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processFormContribution($this,
1140 $contributionParams,
1144 CRM_Utils_Array
::value('is_recur', $this->_params
)
1147 $paymentParams['contributionID'] = $contribution->id
;
1148 $paymentParams['contributionTypeID'] = $contribution->financial_type_id
;
1149 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
1150 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1152 if ($paymentParams['amount'] > 0.0) {
1153 // force a re-get of the payment processor in case the form changed it, CRM-7179
1154 // NOTE - I expect this is obsolete.
1155 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
1157 $completeStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
1158 $result = $payment->doPayment($paymentParams, 'contribute');
1159 $this->assign('trxn_id', $result['trxn_id']);
1160 $contribution->trxn_id
= $result['trxn_id'];
1161 /* Our scenarios here are
1162 * 1) the payment failed & an Exception should have been thrown
1163 * 2) the payment succeeded but the payment is not immediate (for example a recurring payment
1164 * with a delayed start)
1165 * 3) the payment succeeded with an immediate payment.
1167 * The doPayment function ensures that payment_status_id is always set
1168 * as historically we have had to guess from the context - ie doDirectPayment
1169 * = error or success, unless it is a recurring contribution in which case it is pending.
1171 if ($result['payment_status_id'] == $completeStatusId) {
1173 civicrm_api3('contribution', 'completetransaction', array(
1174 'id' => $contribution->id
,
1175 'trxn_id' => $result['trxn_id'],
1176 'payment_processor_id' => $this->_paymentProcessor
['id'],
1177 'is_transactional' => FALSE,
1178 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $result),
1179 'card_type_id' => CRM_Utils_Array
::value('card_type_id', $paymentParams),
1180 'pan_truncation' => CRM_Utils_Array
::value('pan_truncation', $paymentParams),
1181 'is_email_receipt' => FALSE,
1183 // This has now been set to 1 in the DB - declare it here also
1184 $contribution->contribution_status_id
= 1;
1186 catch (CiviCRM_API3_Exception
$e) {
1187 if ($e->getErrorCode() != 'contribution_completed') {
1188 throw new CRM_Core_Exception('Failed to update contribution in database');
1193 // Save the trxn_id.
1194 $contribution->save();
1197 catch (PaymentProcessorException
$e) {
1198 CRM_Contribute_BAO_Contribution
::failPayment($contribution->id
, $paymentParams['contactID'], $e->getMessage());
1199 throw new PaymentProcessorException($e->getMessage());
1202 // Send receipt mail.
1203 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1204 if ($contribution->id
&& !empty($this->_params
['is_email_receipt'])) {
1205 $this->_params
['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $result);
1206 $this->_params
['contact_id'] = $contactID;
1207 $this->_params
['contribution_id'] = $contribution->id
;
1208 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $this->_params
, TRUE)) {
1209 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1213 return $contribution;
1217 * Generate the data to construct a snippet based pane.
1219 * This form also assigns the showAdditionalInfo var based on historical code.
1220 * This appears to mean 'there is a pane to show'.
1222 * @param string $type
1223 * Type of Pane - this is generally used to determine the function name used to build it
1224 * - e.g CreditCard, AdditionalDetail
1225 * @param array $defaults
1228 * We aim to further refactor & simplify this but currently
1230 * - should additional info be shown?
1232 protected function generatePane($type, $defaults) {
1233 $urlParams = "snippet=4&formType={$type}";
1235 $urlParams .= "&mode={$this->_mode}";
1239 if ($type == 'CreditCard' ||
1240 $type == 'DirectDebit'
1246 'url' => CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams),
1251 // See if we need to include this paneName in the current form.
1252 if ($this->_formType
== $type ||
!empty($_POST["hidden_{$type}"]) ||
1253 CRM_Utils_Array
::value("hidden_{$type}", $defaults)
1255 $this->assign('showAdditionalInfo', TRUE);
1256 $pane['open'] = 'true';
1259 if ($type == 'CreditCard' ||
$type == 'DirectDebit') {
1260 // @todo would be good to align tpl name with form name...
1261 // @todo document why this hidden variable is required.
1262 $this->add('hidden', 'hidden_' . $type, 1);
1266 $additionalInfoFormFunction = 'build' . $type;
1267 CRM_Contribute_Form_AdditionalInfo
::$additionalInfoFormFunction($this);
1273 * Wrapper for unit testing the post process submit function.
1275 * (If we expose through api we can get default additions 'for free').
1277 * @param array $params
1278 * @param int $action
1279 * @param string|null $creditCardMode
1281 * @throws \CiviCRM_API3_Exception
1283 public function testSubmit($params, $action, $creditCardMode = NULL) {
1285 'soft_credit_contact_id' => array(),
1286 'receive_date' => date('Y-m-d H:i:s'),
1287 'receipt_date' => '',
1288 'cancel_date' => '',
1289 'hidden_Premium' => 1,
1292 if (!empty($params['id'])) {
1293 $existingContribution = civicrm_api3('contribution', 'getsingle', array(
1294 'id' => $params['id'],
1296 $this->_id
= $params['id'];
1297 $this->_values
= $existingContribution;
1298 if (CRM_Contribute_BAO_Contribution
::checkContributeSettings('invoicing')) {
1299 $this->_values
['tax_amount'] = civicrm_api3('contribution', 'getvalue', array(
1300 'id' => $params['id'],
1301 'return' => 'tax_amount',
1306 $existingContribution = array();
1309 $this->_defaults
['contribution_status_id'] = CRM_Utils_Array
::value('contribution_status_id',
1310 $existingContribution
1313 $this->_defaults
['total_amount'] = CRM_Utils_Array
::value('total_amount',
1314 $existingContribution
1317 if ($creditCardMode) {
1318 $this->_mode
= $creditCardMode;
1321 // Required because processCreditCard calls set method on this.
1322 $_SERVER['REQUEST_METHOD'] = 'GET';
1323 $this->controller
= new CRM_Core_Controller();
1325 CRM_Contribute_Form_AdditionalInfo
::buildPremium($this);
1327 $this->_fields
= array();
1328 return $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array
::value('pledge_payment_id', $params));
1333 * @param array $submittedValues
1335 * @param int $action
1337 * - CRM_Core_Action::UPDATE
1339 * @param $pledgePaymentID
1342 * @throws \Exception
1344 protected function submit($submittedValues, $action, $pledgePaymentID) {
1345 $pId = $contribution = $isRelatedId = FALSE;
1346 $this->_params
= $submittedValues;
1347 $this->beginPostProcess();
1348 // reassign submitted form values if the any information is formatted via beginPostProcess
1349 $submittedValues = $this->_params
;
1351 if (!empty($submittedValues['price_set_id']) && $action & CRM_Core_Action
::UPDATE
) {
1352 $line = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution');
1353 $lineID = key($line);
1354 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array
::value('price_field_id', $line[$lineID]), 'price_set_id');
1355 $quickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1356 // Why do we do this? Seems like a like a wrapper for old functionality - but single line price sets & quick
1357 // config should be treated the same.
1359 CRM_Price_BAO_LineItem
::deleteLineItems($this->_id
, 'civicrm_contribution');
1363 // Process price set and get total amount and line items.
1364 $lineItem = array();
1365 $priceSetId = CRM_Utils_Array
::value('price_set_id', $submittedValues);
1366 if (empty($priceSetId) && !$this->_id
) {
1367 $this->_priceSetId
= $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1368 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
1369 $fieldID = key($this->_priceSet
['fields']);
1370 $fieldValueId = key($this->_priceSet
['fields'][$fieldID]['options']);
1371 $this->_priceSet
['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1372 $submittedValues['price_' . $fieldID] = 1;
1375 // Every contribution has a price-set - the only reason it shouldn't be set is if we are dealing with
1376 // quick config (very very arguably) & yet we see that this could still be quick config so this should be understood
1377 // as a point of fragility rather than a logical 'if' clause.
1379 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
1380 $submittedValues, $lineItem[$priceSetId], NULL, $priceSetId);
1381 // Unset tax amount for offline 'is_quick_config' contribution.
1382 // @todo WHY - quick config was conceived as a quick way to configure contribution forms.
1383 // this is an example of 'other' functionality being hung off it.
1384 if ($this->_priceSet
['is_quick_config'] &&
1385 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant
::getTaxRates())
1387 unset($submittedValues['tax_amount']);
1389 $submittedValues['total_amount'] = CRM_Utils_Array
::value('amount', $submittedValues);
1393 if ($this->_compId
) {
1394 if ($this->_context
== 'participant') {
1395 $pId = $this->_compId
;
1397 elseif ($this->_context
== 'membership') {
1398 $isRelatedId = TRUE;
1401 $pId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id
, 'participant_id', 'contribution_id');
1405 $contributionDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1406 if (array_key_exists('membership', $contributionDetails)) {
1407 $isRelatedId = TRUE;
1409 elseif (array_key_exists('participant', $contributionDetails)) {
1410 $pId = $contributionDetails['participant'];
1413 if (!empty($this->_payNow
)) {
1414 $this->_params
['contribution_id'] = $this->_id
;
1418 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id
) {
1419 // CRM-10117 update the line items for participants.
1420 // @todo - if we are completing a contribution then the api call
1421 // civicrm_api3('Contribution', 'completetransaction') should take care of
1422 // all associated updates rather than replicating them on the form layer.
1424 $entityTable = 'participant';
1426 $isRelatedId = FALSE;
1427 $participantParams = array(
1428 'fee_amount' => $submittedValues['total_amount'],
1431 CRM_Event_BAO_Participant
::add($participantParams);
1432 if (empty($this->_lineItems
)) {
1433 $this->_lineItems
[] = CRM_Price_BAO_LineItem
::getLineItems($entityID, 'participant', TRUE);
1437 $entityTable = 'contribution';
1438 $entityID = $this->_id
;
1441 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, $entityTable, FALSE, TRUE, $isRelatedId);
1442 foreach (array_keys($lineItems) as $id) {
1443 $lineItems[$id]['id'] = $id;
1445 $itemId = key($lineItems);
1446 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1447 $this->_priceSetId
= CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1450 // @todo see above - new functionality has been inappropriately added to the quick config concept
1451 // and new functionality has been added onto the form layer rather than the BAO :-(
1452 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1453 //CRM-16833: Ensure tax is applied only once for membership conribution, when status changed.(e.g Pending to Completed).
1454 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1455 if (!(CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails))) {
1456 if (!($this->_action
& CRM_Core_Action
::UPDATE
&& (($this->_defaults
['contribution_status_id'] != $submittedValues['contribution_status_id'])))) {
1457 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule
::cleanMoney(CRM_Utils_Array
::value('total_amount', $submittedValues));
1461 // Update line total and total amount with tax on edit.
1462 $financialItemsId = CRM_Core_PseudoConstant
::getTaxRates();
1463 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1464 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1467 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1468 $submittedValues['tax_amount'] = 'null';
1470 if ($lineItems[$itemId]['tax_rate']) {
1471 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total'];
1472 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] +
$lineItems[$itemId]['tax_amount'];
1473 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1476 // CRM-10117 update the line items for participants.
1477 if (!empty($lineItems[$itemId]['price_field_id'])) {
1478 $lineItem[$this->_priceSetId
] = $lineItems;
1483 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1486 //CRM-11529 for quick config back office transactions
1487 //when financial_type_id is passed in form, update the
1488 //line items with the financial type selected in form
1489 // NOTE that this IS still a legitimate use of 'quick-config' for contributions under the current DB but
1490 // we should look at having a price field per contribution type & then there would be little reason
1491 // for the back-office contribution form postProcess to know if it is a quick-config form.
1492 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array
::value($this->_priceSetId
, $lineItem)
1494 foreach ($lineItem[$this->_priceSetId
] as &$values) {
1495 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1499 if (!isset($submittedValues['total_amount'])) {
1500 $submittedValues['total_amount'] = CRM_Utils_Array
::value('total_amount', $this->_values
);
1501 // Avoid tax amount deduction on edit form and keep it original, because this will lead to error described in CRM-20676
1503 $submittedValues['total_amount'] -= CRM_Utils_Array
::value('tax_amount', $this->_values
, 0);
1506 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
1508 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
1509 if ($this->_id
&& count($isEmpty) == 1 && key($isEmpty) == NULL) {
1510 civicrm_api3('ContributionSoft', 'get', array('contribution_id' => $this->_id
, 'pcp_id' => NULL, 'api.ContributionSoft.delete' => 1));
1513 // set the contact, when contact is selected
1514 if (!empty($submittedValues['contact_id'])) {
1515 $this->_contactID
= $submittedValues['contact_id'];
1518 $formValues = $submittedValues;
1520 // Credit Card Contribution.
1522 $paramsSetByPaymentProcessingSubsystem = array(
1524 'payment_instrument_id',
1525 'contribution_status_id',
1529 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1530 if (isset($formValues[$key])) {
1531 unset($formValues[$key]);
1534 $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID
);
1535 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1536 $formValues[$key] = $contribution->$key;
1540 // Offline Contribution.
1541 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1543 // get the required field value only.
1546 'contact_id' => $this->_contactID
,
1547 'currency' => $this->getCurrency($submittedValues),
1548 'skipCleanMoney' => TRUE,
1552 //format soft-credit/pcp param first
1553 CRM_Contribute_BAO_ContributionSoft
::formatSoftCreditParams($submittedValues, $this);
1554 $params = array_merge($params, $submittedValues);
1557 'financial_type_id',
1558 'contribution_status_id',
1559 'payment_instrument_id',
1566 foreach ($fields as $f) {
1567 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1570 $params['revenue_recognition_date'] = NULL;
1571 if (!empty($formValues['revenue_recognition_date'])
1572 && count(array_filter($formValues['revenue_recognition_date'])) == 2
1574 $params['revenue_recognition_date'] = CRM_Utils_Date
::processDate(
1575 '01-' . implode('-', $formValues['revenue_recognition_date'])
1579 if (!empty($formValues['is_email_receipt'])) {
1580 $params['receipt_date'] = date("Y-m-d");
1583 if (CRM_Contribute_BAO_Contribution
::isContributionStatusNegative($params['contribution_status_id'])
1585 if (CRM_Utils_System
::isNull(CRM_Utils_Array
::value('cancel_date', $params))) {
1586 $params['cancel_date'] = date('YmdHis');
1590 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1593 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1594 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1595 if ($params['contribution_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending')) {
1596 $params['is_pay_later'] = 1;
1598 elseif ($params['contribution_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed')) {
1599 $params['is_pay_later'] = 0;
1602 // Add Additional common information to formatted params.
1603 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($formValues, $params, $this);
1605 $params['contribution_mode'] = 'participant';
1606 $params['participant_id'] = $pId;
1607 $params['skipLineItem'] = 1;
1609 elseif ($isRelatedId) {
1610 $params['contribution_mode'] = 'membership';
1612 $params['line_item'] = $lineItem;
1613 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array
::value('id', $this->_paymentProcessor
);
1614 $params['tax_amount'] = CRM_Utils_Array
::value('tax_amount', $submittedValues, CRM_Utils_Array
::value('tax_amount', $this->_values
));
1615 //create contribution.
1616 if ($isQuickConfig) {
1617 $params['is_quick_config'] = 1;
1619 $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
1621 // we are already handling note below, so to avoid duplicate notes against $contribution
1622 if (!empty($params['note']) && !empty($submittedValues['note'])) {
1623 unset($params['note']);
1625 $contribution = CRM_Contribute_BAO_Contribution
::create($params);
1627 // process associated membership / participant, CRM-4395
1628 if ($contribution->id
&& $action & CRM_Core_Action
::UPDATE
) {
1629 $this->statusMessage
[] = CRM_Contribute_BAO_Contribution
::transitionComponentWithReturnMessage($contribution->id
,
1630 $contribution->contribution_status_id
,
1631 CRM_Utils_Array
::value('contribution_status_id',
1634 $contribution->receive_date
1638 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1640 $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
1642 //send receipt mail.
1643 if ($contribution->id
&& !empty($formValues['is_email_receipt'])) {
1644 $formValues['contact_id'] = $this->_contactID
;
1645 $formValues['contribution_id'] = $contribution->id
;
1647 $formValues +
= CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
);
1649 // to get 'from email id' for send receipt
1650 $this->fromEmailId
= CRM_Utils_Array
::value('from_email_address', $formValues);
1651 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $formValues)) {
1652 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1656 $this->statusMessageTitle
= ts('Saved');
1660 if ($contribution->id
&& isset($formValues['product_name'][0])) {
1661 CRM_Contribute_Form_AdditionalInfo
::processPremium($submittedValues, $contribution->id
,
1662 $this->_premiumID
, $this->_options
1666 if ($contribution->id
&& array_key_exists('note', $submittedValues)) {
1667 CRM_Contribute_Form_AdditionalInfo
::processNote($submittedValues, $this->_contactID
, $contribution->id
, $this->_noteID
);
1670 CRM_Core_Session
::setStatus(implode(' ', $this->statusMessage
), $this->statusMessageTitle
, 'success');
1672 CRM_Contribute_BAO_Contribution
::updateRelatedPledge(
1676 (CRM_Utils_Array
::value('option_type', $formValues) == 2) ?
TRUE : FALSE,
1677 $formValues['total_amount'],
1678 CRM_Utils_Array
::value('total_amount', $this->_defaults
),
1679 $formValues['contribution_status_id'],
1680 CRM_Utils_Array
::value('contribution_status_id', $this->_defaults
)
1682 return $contribution;
1686 * Assign tax calculations to contribution receipts.
1688 * @param array $submittedValues
1689 * @param int $action
1690 * @param array $lineItem
1692 protected function invoicingPostProcessHook($submittedValues, $action, $lineItem) {
1694 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
1695 if (!CRM_Utils_Array
::value('invoicing', $invoiceSettings)) {
1699 $getTaxDetails = FALSE;
1701 foreach ($lineItem as $key => $value) {
1702 foreach ($value as $v) {
1703 if (isset($taxRate[(string) CRM_Utils_Array
::value('tax_rate', $v)])) {
1704 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $v);
1707 if (isset($v['tax_rate'])) {
1708 $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $v);
1709 $getTaxDetails = TRUE;
1715 if ($action & CRM_Core_Action
::UPDATE
) {
1716 if (isset($submittedValues['tax_amount'])) {
1717 $totalTaxAmount = $submittedValues['tax_amount'];
1720 $totalTaxAmount = $this->_values
['tax_amount'];
1722 $this->assign('totalTaxAmount', $totalTaxAmount);
1723 $this->assign('dataArray', $taxRate);
1726 if (!empty($submittedValues['price_set_id'])) {
1727 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1728 $this->assign('getTaxDetails', $getTaxDetails);
1729 $this->assign('dataArray', $taxRate);
1730 $this->assign('taxTerm', CRM_Utils_Array
::value('tax_term', $invoiceSettings));
1733 $this->assign('totalTaxAmount', CRM_Utils_Array
::value('tax_amount', $submittedValues));
1739 * Calculate non deductible amount.
1742 * if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1743 * if non_deductible_amount does NOT exist - then calculate it depending on:
1744 * $financialType->is_deductible and whether there is a product (premium).
1747 * @param $formValues
1751 protected function calculateNonDeductibleAmount($params, $formValues) {
1752 if (!empty($params['non_deductible_amount'])) {
1753 return $params['non_deductible_amount'];
1756 $priceSetId = CRM_Utils_Array
::value('price_set_id', $params);
1757 // return non-deductible amount if it is set at the price field option level
1758 if ($priceSetId && !empty($params['line_item'])) {
1759 $nonDeductibleAmount = CRM_Price_BAO_PriceSet
::getNonDeductibleAmountFromPriceSet($priceSetId, $params['line_item']);
1760 if (!empty($nonDeductibleAmount)) {
1761 return $nonDeductibleAmount;
1765 $financialType = new CRM_Financial_DAO_FinancialType();
1766 $financialType->id
= $params['financial_type_id'];
1767 $financialType->find(TRUE);
1769 if ($financialType->is_deductible
) {
1771 if (isset($formValues['product_name'][0])) {
1772 $selectProduct = $formValues['product_name'][0];
1774 // if there is a product - compare the value to the contribution amount
1775 if (isset($selectProduct)) {
1776 $productDAO = new CRM_Contribute_DAO_Product();
1777 $productDAO->id
= $selectProduct;
1778 $productDAO->find(TRUE);
1779 // product value exceeds contribution amount
1780 if ($params['total_amount'] < $productDAO->price
) {
1781 return $params['total_amount'];
1783 // product value does NOT exceed contribution amount
1785 return $productDAO->price
;
1788 // contribution is deductible - but there is no product
1793 // contribution is NOT deductible
1795 return $params['total_amount'];