3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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;
207 * Set variables up before form is built.
209 public function preProcess() {
210 // Check permission for action.
211 if (!CRM_Core_Permission
::checkActionPermission('CiviContribute', $this->_action
)) {
212 // @todo replace with throw new CRM_Core_Exception().
213 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
216 parent
::preProcess();
218 $this->_formType
= CRM_Utils_Array
::value('formType', $_GET);
221 $this->_priceSetId
= CRM_Utils_Array
::value('priceSetId', $_GET);
222 $this->set('priceSetId', $this->_priceSetId
);
223 $this->assign('priceSetId', $this->_priceSetId
);
225 // Get the pledge payment id
226 $this->_ppID
= CRM_Utils_Request
::retrieve('ppid', 'Positive', $this);
228 $this->assign('action', $this->_action
);
230 // Get the contribution id if update
231 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this);
232 if (!empty($this->_id
)) {
233 $this->assign('contribID', $this->_id
);
236 $this->_context
= CRM_Utils_Request
::retrieve('context', 'String', $this);
237 $this->assign('context', $this->_context
);
239 $this->_compId
= CRM_Utils_Request
::retrieve('compId', 'Positive', $this);
241 $this->_compContext
= CRM_Utils_Request
::retrieve('compContext', 'String', $this);
243 //set the contribution mode.
244 $this->_mode
= CRM_Utils_Request
::retrieve('mode', 'String', $this);
246 $this->assign('contributionMode', $this->_mode
);
247 if ($this->_action
& CRM_Core_Action
::DELETE
) {
251 $this->_fromEmails
= CRM_Core_BAO_Email
::getFromEmail();
253 if (in_array('CiviPledge', CRM_Core_Config
::singleton()->enableComponents
) && !$this->_formType
) {
254 $this->preProcessPledge();
258 $this->showRecordLinkMesssage($this->_id
);
260 $this->_values
= array();
262 // Current contribution id.
264 $this->assignPremiumProduct($this->_id
);
265 $this->buildValuesAndAssignOnline_Note_Type($this->_id
, $this->_values
);
268 // when custom data is included in this page
269 if (!empty($_POST['hidden_custom'])) {
270 $this->applyCustomData('Contribution', CRM_Utils_Array
::value('financial_type_id', $_POST), $this->_id
);
273 $this->_lineItems
= array();
275 if (!empty($this->_compId
) && $this->_compContext
== 'participant') {
276 $this->assign('compId', $this->_compId
);
277 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_compId
);
280 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution', 1, TRUE, TRUE);
283 empty($lineItem) ?
NULL : $this->_lineItems
[] = $lineItem;
286 $this->assign('lineItem', empty($lineItem) ?
FALSE : array($lineItem));
289 if ($this->_mode
&& $this->_id
) {
290 $this->_payNow
= TRUE;
291 $this->assign('payNow', $this->_payNow
);
292 CRM_Utils_System
::setTitle(ts('Pay with Credit Card'));
294 elseif ($this->_mode
) {
295 $this->setPageTitle($this->_ppID ?
ts('Credit Card Pledge Payment') : ts('Credit Card Contribution'));
298 $this->setPageTitle($this->_ppID ?
ts('Pledge Payment') : ts('Contribution'));
303 * Set default values.
307 public function setDefaultValues() {
308 $defaults = $this->_values
;
310 // Set defaults for pledge payment.
312 $defaults['total_amount'] = CRM_Utils_Array
::value('scheduled_amount', $this->_pledgeValues
['pledgePayment']);
313 $defaults['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $this->_pledgeValues
);
314 $defaults['currency'] = CRM_Utils_Array
::value('currency', $this->_pledgeValues
);
315 $defaults['option_type'] = 1;
318 if ($this->_action
& CRM_Core_Action
::DELETE
) {
322 $defaults['frequency_interval'] = 1;
323 $defaults['frequency_unit'] = 'month';
325 // Set soft credit defaults.
326 CRM_Contribute_Form_SoftCredit
::setDefaultValues($defaults, $this);
329 // @todo - remove this function as the parent does it too.
330 $config = CRM_Core_Config
::singleton();
331 // Set default country from config if no country set.
332 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
333 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry
;
336 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
337 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince
;
340 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID
);
341 $defaults = array_merge($defaults, $billingDefaults);
345 $this->_contactID
= $defaults['contact_id'];
348 // Set $newCredit variable in template to control whether link to credit card mode is included.
349 $this->assign('newCredit', CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments());
351 // Fix the display of the monetary value, CRM-4038.
352 if (isset($defaults['total_amount'])) {
353 if (!empty($defaults['tax_amount'])) {
354 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
355 if (!(CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails))) {
356 $defaults['total_amount'] = CRM_Utils_Money
::format($defaults['total_amount'] - $defaults['tax_amount'], NULL, '%a');
360 $defaults['total_amount'] = CRM_Utils_Money
::format($defaults['total_amount'], NULL, '%a');
364 $amountFields = array('non_deductible_amount', 'fee_amount', 'net_amount');
365 foreach ($amountFields as $amt) {
366 if (isset($defaults[$amt])) {
367 $defaults[$amt] = CRM_Utils_Money
::format($defaults[$amt], NULL, '%a');
371 if ($this->_contributionType
) {
372 $defaults['financial_type_id'] = $this->_contributionType
;
375 if (empty($defaults['payment_instrument_id'])) {
376 $defaults['payment_instrument_id'] = $this->getDefaultPaymentInstrumentId();
379 if (!empty($defaults['is_test'])) {
380 $this->assign('is_test', TRUE);
383 $this->assign('showOption', TRUE);
384 // For Premium section.
385 if ($this->_premiumID
) {
386 $this->assign('showOption', FALSE);
387 $options = isset($this->_options
[$this->_productDAO
->product_id
]) ?
$this->_options
[$this->_productDAO
->product_id
] : "";
389 $this->assign('showOption', TRUE);
391 $options_key = CRM_Utils_Array
::key($this->_productDAO
->product_option
, $options);
393 $defaults['product_name'] = array($this->_productDAO
->product_id
, trim($options_key));
396 $defaults['product_name'] = array($this->_productDAO
->product_id
);
398 if ($this->_productDAO
->fulfilled_date
) {
399 list($defaults['fulfilled_date']) = CRM_Utils_Date
::setDateDefaults($this->_productDAO
->fulfilled_date
);
403 if (isset($this->userEmail
)) {
404 $this->assign('email', $this->userEmail
);
407 if (!empty($defaults['is_pay_later'])) {
408 $this->assign('is_pay_later', TRUE);
410 $this->assign('contribution_status_id', CRM_Utils_Array
::value('contribution_status_id', $defaults));
411 if (!empty($defaults['contribution_status_id']) && in_array(
412 CRM_Contribute_PseudoConstant
::contributionStatus($defaults['contribution_status_id'], 'name'),
413 // Historically not 'Cancelled' hence not using CRM_Contribute_BAO_Contribution::isContributionStatusNegative.
414 array('Refunded', 'Chargeback')
416 $defaults['refund_trxn_id'] = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionTrxnID($this->_id
);
419 $defaults['refund_trxn_id'] = isset($defaults['trxn_id']) ?
$defaults['trxn_id'] : NULL;
427 foreach ($dates as $key) {
428 if (!empty($defaults[$key])) {
429 list($defaults[$key], $defaults[$key . '_time'])
430 = CRM_Utils_Date
::setDateDefaults(CRM_Utils_Array
::value($key, $defaults), 'activityDateTime');
434 if (!$this->_id
&& empty($defaults['receive_date'])) {
435 list($defaults['receive_date'],
436 $defaults['receive_date_time']
437 ) = CRM_Utils_Date
::setDateDefaults(NULL, 'activityDateTime');
440 $this->assign('receive_date', CRM_Utils_Date
::processDate(CRM_Utils_Array
::value('receive_date', $defaults),
441 CRM_Utils_Array
::value('receive_date_time', $defaults)
443 $currency = CRM_Utils_Array
::value('currency', $defaults);
444 $this->assign('currency', $currency);
445 // Hack to get currency info to the js layer. CRM-11440.
446 CRM_Utils_Money
::format(1);
447 $this->assign('currencySymbol', CRM_Utils_Array
::value($currency, CRM_Utils_Money
::$_currencySymbols));
448 $this->assign('totalAmount', CRM_Utils_Array
::value('total_amount', $defaults));
450 // Inherit campaign from pledge.
451 if ($this->_ppID
&& !empty($this->_pledgeValues
['campaign_id'])) {
452 $defaults['campaign_id'] = $this->_pledgeValues
['campaign_id'];
455 $this->_defaults
= $defaults;
460 * Build the form object.
462 public function buildQuickForm() {
463 // FIXME: This probably needs to be done in preprocess
464 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()
465 && $this->_action
& CRM_Core_Action
::UPDATE
466 && CRM_Utils_Array
::value('financial_type_id', $this->_values
)
468 $financialTypeID = CRM_Contribute_PseudoConstant
::financialType($this->_values
['financial_type_id']);
469 CRM_Financial_BAO_FinancialType
::checkPermissionedLineItems($this->_id
, 'edit');
470 if (!CRM_Core_Permission
::check('edit contributions of type ' . $financialTypeID)) {
471 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
476 //tax rate from financialType
477 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant
::getTaxRates()));
478 $this->assign('currencies', json_encode(CRM_Core_OptionGroup
::values('currencies_enabled')));
480 // build price set form.
481 $buildPriceSet = FALSE;
482 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
483 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
484 $this->assign('invoicing', $invoicing);
486 // display tax amount on edit contribution page
487 if ($invoicing && $this->_action
& CRM_Core_Action
::UPDATE
&& isset($this->_values
['tax_amount'])) {
488 $this->assign('totalTaxAmount', $this->_values
['tax_amount']);
491 if (empty($this->_lineItems
) &&
492 ($this->_priceSetId ||
!empty($_POST['price_set_id']))
494 $buildPriceSet = TRUE;
495 $getOnlyPriceSetElements = TRUE;
496 if (!$this->_priceSetId
) {
497 $this->_priceSetId
= $_POST['price_set_id'];
498 $getOnlyPriceSetElements = FALSE;
501 $this->set('priceSetId', $this->_priceSetId
);
502 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
504 // get only price set form elements.
505 if ($getOnlyPriceSetElements) {
509 // use to build form during form rule.
510 $this->assign('buildPriceSet', $buildPriceSet);
512 $defaults = $this->_values
;
513 $additionalDetailFields = array(
517 'non_deductible_amount',
521 foreach ($additionalDetailFields as $key) {
522 if (!empty($defaults[$key])) {
523 $defaults['hidden_AdditionalDetail'] = 1;
528 if ($this->_productDAO
) {
529 if ($this->_productDAO
->product_id
) {
530 $defaults['hidden_Premium'] = 1;
534 if ($this->_noteID
&&
535 isset($this->_values
['note'])
537 $defaults['hidden_AdditionalDetail'] = 1;
540 $paneNames = array();
541 if (empty($this->_payNow
)) {
542 $paneNames[ts('Additional Details')] = 'AdditionalDetail';
545 //Add Premium pane only if Premium is exists.
546 $dao = new CRM_Contribute_DAO_Product();
549 if ($dao->find(TRUE) && empty($this->_payNow
)) {
550 $paneNames[ts('Premium Information')] = 'Premium';
553 $this->payment_instrument_id
= CRM_Utils_Array
::value('payment_instrument_id', $defaults, $this->getDefaultPaymentInstrumentId());
554 if (CRM_Core_Payment_Form
::buildPaymentForm($this, $this->_paymentProcessor
, FALSE, TRUE, $this->payment_instrument_id
) == TRUE) {
555 if (!empty($this->_recurPaymentProcessors
)) {
556 $buildRecurBlock = TRUE;
558 // ppID denotes a pledge payment.
559 foreach ($this->_paymentProcessors
as $processor) {
560 if (!empty($processor['is_recur']) && !empty($processor['object']) && $processor['object']->supports('recurContributionsForPledges')) {
561 $buildRecurBlock = TRUE;
564 $buildRecurBlock = FALSE;
567 if ($buildRecurBlock) {
568 CRM_Contribute_Form_Contribution_Main
::buildRecur($this);
569 $this->setDefaults(array('is_recur' => 0));
570 $this->assign('buildRecurBlock', TRUE);
571 $recurJs = array('onChange' => "buildRecurBlock( this.value ); return false;");
576 foreach ($paneNames as $name => $type) {
577 $allPanes[$name] = $this->generatePane($type, $defaults);
580 $qfKey = $this->controller
->_key
;
581 $this->assign('qfKey', $qfKey);
582 $this->assign('allPanes', $allPanes);
584 $this->addFormRule(array('CRM_Contribute_Form_Contribution', 'formRule'), $this);
586 if ($this->_formType
) {
587 $this->assign('formType', $this->_formType
);
591 $this->applyFilter('__ALL__', 'trim');
593 if ($this->_action
& CRM_Core_Action
::DELETE
) {
594 $this->addButtons(array(
597 'name' => ts('Delete'),
598 'spacing' => ' ',
603 'name' => ts('Cancel'),
610 //need to assign custom data type and subtype to the template
611 $this->assign('customDataType', 'Contribution');
612 $this->assign('customDataSubType', $this->_contributionType
);
613 $this->assign('entityID', $this->_id
);
615 if ($this->_context
== 'standalone') {
616 $this->addEntityRef('contact_id', ts('Contact'), array(
618 'api' => array('extra' => array('email')),
622 $attributes = CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Contribution');
624 // Check permissions for financial type first
625 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes, $this->_action
);
626 if (empty($financialTypes)) {
627 CRM_Core_Error
::statusBounce(ts('You do not have all the permissions needed for this page.'));
629 $financialType = $this->add('select', 'financial_type_id',
630 ts('Financial Type'),
631 array('' => ts('- select -')) +
$financialTypes,
633 array('onChange' => "CRM.buildCustomData( 'Contribution', this.value );")
636 $paymentInstrument = FALSE;
638 $checkPaymentID = array_search('Check', CRM_Contribute_PseudoConstant
::paymentInstrument('name'));
639 $paymentInstrument = $this->add('select', 'payment_instrument_id',
640 ts('Payment Method'),
641 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::paymentInstrument(),
642 TRUE, array('onChange' => "return showHideByValue('payment_instrument_id','{$checkPaymentID}','checkNumber','table-row','select',false);")
646 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), array('class' => 'twelve') +
$attributes['trxn_id']);
648 //add receipt for offline contribution
649 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
651 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
654 $component = 'contribution';
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->addDateTime('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
703 if ($this->_online
) {
704 $this->assign('hideCalender', TRUE);
707 $this->addDateTime('receipt_date', ts('Receipt Date'), FALSE, array('formatType' => 'activityDateTime'));
708 $this->addDateTime('cancel_date', ts('Cancelled / Refunded Date'), FALSE, array('formatType' => 'activityDateTime'));
710 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
711 $this->add('text', 'refund_trxn_id', ts('Transaction ID for the refund payment'));
712 $element = $this->add('select',
713 'payment_processor_id',
714 ts('Payment Processor'),
720 if ($this->_online
) {
725 if (empty($this->_lineItems
)) {
726 $buildPriceSet = FALSE;
727 $priceSets = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute');
728 if (!empty($priceSets) && !$this->_ppID
) {
729 $buildPriceSet = TRUE;
732 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
733 // and if we already have line items for that participant. CRM-5095
734 if ($buildPriceSet && $this->_id
) {
735 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
736 $pledgePaymentId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
741 if ($pledgePaymentId) {
742 $buildPriceSet = FALSE;
744 if ($participantID = CRM_Utils_Array
::value('participant', $componentDetails)) {
745 $participantLI = CRM_Price_BAO_LineItem
::getLineItems($participantID);
746 if (!CRM_Utils_System
::isNull($participantLI)) {
747 $buildPriceSet = FALSE;
752 $hasPriceSets = FALSE;
753 if ($buildPriceSet) {
754 $hasPriceSets = TRUE;
755 // CRM-16451: set financial type of 'Price Set' in back office contribution
756 // instead of selecting manually
757 $financialTypeIds = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute', 'financial_type_id');
758 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
760 '' => ts('Choose price set'),
762 NULL, array('onchange' => "buildAmount( this.value, " . json_encode($financialTypeIds) . ");")
764 if ($this->_online
&& !($this->_action
& CRM_Core_Action
::UPDATE
)) {
768 $this->assign('hasPriceSets', $hasPriceSets);
769 if (!($this->_action
& CRM_Core_Action
::UPDATE
)) {
770 if ($this->_online ||
$this->_ppID
) {
771 $attributes['total_amount'] = array_merge($attributes['total_amount'], array(
773 'style' => "background-color:#EBECE4",
775 $optionTypes = array(
776 '1' => ts('Adjust Pledge Payment Schedule?'),
777 '2' => ts('Adjust Total Pledge Amount?'),
779 $this->addRadio('option_type',
785 $currencyFreeze = TRUE;
789 $totalAmount = $this->addMoney('total_amount',
791 ($hasPriceSets) ?
FALSE : TRUE,
792 $attributes['total_amount'],
793 TRUE, 'currency', NULL, $currencyFreeze
797 $this->add('text', 'source', ts('Source'), CRM_Utils_Array
::value('source', $attributes));
799 // CRM-7362 --add campaigns.
800 CRM_Campaign_BAO_Campaign
::addCampaign($this, CRM_Utils_Array
::value('campaign_id', $this->_values
));
802 if (empty($this->_payNow
)) {
803 CRM_Contribute_Form_SoftCredit
::buildQuickForm($this);
808 $js = array('onclick' => "return verify( );");
811 $mailingInfo = Civi
::settings()->get('mailing_backend');
812 $this->assign('outBound_option', $mailingInfo['outBound_option']);
814 $this->addButtons(array(
817 'name' => ts('Save'),
823 'name' => ts('Save and New'),
829 'name' => ts('Cancel'),
834 // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
835 // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
836 if ($this->_id
&& ($this->_values
['contribution_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Cancelled'))) {
838 $totalAmount->freeze();
840 $paymentInstrument->freeze();
842 $financialType->freeze();
845 // if contribution is related to membership or participant freeze Financial Type, Amount
846 if ($this->_id
&& isset($this->_values
['tax_amount'])) {
847 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
848 if (CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails)) {
850 $totalAmount->freeze();
852 $financialType->freeze();
853 $this->assign('freezeFinancialType', TRUE);
857 if ($this->_action
& CRM_Core_Action
::VIEW
) {
865 * @param array $fields
866 * The input form values.
867 * @param array $files
868 * The uploaded files if any.
872 * true if no errors, else array of errors
874 public static function formRule($fields, $files, $self) {
876 // Check for Credit Card Contribution.
878 if (empty($fields['payment_processor_id'])) {
879 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
882 // validate payment instrument (e.g. credit card number)
883 CRM_Core_Payment_Form
::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, NULL);
887 // Do the amount validations.
888 if (empty($fields['total_amount']) && empty($self->_lineItems
)) {
889 if ($priceSetId = CRM_Utils_Array
::value('price_set_id', $fields)) {
890 CRM_Price_BAO_PriceField
::priceSetValidation($priceSetId, $fields, $errors);
894 $softErrors = CRM_Contribute_Form_SoftCredit
::formRule($fields, $errors, $self);
896 if (!empty($fields['total_amount']) && (!empty($fields['net_amount']) ||
!empty($fields['fee_amount']))) {
897 $sum = CRM_Utils_Rule
::cleanMoney($fields['net_amount']) + CRM_Utils_Rule
::cleanMoney($fields['fee_amount']);
898 if (CRM_Utils_Rule
::cleanMoney($fields['total_amount']) != $sum) {
899 $errors['total_amount'] = ts('The sum of fee amount and net amount must be equal to total amount');
903 //CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
904 CRM_Contribute_BAO_ContributionRecur
::validateRecurContribution($fields, $files, $self, $errors);
906 // Form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
907 if (($self->_action
& CRM_Core_Action
::UPDATE
)
909 && $self->_values
['contribution_status_id'] != $fields['contribution_status_id']
911 CRM_Contribute_BAO_Contribution
::checkStatusValidation($self->_values
, $fields, $errors);
913 // CRM-16015, add form-rule to restrict change of financial type if using price field of different financial type
914 if (($self->_action
& CRM_Core_Action
::UPDATE
)
916 && $self->_values
['financial_type_id'] != $fields['financial_type_id']
918 CRM_Contribute_BAO_Contribution
::checkFinancialTypeChange(NULL, $self->_id
, $errors);
920 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
921 if (!empty($fields['fee_amount']) && !empty($fields['financial_type_id']) && $financialType = CRM_Contribute_BAO_Contribution
::validateFinancialType($fields['financial_type_id'])) {
922 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
925 // $trxn_id must be unique CRM-13919
926 if (!empty($fields['trxn_id'])) {
927 $queryParams = array(1 => array($fields['trxn_id'], 'String'));
928 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
930 $queryParams[2] = array((int) $self->_id
, 'Integer');
931 $query .= ' and id !=%2';
933 $tCnt = CRM_Core_DAO
::singleValueQuery($query, $queryParams);
935 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', array(1 => $fields['trxn_id']));
938 if (!empty($fields['revenue_recognition_date'])
939 && count(array_filter($fields['revenue_recognition_date'])) == 1
941 $errors['revenue_recognition_date'] = ts('Month and Year are required field for Revenue Recognition.');
945 CRM_Financial_BAO_FinancialAccount
::checkFinancialTypeHasDeferred($fields, $self->_id
, $self->_priceSet
['fields']);
947 catch (CRM_Core_Exception
$e) {
948 $errors['financial_type_id'] = ' ';
949 $errors['_qf_default'] = $e->getMessage();
951 $errors = array_merge($errors, $softErrors);
956 * Process the form submission.
958 public function postProcess() {
959 if ($this->_action
& CRM_Core_Action
::DELETE
) {
960 CRM_Contribute_BAO_Contribution
::deleteContribution($this->_id
);
961 CRM_Core_Session
::singleton()->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
962 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
966 // Get the submitted form values.
967 $submittedValues = $this->controller
->exportValues($this->_name
);
970 $contribution = $this->submit($submittedValues, $this->_action
, $this->_ppID
);
972 catch (PaymentProcessorException
$e) {
973 // Set the contribution mode.
974 $urlParams = "action=add&cid={$this->_contactID}";
976 $urlParams .= "&mode={$this->_mode}";
978 if (!empty($this->_ppID
)) {
979 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
982 CRM_Core_Error
::statusBounce($e->getMessage(), $urlParams, ts('Payment Processor Error'));
984 $session = CRM_Core_Session
::singleton();
985 $buttonName = $this->controller
->getButtonName();
986 if ($this->_context
== 'standalone') {
987 if ($buttonName == $this->getButtonName('upload', 'new')) {
988 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contribute/add',
989 'reset=1&action=add&context=standalone'
993 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
994 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
998 elseif ($this->_context
== 'contribution' && $this->_mode
&& $buttonName == $this->getButtonName('upload', 'new')) {
999 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
1000 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
1003 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1004 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
1005 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
1009 //store contribution ID if not yet set (on create)
1010 if (empty($this->_id
) && !empty($contribution->id
)) {
1011 $this->_id
= $contribution->id
;
1013 if (!empty($this->_id
) && CRM_Core_Permission
::access('CiviMember')) {
1014 $membershipPaymentCount = civicrm_api3('MembershipPayment', 'getCount', array('contribution_id' => $this->_id
));
1015 if ($membershipPaymentCount) {
1016 $this->ajaxResponse
['updateTabs']['#tab_member'] = CRM_Contact_BAO_Contact
::getCountComponent('membership', $this->_contactID
);
1019 if (!empty($this->_id
) && CRM_Core_Permission
::access('CiviEvent')) {
1020 $participantPaymentCount = civicrm_api3('ParticipantPayment', 'getCount', array('contribution_id' => $this->_id
));
1021 if ($participantPaymentCount) {
1022 $this->ajaxResponse
['updateTabs']['#tab_participant'] = CRM_Contact_BAO_Contact
::getCountComponent('participant', $this->_contactID
);
1028 * Process credit card payment.
1030 * @param array $submittedValues
1031 * @param array $lineItem
1033 * @param int $contactID
1036 * @return bool|\CRM_Contribute_DAO_Contribution
1037 * @throws \CRM_Core_Exception
1038 * @throws \Civi\Payment\Exception\PaymentProcessorException
1040 protected function processCreditCard($submittedValues, $lineItem, $contactID) {
1041 $isTest = ($this->_mode
== 'test') ?
1 : 0;
1042 // CRM-12680 set $_lineItem if its not set
1043 // @todo - I don't believe this would ever BE set. I can't find anywhere in the code.
1044 // It would be better to pass line item out to functions than $this->_lineItem as
1045 // we don't know what is being changed where.
1046 if (empty($this->_lineItem
) && !empty($lineItem)) {
1047 $this->_lineItem
= $lineItem;
1050 $this->_paymentObject
= Civi\Payment\System
::singleton()->getById($submittedValues['payment_processor_id']);
1051 $this->_paymentProcessor
= $this->_paymentObject
->getPaymentProcessor();
1053 // Set source if not set
1054 if (empty($submittedValues['source'])) {
1055 $userID = CRM_Core_Session
::singleton()->get('userID');
1056 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1059 $submittedValues['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
1062 $params = $submittedValues;
1063 $this->_params
= array_merge($this->_params
, $submittedValues);
1065 // Mapping requiring documentation.
1066 $this->_params
['payment_processor'] = $submittedValues['payment_processor_id'];
1068 $now = date('YmdHis');
1070 // we need to retrieve email address
1071 if ($this->_context
== 'standalone' && !empty($submittedValues['is_email_receipt'])) {
1072 list($this->userDisplayName
,
1074 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contactID);
1075 $this->assign('displayName', $this->userDisplayName
);
1078 $this->_contributorEmail
= $this->userEmail
;
1079 $this->_contributorContactID
= $contactID;
1080 $this->processBillingAddress();
1081 if (!empty($params['source'])) {
1082 unset($params['source']);
1085 $this->_params
['amount'] = $this->_params
['total_amount'];
1086 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
1087 // function to get correct amount level consistently. Remove setting of the amount level in
1088 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
1089 // to cover all variants.
1090 $this->_params
['amount_level'] = 0;
1091 $this->_params
['description'] = ts("Contribution submitted by a staff person using contributor's credit card");
1092 $this->_params
['currencyID'] = CRM_Utils_Array
::value('currency',
1094 CRM_Core_Config
::singleton()->defaultCurrency
1097 if (!empty($this->_params
['receive_date'])) {
1098 $this->_params
['receive_date'] = CRM_Utils_Date
::processDate($this->_params
['receive_date'], $this->_params
['receive_date_time']);
1101 $this->_params
['receive_date'] = $now;
1104 $this->_params
['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $params);
1105 $this->_params
['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $params);
1106 $this->_params
['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $params);
1108 //Add common data to formatted params
1109 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
1111 if (empty($this->_params
['invoice_id'])) {
1112 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
1115 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
1118 // At this point we've created a contact and stored its address etc
1119 // all the payment processors expect the name and address to be in the
1120 // so we copy stuff over to first_name etc.
1121 $paymentParams = $this->_params
;
1122 $paymentParams['contactID'] = $contactID;
1123 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
1125 $financialType = new CRM_Financial_DAO_FinancialType();
1126 $financialType->id
= $params['financial_type_id'];
1127 $financialType->find(TRUE);
1129 // Add some financial type details to the params list
1130 // if folks need to use it.
1131 $paymentParams['contributionType_name'] = $this->_params
['contributionType_name'] = $financialType->name
;
1132 $paymentParams['contributionPageID'] = NULL;
1134 if (!empty($this->_params
['is_email_receipt'])) {
1135 $paymentParams['email'] = $this->userEmail
;
1136 $paymentParams['is_email_receipt'] = 1;
1139 $paymentParams['is_email_receipt'] = 0;
1140 $this->_params
['is_email_receipt'] = 0;
1142 if (!empty($this->_params
['receive_date'])) {
1143 $paymentParams['receive_date'] = $this->_params
['receive_date'];
1146 if (!empty($this->_params
['is_email_receipt'])) {
1147 $this->_params
['receipt_date'] = $now;
1150 $this->_params
['receipt_date'] = CRM_Utils_Date
::processDate($this->_params
['receipt_date'],
1151 $params['receipt_date_time'], TRUE
1155 $this->set('params', $this->_params
);
1157 $this->assign('receive_date', $this->_params
['receive_date']);
1159 // Result has all the stuff we need
1160 // lets archive it to a financial transaction
1161 if ($financialType->is_deductible
) {
1162 $this->assign('is_deductible', TRUE);
1163 $this->set('is_deductible', TRUE);
1165 $contributionParams = array(
1166 'id' => CRM_Utils_Array
::value('contribution_id', $this->_params
),
1167 'contact_id' => $contactID,
1168 'line_item' => $lineItem,
1169 'is_test' => $isTest,
1170 'campaign_id' => CRM_Utils_Array
::value('campaign_id', $this->_params
),
1171 'contribution_page_id' => CRM_Utils_Array
::value('contribution_page_id', $this->_params
),
1172 'source' => CRM_Utils_Array
::value('source', $paymentParams, CRM_Utils_Array
::value('description', $paymentParams)),
1173 'thankyou_date' => CRM_Utils_Array
::value('thankyou_date', $this->_params
),
1175 $contributionParams['payment_instrument_id'] = $this->_paymentProcessor
['payment_instrument_id'];
1177 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processFormContribution($this,
1180 $contributionParams,
1184 CRM_Utils_Array
::value('is_recur', $this->_params
)
1187 $paymentParams['contributionID'] = $contribution->id
;
1188 $paymentParams['contributionTypeID'] = $contribution->financial_type_id
;
1189 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
1190 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1192 if ($paymentParams['amount'] > 0.0) {
1193 // force a re-get of the payment processor in case the form changed it, CRM-7179
1194 // NOTE - I expect this is obsolete.
1195 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
1197 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id');
1198 $result = $payment->doPayment($paymentParams, 'contribute');
1199 $this->assign('trxn_id', $result['trxn_id']);
1200 $contribution->trxn_id
= $result['trxn_id'];
1201 /* Our scenarios here are
1202 * 1) the payment failed & an Exception should have been thrown
1203 * 2) the payment succeeded but the payment is not immediate (for example a recurring payment
1204 * with a delayed start)
1205 * 3) the payment succeeded with an immediate payment.
1207 * The doPayment function ensures that payment_status_id is always set
1208 * as historically we have had to guess from the context - ie doDirectPayment
1209 * = error or success, unless it is a recurring contribution in which case it is pending.
1211 if ($result['payment_status_id'] == array_search('Completed', $statuses)) {
1213 civicrm_api3('contribution', 'completetransaction', array(
1214 'id' => $contribution->id
,
1215 'trxn_id' => $result['trxn_id'],
1216 'payment_processor_id' => $this->_paymentProcessor
['id'],
1217 'is_transactional' => FALSE,
1218 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $result),
1219 'card_type_id' => CRM_Utils_Array
::value('card_type_id', $paymentParams),
1220 'pan_truncation' => CRM_Utils_Array
::value('pan_truncation', $paymentParams),
1221 'is_email_receipt' => FALSE,
1223 // This has now been set to 1 in the DB - declare it here also
1224 $contribution->contribution_status_id
= 1;
1226 catch (CiviCRM_API3_Exception
$e) {
1227 if ($e->getErrorCode() != 'contribution_completed') {
1228 throw new CRM_Core_Exception('Failed to update contribution in database');
1233 // Save the trxn_id.
1234 $contribution->save();
1237 catch (PaymentProcessorException
$e) {
1238 CRM_Contribute_BAO_Contribution
::failPayment($contribution->id
, $paymentParams['contactID'], $e->getMessage());
1239 throw new PaymentProcessorException($e->getMessage());
1242 // Send receipt mail.
1243 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1244 if ($contribution->id
&& !empty($this->_params
['is_email_receipt'])) {
1245 $this->_params
['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $result);
1246 $this->_params
['contact_id'] = $contactID;
1247 $this->_params
['contribution_id'] = $contribution->id
;
1248 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $this->_params
, TRUE)) {
1249 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1253 return $contribution;
1257 * Generate the data to construct a snippet based pane.
1259 * This form also assigns the showAdditionalInfo var based on historical code.
1260 * This appears to mean 'there is a pane to show'.
1262 * @param string $type
1263 * Type of Pane - this is generally used to determine the function name used to build it
1264 * - e.g CreditCard, AdditionalDetail
1265 * @param array $defaults
1268 * We aim to further refactor & simplify this but currently
1270 * - should additional info be shown?
1272 protected function generatePane($type, $defaults) {
1273 $urlParams = "snippet=4&formType={$type}";
1275 $urlParams .= "&mode={$this->_mode}";
1279 if ($type == 'CreditCard' ||
1280 $type == 'DirectDebit'
1286 'url' => CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams),
1291 // See if we need to include this paneName in the current form.
1292 if ($this->_formType
== $type ||
!empty($_POST["hidden_{$type}"]) ||
1293 CRM_Utils_Array
::value("hidden_{$type}", $defaults)
1295 $this->assign('showAdditionalInfo', TRUE);
1296 $pane['open'] = 'true';
1299 if ($type == 'CreditCard' ||
$type == 'DirectDebit') {
1300 // @todo would be good to align tpl name with form name...
1301 // @todo document why this hidden variable is required.
1302 $this->add('hidden', 'hidden_' . $type, 1);
1306 $additionalInfoFormFunction = 'build' . $type;
1307 CRM_Contribute_Form_AdditionalInfo
::$additionalInfoFormFunction($this);
1313 * Wrapper for unit testing the post process submit function.
1315 * (If we expose through api we can get default additions 'for free').
1317 * @param array $params
1318 * @param int $action
1319 * @param string|null $creditCardMode
1321 * @throws \CiviCRM_API3_Exception
1323 public function testSubmit($params, $action, $creditCardMode = NULL) {
1325 'soft_credit_contact_id' => array(),
1326 'receipt_date' => '',
1327 'receipt_date_time' => '',
1328 'cancel_date' => '',
1329 'cancel_date_time' => '',
1330 'hidden_Premium' => 1,
1333 if (!empty($params['id'])) {
1334 $existingContribution = civicrm_api3('contribution', 'getsingle', array(
1335 'id' => $params['id'],
1337 $this->_id
= $params['id'];
1338 $this->_values
= $existingContribution;
1341 $existingContribution = array();
1344 $this->_defaults
['contribution_status_id'] = CRM_Utils_Array
::value('contribution_status_id',
1345 $existingContribution
1348 $this->_defaults
['total_amount'] = CRM_Utils_Array
::value('total_amount',
1349 $existingContribution
1352 if ($creditCardMode) {
1353 $this->_mode
= $creditCardMode;
1356 // Required because processCreditCard calls set method on this.
1357 $_SERVER['REQUEST_METHOD'] = 'GET';
1358 $this->controller
= new CRM_Core_Controller();
1360 CRM_Contribute_Form_AdditionalInfo
::buildPremium($this);
1362 $this->_fields
= array();
1363 return $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array
::value('pledge_payment_id', $params));
1368 * @param array $submittedValues
1370 * @param int $action
1372 * - CRM_Core_Action::UPDATE
1374 * @param $pledgePaymentID
1377 * @throws \Exception
1379 protected function submit($submittedValues, $action, $pledgePaymentID) {
1380 $pId = $contribution = $isRelatedId = FALSE;
1381 $this->_params
= $submittedValues;
1382 $this->beginPostProcess();
1383 // reassign submitted form values if the any information is formatted via beginPostProcess
1384 $submittedValues = $this->_params
;
1386 if (!empty($submittedValues['price_set_id']) && $action & CRM_Core_Action
::UPDATE
) {
1387 $line = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution');
1388 $lineID = key($line);
1389 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array
::value('price_field_id', $line[$lineID]), 'price_set_id');
1390 $quickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1391 // Why do we do this? Seems like a like a wrapper for old functionality - but single line price sets & quick
1392 // config should be treated the same.
1394 CRM_Price_BAO_LineItem
::deleteLineItems($this->_id
, 'civicrm_contribution');
1398 // Process price set and get total amount and line items.
1399 $lineItem = array();
1400 $priceSetId = CRM_Utils_Array
::value('price_set_id', $submittedValues);
1401 if (empty($priceSetId) && !$this->_id
) {
1402 $this->_priceSetId
= $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1403 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
1404 $fieldID = key($this->_priceSet
['fields']);
1405 $fieldValueId = key($this->_priceSet
['fields'][$fieldID]['options']);
1406 $this->_priceSet
['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1407 $submittedValues['price_' . $fieldID] = 1;
1410 // Every contribution has a price-set - the only reason it shouldn't be set is if we are dealing with
1411 // quick config (very very arguably) & yet we see that this could still be quick config so this should be understood
1412 // as a point of fragility rather than a logical 'if' clause.
1414 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
1415 $submittedValues, $lineItem[$priceSetId]);
1416 // Unset tax amount for offline 'is_quick_config' contribution.
1417 // @todo WHY - quick config was conceived as a quick way to configure contribution forms.
1418 // this is an example of 'other' functionality being hung off it.
1419 if ($this->_priceSet
['is_quick_config'] &&
1420 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant
::getTaxRates())
1422 unset($submittedValues['tax_amount']);
1424 // @todo - look to remove this line. I believe it relates to CRM-16460
1425 // and possibly contributes to fixing the issue described there but
1426 // would cause breakage for negative values in some cases.
1427 $submittedValues['total_amount'] = CRM_Utils_Array
::value('amount', $submittedValues);
1430 if ($this->_compId
) {
1431 if ($this->_context
== 'participant') {
1432 $pId = $this->_compId
;
1434 elseif ($this->_context
== 'membership') {
1435 $isRelatedId = TRUE;
1438 $pId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id
, 'participant_id', 'contribution_id');
1442 $contributionDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1443 if (array_key_exists('membership', $contributionDetails)) {
1444 $isRelatedId = TRUE;
1446 elseif (array_key_exists('participant', $contributionDetails)) {
1447 $pId = $contributionDetails['participant'];
1450 if (!empty($this->_payNow
)) {
1451 $this->_params
['contribution_id'] = $this->_id
;
1455 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id
) {
1456 // CRM-10117 update the line items for participants.
1457 // @todo - if we are completing a contribution then the api call
1458 // civicrm_api3('Contribution', 'completetransaction') should take care of
1459 // all associated updates rather than replicating them on the form layer.
1461 $entityTable = 'participant';
1463 $isRelatedId = FALSE;
1464 $participantParams = array(
1465 'fee_amount' => $submittedValues['total_amount'],
1468 CRM_Event_BAO_Participant
::add($participantParams);
1469 if (empty($this->_lineItems
)) {
1470 $this->_lineItems
[] = CRM_Price_BAO_LineItem
::getLineItems($entityID, 'participant', TRUE);
1474 $entityTable = 'contribution';
1475 $entityID = $this->_id
;
1478 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, $entityTable, FALSE, TRUE, $isRelatedId);
1479 foreach (array_keys($lineItems) as $id) {
1480 $lineItems[$id]['id'] = $id;
1482 $itemId = key($lineItems);
1483 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1484 $this->_priceSetId
= CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1487 // @todo see above - new functionality has been inappropriately added to the quick config concept
1488 // and new functionality has been added onto the form layer rather than the BAO :-(
1489 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1490 //CRM-16833: Ensure tax is applied only once for membership conribution, when status changed.(e.g Pending to Completed).
1491 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1492 if (!(CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails))) {
1493 if (!($this->_action
& CRM_Core_Action
::UPDATE
&& (($this->_defaults
['contribution_status_id'] != $submittedValues['contribution_status_id'])))) {
1494 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule
::cleanMoney(CRM_Utils_Array
::value('total_amount', $submittedValues));
1498 // Update line total and total amount with tax on edit.
1499 $financialItemsId = CRM_Core_PseudoConstant
::getTaxRates();
1500 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1501 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1504 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1505 $submittedValues['tax_amount'] = 'null';
1507 if ($lineItems[$itemId]['tax_rate']) {
1508 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total'];
1509 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] +
$lineItems[$itemId]['tax_amount'];
1510 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1513 // CRM-10117 update the line items for participants.
1514 if (!empty($lineItems[$itemId]['price_field_id'])) {
1515 $lineItem[$this->_priceSetId
] = $lineItems;
1520 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1523 //CRM-11529 for quick config back office transactions
1524 //when financial_type_id is passed in form, update the
1525 //line items with the financial type selected in form
1526 // NOTE that this IS still a legitimate use of 'quick-config' for contributions under the current DB but
1527 // we should look at having a price field per contribution type & then there would be little reason
1528 // for the back-office contribution form postProcess to know if it is a quick-config form.
1529 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array
::value($this->_priceSetId
, $lineItem)
1531 foreach ($lineItem[$this->_priceSetId
] as &$values) {
1532 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1536 if (!isset($submittedValues['total_amount'])) {
1537 $submittedValues['total_amount'] = CRM_Utils_Array
::value('total_amount', $this->_values
) - CRM_Utils_Array
::value('tax_amount', $this->_values
);
1539 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
1541 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
1542 if ($this->_id
&& count($isEmpty) == 1 && key($isEmpty) == NULL) {
1543 civicrm_api3('ContributionSoft', 'get', array('contribution_id' => $this->_id
, 'pcp_id' => NULL, 'api.ContributionSoft.delete' => 1));
1546 // set the contact, when contact is selected
1547 if (!empty($submittedValues['contact_id'])) {
1548 $this->_contactID
= $submittedValues['contact_id'];
1551 $formValues = $submittedValues;
1553 // Credit Card Contribution.
1555 $paramsSetByPaymentProcessingSubsystem = array(
1557 'payment_instrument_id',
1558 'contribution_status_id',
1562 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1563 if (isset($formValues[$key])) {
1564 unset($formValues[$key]);
1567 $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID
);
1568 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1569 $formValues[$key] = $contribution->$key;
1573 // Offline Contribution.
1574 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1576 // get the required field value only.
1578 $params = $ids = array();
1580 $params['contact_id'] = $this->_contactID
;
1581 $params['currency'] = $this->getCurrency($submittedValues);
1583 //format soft-credit/pcp param first
1584 CRM_Contribute_BAO_ContributionSoft
::formatSoftCreditParams($submittedValues, $this);
1585 $params = array_merge($params, $submittedValues);
1588 'financial_type_id',
1589 'contribution_status_id',
1590 'payment_instrument_id',
1597 foreach ($fields as $f) {
1598 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1601 // CRM-5740 if priceset is used, no need to cleanup money.
1603 $params['skipCleanMoney'] = 1;
1605 $params['revenue_recognition_date'] = NULL;
1606 if (!empty($formValues['revenue_recognition_date'])
1607 && count(array_filter($formValues['revenue_recognition_date'])) == 2
1609 $params['revenue_recognition_date'] = CRM_Utils_Date
::processDate(
1610 '01-' . implode('-', $formValues['revenue_recognition_date'])
1619 foreach ($dates as $d) {
1620 if (isset($formValues[$d])) {
1621 $params[$d] = CRM_Utils_Date
::processDate($formValues[$d], CRM_Utils_Array
::value($d . '_time', $formValues), TRUE);
1625 if (!empty($formValues['is_email_receipt'])) {
1626 $params['receipt_date'] = date("Y-m-d");
1629 if (CRM_Contribute_BAO_Contribution
::isContributionStatusNegative($params['contribution_status_id'])
1631 if (CRM_Utils_System
::isNull(CRM_Utils_Array
::value('cancel_date', $params))) {
1632 $params['cancel_date'] = date('YmdHis');
1636 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1639 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1640 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1641 if ($params['contribution_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending')) {
1642 $params['is_pay_later'] = 1;
1644 elseif ($params['contribution_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed')) {
1645 $params['is_pay_later'] = 0;
1648 $ids['contribution'] = $params['id'] = $this->_id
;
1650 // Add Additional common information to formatted params.
1651 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($formValues, $params, $this);
1653 $params['contribution_mode'] = 'participant';
1654 $params['participant_id'] = $pId;
1655 $params['skipLineItem'] = 1;
1657 elseif ($isRelatedId) {
1658 $params['contribution_mode'] = 'membership';
1660 $params['line_item'] = $lineItem;
1661 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array
::value('id', $this->_paymentProcessor
);
1662 if (isset($submittedValues['tax_amount'])) {
1663 $params['tax_amount'] = $submittedValues['tax_amount'];
1665 //create contribution.
1666 if ($isQuickConfig) {
1667 $params['is_quick_config'] = 1;
1669 $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
1671 // we are already handling note below, so to avoid duplicate notes against $contribution
1672 if (!empty($params['note']) && !empty($submittedValues['note'])) {
1673 unset($params['note']);
1675 $contribution = CRM_Contribute_BAO_Contribution
::create($params, $ids);
1677 // process associated membership / participant, CRM-4395
1678 if ($contribution->id
&& $action & CRM_Core_Action
::UPDATE
) {
1679 $this->statusMessage
[] = CRM_Contribute_BAO_Contribution
::transitionComponentWithReturnMessage($contribution->id
,
1680 $contribution->contribution_status_id
,
1681 CRM_Utils_Array
::value('contribution_status_id',
1684 $contribution->receive_date
1688 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1690 $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
1692 //send receipt mail.
1693 if ($contribution->id
&& !empty($formValues['is_email_receipt'])) {
1694 $formValues['contact_id'] = $this->_contactID
;
1695 $formValues['contribution_id'] = $contribution->id
;
1697 $formValues +
= CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
);
1699 // to get 'from email id' for send receipt
1700 $this->fromEmailId
= $formValues['from_email_address'];
1701 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $formValues)) {
1702 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1706 $this->statusMessageTitle
= ts('Saved');
1710 if ($contribution->id
&& isset($formValues['product_name'][0])) {
1711 CRM_Contribute_Form_AdditionalInfo
::processPremium($submittedValues, $contribution->id
,
1712 $this->_premiumID
, $this->_options
1716 if ($contribution->id
&& !empty($submittedValues['note'])) {
1717 CRM_Contribute_Form_AdditionalInfo
::processNote($submittedValues, $this->_contactID
, $contribution->id
, $this->_noteID
);
1720 CRM_Core_Session
::setStatus(implode(' ', $this->statusMessage
), $this->statusMessageTitle
, 'success');
1722 CRM_Contribute_BAO_Contribution
::updateRelatedPledge(
1726 (CRM_Utils_Array
::value('option_type', $formValues) == 2) ?
TRUE : FALSE,
1727 $formValues['total_amount'],
1728 CRM_Utils_Array
::value('total_amount', $this->_defaults
),
1729 $formValues['contribution_status_id'],
1730 CRM_Utils_Array
::value('contribution_status_id', $this->_defaults
)
1732 return $contribution;
1736 * Assign tax calculations to contribution receipts.
1738 * @param array $submittedValues
1739 * @param int $action
1740 * @param array $lineItem
1742 protected function invoicingPostProcessHook($submittedValues, $action, $lineItem) {
1744 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
1745 if (!CRM_Utils_Array
::value('invoicing', $invoiceSettings)) {
1749 $getTaxDetails = FALSE;
1751 foreach ($lineItem as $key => $value) {
1752 foreach ($value as $v) {
1753 if (isset($taxRate[(string) CRM_Utils_Array
::value('tax_rate', $v)])) {
1754 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $v);
1757 if (isset($v['tax_rate'])) {
1758 $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $v);
1759 $getTaxDetails = TRUE;
1765 if ($action & CRM_Core_Action
::UPDATE
) {
1766 if (isset($submittedValues['tax_amount'])) {
1767 $totalTaxAmount = $submittedValues['tax_amount'];
1770 $totalTaxAmount = $this->_values
['tax_amount'];
1772 $this->assign('totalTaxAmount', $totalTaxAmount);
1773 $this->assign('dataArray', $taxRate);
1776 if (!empty($submittedValues['price_set_id'])) {
1777 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1778 $this->assign('getTaxDetails', $getTaxDetails);
1779 $this->assign('dataArray', $taxRate);
1780 $this->assign('taxTerm', CRM_Utils_Array
::value('tax_term', $invoiceSettings));
1783 $this->assign('totalTaxAmount', CRM_Utils_Array
::value('tax_amount', $submittedValues));
1789 * Calculate non deductible amount.
1792 * if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1793 * if non_deductible_amount does NOT exist - then calculate it depending on:
1794 * $financialType->is_deductible and whether there is a product (premium).
1797 * @param $formValues
1801 protected function calculateNonDeductibleAmount($params, $formValues) {
1802 if (!empty($params['non_deductible_amount'])) {
1803 return $params['non_deductible_amount'];
1806 $priceSetId = CRM_Utils_Array
::value('price_set_id', $params);
1807 // return non-deductible amount if it is set at the price field option level
1808 if ($priceSetId && !empty($params['line_item'])) {
1809 $nonDeductibleAmount = CRM_Price_BAO_PriceSet
::getNonDeductibleAmountFromPriceSet($priceSetId, $params['line_item']);
1810 if (!empty($nonDeductibleAmount)) {
1811 return $nonDeductibleAmount;
1815 $financialType = new CRM_Financial_DAO_FinancialType();
1816 $financialType->id
= $params['financial_type_id'];
1817 $financialType->find(TRUE);
1819 if ($financialType->is_deductible
) {
1821 if (isset($formValues['product_name'][0])) {
1822 $selectProduct = $formValues['product_name'][0];
1824 // if there is a product - compare the value to the contribution amount
1825 if (isset($selectProduct)) {
1826 $productDAO = new CRM_Contribute_DAO_Product();
1827 $productDAO->id
= $selectProduct;
1828 $productDAO->find(TRUE);
1829 // product value exceeds contribution amount
1830 if ($params['total_amount'] < $productDAO->price
) {
1831 return $params['total_amount'];
1833 // product value does NOT exceed contribution amount
1835 return $productDAO->price
;
1838 // contribution is deductible - but there is no product
1843 // contribution is NOT deductible
1845 return $params['total_amount'];