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;
157 public $_honoreeProfileType;
160 * Array of the payment fields to be displayed in the payment fieldset (pane) in billingBlock.tpl
161 * this contains all the information to describe these fields from quickform. See CRM_Core_Form_Payment getPaymentFormFieldsMetadata
165 public $_paymentFields = array();
167 * Logged in user's email.
179 * Price set as an array
189 public $userDisplayName;
192 * Status message to be shown to the user.
196 protected $statusMessage = array();
199 * Status message title to be shown to the user.
201 * Generally the payment processor message title is 'Complete' and offline is 'Saved'
202 * although this might not be a good fit with the broad range of processors.
206 protected $statusMessageTitle;
209 * Set variables up before form is built.
211 public function preProcess() {
212 // Check permission for action.
213 if (!CRM_Core_Permission
::checkActionPermission('CiviContribute', $this->_action
)) {
214 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
217 parent
::preProcess();
219 $this->_formType
= CRM_Utils_Array
::value('formType', $_GET);
222 $this->_priceSetId
= CRM_Utils_Array
::value('priceSetId', $_GET);
223 $this->set('priceSetId', $this->_priceSetId
);
224 $this->assign('priceSetId', $this->_priceSetId
);
226 // Get the pledge payment id
227 $this->_ppID
= CRM_Utils_Request
::retrieve('ppid', 'Positive', $this);
229 $this->assign('action', $this->_action
);
231 // Get the contribution id if update
232 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this);
233 if (!empty($this->_id
)) {
234 $this->assign('contribID', $this->_id
);
237 $this->_context
= CRM_Utils_Request
::retrieve('context', 'String', $this);
238 $this->assign('context', $this->_context
);
240 $this->_compId
= CRM_Utils_Request
::retrieve('compId', 'Positive', $this);
242 $this->_compContext
= CRM_Utils_Request
::retrieve('compContext', 'String', $this);
244 //set the contribution mode.
245 $this->_mode
= CRM_Utils_Request
::retrieve('mode', 'String', $this);
247 $this->assign('contributionMode', $this->_mode
);
248 if ($this->_action
& CRM_Core_Action
::DELETE
) {
252 $this->assign('showCheckNumber', TRUE);
254 $this->_fromEmails
= CRM_Core_BAO_Email
::getFromEmail();
255 $this->assignPaymentRelatedVariables();
257 if (in_array('CiviPledge', CRM_Core_Config
::singleton()->enableComponents
) && !$this->_formType
) {
258 $this->preProcessPledge();
262 $this->showRecordLinkMesssage($this->_id
);
264 $this->_values
= array();
266 // Current contribution id.
268 $this->assignPremiumProduct($this->_id
);
269 $this->buildValuesAndAssignOnline_Note_Type($this->_id
, $this->_values
);
272 // when custom data is included in this page
273 if (!empty($_POST['hidden_custom'])) {
274 $this->applyCustomData('Contribution', CRM_Utils_Array
::value('financial_type_id', $_POST), $this->_id
);
277 $this->_lineItems
= array();
279 if (!empty($this->_compId
) && $this->_compContext
== 'participant') {
280 $this->assign('compId', $this->_compId
);
281 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_compId
);
284 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution', 1, TRUE, TRUE);
287 empty($lineItem) ?
NULL : $this->_lineItems
[] = $lineItem;
290 $this->assign('lineItem', empty($lineItem) ?
FALSE : array($lineItem));
293 if ($this->_mode
&& $this->_id
) {
294 $this->_payNow
= TRUE;
295 $this->assign('payNow', $this->_payNow
);
296 CRM_Utils_System
::setTitle(ts('Pay with Credit Card'));
298 elseif ($this->_mode
) {
299 $this->setPageTitle($this->_ppID ?
ts('Credit Card Pledge Payment') : ts('Credit Card Contribution'));
302 $this->setPageTitle($this->_ppID ?
ts('Pledge Payment') : ts('Contribution'));
306 CRM_Contribute_Form_SoftCredit
::preprocess($this);
311 * Set default values.
315 public function setDefaultValues() {
317 $defaults = $this->_values
;
319 // Set defaults for pledge payment.
321 $defaults['total_amount'] = CRM_Utils_Array
::value('scheduled_amount', $this->_pledgeValues
['pledgePayment']);
322 $defaults['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $this->_pledgeValues
);
323 $defaults['currency'] = CRM_Utils_Array
::value('currency', $this->_pledgeValues
);
324 $defaults['option_type'] = 1;
327 if ($this->_action
& CRM_Core_Action
::DELETE
) {
331 $defaults['frequency_interval'] = 1;
332 $defaults['frequency_unit'] = 'month';
334 // Set soft credit defaults.
335 CRM_Contribute_Form_SoftCredit
::setDefaultValues($defaults, $this);
338 // @todo - remove this function as the parent does it too.
339 $config = CRM_Core_Config
::singleton();
340 // Set default country from config if no country set.
341 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
342 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry
;
345 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
346 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince
;
349 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID
);
350 $defaults = array_merge($defaults, $billingDefaults);
354 $this->_contactID
= $defaults['contact_id'];
357 // Set $newCredit variable in template to control whether link to credit card mode is included.
358 $this->assign('newCredit', CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments());
360 // Fix the display of the monetary value, CRM-4038.
361 if (isset($defaults['total_amount'])) {
362 if (!empty($defaults['tax_amount'])) {
363 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
364 if (!(CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails))) {
365 $defaults['total_amount'] = CRM_Utils_Money
::format($defaults['total_amount'] - $defaults['tax_amount'], NULL, '%a');
369 $defaults['total_amount'] = CRM_Utils_Money
::format($defaults['total_amount'], NULL, '%a');
373 if (isset($defaults['non_deductible_amount'])) {
374 $defaults['non_deductible_amount'] = CRM_Utils_Money
::format($defaults['non_deductible_amount'], NULL, '%a');
377 if (isset($defaults['fee_amount'])) {
378 $defaults['fee_amount'] = CRM_Utils_Money
::format($defaults['fee_amount'], NULL, '%a');
381 if ($this->_contributionType
) {
382 $defaults['financial_type_id'] = $this->_contributionType
;
385 if (empty($defaults['payment_instrument_id'])) {
386 $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup
::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
389 if (!empty($defaults['is_test'])) {
390 $this->assign('is_test', TRUE);
393 $this->assign('showOption', TRUE);
394 // For Premium section.
395 if ($this->_premiumID
) {
396 $this->assign('showOption', FALSE);
397 $options = isset($this->_options
[$this->_productDAO
->product_id
]) ?
$this->_options
[$this->_productDAO
->product_id
] : "";
399 $this->assign('showOption', TRUE);
401 $options_key = CRM_Utils_Array
::key($this->_productDAO
->product_option
, $options);
403 $defaults['product_name'] = array($this->_productDAO
->product_id
, trim($options_key));
406 $defaults['product_name'] = array($this->_productDAO
->product_id
);
408 if ($this->_productDAO
->fulfilled_date
) {
409 list($defaults['fulfilled_date']) = CRM_Utils_Date
::setDateDefaults($this->_productDAO
->fulfilled_date
);
413 if (isset($this->userEmail
)) {
414 $this->assign('email', $this->userEmail
);
417 if (!empty($defaults['is_pay_later'])) {
418 $this->assign('is_pay_later', TRUE);
420 $this->assign('contribution_status_id', CRM_Utils_Array
::value('contribution_status_id', $defaults));
421 if (!empty($defaults['contribution_status_id']) && in_array(
422 CRM_Contribute_PseudoConstant
::contributionStatus($defaults['contribution_status_id'], 'name'),
423 // Historically not 'Cancelled' hence not using CRM_Contribute_BAO_Contribution::isContributionStatusNegative.
424 array('Refunded', 'Chargeback')
426 $defaults['refund_trxn_id'] = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionTrxnID($this->_id
);
429 $defaults['refund_trxn_id'] = isset($defaults['trxn_id']) ?
$defaults['trxn_id'] : NULL;
437 foreach ($dates as $key) {
438 if (!empty($defaults[$key])) {
439 list($defaults[$key], $defaults[$key . '_time'])
440 = CRM_Utils_Date
::setDateDefaults(CRM_Utils_Array
::value($key, $defaults), 'activityDateTime');
444 if (!$this->_id
&& empty($defaults['receive_date'])) {
445 list($defaults['receive_date'],
446 $defaults['receive_date_time']
447 ) = CRM_Utils_Date
::setDateDefaults(NULL, 'activityDateTime');
450 $this->assign('receive_date', CRM_Utils_Date
::processDate(CRM_Utils_Array
::value('receive_date', $defaults),
451 CRM_Utils_Array
::value('receive_date_time', $defaults)
453 $currency = CRM_Utils_Array
::value('currency', $defaults);
454 $this->assign('currency', $currency);
455 // Hack to get currency info to the js layer. CRM-11440.
456 CRM_Utils_Money
::format(1);
457 $this->assign('currencySymbol', CRM_Utils_Array
::value($currency, CRM_Utils_Money
::$_currencySymbols));
458 $this->assign('totalAmount', CRM_Utils_Array
::value('total_amount', $defaults));
460 // Inherit campaign from pledge.
461 if ($this->_ppID
&& !empty($this->_pledgeValues
['campaign_id'])) {
462 $defaults['campaign_id'] = $this->_pledgeValues
['campaign_id'];
465 $this->_defaults
= $defaults;
470 * Build the form object.
472 public function buildQuickForm() {
473 // FIXME: This probably needs to be done in preprocess
474 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()
475 && $this->_action
& CRM_Core_Action
::UPDATE
476 && CRM_Utils_Array
::value('financial_type_id', $this->_values
)
478 $financialTypeID = CRM_Contribute_PseudoConstant
::financialType($this->_values
['financial_type_id']);
479 CRM_Financial_BAO_FinancialType
::checkPermissionedLineItems($this->_id
, 'edit');
480 if (!CRM_Core_Permission
::check('edit contributions of type ' . $financialTypeID)) {
481 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
486 //tax rate from financialType
487 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant
::getTaxRates()));
488 $this->assign('currencies', json_encode(CRM_Core_OptionGroup
::values('currencies_enabled')));
490 // build price set form.
491 $buildPriceSet = FALSE;
492 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
493 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
494 $this->assign('invoicing', $invoicing);
496 // display tax amount on edit contribution page
497 if ($invoicing && $this->_action
& CRM_Core_Action
::UPDATE
&& isset($this->_values
['tax_amount'])) {
498 $this->assign('totalTaxAmount', $this->_values
['tax_amount']);
501 if (empty($this->_lineItems
) &&
502 ($this->_priceSetId ||
!empty($_POST['price_set_id']))
504 $buildPriceSet = TRUE;
505 $getOnlyPriceSetElements = TRUE;
506 if (!$this->_priceSetId
) {
507 $this->_priceSetId
= $_POST['price_set_id'];
508 $getOnlyPriceSetElements = FALSE;
511 $this->set('priceSetId', $this->_priceSetId
);
512 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
514 // get only price set form elements.
515 if ($getOnlyPriceSetElements) {
519 // use to build form during form rule.
520 $this->assign('buildPriceSet', $buildPriceSet);
522 $defaults = $this->_values
;
523 $additionalDetailFields = array(
527 'non_deductible_amount',
531 foreach ($additionalDetailFields as $key) {
532 if (!empty($defaults[$key])) {
533 $defaults['hidden_AdditionalDetail'] = 1;
538 if ($this->_productDAO
) {
539 if ($this->_productDAO
->product_id
) {
540 $defaults['hidden_Premium'] = 1;
544 if ($this->_noteID
&&
545 isset($this->_values
['note'])
547 $defaults['hidden_AdditionalDetail'] = 1;
550 $paneNames = array();
551 if (empty($this->_payNow
)) {
552 $paneNames[ts('Additional Details')] = 'AdditionalDetail';
555 //Add Premium pane only if Premium is exists.
556 $dao = new CRM_Contribute_DAO_Product();
559 if ($dao->find(TRUE) && empty($this->_payNow
)) {
560 $paneNames[ts('Premium Information')] = 'Premium';
564 if (CRM_Core_Payment_Form
::buildPaymentForm($this, $this->_paymentProcessor
, FALSE, TRUE) == TRUE) {
565 if (!empty($this->_recurPaymentProcessors
)) {
566 $buildRecurBlock = TRUE;
568 // ppID denotes a pledge payment.
569 foreach ($this->_paymentProcessors
as $processor) {
570 if (!empty($processor['is_recur']) && !empty($processor['object']) && $processor['object']->supports('recurContributionsForPledges')) {
571 $buildRecurBlock = TRUE;
574 $buildRecurBlock = FALSE;
577 if ($buildRecurBlock) {
578 CRM_Contribute_Form_Contribution_Main
::buildRecur($this);
579 $this->setDefaults(array('is_recur' => 0));
580 $this->assign('buildRecurBlock', TRUE);
581 $recurJs = array('onChange' => "buildRecurBlock( this.value ); return false;");
587 foreach ($paneNames as $name => $type) {
588 $allPanes[$name] = $this->generatePane($type, $defaults);
591 $qfKey = $this->controller
->_key
;
592 $this->assign('qfKey', $qfKey);
593 $this->assign('allPanes', $allPanes);
595 $this->addFormRule(array('CRM_Contribute_Form_Contribution', 'formRule'), $this);
597 if ($this->_formType
) {
598 $this->assign('formType', $this->_formType
);
602 $this->applyFilter('__ALL__', 'trim');
604 if ($this->_action
& CRM_Core_Action
::DELETE
) {
605 $this->addButtons(array(
608 'name' => ts('Delete'),
609 'spacing' => ' ',
614 'name' => ts('Cancel'),
621 //need to assign custom data type and subtype to the template
622 $this->assign('customDataType', 'Contribution');
623 $this->assign('customDataSubType', $this->_contributionType
);
624 $this->assign('entityID', $this->_id
);
626 if ($this->_context
== 'standalone') {
627 $this->addEntityRef('contact_id', ts('Contact'), array(
629 'api' => array('extra' => array('email')),
633 $attributes = CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Contribution');
635 // Check permissions for financial type first
636 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes, $this->_action
);
637 if (empty($financialTypes)) {
638 CRM_Core_Error
::statusBounce(ts('You do not have all the permissions needed for this page.'));
640 $financialType = $this->add('select', 'financial_type_id',
641 ts('Financial Type'),
642 array('' => ts('- select -')) +
$financialTypes,
644 array('onChange' => "CRM.buildCustomData( 'Contribution', this.value );")
647 $paymentInstrument = FALSE;
649 $checkPaymentID = array_search('Check', CRM_Contribute_PseudoConstant
::paymentInstrument('name'));
650 $paymentInstrument = $this->add('select', 'payment_instrument_id',
651 ts('Payment Method'),
652 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::paymentInstrument(),
653 TRUE, array('onChange' => "return showHideByValue('payment_instrument_id','{$checkPaymentID}','checkNumber','table-row','select',false);")
657 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), array('class' => 'twelve') +
$attributes['trxn_id']);
659 //add receipt for offline contribution
660 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
662 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
664 $status = CRM_Contribute_PseudoConstant
::contributionStatus();
666 // suppressing contribution statuses that are NOT relevant to pledges (CRM-5169)
667 $statusName = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
674 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
677 elseif ((!$this->_ppID
&& $this->_id
) ||
!$this->_id
) {
678 $suppressFlag = FALSE;
680 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
681 if (CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails)) {
682 $suppressFlag = TRUE;
685 if (!$suppressFlag) {
690 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
694 unset($status[CRM_Utils_Array
::key('Overdue', $statusName)]);
698 // define the status IDs that show the cancellation info, see CRM-17589
699 $cancelInfo_show_ids = array();
700 foreach (array_keys($statusName) as $status_id) {
701 if (CRM_Contribute_BAO_Contribution
::isContributionStatusNegative($status_id)) {
702 $cancelInfo_show_ids[] = "'$status_id'";
705 $this->assign('cancelInfo_show_ids', implode(',', $cancelInfo_show_ids));
708 $contributionStatus = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_id
, 'contribution_status_id');
709 $name = CRM_Utils_Array
::value($contributionStatus, $statusName);
712 // [CRM-17498] Removing unsupported status change options.
713 unset($status[CRM_Utils_Array
::key('Pending', $statusName)]);
714 unset($status[CRM_Utils_Array
::key('Failed', $statusName)]);
715 unset($status[CRM_Utils_Array
::key('Partially paid', $statusName)]);
716 unset($status[CRM_Utils_Array
::key('Pending refund', $statusName)]);
720 unset($status[CRM_Utils_Array
::key('In Progress', $statusName)]);
721 unset($status[CRM_Utils_Array
::key('Pending', $statusName)]);
722 unset($status[CRM_Utils_Array
::key('Failed', $statusName)]);
727 unset($status[CRM_Utils_Array
::key('Refunded', $statusName)]);
728 unset($status[CRM_Utils_Array
::key('Chargeback', $statusName)]);
740 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
746 unset($status[CRM_Utils_Array
::key('Refunded', $statusName)]);
747 unset($status[CRM_Utils_Array
::key('Chargeback', $statusName)]);
750 $statusElement = $this->add('select', 'contribution_status_id',
751 ts('Contribution Status'),
756 $currencyFreeze = FALSE;
757 if (!empty($this->_payNow
) && ($this->_action
& CRM_Core_Action
::UPDATE
)) {
758 $statusElement->freeze();
759 $currencyFreeze = TRUE;
760 $attributes['total_amount']['readonly'] = TRUE;
763 // CRM-16189, add Revenue Recognition Date
764 if (CRM_Contribute_BAO_Contribution
::checkContributeSettings('deferred_revenue_enabled')) {
765 $revenueDate = $this->add('date', 'revenue_recognition_date', ts('Revenue Recognition Date'), CRM_Core_SelectValues
::date(NULL, 'M Y', NULL, 5));
766 if ($this->_id
&& !CRM_Contribute_BAO_Contribution
::allowUpdateRevenueRecognitionDate($this->_id
)) {
767 $revenueDate->freeze();
772 $this->addDateTime('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
774 if ($this->_online
) {
775 $this->assign('hideCalender', TRUE);
777 $checkNumber = $this->add('text', 'check_number', ts('Check Number'), $attributes['contribution_check_number']);
779 $this->addDateTime('receipt_date', ts('Receipt Date'), FALSE, array('formatType' => 'activityDateTime'));
780 $this->addDateTime('cancel_date', ts('Cancelled / Refunded Date'), FALSE, array('formatType' => 'activityDateTime'));
782 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
783 $this->add('text', 'refund_trxn_id', ts('Transaction ID for the refund payment'));
784 $element = $this->add('select',
785 'payment_processor_id',
786 ts('Payment Processor'),
792 if ($this->_online
) {
797 if (empty($this->_lineItems
)) {
798 $buildPriceSet = FALSE;
799 $priceSets = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute');
800 if (!empty($priceSets) && !$this->_ppID
) {
801 $buildPriceSet = TRUE;
804 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
805 // and if we already have line items for that participant. CRM-5095
806 if ($buildPriceSet && $this->_id
) {
807 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
808 $pledgePaymentId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
813 if ($pledgePaymentId) {
814 $buildPriceSet = FALSE;
816 if ($participantID = CRM_Utils_Array
::value('participant', $componentDetails)) {
817 $participantLI = CRM_Price_BAO_LineItem
::getLineItems($participantID);
818 if (!CRM_Utils_System
::isNull($participantLI)) {
819 $buildPriceSet = FALSE;
824 $hasPriceSets = FALSE;
825 if ($buildPriceSet) {
826 $hasPriceSets = TRUE;
827 // CRM-16451: set financial type of 'Price Set' in back office contribution
828 // instead of selecting manually
829 $financialTypeIds = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute', 'financial_type_id');
830 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
832 '' => ts('Choose price set'),
834 NULL, array('onchange' => "buildAmount( this.value, " . json_encode($financialTypeIds) . ");")
836 if ($this->_online
&& !($this->_action
& CRM_Core_Action
::UPDATE
)) {
840 $this->assign('hasPriceSets', $hasPriceSets);
841 if (!($this->_action
& CRM_Core_Action
::UPDATE
)) {
842 if ($this->_online ||
$this->_ppID
) {
843 $attributes['total_amount'] = array_merge($attributes['total_amount'], array(
845 'style' => "background-color:#EBECE4",
847 $optionTypes = array(
848 '1' => ts('Adjust Pledge Payment Schedule?'),
849 '2' => ts('Adjust Total Pledge Amount?'),
851 $this->addRadio('option_type',
857 $currencyFreeze = TRUE;
861 $totalAmount = $this->addMoney('total_amount',
863 ($hasPriceSets) ?
FALSE : TRUE,
864 $attributes['total_amount'],
865 TRUE, 'currency', NULL, $currencyFreeze
869 $this->add('text', 'source', ts('Source'), CRM_Utils_Array
::value('source', $attributes));
871 // CRM-7362 --add campaigns.
872 CRM_Campaign_BAO_Campaign
::addCampaign($this, CRM_Utils_Array
::value('campaign_id', $this->_values
));
874 if (empty($this->_payNow
)) {
875 CRM_Contribute_Form_SoftCredit
::buildQuickForm($this);
880 $js = array('onclick' => "return verify( );");
883 $mailingInfo = Civi
::settings()->get('mailing_backend');
884 $this->assign('outBound_option', $mailingInfo['outBound_option']);
886 $this->addButtons(array(
889 'name' => ts('Save'),
895 'name' => ts('Save and New'),
901 'name' => ts('Cancel'),
906 // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
907 // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
908 if ($this->_id
&& $this->_values
['contribution_status_id'] == array_search('Cancelled', $statusName)) {
910 $totalAmount->freeze();
912 $checkNumber->freeze();
913 $paymentInstrument->freeze();
915 $financialType->freeze();
918 // if contribution is related to membership or participant freeze Financial Type, Amount
919 if ($this->_id
&& isset($this->_values
['tax_amount'])) {
920 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
921 if (CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails)) {
923 $totalAmount->freeze();
925 $financialType->freeze();
926 $this->assign('freezeFinancialType', TRUE);
930 if ($this->_action
& CRM_Core_Action
::VIEW
) {
938 * @param array $fields
939 * The input form values.
940 * @param array $files
941 * The uploaded files if any.
945 * true if no errors, else array of errors
947 public static function formRule($fields, $files, $self) {
949 // Check for Credit Card Contribution.
951 if (empty($fields['payment_processor_id'])) {
952 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
955 // validate payment instrument (e.g. credit card number)
956 CRM_Core_Payment_Form
::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, NULL);
960 // Do the amount validations.
961 if (empty($fields['total_amount']) && empty($self->_lineItems
)) {
962 if ($priceSetId = CRM_Utils_Array
::value('price_set_id', $fields)) {
963 CRM_Price_BAO_PriceField
::priceSetValidation($priceSetId, $fields, $errors);
967 $softErrors = CRM_Contribute_Form_SoftCredit
::formRule($fields, $errors, $self);
969 if (!empty($fields['total_amount']) && (!empty($fields['net_amount']) ||
!empty($fields['fee_amount']))) {
970 $sum = CRM_Utils_Rule
::cleanMoney($fields['net_amount']) + CRM_Utils_Rule
::cleanMoney($fields['fee_amount']);
971 if (CRM_Utils_Rule
::cleanMoney($fields['total_amount']) != $sum) {
972 $errors['total_amount'] = ts('The sum of fee amount and net amount must be equal to total amount');
976 //CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
977 CRM_Contribute_BAO_ContributionRecur
::validateRecurContribution($fields, $files, $self, $errors);
979 // Form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
980 if (($self->_action
& CRM_Core_Action
::UPDATE
)
982 && $self->_values
['contribution_status_id'] != $fields['contribution_status_id']
984 CRM_Contribute_BAO_Contribution
::checkStatusValidation($self->_values
, $fields, $errors);
986 // CRM-16015, add form-rule to restrict change of financial type if using price field of different financial type
987 if (($self->_action
& CRM_Core_Action
::UPDATE
)
989 && $self->_values
['financial_type_id'] != $fields['financial_type_id']
991 CRM_Contribute_BAO_Contribution
::checkFinancialTypeChange(NULL, $self->_id
, $errors);
993 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
994 if (!empty($fields['fee_amount']) && !empty($fields['financial_type_id']) && $financialType = CRM_Contribute_BAO_Contribution
::validateFinancialType($fields['financial_type_id'])) {
995 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
998 // $trxn_id must be unique CRM-13919
999 if (!empty($fields['trxn_id'])) {
1000 $queryParams = array(1 => array($fields['trxn_id'], 'String'));
1001 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
1003 $queryParams[2] = array((int) $self->_id
, 'Integer');
1004 $query .= ' and id !=%2';
1006 $tCnt = CRM_Core_DAO
::singleValueQuery($query, $queryParams);
1008 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', array(1 => $fields['trxn_id']));
1011 if (!empty($fields['revenue_recognition_date'])
1012 && count(array_filter($fields['revenue_recognition_date'])) == 1
1014 $errors['revenue_recognition_date'] = ts('Month and Year are required field for Revenue Recognition.');
1018 CRM_Financial_BAO_FinancialAccount
::checkFinancialTypeHasDeferred($fields, $self->_id
, $self->_priceSet
['fields']);
1020 catch (CRM_Core_Exception
$e) {
1021 $errors['financial_type_id'] = ' ';
1022 $errors['_qf_default'] = $e->getMessage();
1024 $errors = array_merge($errors, $softErrors);
1029 * Process the form submission.
1031 public function postProcess() {
1032 if ($this->_action
& CRM_Core_Action
::DELETE
) {
1033 CRM_Contribute_BAO_Contribution
::deleteContribution($this->_id
);
1034 CRM_Core_Session
::singleton()->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
1035 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1039 // Get the submitted form values.
1040 $submittedValues = $this->controller
->exportValues($this->_name
);
1043 $contribution = $this->submit($submittedValues, $this->_action
, $this->_ppID
);
1045 catch (PaymentProcessorException
$e) {
1046 // Set the contribution mode.
1047 $urlParams = "action=add&cid={$this->_contactID}";
1049 $urlParams .= "&mode={$this->_mode}";
1051 if (!empty($this->_ppID
)) {
1052 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
1055 CRM_Core_Error
::statusBounce($e->getMessage(), $urlParams, ts('Payment Processor Error'));
1057 $session = CRM_Core_Session
::singleton();
1058 $buttonName = $this->controller
->getButtonName();
1059 if ($this->_context
== 'standalone') {
1060 if ($buttonName == $this->getButtonName('upload', 'new')) {
1061 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contribute/add',
1062 'reset=1&action=add&context=standalone'
1066 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
1067 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1071 elseif ($this->_context
== 'contribution' && $this->_mode
&& $buttonName == $this->getButtonName('upload', 'new')) {
1072 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
1073 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
1076 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1077 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
1078 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
1082 //store contribution ID if not yet set (on create)
1083 if (empty($this->_id
) && !empty($contribution->id
)) {
1084 $this->_id
= $contribution->id
;
1089 * Process credit card payment.
1091 * @param array $submittedValues
1092 * @param array $lineItem
1094 * @param int $contactID
1097 * @return bool|\CRM_Contribute_DAO_Contribution
1098 * @throws \CRM_Core_Exception
1099 * @throws \Civi\Payment\Exception\PaymentProcessorException
1101 protected function processCreditCard($submittedValues, $lineItem, $contactID) {
1102 $isTest = ($this->_mode
== 'test') ?
1 : 0;
1103 // CRM-12680 set $_lineItem if its not set
1104 // @todo - I don't believe this would ever BE set. I can't find anywhere in the code.
1105 // It would be better to pass line item out to functions than $this->_lineItem as
1106 // we don't know what is being changed where.
1107 if (empty($this->_lineItem
) && !empty($lineItem)) {
1108 $this->_lineItem
= $lineItem;
1111 $this->_paymentObject
= Civi\Payment\System
::singleton()->getById($submittedValues['payment_processor_id']);
1112 $this->_paymentProcessor
= $this->_paymentObject
->getPaymentProcessor();
1114 // Set source if not set
1115 if (empty($submittedValues['source'])) {
1116 $userID = CRM_Core_Session
::singleton()->get('userID');
1117 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1120 $submittedValues['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
1123 $params = $submittedValues;
1124 $this->_params
= array_merge($this->_params
, $submittedValues);
1126 // Mapping requiring documentation.
1127 $this->_params
['payment_processor'] = $submittedValues['payment_processor_id'];
1129 $now = date('YmdHis');
1131 // we need to retrieve email address
1132 if ($this->_context
== 'standalone' && !empty($submittedValues['is_email_receipt'])) {
1133 list($this->userDisplayName
,
1135 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contactID);
1136 $this->assign('displayName', $this->userDisplayName
);
1139 $this->_contributorEmail
= $this->userEmail
;
1140 $this->_contributorContactID
= $contactID;
1141 $this->processBillingAddress();
1142 if (!empty($params['source'])) {
1143 unset($params['source']);
1146 $this->_params
['amount'] = $this->_params
['total_amount'];
1147 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
1148 // function to get correct amount level consistently. Remove setting of the amount level in
1149 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
1150 // to cover all variants.
1151 $this->_params
['amount_level'] = 0;
1152 $this->_params
['description'] = ts("Contribution submitted by a staff person using contributor's credit card");
1153 $this->_params
['currencyID'] = CRM_Utils_Array
::value('currency',
1155 CRM_Core_Config
::singleton()->defaultCurrency
1158 if (!empty($this->_params
['receive_date'])) {
1159 $this->_params
['receive_date'] = CRM_Utils_Date
::processDate($this->_params
['receive_date'], $this->_params
['receive_date_time']);
1162 $this->_params
['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $params);
1163 $this->_params
['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $params);
1164 $this->_params
['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $params);
1166 //Add common data to formatted params
1167 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
1169 if (empty($this->_params
['invoice_id'])) {
1170 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
1173 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
1176 // At this point we've created a contact and stored its address etc
1177 // all the payment processors expect the name and address to be in the
1178 // so we copy stuff over to first_name etc.
1179 $paymentParams = $this->_params
;
1180 $paymentParams['contactID'] = $contactID;
1181 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
1183 $financialType = new CRM_Financial_DAO_FinancialType();
1184 $financialType->id
= $params['financial_type_id'];
1185 $financialType->find(TRUE);
1187 // Add some financial type details to the params list
1188 // if folks need to use it.
1189 $paymentParams['contributionType_name'] = $this->_params
['contributionType_name'] = $financialType->name
;
1190 $paymentParams['contributionPageID'] = NULL;
1192 if (!empty($this->_params
['is_email_receipt'])) {
1193 $paymentParams['email'] = $this->userEmail
;
1194 $paymentParams['is_email_receipt'] = 1;
1197 $paymentParams['is_email_receipt'] = 0;
1198 $this->_params
['is_email_receipt'] = 0;
1200 if (!empty($this->_params
['receive_date'])) {
1201 $paymentParams['receive_date'] = $this->_params
['receive_date'];
1204 $this->_params
['receive_date'] = $now;
1206 if (!empty($this->_params
['is_email_receipt'])) {
1207 $this->_params
['receipt_date'] = $now;
1210 $this->_params
['receipt_date'] = CRM_Utils_Date
::processDate($this->_params
['receipt_date'],
1211 $params['receipt_date_time'], TRUE
1215 $this->set('params', $this->_params
);
1217 $this->assign('receive_date', $this->_params
['receive_date']);
1219 // Result has all the stuff we need
1220 // lets archive it to a financial transaction
1221 if ($financialType->is_deductible
) {
1222 $this->assign('is_deductible', TRUE);
1223 $this->set('is_deductible', TRUE);
1225 $contributionParams = array(
1226 'id' => CRM_Utils_Array
::value('contribution_id', $this->_params
),
1227 'contact_id' => $contactID,
1228 'line_item' => $lineItem,
1229 'is_test' => $isTest,
1230 'campaign_id' => CRM_Utils_Array
::value('campaign_id', $this->_params
),
1231 'contribution_page_id' => CRM_Utils_Array
::value('contribution_page_id', $this->_params
),
1232 'source' => CRM_Utils_Array
::value('source', $paymentParams, CRM_Utils_Array
::value('description', $paymentParams)),
1233 'thankyou_date' => CRM_Utils_Array
::value('thankyou_date', $this->_params
),
1235 $contributionParams['payment_instrument_id'] = $this->_paymentProcessor
['payment_instrument_id'];
1237 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processFormContribution($this,
1240 $contributionParams,
1244 CRM_Utils_Array
::value('is_recur', $this->_params
)
1247 $paymentParams['contributionID'] = $contribution->id
;
1248 $paymentParams['contributionTypeID'] = $contribution->financial_type_id
;
1249 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
1250 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1252 if ($paymentParams['amount'] > 0.0) {
1253 // force a re-get of the payment processor in case the form changed it, CRM-7179
1254 // NOTE - I expect this is obsolete.
1255 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
1257 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id');
1258 $result = $payment->doPayment($paymentParams, 'contribute');
1259 $this->assign('trxn_id', $result['trxn_id']);
1260 $contribution->trxn_id
= $result['trxn_id'];
1261 /* Our scenarios here are
1262 * 1) the payment failed & an Exception should have been thrown
1263 * 2) the payment succeeded but the payment is not immediate (for example a recurring payment
1264 * with a delayed start)
1265 * 3) the payment succeeded with an immediate payment.
1267 * The doPayment function ensures that payment_status_id is always set
1268 * as historically we have had to guess from the context - ie doDirectPayment
1269 * = error or success, unless it is a recurring contribution in which case it is pending.
1271 if ($result['payment_status_id'] == array_search('Completed', $statuses)) {
1273 civicrm_api3('contribution', 'completetransaction', array(
1274 'id' => $contribution->id
,
1275 'trxn_id' => $result['trxn_id'],
1276 'payment_processor_id' => $this->_paymentProcessor
['id'],
1277 'is_transactional' => FALSE,
1278 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $result),
1280 // This has now been set to 1 in the DB - declare it here also
1281 $contribution->contribution_status_id
= 1;
1283 catch (CiviCRM_API3_Exception
$e) {
1284 if ($e->getErrorCode() != 'contribution_completed') {
1285 throw new CRM_Core_Exception('Failed to update contribution in database');
1290 // Save the trxn_id.
1291 $contribution->save();
1294 catch (PaymentProcessorException
$e) {
1295 CRM_Contribute_BAO_Contribution
::failPayment($contribution->id
, $paymentParams['contactID'], $e->getMessage());
1296 throw new PaymentProcessorException($e->getMessage());
1299 // Send receipt mail.
1300 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1301 if ($contribution->id
&& !empty($this->_params
['is_email_receipt'])) {
1302 $this->_params
['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $result);
1303 $this->_params
['contact_id'] = $contactID;
1304 $this->_params
['contribution_id'] = $contribution->id
;
1305 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $this->_params
, TRUE)) {
1306 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1310 return $contribution;
1314 * Generate the data to construct a snippet based pane.
1316 * This form also assigns the showAdditionalInfo var based on historical code.
1317 * This appears to mean 'there is a pane to show'.
1319 * @param string $type
1320 * Type of Pane - this is generally used to determine the function name used to build it
1321 * - e.g CreditCard, AdditionalDetail
1322 * @param array $defaults
1325 * We aim to further refactor & simplify this but currently
1327 * - should additional info be shown?
1329 protected function generatePane($type, $defaults) {
1330 $urlParams = "snippet=4&formType={$type}";
1332 $urlParams .= "&mode={$this->_mode}";
1336 if ($type == 'CreditCard' ||
1337 $type == 'DirectDebit'
1343 'url' => CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams),
1348 // See if we need to include this paneName in the current form.
1349 if ($this->_formType
== $type ||
!empty($_POST["hidden_{$type}"]) ||
1350 CRM_Utils_Array
::value("hidden_{$type}", $defaults)
1352 $this->assign('showAdditionalInfo', TRUE);
1353 $pane['open'] = 'true';
1356 if ($type == 'CreditCard' ||
$type == 'DirectDebit') {
1357 // @todo would be good to align tpl name with form name...
1358 // @todo document why this hidden variable is required.
1359 $this->add('hidden', 'hidden_' . $type, 1);
1363 $additionalInfoFormFunction = 'build' . $type;
1364 CRM_Contribute_Form_AdditionalInfo
::$additionalInfoFormFunction($this);
1370 * Wrapper for unit testing the post process submit function.
1372 * (If we expose through api we can get default additions 'for free').
1374 * @param array $params
1375 * @param int $action
1376 * @param string|null $creditCardMode
1378 * @throws \CiviCRM_API3_Exception
1380 public function testSubmit($params, $action, $creditCardMode = NULL) {
1382 'soft_credit_contact_id' => array(),
1383 'receipt_date' => '',
1384 'receipt_date_time' => '',
1385 'cancel_date' => '',
1386 'cancel_date_time' => '',
1387 'hidden_Premium' => 1,
1390 if (!empty($params['id'])) {
1391 $existingContribution = civicrm_api3('contribution', 'getsingle', array(
1392 'id' => $params['id'],
1394 $this->_id
= $params['id'];
1395 $this->_values
= $existingContribution;
1398 $existingContribution = array();
1401 $this->_defaults
['contribution_status_id'] = CRM_Utils_Array
::value('contribution_status_id',
1402 $existingContribution
1405 $this->_defaults
['total_amount'] = CRM_Utils_Array
::value('total_amount',
1406 $existingContribution
1409 if ($creditCardMode) {
1410 $this->_mode
= $creditCardMode;
1413 // Required because processCreditCard calls set method on this.
1414 $_SERVER['REQUEST_METHOD'] = 'GET';
1415 $this->controller
= new CRM_Core_Controller();
1417 CRM_Contribute_Form_AdditionalInfo
::buildPremium($this);
1419 $this->_fields
= array();
1420 $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array
::value('pledge_payment_id', $params));
1425 * @param array $submittedValues
1427 * @param int $action
1429 * - CRM_Core_Action::UPDATE
1431 * @param $pledgePaymentID
1434 * @throws \Exception
1436 protected function submit($submittedValues, $action, $pledgePaymentID) {
1438 $pId = $contribution = $isRelatedId = FALSE;
1439 $this->_params
= $submittedValues;
1440 $this->beginPostProcess();
1442 if (!empty($submittedValues['price_set_id']) && $action & CRM_Core_Action
::UPDATE
) {
1443 $line = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution');
1444 $lineID = key($line);
1445 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array
::value('price_field_id', $line[$lineID]), 'price_set_id');
1446 $quickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1447 // Why do we do this? Seems like a like a wrapper for old functionality - but single line price sets & quick
1448 // config should be treated the same.
1450 CRM_Price_BAO_LineItem
::deleteLineItems($this->_id
, 'civicrm_contribution');
1454 // Process price set and get total amount and line items.
1455 $lineItem = array();
1456 $priceSetId = CRM_Utils_Array
::value('price_set_id', $submittedValues);
1457 if (empty($priceSetId) && !$this->_id
) {
1458 $this->_priceSetId
= $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1459 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
1460 $fieldID = key($this->_priceSet
['fields']);
1461 $fieldValueId = key($this->_priceSet
['fields'][$fieldID]['options']);
1462 $this->_priceSet
['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1463 $submittedValues['price_' . $fieldID] = 1;
1466 // Every contribution has a price-set - the only reason it shouldn't be set is if we are dealing with
1467 // quick config (very very arguably) & yet we see that this could still be quick config so this should be understood
1468 // as a point of fragility rather than a logical 'if' clause.
1470 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
1471 $submittedValues, $lineItem[$priceSetId]);
1472 // Unset tax amount for offline 'is_quick_config' contribution.
1473 // @todo WHY - quick config was conceived as a quick way to configure contribution forms.
1474 // this is an example of 'other' functionality being hung off it.
1475 if ($this->_priceSet
['is_quick_config'] &&
1476 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant
::getTaxRates())
1478 unset($submittedValues['tax_amount']);
1480 $submittedValues['total_amount'] = CRM_Utils_Array
::value('amount', $submittedValues);
1483 if ($this->_compId
) {
1484 if ($this->_context
== 'participant') {
1485 $pId = $this->_compId
;
1487 elseif ($this->_context
== 'membership') {
1488 $isRelatedId = TRUE;
1491 $pId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id
, 'participant_id', 'contribution_id');
1495 $contributionDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1496 if (array_key_exists('membership', $contributionDetails)) {
1497 $isRelatedId = TRUE;
1499 elseif (array_key_exists('participant', $contributionDetails)) {
1500 $pId = $contributionDetails['participant'];
1503 if (!empty($this->_payNow
)) {
1504 $this->_params
['contribution_id'] = $this->_id
;
1508 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id
) {
1509 // CRM-10117 update the line items for participants.
1510 // @todo - if we are completing a contribution then the api call
1511 // civicrm_api3('Contribution', 'completetransaction') should take care of
1512 // all associated updates rather than replicating them on the form layer.
1514 $entityTable = 'participant';
1516 $isRelatedId = FALSE;
1517 $participantParams = array(
1518 'fee_amount' => $submittedValues['total_amount'],
1521 CRM_Event_BAO_Participant
::add($participantParams);
1522 if (empty($this->_lineItems
)) {
1523 $this->_lineItems
[] = CRM_Price_BAO_LineItem
::getLineItems($entityID, 'participant', TRUE);
1527 $entityTable = 'contribution';
1528 $entityID = $this->_id
;
1531 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, $entityTable, FALSE, TRUE, $isRelatedId);
1532 foreach (array_keys($lineItems) as $id) {
1533 $lineItems[$id]['id'] = $id;
1535 $itemId = key($lineItems);
1536 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1537 $this->_priceSetId
= CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1540 // @todo see above - new functionality has been inappropriately added to the quick config concept
1541 // and new functionality has been added onto the form layer rather than the BAO :-(
1542 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1543 //CRM-16833: Ensure tax is applied only once for membership conribution, when status changed.(e.g Pending to Completed).
1544 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1545 if (!(CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails))) {
1546 if (!($this->_action
& CRM_Core_Action
::UPDATE
&& (($this->_defaults
['contribution_status_id'] != $submittedValues['contribution_status_id'])))) {
1547 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule
::cleanMoney(CRM_Utils_Array
::value('total_amount', $submittedValues));
1551 // Update line total and total amount with tax on edit.
1552 $financialItemsId = CRM_Core_PseudoConstant
::getTaxRates();
1553 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1554 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1557 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1558 $submittedValues['tax_amount'] = 'null';
1560 if ($lineItems[$itemId]['tax_rate']) {
1561 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total'];
1562 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] +
$lineItems[$itemId]['tax_amount'];
1563 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1566 // CRM-10117 update the line items for participants.
1567 if (!empty($lineItems[$itemId]['price_field_id'])) {
1568 $lineItem[$this->_priceSetId
] = $lineItems;
1573 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1576 //CRM-11529 for quick config back office transactions
1577 //when financial_type_id is passed in form, update the
1578 //line items with the financial type selected in form
1579 // NOTE that this IS still a legitimate use of 'quick-config' for contributions under the current DB but
1580 // we should look at having a price field per contribution type & then there would be little reason
1581 // for the back-office contribution form postProcess to know if it is a quick-config form.
1582 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array
::value($this->_priceSetId
, $lineItem)
1584 foreach ($lineItem[$this->_priceSetId
] as &$values) {
1585 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1589 if (!isset($submittedValues['total_amount'])) {
1590 $submittedValues['total_amount'] = CRM_Utils_Array
::value('total_amount', $this->_values
) - CRM_Utils_Array
::value('tax_amount', $this->_values
);
1592 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
1594 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
1595 if ($this->_id
&& count($isEmpty) == 1 && key($isEmpty) == NULL) {
1596 //Delete existing soft credit records if soft credit list is empty on update
1597 CRM_Contribute_BAO_ContributionSoft
::del(array('contribution_id' => $this->_id
, 'pcp_id' => 0));
1600 // set the contact, when contact is selected
1601 if (!empty($submittedValues['contact_id'])) {
1602 $this->_contactID
= $submittedValues['contact_id'];
1605 $formValues = $submittedValues;
1607 // Credit Card Contribution.
1609 $paramsSetByPaymentProcessingSubsystem = array(
1611 'payment_instrument_id',
1612 'contribution_status_id',
1616 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1617 if (isset($formValues[$key])) {
1618 unset($formValues[$key]);
1621 $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID
);
1622 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1623 $formValues[$key] = $contribution->$key;
1627 // Offline Contribution.
1628 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1630 // get the required field value only.
1632 $params = $ids = array();
1634 $params['contact_id'] = $this->_contactID
;
1635 $params['currency'] = $this->getCurrency($submittedValues);
1637 //format soft-credit/pcp param first
1638 CRM_Contribute_BAO_ContributionSoft
::formatSoftCreditParams($submittedValues, $this);
1639 $params = array_merge($params, $submittedValues);
1642 'financial_type_id',
1643 'contribution_status_id',
1644 'payment_instrument_id',
1649 foreach ($fields as $f) {
1650 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1653 // CRM-5740 if priceset is used, no need to cleanup money.
1655 $params['skipCleanMoney'] = 1;
1657 $params['revenue_recognition_date'] = NULL;
1658 if (!empty($formValues['revenue_recognition_date'])
1659 && count(array_filter($formValues['revenue_recognition_date'])) == 2
1661 $params['revenue_recognition_date'] = CRM_Utils_Date
::processDate(
1662 '01-' . implode('-', $formValues['revenue_recognition_date'])
1671 foreach ($dates as $d) {
1672 if (isset($formValues[$d])) {
1673 $params[$d] = CRM_Utils_Date
::processDate($formValues[$d], CRM_Utils_Array
::value($d . '_time', $formValues), TRUE);
1677 if (!empty($formValues['is_email_receipt'])) {
1678 $params['receipt_date'] = date("Y-m-d");
1681 if (CRM_Contribute_BAO_Contribution
::isContributionStatusNegative($params['contribution_status_id'])
1683 if (CRM_Utils_System
::isNull(CRM_Utils_Array
::value('cancel_date', $params))) {
1684 $params['cancel_date'] = date('YmdHis');
1688 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1691 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1692 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1693 if ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Pending', 'name')) {
1694 $params['is_pay_later'] = 1;
1696 elseif ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name')) {
1697 $params['is_pay_later'] = 0;
1700 $ids['contribution'] = $params['id'] = $this->_id
;
1702 // Add Additional common information to formatted params.
1703 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($formValues, $params, $this);
1705 $params['contribution_mode'] = 'participant';
1706 $params['participant_id'] = $pId;
1707 $params['skipLineItem'] = 1;
1709 elseif ($isRelatedId) {
1710 $params['contribution_mode'] = 'membership';
1712 $params['line_item'] = $lineItem;
1713 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array
::value('id', $this->_paymentProcessor
);
1714 if (isset($submittedValues['tax_amount'])) {
1715 $params['tax_amount'] = $submittedValues['tax_amount'];
1717 //create contribution.
1718 if ($isQuickConfig) {
1719 $params['is_quick_config'] = 1;
1721 $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
1723 // we are already handling note below, so to avoid duplicate notes against $contribution
1724 if (!empty($params['note']) && !empty($submittedValues['note'])) {
1725 unset($params['note']);
1727 $contribution = CRM_Contribute_BAO_Contribution
::create($params, $ids);
1729 // process associated membership / participant, CRM-4395
1730 if ($contribution->id
&& $action & CRM_Core_Action
::UPDATE
) {
1731 $this->statusMessage
[] = CRM_Contribute_BAO_Contribution
::transitionComponentWithReturnMessage($contribution->id
,
1732 $contribution->contribution_status_id
,
1733 CRM_Utils_Array
::value('contribution_status_id',
1736 $contribution->receive_date
1740 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1742 $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
1744 //send receipt mail.
1745 if ($contribution->id
&& !empty($formValues['is_email_receipt'])) {
1746 $formValues['contact_id'] = $this->_contactID
;
1747 $formValues['contribution_id'] = $contribution->id
;
1749 $formValues +
= CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
);
1751 // to get 'from email id' for send receipt
1752 $this->fromEmailId
= $formValues['from_email_address'];
1753 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $formValues)) {
1754 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1758 $this->statusMessageTitle
= ts('Saved');
1762 if ($contribution->id
&& isset($formValues['product_name'][0])) {
1763 CRM_Contribute_Form_AdditionalInfo
::processPremium($submittedValues, $contribution->id
,
1764 $this->_premiumID
, $this->_options
1768 if ($contribution->id
&& !empty($submittedValues['note'])) {
1769 CRM_Contribute_Form_AdditionalInfo
::processNote($submittedValues, $this->_contactID
, $contribution->id
, $this->_noteID
);
1772 CRM_Core_Session
::setStatus(implode(' ', $this->statusMessage
), $this->statusMessageTitle
, 'success');
1774 CRM_Contribute_BAO_Contribution
::updateRelatedPledge(
1778 (CRM_Utils_Array
::value('option_type', $formValues) == 2) ?
TRUE : FALSE,
1779 $formValues['total_amount'],
1780 CRM_Utils_Array
::value('total_amount', $this->_defaults
),
1781 $formValues['contribution_status_id'],
1782 CRM_Utils_Array
::value('contribution_status_id', $this->_defaults
)
1784 return $contribution;
1788 * Assign tax calculations to contribution receipts.
1790 * @param array $submittedValues
1791 * @param int $action
1792 * @param array $lineItem
1794 protected function invoicingPostProcessHook($submittedValues, $action, $lineItem) {
1796 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
1797 if (!CRM_Utils_Array
::value('invoicing', $invoiceSettings)) {
1801 $getTaxDetails = FALSE;
1803 foreach ($lineItem as $key => $value) {
1804 foreach ($value as $v) {
1805 if (isset($taxRate[(string) CRM_Utils_Array
::value('tax_rate', $v)])) {
1806 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $v);
1809 if (isset($v['tax_rate'])) {
1810 $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $v);
1811 $getTaxDetails = TRUE;
1817 if ($action & CRM_Core_Action
::UPDATE
) {
1818 if (isset($submittedValues['tax_amount'])) {
1819 $totalTaxAmount = $submittedValues['tax_amount'];
1822 $totalTaxAmount = $this->_values
['tax_amount'];
1824 $this->assign('totalTaxAmount', $totalTaxAmount);
1825 $this->assign('dataArray', $taxRate);
1828 if (!empty($submittedValues['price_set_id'])) {
1829 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1830 $this->assign('getTaxDetails', $getTaxDetails);
1831 $this->assign('dataArray', $taxRate);
1832 $this->assign('taxTerm', CRM_Utils_Array
::value('tax_term', $invoiceSettings));
1835 $this->assign('totalTaxAmount', CRM_Utils_Array
::value('tax_amount', $submittedValues));
1841 * Calculate non deductible amount.
1844 * if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1845 * if non_deductible_amount does NOT exist - then calculate it depending on:
1846 * $financialType->is_deductible and whether there is a product (premium).
1849 * @param $formValues
1853 protected function calculateNonDeductibleAmount($params, $formValues) {
1854 if (!empty($params['non_deductible_amount'])) {
1855 return $params['non_deductible_amount'];
1858 $priceSetId = CRM_Utils_Array
::value('price_set_id', $params);
1859 // return non-deductible amount if it is set at the price field option level
1860 if ($priceSetId && !empty($params['line_item'])) {
1861 $nonDeductibleAmount = CRM_Price_BAO_PriceSet
::getNonDeductibleAmountFromPriceSet($priceSetId, $params['line_item']);
1862 if (!empty($nonDeductibleAmount)) {
1863 return $nonDeductibleAmount;
1867 $financialType = new CRM_Financial_DAO_FinancialType();
1868 $financialType->id
= $params['financial_type_id'];
1869 $financialType->find(TRUE);
1871 if ($financialType->is_deductible
) {
1873 if (isset($formValues['product_name'][0])) {
1874 $selectProduct = $formValues['product_name'][0];
1876 // if there is a product - compare the value to the contribution amount
1877 if (isset($selectProduct)) {
1878 $productDAO = new CRM_Contribute_DAO_Product();
1879 $productDAO->id
= $selectProduct;
1880 $productDAO->find(TRUE);
1881 // product value exceeds contribution amount
1882 if ($params['total_amount'] < $productDAO->price
) {
1883 return $params['total_amount'];
1885 // product value does NOT exceed contribution amount
1887 return $productDAO->price
;
1890 // contribution is deductible - but there is no product
1895 // contribution is NOT deductible
1897 return $params['total_amount'];