3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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);
286 empty($lineItem) ?
NULL : $this->_lineItems
[] = $lineItem;
289 $this->assign('lineItem', empty($this->_lineItems
) ?
FALSE : $this->_lineItems
);
293 $this->setPageTitle($this->_ppID ?
ts('Credit Card Pledge Payment') : ts('Credit Card Contribution'));
296 $this->setPageTitle($this->_ppID ?
ts('Pledge Payment') : ts('Contribution'));
300 CRM_Contribute_Form_SoftCredit
::preprocess($this);
305 * Set default values.
309 public function setDefaultValues() {
311 $defaults = $this->_values
;
313 // Set defaults for pledge payment.
315 $defaults['total_amount'] = CRM_Utils_Array
::value('scheduled_amount', $this->_pledgeValues
['pledgePayment']);
316 $defaults['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $this->_pledgeValues
);
317 $defaults['currency'] = CRM_Utils_Array
::value('currency', $this->_pledgeValues
);
318 $defaults['option_type'] = 1;
321 if ($this->_action
& CRM_Core_Action
::DELETE
) {
325 $defaults['frequency_interval'] = 1;
326 $defaults['frequency_unit'] = 'month';
328 // Set soft credit defaults.
329 CRM_Contribute_Form_SoftCredit
::setDefaultValues($defaults, $this);
332 // @todo - remove this function as the parent does it too.
333 $config = CRM_Core_Config
::singleton();
334 // Set default country from config if no country set.
335 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
336 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry
;
339 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
340 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince
;
343 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID
);
344 $defaults = array_merge($defaults, $billingDefaults);
348 $this->_contactID
= $defaults['contact_id'];
351 // Set $newCredit variable in template to control whether link to credit card mode is included.
352 $this->assign('newCredit', CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments());
354 // Fix the display of the monetary value, CRM-4038.
355 if (isset($defaults['total_amount'])) {
356 if (!empty($defaults['tax_amount'])) {
357 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
358 if (!(CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails))) {
359 $defaults['total_amount'] = CRM_Utils_Money
::format($defaults['total_amount'] - $defaults['tax_amount'], NULL, '%a');
363 $defaults['total_amount'] = CRM_Utils_Money
::format($defaults['total_amount'], NULL, '%a');
367 if (isset($defaults['non_deductible_amount'])) {
368 $defaults['non_deductible_amount'] = CRM_Utils_Money
::format($defaults['non_deductible_amount'], NULL, '%a');
371 if (isset($defaults['fee_amount'])) {
372 $defaults['fee_amount'] = CRM_Utils_Money
::format($defaults['fee_amount'], NULL, '%a');
375 if (isset($defaults['net_amount'])) {
376 $defaults['net_amount'] = CRM_Utils_Money
::format($defaults['net_amount'], NULL, '%a');
379 if ($this->_contributionType
) {
380 $defaults['financial_type_id'] = $this->_contributionType
;
383 if (empty($defaults['payment_instrument_id'])) {
384 $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup
::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
387 if (!empty($defaults['is_test'])) {
388 $this->assign('is_test', TRUE);
391 $this->assign('showOption', TRUE);
392 // For Premium section.
393 if ($this->_premiumID
) {
394 $this->assign('showOption', FALSE);
395 $options = isset($this->_options
[$this->_productDAO
->product_id
]) ?
$this->_options
[$this->_productDAO
->product_id
] : "";
397 $this->assign('showOption', TRUE);
399 $options_key = CRM_Utils_Array
::key($this->_productDAO
->product_option
, $options);
401 $defaults['product_name'] = array($this->_productDAO
->product_id
, trim($options_key));
404 $defaults['product_name'] = array($this->_productDAO
->product_id
);
406 if ($this->_productDAO
->fulfilled_date
) {
407 list($defaults['fulfilled_date']) = CRM_Utils_Date
::setDateDefaults($this->_productDAO
->fulfilled_date
);
411 if (isset($this->userEmail
)) {
412 $this->assign('email', $this->userEmail
);
415 if (!empty($defaults['is_pay_later'])) {
416 $this->assign('is_pay_later', TRUE);
418 $this->assign('contribution_status_id', CRM_Utils_Array
::value('contribution_status_id', $defaults));
419 if (!empty($defaults['contribution_status_id']) && in_array(
420 CRM_Contribute_PseudoConstant
::contributionStatus($defaults['contribution_status_id'], 'name'),
421 // Historically not 'Cancelled' hence not using CRM_Contribute_BAO_Contribution::isContributionStatusNegative.
422 array('Refunded', 'Chargeback')
424 $defaults['refund_trxn_id'] = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionTrxnID($this->_id
);
427 $defaults['refund_trxn_id'] = isset($defaults['trxn_id']) ?
$defaults['trxn_id'] : NULL;
435 foreach ($dates as $key) {
436 if (!empty($defaults[$key])) {
437 list($defaults[$key], $defaults[$key . '_time'])
438 = CRM_Utils_Date
::setDateDefaults(CRM_Utils_Array
::value($key, $defaults), 'activityDateTime');
442 if (!$this->_id
&& empty($defaults['receive_date'])) {
443 list($defaults['receive_date'],
444 $defaults['receive_date_time']
445 ) = CRM_Utils_Date
::setDateDefaults(NULL, 'activityDateTime');
448 $this->assign('receive_date', CRM_Utils_Date
::processDate(CRM_Utils_Array
::value('receive_date', $defaults),
449 CRM_Utils_Array
::value('receive_date_time', $defaults)
451 $currency = CRM_Utils_Array
::value('currency', $defaults);
452 $this->assign('currency', $currency);
453 // Hack to get currency info to the js layer. CRM-11440.
454 CRM_Utils_Money
::format(1);
455 $this->assign('currencySymbol', CRM_Utils_Array
::value($currency, CRM_Utils_Money
::$_currencySymbols));
456 $this->assign('totalAmount', CRM_Utils_Array
::value('total_amount', $defaults));
458 // Inherit campaign from pledge.
459 if ($this->_ppID
&& !empty($this->_pledgeValues
['campaign_id'])) {
460 $defaults['campaign_id'] = $this->_pledgeValues
['campaign_id'];
463 $this->_defaults
= $defaults;
468 * Build the form object.
470 public function buildQuickForm() {
471 // FIXME: This probably needs to be done in preprocess
472 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()
473 && $this->_action
& CRM_Core_Action
::UPDATE
474 && CRM_Utils_Array
::value('financial_type_id', $this->_values
)
476 $financialTypeID = CRM_Contribute_PseudoConstant
::financialType($this->_values
['financial_type_id']);
477 CRM_Financial_BAO_FinancialType
::checkPermissionedLineItems($this->_id
, 'edit');
478 if (!CRM_Core_Permission
::check('edit contributions of type ' . $financialTypeID)) {
479 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
484 //tax rate from financialType
485 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant
::getTaxRates()));
486 $this->assign('currencies', json_encode(CRM_Core_OptionGroup
::values('currencies_enabled')));
488 // build price set form.
489 $buildPriceSet = FALSE;
490 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
491 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
492 $this->assign('invoicing', $invoicing);
494 // display tax amount on edit contribution page
495 if ($invoicing && $this->_action
& CRM_Core_Action
::UPDATE
&& isset($this->_values
['tax_amount'])) {
496 $this->assign('totalTaxAmount', $this->_values
['tax_amount']);
499 if (empty($this->_lineItems
) &&
500 ($this->_priceSetId ||
!empty($_POST['price_set_id']))
502 $buildPriceSet = TRUE;
503 $getOnlyPriceSetElements = TRUE;
504 if (!$this->_priceSetId
) {
505 $this->_priceSetId
= $_POST['price_set_id'];
506 $getOnlyPriceSetElements = FALSE;
509 $this->set('priceSetId', $this->_priceSetId
);
510 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
512 // get only price set form elements.
513 if ($getOnlyPriceSetElements) {
517 // use to build form during form rule.
518 $this->assign('buildPriceSet', $buildPriceSet);
520 $defaults = $this->_values
;
521 $additionalDetailFields = array(
525 'non_deductible_amount',
529 foreach ($additionalDetailFields as $key) {
530 if (!empty($defaults[$key])) {
531 $defaults['hidden_AdditionalDetail'] = 1;
536 if ($this->_productDAO
) {
537 if ($this->_productDAO
->product_id
) {
538 $defaults['hidden_Premium'] = 1;
542 if ($this->_noteID
&&
543 isset($this->_values
['note'])
545 $defaults['hidden_AdditionalDetail'] = 1;
549 ts('Additional Details') => 'AdditionalDetail',
552 //Add Premium pane only if Premium is exists.
553 $dao = new CRM_Contribute_DAO_Product();
556 if ($dao->find(TRUE)) {
557 $paneNames[ts('Premium Information')] = 'Premium';
561 if (CRM_Core_Payment_Form
::buildPaymentForm($this, $this->_paymentProcessor
, FALSE, TRUE) == TRUE) {
562 if (!empty($this->_recurPaymentProcessors
)) {
563 $buildRecurBlock = TRUE;
565 // ppID denotes a pledge payment.
566 foreach ($this->_paymentProcessors
as $processor) {
567 if (!empty($processor['is_recur']) && !empty($processor['object']) && $processor['object']->supports('recurContributionsForPledges')) {
568 $buildRecurBlock = TRUE;
571 $buildRecurBlock = FALSE;
574 if ($buildRecurBlock) {
575 CRM_Contribute_Form_Contribution_Main
::buildRecur($this);
576 $this->setDefaults(array('is_recur' => 0));
577 $this->assign('buildRecurBlock', TRUE);
578 $recurJs = array('onChange' => "buildRecurBlock( this.value ); return false;");
584 foreach ($paneNames as $name => $type) {
585 $allPanes[$name] = $this->generatePane($type, $defaults);
588 $qfKey = $this->controller
->_key
;
589 $this->assign('qfKey', $qfKey);
590 $this->assign('allPanes', $allPanes);
592 $this->addFormRule(array('CRM_Contribute_Form_Contribution', 'formRule'), $this);
594 if ($this->_formType
) {
595 $this->assign('formType', $this->_formType
);
599 $this->applyFilter('__ALL__', 'trim');
601 if ($this->_action
& CRM_Core_Action
::DELETE
) {
602 $this->addButtons(array(
605 'name' => ts('Delete'),
606 'spacing' => ' ',
611 'name' => ts('Cancel'),
618 //need to assign custom data type and subtype to the template
619 $this->assign('customDataType', 'Contribution');
620 $this->assign('customDataSubType', $this->_contributionType
);
621 $this->assign('entityID', $this->_id
);
623 if ($this->_context
== 'standalone') {
624 $this->addEntityRef('contact_id', ts('Contact'), array(
626 'api' => array('extra' => array('email')),
630 $attributes = CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Contribution');
632 // Check permissions for financial type first
633 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes, $this->_action
);
634 if (empty($financialTypes)) {
635 CRM_Core_Error
::statusBounce(ts('You do not have all the permissions needed for this page.'));
637 $financialType = $this->add('select', 'financial_type_id',
638 ts('Financial Type'),
639 array('' => ts('- select -')) +
$financialTypes,
641 array('onChange' => "CRM.buildCustomData( 'Contribution', this.value );")
644 $paymentInstrument = FALSE;
646 $paymentInstrument = $this->add('select', 'payment_instrument_id',
647 ts('Payment Method'),
648 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::paymentInstrument(),
649 TRUE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
653 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), array('class' => 'twelve') +
$attributes['trxn_id']);
655 //add receipt for offline contribution
656 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
658 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
660 $status = CRM_Contribute_PseudoConstant
::contributionStatus();
662 // suppressing contribution statuses that are NOT relevant to pledges (CRM-5169)
663 $statusName = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
670 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
673 elseif ((!$this->_ppID
&& $this->_id
) ||
!$this->_id
) {
674 $suppressFlag = FALSE;
676 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
677 if (CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails)) {
678 $suppressFlag = TRUE;
681 if (!$suppressFlag) {
686 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
690 unset($status[CRM_Utils_Array
::key('Overdue', $statusName)]);
694 // define the status IDs that show the cancellation info, see CRM-17589
695 $cancelInfo_show_ids = array();
696 foreach (array_keys($statusName) as $status_id) {
697 if (CRM_Contribute_BAO_Contribution
::isContributionStatusNegative($status_id)) {
698 $cancelInfo_show_ids[] = "'$status_id'";
701 $this->assign('cancelInfo_show_ids', implode(',', $cancelInfo_show_ids));
704 $contributionStatus = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_id
, 'contribution_status_id');
705 $name = CRM_Utils_Array
::value($contributionStatus, $statusName);
711 unset($status[CRM_Utils_Array
::key('In Progress', $statusName)]);
712 unset($status[CRM_Utils_Array
::key('Pending', $statusName)]);
713 unset($status[CRM_Utils_Array
::key('Failed', $statusName)]);
718 unset($status[CRM_Utils_Array
::key('Refunded', $statusName)]);
719 unset($status[CRM_Utils_Array
::key('Chargeback', $statusName)]);
731 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
737 unset($status[CRM_Utils_Array
::key('Refunded', $statusName)]);
738 unset($status[CRM_Utils_Array
::key('Chargeback', $statusName)]);
741 $this->add('select', 'contribution_status_id',
742 ts('Contribution Status'),
748 $this->addDateTime('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
750 if ($this->_online
) {
751 $this->assign('hideCalender', TRUE);
753 $checkNumber = $this->add('text', 'check_number', ts('Check Number'), $attributes['check_number']);
755 $this->addDateTime('receipt_date', ts('Receipt Date'), FALSE, array('formatType' => 'activityDateTime'));
756 $this->addDateTime('cancel_date', ts('Cancelled / Refunded Date'), FALSE, array('formatType' => 'activityDateTime'));
758 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
759 $this->add('text', 'refund_trxn_id', ts('Transaction ID for the refund payment'));
760 $element = $this->add('select',
761 'payment_processor_id',
762 ts('Payment Processor'),
768 if ($this->_online
) {
773 if (empty($this->_lineItems
)) {
774 $buildPriceSet = FALSE;
775 $priceSets = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute');
776 if (!empty($priceSets) && !$this->_ppID
) {
777 $buildPriceSet = TRUE;
780 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
781 // and if we already have line items for that participant. CRM-5095
782 if ($buildPriceSet && $this->_id
) {
783 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
784 $pledgePaymentId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
789 if ($pledgePaymentId) {
790 $buildPriceSet = FALSE;
792 if ($participantID = CRM_Utils_Array
::value('participant', $componentDetails)) {
793 $participantLI = CRM_Price_BAO_LineItem
::getLineItems($participantID);
794 if (!CRM_Utils_System
::isNull($participantLI)) {
795 $buildPriceSet = FALSE;
800 $hasPriceSets = FALSE;
801 if ($buildPriceSet) {
802 $hasPriceSets = TRUE;
803 // CRM-16451: set financial type of 'Price Set' in back office contribution
804 // instead of selecting manually
805 $financialTypeIds = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute', 'financial_type_id');
806 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
808 '' => ts('Choose price set'),
810 NULL, array('onchange' => "buildAmount( this.value, " . json_encode($financialTypeIds) . ");")
812 if ($this->_online
&& !($this->_action
& CRM_Core_Action
::UPDATE
)) {
816 $this->assign('hasPriceSets', $hasPriceSets);
817 $currencyFreeze = FALSE;
818 if (!($this->_action
& CRM_Core_Action
::UPDATE
)) {
819 if ($this->_online ||
$this->_ppID
) {
820 $attributes['total_amount'] = array_merge($attributes['total_amount'], array(
822 'style' => "background-color:#EBECE4",
824 $optionTypes = array(
825 '1' => ts('Adjust Pledge Payment Schedule?'),
826 '2' => ts('Adjust Total Pledge Amount?'),
828 $this->addRadio('option_type',
834 $currencyFreeze = TRUE;
838 $totalAmount = $this->addMoney('total_amount',
840 ($hasPriceSets) ?
FALSE : TRUE,
841 $attributes['total_amount'],
842 TRUE, 'currency', NULL, $currencyFreeze
846 $this->add('text', 'source', ts('Source'), CRM_Utils_Array
::value('source', $attributes));
848 // CRM-7362 --add campaigns.
849 CRM_Campaign_BAO_Campaign
::addCampaign($this, CRM_Utils_Array
::value('campaign_id', $this->_values
));
851 CRM_Contribute_Form_SoftCredit
::buildQuickForm($this);
855 $js = array('onclick' => "return verify( );");
858 $mailingInfo = Civi
::settings()->get('mailing_backend');
859 $this->assign('outBound_option', $mailingInfo['outBound_option']);
861 $this->addButtons(array(
864 'name' => ts('Save'),
870 'name' => ts('Save and New'),
876 'name' => ts('Cancel'),
881 // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
882 // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
883 if ($this->_id
&& $this->_values
['contribution_status_id'] == array_search('Cancelled', $statusName)) {
885 $totalAmount->freeze();
887 $checkNumber->freeze();
888 $paymentInstrument->freeze();
890 $financialType->freeze();
893 // if contribution is related to membership or participant freeze Financial Type, Amount
894 if ($this->_id
&& isset($this->_values
['tax_amount'])) {
895 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
896 if (CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails)) {
898 $totalAmount->freeze();
900 $financialType->freeze();
901 $this->assign('freezeFinancialType', TRUE);
905 if ($this->_action
& CRM_Core_Action
::VIEW
) {
913 * @param array $fields
914 * The input form values.
915 * @param array $files
916 * The uploaded files if any.
920 * true if no errors, else array of errors
922 public static function formRule($fields, $files, $self) {
924 // Check for Credit Card Contribution.
926 if (empty($fields['payment_processor_id'])) {
927 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
930 // validate payment instrument (e.g. credit card number)
931 CRM_Core_Payment_Form
::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, NULL);
935 // Do the amount validations.
936 if (empty($fields['total_amount']) && empty($self->_lineItems
)) {
937 if ($priceSetId = CRM_Utils_Array
::value('price_set_id', $fields)) {
938 CRM_Price_BAO_PriceField
::priceSetValidation($priceSetId, $fields, $errors);
942 $softErrors = CRM_Contribute_Form_SoftCredit
::formRule($fields, $errors, $self);
944 if (!empty($fields['total_amount']) && (!empty($fields['net_amount']) ||
!empty($fields['fee_amount']))) {
945 $sum = CRM_Utils_Rule
::cleanMoney($fields['net_amount']) + CRM_Utils_Rule
::cleanMoney($fields['fee_amount']);
946 // For taxable contribution we need to deduct taxable amount from
947 // (net amount + fee amount) before comparing it with total amount
948 if (!empty($self->_values
['tax_amount'])) {
949 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($self->_id
);
950 if (!(CRM_Utils_Array
::value('membership', $componentDetails) ||
951 CRM_Utils_Array
::value('participant', $componentDetails))
953 $sum = CRM_Utils_Money
::format($sum - $self->_values
['tax_amount'], NULL, '%a');
956 if (CRM_Utils_Rule
::cleanMoney($fields['total_amount']) != $sum) {
957 $errors['total_amount'] = ts('The sum of fee amount and net amount must be equal to total amount');
961 //CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
962 CRM_Contribute_BAO_ContributionRecur
::validateRecurContribution($fields, $files, $self, $errors);
964 // Form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
965 if (($self->_action
& CRM_Core_Action
::UPDATE
)
967 && $self->_values
['contribution_status_id'] != $fields['contribution_status_id']
969 CRM_Contribute_BAO_Contribution
::checkStatusValidation($self->_values
, $fields, $errors);
971 // CRM-16015, add form-rule to restrict change of financial type if using price field of different financial type
972 if (($self->_action
& CRM_Core_Action
::UPDATE
)
974 && $self->_values
['financial_type_id'] != $fields['financial_type_id']
976 CRM_Contribute_BAO_Contribution
::checkFinancialTypeChange(NULL, $self->_id
, $errors);
978 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
979 if (!empty($fields['fee_amount']) && !empty($fields['financial_type_id']) && $financialType = CRM_Contribute_BAO_Contribution
::validateFinancialType($fields['financial_type_id'])) {
980 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
983 // $trxn_id must be unique CRM-13919
984 if (!empty($fields['trxn_id'])) {
985 $queryParams = array(1 => array($fields['trxn_id'], 'String'));
986 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
988 $queryParams[2] = array((int) $self->_id
, 'Integer');
989 $query .= ' and id !=%2';
991 $tCnt = CRM_Core_DAO
::singleValueQuery($query, $queryParams);
993 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', array(1 => $fields['trxn_id']));
997 $errors = array_merge($errors, $softErrors);
1002 * Process the form submission.
1004 public function postProcess() {
1005 if ($this->_action
& CRM_Core_Action
::DELETE
) {
1006 CRM_Contribute_BAO_Contribution
::deleteContribution($this->_id
);
1007 CRM_Core_Session
::singleton()->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
1008 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1012 // Get the submitted form values.
1013 $submittedValues = $this->controller
->exportValues($this->_name
);
1016 $contribution = $this->submit($submittedValues, $this->_action
, $this->_ppID
);
1018 catch (PaymentProcessorException
$e) {
1019 // Set the contribution mode.
1020 $urlParams = "action=add&cid={$this->_contactID}";
1022 $urlParams .= "&mode={$this->_mode}";
1024 if (!empty($this->_ppID
)) {
1025 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
1028 CRM_Core_Error
::statusBounce($e->getMessage(), $urlParams, ts('Payment Processor Error'));
1030 $session = CRM_Core_Session
::singleton();
1031 $buttonName = $this->controller
->getButtonName();
1032 if ($this->_context
== 'standalone') {
1033 if ($buttonName == $this->getButtonName('upload', 'new')) {
1034 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contribute/add',
1035 'reset=1&action=add&context=standalone'
1039 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
1040 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1044 elseif ($this->_context
== 'contribution' && $this->_mode
&& $buttonName == $this->getButtonName('upload', 'new')) {
1045 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
1046 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
1049 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1050 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
1051 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
1055 //store contribution ID if not yet set (on create)
1056 if (empty($this->_id
) && !empty($contribution->id
)) {
1057 $this->_id
= $contribution->id
;
1062 * Process credit card payment.
1064 * @param array $submittedValues
1065 * @param array $lineItem
1067 * @param int $contactID
1070 * @return bool|\CRM_Contribute_DAO_Contribution
1071 * @throws \CRM_Core_Exception
1072 * @throws \Civi\Payment\Exception\PaymentProcessorException
1074 protected function processCreditCard($submittedValues, $lineItem, $contactID) {
1075 $isTest = ($this->_mode
== 'test') ?
1 : 0;
1076 // CRM-12680 set $_lineItem if its not set
1077 // @todo - I don't believe this would ever BE set. I can't find anywhere in the code.
1078 // It would be better to pass line item out to functions than $this->_lineItem as
1079 // we don't know what is being changed where.
1080 if (empty($this->_lineItem
) && !empty($lineItem)) {
1081 $this->_lineItem
= $lineItem;
1084 $this->_paymentObject
= Civi\Payment\System
::singleton()->getById($submittedValues['payment_processor_id']);
1085 $this->_paymentProcessor
= $this->_paymentObject
->getPaymentProcessor();
1087 // Set source if not set
1088 if (empty($submittedValues['source'])) {
1089 $userID = CRM_Core_Session
::singleton()->get('userID');
1090 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1093 $submittedValues['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
1096 $params = $submittedValues;
1097 $this->_params
= array_merge($this->_params
, $submittedValues);
1099 // Mapping requiring documentation.
1100 $this->_params
['payment_processor'] = $submittedValues['payment_processor_id'];
1102 $now = date('YmdHis');
1104 // we need to retrieve email address
1105 if ($this->_context
== 'standalone' && !empty($submittedValues['is_email_receipt'])) {
1106 list($this->userDisplayName
,
1108 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contactID);
1109 $this->assign('displayName', $this->userDisplayName
);
1112 $this->_contributorEmail
= $this->userEmail
;
1113 $this->_contributorContactID
= $contactID;
1114 $this->processBillingAddress();
1115 if (!empty($params['source'])) {
1116 unset($params['source']);
1119 $this->_params
['amount'] = $this->_params
['total_amount'];
1120 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
1121 // function to get correct amount level consistently. Remove setting of the amount level in
1122 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
1123 // to cover all variants.
1124 $this->_params
['amount_level'] = 0;
1125 $this->_params
['description'] = ts("Contribution submitted by a staff person using contributor's credit card");
1126 $this->_params
['currencyID'] = CRM_Utils_Array
::value('currency',
1128 CRM_Core_Config
::singleton()->defaultCurrency
1131 if (!empty($this->_params
['receive_date'])) {
1132 $this->_params
['receive_date'] = CRM_Utils_Date
::processDate($this->_params
['receive_date'], $this->_params
['receive_date_time']);
1135 $this->_params
['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $params);
1136 $this->_params
['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $params);
1137 $this->_params
['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $params);
1139 //Add common data to formatted params
1140 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
1142 if (empty($this->_params
['invoice_id'])) {
1143 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
1146 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
1149 // At this point we've created a contact and stored its address etc
1150 // all the payment processors expect the name and address to be in the
1151 // so we copy stuff over to first_name etc.
1152 $paymentParams = $this->_params
;
1153 $paymentParams['contactID'] = $contactID;
1154 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
1156 $financialType = new CRM_Financial_DAO_FinancialType();
1157 $financialType->id
= $params['financial_type_id'];
1158 $financialType->find(TRUE);
1160 // Add some financial type details to the params list
1161 // if folks need to use it.
1162 $paymentParams['contributionType_name'] = $this->_params
['contributionType_name'] = $financialType->name
;
1163 $paymentParams['contributionPageID'] = NULL;
1165 if (!empty($this->_params
['is_email_receipt'])) {
1166 $paymentParams['email'] = $this->userEmail
;
1167 $paymentParams['is_email_receipt'] = 1;
1170 $paymentParams['is_email_receipt'] = 0;
1171 $this->_params
['is_email_receipt'] = 0;
1173 if (!empty($this->_params
['receive_date'])) {
1174 $paymentParams['receive_date'] = $this->_params
['receive_date'];
1177 $this->_params
['receive_date'] = $now;
1179 if (!empty($this->_params
['is_email_receipt'])) {
1180 $this->_params
['receipt_date'] = $now;
1183 $this->_params
['receipt_date'] = CRM_Utils_Date
::processDate($this->_params
['receipt_date'],
1184 $params['receipt_date_time'], TRUE
1188 $this->set('params', $this->_params
);
1190 $this->assign('receive_date', $this->_params
['receive_date']);
1192 // Result has all the stuff we need
1193 // lets archive it to a financial transaction
1194 if ($financialType->is_deductible
) {
1195 $this->assign('is_deductible', TRUE);
1196 $this->set('is_deductible', TRUE);
1198 $contributionParams = array(
1199 'contact_id' => $contactID,
1200 'line_item' => $lineItem,
1201 'is_test' => $isTest,
1202 'campaign_id' => CRM_Utils_Array
::value('campaign_id', $this->_params
),
1203 'contribution_page_id' => CRM_Utils_Array
::value('contribution_page_id', $this->_params
),
1204 'source' => CRM_Utils_Array
::value('source', $paymentParams, CRM_Utils_Array
::value('description', $paymentParams)),
1205 'thankyou_date' => CRM_Utils_Array
::value('thankyou_date', $this->_params
),
1208 if (empty($paymentParams['is_pay_later'])) {
1209 // @todo look up payment_instrument_id on payment processor table.
1210 $contributionParams['payment_instrument_id'] = 1;
1213 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processFormContribution($this,
1216 $contributionParams,
1220 CRM_Utils_Array
::value('is_recur', $this->_params
)
1223 $paymentParams['contributionID'] = $contribution->id
;
1224 $paymentParams['contributionTypeID'] = $contribution->financial_type_id
;
1225 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
1226 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1228 if ($paymentParams['amount'] > 0.0) {
1229 // force a re-get of the payment processor in case the form changed it, CRM-7179
1230 // NOTE - I expect this is obsolete.
1231 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
1233 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id');
1234 $result = $payment->doPayment($paymentParams, 'contribute');
1235 $this->assign('trxn_id', $result['trxn_id']);
1236 $contribution->trxn_id
= $result['trxn_id'];
1237 /* Our scenarios here are
1238 * 1) the payment failed & an Exception should have been thrown
1239 * 2) the payment succeeded but the payment is not immediate (for example a recurring payment
1240 * with a delayed start)
1241 * 3) the payment succeeded with an immediate payment.
1243 * The doPayment function ensures that payment_status_id is always set
1244 * as historically we have had to guess from the context - ie doDirectPayment
1245 * = error or success, unless it is a recurring contribution in which case it is pending.
1247 if ($result['payment_status_id'] == array_search('Completed', $statuses)) {
1249 civicrm_api3('contribution', 'completetransaction', array(
1250 'id' => $contribution->id
,
1251 'trxn_id' => $result['trxn_id'],
1252 'payment_processor_id' => $this->_paymentProcessor
['id'],
1253 'is_transactional' => FALSE,
1254 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $result),
1256 // This has now been set to 1 in the DB - declare it here also
1257 $contribution->contribution_status_id
= 1;
1259 catch (CiviCRM_API3_Exception
$e) {
1260 if ($e->getErrorCode() != 'contribution_completed') {
1261 throw new CRM_Core_Exception('Failed to update contribution in database');
1266 // Save the trxn_id.
1267 $contribution->save();
1270 catch (PaymentProcessorException
$e) {
1271 CRM_Contribute_BAO_Contribution
::failPayment($contribution->id
, $paymentParams['contactID'], $e->getMessage());
1272 throw new PaymentProcessorException($e->getMessage());
1275 // Send receipt mail.
1276 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1277 if ($contribution->id
&& !empty($this->_params
['is_email_receipt'])) {
1278 $this->_params
['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $result);
1279 $this->_params
['contact_id'] = $contactID;
1280 $this->_params
['contribution_id'] = $contribution->id
;
1281 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $this->_params
, TRUE)) {
1282 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1286 return $contribution;
1290 * Generate the data to construct a snippet based pane.
1292 * This form also assigns the showAdditionalInfo var based on historical code.
1293 * This appears to mean 'there is a pane to show'.
1295 * @param string $type
1296 * Type of Pane - this is generally used to determine the function name used to build it
1297 * - e.g CreditCard, AdditionalDetail
1298 * @param array $defaults
1301 * We aim to further refactor & simplify this but currently
1303 * - should additional info be shown?
1305 protected function generatePane($type, $defaults) {
1306 $urlParams = "snippet=4&formType={$type}";
1308 $urlParams .= "&mode={$this->_mode}";
1312 if ($type == 'CreditCard' ||
1313 $type == 'DirectDebit'
1319 'url' => CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams),
1324 // See if we need to include this paneName in the current form.
1325 if ($this->_formType
== $type ||
!empty($_POST["hidden_{$type}"]) ||
1326 CRM_Utils_Array
::value("hidden_{$type}", $defaults)
1328 $this->assign('showAdditionalInfo', TRUE);
1329 $pane['open'] = 'true';
1332 if ($type == 'CreditCard' ||
$type == 'DirectDebit') {
1333 // @todo would be good to align tpl name with form name...
1334 // @todo document why this hidden variable is required.
1335 $this->add('hidden', 'hidden_' . $type, 1);
1339 $additionalInfoFormFunction = 'build' . $type;
1340 CRM_Contribute_Form_AdditionalInfo
::$additionalInfoFormFunction($this);
1346 * Wrapper for unit testing the post process submit function.
1348 * (If we expose through api we can get default additions 'for free').
1350 * @param array $params
1351 * @param int $action
1352 * @param string|null $creditCardMode
1354 * @throws \CiviCRM_API3_Exception
1356 public function testSubmit($params, $action, $creditCardMode = NULL) {
1358 'soft_credit_contact_id' => array(),
1359 'receipt_date' => '',
1360 'receipt_date_time' => '',
1361 'cancel_date' => '',
1362 'cancel_date_time' => '',
1363 'hidden_Premium' => 1,
1366 if (!empty($params['id'])) {
1367 $existingContribution = civicrm_api3('contribution', 'getsingle', array(
1368 'id' => $params['id'],
1370 $this->_id
= $params['id'];
1373 $existingContribution = array();
1376 $this->_defaults
['contribution_status_id'] = CRM_Utils_Array
::value('contribution_status_id',
1377 $existingContribution
1380 $this->_defaults
['total_amount'] = CRM_Utils_Array
::value('total_amount',
1381 $existingContribution
1384 if ($creditCardMode) {
1385 $this->_mode
= $creditCardMode;
1388 // Required because processCreditCard calls set method on this.
1389 $_SERVER['REQUEST_METHOD'] = 'GET';
1390 $this->controller
= new CRM_Core_Controller();
1392 CRM_Contribute_Form_AdditionalInfo
::buildPremium($this);
1394 $this->_fields
= array();
1395 $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array
::value('pledge_payment_id', $params));
1400 * @param array $submittedValues
1402 * @param int $action
1404 * - CRM_Core_Action::UPDATE
1406 * @param $pledgePaymentID
1409 * @throws \Exception
1411 protected function submit($submittedValues, $action, $pledgePaymentID) {
1412 $softParams = $softIDs = array();
1413 $pId = $contribution = $isRelatedId = FALSE;
1414 $this->_params
= $submittedValues;
1415 $this->beginPostProcess();
1417 if (!empty($submittedValues['price_set_id']) && $action & CRM_Core_Action
::UPDATE
) {
1418 $line = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution');
1419 $lineID = key($line);
1420 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array
::value('price_field_id', $line[$lineID]), 'price_set_id');
1421 $quickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1422 // Why do we do this? Seems like a like a wrapper for old functionality - but single line price sets & quick
1423 // config should be treated the same.
1425 CRM_Price_BAO_LineItem
::deleteLineItems($this->_id
, 'civicrm_contribution');
1429 // Process price set and get total amount and line items.
1430 $lineItem = array();
1431 $priceSetId = CRM_Utils_Array
::value('price_set_id', $submittedValues);
1432 if (empty($priceSetId) && !$this->_id
) {
1433 $this->_priceSetId
= $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1434 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
1435 $fieldID = key($this->_priceSet
['fields']);
1436 $fieldValueId = key($this->_priceSet
['fields'][$fieldID]['options']);
1437 $this->_priceSet
['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1438 $submittedValues['price_' . $fieldID] = 1;
1441 // Every contribution has a price-set - the only reason it shouldn't be set is if we are dealing with
1442 // quick config (very very arguably) & yet we see that this could still be quick config so this should be understood
1443 // as a point of fragility rather than a logical 'if' clause.
1445 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
1446 $submittedValues, $lineItem[$priceSetId]);
1447 // Unset tax amount for offline 'is_quick_config' contribution.
1448 // @todo WHY - quick config was conceived as a quick way to configure contribution forms.
1449 // this is an example of 'other' functionality being hung off it.
1450 if ($this->_priceSet
['is_quick_config'] &&
1451 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant
::getTaxRates())
1453 unset($submittedValues['tax_amount']);
1455 $submittedValues['total_amount'] = CRM_Utils_Array
::value('amount', $submittedValues);
1458 if ($this->_compId
) {
1459 if ($this->_context
== 'participant') {
1460 $pId = $this->_compId
;
1462 elseif ($this->_context
== 'membership') {
1463 $isRelatedId = TRUE;
1466 $pId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id
, 'participant_id', 'contribution_id');
1470 $contributionDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1471 if (array_key_exists('membership', $contributionDetails)) {
1472 $isRelatedId = TRUE;
1474 elseif (array_key_exists('participant', $contributionDetails)) {
1475 $pId = $contributionDetails['participant'];
1480 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id
) {
1481 // CRM-10117 update the line items for participants.
1482 // @todo - if we are completing a contribution then the api call
1483 // civicrm_api3('Contribution', 'completetransaction') should take care of
1484 // all associated updates rather than replicating them on the form layer.
1486 $entityTable = 'participant';
1488 $isRelatedId = FALSE;
1489 $participantParams = array(
1490 'fee_amount' => $submittedValues['total_amount'],
1493 CRM_Event_BAO_Participant
::add($participantParams);
1494 if (empty($this->_lineItems
)) {
1495 $this->_lineItems
[] = CRM_Price_BAO_LineItem
::getLineItems($entityID, 'participant', 1);
1499 $entityTable = 'contribution';
1500 $entityID = $this->_id
;
1503 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, $entityTable, NULL, TRUE, $isRelatedId);
1504 foreach (array_keys($lineItems) as $id) {
1505 $lineItems[$id]['id'] = $id;
1507 $itemId = key($lineItems);
1508 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1509 $this->_priceSetId
= CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1512 // @todo see above - new functionality has been inappropriately added to the quick config concept
1513 // and new functionality has been added onto the form layer rather than the BAO :-(
1514 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1515 //CRM-16833: Ensure tax is applied only once for membership conribution, when status changed.(e.g Pending to Completed).
1516 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1517 if (!(CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails))) {
1518 if (!($this->_action
& CRM_Core_Action
::UPDATE
&& (($this->_defaults
['contribution_status_id'] != $submittedValues['contribution_status_id'])))) {
1519 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule
::cleanMoney(CRM_Utils_Array
::value('total_amount', $submittedValues));
1523 // Update line total and total amount with tax on edit.
1524 $financialItemsId = CRM_Core_PseudoConstant
::getTaxRates();
1525 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1526 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1529 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1530 $submittedValues['tax_amount'] = 'null';
1532 if ($lineItems[$itemId]['tax_rate']) {
1533 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total'];
1534 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] +
$lineItems[$itemId]['tax_amount'];
1535 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1538 // CRM-10117 update the line items for participants.
1539 if (!empty($lineItems[$itemId]['price_field_id'])) {
1540 $lineItem[$this->_priceSetId
] = $lineItems;
1545 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1548 //CRM-11529 for quick config back office transactions
1549 //when financial_type_id is passed in form, update the
1550 //line items with the financial type selected in form
1551 // NOTE that this IS still a legitimate use of 'quick-config' for contributions under the current DB but
1552 // we should look at having a price field per contribution type & then there would be little reason
1553 // for the back-office contribution form postProcess to know if it is a quick-config form.
1554 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array
::value($this->_priceSetId
, $lineItem)
1556 foreach ($lineItem[$this->_priceSetId
] as &$values) {
1557 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1561 if (!isset($submittedValues['total_amount'])) {
1562 $submittedValues['total_amount'] = CRM_Utils_Array
::value('total_amount', $this->_values
);
1564 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
1566 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
1567 if ($this->_id
&& count($isEmpty) == 1 && key($isEmpty) == NULL) {
1568 //Delete existing soft credit records if soft credit list is empty on update
1569 CRM_Contribute_BAO_ContributionSoft
::del(array('contribution_id' => $this->_id
, 'pcp_id' => 0));
1572 // set the contact, when contact is selected
1573 if (!empty($submittedValues['contact_id'])) {
1574 $this->_contactID
= $submittedValues['contact_id'];
1577 $formValues = $submittedValues;
1579 // Credit Card Contribution.
1581 $paramsSetByPaymentProcessingSubsystem = array(
1583 'payment_instrument_id',
1584 'contribution_status_id',
1588 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1589 if (isset($formValues[$key])) {
1590 unset($formValues[$key]);
1593 $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID
);
1594 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1595 $formValues[$key] = $contribution->$key;
1599 // Offline Contribution.
1600 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1602 // get the required field value only.
1604 $params = $ids = array();
1606 $params['contact_id'] = $this->_contactID
;
1607 $params['currency'] = $this->getCurrency($submittedValues);
1609 //format soft-credit/pcp param first
1610 CRM_Contribute_BAO_ContributionSoft
::formatSoftCreditParams($submittedValues, $this);
1611 $params = array_merge($params, $submittedValues);
1614 'financial_type_id',
1615 'contribution_status_id',
1616 'payment_instrument_id',
1621 foreach ($fields as $f) {
1622 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1625 // CRM-5740 if priceset is used, no need to cleanup money.
1627 $params['skipCleanMoney'] = 1;
1636 foreach ($dates as $d) {
1637 $params[$d] = CRM_Utils_Date
::processDate($formValues[$d], $formValues[$d . '_time'], TRUE);
1640 if (!empty($formValues['is_email_receipt'])) {
1641 $params['receipt_date'] = date("Y-m-d");
1644 if (CRM_Contribute_BAO_Contribution
::isContributionStatusNegative($params['contribution_status_id'])
1646 if (CRM_Utils_System
::isNull(CRM_Utils_Array
::value('cancel_date', $params))) {
1647 $params['cancel_date'] = date('YmdHis');
1651 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1654 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1655 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1656 if ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Pending', 'name')) {
1657 $params['is_pay_later'] = 1;
1659 elseif ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name')) {
1660 $params['is_pay_later'] = 0;
1663 $ids['contribution'] = $params['id'] = $this->_id
;
1665 // Add Additional common information to formatted params.
1666 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($formValues, $params, $this);
1668 $params['contribution_mode'] = 'participant';
1669 $params['participant_id'] = $pId;
1670 $params['skipLineItem'] = 1;
1672 elseif ($isRelatedId) {
1673 $params['contribution_mode'] = 'membership';
1675 $params['line_item'] = $lineItem;
1676 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array
::value('id', $this->_paymentProcessor
);
1677 if (isset($submittedValues['tax_amount'])) {
1678 $params['tax_amount'] = $submittedValues['tax_amount'];
1680 //create contribution.
1681 if ($isQuickConfig) {
1682 $params['is_quick_config'] = 1;
1684 $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
1686 // we are already handling note below, so to avoid duplicate notes against $contribution
1687 if (!empty($params['note']) && !empty($submittedValues['note'])) {
1688 unset($params['note']);
1690 $contribution = CRM_Contribute_BAO_Contribution
::create($params, $ids);
1692 // process associated membership / participant, CRM-4395
1693 if ($contribution->id
&& $action & CRM_Core_Action
::UPDATE
) {
1694 $this->statusMessage
[] = $this->updateRelatedComponent($contribution->id
,
1695 $contribution->contribution_status_id
,
1696 CRM_Utils_Array
::value('contribution_status_id',
1699 $contribution->receive_date
1703 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1705 $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
1707 //send receipt mail.
1708 if ($contribution->id
&& !empty($formValues['is_email_receipt'])) {
1709 $formValues['contact_id'] = $this->_contactID
;
1710 $formValues['contribution_id'] = $contribution->id
;
1712 $formValues +
= CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
);
1714 // to get 'from email id' for send receipt
1715 $this->fromEmailId
= $formValues['from_email_address'];
1716 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $formValues)) {
1717 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1721 $this->statusMessageTitle
= ts('Saved');
1725 if ($contribution->id
&& isset($formValues['product_name'][0])) {
1726 CRM_Contribute_Form_AdditionalInfo
::processPremium($submittedValues, $contribution->id
,
1727 $this->_premiumID
, $this->_options
1731 if ($contribution->id
&& !empty($submittedValues['note'])) {
1732 CRM_Contribute_Form_AdditionalInfo
::processNote($submittedValues, $this->_contactID
, $contribution->id
, $this->_noteID
);
1735 CRM_Core_Session
::setStatus(implode(' ', $this->statusMessage
), $this->statusMessageTitle
, 'success');
1737 CRM_Contribute_BAO_Contribution
::updateRelatedPledge(
1741 (CRM_Utils_Array
::value('option_type', $formValues) == 2) ?
TRUE : FALSE,
1742 $formValues['total_amount'],
1743 CRM_Utils_Array
::value('total_amount', $this->_defaults
),
1744 $formValues['contribution_status_id'],
1745 CRM_Utils_Array
::value('contribution_status_id', $this->_defaults
)
1747 return $contribution;
1751 * Assign tax calculations to contribution receipts.
1753 * @param array $submittedValues
1754 * @param int $action
1755 * @param array $lineItem
1757 protected function invoicingPostProcessHook($submittedValues, $action, $lineItem) {
1759 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
1760 if (!CRM_Utils_Array
::value('invoicing', $invoiceSettings)) {
1764 $getTaxDetails = FALSE;
1765 if ($action & CRM_Core_Action
::ADD
) {
1768 elseif ($action & CRM_Core_Action
::UPDATE
) {
1769 $line = $this->_lineItems
;
1771 foreach ($line as $key => $value) {
1772 foreach ($value as $v) {
1773 if (isset($taxRate[(string) CRM_Utils_Array
::value('tax_rate', $v)])) {
1774 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $v);
1777 if (isset($v['tax_rate'])) {
1778 $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $v);
1779 $getTaxDetails = TRUE;
1785 if ($action & CRM_Core_Action
::UPDATE
) {
1786 if (isset($submittedValues['tax_amount'])) {
1787 $totalTaxAmount = $submittedValues['tax_amount'];
1790 $totalTaxAmount = $this->_values
['tax_amount'];
1792 $this->assign('totalTaxAmount', $totalTaxAmount);
1793 $this->assign('dataArray', $taxRate);
1796 if (!empty($submittedValues['price_set_id'])) {
1797 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1798 $this->assign('getTaxDetails', $getTaxDetails);
1799 $this->assign('dataArray', $taxRate);
1800 $this->assign('taxTerm', CRM_Utils_Array
::value('tax_term', $invoiceSettings));
1803 $this->assign('totalTaxAmount', CRM_Utils_Array
::value('tax_amount', $submittedValues));
1809 * Calculate non deductible amount.
1812 * if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1813 * if non_deductible_amount does NOT exist - then calculate it depending on:
1814 * $financialType->is_deductible and whether there is a product (premium).
1817 * @param $formValues
1821 protected function calculateNonDeductibleAmount($params, $formValues) {
1822 if (!empty($params['non_deductible_amount'])) {
1823 return $params['non_deductible_amount'];
1826 $financialType = new CRM_Financial_DAO_FinancialType();
1827 $financialType->id
= $params['financial_type_id'];
1828 $financialType->find(TRUE);
1830 if ($financialType->is_deductible
) {
1832 if (isset($formValues['product_name'][0])) {
1833 $selectProduct = $formValues['product_name'][0];
1835 // if there is a product - compare the value to the contribution amount
1836 if (isset($selectProduct)) {
1837 $productDAO = new CRM_Contribute_DAO_Product();
1838 $productDAO->id
= $selectProduct;
1839 $productDAO->find(TRUE);
1840 // product value exceeds contribution amount
1841 if ($params['total_amount'] < $productDAO->price
) {
1842 return $params['total_amount'];
1844 // product value does NOT exceed contribution amount
1846 return $productDAO->price
;
1849 // contribution is deductible - but there is no product
1854 // contribution is NOT deductible
1856 return $params['total_amount'];