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 * Set variables up before form is built.
216 public function preProcess() {
218 // Check permission for action.
219 if (!CRM_Core_Permission
::checkActionPermission('CiviContribute', $this->_action
)) {
220 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
223 // @todo - if anyone ever figures out what this _cdType subroutine is about
224 // (or even if it still applies) please add comments!!!!!!!!!!
225 $this->_cdType
= CRM_Utils_Array
::value('type', $_GET);
226 $this->assign('cdType', FALSE);
227 if ($this->_cdType
) {
228 $this->assign('cdType', TRUE);
229 CRM_Custom_Form_CustomData
::preProcess($this);
233 $this->_formType
= CRM_Utils_Array
::value('formType', $_GET);
236 $this->_priceSetId
= CRM_Utils_Array
::value('priceSetId', $_GET);
237 $this->set('priceSetId', $this->_priceSetId
);
238 $this->assign('priceSetId', $this->_priceSetId
);
240 // Get the pledge payment id
241 $this->_ppID
= CRM_Utils_Request
::retrieve('ppid', 'Positive', $this);
243 // Get the contact id
244 $this->_contactID
= CRM_Utils_Request
::retrieve('cid', 'Positive', $this);
247 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, 'add');
248 $this->assign('action', $this->_action
);
250 // Get the contribution id if update
251 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this);
252 if (!empty($this->_id
)) {
253 $this->assign('contribID', $this->_id
);
256 $this->_context
= CRM_Utils_Request
::retrieve('context', 'String', $this);
257 $this->assign('context', $this->_context
);
259 $this->_compId
= CRM_Utils_Request
::retrieve('compId', 'Positive', $this);
261 $this->_compContext
= CRM_Utils_Request
::retrieve('compContext', 'String', $this);
263 //set the contribution mode.
264 $this->_mode
= CRM_Utils_Request
::retrieve('mode', 'String', $this);
266 $this->assign('contributionMode', $this->_mode
);
267 if ($this->_action
& CRM_Core_Action
::DELETE
) {
271 $this->assign('showCheckNumber', TRUE);
273 $this->_fromEmails
= CRM_Core_BAO_Email
::getFromEmail();
274 $this->assignPaymentRelatedVariables();
276 if (in_array('CiviPledge', CRM_Core_Config
::singleton()->enableComponents
) && !$this->_formType
) {
277 $this->preProcessPledge();
281 $this->showRecordLinkMesssage($this->_id
);
283 $this->_values
= array();
285 // Current contribution id.
287 $this->assignPremiumProduct($this->_id
);
288 $this->buildValuesAndAssignOnline_Note_Type($this->_id
, $this->_values
);
291 // when custom data is included in this page
292 if (!empty($_POST['hidden_custom'])) {
293 $this->applyCustomData('Contribution', CRM_Utils_Array
::value('financial_type_id', $_POST), $this->_id
);
296 $this->_lineItems
= array();
298 if (!empty($this->_compId
) && $this->_compContext
== 'participant') {
299 $this->assign('compId', $this->_compId
);
300 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_compId
);
303 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution', 1, TRUE, TRUE);
305 empty($lineItem) ?
NULL : $this->_lineItems
[] = $lineItem;
308 $this->assign('lineItem', empty($this->_lineItems
) ?
FALSE : $this->_lineItems
);
312 $this->setPageTitle($this->_ppID ?
ts('Credit Card Pledge Payment') : ts('Credit Card Contribution'));
315 $this->setPageTitle($this->_ppID ?
ts('Pledge Payment') : ts('Contribution'));
319 CRM_Contribute_Form_SoftCredit
::preprocess($this);
324 * Set default values.
328 public function setDefaultValues() {
329 if ($this->_cdType
) {
330 // @todo document when this function would be called in this way
331 // (and whether it is valid or an overloading of this form).
332 return CRM_Custom_Form_CustomData
::setDefaultValues($this);
335 $defaults = $this->_values
;
337 // Set defaults for pledge payment.
339 $defaults['total_amount'] = CRM_Utils_Array
::value('scheduled_amount', $this->_pledgeValues
['pledgePayment']);
340 $defaults['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $this->_pledgeValues
);
341 $defaults['currency'] = CRM_Utils_Array
::value('currency', $this->_pledgeValues
);
342 $defaults['option_type'] = 1;
345 if ($this->_action
& CRM_Core_Action
::DELETE
) {
349 $defaults['frequency_interval'] = 1;
350 $defaults['frequency_unit'] = 'month';
352 // Set soft credit defaults.
353 CRM_Contribute_Form_SoftCredit
::setDefaultValues($defaults, $this);
356 $config = CRM_Core_Config
::singleton();
357 // Set default country from config if no country set.
358 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
359 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry
;
362 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
363 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince
;
366 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID
);
367 $defaults = array_merge($defaults, $billingDefaults);
371 $this->_contactID
= $defaults['contact_id'];
374 // Set $newCredit variable in template to control whether link to credit card mode is included.
375 $this->assign('newCredit', CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments());
377 // Fix the display of the monetary value, CRM-4038.
378 if (isset($defaults['total_amount'])) {
379 if (!empty($defaults['tax_amount'])) {
380 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
381 if (!(CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails))) {
382 $defaults['total_amount'] = CRM_Utils_Money
::format($defaults['total_amount'] - $defaults['tax_amount'], NULL, '%a');
386 $defaults['total_amount'] = CRM_Utils_Money
::format($defaults['total_amount'], NULL, '%a');
390 if (isset($defaults['non_deductible_amount'])) {
391 $defaults['non_deductible_amount'] = CRM_Utils_Money
::format($defaults['non_deductible_amount'], NULL, '%a');
394 if (isset($defaults['fee_amount'])) {
395 $defaults['fee_amount'] = CRM_Utils_Money
::format($defaults['fee_amount'], NULL, '%a');
398 if (isset($defaults['net_amount'])) {
399 $defaults['net_amount'] = CRM_Utils_Money
::format($defaults['net_amount'], NULL, '%a');
402 if ($this->_contributionType
) {
403 $defaults['financial_type_id'] = $this->_contributionType
;
406 if (empty($defaults['payment_instrument_id'])) {
407 $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup
::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
410 if (!empty($defaults['is_test'])) {
411 $this->assign('is_test', TRUE);
414 $this->assign('showOption', TRUE);
415 // For Premium section.
416 if ($this->_premiumID
) {
417 $this->assign('showOption', FALSE);
418 $options = isset($this->_options
[$this->_productDAO
->product_id
]) ?
$this->_options
[$this->_productDAO
->product_id
] : "";
420 $this->assign('showOption', TRUE);
422 $options_key = CRM_Utils_Array
::key($this->_productDAO
->product_option
, $options);
424 $defaults['product_name'] = array($this->_productDAO
->product_id
, trim($options_key));
427 $defaults['product_name'] = array($this->_productDAO
->product_id
);
429 if ($this->_productDAO
->fulfilled_date
) {
430 list($defaults['fulfilled_date']) = CRM_Utils_Date
::setDateDefaults($this->_productDAO
->fulfilled_date
);
434 if (isset($this->userEmail
)) {
435 $this->assign('email', $this->userEmail
);
438 if (!empty($defaults['is_pay_later'])) {
439 $this->assign('is_pay_later', TRUE);
441 $this->assign('contribution_status_id', CRM_Utils_Array
::value('contribution_status_id', $defaults));
449 foreach ($dates as $key) {
450 if (!empty($defaults[$key])) {
451 list($defaults[$key], $defaults[$key . '_time'])
452 = CRM_Utils_Date
::setDateDefaults(CRM_Utils_Array
::value($key, $defaults), 'activityDateTime');
456 if (!$this->_id
&& empty($defaults['receive_date'])) {
457 list($defaults['receive_date'],
458 $defaults['receive_date_time']
459 ) = CRM_Utils_Date
::setDateDefaults(NULL, 'activityDateTime');
462 $this->assign('receive_date', CRM_Utils_Date
::processDate(CRM_Utils_Array
::value('receive_date', $defaults),
463 CRM_Utils_Array
::value('receive_date_time', $defaults)
465 $currency = CRM_Utils_Array
::value('currency', $defaults);
466 $this->assign('currency', $currency);
467 // Hack to get currency info to the js layer. CRM-11440.
468 CRM_Utils_Money
::format(1);
469 $this->assign('currencySymbol', CRM_Utils_Array
::value($currency, CRM_Utils_Money
::$_currencySymbols));
470 $this->assign('totalAmount', CRM_Utils_Array
::value('total_amount', $defaults));
472 // Inherit campaign from pledge.
473 if ($this->_ppID
&& !empty($this->_pledgeValues
['campaign_id'])) {
474 $defaults['campaign_id'] = $this->_pledgeValues
['campaign_id'];
477 $this->_defaults
= $defaults;
482 * Build the form object.
484 public function buildQuickForm() {
485 //@todo document the purpose of cdType (if still in use)
486 if ($this->_cdType
) {
487 CRM_Custom_Form_CustomData
::buildQuickForm($this);
492 //tax rate from financialType
493 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant
::getTaxRates()));
494 $this->assign('currencies', json_encode(CRM_Core_OptionGroup
::values('currencies_enabled')));
496 // build price set form.
497 $buildPriceSet = FALSE;
498 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
499 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
500 $this->assign('invoicing', $invoicing);
502 // display tax amount on edit contribution page
503 if ($invoicing && $this->_action
& CRM_Core_Action
::UPDATE
&& isset($this->_values
['tax_amount'])) {
504 $this->assign('totalTaxAmount', $this->_values
['tax_amount']);
507 if (empty($this->_lineItems
) &&
508 ($this->_priceSetId ||
!empty($_POST['price_set_id']))
510 $buildPriceSet = TRUE;
511 $getOnlyPriceSetElements = TRUE;
512 if (!$this->_priceSetId
) {
513 $this->_priceSetId
= $_POST['price_set_id'];
514 $getOnlyPriceSetElements = FALSE;
517 $this->set('priceSetId', $this->_priceSetId
);
518 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
520 // get only price set form elements.
521 if ($getOnlyPriceSetElements) {
525 // use to build form during form rule.
526 $this->assign('buildPriceSet', $buildPriceSet);
528 $defaults = $this->_values
;
529 $additionalDetailFields = array(
533 'non_deductible_amount',
537 foreach ($additionalDetailFields as $key) {
538 if (!empty($defaults[$key])) {
539 $defaults['hidden_AdditionalDetail'] = 1;
544 if ($this->_productDAO
) {
545 if ($this->_productDAO
->product_id
) {
546 $defaults['hidden_Premium'] = 1;
550 if ($this->_noteID
&&
551 isset($this->_values
['note'])
553 $defaults['hidden_AdditionalDetail'] = 1;
557 ts('Additional Details') => 'AdditionalDetail',
560 //Add Premium pane only if Premium is exists.
561 $dao = new CRM_Contribute_DAO_Product();
564 if ($dao->find(TRUE)) {
565 $paneNames[ts('Premium Information')] = 'Premium';
568 $billingPanes = array();
570 if (CRM_Core_Payment_Form
::buildPaymentForm($this, $this->_paymentProcessor
, FALSE) == TRUE) {
571 foreach ($this->billingPane
as $name => $label) {
572 if (!empty($this->billingFieldSets
[$name]['fields'])) {
573 // @todo reduce variation so we don't have to convert 'credit_card' to 'CreditCard'
574 $billingPanes[$label] = $this->generatePane(CRM_Utils_String
::convertStringToCamel($name), $defaults);
577 if (!empty($this->_recurPaymentProcessors
)) {
578 CRM_Contribute_Form_Contribution_Main
::buildRecur($this);
579 $this->setDefaults(array('is_recur' => 0));
580 $this->assign('buildRecurBlock', TRUE);
581 $recurJs = array('onChange' => "buildRecurBlock( this.value ); return false;");
586 foreach ($paneNames as $name => $type) {
587 $allPanes[$name] = $this->generatePane($type, $defaults);
590 $qfKey = $this->controller
->_key
;
591 $this->assign('qfKey', $qfKey);
592 $this->assign('billingPanes', $billingPanes);
593 $this->assign('allPanes', $allPanes);
595 $this->addFormRule(array('CRM_Contribute_Form_Contribution', 'formRule'), $this);
597 if ($this->_formType
) {
598 $this->assign('formType', $this->_formType
);
602 $this->applyFilter('__ALL__', 'trim');
604 if ($this->_action
& CRM_Core_Action
::DELETE
) {
605 $this->addButtons(array(
608 'name' => ts('Delete'),
609 'spacing' => ' ',
614 'name' => ts('Cancel'),
621 //need to assign custom data type and subtype to the template
622 $this->assign('customDataType', 'Contribution');
623 $this->assign('customDataSubType', $this->_contributionType
);
624 $this->assign('entityID', $this->_id
);
626 if ($this->_context
== 'standalone') {
627 $this->addEntityRef('contact_id', ts('Contact'), array(
629 'api' => array('extra' => array('email')),
633 $attributes = CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Contribution');
635 $financialType = $this->add('select', 'financial_type_id',
636 ts('Financial Type'),
637 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::financialType(),
639 array('onChange' => "CRM.buildCustomData( 'Contribution', this.value );")
641 $paymentInstrument = FALSE;
643 $paymentInstrument = $this->add('select', 'payment_instrument_id',
645 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::paymentInstrument(),
646 TRUE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
650 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), array('class' => 'twelve') +
$attributes['trxn_id']);
652 //add receipt for offline contribution
653 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
655 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
657 $status = CRM_Contribute_PseudoConstant
::contributionStatus();
659 // suppressing contribution statuses that are NOT relevant to pledges (CRM-5169)
660 $statusName = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
667 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
670 elseif ((!$this->_ppID
&& $this->_id
) ||
!$this->_id
) {
671 $suppressFlag = FALSE;
673 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
674 if (CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails)) {
675 $suppressFlag = TRUE;
678 if (!$suppressFlag) {
683 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
687 unset($status[CRM_Utils_Array
::key('Overdue', $statusName)]);
692 $contributionStatus = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_id
, 'contribution_status_id');
693 $name = CRM_Utils_Array
::value($contributionStatus, $statusName);
698 unset($status[CRM_Utils_Array
::key('In Progress', $statusName)]);
699 unset($status[CRM_Utils_Array
::key('Pending', $statusName)]);
700 unset($status[CRM_Utils_Array
::key('Failed', $statusName)]);
705 unset($status[CRM_Utils_Array
::key('Refunded', $statusName)]);
716 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
722 unset($status[CRM_Utils_Array
::key('Refunded', $statusName)]);
725 $this->add('select', 'contribution_status_id',
726 ts('Contribution Status'),
732 $this->addDateTime('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
734 if ($this->_online
) {
735 $this->assign('hideCalender', TRUE);
737 $checkNumber = $this->add('text', 'check_number', ts('Check Number'), $attributes['check_number']);
739 $this->addDateTime('receipt_date', ts('Receipt Date'), FALSE, array('formatType' => 'activityDateTime'));
740 $this->addDateTime('cancel_date', ts('Cancelled / Refunded Date'), FALSE, array('formatType' => 'activityDateTime'));
742 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
744 $element = $this->add('select',
745 'payment_processor_id',
746 ts('Payment Processor'),
752 if ($this->_online
) {
756 if (empty($this->_lineItems
)) {
757 $buildPriceSet = FALSE;
758 $priceSets = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute');
759 if (!empty($priceSets) && !$this->_ppID
) {
760 $buildPriceSet = TRUE;
763 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
764 // and if we already have line items for that participant. CRM-5095
765 if ($buildPriceSet && $this->_id
) {
766 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
767 $pledgePaymentId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
772 if ($pledgePaymentId) {
773 $buildPriceSet = FALSE;
775 if ($participantID = CRM_Utils_Array
::value('participant', $componentDetails)) {
776 $participantLI = CRM_Price_BAO_LineItem
::getLineItems($participantID);
777 if (!CRM_Utils_System
::isNull($participantLI)) {
778 $buildPriceSet = FALSE;
783 $hasPriceSets = FALSE;
784 if ($buildPriceSet) {
785 $hasPriceSets = TRUE;
786 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
788 '' => ts('Choose price set'),
790 NULL, array('onchange' => "buildAmount( this.value );")
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 if (CRM_Utils_Rule
::cleanMoney($fields['total_amount']) != $sum) {
930 $errors['total_amount'] = ts('The sum of fee amount and net amount must be equal to total amount');
933 // Form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
934 if ($self->_id
&& $self->_values
['contribution_status_id'] != $fields['contribution_status_id']) {
935 CRM_Contribute_BAO_Contribution
::checkStatusValidation($self->_values
, $fields, $errors);
937 // CRM-16015, add form-rule to restrict change of financial type if using price field of different financial type
938 if ($self->_id
&& $self->_values
['financial_type_id'] != $fields['financial_type_id']) {
939 CRM_Contribute_BAO_Contribution
::checkFinancialTypeChange(NULL, $self->_id
, $errors);
941 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
942 if (!empty($fields['fee_amount']) && !empty($fields['financial_type_id']) && $financialType = CRM_Contribute_BAO_Contribution
::validateFinancialType($fields['financial_type_id'])) {
943 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
946 // $trxn_id must be unique CRM-13919
947 if (!empty($fields['trxn_id'])) {
948 $queryParams = array(1 => array($fields['trxn_id'], 'String'));
949 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
951 $queryParams[2] = array((int) $self->_id
, 'Integer');
952 $query .= ' and id !=%2';
954 $tCnt = CRM_Core_DAO
::singleValueQuery($query, $queryParams);
956 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', array(1 => $fields['trxn_id']));
960 $errors = array_merge($errors, $softErrors);
965 * Process the form submission.
967 public function postProcess() {
968 if ($this->_action
& CRM_Core_Action
::DELETE
) {
969 CRM_Contribute_BAO_Contribution
::deleteContribution($this->_id
);
970 CRM_Core_Session
::singleton()->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
971 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
976 // Get the submitted form values.
977 $submittedValues = $this->controller
->exportValues($this->_name
);
978 $contribution = $this->submit($submittedValues, $this->_action
, $this->_ppID
);
979 $session = CRM_Core_Session
::singleton();
980 $buttonName = $this->controller
->getButtonName();
981 if ($this->_context
== 'standalone') {
982 if ($buttonName == $this->getButtonName('upload', 'new')) {
983 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contribute/add',
984 'reset=1&action=add&context=standalone'
988 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
989 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
993 elseif ($this->_context
== 'contribution' && $this->_mode
&& $buttonName == $this->getButtonName('upload', 'new')) {
994 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
995 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
998 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
999 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
1000 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
1004 //store contribution ID if not yet set (on create)
1005 if (empty($this->_id
) && !empty($contribution->id
)) {
1006 $this->_id
= $contribution->id
;
1011 * Process credit card payment.
1013 * @param array $submittedValues
1014 * @param array $lineItem
1016 * @return bool|\CRM_Contribute_DAO_Contribution
1018 protected function processCreditCard($submittedValues, $lineItem) {
1019 $sendReceipt = $contribution = FALSE;
1021 $unsetParams = array(
1023 'payment_instrument_id',
1024 'contribution_status_id',
1028 foreach ($unsetParams as $key) {
1029 if (isset($submittedValues[$key])) {
1030 unset($submittedValues[$key]);
1033 $isTest = ($this->_mode
== 'test') ?
1 : 0;
1034 // CRM-12680 set $_lineItem if its not set
1035 if (empty($this->_lineItem
) && !empty($lineItem)) {
1036 $this->_lineItem
= $lineItem;
1039 //Get the require fields value only.
1040 $params = $this->_params
= $submittedValues;
1042 $this->_paymentProcessor
= CRM_Financial_BAO_PaymentProcessor
::getPayment($this->_params
['payment_processor_id'],
1046 // Get the payment processor id as per mode.
1047 $this->_params
['payment_processor'] = $params['payment_processor_id']
1048 = $this->_params
['payment_processor_id'] = $submittedValues['payment_processor_id'] = $this->_paymentProcessor
['id'];
1050 $now = date('YmdHis');
1053 // we need to retrieve email address
1054 if ($this->_context
== 'standalone' && !empty($submittedValues['is_email_receipt'])) {
1055 list($this->userDisplayName
,
1057 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
1058 $this->assign('displayName', $this->userDisplayName
);
1061 // Set email for primary location.
1062 $fields['email-Primary'] = 1;
1063 $params['email-Primary'] = $this->userEmail
;
1065 // now set the values for the billing location.
1066 foreach (array_keys($this->_fields
) as $name) {
1070 // also add location name to the array
1071 $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);
1073 $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
1074 $fields["address_name-{$this->_bltID}"] = 1;
1075 $ctype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
1080 $nameFields = array('first_name', 'middle_name', 'last_name');
1081 foreach ($nameFields as $name) {
1083 if (array_key_exists("billing_$name", $params)) {
1084 $params[$name] = $params["billing_{$name}"];
1085 $params['preserveDBName'] = TRUE;
1089 if (!empty($params['source'])) {
1090 unset($params['source']);
1092 $contactID = CRM_Contact_BAO_Contact
::createProfileContact($params, $fields,
1098 // add all the additional payment params we need
1099 if (!empty($this->_params
["billing_state_province_id-{$this->_bltID}"])) {
1100 $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}"]);
1102 if (!empty($this->_params
["billing_country_id-{$this->_bltID}"])) {
1103 $this->_params
["country-{$this->_bltID}"] = $this->_params
["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant
::countryIsoCode($this->_params
["billing_country_id-{$this->_bltID}"]);
1105 $legacyCreditCardExpiryCheck = FALSE;
1106 if ($this->_paymentProcessor
['payment_type'] & CRM_Core_Payment
::PAYMENT_TYPE_CREDIT_CARD
&& !isset($this->_paymentFields
)) {
1107 $legacyCreditCardExpiryCheck = TRUE;
1109 if ($legacyCreditCardExpiryCheck ||
in_array('credit_card_exp_date', array_keys($this->_paymentFields
))) {
1110 $this->_params
['year'] = CRM_Core_Payment_Form
::getCreditCardExpirationYear($this->_params
);
1111 $this->_params
['month'] = CRM_Core_Payment_Form
::getCreditCardExpirationMonth($this->_params
);
1113 $this->_params
['ip_address'] = CRM_Utils_System
::ipAddress();
1114 $this->_params
['amount'] = $this->_params
['total_amount'];
1115 $this->_params
['amount_level'] = 0;
1116 $this->_params
['description'] = ts('Office Credit Card contribution');
1117 $this->_params
['currencyID'] = CRM_Utils_Array
::value('currency',
1119 CRM_Core_Config
::singleton()->defaultCurrency
1121 $this->_params
['payment_action'] = 'Sale';
1122 if (!empty($this->_params
['receive_date'])) {
1123 $this->_params
['receive_date'] = CRM_Utils_Date
::processDate($this->_params
['receive_date'], $this->_params
['receive_date_time']);
1126 if (!empty($params['soft_credit_to'])) {
1127 $this->_params
['soft_credit_to'] = $params['soft_credit_to'];
1128 $this->_params
['pcp_made_through_id'] = $params['pcp_made_through_id'];
1131 $this->_params
['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $params);
1132 $this->_params
['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $params);
1133 $this->_params
['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $params);
1135 //Add common data to formatted params
1136 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
1138 if (empty($this->_params
['invoice_id'])) {
1139 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
1142 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
1145 // At this point we've created a contact and stored its address etc
1146 // all the payment processors expect the name and address to be in the
1147 // so we copy stuff over to first_name etc.
1148 $paymentParams = $this->_params
;
1149 $paymentParams['contactID'] = $this->_contactID
;
1150 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
1152 $contributionType = new CRM_Financial_DAO_FinancialType();
1153 $contributionType->id
= $params['financial_type_id'];
1155 // Add some financial type details to the params list
1156 // if folks need to use it.
1157 $paymentParams['contributionType_name'] = $this->_params
['contributionType_name'] = $contributionType->name
;
1158 $paymentParams['contributionPageID'] = NULL;
1160 if (!empty($this->_params
['is_email_receipt'])) {
1161 $paymentParams['email'] = $this->userEmail
;
1162 $paymentParams['is_email_receipt'] = 1;
1165 $paymentParams['is_email_receipt'] = 0;
1166 $this->_params
['is_email_receipt'] = 0;
1168 if (!empty($this->_params
['receive_date'])) {
1169 $paymentParams['receive_date'] = $this->_params
['receive_date'];
1172 // For recurring contribution, create Contribution Record first.
1173 // Contribution ID, Recurring ID and Contact ID needed
1174 // When we get a callback from the payment processor, CRM-7115
1176 if (!empty($paymentParams['is_recur'])) {
1177 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processContribution($this,
1187 $paymentParams['contributionID'] = $contribution->id
;
1188 $paymentParams['contributionTypeID'] = $contribution->financial_type_id
;
1189 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
1190 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1193 if ($paymentParams['amount'] > 0.0) {
1194 // force a re-get of the payment processor in case the form changed it, CRM-7179
1195 $payment = CRM_Core_Payment
::singleton($this->_mode
, $this->_paymentProcessor
, $this, TRUE);
1197 $result = $payment->doPayment($paymentParams, 'contribute');
1199 catch (CRM_Core_Exception
$e) {
1200 $message = ts("Payment Processor Error message") . $e->getMessage();
1201 $this->cleanupDBAfterPaymentFailure($paymentParams, $message);
1202 // Set the contribution mode.
1203 $urlParams = "action=add&cid={$this->_contactID}";
1205 $urlParams .= "&mode={$this->_mode}";
1207 if (!empty($this->_ppID
)) {
1208 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
1210 CRM_Core_Error
::statusBounce($message, $urlParams, ts('Payment Processor Error'));
1214 $this->_params
= array_merge($this->_params
, $result);
1216 $this->_params
['receive_date'] = $now;
1218 if (!empty($this->_params
['is_email_receipt'])) {
1219 $this->_params
['receipt_date'] = $now;
1222 $this->_params
['receipt_date'] = CRM_Utils_Date
::processDate($this->_params
['receipt_date'],
1223 $params['receipt_date_time'], TRUE
1227 $this->set('params', $this->_params
);
1228 $this->assign('trxn_id', $result['trxn_id']);
1229 $this->assign('receive_date', $this->_params
['receive_date']);
1231 // Result has all the stuff we need
1232 // lets archive it to a financial transaction
1233 if ($contributionType->is_deductible
) {
1234 $this->assign('is_deductible', TRUE);
1235 $this->set('is_deductible', TRUE);
1238 // Set source if not set
1239 if (empty($this->_params
['source'])) {
1240 $userID = CRM_Core_Session
::singleton()->get('userID');
1241 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1244 $this->_params
['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
1247 // Build custom data getFields array
1248 $customFieldsContributionType = CRM_Core_BAO_CustomField
::getFields('Contribution', FALSE, FALSE,
1249 CRM_Utils_Array
::value('financial_type_id', $params)
1251 $customFields = CRM_Utils_Array
::crmArrayMerge($customFieldsContributionType,
1252 CRM_Core_BAO_CustomField
::getFields('Contribution', FALSE, FALSE, NULL, NULL, TRUE)
1254 $params['custom'] = CRM_Core_BAO_CustomField
::postProcess($params,
1259 if (empty($paymentParams['is_recur'])) {
1260 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processContribution($this,
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'] = $this->_contactID
;
1275 $this->_params
['contribution_id'] = $contribution->id
;
1276 $sendReceipt = CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $this->_params
, TRUE);
1280 if ($contribution->id
&& isset($params['note'])) {
1281 CRM_Contribute_Form_AdditionalInfo
::processNote($params, $contactID, $contribution->id
, NULL);
1284 if ($contribution->id
&& isset($params['product_name'][0])) {
1285 CRM_Contribute_Form_AdditionalInfo
::processPremium($params, $contribution->id
, NULL, $this->_options
);
1288 if ($contribution->id
) {
1289 $statusMsg = ts('The contribution record has been processed.');
1290 if (!empty($this->_params
['is_email_receipt']) && $sendReceipt) {
1291 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
1293 CRM_Core_Session
::setStatus($statusMsg, ts('Complete'), 'success');
1295 return $contribution;
1299 * Clean up DB after payment fails.
1301 * This function removes related DB entries. Note that it has been agreed in principle,
1302 * but not implemented, that contributions should be retained as 'Failed' rather than
1305 * @todo it doesn't clean up line items.
1307 * @param array $paymentParams
1308 * @param string $message
1310 public function cleanupDBAfterPaymentFailure($paymentParams, $message) {
1311 // Make sure to cleanup db for recurring case.
1312 if (!empty($paymentParams['contributionID'])) {
1313 CRM_Core_Error
::debug_log_message($message .
1314 "contact id={$this->_contactID} (deleting contribution {$paymentParams['contributionID']}");
1315 CRM_Contribute_BAO_Contribution
::deleteContribution($paymentParams['contributionID']);
1317 if (!empty($paymentParams['contributionRecurID'])) {
1318 CRM_Core_Error
::debug_log_message($message .
1319 "contact id={$this->_contactID} (deleting recurring contribution {$paymentParams['contributionRecurID']}");
1320 CRM_Contribute_BAO_ContributionRecur
::deleteRecurContribution($paymentParams['contributionRecurID']);
1325 * Generate the data to construct a snippet based pane.
1327 * This form also assigns the showAdditionalInfo var based on historical code.
1328 * This appears to mean 'there is a pane to show'.
1330 * @param string $type
1331 * Type of Pane - this is generally used to determine the function name used to build it
1332 * - e.g CreditCard, AdditionalDetail
1333 * @param array $defaults
1336 * We aim to further refactor & simplify this but currently
1338 * - should additional info be shown?
1340 protected function generatePane($type, $defaults) {
1341 $urlParams = "snippet=4&formType={$type}";
1343 $urlParams .= "&mode={$this->_mode}";
1347 if ($type == 'CreditCard' ||
1348 $type == 'DirectDebit'
1354 'url' => CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams),
1359 // See if we need to include this paneName in the current form.
1360 if ($this->_formType
== $type ||
!empty($_POST["hidden_{$type}"]) ||
1361 CRM_Utils_Array
::value("hidden_{$type}", $defaults)
1363 $this->assign('showAdditionalInfo', TRUE);
1364 $pane['open'] = 'true';
1367 if ($type == 'CreditCard' ||
$type == 'DirectDebit') {
1368 // @todo would be good to align tpl name with form name...
1369 // @todo document why this hidden variable is required.
1370 $this->add('hidden', 'hidden_' . $type, 1);
1374 $additionalInfoFormFunction = 'build' . $type;
1375 CRM_Contribute_Form_AdditionalInfo
::$additionalInfoFormFunction($this);
1381 * Wrapper for unit testing the post process submit function.
1383 * (If we expose through api we can get default additions 'for free').
1385 * @param array $params
1386 * @param int $action
1388 public function testSubmit($params, $action) {
1390 'soft_credit_contact_id' => array(),
1391 'receipt_date' => '',
1392 'receipt_date_time' => '',
1393 'cancel_date' => '',
1394 'cancel_date_time' => '',
1396 if (!empty($params['id'])) {
1397 $existingContribution = civicrm_api3('contribution', 'getsingle', array(
1398 'id' => $params['id'],
1402 $existingContribution = array();
1405 $this->_defaults
['contribution_status_id'] = CRM_Utils_Array
::value('contribution_status_id',
1406 $existingContribution
1409 $this->_defaults
['total_amount'] = CRM_Utils_Array
::value('total_amount',
1410 $existingContribution
1413 $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array
::value('pledge_payment_id', $params));
1417 * @param array $submittedValues
1419 * @param int $action
1421 * - CRM_Core_Action::UPDATE
1423 * @param $pledgePaymentID
1426 * @throws \Exception
1428 protected function submit($submittedValues, $action, $pledgePaymentID) {
1429 $softParams = $softIDs = array();
1430 $pId = $contribution = $isRelatedId = FALSE;
1431 if (!empty($submittedValues['price_set_id']) && $action & CRM_Core_Action
::UPDATE
) {
1432 $line = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution');
1433 $lineID = key($line);
1434 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array
::value('price_field_id', $line[$lineID]), 'price_set_id');
1435 $quickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1437 CRM_Price_BAO_LineItem
::deleteLineItems($this->_id
, 'civicrm_contribution');
1441 // Process price set and get total amount and line items.
1442 $lineItem = array();
1443 $priceSetId = CRM_Utils_Array
::value('price_set_id', $submittedValues);
1444 if (empty($priceSetId) && !$this->_id
) {
1445 $this->_priceSetId
= $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1446 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
1447 $fieldID = key($this->_priceSet
['fields']);
1448 $fieldValueId = key($this->_priceSet
['fields'][$fieldID]['options']);
1449 $this->_priceSet
['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1450 $submittedValues['price_' . $fieldID] = 1;
1454 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
1455 $submittedValues, $lineItem[$priceSetId]);
1457 // Unset tax amount for offline 'is_quick_config' contribution.
1458 if ($this->_priceSet
['is_quick_config'] &&
1459 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant
::getTaxRates())
1461 unset($submittedValues['tax_amount']);
1463 $submittedValues['total_amount'] = CRM_Utils_Array
::value('amount', $submittedValues);
1466 if ($this->_compId
) {
1467 if ($this->_context
== 'participant') {
1468 $pId = $this->_compId
;
1470 elseif ($this->_context
== 'membership') {
1471 $isRelatedId = TRUE;
1474 $pId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id
, 'participant_id', 'contribution_id');
1478 $contributionDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1479 if (array_key_exists('membership', $contributionDetails)) {
1480 $isRelatedId = TRUE;
1482 elseif (array_key_exists('participant', $contributionDetails)) {
1483 $pId = $contributionDetails['participant'];
1487 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id
) {
1488 // CRM-10117 update the line items for participants.
1490 $entityTable = 'participant';
1492 $isRelatedId = FALSE;
1493 $participantParams = array(
1494 'fee_amount' => $submittedValues['total_amount'],
1497 CRM_Event_BAO_Participant
::add($participantParams);
1498 if (empty($this->_lineItems
)) {
1499 $this->_lineItems
[] = CRM_Price_BAO_LineItem
::getLineItems($entityID, 'participant', 1);
1503 $entityTable = 'contribution';
1504 $entityID = $this->_id
;
1507 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, $entityTable, NULL, TRUE, $isRelatedId);
1508 foreach (array_keys($lineItems) as $id) {
1509 $lineItems[$id]['id'] = $id;
1511 $itemId = key($lineItems);
1512 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1513 $this->_priceSetId
= CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1516 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1517 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule
::cleanMoney(CRM_Utils_Array
::value('total_amount', $submittedValues));
1519 // Update line total and total amount with tax on edit.
1520 $financialItemsId = CRM_Core_PseudoConstant
::getTaxRates();
1521 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1522 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1525 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1526 $submittedValues['tax_amount'] = 'null';
1528 if ($lineItems[$itemId]['tax_rate']) {
1529 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total'];
1530 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] +
$lineItems[$itemId]['tax_amount'];
1531 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1534 // CRM-10117 update the line items for participants.
1535 if (!empty($lineItems[$itemId]['price_field_id'])) {
1536 $lineItem[$this->_priceSetId
] = $lineItems;
1541 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1544 //CRM-11529 for quick config back office transactions
1545 //when financial_type_id is passed in form, update the
1546 //line items with the financial type selected in form
1547 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array
::value($this->_priceSetId
, $lineItem)
1549 foreach ($lineItem[$this->_priceSetId
] as &$values) {
1550 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1554 if (!isset($submittedValues['total_amount'])) {
1555 $submittedValues['total_amount'] = CRM_Utils_Array
::value('total_amount', $this->_values
);
1557 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
1559 if (!empty($submittedValues['pcp_made_through_id'])) {
1562 'pcp_made_through_id',
1563 'pcp_display_in_roll',
1564 'pcp_roll_nickname',
1565 'pcp_personal_note',
1567 foreach ($fields as $f) {
1568 $pcp[$f] = CRM_Utils_Array
::value($f, $submittedValues);
1572 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
1573 if ($this->_id
&& count($isEmpty) == 1 && key($isEmpty) == NULL) {
1574 //Delete existing soft credit records if soft credit list is empty on update
1575 CRM_Contribute_BAO_ContributionSoft
::del(array('contribution_id' => $this->_id
));
1578 //build soft credit params
1579 foreach ($submittedValues['soft_credit_contact_id'] as $key => $val) {
1580 if ($val && $submittedValues['soft_credit_amount'][$key]) {
1581 $softParams[$key]['contact_id'] = $val;
1582 $softParams[$key]['amount'] = CRM_Utils_Rule
::cleanMoney($submittedValues['soft_credit_amount'][$key]);
1583 $softParams[$key]['soft_credit_type_id'] = $submittedValues['soft_credit_type'][$key];
1584 if (!empty($submittedValues['soft_credit_id'][$key])) {
1585 $softIDs[] = $softParams[$key]['id'] = $submittedValues['soft_credit_id'][$key];
1591 // set the contact, when contact is selected
1592 if (!empty($submittedValues['contact_id'])) {
1593 $this->_contactID
= $submittedValues['contact_id'];
1596 // Credit Card Contribution.
1598 $contribution = $this->processCreditCard($submittedValues, $lineItem);
1601 // Offline Contribution.
1602 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1604 // get the required field value only.
1605 $formValues = $submittedValues;
1606 $params = $ids = array();
1608 $params['contact_id'] = $this->_contactID
;
1610 $params['currency'] = $this->getCurrency($submittedValues);
1613 'financial_type_id',
1614 'contribution_status_id',
1615 'payment_instrument_id',
1620 foreach ($fields as $f) {
1621 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1625 $params['pcp'] = $pcp;
1627 if (!empty($softParams)) {
1628 $params['soft_credit'] = $softParams;
1629 $params['soft_credit_ids'] = $softIDs;
1632 // CRM-5740 if priceset is used, no need to cleanup money.
1634 $params['skipCleanMoney'] = 1;
1643 foreach ($dates as $d) {
1644 $params[$d] = CRM_Utils_Date
::processDate($formValues[$d], $formValues[$d . '_time'], TRUE);
1647 if (!empty($formValues['is_email_receipt'])) {
1648 $params['receipt_date'] = date("Y-m-d");
1651 if ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Cancelled', 'name')
1652 ||
$params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name')
1654 if (CRM_Utils_System
::isNull(CRM_Utils_Array
::value('cancel_date', $params))) {
1655 $params['cancel_date'] = date('Y-m-d');
1659 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1662 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1663 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1664 if ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Pending', 'name')) {
1665 $params['is_pay_later'] = 1;
1667 elseif ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name')) {
1668 $params['is_pay_later'] = 0;
1671 $ids['contribution'] = $params['id'] = $this->_id
;
1673 // Add Additional common information to formatted params.
1674 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($formValues, $params, $this);
1676 $params['contribution_mode'] = 'participant';
1677 $params['participant_id'] = $pId;
1678 $params['skipLineItem'] = 1;
1680 elseif ($isRelatedId) {
1681 $params['contribution_mode'] = 'membership';
1683 $params['line_item'] = $lineItem;
1684 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array
::value('id', $this->_paymentProcessor
);
1685 if (isset($submittedValues['tax_amount'])) {
1686 $params['tax_amount'] = $submittedValues['tax_amount'];
1688 //create contribution.
1689 if ($isQuickConfig) {
1690 $params['is_quick_config'] = 1;
1694 // if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1695 // if non_deductible_amount does NOT exist - then calculate it depending on:
1696 // $ContributionType->is_deductible and whether there is a product (premium).
1697 if (empty($params['non_deductible_amount'])) {
1698 $contributionType = new CRM_Financial_DAO_FinancialType();
1699 $contributionType->id
= $params['financial_type_id'];
1700 if (!$contributionType->find(TRUE)) {
1701 CRM_Core_Error
::fatal('Could not find a system table');
1703 if ($contributionType->is_deductible
) {
1705 if (isset($formValues['product_name'][0])) {
1706 $selectProduct = $formValues['product_name'][0];
1708 // if there is a product - compare the value to the contribution amount
1709 if (isset($selectProduct)) {
1710 $productDAO = new CRM_Contribute_DAO_Product();
1711 $productDAO->id
= $selectProduct;
1712 $productDAO->find(TRUE);
1713 // product value exceeds contribution amount
1714 if ($params['total_amount'] < $productDAO->price
) {
1715 $params['non_deductible_amount'] = $params['total_amount'];
1717 // product value does NOT exceed contribution amount
1719 $params['non_deductible_amount'] = $productDAO->price
;
1722 // contribution is deductible - but there is no product
1724 $params['non_deductible_amount'] = '0.00';
1727 // contribution is NOT deductible
1729 $params['non_deductible_amount'] = $params['total_amount'];
1733 $contribution = CRM_Contribute_BAO_Contribution
::create($params, $ids);
1735 // process associated membership / participant, CRM-4395
1736 $relatedComponentStatusMsg = NULL;
1737 if ($contribution->id
&& $action & CRM_Core_Action
::UPDATE
) {
1738 $relatedComponentStatusMsg = $this->updateRelatedComponent($contribution->id
,
1739 $contribution->contribution_status_id
,
1740 CRM_Utils_Array
::value('contribution_status_id',
1743 $contribution->receive_date
1748 if ($contribution->id
&& isset($formValues['note'])) {
1749 CRM_Contribute_Form_AdditionalInfo
::processNote($formValues, $this->_contactID
, $contribution->id
, $this->_noteID
);
1753 if ($contribution->id
&& isset($formValues['product_name'][0])) {
1754 CRM_Contribute_Form_AdditionalInfo
::processPremium($formValues, $contribution->id
,
1755 $this->_premiumID
, $this->_options
1758 $statusMsg = ts('The contribution record has been saved.');
1760 // assign tax calculation for contribution receipts
1762 $getTaxDetails = FALSE;
1763 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
1764 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
1766 if ($action & CRM_Core_Action
::ADD
) {
1769 elseif ($action & CRM_Core_Action
::UPDATE
) {
1770 $line = $this->_lineItems
;
1772 foreach ($line as $key => $value) {
1773 foreach ($value as $v) {
1774 if (isset($taxRate[(string) CRM_Utils_Array
::value('tax_rate', $v)])) {
1775 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $v);
1778 if (isset($v['tax_rate'])) {
1779 $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $v);
1780 $getTaxDetails = TRUE;
1788 if ($action & CRM_Core_Action
::UPDATE
) {
1789 if (isset($submittedValues['tax_amount'])) {
1790 $totalTaxAmount = $submittedValues['tax_amount'];
1793 $totalTaxAmount = $this->_values
['tax_amount'];
1795 $this->assign('totalTaxAmount', $totalTaxAmount);
1796 $this->assign('dataArray', $taxRate);
1799 if (!empty($submittedValues['price_set_id'])) {
1800 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1801 $this->assign('getTaxDetails', $getTaxDetails);
1802 $this->assign('dataArray', $taxRate);
1803 $this->assign('taxTerm', CRM_Utils_Array
::value('tax_term', $invoiceSettings));
1806 $this->assign('totalTaxAmount', CRM_Utils_Array
::value('tax_amount', $submittedValues));
1811 //send receipt mail.
1812 if ($contribution->id
&& !empty($formValues['is_email_receipt'])) {
1813 $formValues['contact_id'] = $this->_contactID
;
1814 $formValues['contribution_id'] = $contribution->id
;
1816 $formValues +
= CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
);
1818 // to get 'from email id' for send receipt
1819 $this->fromEmailId
= $formValues['from_email_address'];
1820 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $formValues)) {
1821 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
1825 if ($relatedComponentStatusMsg) {
1826 $statusMsg .= ' ' . $relatedComponentStatusMsg;
1829 CRM_Core_Session
::setStatus($statusMsg, ts('Saved'), 'success');
1830 //Offline Contribution ends.
1833 CRM_Contribute_BAO_Contribution
::updateRelatedPledge(
1837 (CRM_Utils_Array
::value('option_type', $formValues) == 2) ?
TRUE : FALSE,
1838 $formValues['total_amount'],
1839 $this->_defaults
['total_amount'],
1840 $formValues['contribution_status_id'],
1841 $this->_defaults
['contribution_status_id']
1843 return $contribution;