3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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 +--------------------------------------------------------------------+
29 * This class generates form components for processing a contribution.
31 class CRM_Contribute_Form_Contribution
extends CRM_Contribute_Form_AbstractEditPayment
{
33 * The id of the contribution that we are processing.
40 * The id of the premium that we are processing.
44 public $_premiumID = NULL;
47 * @var CRM_Contribute_DAO_ContributionProduct
49 public $_productDAO = NULL;
59 * The id of the contact associated with this contribution.
66 * The id of the pledge payment that we are processing.
73 * Is this contribution associated with an online.
74 * financial transaction
78 public $_online = FALSE;
81 * Stores all product options.
88 * Storage of parameters from form
95 * Store the contribution Type ID
99 public $_contributionType;
102 * The contribution values if an existing contribution
107 * The pledge values if this contribution is associated with pledge
109 public $_pledgeValues;
111 public $_contributeMode = 'direct';
116 * Parameter with confusing name.
120 public $_compContext;
125 * Possible From email addresses
137 * Store the line items if price set used.
143 * @todo explain why we use lineItem & lineItems
149 * @var array soft credit info
151 public $_softCreditInfo;
153 protected $_formType;
156 * @todo what on earth does cdType stand for????
160 public $_honoreeProfileType;
163 * Array of billing panes to be displayed by billingBlock.tpl.
164 * Currently this is likely to look like
165 * array('Credit Card' => ts('Credit Card') or
166 * array('Direct Debit => ts('Direct Debit')
167 * @todo billing details (address stuff) to be added when we stop hard coding the panes in billingBlock.tpl
171 public $billingPane = array();
174 * Array of the payment fields to be displayed in the payment fieldset (pane) in billingBlock.tpl
175 * this contains all the information to describe these fields from quickform. See CRM_Core_Form_Payment getPaymentFormFieldsMetadata
179 public $_paymentFields = array();
181 * Logged in user's email.
194 * Price set as an array
201 * @todo can we define this a as protected? can we define higher up the chain
211 public $userDisplayName;
214 * Status message to be shown to the user.
218 protected $statusMessage = array();
221 * Status message title to be shown to the user.
223 * Generally the payment processor message title is 'Complete' and offline is 'Saved'
224 * although this might not be a good fit with the broad range of processors.
228 protected $statusMessageTitle;
231 * Set variables up before form is built.
233 public function preProcess() {
235 // Check permission for action.
236 if (!CRM_Core_Permission
::checkActionPermission('CiviContribute', $this->_action
)) {
237 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
240 // @todo - if anyone ever figures out what this _cdType subroutine is about
241 // (or even if it still applies) please add comments!!!!!!!!!!
242 $this->_cdType
= CRM_Utils_Array
::value('type', $_GET);
243 $this->assign('cdType', FALSE);
244 if ($this->_cdType
) {
245 $this->assign('cdType', TRUE);
246 CRM_Custom_Form_CustomData
::preProcess($this);
250 $this->_formType
= CRM_Utils_Array
::value('formType', $_GET);
253 $this->_priceSetId
= CRM_Utils_Array
::value('priceSetId', $_GET);
254 $this->set('priceSetId', $this->_priceSetId
);
255 $this->assign('priceSetId', $this->_priceSetId
);
257 // Get the pledge payment id
258 $this->_ppID
= CRM_Utils_Request
::retrieve('ppid', 'Positive', $this);
260 // Get the contact id
261 $this->_contactID
= CRM_Utils_Request
::retrieve('cid', 'Positive', $this);
264 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, 'add');
265 $this->assign('action', $this->_action
);
267 // Get the contribution id if update
268 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this);
269 if (!empty($this->_id
)) {
270 $this->assign('contribID', $this->_id
);
273 $this->_context
= CRM_Utils_Request
::retrieve('context', 'String', $this);
274 $this->assign('context', $this->_context
);
276 $this->_compId
= CRM_Utils_Request
::retrieve('compId', 'Positive', $this);
278 $this->_compContext
= CRM_Utils_Request
::retrieve('compContext', 'String', $this);
280 //set the contribution mode.
281 $this->_mode
= CRM_Utils_Request
::retrieve('mode', 'String', $this);
283 $this->assign('contributionMode', $this->_mode
);
284 if ($this->_action
& CRM_Core_Action
::DELETE
) {
288 $this->assign('showCheckNumber', TRUE);
290 $this->_fromEmails
= CRM_Core_BAO_Email
::getFromEmail();
291 $this->assignPaymentRelatedVariables();
293 if (in_array('CiviPledge', CRM_Core_Config
::singleton()->enableComponents
) && !$this->_formType
) {
294 $this->preProcessPledge();
298 $this->showRecordLinkMesssage($this->_id
);
300 $this->_values
= array();
302 // Current contribution id.
304 $this->assignPremiumProduct($this->_id
);
305 $this->buildValuesAndAssignOnline_Note_Type($this->_id
, $this->_values
);
308 // when custom data is included in this page
309 if (!empty($_POST['hidden_custom'])) {
310 $this->applyCustomData('Contribution', CRM_Utils_Array
::value('financial_type_id', $_POST), $this->_id
);
313 $this->_lineItems
= array();
315 if (!empty($this->_compId
) && $this->_compContext
== 'participant') {
316 $this->assign('compId', $this->_compId
);
317 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_compId
);
320 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution', 1, TRUE, TRUE);
322 empty($lineItem) ?
NULL : $this->_lineItems
[] = $lineItem;
325 $this->assign('lineItem', empty($this->_lineItems
) ?
FALSE : $this->_lineItems
);
329 $this->setPageTitle($this->_ppID ?
ts('Credit Card Pledge Payment') : ts('Credit Card Contribution'));
332 $this->setPageTitle($this->_ppID ?
ts('Pledge Payment') : ts('Contribution'));
336 CRM_Contribute_Form_SoftCredit
::preprocess($this);
341 * Set default values.
345 public function setDefaultValues() {
346 if ($this->_cdType
) {
347 // @todo document when this function would be called in this way
348 // (and whether it is valid or an overloading of this form).
349 return CRM_Custom_Form_CustomData
::setDefaultValues($this);
352 $defaults = $this->_values
;
354 // Set defaults for pledge payment.
356 $defaults['total_amount'] = CRM_Utils_Array
::value('scheduled_amount', $this->_pledgeValues
['pledgePayment']);
357 $defaults['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $this->_pledgeValues
);
358 $defaults['currency'] = CRM_Utils_Array
::value('currency', $this->_pledgeValues
);
359 $defaults['option_type'] = 1;
362 if ($this->_action
& CRM_Core_Action
::DELETE
) {
366 $defaults['frequency_interval'] = 1;
367 $defaults['frequency_unit'] = 'month';
369 // Set soft credit defaults.
370 CRM_Contribute_Form_SoftCredit
::setDefaultValues($defaults, $this);
373 $config = CRM_Core_Config
::singleton();
374 // Set default country from config if no country set.
375 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
376 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry
;
379 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
380 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince
;
383 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID
);
384 $defaults = array_merge($defaults, $billingDefaults);
388 $this->_contactID
= $defaults['contact_id'];
391 // Set $newCredit variable in template to control whether link to credit card mode is included.
392 $this->assign('newCredit', CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments());
394 // Fix the display of the monetary value, CRM-4038.
395 if (isset($defaults['total_amount'])) {
396 if (!empty($defaults['tax_amount'])) {
397 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
398 if (!(CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails))) {
399 $defaults['total_amount'] = CRM_Utils_Money
::format($defaults['total_amount'] - $defaults['tax_amount'], NULL, '%a');
403 $defaults['total_amount'] = CRM_Utils_Money
::format($defaults['total_amount'], NULL, '%a');
407 if (isset($defaults['non_deductible_amount'])) {
408 $defaults['non_deductible_amount'] = CRM_Utils_Money
::format($defaults['non_deductible_amount'], NULL, '%a');
411 if (isset($defaults['fee_amount'])) {
412 $defaults['fee_amount'] = CRM_Utils_Money
::format($defaults['fee_amount'], NULL, '%a');
415 if (isset($defaults['net_amount'])) {
416 $defaults['net_amount'] = CRM_Utils_Money
::format($defaults['net_amount'], NULL, '%a');
419 if ($this->_contributionType
) {
420 $defaults['financial_type_id'] = $this->_contributionType
;
423 if (empty($defaults['payment_instrument_id'])) {
424 $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup
::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
427 if (!empty($defaults['is_test'])) {
428 $this->assign('is_test', TRUE);
431 $this->assign('showOption', TRUE);
432 // For Premium section.
433 if ($this->_premiumID
) {
434 $this->assign('showOption', FALSE);
435 $options = isset($this->_options
[$this->_productDAO
->product_id
]) ?
$this->_options
[$this->_productDAO
->product_id
] : "";
437 $this->assign('showOption', TRUE);
439 $options_key = CRM_Utils_Array
::key($this->_productDAO
->product_option
, $options);
441 $defaults['product_name'] = array($this->_productDAO
->product_id
, trim($options_key));
444 $defaults['product_name'] = array($this->_productDAO
->product_id
);
446 if ($this->_productDAO
->fulfilled_date
) {
447 list($defaults['fulfilled_date']) = CRM_Utils_Date
::setDateDefaults($this->_productDAO
->fulfilled_date
);
451 if (isset($this->userEmail
)) {
452 $this->assign('email', $this->userEmail
);
455 if (!empty($defaults['is_pay_later'])) {
456 $this->assign('is_pay_later', TRUE);
458 $this->assign('contribution_status_id', CRM_Utils_Array
::value('contribution_status_id', $defaults));
466 foreach ($dates as $key) {
467 if (!empty($defaults[$key])) {
468 list($defaults[$key], $defaults[$key . '_time'])
469 = CRM_Utils_Date
::setDateDefaults(CRM_Utils_Array
::value($key, $defaults), 'activityDateTime');
473 if (!$this->_id
&& empty($defaults['receive_date'])) {
474 list($defaults['receive_date'],
475 $defaults['receive_date_time']
476 ) = CRM_Utils_Date
::setDateDefaults(NULL, 'activityDateTime');
479 $this->assign('receive_date', CRM_Utils_Date
::processDate(CRM_Utils_Array
::value('receive_date', $defaults),
480 CRM_Utils_Array
::value('receive_date_time', $defaults)
482 $currency = CRM_Utils_Array
::value('currency', $defaults);
483 $this->assign('currency', $currency);
484 // Hack to get currency info to the js layer. CRM-11440.
485 CRM_Utils_Money
::format(1);
486 $this->assign('currencySymbol', CRM_Utils_Array
::value($currency, CRM_Utils_Money
::$_currencySymbols));
487 $this->assign('totalAmount', CRM_Utils_Array
::value('total_amount', $defaults));
489 // Inherit campaign from pledge.
490 if ($this->_ppID
&& !empty($this->_pledgeValues
['campaign_id'])) {
491 $defaults['campaign_id'] = $this->_pledgeValues
['campaign_id'];
494 $this->_defaults
= $defaults;
499 * Build the form object.
501 public function buildQuickForm() {
503 //@todo document the purpose of cdType (if still in use)
504 if ($this->_cdType
) {
505 CRM_Custom_Form_CustomData
::buildQuickForm($this);
510 //tax rate from financialType
511 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant
::getTaxRates()));
512 $this->assign('currencies', json_encode(CRM_Core_OptionGroup
::values('currencies_enabled')));
514 // build price set form.
515 $buildPriceSet = FALSE;
516 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
517 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
518 $this->assign('invoicing', $invoicing);
520 // display tax amount on edit contribution page
521 if ($invoicing && $this->_action
& CRM_Core_Action
::UPDATE
&& isset($this->_values
['tax_amount'])) {
522 $this->assign('totalTaxAmount', $this->_values
['tax_amount']);
525 if (empty($this->_lineItems
) &&
526 ($this->_priceSetId ||
!empty($_POST['price_set_id']))
528 $buildPriceSet = TRUE;
529 $getOnlyPriceSetElements = TRUE;
530 if (!$this->_priceSetId
) {
531 $this->_priceSetId
= $_POST['price_set_id'];
532 $getOnlyPriceSetElements = FALSE;
535 $this->set('priceSetId', $this->_priceSetId
);
536 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
538 // get only price set form elements.
539 if ($getOnlyPriceSetElements) {
543 // use to build form during form rule.
544 $this->assign('buildPriceSet', $buildPriceSet);
546 $defaults = $this->_values
;
547 $additionalDetailFields = array(
551 'non_deductible_amount',
555 foreach ($additionalDetailFields as $key) {
556 if (!empty($defaults[$key])) {
557 $defaults['hidden_AdditionalDetail'] = 1;
562 if ($this->_productDAO
) {
563 if ($this->_productDAO
->product_id
) {
564 $defaults['hidden_Premium'] = 1;
568 if ($this->_noteID
&&
569 isset($this->_values
['note'])
571 $defaults['hidden_AdditionalDetail'] = 1;
575 ts('Additional Details') => 'AdditionalDetail',
578 //Add Premium pane only if Premium is exists.
579 $dao = new CRM_Contribute_DAO_Product();
582 if ($dao->find(TRUE)) {
583 $paneNames[ts('Premium Information')] = 'Premium';
586 $billingPanes = array();
588 if (CRM_Core_Payment_Form
::buildPaymentForm($this, $this->_paymentProcessor
, FALSE) == TRUE) {
589 foreach ($this->billingPane
as $name => $label) {
590 if (!empty($this->billingFieldSets
[$name]['fields'])) {
591 // @todo reduce variation so we don't have to convert 'credit_card' to 'CreditCard'
592 $billingPanes[$label] = $this->generatePane(CRM_Utils_String
::convertStringToCamel($name), $defaults);
595 if (!empty($this->_recurPaymentProcessors
)) {
596 CRM_Contribute_Form_Contribution_Main
::buildRecur($this);
597 $this->setDefaults(array('is_recur' => 0));
598 $this->assign('buildRecurBlock', TRUE);
599 $recurJs = array('onChange' => "buildRecurBlock( this.value ); return false;");
604 foreach ($paneNames as $name => $type) {
605 $allPanes[$name] = $this->generatePane($type, $defaults);
608 $qfKey = $this->controller
->_key
;
609 $this->assign('qfKey', $qfKey);
610 $this->assign('billingPanes', $billingPanes);
611 $this->assign('allPanes', $allPanes);
613 $this->addFormRule(array('CRM_Contribute_Form_Contribution', 'formRule'), $this);
615 if ($this->_formType
) {
616 $this->assign('formType', $this->_formType
);
620 $this->applyFilter('__ALL__', 'trim');
622 if ($this->_action
& CRM_Core_Action
::DELETE
) {
623 $this->addButtons(array(
626 'name' => ts('Delete'),
627 'spacing' => ' ',
632 'name' => ts('Cancel'),
639 //need to assign custom data type and subtype to the template
640 $this->assign('customDataType', 'Contribution');
641 $this->assign('customDataSubType', $this->_contributionType
);
642 $this->assign('entityID', $this->_id
);
644 if ($this->_context
== 'standalone') {
645 $this->addEntityRef('contact_id', ts('Contact'), array(
647 'api' => array('extra' => array('email')),
651 $attributes = CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Contribution');
653 $financialType = $this->add('select', 'financial_type_id',
654 ts('Financial Type'),
655 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::financialType(),
657 array('onChange' => "CRM.buildCustomData( 'Contribution', this.value );")
659 $paymentInstrument = FALSE;
661 $paymentInstrument = $this->add('select', 'payment_instrument_id',
663 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::paymentInstrument(),
664 TRUE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
668 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), array('class' => 'twelve') +
$attributes['trxn_id']);
670 //add receipt for offline contribution
671 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
673 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
675 $status = CRM_Contribute_PseudoConstant
::contributionStatus();
677 // suppressing contribution statuses that are NOT relevant to pledges (CRM-5169)
678 $statusName = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
685 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
688 elseif ((!$this->_ppID
&& $this->_id
) ||
!$this->_id
) {
689 $suppressFlag = FALSE;
691 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
692 if (CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails)) {
693 $suppressFlag = TRUE;
696 if (!$suppressFlag) {
701 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
705 unset($status[CRM_Utils_Array
::key('Overdue', $statusName)]);
710 $contributionStatus = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_id
, 'contribution_status_id');
711 $name = CRM_Utils_Array
::value($contributionStatus, $statusName);
716 unset($status[CRM_Utils_Array
::key('In Progress', $statusName)]);
717 unset($status[CRM_Utils_Array
::key('Pending', $statusName)]);
718 unset($status[CRM_Utils_Array
::key('Failed', $statusName)]);
723 unset($status[CRM_Utils_Array
::key('Refunded', $statusName)]);
734 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
740 unset($status[CRM_Utils_Array
::key('Refunded', $statusName)]);
743 $this->add('select', 'contribution_status_id',
744 ts('Contribution Status'),
750 $this->addDateTime('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
752 if ($this->_online
) {
753 $this->assign('hideCalender', TRUE);
755 $checkNumber = $this->add('text', 'check_number', ts('Check Number'), $attributes['check_number']);
757 $this->addDateTime('receipt_date', ts('Receipt Date'), FALSE, array('formatType' => 'activityDateTime'));
758 $this->addDateTime('cancel_date', ts('Cancelled / Refunded Date'), FALSE, array('formatType' => 'activityDateTime'));
760 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
762 $element = $this->add('select',
763 'payment_processor_id',
764 ts('Payment Processor'),
770 if ($this->_online
) {
774 if (empty($this->_lineItems
)) {
775 $buildPriceSet = FALSE;
776 $priceSets = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute');
777 if (!empty($priceSets) && !$this->_ppID
) {
778 $buildPriceSet = TRUE;
781 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
782 // and if we already have line items for that participant. CRM-5095
783 if ($buildPriceSet && $this->_id
) {
784 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
785 $pledgePaymentId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
790 if ($pledgePaymentId) {
791 $buildPriceSet = FALSE;
793 if ($participantID = CRM_Utils_Array
::value('participant', $componentDetails)) {
794 $participantLI = CRM_Price_BAO_LineItem
::getLineItems($participantID);
795 if (!CRM_Utils_System
::isNull($participantLI)) {
796 $buildPriceSet = FALSE;
801 $hasPriceSets = FALSE;
802 if ($buildPriceSet) {
803 $hasPriceSets = TRUE;
804 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
806 '' => ts('Choose price set'),
808 NULL, array('onchange' => "buildAmount( this.value );")
810 if ($this->_online
&& !($this->_action
& CRM_Core_Action
::UPDATE
)) {
814 $this->assign('hasPriceSets', $hasPriceSets);
815 $currencyFreeze = FALSE;
816 if (!($this->_action
& CRM_Core_Action
::UPDATE
)) {
817 if ($this->_online ||
$this->_ppID
) {
818 $attributes['total_amount'] = array_merge($attributes['total_amount'], array(
820 'style' => "background-color:#EBECE4",
822 $optionTypes = array(
823 '1' => ts('Adjust Pledge Payment Schedule?'),
824 '2' => ts('Adjust Total Pledge Amount?'),
826 $this->addRadio('option_type',
832 $currencyFreeze = TRUE;
836 $totalAmount = $this->addMoney('total_amount',
838 ($hasPriceSets) ?
FALSE : TRUE,
839 $attributes['total_amount'],
840 TRUE, 'currency', NULL, $currencyFreeze
844 $this->add('text', 'source', ts('Source'), CRM_Utils_Array
::value('source', $attributes));
846 // CRM-7362 --add campaigns.
847 CRM_Campaign_BAO_Campaign
::addCampaign($this, CRM_Utils_Array
::value('campaign_id', $this->_values
));
849 CRM_Contribute_Form_SoftCredit
::buildQuickForm($this);
853 $js = array('onclick' => "return verify( );");
856 $mailingInfo = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
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) {
925 // Check for Credit Card Contribution.
927 if (empty($fields['payment_processor_id'])) {
928 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
931 // validate payment instrument (e.g. credit card number)
932 CRM_Core_Payment_Form
::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, $self);
936 // Do the amount validations.
937 if (empty($fields['total_amount']) && empty($self->_lineItems
)) {
938 if ($priceSetId = CRM_Utils_Array
::value('price_set_id', $fields)) {
939 CRM_Price_BAO_PriceField
::priceSetValidation($priceSetId, $fields, $errors);
943 $softErrors = CRM_Contribute_Form_SoftCredit
::formRule($fields, $errors, $self);
945 if (!empty($fields['total_amount']) && (!empty($fields['net_amount']) ||
!empty($fields['fee_amount']))) {
946 $sum = CRM_Utils_Rule
::cleanMoney($fields['net_amount']) + CRM_Utils_Rule
::cleanMoney($fields['fee_amount']);
947 if (CRM_Utils_Rule
::cleanMoney($fields['total_amount']) != $sum) {
948 $errors['total_amount'] = ts('The sum of fee amount and net amount must be equal to total amount');
951 // Form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
952 if ($self->_id
&& $self->_values
['contribution_status_id'] != $fields['contribution_status_id']) {
953 CRM_Contribute_BAO_Contribution
::checkStatusValidation($self->_values
, $fields, $errors);
955 // CRM-16015, add form-rule to restrict change of financial type if using price field of different financial type
956 if ($self->_id
&& $self->_values
['financial_type_id'] != $fields['financial_type_id']) {
957 CRM_Contribute_BAO_Contribution
::checkFinancialTypeChange(NULL, $self->_id
, $errors);
959 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
960 if (!empty($fields['fee_amount']) && !empty($fields['financial_type_id']) && $financialType = CRM_Contribute_BAO_Contribution
::validateFinancialType($fields['financial_type_id'])) {
961 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
964 // $trxn_id must be unique CRM-13919
965 if (!empty($fields['trxn_id'])) {
966 $queryParams = array(1 => array($fields['trxn_id'], 'String'));
967 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
969 $queryParams[2] = array((int) $self->_id
, 'Integer');
970 $query .= ' and id !=%2';
972 $tCnt = CRM_Core_DAO
::singleValueQuery($query, $queryParams);
974 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', array(1 => $fields['trxn_id']));
978 $errors = array_merge($errors, $softErrors);
983 * Process the form submission.
985 public function postProcess() {
986 if ($this->_action
& CRM_Core_Action
::DELETE
) {
987 CRM_Contribute_BAO_Contribution
::deleteContribution($this->_id
);
988 CRM_Core_Session
::singleton()->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
989 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
994 // Get the submitted form values.
995 $submittedValues = $this->controller
->exportValues($this->_name
);
996 $contribution = $this->submit($submittedValues, $this->_action
, $this->_ppID
);
997 $session = CRM_Core_Session
::singleton();
998 $buttonName = $this->controller
->getButtonName();
999 if ($this->_context
== 'standalone') {
1000 if ($buttonName == $this->getButtonName('upload', 'new')) {
1001 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contribute/add',
1002 'reset=1&action=add&context=standalone'
1006 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
1007 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1011 elseif ($this->_context
== 'contribution' && $this->_mode
&& $buttonName == $this->getButtonName('upload', 'new')) {
1012 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
1013 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
1016 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1017 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
1018 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
1022 //store contribution ID if not yet set (on create)
1023 if (empty($this->_id
) && !empty($contribution->id
)) {
1024 $this->_id
= $contribution->id
;
1029 * Process credit card payment.
1031 * @param array $submittedValues
1032 * @param array $lineItem
1034 * @return bool|\CRM_Contribute_DAO_Contribution
1036 protected function processCreditCard($submittedValues, $lineItem) {
1037 $sendReceipt = $contribution = FALSE;
1039 $unsetParams = array(
1041 'payment_instrument_id',
1042 'contribution_status_id',
1046 foreach ($unsetParams as $key) {
1047 if (isset($submittedValues[$key])) {
1048 unset($submittedValues[$key]);
1051 $isTest = ($this->_mode
== 'test') ?
1 : 0;
1052 // CRM-12680 set $_lineItem if its not set
1053 if (empty($this->_lineItem
) && !empty($lineItem)) {
1054 $this->_lineItem
= $lineItem;
1057 //Get the require fields value only.
1058 $params = $this->_params
= $submittedValues;
1060 $this->_paymentProcessor
= CRM_Financial_BAO_PaymentProcessor
::getPayment($params['payment_processor_id'],
1064 // Get the payment processor id as per mode.
1065 $this->_params
['payment_processor'] = $params['payment_processor_id']
1066 = $this->_params
['payment_processor_id'] = $submittedValues['payment_processor_id'] = $this->_paymentProcessor
['id'];
1068 $now = date('YmdHis');
1071 // we need to retrieve email address
1072 if ($this->_context
== 'standalone' && !empty($submittedValues['is_email_receipt'])) {
1073 list($this->userDisplayName
,
1075 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
1076 $this->assign('displayName', $this->userDisplayName
);
1079 // Set email for primary location.
1080 $fields['email-Primary'] = 1;
1081 $params['email-Primary'] = $this->userEmail
;
1083 // now set the values for the billing location.
1084 foreach (array_keys($this->_fields
) as $name) {
1088 // also add location name to the array
1089 $params["address_name-{$this->_bltID}"] = CRM_Utils_Array
::value('billing_first_name', $params) . ' ' . CRM_Utils_Array
::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array
::value('billing_last_name', $params);
1091 $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
1092 $fields["address_name-{$this->_bltID}"] = 1;
1093 $ctype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
1098 $nameFields = array('first_name', 'middle_name', 'last_name');
1099 foreach ($nameFields as $name) {
1101 if (array_key_exists("billing_$name", $params)) {
1102 $params[$name] = $params["billing_{$name}"];
1103 $params['preserveDBName'] = TRUE;
1107 if (!empty($params['source'])) {
1108 unset($params['source']);
1110 $contactID = CRM_Contact_BAO_Contact
::createProfileContact($params, $fields,
1116 // add all the additional payment params we need
1117 if (!empty($this->_params
["billing_state_province_id-{$this->_bltID}"])) {
1118 $this->_params
["state_province-{$this->_bltID}"] = $this->_params
["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($this->_params
["billing_state_province_id-{$this->_bltID}"]);
1120 if (!empty($this->_params
["billing_country_id-{$this->_bltID}"])) {
1121 $this->_params
["country-{$this->_bltID}"] = $this->_params
["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant
::countryIsoCode($this->_params
["billing_country_id-{$this->_bltID}"]);
1123 $legacyCreditCardExpiryCheck = FALSE;
1124 if ($this->_paymentProcessor
['payment_type'] & CRM_Core_Payment
::PAYMENT_TYPE_CREDIT_CARD
&& !isset($this->_paymentFields
)) {
1125 $legacyCreditCardExpiryCheck = TRUE;
1127 if ($legacyCreditCardExpiryCheck ||
in_array('credit_card_exp_date', array_keys($this->_paymentFields
))) {
1128 $this->_params
['year'] = CRM_Core_Payment_Form
::getCreditCardExpirationYear($this->_params
);
1129 $this->_params
['month'] = CRM_Core_Payment_Form
::getCreditCardExpirationMonth($this->_params
);
1131 $this->_params
['ip_address'] = CRM_Utils_System
::ipAddress();
1132 $this->_params
['amount'] = $this->_params
['total_amount'];
1133 $this->_params
['amount_level'] = 0;
1134 $this->_params
['description'] = ts('Office Credit Card contribution');
1135 $this->_params
['currencyID'] = CRM_Utils_Array
::value('currency',
1137 CRM_Core_Config
::singleton()->defaultCurrency
1139 $this->_params
['payment_action'] = 'Sale';
1140 if (!empty($this->_params
['receive_date'])) {
1141 $this->_params
['receive_date'] = CRM_Utils_Date
::processDate($this->_params
['receive_date'], $this->_params
['receive_date_time']);
1144 if (!empty($params['soft_credit_to'])) {
1145 $this->_params
['soft_credit_to'] = $params['soft_credit_to'];
1146 $this->_params
['pcp_made_through_id'] = $params['pcp_made_through_id'];
1149 $this->_params
['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $params);
1150 $this->_params
['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $params);
1151 $this->_params
['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $params);
1153 //Add common data to formatted params
1154 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
1156 if (empty($this->_params
['invoice_id'])) {
1157 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
1160 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
1163 // At this point we've created a contact and stored its address etc
1164 // all the payment processors expect the name and address to be in the
1165 // so we copy stuff over to first_name etc.
1166 $paymentParams = $this->_params
;
1167 $paymentParams['contactID'] = $this->_contactID
;
1168 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
1170 $financialType = new CRM_Financial_DAO_FinancialType();
1171 $financialType->id
= $params['financial_type_id'];
1173 // Add some financial type details to the params list
1174 // if folks need to use it.
1175 $paymentParams['contributionType_name'] = $this->_params
['contributionType_name'] = $financialType->name
;
1176 $paymentParams['contributionPageID'] = NULL;
1178 if (!empty($this->_params
['is_email_receipt'])) {
1179 $paymentParams['email'] = $this->userEmail
;
1180 $paymentParams['is_email_receipt'] = 1;
1183 $paymentParams['is_email_receipt'] = 0;
1184 $this->_params
['is_email_receipt'] = 0;
1186 if (!empty($this->_params
['receive_date'])) {
1187 $paymentParams['receive_date'] = $this->_params
['receive_date'];
1190 // For recurring contribution, create Contribution Record first.
1191 // Contribution ID, Recurring ID and Contact ID needed
1192 // When we get a callback from the payment processor, CRM-7115
1194 if (!empty($paymentParams['is_recur'])) {
1195 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processContribution($this,
1205 $paymentParams['contributionID'] = $contribution->id
;
1206 $paymentParams['contributionTypeID'] = $contribution->financial_type_id
;
1207 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
1208 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1211 if ($paymentParams['amount'] > 0.0) {
1212 // force a re-get of the payment processor in case the form changed it, CRM-7179
1213 $payment = CRM_Core_Payment
::singleton($this->_mode
, $this->_paymentProcessor
, $this, TRUE);
1215 $result = $payment->doPayment($paymentParams, 'contribute');
1217 catch (CRM_Core_Exception
$e) {
1218 $message = ts("Payment Processor Error message") . $e->getMessage();
1219 $this->cleanupDBAfterPaymentFailure($paymentParams, $message);
1220 // Set the contribution mode.
1221 $urlParams = "action=add&cid={$this->_contactID}";
1223 $urlParams .= "&mode={$this->_mode}";
1225 if (!empty($this->_ppID
)) {
1226 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
1228 CRM_Core_Error
::statusBounce($message, $urlParams, ts('Payment Processor Error'));
1232 $this->_params
= array_merge($this->_params
, $result);
1234 $this->_params
['receive_date'] = $now;
1236 if (!empty($this->_params
['is_email_receipt'])) {
1237 $this->_params
['receipt_date'] = $now;
1240 $this->_params
['receipt_date'] = CRM_Utils_Date
::processDate($this->_params
['receipt_date'],
1241 $params['receipt_date_time'], TRUE
1245 $this->set('params', $this->_params
);
1246 $this->assign('trxn_id', $result['trxn_id']);
1247 $this->assign('receive_date', $this->_params
['receive_date']);
1249 // Result has all the stuff we need
1250 // lets archive it to a financial transaction
1251 if ($financialType->is_deductible
) {
1252 $this->assign('is_deductible', TRUE);
1253 $this->set('is_deductible', TRUE);
1256 // Set source if not set
1257 if (empty($this->_params
['source'])) {
1258 $userID = CRM_Core_Session
::singleton()->get('userID');
1259 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1262 $this->_params
['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
1265 // Build custom data getFields array
1266 $customFieldsContributionType = CRM_Core_BAO_CustomField
::getFields('Contribution', FALSE, FALSE,
1267 CRM_Utils_Array
::value('financial_type_id', $params)
1269 $customFields = CRM_Utils_Array
::crmArrayMerge($customFieldsContributionType,
1270 CRM_Core_BAO_CustomField
::getFields('Contribution', FALSE, FALSE, NULL, NULL, TRUE)
1272 $params['custom'] = CRM_Core_BAO_CustomField
::postProcess($params,
1277 if (empty($paymentParams['is_recur'])) {
1278 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processContribution($this,
1289 // Send receipt mail.
1290 if ($contribution->id
&& !empty($this->_params
['is_email_receipt'])) {
1291 $this->_params
['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $result);
1292 $this->_params
['contact_id'] = $this->_contactID
;
1293 $this->_params
['contribution_id'] = $contribution->id
;
1294 $sendReceipt = CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $this->_params
, TRUE);
1297 if ($contribution->id
) {
1298 array_unshift($this->statusMessage
, ts('The contribution record has been processed.'));
1299 if (!empty($this->_params
['is_email_receipt']) && $sendReceipt) {
1300 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1302 $this->statusMessageTitle
= ts('Complete');
1304 return $contribution;
1308 * Clean up DB after payment fails.
1310 * This function removes related DB entries. Note that it has been agreed in principle,
1311 * but not implemented, that contributions should be retained as 'Failed' rather than
1314 * @todo it doesn't clean up line items.
1316 * @param array $paymentParams
1317 * @param string $message
1319 public function cleanupDBAfterPaymentFailure($paymentParams, $message) {
1320 // Make sure to cleanup db for recurring case.
1321 if (!empty($paymentParams['contributionID'])) {
1322 CRM_Core_Error
::debug_log_message($message .
1323 "contact id={$this->_contactID} (deleting contribution {$paymentParams['contributionID']}");
1324 CRM_Contribute_BAO_Contribution
::deleteContribution($paymentParams['contributionID']);
1326 if (!empty($paymentParams['contributionRecurID'])) {
1327 CRM_Core_Error
::debug_log_message($message .
1328 "contact id={$this->_contactID} (deleting recurring contribution {$paymentParams['contributionRecurID']}");
1329 CRM_Contribute_BAO_ContributionRecur
::deleteRecurContribution($paymentParams['contributionRecurID']);
1334 * Generate the data to construct a snippet based pane.
1336 * This form also assigns the showAdditionalInfo var based on historical code.
1337 * This appears to mean 'there is a pane to show'.
1339 * @param string $type
1340 * Type of Pane - this is generally used to determine the function name used to build it
1341 * - e.g CreditCard, AdditionalDetail
1342 * @param array $defaults
1345 * We aim to further refactor & simplify this but currently
1347 * - should additional info be shown?
1349 protected function generatePane($type, $defaults) {
1350 $urlParams = "snippet=4&formType={$type}";
1352 $urlParams .= "&mode={$this->_mode}";
1356 if ($type == 'CreditCard' ||
1357 $type == 'DirectDebit'
1363 'url' => CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams),
1368 // See if we need to include this paneName in the current form.
1369 if ($this->_formType
== $type ||
!empty($_POST["hidden_{$type}"]) ||
1370 CRM_Utils_Array
::value("hidden_{$type}", $defaults)
1372 $this->assign('showAdditionalInfo', TRUE);
1373 $pane['open'] = 'true';
1376 if ($type == 'CreditCard' ||
$type == 'DirectDebit') {
1377 // @todo would be good to align tpl name with form name...
1378 // @todo document why this hidden variable is required.
1379 $this->add('hidden', 'hidden_' . $type, 1);
1383 $additionalInfoFormFunction = 'build' . $type;
1384 CRM_Contribute_Form_AdditionalInfo
::$additionalInfoFormFunction($this);
1390 * Wrapper for unit testing the post process submit function.
1392 * (If we expose through api we can get default additions 'for free').
1394 * @param array $params
1395 * @param int $action
1396 * @param string|null $creditCardMode
1398 * @throws \CiviCRM_API3_Exception
1400 public function testSubmit($params, $action, $creditCardMode = NULL) {
1402 'soft_credit_contact_id' => array(),
1403 'receipt_date' => '',
1404 'receipt_date_time' => '',
1405 'cancel_date' => '',
1406 'cancel_date_time' => '',
1407 'hidden_Premium' => 1,
1409 if (!empty($params['id'])) {
1410 $existingContribution = civicrm_api3('contribution', 'getsingle', array(
1411 'id' => $params['id'],
1415 $existingContribution = array();
1418 $this->_defaults
['contribution_status_id'] = CRM_Utils_Array
::value('contribution_status_id',
1419 $existingContribution
1422 $this->_defaults
['total_amount'] = CRM_Utils_Array
::value('total_amount',
1423 $existingContribution
1426 if ($creditCardMode) {
1427 $this->_mode
= $creditCardMode;
1430 // Required because processCreditCard calls set method on this.
1431 $_SERVER['REQUEST_METHOD'] = 'GET';
1432 $this->controller
= new CRM_Core_Controller();
1434 CRM_Contribute_Form_AdditionalInfo
::buildPremium($this);
1436 $this->_fields
= array();
1437 $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array
::value('pledge_payment_id', $params));
1442 * @param array $submittedValues
1444 * @param int $action
1446 * - CRM_Core_Action::UPDATE
1448 * @param $pledgePaymentID
1451 * @throws \Exception
1453 protected function submit($submittedValues, $action, $pledgePaymentID) {
1454 $softParams = $softIDs = array();
1455 $pId = $contribution = $isRelatedId = FALSE;
1457 if (!empty($submittedValues['price_set_id']) && $action & CRM_Core_Action
::UPDATE
) {
1458 $line = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution');
1459 $lineID = key($line);
1460 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array
::value('price_field_id', $line[$lineID]), 'price_set_id');
1461 $quickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1463 CRM_Price_BAO_LineItem
::deleteLineItems($this->_id
, 'civicrm_contribution');
1467 // Process price set and get total amount and line items.
1468 $lineItem = array();
1469 $priceSetId = CRM_Utils_Array
::value('price_set_id', $submittedValues);
1470 if (empty($priceSetId) && !$this->_id
) {
1471 $this->_priceSetId
= $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1472 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
1473 $fieldID = key($this->_priceSet
['fields']);
1474 $fieldValueId = key($this->_priceSet
['fields'][$fieldID]['options']);
1475 $this->_priceSet
['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1476 $submittedValues['price_' . $fieldID] = 1;
1480 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
1481 $submittedValues, $lineItem[$priceSetId]);
1483 // Unset tax amount for offline 'is_quick_config' contribution.
1484 if ($this->_priceSet
['is_quick_config'] &&
1485 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant
::getTaxRates())
1487 unset($submittedValues['tax_amount']);
1489 $submittedValues['total_amount'] = CRM_Utils_Array
::value('amount', $submittedValues);
1492 if ($this->_compId
) {
1493 if ($this->_context
== 'participant') {
1494 $pId = $this->_compId
;
1496 elseif ($this->_context
== 'membership') {
1497 $isRelatedId = TRUE;
1500 $pId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id
, 'participant_id', 'contribution_id');
1504 $contributionDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1505 if (array_key_exists('membership', $contributionDetails)) {
1506 $isRelatedId = TRUE;
1508 elseif (array_key_exists('participant', $contributionDetails)) {
1509 $pId = $contributionDetails['participant'];
1513 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id
) {
1514 // CRM-10117 update the line items for participants.
1516 $entityTable = 'participant';
1518 $isRelatedId = FALSE;
1519 $participantParams = array(
1520 'fee_amount' => $submittedValues['total_amount'],
1523 CRM_Event_BAO_Participant
::add($participantParams);
1524 if (empty($this->_lineItems
)) {
1525 $this->_lineItems
[] = CRM_Price_BAO_LineItem
::getLineItems($entityID, 'participant', 1);
1529 $entityTable = 'contribution';
1530 $entityID = $this->_id
;
1533 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, $entityTable, NULL, TRUE, $isRelatedId);
1534 foreach (array_keys($lineItems) as $id) {
1535 $lineItems[$id]['id'] = $id;
1537 $itemId = key($lineItems);
1538 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1539 $this->_priceSetId
= CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1542 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1543 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule
::cleanMoney(CRM_Utils_Array
::value('total_amount', $submittedValues));
1545 // Update line total and total amount with tax on edit.
1546 $financialItemsId = CRM_Core_PseudoConstant
::getTaxRates();
1547 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1548 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1551 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1552 $submittedValues['tax_amount'] = 'null';
1554 if ($lineItems[$itemId]['tax_rate']) {
1555 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total'];
1556 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] +
$lineItems[$itemId]['tax_amount'];
1557 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1560 // CRM-10117 update the line items for participants.
1561 if (!empty($lineItems[$itemId]['price_field_id'])) {
1562 $lineItem[$this->_priceSetId
] = $lineItems;
1567 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1570 //CRM-11529 for quick config back office transactions
1571 //when financial_type_id is passed in form, update the
1572 //line items with the financial type selected in form
1573 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array
::value($this->_priceSetId
, $lineItem)
1575 foreach ($lineItem[$this->_priceSetId
] as &$values) {
1576 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1580 if (!isset($submittedValues['total_amount'])) {
1581 $submittedValues['total_amount'] = CRM_Utils_Array
::value('total_amount', $this->_values
);
1583 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
1585 if (!empty($submittedValues['pcp_made_through_id'])) {
1588 'pcp_made_through_id',
1589 'pcp_display_in_roll',
1590 'pcp_roll_nickname',
1591 'pcp_personal_note',
1593 foreach ($fields as $f) {
1594 $pcp[$f] = CRM_Utils_Array
::value($f, $submittedValues);
1598 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
1599 if ($this->_id
&& count($isEmpty) == 1 && key($isEmpty) == NULL) {
1600 //Delete existing soft credit records if soft credit list is empty on update
1601 CRM_Contribute_BAO_ContributionSoft
::del(array('contribution_id' => $this->_id
));
1604 //build soft credit params
1605 foreach ($submittedValues['soft_credit_contact_id'] as $key => $val) {
1606 if ($val && $submittedValues['soft_credit_amount'][$key]) {
1607 $softParams[$key]['contact_id'] = $val;
1608 $softParams[$key]['amount'] = CRM_Utils_Rule
::cleanMoney($submittedValues['soft_credit_amount'][$key]);
1609 $softParams[$key]['soft_credit_type_id'] = $submittedValues['soft_credit_type'][$key];
1610 if (!empty($submittedValues['soft_credit_id'][$key])) {
1611 $softIDs[] = $softParams[$key]['id'] = $submittedValues['soft_credit_id'][$key];
1617 // set the contact, when contact is selected
1618 if (!empty($submittedValues['contact_id'])) {
1619 $this->_contactID
= $submittedValues['contact_id'];
1621 $formValues = $submittedValues;
1623 // Credit Card Contribution.
1625 $contribution = $this->processCreditCard($submittedValues, $lineItem);
1628 // Offline Contribution.
1629 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1631 // get the required field value only.
1633 $params = $ids = array();
1635 $params['contact_id'] = $this->_contactID
;
1636 $params['currency'] = $this->getCurrency($submittedValues);
1639 'financial_type_id',
1640 'contribution_status_id',
1641 'payment_instrument_id',
1646 foreach ($fields as $f) {
1647 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1651 $params['pcp'] = $pcp;
1653 if (!empty($softParams)) {
1654 $params['soft_credit'] = $softParams;
1655 $params['soft_credit_ids'] = $softIDs;
1658 // CRM-5740 if priceset is used, no need to cleanup money.
1660 $params['skipCleanMoney'] = 1;
1669 foreach ($dates as $d) {
1670 $params[$d] = CRM_Utils_Date
::processDate($formValues[$d], $formValues[$d . '_time'], TRUE);
1673 if (!empty($formValues['is_email_receipt'])) {
1674 $params['receipt_date'] = date("Y-m-d");
1677 if ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Cancelled', 'name')
1678 ||
$params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name')
1680 if (CRM_Utils_System
::isNull(CRM_Utils_Array
::value('cancel_date', $params))) {
1681 $params['cancel_date'] = date('Y-m-d');
1685 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1688 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1689 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1690 if ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Pending', 'name')) {
1691 $params['is_pay_later'] = 1;
1693 elseif ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name')) {
1694 $params['is_pay_later'] = 0;
1697 $ids['contribution'] = $params['id'] = $this->_id
;
1699 // Add Additional common information to formatted params.
1700 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($formValues, $params, $this);
1702 $params['contribution_mode'] = 'participant';
1703 $params['participant_id'] = $pId;
1704 $params['skipLineItem'] = 1;
1706 elseif ($isRelatedId) {
1707 $params['contribution_mode'] = 'membership';
1709 $params['line_item'] = $lineItem;
1710 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array
::value('id', $this->_paymentProcessor
);
1711 if (isset($submittedValues['tax_amount'])) {
1712 $params['tax_amount'] = $submittedValues['tax_amount'];
1714 //create contribution.
1715 if ($isQuickConfig) {
1716 $params['is_quick_config'] = 1;
1718 $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
1720 $contribution = CRM_Contribute_BAO_Contribution
::create($params, $ids);
1722 // process associated membership / participant, CRM-4395
1723 if ($contribution->id
&& $action & CRM_Core_Action
::UPDATE
) {
1724 $this->statusMessage
[] = $this->updateRelatedComponent($contribution->id
,
1725 $contribution->contribution_status_id
,
1726 CRM_Utils_Array
::value('contribution_status_id',
1729 $contribution->receive_date
1733 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1735 $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
1737 //send receipt mail.
1738 if ($contribution->id
&& !empty($formValues['is_email_receipt'])) {
1739 $formValues['contact_id'] = $this->_contactID
;
1740 $formValues['contribution_id'] = $contribution->id
;
1742 $formValues +
= CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
);
1744 // to get 'from email id' for send receipt
1745 $this->fromEmailId
= $formValues['from_email_address'];
1746 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $formValues)) {
1747 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1751 $this->statusMessageTitle
= ts('Saved');
1755 if ($contribution->id
&& isset($formValues['product_name'][0])) {
1756 CRM_Contribute_Form_AdditionalInfo
::processPremium($submittedValues, $contribution->id
,
1757 $this->_premiumID
, $this->_options
1761 if ($contribution->id
&& isset($submittedValues['note'])) {
1762 CRM_Contribute_Form_AdditionalInfo
::processNote($submittedValues, $this->_contactID
, $contribution->id
, $this->_noteID
);
1765 CRM_Core_Session
::setStatus(implode(' ', $this->statusMessage
), $this->statusMessageTitle
, 'success');
1767 CRM_Contribute_BAO_Contribution
::updateRelatedPledge(
1771 (CRM_Utils_Array
::value('option_type', $formValues) == 2) ?
TRUE : FALSE,
1772 $formValues['total_amount'],
1773 CRM_Utils_Array
::value('total_amount', $this->_defaults
),
1774 $formValues['contribution_status_id'],
1775 CRM_Utils_Array
::value('contribution_status_id', $this->_defaults
)
1777 return $contribution;
1781 * Assign tax calculations to contribution receipts.
1783 * @param array $submittedValues
1784 * @param int $action
1785 * @param array $lineItem
1787 protected function invoicingPostProcessHook($submittedValues, $action, $lineItem) {
1789 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
1790 if (!CRM_Utils_Array
::value('invoicing', $invoiceSettings)) {
1794 $getTaxDetails = FALSE;
1795 if ($action & CRM_Core_Action
::ADD
) {
1798 elseif ($action & CRM_Core_Action
::UPDATE
) {
1799 $line = $this->_lineItems
;
1801 foreach ($line as $key => $value) {
1802 foreach ($value as $v) {
1803 if (isset($taxRate[(string) CRM_Utils_Array
::value('tax_rate', $v)])) {
1804 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $v);
1807 if (isset($v['tax_rate'])) {
1808 $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $v);
1809 $getTaxDetails = TRUE;
1815 if ($action & CRM_Core_Action
::UPDATE
) {
1816 if (isset($submittedValues['tax_amount'])) {
1817 $totalTaxAmount = $submittedValues['tax_amount'];
1820 $totalTaxAmount = $this->_values
['tax_amount'];
1822 $this->assign('totalTaxAmount', $totalTaxAmount);
1823 $this->assign('dataArray', $taxRate);
1826 if (!empty($submittedValues['price_set_id'])) {
1827 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1828 $this->assign('getTaxDetails', $getTaxDetails);
1829 $this->assign('dataArray', $taxRate);
1830 $this->assign('taxTerm', CRM_Utils_Array
::value('tax_term', $invoiceSettings));
1833 $this->assign('totalTaxAmount', CRM_Utils_Array
::value('tax_amount', $submittedValues));
1839 * Calculate non deductible amount.
1842 * if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1843 * if non_deductible_amount does NOT exist - then calculate it depending on:
1844 * $financialType->is_deductible and whether there is a product (premium).
1847 * @param $formValues
1851 protected function calculateNonDeductibleAmount($params, $formValues) {
1852 if (!empty($params['non_deductible_amount'])) {
1853 return $params['non_deductible_amount'];
1855 if (empty($params['non_deductible_amount'])) {
1856 $contributionType = new CRM_Financial_DAO_FinancialType();
1857 $contributionType->id
= $params['financial_type_id'];
1859 if ($contributionType->is_deductible
) {
1861 if (isset($formValues['product_name'][0])) {
1862 $selectProduct = $formValues['product_name'][0];
1864 // if there is a product - compare the value to the contribution amount
1865 if (isset($selectProduct)) {
1866 $productDAO = new CRM_Contribute_DAO_Product();
1867 $productDAO->id
= $selectProduct;
1868 $productDAO->find(TRUE);
1869 // product value exceeds contribution amount
1870 if ($params['total_amount'] < $productDAO->price
) {
1871 return $params['total_amount'];
1873 // product value does NOT exceed contribution amount
1875 return $productDAO->price
;
1878 // contribution is deductible - but there is no product
1883 // contribution is NOT deductible
1885 return $params['total_amount'];