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 +--------------------------------------------------------------------+
28 use Civi\Payment\Exception\PaymentProcessorException
;
31 * This class generates form components for processing a contribution.
33 class CRM_Contribute_Form_Contribution
extends CRM_Contribute_Form_AbstractEditPayment
{
35 * The id of the contribution that we are processing.
42 * The id of the premium that we are processing.
46 public $_premiumID = NULL;
49 * @var CRM_Contribute_DAO_ContributionProduct
51 public $_productDAO = NULL;
61 * The id of the contact associated with this contribution.
68 * The id of the pledge payment that we are processing.
75 * Is this contribution associated with an online.
76 * financial transaction
80 public $_online = FALSE;
83 * Stores all product options.
90 * Storage of parameters from form
97 * Store the contribution Type ID
101 public $_contributionType;
104 * The contribution values if an existing contribution
109 * The pledge values if this contribution is associated with pledge
111 public $_pledgeValues;
113 public $_contributeMode = 'direct';
118 * Parameter with confusing name.
122 public $_compContext;
127 * Possible From email addresses
139 * Store the line items if price set used.
145 * @todo explain why we use lineItem & lineItems
151 * @var array soft credit info
153 public $_softCreditInfo;
155 protected $_formType;
158 * @todo what on earth does cdType stand for????
162 public $_honoreeProfileType;
165 * Array of the payment fields to be displayed in the payment fieldset (pane) in billingBlock.tpl
166 * this contains all the information to describe these fields from quickform. See CRM_Core_Form_Payment getPaymentFormFieldsMetadata
170 public $_paymentFields = array();
172 * Logged in user's email.
184 * Price set as an array
191 * @todo can we define this a as protected? can we define higher up the chain
201 public $userDisplayName;
204 * Status message to be shown to the user.
208 protected $statusMessage = array();
211 * Status message title to be shown to the user.
213 * Generally the payment processor message title is 'Complete' and offline is 'Saved'
214 * although this might not be a good fit with the broad range of processors.
218 protected $statusMessageTitle;
221 * Set variables up before form is built.
223 public function preProcess() {
224 // Check permission for action.
225 if (!CRM_Core_Permission
::checkActionPermission('CiviContribute', $this->_action
)) {
226 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
228 // @todo - if anyone ever figures out what this _cdType subroutine is about
229 // (or even if it still applies) please add comments!!!!!!!!!!
230 $this->_cdType
= CRM_Utils_Array
::value('type', $_GET);
231 $this->assign('cdType', FALSE);
232 if ($this->_cdType
) {
233 $this->assign('cdType', TRUE);
234 CRM_Custom_Form_CustomData
::preProcess($this);
238 parent
::preProcess();
240 $this->_formType
= CRM_Utils_Array
::value('formType', $_GET);
243 $this->_priceSetId
= CRM_Utils_Array
::value('priceSetId', $_GET);
244 $this->set('priceSetId', $this->_priceSetId
);
245 $this->assign('priceSetId', $this->_priceSetId
);
247 // Get the pledge payment id
248 $this->_ppID
= CRM_Utils_Request
::retrieve('ppid', 'Positive', $this);
250 $this->assign('action', $this->_action
);
252 // Get the contribution id if update
253 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this);
254 if (!empty($this->_id
)) {
255 $this->assign('contribID', $this->_id
);
258 $this->_context
= CRM_Utils_Request
::retrieve('context', 'String', $this);
259 $this->assign('context', $this->_context
);
261 $this->_compId
= CRM_Utils_Request
::retrieve('compId', 'Positive', $this);
263 $this->_compContext
= CRM_Utils_Request
::retrieve('compContext', 'String', $this);
265 //set the contribution mode.
266 $this->_mode
= CRM_Utils_Request
::retrieve('mode', 'String', $this);
268 $this->assign('contributionMode', $this->_mode
);
269 if ($this->_action
& CRM_Core_Action
::DELETE
) {
273 $this->assign('showCheckNumber', TRUE);
275 $this->_fromEmails
= CRM_Core_BAO_Email
::getFromEmail();
276 $this->assignPaymentRelatedVariables();
278 if (in_array('CiviPledge', CRM_Core_Config
::singleton()->enableComponents
) && !$this->_formType
) {
279 $this->preProcessPledge();
283 $this->showRecordLinkMesssage($this->_id
);
285 $this->_values
= array();
287 // Current contribution id.
289 $this->assignPremiumProduct($this->_id
);
290 $this->buildValuesAndAssignOnline_Note_Type($this->_id
, $this->_values
);
293 // when custom data is included in this page
294 if (!empty($_POST['hidden_custom'])) {
295 $this->applyCustomData('Contribution', CRM_Utils_Array
::value('financial_type_id', $_POST), $this->_id
);
298 $this->_lineItems
= array();
300 if (!empty($this->_compId
) && $this->_compContext
== 'participant') {
301 $this->assign('compId', $this->_compId
);
302 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_compId
);
305 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution', 1, TRUE, TRUE);
307 empty($lineItem) ?
NULL : $this->_lineItems
[] = $lineItem;
310 $this->assign('lineItem', empty($this->_lineItems
) ?
FALSE : $this->_lineItems
);
314 CRM_Financial_Form_Payment
::addCreditCardJs();
315 $this->setPageTitle($this->_ppID ?
ts('Credit Card Pledge Payment') : ts('Credit Card Contribution'));
318 $this->setPageTitle($this->_ppID ?
ts('Pledge Payment') : ts('Contribution'));
322 CRM_Contribute_Form_SoftCredit
::preprocess($this);
327 * Set default values.
331 public function setDefaultValues() {
332 if ($this->_cdType
) {
333 // @todo document when this function would be called in this way
334 // (and whether it is valid or an overloading of this form).
335 return CRM_Custom_Form_CustomData
::setDefaultValues($this);
338 $defaults = $this->_values
;
340 // Set defaults for pledge payment.
342 $defaults['total_amount'] = CRM_Utils_Array
::value('scheduled_amount', $this->_pledgeValues
['pledgePayment']);
343 $defaults['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $this->_pledgeValues
);
344 $defaults['currency'] = CRM_Utils_Array
::value('currency', $this->_pledgeValues
);
345 $defaults['option_type'] = 1;
348 if ($this->_action
& CRM_Core_Action
::DELETE
) {
352 $defaults['frequency_interval'] = 1;
353 $defaults['frequency_unit'] = 'month';
355 // Set soft credit defaults.
356 CRM_Contribute_Form_SoftCredit
::setDefaultValues($defaults, $this);
359 $config = CRM_Core_Config
::singleton();
360 // Set default country from config if no country set.
361 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
362 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry
;
365 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
366 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince
;
369 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID
);
370 $defaults = array_merge($defaults, $billingDefaults);
374 $this->_contactID
= $defaults['contact_id'];
377 // Set $newCredit variable in template to control whether link to credit card mode is included.
378 $this->assign('newCredit', CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments());
380 // Fix the display of the monetary value, CRM-4038.
381 if (isset($defaults['total_amount'])) {
382 if (!empty($defaults['tax_amount'])) {
383 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
384 if (!(CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails))) {
385 $defaults['total_amount'] = CRM_Utils_Money
::format($defaults['total_amount'] - $defaults['tax_amount'], NULL, '%a');
389 $defaults['total_amount'] = CRM_Utils_Money
::format($defaults['total_amount'], NULL, '%a');
393 if (isset($defaults['non_deductible_amount'])) {
394 $defaults['non_deductible_amount'] = CRM_Utils_Money
::format($defaults['non_deductible_amount'], NULL, '%a');
397 if (isset($defaults['fee_amount'])) {
398 $defaults['fee_amount'] = CRM_Utils_Money
::format($defaults['fee_amount'], NULL, '%a');
401 if (isset($defaults['net_amount'])) {
402 $defaults['net_amount'] = CRM_Utils_Money
::format($defaults['net_amount'], NULL, '%a');
405 if ($this->_contributionType
) {
406 $defaults['financial_type_id'] = $this->_contributionType
;
409 if (empty($defaults['payment_instrument_id'])) {
410 $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup
::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
413 if (!empty($defaults['is_test'])) {
414 $this->assign('is_test', TRUE);
417 $this->assign('showOption', TRUE);
418 // For Premium section.
419 if ($this->_premiumID
) {
420 $this->assign('showOption', FALSE);
421 $options = isset($this->_options
[$this->_productDAO
->product_id
]) ?
$this->_options
[$this->_productDAO
->product_id
] : "";
423 $this->assign('showOption', TRUE);
425 $options_key = CRM_Utils_Array
::key($this->_productDAO
->product_option
, $options);
427 $defaults['product_name'] = array($this->_productDAO
->product_id
, trim($options_key));
430 $defaults['product_name'] = array($this->_productDAO
->product_id
);
432 if ($this->_productDAO
->fulfilled_date
) {
433 list($defaults['fulfilled_date']) = CRM_Utils_Date
::setDateDefaults($this->_productDAO
->fulfilled_date
);
437 if (isset($this->userEmail
)) {
438 $this->assign('email', $this->userEmail
);
441 if (!empty($defaults['is_pay_later'])) {
442 $this->assign('is_pay_later', TRUE);
444 $this->assign('contribution_status_id', CRM_Utils_Array
::value('contribution_status_id', $defaults));
452 foreach ($dates as $key) {
453 if (!empty($defaults[$key])) {
454 list($defaults[$key], $defaults[$key . '_time'])
455 = CRM_Utils_Date
::setDateDefaults(CRM_Utils_Array
::value($key, $defaults), 'activityDateTime');
459 if (!$this->_id
&& empty($defaults['receive_date'])) {
460 list($defaults['receive_date'],
461 $defaults['receive_date_time']
462 ) = CRM_Utils_Date
::setDateDefaults(NULL, 'activityDateTime');
465 $this->assign('receive_date', CRM_Utils_Date
::processDate(CRM_Utils_Array
::value('receive_date', $defaults),
466 CRM_Utils_Array
::value('receive_date_time', $defaults)
468 $currency = CRM_Utils_Array
::value('currency', $defaults);
469 $this->assign('currency', $currency);
470 // Hack to get currency info to the js layer. CRM-11440.
471 CRM_Utils_Money
::format(1);
472 $this->assign('currencySymbol', CRM_Utils_Array
::value($currency, CRM_Utils_Money
::$_currencySymbols));
473 $this->assign('totalAmount', CRM_Utils_Array
::value('total_amount', $defaults));
475 // Inherit campaign from pledge.
476 if ($this->_ppID
&& !empty($this->_pledgeValues
['campaign_id'])) {
477 $defaults['campaign_id'] = $this->_pledgeValues
['campaign_id'];
480 $this->_defaults
= $defaults;
485 * Build the form object.
487 public function buildQuickForm() {
489 //@todo document the purpose of cdType (if still in use)
490 if ($this->_cdType
) {
491 CRM_Custom_Form_CustomData
::buildQuickForm($this);
496 //tax rate from financialType
497 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant
::getTaxRates()));
498 $this->assign('currencies', json_encode(CRM_Core_OptionGroup
::values('currencies_enabled')));
500 // build price set form.
501 $buildPriceSet = FALSE;
502 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
503 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
504 $this->assign('invoicing', $invoicing);
506 // display tax amount on edit contribution page
507 if ($invoicing && $this->_action
& CRM_Core_Action
::UPDATE
&& isset($this->_values
['tax_amount'])) {
508 $this->assign('totalTaxAmount', $this->_values
['tax_amount']);
511 if (empty($this->_lineItems
) &&
512 ($this->_priceSetId ||
!empty($_POST['price_set_id']))
514 $buildPriceSet = TRUE;
515 $getOnlyPriceSetElements = TRUE;
516 if (!$this->_priceSetId
) {
517 $this->_priceSetId
= $_POST['price_set_id'];
518 $getOnlyPriceSetElements = FALSE;
521 $this->set('priceSetId', $this->_priceSetId
);
522 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
524 // get only price set form elements.
525 if ($getOnlyPriceSetElements) {
529 // use to build form during form rule.
530 $this->assign('buildPriceSet', $buildPriceSet);
532 $defaults = $this->_values
;
533 $additionalDetailFields = array(
537 'non_deductible_amount',
541 foreach ($additionalDetailFields as $key) {
542 if (!empty($defaults[$key])) {
543 $defaults['hidden_AdditionalDetail'] = 1;
548 if ($this->_productDAO
) {
549 if ($this->_productDAO
->product_id
) {
550 $defaults['hidden_Premium'] = 1;
554 if ($this->_noteID
&&
555 isset($this->_values
['note'])
557 $defaults['hidden_AdditionalDetail'] = 1;
561 ts('Additional Details') => 'AdditionalDetail',
564 //Add Premium pane only if Premium is exists.
565 $dao = new CRM_Contribute_DAO_Product();
568 if ($dao->find(TRUE)) {
569 $paneNames[ts('Premium Information')] = 'Premium';
573 if (CRM_Core_Payment_Form
::buildPaymentForm($this, $this->_paymentProcessor
, FALSE, TRUE) == TRUE) {
574 if (!empty($this->_recurPaymentProcessors
)) {
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;");
583 foreach ($paneNames as $name => $type) {
584 $allPanes[$name] = $this->generatePane($type, $defaults);
587 $qfKey = $this->controller
->_key
;
588 $this->assign('qfKey', $qfKey);
589 $this->assign('allPanes', $allPanes);
591 $this->addFormRule(array('CRM_Contribute_Form_Contribution', 'formRule'), $this);
593 if ($this->_formType
) {
594 $this->assign('formType', $this->_formType
);
598 $this->applyFilter('__ALL__', 'trim');
600 if ($this->_action
& CRM_Core_Action
::DELETE
) {
601 $this->addButtons(array(
604 'name' => ts('Delete'),
605 'spacing' => ' ',
610 'name' => ts('Cancel'),
617 //need to assign custom data type and subtype to the template
618 $this->assign('customDataType', 'Contribution');
619 $this->assign('customDataSubType', $this->_contributionType
);
620 $this->assign('entityID', $this->_id
);
622 if ($this->_context
== 'standalone') {
623 $this->addEntityRef('contact_id', ts('Contact'), array(
625 'api' => array('extra' => array('email')),
629 $attributes = CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Contribution');
631 $financialType = $this->add('select', 'financial_type_id',
632 ts('Financial Type'),
633 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::financialType(),
635 array('onChange' => "CRM.buildCustomData( 'Contribution', this.value );")
637 $paymentInstrument = FALSE;
639 $paymentInstrument = $this->add('select', 'payment_instrument_id',
641 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::paymentInstrument(),
642 TRUE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
646 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), array('class' => 'twelve') +
$attributes['trxn_id']);
648 //add receipt for offline contribution
649 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
651 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
653 $status = CRM_Contribute_PseudoConstant
::contributionStatus();
655 // suppressing contribution statuses that are NOT relevant to pledges (CRM-5169)
656 $statusName = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
663 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
666 elseif ((!$this->_ppID
&& $this->_id
) ||
!$this->_id
) {
667 $suppressFlag = FALSE;
669 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
670 if (CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails)) {
671 $suppressFlag = TRUE;
674 if (!$suppressFlag) {
679 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
683 unset($status[CRM_Utils_Array
::key('Overdue', $statusName)]);
688 $contributionStatus = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_id
, 'contribution_status_id');
689 $name = CRM_Utils_Array
::value($contributionStatus, $statusName);
694 unset($status[CRM_Utils_Array
::key('In Progress', $statusName)]);
695 unset($status[CRM_Utils_Array
::key('Pending', $statusName)]);
696 unset($status[CRM_Utils_Array
::key('Failed', $statusName)]);
701 unset($status[CRM_Utils_Array
::key('Refunded', $statusName)]);
712 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
718 unset($status[CRM_Utils_Array
::key('Refunded', $statusName)]);
721 $this->add('select', 'contribution_status_id',
722 ts('Contribution Status'),
728 $this->addDateTime('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
730 if ($this->_online
) {
731 $this->assign('hideCalender', TRUE);
733 $checkNumber = $this->add('text', 'check_number', ts('Check Number'), $attributes['check_number']);
735 $this->addDateTime('receipt_date', ts('Receipt Date'), FALSE, array('formatType' => 'activityDateTime'));
736 $this->addDateTime('cancel_date', ts('Cancelled / Refunded Date'), FALSE, array('formatType' => 'activityDateTime'));
738 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
740 $element = $this->add('select',
741 'payment_processor_id',
742 ts('Payment Processor'),
748 if ($this->_online
) {
753 if (empty($this->_lineItems
)) {
754 $buildPriceSet = FALSE;
755 $priceSets = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute');
756 if (!empty($priceSets) && !$this->_ppID
) {
757 $buildPriceSet = TRUE;
760 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
761 // and if we already have line items for that participant. CRM-5095
762 if ($buildPriceSet && $this->_id
) {
763 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
764 $pledgePaymentId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
769 if ($pledgePaymentId) {
770 $buildPriceSet = FALSE;
772 if ($participantID = CRM_Utils_Array
::value('participant', $componentDetails)) {
773 $participantLI = CRM_Price_BAO_LineItem
::getLineItems($participantID);
774 if (!CRM_Utils_System
::isNull($participantLI)) {
775 $buildPriceSet = FALSE;
780 $hasPriceSets = FALSE;
781 if ($buildPriceSet) {
782 $hasPriceSets = TRUE;
783 // CRM-16451: set financial type of 'Price Set' in back office contribution
784 // instead of selecting manually
785 $financialTypeIds = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute', 'financial_type_id');
786 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
788 '' => ts('Choose price set'),
790 NULL, array('onchange' => "buildAmount( this.value, " . json_encode($financialTypeIds) . ");")
792 if ($this->_online
&& !($this->_action
& CRM_Core_Action
::UPDATE
)) {
796 $this->assign('hasPriceSets', $hasPriceSets);
797 $currencyFreeze = FALSE;
798 if (!($this->_action
& CRM_Core_Action
::UPDATE
)) {
799 if ($this->_online ||
$this->_ppID
) {
800 $attributes['total_amount'] = array_merge($attributes['total_amount'], array(
802 'style' => "background-color:#EBECE4",
804 $optionTypes = array(
805 '1' => ts('Adjust Pledge Payment Schedule?'),
806 '2' => ts('Adjust Total Pledge Amount?'),
808 $this->addRadio('option_type',
814 $currencyFreeze = TRUE;
818 $totalAmount = $this->addMoney('total_amount',
820 ($hasPriceSets) ?
FALSE : TRUE,
821 $attributes['total_amount'],
822 TRUE, 'currency', NULL, $currencyFreeze
826 $this->add('text', 'source', ts('Source'), CRM_Utils_Array
::value('source', $attributes));
828 // CRM-7362 --add campaigns.
829 CRM_Campaign_BAO_Campaign
::addCampaign($this, CRM_Utils_Array
::value('campaign_id', $this->_values
));
831 CRM_Contribute_Form_SoftCredit
::buildQuickForm($this);
835 $js = array('onclick' => "return verify( );");
838 $mailingInfo = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
841 $this->assign('outBound_option', $mailingInfo['outBound_option']);
843 $this->addButtons(array(
846 'name' => ts('Save'),
852 'name' => ts('Save and New'),
858 'name' => ts('Cancel'),
863 // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
864 // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
865 if ($this->_id
&& $this->_values
['contribution_status_id'] == array_search('Cancelled', $statusName)) {
867 $totalAmount->freeze();
869 $checkNumber->freeze();
870 $paymentInstrument->freeze();
872 $financialType->freeze();
875 // if contribution is related to membership or participant freeze Financial Type, Amount
876 if ($this->_id
&& isset($this->_values
['tax_amount'])) {
877 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
878 if (CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails)) {
880 $totalAmount->freeze();
882 $financialType->freeze();
883 $this->assign('freezeFinancialType', TRUE);
887 if ($this->_action
& CRM_Core_Action
::VIEW
) {
895 * @param array $fields
896 * The input form values.
897 * @param array $files
898 * The uploaded files if any.
902 * true if no errors, else array of errors
904 public static function formRule($fields, $files, $self) {
907 // Check for Credit Card Contribution.
909 if (empty($fields['payment_processor_id'])) {
910 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
913 // validate payment instrument (e.g. credit card number)
914 CRM_Core_Payment_Form
::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, $self);
918 // Do the amount validations.
919 if (empty($fields['total_amount']) && empty($self->_lineItems
)) {
920 if ($priceSetId = CRM_Utils_Array
::value('price_set_id', $fields)) {
921 CRM_Price_BAO_PriceField
::priceSetValidation($priceSetId, $fields, $errors);
925 $softErrors = CRM_Contribute_Form_SoftCredit
::formRule($fields, $errors, $self);
927 if (!empty($fields['total_amount']) && (!empty($fields['net_amount']) ||
!empty($fields['fee_amount']))) {
928 $sum = CRM_Utils_Rule
::cleanMoney($fields['net_amount']) + CRM_Utils_Rule
::cleanMoney($fields['fee_amount']);
929 // For taxable contribution we need to deduct taxable amount from
930 // (net amount + fee amount) before comparing it with total amount
931 if (!empty($self->_values
['tax_amount'])) {
932 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($self->_id
);
933 if (!(CRM_Utils_Array
::value('membership', $componentDetails) ||
934 CRM_Utils_Array
::value('participant', $componentDetails))
936 $sum = CRM_Utils_Money
::format($sum - $self->_values
['tax_amount'], NULL, '%a');
939 if (CRM_Utils_Rule
::cleanMoney($fields['total_amount']) != $sum) {
940 $errors['total_amount'] = ts('The sum of fee amount and net amount must be equal to total amount');
944 //CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
945 CRM_Contribute_BAO_ContributionRecur
::validateRecurContribution($fields, $files, $self, $errors);
947 // Form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
948 if ($self->_id
&& $self->_values
['contribution_status_id'] != $fields['contribution_status_id']) {
949 CRM_Contribute_BAO_Contribution
::checkStatusValidation($self->_values
, $fields, $errors);
951 // CRM-16015, add form-rule to restrict change of financial type if using price field of different financial type
952 if ($self->_id
&& $self->_values
['financial_type_id'] != $fields['financial_type_id']) {
953 CRM_Contribute_BAO_Contribution
::checkFinancialTypeChange(NULL, $self->_id
, $errors);
955 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
956 if (!empty($fields['fee_amount']) && !empty($fields['financial_type_id']) && $financialType = CRM_Contribute_BAO_Contribution
::validateFinancialType($fields['financial_type_id'])) {
957 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
960 // $trxn_id must be unique CRM-13919
961 if (!empty($fields['trxn_id'])) {
962 $queryParams = array(1 => array($fields['trxn_id'], 'String'));
963 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
965 $queryParams[2] = array((int) $self->_id
, 'Integer');
966 $query .= ' and id !=%2';
968 $tCnt = CRM_Core_DAO
::singleValueQuery($query, $queryParams);
970 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', array(1 => $fields['trxn_id']));
974 $errors = array_merge($errors, $softErrors);
979 * Process the form submission.
981 public function postProcess() {
982 if ($this->_action
& CRM_Core_Action
::DELETE
) {
983 CRM_Contribute_BAO_Contribution
::deleteContribution($this->_id
);
984 CRM_Core_Session
::singleton()->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
985 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
989 $submittedValues = $this->controller
->exportValues($this->_name
);
992 // Get the submitted form values.
993 $contribution = $this->submit($submittedValues, $this->_action
, $this->_ppID
);
995 catch (PaymentProcessorException
$e) {
996 // Set the contribution mode.
997 $urlParams = "action=add&cid={$this->_contactID}";
999 $urlParams .= "&mode={$this->_mode}";
1001 if (!empty($this->_ppID
)) {
1002 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
1005 CRM_Core_Error
::statusBounce($e->getMessage(), $urlParams, ts('Payment Processor Error'));
1007 $session = CRM_Core_Session
::singleton();
1008 $buttonName = $this->controller
->getButtonName();
1009 if ($this->_context
== 'standalone') {
1010 if ($buttonName == $this->getButtonName('upload', 'new')) {
1011 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contribute/add',
1012 'reset=1&action=add&context=standalone'
1016 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
1017 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1021 elseif ($this->_context
== 'contribution' && $this->_mode
&& $buttonName == $this->getButtonName('upload', 'new')) {
1022 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
1023 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
1026 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1027 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
1028 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
1032 //store contribution ID if not yet set (on create)
1033 if (empty($this->_id
) && !empty($contribution->id
)) {
1034 $this->_id
= $contribution->id
;
1039 * Process credit card payment.
1041 * @param array $submittedValues
1042 * @param array $lineItem
1044 * @param int $contactID
1047 * @return bool|\CRM_Contribute_DAO_Contribution
1048 * @throws \CiviCRM_API3_Exception
1049 * @throws \Civi\Payment\Exception\PaymentProcessorException
1051 protected function processCreditCard($submittedValues, $lineItem, $contactID) {
1052 $contribution = FALSE;
1054 $isTest = ($this->_mode
== 'test') ?
1 : 0;
1055 // CRM-12680 set $_lineItem if its not set
1056 // @todo - I don't believe this would ever BE set. I can't find anywhere in the code.
1057 // It would be better to pass line item out to functions than $this->_lineItem as
1058 // we don't know what is being changed where.
1059 if (empty($this->_lineItem
) && !empty($lineItem)) {
1060 $this->_lineItem
= $lineItem;
1063 $this->_paymentObject
= Civi\Payment\System
::singleton()->getById($submittedValues['payment_processor_id']);
1064 $this->_paymentProcessor
= $this->_paymentObject
->getPaymentProcessor();
1066 // Set source if not set
1067 if (empty($submittedValues['source'])) {
1068 $userID = CRM_Core_Session
::singleton()->get('userID');
1069 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1072 $submittedValues['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
1075 $params = $this->_params
= $submittedValues;
1077 // Mapping requiring documentation.
1078 $this->_params
['payment_processor'] = $submittedValues['payment_processor_id'];
1080 $now = date('YmdHis');
1083 // we need to retrieve email address
1084 if ($this->_context
== 'standalone' && !empty($submittedValues['is_email_receipt'])) {
1085 list($this->userDisplayName
,
1087 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contactID);
1088 $this->assign('displayName', $this->userDisplayName
);
1091 // Set email for primary location.
1092 $fields['email-Primary'] = 1;
1093 $params['email-Primary'] = $this->userEmail
;
1095 // now set the values for the billing location.
1096 foreach (array_keys($this->_fields
) as $name) {
1100 // also add location name to the array
1101 $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);
1103 $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
1104 $fields["address_name-{$this->_bltID}"] = 1;
1106 $nameFields = array('first_name', 'middle_name', 'last_name');
1107 foreach ($nameFields as $name) {
1109 if (array_key_exists("billing_$name", $params)) {
1110 $params[$name] = $params["billing_{$name}"];
1111 $params['preserveDBName'] = TRUE;
1115 if (!empty($params['source'])) {
1116 unset($params['source']);
1118 CRM_Contact_BAO_Contact
::createProfileContact($params, $fields,
1121 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
1127 // add all the additional payment params we need
1128 if (!empty($this->_params
["billing_state_province_id-{$this->_bltID}"])) {
1129 $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}"]);
1131 if (!empty($this->_params
["billing_country_id-{$this->_bltID}"])) {
1132 $this->_params
["country-{$this->_bltID}"] = $this->_params
["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant
::countryIsoCode($this->_params
["billing_country_id-{$this->_bltID}"]);
1135 if (in_array('credit_card_exp_date', array_keys($this->_paymentFields
))) {
1136 $this->_params
['year'] = CRM_Core_Payment_Form
::getCreditCardExpirationYear($this->_params
);
1137 $this->_params
['month'] = CRM_Core_Payment_Form
::getCreditCardExpirationMonth($this->_params
);
1140 $this->_params
['ip_address'] = CRM_Utils_System
::ipAddress();
1141 $this->_params
['amount'] = $this->_params
['total_amount'];
1142 $this->_params
['amount_level'] = 0;
1143 $this->_params
['description'] = ts('Office Credit Card contribution');
1144 $this->_params
['currencyID'] = CRM_Utils_Array
::value('currency',
1146 CRM_Core_Config
::singleton()->defaultCurrency
1149 if (!empty($this->_params
['receive_date'])) {
1150 $this->_params
['receive_date'] = CRM_Utils_Date
::processDate($this->_params
['receive_date'], $this->_params
['receive_date_time']);
1153 if (!empty($params['soft_credit_to'])) {
1154 $this->_params
['soft_credit_to'] = $params['soft_credit_to'];
1155 $this->_params
['pcp_made_through_id'] = $params['pcp_made_through_id'];
1158 $this->_params
['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $params);
1159 $this->_params
['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $params);
1160 $this->_params
['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $params);
1162 //Add common data to formatted params
1163 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
1165 if (empty($this->_params
['invoice_id'])) {
1166 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
1169 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
1172 // At this point we've created a contact and stored its address etc
1173 // all the payment processors expect the name and address to be in the
1174 // so we copy stuff over to first_name etc.
1175 $paymentParams = $this->_params
;
1176 $paymentParams['contactID'] = $contactID;
1177 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
1179 $financialType = new CRM_Financial_DAO_FinancialType();
1180 $financialType->id
= $params['financial_type_id'];
1182 // Add some financial type details to the params list
1183 // if folks need to use it.
1184 $paymentParams['contributionType_name'] = $this->_params
['contributionType_name'] = $financialType->name
;
1185 $paymentParams['contributionPageID'] = NULL;
1187 if (!empty($this->_params
['is_email_receipt'])) {
1188 $paymentParams['email'] = $this->userEmail
;
1189 $paymentParams['is_email_receipt'] = 1;
1192 $paymentParams['is_email_receipt'] = 0;
1193 $this->_params
['is_email_receipt'] = 0;
1195 if (!empty($this->_params
['receive_date'])) {
1196 $paymentParams['receive_date'] = $this->_params
['receive_date'];
1199 $this->_params
['receive_date'] = $now;
1201 if (!empty($this->_params
['is_email_receipt'])) {
1202 $this->_params
['receipt_date'] = $now;
1205 $this->_params
['receipt_date'] = CRM_Utils_Date
::processDate($this->_params
['receipt_date'],
1206 $params['receipt_date_time'], TRUE
1210 $this->set('params', $this->_params
);
1212 $this->assign('receive_date', $this->_params
['receive_date']);
1214 // Result has all the stuff we need
1215 // lets archive it to a financial transaction
1216 if ($financialType->is_deductible
) {
1217 $this->assign('is_deductible', TRUE);
1218 $this->set('is_deductible', TRUE);
1221 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processFormContribution($this,
1233 $paymentParams['contributionID'] = $contribution->id
;
1234 $paymentParams['contributionTypeID'] = $contribution->financial_type_id
;
1235 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
1236 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1238 if ($paymentParams['amount'] > 0.0) {
1239 // force a re-get of the payment processor in case the form changed it, CRM-7179
1240 // NOTE - I expect this is not obsolete.
1241 $payment = CRM_Core_Payment
::singleton($this->_mode
, $this->_paymentProcessor
, $this, TRUE);
1243 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id');
1244 $result = $payment->doPayment($paymentParams, 'contribute');
1245 $this->assign('trxn_id', $result['trxn_id']);
1246 $contribution->trxn_id
= $result['trxn_id'];
1247 /* Our scenarios here are
1248 * 1) the payment failed & an Exception should have been thrown
1249 * 2) the payment succeeded but the payment is not immediate (for example a recurring payment
1250 * with a delayed start)
1251 * 3) the payment succeeded with an immediate payment.
1253 * The doPayment function ensures that contribution_status_id is always set
1254 * as historically we have had to guess from the context - ie doDirectPayment
1255 * = error or success, unless it is a recurring contribution in which case it is pending.
1257 if (!isset($result['contribution_status_id']) ||
$result['contribution_status_id'] ==
1258 array_search('Completed', $statuses)) {
1259 civicrm_api3('contribution', 'completetransaction', array('id' => $contribution->id
, 'trxn_id' => $result['trxn_id']));
1262 // Save the trxn_id.
1263 $contribution->save();
1266 catch (PaymentProcessorException
$e) {
1267 CRM_Contribute_BAO_Contribution
::failPayment($contribution->id
, $paymentParams['contactID'], $e->getMessage());
1268 throw new PaymentProcessorException($e->getMessage());
1271 // Send receipt mail.
1272 if ($contribution->id
&& !empty($this->_params
['is_email_receipt'])) {
1273 $this->_params
['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $result);
1274 $this->_params
['contact_id'] = $contactID;
1275 $this->_params
['contribution_id'] = $contribution->id
;
1276 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $this->_params
, TRUE)) {
1277 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1281 return $contribution;
1285 * Generate the data to construct a snippet based pane.
1287 * This form also assigns the showAdditionalInfo var based on historical code.
1288 * This appears to mean 'there is a pane to show'.
1290 * @param string $type
1291 * Type of Pane - this is generally used to determine the function name used to build it
1292 * - e.g CreditCard, AdditionalDetail
1293 * @param array $defaults
1296 * We aim to further refactor & simplify this but currently
1298 * - should additional info be shown?
1300 protected function generatePane($type, $defaults) {
1301 $urlParams = "snippet=4&formType={$type}";
1303 $urlParams .= "&mode={$this->_mode}";
1307 if ($type == 'CreditCard' ||
1308 $type == 'DirectDebit'
1314 'url' => CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams),
1319 // See if we need to include this paneName in the current form.
1320 if ($this->_formType
== $type ||
!empty($_POST["hidden_{$type}"]) ||
1321 CRM_Utils_Array
::value("hidden_{$type}", $defaults)
1323 $this->assign('showAdditionalInfo', TRUE);
1324 $pane['open'] = 'true';
1327 if ($type == 'CreditCard' ||
$type == 'DirectDebit') {
1328 // @todo would be good to align tpl name with form name...
1329 // @todo document why this hidden variable is required.
1330 $this->add('hidden', 'hidden_' . $type, 1);
1334 $additionalInfoFormFunction = 'build' . $type;
1335 CRM_Contribute_Form_AdditionalInfo
::$additionalInfoFormFunction($this);
1341 * Wrapper for unit testing the post process submit function.
1343 * (If we expose through api we can get default additions 'for free').
1345 * @param array $params
1346 * @param int $action
1347 * @param string|null $creditCardMode
1349 * @throws \CiviCRM_API3_Exception
1351 public function testSubmit($params, $action, $creditCardMode = NULL) {
1353 'soft_credit_contact_id' => array(),
1354 'receipt_date' => '',
1355 'receipt_date_time' => '',
1356 'cancel_date' => '',
1357 'cancel_date_time' => '',
1358 'hidden_Premium' => 1,
1360 if (!empty($params['id'])) {
1361 $existingContribution = civicrm_api3('contribution', 'getsingle', array(
1362 'id' => $params['id'],
1364 $this->_id
= $params['id'];
1367 $existingContribution = array();
1370 $this->_defaults
['contribution_status_id'] = CRM_Utils_Array
::value('contribution_status_id',
1371 $existingContribution
1374 $this->_defaults
['total_amount'] = CRM_Utils_Array
::value('total_amount',
1375 $existingContribution
1378 if ($creditCardMode) {
1379 $this->_mode
= $creditCardMode;
1382 // Required because processCreditCard calls set method on this.
1383 $_SERVER['REQUEST_METHOD'] = 'GET';
1384 $this->controller
= new CRM_Core_Controller();
1386 CRM_Contribute_Form_AdditionalInfo
::buildPremium($this);
1388 $this->_fields
= array();
1389 $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array
::value('pledge_payment_id', $params));
1394 * @param array $submittedValues
1396 * @param int $action
1398 * - CRM_Core_Action::UPDATE
1400 * @param $pledgePaymentID
1403 * @throws \Exception
1405 protected function submit($submittedValues, $action, $pledgePaymentID) {
1406 $softParams = $softIDs = array();
1407 $pId = $contribution = $isRelatedId = FALSE;
1409 if (!empty($submittedValues['price_set_id']) && $action & CRM_Core_Action
::UPDATE
) {
1410 $line = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution');
1411 $lineID = key($line);
1412 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array
::value('price_field_id', $line[$lineID]), 'price_set_id');
1413 $quickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1415 CRM_Price_BAO_LineItem
::deleteLineItems($this->_id
, 'civicrm_contribution');
1419 // Process price set and get total amount and line items.
1420 $lineItem = array();
1421 $priceSetId = CRM_Utils_Array
::value('price_set_id', $submittedValues);
1422 if (empty($priceSetId) && !$this->_id
) {
1423 $this->_priceSetId
= $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1424 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
1425 $fieldID = key($this->_priceSet
['fields']);
1426 $fieldValueId = key($this->_priceSet
['fields'][$fieldID]['options']);
1427 $this->_priceSet
['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1428 $submittedValues['price_' . $fieldID] = 1;
1432 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
1433 $submittedValues, $lineItem[$priceSetId]);
1435 // Unset tax amount for offline 'is_quick_config' contribution.
1436 if ($this->_priceSet
['is_quick_config'] &&
1437 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant
::getTaxRates())
1439 unset($submittedValues['tax_amount']);
1441 $submittedValues['total_amount'] = CRM_Utils_Array
::value('amount', $submittedValues);
1444 if ($this->_compId
) {
1445 if ($this->_context
== 'participant') {
1446 $pId = $this->_compId
;
1448 elseif ($this->_context
== 'membership') {
1449 $isRelatedId = TRUE;
1452 $pId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id
, 'participant_id', 'contribution_id');
1456 $contributionDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1457 if (array_key_exists('membership', $contributionDetails)) {
1458 $isRelatedId = TRUE;
1460 elseif (array_key_exists('participant', $contributionDetails)) {
1461 $pId = $contributionDetails['participant'];
1465 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id
) {
1466 // CRM-10117 update the line items for participants.
1468 $entityTable = 'participant';
1470 $isRelatedId = FALSE;
1471 $participantParams = array(
1472 'fee_amount' => $submittedValues['total_amount'],
1475 CRM_Event_BAO_Participant
::add($participantParams);
1476 if (empty($this->_lineItems
)) {
1477 $this->_lineItems
[] = CRM_Price_BAO_LineItem
::getLineItems($entityID, 'participant', 1);
1481 $entityTable = 'contribution';
1482 $entityID = $this->_id
;
1485 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, $entityTable, NULL, TRUE, $isRelatedId);
1486 foreach (array_keys($lineItems) as $id) {
1487 $lineItems[$id]['id'] = $id;
1489 $itemId = key($lineItems);
1490 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1491 $this->_priceSetId
= CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1494 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1495 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule
::cleanMoney(CRM_Utils_Array
::value('total_amount', $submittedValues));
1497 // Update line total and total amount with tax on edit.
1498 $financialItemsId = CRM_Core_PseudoConstant
::getTaxRates();
1499 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1500 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1503 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1504 $submittedValues['tax_amount'] = 'null';
1506 if ($lineItems[$itemId]['tax_rate']) {
1507 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total'];
1508 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] +
$lineItems[$itemId]['tax_amount'];
1509 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1512 // CRM-10117 update the line items for participants.
1513 if (!empty($lineItems[$itemId]['price_field_id'])) {
1514 $lineItem[$this->_priceSetId
] = $lineItems;
1519 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1522 //CRM-11529 for quick config back office transactions
1523 //when financial_type_id is passed in form, update the
1524 //line items with the financial type selected in form
1525 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array
::value($this->_priceSetId
, $lineItem)
1527 foreach ($lineItem[$this->_priceSetId
] as &$values) {
1528 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1532 if (!isset($submittedValues['total_amount'])) {
1533 $submittedValues['total_amount'] = CRM_Utils_Array
::value('total_amount', $this->_values
);
1535 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
1537 if (!empty($submittedValues['pcp_made_through_id'])) {
1540 'pcp_made_through_id',
1541 'pcp_display_in_roll',
1542 'pcp_roll_nickname',
1543 'pcp_personal_note',
1545 foreach ($fields as $f) {
1546 $pcp[$f] = CRM_Utils_Array
::value($f, $submittedValues);
1550 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
1551 if ($this->_id
&& count($isEmpty) == 1 && key($isEmpty) == NULL) {
1552 //Delete existing soft credit records if soft credit list is empty on update
1553 CRM_Contribute_BAO_ContributionSoft
::del(array('contribution_id' => $this->_id
));
1556 //build soft credit params
1557 foreach ($submittedValues['soft_credit_contact_id'] as $key => $val) {
1558 if ($val && $submittedValues['soft_credit_amount'][$key]) {
1559 $softParams[$key]['contact_id'] = $val;
1560 $softParams[$key]['amount'] = CRM_Utils_Rule
::cleanMoney($submittedValues['soft_credit_amount'][$key]);
1561 $softParams[$key]['soft_credit_type_id'] = $submittedValues['soft_credit_type'][$key];
1562 if (!empty($submittedValues['soft_credit_id'][$key])) {
1563 $softIDs[] = $softParams[$key]['id'] = $submittedValues['soft_credit_id'][$key];
1569 // set the contact, when contact is selected
1570 if (!empty($submittedValues['contact_id'])) {
1571 $this->_contactID
= $submittedValues['contact_id'];
1573 $formValues = $submittedValues;
1575 // Credit Card Contribution.
1577 $paramsSetByPaymentProcessingSubsystem = array(
1579 'payment_instrument_id',
1580 'contribution_status_id',
1584 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1585 if (isset($formValues[$key])) {
1586 unset($formValues[$key]);
1589 $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID
);
1590 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1591 $formValues[$key] = $contribution->$key;
1595 // Offline Contribution.
1596 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1598 // get the required field value only.
1600 $params = $ids = array();
1602 $params['contact_id'] = $this->_contactID
;
1603 $params['currency'] = $this->getCurrency($submittedValues);
1606 'financial_type_id',
1607 'contribution_status_id',
1608 'payment_instrument_id',
1613 foreach ($fields as $f) {
1614 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1618 $params['pcp'] = $pcp;
1620 if (!empty($softParams)) {
1621 $params['soft_credit'] = $softParams;
1622 $params['soft_credit_ids'] = $softIDs;
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 ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Cancelled', 'name')
1645 ||
$params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name')
1647 if (CRM_Utils_System
::isNull(CRM_Utils_Array
::value('cancel_date', $params))) {
1648 $params['cancel_date'] = date('Y-m-d');
1652 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1655 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1656 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1657 if ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Pending', 'name')) {
1658 $params['is_pay_later'] = 1;
1660 elseif ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name')) {
1661 $params['is_pay_later'] = 0;
1664 $ids['contribution'] = $params['id'] = $this->_id
;
1666 // Add Additional common information to formatted params.
1667 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($formValues, $params, $this);
1669 $params['contribution_mode'] = 'participant';
1670 $params['participant_id'] = $pId;
1671 $params['skipLineItem'] = 1;
1673 elseif ($isRelatedId) {
1674 $params['contribution_mode'] = 'membership';
1676 $params['line_item'] = $lineItem;
1677 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array
::value('id', $this->_paymentProcessor
);
1678 if (isset($submittedValues['tax_amount'])) {
1679 $params['tax_amount'] = $submittedValues['tax_amount'];
1681 //create contribution.
1682 if ($isQuickConfig) {
1683 $params['is_quick_config'] = 1;
1685 $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
1687 $contribution = CRM_Contribute_BAO_Contribution
::create($params, $ids);
1689 // process associated membership / participant, CRM-4395
1690 if ($contribution->id
&& $action & CRM_Core_Action
::UPDATE
) {
1691 $this->statusMessage
[] = $this->updateRelatedComponent($contribution->id
,
1692 $contribution->contribution_status_id
,
1693 CRM_Utils_Array
::value('contribution_status_id',
1696 $contribution->receive_date
1700 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1702 $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
1704 //send receipt mail.
1705 if ($contribution->id
&& !empty($formValues['is_email_receipt'])) {
1706 $formValues['contact_id'] = $this->_contactID
;
1707 $formValues['contribution_id'] = $contribution->id
;
1709 $formValues +
= CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
);
1711 // to get 'from email id' for send receipt
1712 $this->fromEmailId
= $formValues['from_email_address'];
1713 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $formValues)) {
1714 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1718 $this->statusMessageTitle
= ts('Saved');
1722 if ($contribution->id
&& !empty($formValues['product_name'][0])) {
1723 CRM_Contribute_Form_AdditionalInfo
::processPremium($submittedValues, $contribution->id
,
1724 $this->_premiumID
, $this->_options
1728 if ($contribution->id
&& isset($submittedValues['note'])) {
1729 CRM_Contribute_Form_AdditionalInfo
::processNote($submittedValues, $this->_contactID
, $contribution->id
, $this->_noteID
);
1732 CRM_Core_Session
::setStatus(implode(' ', $this->statusMessage
), $this->statusMessageTitle
, 'success');
1734 CRM_Contribute_BAO_Contribution
::updateRelatedPledge(
1738 (CRM_Utils_Array
::value('option_type', $formValues) == 2) ?
TRUE : FALSE,
1739 $formValues['total_amount'],
1740 CRM_Utils_Array
::value('total_amount', $this->_defaults
),
1741 $formValues['contribution_status_id'],
1742 CRM_Utils_Array
::value('contribution_status_id', $this->_defaults
)
1744 return $contribution;
1748 * Assign tax calculations to contribution receipts.
1750 * @param array $submittedValues
1751 * @param int $action
1752 * @param array $lineItem
1754 protected function invoicingPostProcessHook($submittedValues, $action, $lineItem) {
1756 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
1757 if (!CRM_Utils_Array
::value('invoicing', $invoiceSettings)) {
1761 $getTaxDetails = FALSE;
1762 if ($action & CRM_Core_Action
::ADD
) {
1765 elseif ($action & CRM_Core_Action
::UPDATE
) {
1766 $line = $this->_lineItems
;
1768 foreach ($line as $key => $value) {
1769 foreach ($value as $v) {
1770 if (isset($taxRate[(string) CRM_Utils_Array
::value('tax_rate', $v)])) {
1771 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $v);
1774 if (isset($v['tax_rate'])) {
1775 $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $v);
1776 $getTaxDetails = TRUE;
1782 if ($action & CRM_Core_Action
::UPDATE
) {
1783 if (isset($submittedValues['tax_amount'])) {
1784 $totalTaxAmount = $submittedValues['tax_amount'];
1787 $totalTaxAmount = $this->_values
['tax_amount'];
1789 $this->assign('totalTaxAmount', $totalTaxAmount);
1790 $this->assign('dataArray', $taxRate);
1793 if (!empty($submittedValues['price_set_id'])) {
1794 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1795 $this->assign('getTaxDetails', $getTaxDetails);
1796 $this->assign('dataArray', $taxRate);
1797 $this->assign('taxTerm', CRM_Utils_Array
::value('tax_term', $invoiceSettings));
1800 $this->assign('totalTaxAmount', CRM_Utils_Array
::value('tax_amount', $submittedValues));
1806 * Calculate non deductible amount.
1809 * if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1810 * if non_deductible_amount does NOT exist - then calculate it depending on:
1811 * $financialType->is_deductible and whether there is a product (premium).
1814 * @param $formValues
1818 protected function calculateNonDeductibleAmount($params, $formValues) {
1819 if (!empty($params['non_deductible_amount'])) {
1820 return $params['non_deductible_amount'];
1822 if (empty($params['non_deductible_amount'])) {
1823 $contributionType = new CRM_Financial_DAO_FinancialType();
1824 $contributionType->id
= $params['financial_type_id'];
1826 if ($contributionType->is_deductible
) {
1828 if (isset($formValues['product_name'][0])) {
1829 $selectProduct = $formValues['product_name'][0];
1831 // if there is a product - compare the value to the contribution amount
1832 if (isset($selectProduct)) {
1833 $productDAO = new CRM_Contribute_DAO_Product();
1834 $productDAO->id
= $selectProduct;
1835 $productDAO->find(TRUE);
1836 // product value exceeds contribution amount
1837 if ($params['total_amount'] < $productDAO->price
) {
1838 return $params['total_amount'];
1840 // product value does NOT exceed contribution amount
1842 return $productDAO->price
;
1845 // contribution is deductible - but there is no product
1850 // contribution is NOT deductible
1852 return $params['total_amount'];