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->assign('showCheckNumber', TRUE);
253 $this->_fromEmails
= CRM_Core_BAO_Email
::getFromEmail();
255 if (in_array('CiviPledge', CRM_Core_Config
::singleton()->enableComponents
) && !$this->_formType
) {
256 $this->preProcessPledge();
260 $this->showRecordLinkMesssage($this->_id
);
262 $this->_values
= array();
264 // Current contribution id.
266 $this->assignPremiumProduct($this->_id
);
267 $this->buildValuesAndAssignOnline_Note_Type($this->_id
, $this->_values
);
270 // when custom data is included in this page
271 if (!empty($_POST['hidden_custom'])) {
272 $this->applyCustomData('Contribution', CRM_Utils_Array
::value('financial_type_id', $_POST), $this->_id
);
275 $this->_lineItems
= array();
277 if (!empty($this->_compId
) && $this->_compContext
== 'participant') {
278 $this->assign('compId', $this->_compId
);
279 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_compId
);
282 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution', 1, TRUE, TRUE);
285 empty($lineItem) ?
NULL : $this->_lineItems
[] = $lineItem;
288 $this->assign('lineItem', empty($lineItem) ?
FALSE : array($lineItem));
291 if ($this->_mode
&& $this->_id
) {
292 $this->_payNow
= TRUE;
293 $this->assign('payNow', $this->_payNow
);
294 CRM_Utils_System
::setTitle(ts('Pay with Credit Card'));
296 elseif ($this->_mode
) {
297 $this->setPageTitle($this->_ppID ?
ts('Credit Card Pledge Payment') : ts('Credit Card Contribution'));
300 $this->setPageTitle($this->_ppID ?
ts('Pledge Payment') : ts('Contribution'));
305 * Set default values.
309 public function setDefaultValues() {
310 $defaults = $this->_values
;
312 // Set defaults for pledge payment.
314 $defaults['total_amount'] = CRM_Utils_Array
::value('scheduled_amount', $this->_pledgeValues
['pledgePayment']);
315 $defaults['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $this->_pledgeValues
);
316 $defaults['currency'] = CRM_Utils_Array
::value('currency', $this->_pledgeValues
);
317 $defaults['option_type'] = 1;
320 if ($this->_action
& CRM_Core_Action
::DELETE
) {
324 $defaults['frequency_interval'] = 1;
325 $defaults['frequency_unit'] = 'month';
327 // Set soft credit defaults.
328 CRM_Contribute_Form_SoftCredit
::setDefaultValues($defaults, $this);
331 // @todo - remove this function as the parent does it too.
332 $config = CRM_Core_Config
::singleton();
333 // Set default country from config if no country set.
334 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
335 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry
;
338 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
339 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince
;
342 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID
);
343 $defaults = array_merge($defaults, $billingDefaults);
347 $this->_contactID
= $defaults['contact_id'];
350 // Set $newCredit variable in template to control whether link to credit card mode is included.
351 $this->assign('newCredit', CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments());
353 // Fix the display of the monetary value, CRM-4038.
354 if (isset($defaults['total_amount'])) {
355 if (!empty($defaults['tax_amount'])) {
356 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
357 if (!(CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails))) {
358 $defaults['total_amount'] = CRM_Utils_Money
::format($defaults['total_amount'] - $defaults['tax_amount'], NULL, '%a');
362 $defaults['total_amount'] = CRM_Utils_Money
::format($defaults['total_amount'], NULL, '%a');
366 $amountFields = array('non_deductible_amount', 'fee_amount', 'net_amount');
367 foreach ($amountFields as $amt) {
368 if (isset($defaults[$amt])) {
369 $defaults[$amt] = CRM_Utils_Money
::format($defaults[$amt], NULL, '%a');
373 if ($this->_contributionType
) {
374 $defaults['financial_type_id'] = $this->_contributionType
;
377 if (empty($defaults['payment_instrument_id'])) {
378 $defaults['payment_instrument_id'] = $this->getDefaultPaymentInstrumentId();
381 if (!empty($defaults['is_test'])) {
382 $this->assign('is_test', TRUE);
385 $this->assign('showOption', TRUE);
386 // For Premium section.
387 if ($this->_premiumID
) {
388 $this->assign('showOption', FALSE);
389 $options = isset($this->_options
[$this->_productDAO
->product_id
]) ?
$this->_options
[$this->_productDAO
->product_id
] : "";
391 $this->assign('showOption', TRUE);
393 $options_key = CRM_Utils_Array
::key($this->_productDAO
->product_option
, $options);
395 $defaults['product_name'] = array($this->_productDAO
->product_id
, trim($options_key));
398 $defaults['product_name'] = array($this->_productDAO
->product_id
);
400 if ($this->_productDAO
->fulfilled_date
) {
401 list($defaults['fulfilled_date']) = CRM_Utils_Date
::setDateDefaults($this->_productDAO
->fulfilled_date
);
405 if (isset($this->userEmail
)) {
406 $this->assign('email', $this->userEmail
);
409 if (!empty($defaults['is_pay_later'])) {
410 $this->assign('is_pay_later', TRUE);
412 $this->assign('contribution_status_id', CRM_Utils_Array
::value('contribution_status_id', $defaults));
413 if (!empty($defaults['contribution_status_id']) && in_array(
414 CRM_Contribute_PseudoConstant
::contributionStatus($defaults['contribution_status_id'], 'name'),
415 // Historically not 'Cancelled' hence not using CRM_Contribute_BAO_Contribution::isContributionStatusNegative.
416 array('Refunded', 'Chargeback')
418 $defaults['refund_trxn_id'] = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionTrxnID($this->_id
);
421 $defaults['refund_trxn_id'] = isset($defaults['trxn_id']) ?
$defaults['trxn_id'] : NULL;
429 foreach ($dates as $key) {
430 if (!empty($defaults[$key])) {
431 list($defaults[$key], $defaults[$key . '_time'])
432 = CRM_Utils_Date
::setDateDefaults(CRM_Utils_Array
::value($key, $defaults), 'activityDateTime');
436 if (!$this->_id
&& empty($defaults['receive_date'])) {
437 list($defaults['receive_date'],
438 $defaults['receive_date_time']
439 ) = CRM_Utils_Date
::setDateDefaults(NULL, 'activityDateTime');
442 $this->assign('receive_date', CRM_Utils_Date
::processDate(CRM_Utils_Array
::value('receive_date', $defaults),
443 CRM_Utils_Array
::value('receive_date_time', $defaults)
445 $currency = CRM_Utils_Array
::value('currency', $defaults);
446 $this->assign('currency', $currency);
447 // Hack to get currency info to the js layer. CRM-11440.
448 CRM_Utils_Money
::format(1);
449 $this->assign('currencySymbol', CRM_Utils_Array
::value($currency, CRM_Utils_Money
::$_currencySymbols));
450 $this->assign('totalAmount', CRM_Utils_Array
::value('total_amount', $defaults));
452 // Inherit campaign from pledge.
453 if ($this->_ppID
&& !empty($this->_pledgeValues
['campaign_id'])) {
454 $defaults['campaign_id'] = $this->_pledgeValues
['campaign_id'];
457 $this->_defaults
= $defaults;
462 * Build the form object.
464 public function buildQuickForm() {
465 // FIXME: This probably needs to be done in preprocess
466 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()
467 && $this->_action
& CRM_Core_Action
::UPDATE
468 && CRM_Utils_Array
::value('financial_type_id', $this->_values
)
470 $financialTypeID = CRM_Contribute_PseudoConstant
::financialType($this->_values
['financial_type_id']);
471 CRM_Financial_BAO_FinancialType
::checkPermissionedLineItems($this->_id
, 'edit');
472 if (!CRM_Core_Permission
::check('edit contributions of type ' . $financialTypeID)) {
473 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
478 //tax rate from financialType
479 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant
::getTaxRates()));
480 $this->assign('currencies', json_encode(CRM_Core_OptionGroup
::values('currencies_enabled')));
482 // build price set form.
483 $buildPriceSet = FALSE;
484 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
485 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
486 $this->assign('invoicing', $invoicing);
488 // display tax amount on edit contribution page
489 if ($invoicing && $this->_action
& CRM_Core_Action
::UPDATE
&& isset($this->_values
['tax_amount'])) {
490 $this->assign('totalTaxAmount', $this->_values
['tax_amount']);
493 if (empty($this->_lineItems
) &&
494 ($this->_priceSetId ||
!empty($_POST['price_set_id']))
496 $buildPriceSet = TRUE;
497 $getOnlyPriceSetElements = TRUE;
498 if (!$this->_priceSetId
) {
499 $this->_priceSetId
= $_POST['price_set_id'];
500 $getOnlyPriceSetElements = FALSE;
503 $this->set('priceSetId', $this->_priceSetId
);
504 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
506 // get only price set form elements.
507 if ($getOnlyPriceSetElements) {
511 // use to build form during form rule.
512 $this->assign('buildPriceSet', $buildPriceSet);
514 $defaults = $this->_values
;
515 $additionalDetailFields = array(
519 'non_deductible_amount',
523 foreach ($additionalDetailFields as $key) {
524 if (!empty($defaults[$key])) {
525 $defaults['hidden_AdditionalDetail'] = 1;
530 if ($this->_productDAO
) {
531 if ($this->_productDAO
->product_id
) {
532 $defaults['hidden_Premium'] = 1;
536 if ($this->_noteID
&&
537 isset($this->_values
['note'])
539 $defaults['hidden_AdditionalDetail'] = 1;
542 $paneNames = array();
543 if (empty($this->_payNow
)) {
544 $paneNames[ts('Additional Details')] = 'AdditionalDetail';
547 //Add Premium pane only if Premium is exists.
548 $dao = new CRM_Contribute_DAO_Product();
551 if ($dao->find(TRUE) && empty($this->_payNow
)) {
552 $paneNames[ts('Premium Information')] = 'Premium';
555 if (CRM_Core_Payment_Form
::buildPaymentForm($this, $this->_paymentProcessor
, FALSE, TRUE, $this->getDefaultPaymentInstrumentId()) == TRUE) {
556 if (!empty($this->_recurPaymentProcessors
)) {
557 $buildRecurBlock = TRUE;
559 // ppID denotes a pledge payment.
560 foreach ($this->_paymentProcessors
as $processor) {
561 if (!empty($processor['is_recur']) && !empty($processor['object']) && $processor['object']->supports('recurContributionsForPledges')) {
562 $buildRecurBlock = TRUE;
565 $buildRecurBlock = FALSE;
568 if ($buildRecurBlock) {
569 CRM_Contribute_Form_Contribution_Main
::buildRecur($this);
570 $this->setDefaults(array('is_recur' => 0));
571 $this->assign('buildRecurBlock', TRUE);
572 $recurJs = array('onChange' => "buildRecurBlock( this.value ); return false;");
577 foreach ($paneNames as $name => $type) {
578 $allPanes[$name] = $this->generatePane($type, $defaults);
581 $qfKey = $this->controller
->_key
;
582 $this->assign('qfKey', $qfKey);
583 $this->assign('allPanes', $allPanes);
585 $this->addFormRule(array('CRM_Contribute_Form_Contribution', 'formRule'), $this);
587 if ($this->_formType
) {
588 $this->assign('formType', $this->_formType
);
592 $this->applyFilter('__ALL__', 'trim');
594 if ($this->_action
& CRM_Core_Action
::DELETE
) {
595 $this->addButtons(array(
598 'name' => ts('Delete'),
599 'spacing' => ' ',
604 'name' => ts('Cancel'),
611 //need to assign custom data type and subtype to the template
612 $this->assign('customDataType', 'Contribution');
613 $this->assign('customDataSubType', $this->_contributionType
);
614 $this->assign('entityID', $this->_id
);
616 if ($this->_context
== 'standalone') {
617 $this->addEntityRef('contact_id', ts('Contact'), array(
619 'api' => array('extra' => array('email')),
623 $attributes = CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Contribution');
625 // Check permissions for financial type first
626 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes, $this->_action
);
627 if (empty($financialTypes)) {
628 CRM_Core_Error
::statusBounce(ts('You do not have all the permissions needed for this page.'));
630 $financialType = $this->add('select', 'financial_type_id',
631 ts('Financial Type'),
632 array('' => ts('- select -')) +
$financialTypes,
634 array('onChange' => "CRM.buildCustomData( 'Contribution', this.value );")
637 $paymentInstrument = FALSE;
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 TRUE, 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 $status = CRM_Contribute_PseudoConstant
::contributionStatus();
656 // suppressing contribution statuses that are NOT relevant to pledges (CRM-5169)
657 $statusName = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
664 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
667 elseif ((!$this->_ppID
&& $this->_id
) ||
!$this->_id
) {
668 $suppressFlag = FALSE;
670 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
671 if (CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails)) {
672 $suppressFlag = TRUE;
675 if (!$suppressFlag) {
680 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
684 unset($status[CRM_Utils_Array
::key('Overdue', $statusName)]);
688 // define the status IDs that show the cancellation info, see CRM-17589
689 $cancelInfo_show_ids = array();
690 foreach (array_keys($statusName) as $status_id) {
691 if (CRM_Contribute_BAO_Contribution
::isContributionStatusNegative($status_id)) {
692 $cancelInfo_show_ids[] = "'$status_id'";
695 $this->assign('cancelInfo_show_ids', implode(',', $cancelInfo_show_ids));
698 $contributionStatus = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_id
, 'contribution_status_id');
699 $name = CRM_Utils_Array
::value($contributionStatus, $statusName);
702 // [CRM-17498] Removing unsupported status change options.
703 unset($status[CRM_Utils_Array
::key('Pending', $statusName)]);
704 unset($status[CRM_Utils_Array
::key('Failed', $statusName)]);
705 unset($status[CRM_Utils_Array
::key('Partially paid', $statusName)]);
706 unset($status[CRM_Utils_Array
::key('Pending refund', $statusName)]);
710 unset($status[CRM_Utils_Array
::key('In Progress', $statusName)]);
711 unset($status[CRM_Utils_Array
::key('Pending', $statusName)]);
712 unset($status[CRM_Utils_Array
::key('Failed', $statusName)]);
717 unset($status[CRM_Utils_Array
::key('Refunded', $statusName)]);
718 unset($status[CRM_Utils_Array
::key('Chargeback', $statusName)]);
730 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
736 unset($status[CRM_Utils_Array
::key('Refunded', $statusName)]);
737 unset($status[CRM_Utils_Array
::key('Chargeback', $statusName)]);
740 $statusElement = $this->add('select', 'contribution_status_id',
741 ts('Contribution Status'),
746 $currencyFreeze = FALSE;
747 if (!empty($this->_payNow
) && ($this->_action
& CRM_Core_Action
::UPDATE
)) {
748 $statusElement->freeze();
749 $currencyFreeze = TRUE;
750 $attributes['total_amount']['readonly'] = TRUE;
753 // CRM-16189, add Revenue Recognition Date
754 if (CRM_Contribute_BAO_Contribution
::checkContributeSettings('deferred_revenue_enabled')) {
755 $revenueDate = $this->add('date', 'revenue_recognition_date', ts('Revenue Recognition Date'), CRM_Core_SelectValues
::date(NULL, 'M Y', NULL, 5));
756 if ($this->_id
&& !CRM_Contribute_BAO_Contribution
::allowUpdateRevenueRecognitionDate($this->_id
)) {
757 $revenueDate->freeze();
762 $this->addDateTime('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
764 if ($this->_online
) {
765 $this->assign('hideCalender', TRUE);
767 $checkNumber = $this->add('text', 'check_number', ts('Check Number'), $attributes['contribution_check_number']);
769 $this->addDateTime('receipt_date', ts('Receipt Date'), FALSE, array('formatType' => 'activityDateTime'));
770 $this->addDateTime('cancel_date', ts('Cancelled / Refunded Date'), FALSE, array('formatType' => 'activityDateTime'));
772 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
773 $this->add('text', 'refund_trxn_id', ts('Transaction ID for the refund payment'));
774 $element = $this->add('select',
775 'payment_processor_id',
776 ts('Payment Processor'),
782 if ($this->_online
) {
787 if (empty($this->_lineItems
)) {
788 $buildPriceSet = FALSE;
789 $priceSets = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute');
790 if (!empty($priceSets) && !$this->_ppID
) {
791 $buildPriceSet = TRUE;
794 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
795 // and if we already have line items for that participant. CRM-5095
796 if ($buildPriceSet && $this->_id
) {
797 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
798 $pledgePaymentId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
803 if ($pledgePaymentId) {
804 $buildPriceSet = FALSE;
806 if ($participantID = CRM_Utils_Array
::value('participant', $componentDetails)) {
807 $participantLI = CRM_Price_BAO_LineItem
::getLineItems($participantID);
808 if (!CRM_Utils_System
::isNull($participantLI)) {
809 $buildPriceSet = FALSE;
814 $hasPriceSets = FALSE;
815 if ($buildPriceSet) {
816 $hasPriceSets = TRUE;
817 // CRM-16451: set financial type of 'Price Set' in back office contribution
818 // instead of selecting manually
819 $financialTypeIds = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute', 'financial_type_id');
820 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
822 '' => ts('Choose price set'),
824 NULL, array('onchange' => "buildAmount( this.value, " . json_encode($financialTypeIds) . ");")
826 if ($this->_online
&& !($this->_action
& CRM_Core_Action
::UPDATE
)) {
830 $this->assign('hasPriceSets', $hasPriceSets);
831 if (!($this->_action
& CRM_Core_Action
::UPDATE
)) {
832 if ($this->_online ||
$this->_ppID
) {
833 $attributes['total_amount'] = array_merge($attributes['total_amount'], array(
835 'style' => "background-color:#EBECE4",
837 $optionTypes = array(
838 '1' => ts('Adjust Pledge Payment Schedule?'),
839 '2' => ts('Adjust Total Pledge Amount?'),
841 $this->addRadio('option_type',
847 $currencyFreeze = TRUE;
851 $totalAmount = $this->addMoney('total_amount',
853 ($hasPriceSets) ?
FALSE : TRUE,
854 $attributes['total_amount'],
855 TRUE, 'currency', NULL, $currencyFreeze
859 $this->add('text', 'source', ts('Source'), CRM_Utils_Array
::value('source', $attributes));
861 // CRM-7362 --add campaigns.
862 CRM_Campaign_BAO_Campaign
::addCampaign($this, CRM_Utils_Array
::value('campaign_id', $this->_values
));
864 if (empty($this->_payNow
)) {
865 CRM_Contribute_Form_SoftCredit
::buildQuickForm($this);
870 $js = array('onclick' => "return verify( );");
873 $mailingInfo = Civi
::settings()->get('mailing_backend');
874 $this->assign('outBound_option', $mailingInfo['outBound_option']);
876 $this->addButtons(array(
879 'name' => ts('Save'),
885 'name' => ts('Save and New'),
891 'name' => ts('Close'),
896 // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
897 // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
898 if ($this->_id
&& $this->_values
['contribution_status_id'] == array_search('Cancelled', $statusName)) {
900 $totalAmount->freeze();
902 $checkNumber->freeze();
903 $paymentInstrument->freeze();
905 $financialType->freeze();
908 // if contribution is related to membership or participant freeze Financial Type, Amount
909 if ($this->_id
&& isset($this->_values
['tax_amount'])) {
910 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
911 if (CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails)) {
913 $totalAmount->freeze();
915 $financialType->freeze();
916 $this->assign('freezeFinancialType', TRUE);
920 if ($this->_action
& CRM_Core_Action
::VIEW
) {
928 * @param array $fields
929 * The input form values.
930 * @param array $files
931 * The uploaded files if any.
935 * true if no errors, else array of errors
937 public static function formRule($fields, $files, $self) {
939 // Check for Credit Card Contribution.
941 if (empty($fields['payment_processor_id'])) {
942 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
945 // validate payment instrument (e.g. credit card number)
946 CRM_Core_Payment_Form
::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, NULL);
950 // Do the amount validations.
951 if (empty($fields['total_amount']) && empty($self->_lineItems
)) {
952 if ($priceSetId = CRM_Utils_Array
::value('price_set_id', $fields)) {
953 CRM_Price_BAO_PriceField
::priceSetValidation($priceSetId, $fields, $errors);
957 $softErrors = CRM_Contribute_Form_SoftCredit
::formRule($fields, $errors, $self);
959 if (!empty($fields['total_amount']) && (!empty($fields['net_amount']) ||
!empty($fields['fee_amount']))) {
960 $sum = CRM_Utils_Rule
::cleanMoney($fields['net_amount']) + CRM_Utils_Rule
::cleanMoney($fields['fee_amount']);
961 if (CRM_Utils_Rule
::cleanMoney($fields['total_amount']) != $sum) {
962 $errors['total_amount'] = ts('The sum of fee amount and net amount must be equal to total amount');
966 //CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
967 CRM_Contribute_BAO_ContributionRecur
::validateRecurContribution($fields, $files, $self, $errors);
969 // Form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
970 if (($self->_action
& CRM_Core_Action
::UPDATE
)
972 && $self->_values
['contribution_status_id'] != $fields['contribution_status_id']
974 CRM_Contribute_BAO_Contribution
::checkStatusValidation($self->_values
, $fields, $errors);
976 // CRM-16015, add form-rule to restrict change of financial type if using price field of different financial type
977 if (($self->_action
& CRM_Core_Action
::UPDATE
)
979 && $self->_values
['financial_type_id'] != $fields['financial_type_id']
981 CRM_Contribute_BAO_Contribution
::checkFinancialTypeChange(NULL, $self->_id
, $errors);
983 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
984 if (!empty($fields['fee_amount']) && !empty($fields['financial_type_id']) && $financialType = CRM_Contribute_BAO_Contribution
::validateFinancialType($fields['financial_type_id'])) {
985 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
988 // $trxn_id must be unique CRM-13919
989 if (!empty($fields['trxn_id'])) {
990 $queryParams = array(1 => array($fields['trxn_id'], 'String'));
991 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
993 $queryParams[2] = array((int) $self->_id
, 'Integer');
994 $query .= ' and id !=%2';
996 $tCnt = CRM_Core_DAO
::singleValueQuery($query, $queryParams);
998 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', array(1 => $fields['trxn_id']));
1001 if (!empty($fields['revenue_recognition_date'])
1002 && count(array_filter($fields['revenue_recognition_date'])) == 1
1004 $errors['revenue_recognition_date'] = ts('Month and Year are required field for Revenue Recognition.');
1008 CRM_Financial_BAO_FinancialAccount
::checkFinancialTypeHasDeferred($fields, $self->_id
, $self->_priceSet
['fields']);
1010 catch (CRM_Core_Exception
$e) {
1011 $errors['financial_type_id'] = ' ';
1012 $errors['_qf_default'] = $e->getMessage();
1014 $errors = array_merge($errors, $softErrors);
1019 * Process the form submission.
1021 public function postProcess() {
1022 if ($this->_action
& CRM_Core_Action
::DELETE
) {
1023 CRM_Contribute_BAO_Contribution
::deleteContribution($this->_id
);
1024 CRM_Core_Session
::singleton()->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
1025 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1029 // Get the submitted form values.
1030 $submittedValues = $this->controller
->exportValues($this->_name
);
1033 $contribution = $this->submit($submittedValues, $this->_action
, $this->_ppID
);
1035 catch (PaymentProcessorException
$e) {
1036 // Set the contribution mode.
1037 $urlParams = "action=add&cid={$this->_contactID}";
1039 $urlParams .= "&mode={$this->_mode}";
1041 if (!empty($this->_ppID
)) {
1042 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
1045 CRM_Core_Error
::statusBounce($e->getMessage(), $urlParams, ts('Payment Processor Error'));
1047 $session = CRM_Core_Session
::singleton();
1048 $buttonName = $this->controller
->getButtonName();
1049 if ($this->_context
== 'standalone') {
1050 if ($buttonName == $this->getButtonName('upload', 'new')) {
1051 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contribute/add',
1052 'reset=1&action=add&context=standalone'
1056 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
1057 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1061 elseif ($this->_context
== 'contribution' && $this->_mode
&& $buttonName == $this->getButtonName('upload', 'new')) {
1062 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
1063 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
1066 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1067 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
1068 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
1072 //store contribution ID if not yet set (on create)
1073 if (empty($this->_id
) && !empty($contribution->id
)) {
1074 $this->_id
= $contribution->id
;
1076 if (!empty($this->_id
) && CRM_Core_Permission
::access('CiviMember')) {
1077 $membershipPaymentCount = civicrm_api3('MembershipPayment', 'getCount', array('contribution_id' => $this->_id
));
1078 if ($membershipPaymentCount) {
1079 $this->ajaxResponse
['updateTabs']['#tab_member'] = CRM_Contact_BAO_Contact
::getCountComponent('membership', $this->_contactID
);
1082 if (!empty($this->_id
) && CRM_Core_Permission
::access('CiviEvent')) {
1083 $participantPaymentCount = civicrm_api3('ParticipantPayment', 'getCount', array('contribution_id' => $this->_id
));
1084 if ($participantPaymentCount) {
1085 $this->ajaxResponse
['updateTabs']['#tab_participant'] = CRM_Contact_BAO_Contact
::getCountComponent('participant', $this->_contactID
);
1091 * Process credit card payment.
1093 * @param array $submittedValues
1094 * @param array $lineItem
1096 * @param int $contactID
1099 * @return bool|\CRM_Contribute_DAO_Contribution
1100 * @throws \CRM_Core_Exception
1101 * @throws \Civi\Payment\Exception\PaymentProcessorException
1103 protected function processCreditCard($submittedValues, $lineItem, $contactID) {
1104 $isTest = ($this->_mode
== 'test') ?
1 : 0;
1105 // CRM-12680 set $_lineItem if its not set
1106 // @todo - I don't believe this would ever BE set. I can't find anywhere in the code.
1107 // It would be better to pass line item out to functions than $this->_lineItem as
1108 // we don't know what is being changed where.
1109 if (empty($this->_lineItem
) && !empty($lineItem)) {
1110 $this->_lineItem
= $lineItem;
1113 $this->_paymentObject
= Civi\Payment\System
::singleton()->getById($submittedValues['payment_processor_id']);
1114 $this->_paymentProcessor
= $this->_paymentObject
->getPaymentProcessor();
1116 // Set source if not set
1117 if (empty($submittedValues['source'])) {
1118 $userID = CRM_Core_Session
::singleton()->get('userID');
1119 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1122 $submittedValues['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
1125 $params = $submittedValues;
1126 $this->_params
= array_merge($this->_params
, $submittedValues);
1128 // Mapping requiring documentation.
1129 $this->_params
['payment_processor'] = $submittedValues['payment_processor_id'];
1131 $now = date('YmdHis');
1133 // we need to retrieve email address
1134 if ($this->_context
== 'standalone' && !empty($submittedValues['is_email_receipt'])) {
1135 list($this->userDisplayName
,
1137 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contactID);
1138 $this->assign('displayName', $this->userDisplayName
);
1141 $this->_contributorEmail
= $this->userEmail
;
1142 $this->_contributorContactID
= $contactID;
1143 $this->processBillingAddress();
1144 if (!empty($params['source'])) {
1145 unset($params['source']);
1148 $this->_params
['amount'] = $this->_params
['total_amount'];
1149 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
1150 // function to get correct amount level consistently. Remove setting of the amount level in
1151 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
1152 // to cover all variants.
1153 $this->_params
['amount_level'] = 0;
1154 $this->_params
['description'] = ts("Contribution submitted by a staff person using contributor's credit card");
1155 $this->_params
['currencyID'] = CRM_Utils_Array
::value('currency',
1157 CRM_Core_Config
::singleton()->defaultCurrency
1160 if (!empty($this->_params
['receive_date'])) {
1161 $this->_params
['receive_date'] = CRM_Utils_Date
::processDate($this->_params
['receive_date'], $this->_params
['receive_date_time']);
1164 $this->_params
['receive_date'] = $now;
1167 $this->_params
['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $params);
1168 $this->_params
['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $params);
1169 $this->_params
['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $params);
1171 //Add common data to formatted params
1172 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
1174 if (empty($this->_params
['invoice_id'])) {
1175 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
1178 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
1181 // At this point we've created a contact and stored its address etc
1182 // all the payment processors expect the name and address to be in the
1183 // so we copy stuff over to first_name etc.
1184 $paymentParams = $this->_params
;
1185 $paymentParams['contactID'] = $contactID;
1186 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
1188 $financialType = new CRM_Financial_DAO_FinancialType();
1189 $financialType->id
= $params['financial_type_id'];
1190 $financialType->find(TRUE);
1192 // Add some financial type details to the params list
1193 // if folks need to use it.
1194 $paymentParams['contributionType_name'] = $this->_params
['contributionType_name'] = $financialType->name
;
1195 $paymentParams['contributionPageID'] = NULL;
1197 if (!empty($this->_params
['is_email_receipt'])) {
1198 $paymentParams['email'] = $this->userEmail
;
1199 $paymentParams['is_email_receipt'] = 1;
1202 $paymentParams['is_email_receipt'] = 0;
1203 $this->_params
['is_email_receipt'] = 0;
1205 if (!empty($this->_params
['receive_date'])) {
1206 $paymentParams['receive_date'] = $this->_params
['receive_date'];
1209 if (!empty($this->_params
['is_email_receipt'])) {
1210 $this->_params
['receipt_date'] = $now;
1213 $this->_params
['receipt_date'] = CRM_Utils_Date
::processDate($this->_params
['receipt_date'],
1214 $params['receipt_date_time'], TRUE
1218 $this->set('params', $this->_params
);
1220 $this->assign('receive_date', $this->_params
['receive_date']);
1222 // Result has all the stuff we need
1223 // lets archive it to a financial transaction
1224 if ($financialType->is_deductible
) {
1225 $this->assign('is_deductible', TRUE);
1226 $this->set('is_deductible', TRUE);
1228 $contributionParams = array(
1229 'id' => CRM_Utils_Array
::value('contribution_id', $this->_params
),
1230 'contact_id' => $contactID,
1231 'line_item' => $lineItem,
1232 'is_test' => $isTest,
1233 'campaign_id' => CRM_Utils_Array
::value('campaign_id', $this->_params
),
1234 'contribution_page_id' => CRM_Utils_Array
::value('contribution_page_id', $this->_params
),
1235 'source' => CRM_Utils_Array
::value('source', $paymentParams, CRM_Utils_Array
::value('description', $paymentParams)),
1236 'thankyou_date' => CRM_Utils_Array
::value('thankyou_date', $this->_params
),
1238 $contributionParams['payment_instrument_id'] = $this->_paymentProcessor
['payment_instrument_id'];
1240 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processFormContribution($this,
1243 $contributionParams,
1247 CRM_Utils_Array
::value('is_recur', $this->_params
)
1250 $paymentParams['contributionID'] = $contribution->id
;
1251 $paymentParams['contributionTypeID'] = $contribution->financial_type_id
;
1252 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
1253 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1255 if ($paymentParams['amount'] > 0.0) {
1256 // force a re-get of the payment processor in case the form changed it, CRM-7179
1257 // NOTE - I expect this is obsolete.
1258 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
1260 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id');
1261 $result = $payment->doPayment($paymentParams, 'contribute');
1262 $this->assign('trxn_id', $result['trxn_id']);
1263 $contribution->trxn_id
= $result['trxn_id'];
1264 /* Our scenarios here are
1265 * 1) the payment failed & an Exception should have been thrown
1266 * 2) the payment succeeded but the payment is not immediate (for example a recurring payment
1267 * with a delayed start)
1268 * 3) the payment succeeded with an immediate payment.
1270 * The doPayment function ensures that payment_status_id is always set
1271 * as historically we have had to guess from the context - ie doDirectPayment
1272 * = error or success, unless it is a recurring contribution in which case it is pending.
1274 if ($result['payment_status_id'] == array_search('Completed', $statuses)) {
1276 civicrm_api3('contribution', 'completetransaction', array(
1277 'id' => $contribution->id
,
1278 'trxn_id' => $result['trxn_id'],
1279 'payment_processor_id' => $this->_paymentProcessor
['id'],
1280 'is_transactional' => FALSE,
1281 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $result),
1282 'card_type_id' => CRM_Utils_Array
::value('card_type_id', $paymentParams),
1283 'pan_truncation' => CRM_Utils_Array
::value('pan_truncation', $paymentParams),
1284 'is_email_receipt' => FALSE,
1286 // This has now been set to 1 in the DB - declare it here also
1287 $contribution->contribution_status_id
= 1;
1289 catch (CiviCRM_API3_Exception
$e) {
1290 if ($e->getErrorCode() != 'contribution_completed') {
1291 throw new CRM_Core_Exception('Failed to update contribution in database');
1296 // Save the trxn_id.
1297 $contribution->save();
1300 catch (PaymentProcessorException
$e) {
1301 CRM_Contribute_BAO_Contribution
::failPayment($contribution->id
, $paymentParams['contactID'], $e->getMessage());
1302 throw new PaymentProcessorException($e->getMessage());
1305 // Send receipt mail.
1306 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1307 if ($contribution->id
&& !empty($this->_params
['is_email_receipt'])) {
1308 $this->_params
['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $result);
1309 $this->_params
['contact_id'] = $contactID;
1310 $this->_params
['contribution_id'] = $contribution->id
;
1311 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $this->_params
, TRUE)) {
1312 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1316 return $contribution;
1320 * Generate the data to construct a snippet based pane.
1322 * This form also assigns the showAdditionalInfo var based on historical code.
1323 * This appears to mean 'there is a pane to show'.
1325 * @param string $type
1326 * Type of Pane - this is generally used to determine the function name used to build it
1327 * - e.g CreditCard, AdditionalDetail
1328 * @param array $defaults
1331 * We aim to further refactor & simplify this but currently
1333 * - should additional info be shown?
1335 protected function generatePane($type, $defaults) {
1336 $urlParams = "snippet=4&formType={$type}";
1338 $urlParams .= "&mode={$this->_mode}";
1342 if ($type == 'CreditCard' ||
1343 $type == 'DirectDebit'
1349 'url' => CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams),
1354 // See if we need to include this paneName in the current form.
1355 if ($this->_formType
== $type ||
!empty($_POST["hidden_{$type}"]) ||
1356 CRM_Utils_Array
::value("hidden_{$type}", $defaults)
1358 $this->assign('showAdditionalInfo', TRUE);
1359 $pane['open'] = 'true';
1362 if ($type == 'CreditCard' ||
$type == 'DirectDebit') {
1363 // @todo would be good to align tpl name with form name...
1364 // @todo document why this hidden variable is required.
1365 $this->add('hidden', 'hidden_' . $type, 1);
1369 $additionalInfoFormFunction = 'build' . $type;
1370 CRM_Contribute_Form_AdditionalInfo
::$additionalInfoFormFunction($this);
1376 * Wrapper for unit testing the post process submit function.
1378 * (If we expose through api we can get default additions 'for free').
1380 * @param array $params
1381 * @param int $action
1382 * @param string|null $creditCardMode
1384 * @throws \CiviCRM_API3_Exception
1386 public function testSubmit($params, $action, $creditCardMode = NULL) {
1388 'soft_credit_contact_id' => array(),
1389 'receipt_date' => '',
1390 'receipt_date_time' => '',
1391 'cancel_date' => '',
1392 'cancel_date_time' => '',
1393 'hidden_Premium' => 1,
1396 if (!empty($params['id'])) {
1397 $existingContribution = civicrm_api3('contribution', 'getsingle', array(
1398 'id' => $params['id'],
1400 $this->_id
= $params['id'];
1401 $this->_values
= $existingContribution;
1404 $existingContribution = array();
1407 $this->_defaults
['contribution_status_id'] = CRM_Utils_Array
::value('contribution_status_id',
1408 $existingContribution
1411 $this->_defaults
['total_amount'] = CRM_Utils_Array
::value('total_amount',
1412 $existingContribution
1415 if ($creditCardMode) {
1416 $this->_mode
= $creditCardMode;
1419 // Required because processCreditCard calls set method on this.
1420 $_SERVER['REQUEST_METHOD'] = 'GET';
1421 $this->controller
= new CRM_Core_Controller();
1423 CRM_Contribute_Form_AdditionalInfo
::buildPremium($this);
1425 $this->_fields
= array();
1426 return $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array
::value('pledge_payment_id', $params));
1431 * @param array $submittedValues
1433 * @param int $action
1435 * - CRM_Core_Action::UPDATE
1437 * @param $pledgePaymentID
1440 * @throws \Exception
1442 protected function submit($submittedValues, $action, $pledgePaymentID) {
1443 $pId = $contribution = $isRelatedId = FALSE;
1444 $this->_params
= $submittedValues;
1445 $this->beginPostProcess();
1446 // reassign submitted form values if the any information is formatted via beginPostProcess
1447 $submittedValues = $this->_params
;
1449 if (!empty($submittedValues['price_set_id']) && $action & CRM_Core_Action
::UPDATE
) {
1450 $line = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution');
1451 $lineID = key($line);
1452 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array
::value('price_field_id', $line[$lineID]), 'price_set_id');
1453 $quickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1454 // Why do we do this? Seems like a like a wrapper for old functionality - but single line price sets & quick
1455 // config should be treated the same.
1457 CRM_Price_BAO_LineItem
::deleteLineItems($this->_id
, 'civicrm_contribution');
1461 // Process price set and get total amount and line items.
1462 $lineItem = array();
1463 $priceSetId = CRM_Utils_Array
::value('price_set_id', $submittedValues);
1464 if (empty($priceSetId) && !$this->_id
) {
1465 $this->_priceSetId
= $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1466 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
1467 $fieldID = key($this->_priceSet
['fields']);
1468 $fieldValueId = key($this->_priceSet
['fields'][$fieldID]['options']);
1469 $this->_priceSet
['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1470 $submittedValues['price_' . $fieldID] = 1;
1473 // Every contribution has a price-set - the only reason it shouldn't be set is if we are dealing with
1474 // quick config (very very arguably) & yet we see that this could still be quick config so this should be understood
1475 // as a point of fragility rather than a logical 'if' clause.
1477 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
1478 $submittedValues, $lineItem[$priceSetId]);
1479 // Unset tax amount for offline 'is_quick_config' contribution.
1480 // @todo WHY - quick config was conceived as a quick way to configure contribution forms.
1481 // this is an example of 'other' functionality being hung off it.
1482 if ($this->_priceSet
['is_quick_config'] &&
1483 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant
::getTaxRates())
1485 unset($submittedValues['tax_amount']);
1487 // @todo - look to remove this line. I believe it relates to CRM-16460
1488 // and possibly contributes to fixing the issue described there but
1489 // would cause breakage for negative values in some cases.
1490 $submittedValues['total_amount'] = CRM_Utils_Array
::value('amount', $submittedValues);
1493 if ($this->_compId
) {
1494 if ($this->_context
== 'participant') {
1495 $pId = $this->_compId
;
1497 elseif ($this->_context
== 'membership') {
1498 $isRelatedId = TRUE;
1501 $pId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id
, 'participant_id', 'contribution_id');
1505 $contributionDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1506 if (array_key_exists('membership', $contributionDetails)) {
1507 $isRelatedId = TRUE;
1509 elseif (array_key_exists('participant', $contributionDetails)) {
1510 $pId = $contributionDetails['participant'];
1513 if (!empty($this->_payNow
)) {
1514 $this->_params
['contribution_id'] = $this->_id
;
1518 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id
) {
1519 // CRM-10117 update the line items for participants.
1520 // @todo - if we are completing a contribution then the api call
1521 // civicrm_api3('Contribution', 'completetransaction') should take care of
1522 // all associated updates rather than replicating them on the form layer.
1524 $entityTable = 'participant';
1526 $isRelatedId = FALSE;
1527 $participantParams = array(
1528 'fee_amount' => $submittedValues['total_amount'],
1531 CRM_Event_BAO_Participant
::add($participantParams);
1532 if (empty($this->_lineItems
)) {
1533 $this->_lineItems
[] = CRM_Price_BAO_LineItem
::getLineItems($entityID, 'participant', TRUE);
1537 $entityTable = 'contribution';
1538 $entityID = $this->_id
;
1541 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, $entityTable, FALSE, TRUE, $isRelatedId);
1542 foreach (array_keys($lineItems) as $id) {
1543 $lineItems[$id]['id'] = $id;
1545 $itemId = key($lineItems);
1546 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1547 $this->_priceSetId
= CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1550 // @todo see above - new functionality has been inappropriately added to the quick config concept
1551 // and new functionality has been added onto the form layer rather than the BAO :-(
1552 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1553 //CRM-16833: Ensure tax is applied only once for membership conribution, when status changed.(e.g Pending to Completed).
1554 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1555 if (!(CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails))) {
1556 if (!($this->_action
& CRM_Core_Action
::UPDATE
&& (($this->_defaults
['contribution_status_id'] != $submittedValues['contribution_status_id'])))) {
1557 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule
::cleanMoney(CRM_Utils_Array
::value('total_amount', $submittedValues));
1561 // Update line total and total amount with tax on edit.
1562 $financialItemsId = CRM_Core_PseudoConstant
::getTaxRates();
1563 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1564 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1567 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1568 $submittedValues['tax_amount'] = 'null';
1570 if ($lineItems[$itemId]['tax_rate']) {
1571 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total'];
1572 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] +
$lineItems[$itemId]['tax_amount'];
1573 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1576 // CRM-10117 update the line items for participants.
1577 if (!empty($lineItems[$itemId]['price_field_id'])) {
1578 $lineItem[$this->_priceSetId
] = $lineItems;
1583 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1586 //CRM-11529 for quick config back office transactions
1587 //when financial_type_id is passed in form, update the
1588 //line items with the financial type selected in form
1589 // NOTE that this IS still a legitimate use of 'quick-config' for contributions under the current DB but
1590 // we should look at having a price field per contribution type & then there would be little reason
1591 // for the back-office contribution form postProcess to know if it is a quick-config form.
1592 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array
::value($this->_priceSetId
, $lineItem)
1594 foreach ($lineItem[$this->_priceSetId
] as &$values) {
1595 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1599 if (!isset($submittedValues['total_amount'])) {
1600 $submittedValues['total_amount'] = CRM_Utils_Array
::value('total_amount', $this->_values
) - CRM_Utils_Array
::value('tax_amount', $this->_values
);
1602 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
1604 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
1605 if ($this->_id
&& count($isEmpty) == 1 && key($isEmpty) == NULL) {
1606 civicrm_api3('ContributionSoft', 'get', array('contribution_id' => $this->_id
, 'pcp_id' => NULL, 'api.ContributionSoft.delete' => 1));
1609 // set the contact, when contact is selected
1610 if (!empty($submittedValues['contact_id'])) {
1611 $this->_contactID
= $submittedValues['contact_id'];
1614 $formValues = $submittedValues;
1616 // Credit Card Contribution.
1618 $paramsSetByPaymentProcessingSubsystem = array(
1620 'payment_instrument_id',
1621 'contribution_status_id',
1625 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1626 if (isset($formValues[$key])) {
1627 unset($formValues[$key]);
1630 $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID
);
1631 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1632 $formValues[$key] = $contribution->$key;
1636 // Offline Contribution.
1637 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1639 // get the required field value only.
1641 $params = $ids = array();
1643 $params['contact_id'] = $this->_contactID
;
1644 $params['currency'] = $this->getCurrency($submittedValues);
1646 //format soft-credit/pcp param first
1647 CRM_Contribute_BAO_ContributionSoft
::formatSoftCreditParams($submittedValues, $this);
1648 $params = array_merge($params, $submittedValues);
1651 'financial_type_id',
1652 'contribution_status_id',
1653 'payment_instrument_id',
1660 foreach ($fields as $f) {
1661 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1664 // CRM-5740 if priceset is used, no need to cleanup money.
1666 $params['skipCleanMoney'] = 1;
1668 $params['revenue_recognition_date'] = NULL;
1669 if (!empty($formValues['revenue_recognition_date'])
1670 && count(array_filter($formValues['revenue_recognition_date'])) == 2
1672 $params['revenue_recognition_date'] = CRM_Utils_Date
::processDate(
1673 '01-' . implode('-', $formValues['revenue_recognition_date'])
1682 foreach ($dates as $d) {
1683 if (isset($formValues[$d])) {
1684 $params[$d] = CRM_Utils_Date
::processDate($formValues[$d], CRM_Utils_Array
::value($d . '_time', $formValues), TRUE);
1688 if (!empty($formValues['is_email_receipt'])) {
1689 $params['receipt_date'] = date("Y-m-d");
1692 if (CRM_Contribute_BAO_Contribution
::isContributionStatusNegative($params['contribution_status_id'])
1694 if (CRM_Utils_System
::isNull(CRM_Utils_Array
::value('cancel_date', $params))) {
1695 $params['cancel_date'] = date('YmdHis');
1699 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1702 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1703 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1704 if ($params['contribution_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending')) {
1705 $params['is_pay_later'] = 1;
1707 elseif ($params['contribution_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed')) {
1708 $params['is_pay_later'] = 0;
1711 $ids['contribution'] = $params['id'] = $this->_id
;
1713 // Add Additional common information to formatted params.
1714 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($formValues, $params, $this);
1716 $params['contribution_mode'] = 'participant';
1717 $params['participant_id'] = $pId;
1718 $params['skipLineItem'] = 1;
1720 elseif ($isRelatedId) {
1721 $params['contribution_mode'] = 'membership';
1723 $params['line_item'] = $lineItem;
1724 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array
::value('id', $this->_paymentProcessor
);
1725 if (isset($submittedValues['tax_amount'])) {
1726 $params['tax_amount'] = $submittedValues['tax_amount'];
1728 //create contribution.
1729 if ($isQuickConfig) {
1730 $params['is_quick_config'] = 1;
1732 $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
1734 // we are already handling note below, so to avoid duplicate notes against $contribution
1735 if (!empty($params['note']) && !empty($submittedValues['note'])) {
1736 unset($params['note']);
1738 $contribution = CRM_Contribute_BAO_Contribution
::create($params, $ids);
1740 // process associated membership / participant, CRM-4395
1741 if ($contribution->id
&& $action & CRM_Core_Action
::UPDATE
) {
1742 $this->statusMessage
[] = CRM_Contribute_BAO_Contribution
::transitionComponentWithReturnMessage($contribution->id
,
1743 $contribution->contribution_status_id
,
1744 CRM_Utils_Array
::value('contribution_status_id',
1747 $contribution->receive_date
1751 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1753 $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
1755 //send receipt mail.
1756 if ($contribution->id
&& !empty($formValues['is_email_receipt'])) {
1757 $formValues['contact_id'] = $this->_contactID
;
1758 $formValues['contribution_id'] = $contribution->id
;
1760 $formValues +
= CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
);
1762 // to get 'from email id' for send receipt
1763 $this->fromEmailId
= $formValues['from_email_address'];
1764 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $formValues)) {
1765 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1769 $this->statusMessageTitle
= ts('Saved');
1773 if ($contribution->id
&& isset($formValues['product_name'][0])) {
1774 CRM_Contribute_Form_AdditionalInfo
::processPremium($submittedValues, $contribution->id
,
1775 $this->_premiumID
, $this->_options
1779 if ($contribution->id
&& !empty($submittedValues['note'])) {
1780 CRM_Contribute_Form_AdditionalInfo
::processNote($submittedValues, $this->_contactID
, $contribution->id
, $this->_noteID
);
1783 CRM_Core_Session
::setStatus(implode(' ', $this->statusMessage
), $this->statusMessageTitle
, 'success');
1785 CRM_Contribute_BAO_Contribution
::updateRelatedPledge(
1789 (CRM_Utils_Array
::value('option_type', $formValues) == 2) ?
TRUE : FALSE,
1790 $formValues['total_amount'],
1791 CRM_Utils_Array
::value('total_amount', $this->_defaults
),
1792 $formValues['contribution_status_id'],
1793 CRM_Utils_Array
::value('contribution_status_id', $this->_defaults
)
1795 return $contribution;
1799 * Assign tax calculations to contribution receipts.
1801 * @param array $submittedValues
1802 * @param int $action
1803 * @param array $lineItem
1805 protected function invoicingPostProcessHook($submittedValues, $action, $lineItem) {
1807 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
1808 if (!CRM_Utils_Array
::value('invoicing', $invoiceSettings)) {
1812 $getTaxDetails = FALSE;
1814 foreach ($lineItem as $key => $value) {
1815 foreach ($value as $v) {
1816 if (isset($taxRate[(string) CRM_Utils_Array
::value('tax_rate', $v)])) {
1817 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $v);
1820 if (isset($v['tax_rate'])) {
1821 $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $v);
1822 $getTaxDetails = TRUE;
1828 if ($action & CRM_Core_Action
::UPDATE
) {
1829 if (isset($submittedValues['tax_amount'])) {
1830 $totalTaxAmount = $submittedValues['tax_amount'];
1833 $totalTaxAmount = $this->_values
['tax_amount'];
1835 $this->assign('totalTaxAmount', $totalTaxAmount);
1836 $this->assign('dataArray', $taxRate);
1839 if (!empty($submittedValues['price_set_id'])) {
1840 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1841 $this->assign('getTaxDetails', $getTaxDetails);
1842 $this->assign('dataArray', $taxRate);
1843 $this->assign('taxTerm', CRM_Utils_Array
::value('tax_term', $invoiceSettings));
1846 $this->assign('totalTaxAmount', CRM_Utils_Array
::value('tax_amount', $submittedValues));
1852 * Calculate non deductible amount.
1855 * if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1856 * if non_deductible_amount does NOT exist - then calculate it depending on:
1857 * $financialType->is_deductible and whether there is a product (premium).
1860 * @param $formValues
1864 protected function calculateNonDeductibleAmount($params, $formValues) {
1865 if (!empty($params['non_deductible_amount'])) {
1866 return $params['non_deductible_amount'];
1869 $priceSetId = CRM_Utils_Array
::value('price_set_id', $params);
1870 // return non-deductible amount if it is set at the price field option level
1871 if ($priceSetId && !empty($params['line_item'])) {
1872 $nonDeductibleAmount = CRM_Price_BAO_PriceSet
::getNonDeductibleAmountFromPriceSet($priceSetId, $params['line_item']);
1873 if (!empty($nonDeductibleAmount)) {
1874 return $nonDeductibleAmount;
1878 $financialType = new CRM_Financial_DAO_FinancialType();
1879 $financialType->id
= $params['financial_type_id'];
1880 $financialType->find(TRUE);
1882 if ($financialType->is_deductible
) {
1884 if (isset($formValues['product_name'][0])) {
1885 $selectProduct = $formValues['product_name'][0];
1887 // if there is a product - compare the value to the contribution amount
1888 if (isset($selectProduct)) {
1889 $productDAO = new CRM_Contribute_DAO_Product();
1890 $productDAO->id
= $selectProduct;
1891 $productDAO->find(TRUE);
1892 // product value exceeds contribution amount
1893 if ($params['total_amount'] < $productDAO->price
) {
1894 return $params['total_amount'];
1896 // product value does NOT exceed contribution amount
1898 return $productDAO->price
;
1901 // contribution is deductible - but there is no product
1906 // contribution is NOT deductible
1908 return $params['total_amount'];