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);
491 //tax rate from financialType
492 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant
::getTaxRates()));
493 $this->assign('currencies', json_encode(CRM_Core_OptionGroup
::values('currencies_enabled')));
495 // build price set form.
496 $buildPriceSet = FALSE;
497 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
498 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
499 $this->assign('invoicing', $invoicing);
501 // display tax amount on edit contribution page
502 if ($invoicing && $this->_action
& CRM_Core_Action
::UPDATE
&& isset($this->_values
['tax_amount'])) {
503 $this->assign('totalTaxAmount', $this->_values
['tax_amount']);
506 if (empty($this->_lineItems
) &&
507 ($this->_priceSetId ||
!empty($_POST['price_set_id']))
509 $buildPriceSet = TRUE;
510 $getOnlyPriceSetElements = TRUE;
511 if (!$this->_priceSetId
) {
512 $this->_priceSetId
= $_POST['price_set_id'];
513 $getOnlyPriceSetElements = FALSE;
516 $this->set('priceSetId', $this->_priceSetId
);
517 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
519 // get only price set form elements.
520 if ($getOnlyPriceSetElements) {
524 // use to build form during form rule.
525 $this->assign('buildPriceSet', $buildPriceSet);
527 $showAdditionalInfo = FALSE;
529 $defaults = $this->_values
;
530 $additionalDetailFields = array(
534 'non_deductible_amount',
538 foreach ($additionalDetailFields as $key) {
539 if (!empty($defaults[$key])) {
540 $defaults['hidden_AdditionalDetail'] = 1;
545 if ($this->_productDAO
) {
546 if ($this->_productDAO
->product_id
) {
547 $defaults['hidden_Premium'] = 1;
551 if ($this->_noteID
&&
552 isset($this->_values
['note'])
554 $defaults['hidden_AdditionalDetail'] = 1;
558 ts('Additional Details') => 'AdditionalDetail',
561 //Add Premium pane only if Premium is exists.
562 $dao = new CRM_Contribute_DAO_Product();
565 if ($dao->find(TRUE)) {
566 $paneNames[ts('Premium Information')] = 'Premium';
569 $billingPanes = array();
571 if (CRM_Core_Payment_Form
::buildPaymentForm($this, $this->_paymentProcessor
, FALSE) == TRUE) {
572 $buildRecurBlock = TRUE;
573 foreach ($this->billingPane
as $name => $label) {
574 if (!empty($this->billingFieldSets
[$name]['fields'])) {
575 // @todo reduce variation so we don't have to convert 'credit_card' to 'CreditCard'
576 $billingPanes[$label] = $this->generatePane(CRM_Utils_String
::convertStringToCamel($name), $defaults);
582 foreach ($paneNames as $name => $type) {
583 $allPanes[$name] = $this->generatePane($type, $defaults);
585 if (empty($this->_recurPaymentProcessors
)) {
586 $buildRecurBlock = FALSE;
588 if ($buildRecurBlock) {
589 CRM_Contribute_Form_Contribution_Main
::buildRecur($this);
590 $this->setDefaults(array('is_recur' => 0));
592 $this->assign('buildRecurBlock', $buildRecurBlock);
593 $qfKey = $this->controller
->_key
;
594 $this->assign('qfKey', $qfKey);
595 $this->assign('billingPanes', $billingPanes);
596 $this->assign('allPanes', $allPanes);
598 $this->addFormRule(array('CRM_Contribute_Form_Contribution', 'formRule'), $this);
600 if ($this->_formType
) {
601 $this->assign('formType', $this->_formType
);
605 $this->applyFilter('__ALL__', 'trim');
607 if ($this->_action
& CRM_Core_Action
::DELETE
) {
608 $this->addButtons(array(
611 'name' => ts('Delete'),
612 'spacing' => ' ',
617 'name' => ts('Cancel'),
624 //need to assign custom data type and subtype to the template
625 $this->assign('customDataType', 'Contribution');
626 $this->assign('customDataSubType', $this->_contributionType
);
627 $this->assign('entityID', $this->_id
);
629 if ($this->_context
== 'standalone') {
630 $this->addEntityRef('contact_id', ts('Contact'), array(
632 'api' => array('extra' => array('email')),
636 $attributes = CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Contribution');
638 $financialType = $this->add('select', 'financial_type_id',
639 ts('Financial Type'),
640 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::financialType(),
642 array('onChange' => "CRM.buildCustomData( 'Contribution', this.value );")
644 $paymentInstrument = FALSE;
646 $paymentInstrument = $this->add('select', 'payment_instrument_id',
648 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::paymentInstrument(),
649 TRUE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
653 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), array('class' => 'twelve') +
$attributes['trxn_id']);
655 //add receipt for offline contribution
656 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
658 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
660 $status = CRM_Contribute_PseudoConstant
::contributionStatus();
662 // suppressing contribution statuses that are NOT relevant to pledges (CRM-5169)
663 $statusName = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
670 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
673 elseif ((!$this->_ppID
&& $this->_id
) ||
!$this->_id
) {
674 $suppressFlag = FALSE;
676 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
677 if (CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails)) {
678 $suppressFlag = TRUE;
681 if (!$suppressFlag) {
686 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
690 unset($status[CRM_Utils_Array
::key('Overdue', $statusName)]);
695 $contributionStatus = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_id
, 'contribution_status_id');
696 $name = CRM_Utils_Array
::value($contributionStatus, $statusName);
701 unset($status[CRM_Utils_Array
::key('In Progress', $statusName)]);
702 unset($status[CRM_Utils_Array
::key('Pending', $statusName)]);
703 unset($status[CRM_Utils_Array
::key('Failed', $statusName)]);
708 unset($status[CRM_Utils_Array
::key('Refunded', $statusName)]);
719 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
725 unset($status[CRM_Utils_Array
::key('Refunded', $statusName)]);
728 $this->add('select', 'contribution_status_id',
729 ts('Contribution Status'),
735 $this->addDateTime('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
737 if ($this->_online
) {
738 $this->assign('hideCalender', TRUE);
740 $checkNumber = $this->add('text', 'check_number', ts('Check Number'), $attributes['check_number']);
742 $this->addDateTime('receipt_date', ts('Receipt Date'), FALSE, array('formatType' => 'activityDateTime'));
743 $this->addDateTime('cancel_date', ts('Cancelled / Refunded Date'), FALSE, array('formatType' => 'activityDateTime'));
745 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
748 if ($buildRecurBlock) {
749 $recurJs = array('onChange' => "buildRecurBlock( this.value ); return false;");
751 $element = $this->add('select',
752 'payment_processor_id',
753 ts('Payment Processor'),
759 if ($this->_online
) {
763 if (empty($this->_lineItems
)) {
764 $buildPriceSet = FALSE;
765 $priceSets = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute');
766 if (!empty($priceSets) && !$this->_ppID
) {
767 $buildPriceSet = TRUE;
770 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
771 // and if we already have line items for that participant. CRM-5095
772 if ($buildPriceSet && $this->_id
) {
773 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
774 $pledgePaymentId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
779 if ($pledgePaymentId) {
780 $buildPriceSet = FALSE;
782 if ($participantID = CRM_Utils_Array
::value('participant', $componentDetails)) {
783 $participantLI = CRM_Price_BAO_LineItem
::getLineItems($participantID);
784 if (!CRM_Utils_System
::isNull($participantLI)) {
785 $buildPriceSet = FALSE;
790 $hasPriceSets = FALSE;
791 if ($buildPriceSet) {
792 $hasPriceSets = TRUE;
793 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
795 '' => ts('Choose price set'),
797 NULL, array('onchange' => "buildAmount( this.value );")
799 if ($this->_online
&& !($this->_action
& CRM_Core_Action
::UPDATE
)) {
803 $this->assign('hasPriceSets', $hasPriceSets);
804 $currencyFreeze = FALSE;
805 if (!($this->_action
& CRM_Core_Action
::UPDATE
)) {
806 if ($this->_online ||
$this->_ppID
) {
807 $attributes['total_amount'] = array_merge($attributes['total_amount'], array(
809 'style' => "background-color:#EBECE4",
811 $optionTypes = array(
812 '1' => ts('Adjust Pledge Payment Schedule?'),
813 '2' => ts('Adjust Total Pledge Amount?'),
815 $this->addRadio('option_type',
821 $currencyFreeze = TRUE;
825 $totalAmount = $this->addMoney('total_amount',
827 ($hasPriceSets) ?
FALSE : TRUE,
828 $attributes['total_amount'],
829 TRUE, 'currency', NULL, $currencyFreeze
833 $this->add('text', 'source', ts('Source'), CRM_Utils_Array
::value('source', $attributes));
835 // CRM-7362 --add campaigns.
836 CRM_Campaign_BAO_Campaign
::addCampaign($this, CRM_Utils_Array
::value('campaign_id', $this->_values
));
838 CRM_Contribute_Form_SoftCredit
::buildQuickForm($this);
842 $js = array('onclick' => "return verify( );");
845 $mailingInfo = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
848 $this->assign('outBound_option', $mailingInfo['outBound_option']);
850 $this->addButtons(array(
853 'name' => ts('Save'),
859 'name' => ts('Save and New'),
865 'name' => ts('Cancel'),
870 // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
871 // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
872 if ($this->_id
&& $this->_values
['contribution_status_id'] == array_search('Cancelled', $statusName)) {
874 $totalAmount->freeze();
876 $checkNumber->freeze();
877 $paymentInstrument->freeze();
879 $financialType->freeze();
882 // if contribution is related to membership or participant freeze Financial Type, Amount
883 if ($this->_id
&& isset($this->_values
['tax_amount'])) {
884 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
885 if (CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails)) {
887 $totalAmount->freeze();
889 $financialType->freeze();
890 $this->assign('freezeFinancialType', TRUE);
894 if ($this->_action
& CRM_Core_Action
::VIEW
) {
902 * @param array $fields
903 * The input form values.
904 * @param array $files
905 * The uploaded files if any.
909 * true if no errors, else array of errors
911 public static function formRule($fields, $files, $self) {
914 // Check for Credit Card Contribution.
916 if (empty($fields['payment_processor_id'])) {
917 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
920 // validate payment instrument (e.g. credit card number)
921 CRM_Core_Payment_Form
::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, $self);
925 // Do the amount validations.
926 if (empty($fields['total_amount']) && empty($self->_lineItems
)) {
927 if ($priceSetId = CRM_Utils_Array
::value('price_set_id', $fields)) {
928 CRM_Price_BAO_PriceField
::priceSetValidation($priceSetId, $fields, $errors);
932 $softErrors = CRM_Contribute_Form_SoftCredit
::formRule($fields, $errors, $self);
934 if (!empty($fields['total_amount']) && (!empty($fields['net_amount']) ||
!empty($fields['fee_amount']))) {
935 $sum = CRM_Utils_Rule
::cleanMoney($fields['net_amount']) + CRM_Utils_Rule
::cleanMoney($fields['fee_amount']);
936 if (CRM_Utils_Rule
::cleanMoney($fields['total_amount']) != $sum) {
937 $errors['total_amount'] = ts('The sum of fee amount and net amount must be equal to total amount');
940 // Form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
941 if ($self->_id
&& $self->_values
['contribution_status_id'] != $fields['contribution_status_id']) {
942 CRM_Contribute_BAO_Contribution
::checkStatusValidation($self->_values
, $fields, $errors);
944 // CRM-16015, add form-rule to restrict change of financial type if using price field of different financial type
945 if ($self->_id
&& $self->_values
['financial_type_id'] != $fields['financial_type_id']) {
946 CRM_Contribute_BAO_Contribution
::checkFinancialTypeChange(NULL, $self->_id
, $errors);
948 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
949 if (!empty($fields['fee_amount']) && !empty($fields['financial_type_id']) && $financialType = CRM_Contribute_BAO_Contribution
::validateFinancialType($fields['financial_type_id'])) {
950 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
953 // $trxn_id must be unique CRM-13919
954 if (!empty($fields['trxn_id'])) {
955 $queryParams = array(1 => array($fields['trxn_id'], 'String'));
956 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
958 $queryParams[2] = array((int) $self->_id
, 'Integer');
959 $query .= ' and id !=%2';
961 $tCnt = CRM_Core_DAO
::singleValueQuery($query, $queryParams);
963 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', array(1 => $fields['trxn_id']));
967 $errors = array_merge($errors, $softErrors);
972 * Process the form submission.
974 public function postProcess() {
975 if ($this->_action
& CRM_Core_Action
::DELETE
) {
976 CRM_Contribute_BAO_Contribution
::deleteContribution($this->_id
);
977 CRM_Core_Session
::singleton()->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
978 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
983 // Get the submitted form values.
984 $submittedValues = $this->controller
->exportValues($this->_name
);
985 $contribution = $this->submit($submittedValues, $this->_action
, $this->_ppID
);
986 $session = CRM_Core_Session
::singleton();
987 $buttonName = $this->controller
->getButtonName();
988 if ($this->_context
== 'standalone') {
989 if ($buttonName == $this->getButtonName('upload', 'new')) {
990 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contribute/add',
991 'reset=1&action=add&context=standalone'
995 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
996 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1000 elseif ($this->_context
== 'contribution' && $this->_mode
&& $buttonName == $this->getButtonName('upload', 'new')) {
1001 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
1002 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
1005 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1006 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
1007 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
1011 //store contribution ID if not yet set (on create)
1012 if (empty($this->_id
) && !empty($contribution->id
)) {
1013 $this->_id
= $contribution->id
;
1018 * Process credit card payment.
1020 * @param array $submittedValues
1021 * @param array $lineItem
1023 * @throws CRM_Core_Exception
1025 protected function processCreditCard($submittedValues, $lineItem, $pledgePaymentID) {
1026 $sendReceipt = $contribution = FALSE;
1028 $unsetParams = array(
1030 'payment_instrument_id',
1031 'contribution_status_id',
1035 foreach ($unsetParams as $key) {
1036 if (isset($submittedValues[$key])) {
1037 unset($submittedValues[$key]);
1040 $isTest = ($this->_mode
== 'test') ?
1 : 0;
1041 // CRM-12680 set $_lineItem if its not set
1042 if (empty($this->_lineItem
) && !empty($lineItem)) {
1043 $this->_lineItem
= $lineItem;
1046 //Get the require fields value only.
1047 $params = $this->_params
= $submittedValues;
1049 $this->_paymentProcessor
= CRM_Financial_BAO_PaymentProcessor
::getPayment($this->_params
['payment_processor_id'],
1053 // Get the payment processor id as per mode.
1054 $this->_params
['payment_processor'] = $params['payment_processor_id']
1055 = $this->_params
['payment_processor_id'] = $submittedValues['payment_processor_id'] = $this->_paymentProcessor
['id'];
1057 $now = date('YmdHis');
1060 // we need to retrieve email address
1061 if ($this->_context
== 'standalone' && !empty($submittedValues['is_email_receipt'])) {
1062 list($this->userDisplayName
,
1064 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
1065 $this->assign('displayName', $this->userDisplayName
);
1068 // Set email for primary location.
1069 $fields['email-Primary'] = 1;
1070 $params['email-Primary'] = $this->userEmail
;
1072 // now set the values for the billing location.
1073 foreach (array_keys($this->_fields
) as $name) {
1077 // also add location name to the array
1078 $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);
1080 $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
1081 $fields["address_name-{$this->_bltID}"] = 1;
1082 $ctype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
1087 $nameFields = array('first_name', 'middle_name', 'last_name');
1088 foreach ($nameFields as $name) {
1090 if (array_key_exists("billing_$name", $params)) {
1091 $params[$name] = $params["billing_{$name}"];
1092 $params['preserveDBName'] = TRUE;
1096 if (!empty($params['source'])) {
1097 unset($params['source']);
1099 $contactID = CRM_Contact_BAO_Contact
::createProfileContact($params, $fields,
1105 // add all the additional payment params we need
1106 if (!empty($this->_params
["billing_state_province_id-{$this->_bltID}"])) {
1107 $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}"]);
1109 if (!empty($this->_params
["billing_country_id-{$this->_bltID}"])) {
1110 $this->_params
["country-{$this->_bltID}"] = $this->_params
["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant
::countryIsoCode($this->_params
["billing_country_id-{$this->_bltID}"]);
1112 $legacyCreditCardExpiryCheck = FALSE;
1113 if ($this->_paymentProcessor
['payment_type'] & CRM_Core_Payment
::PAYMENT_TYPE_CREDIT_CARD
&& !isset($this->_paymentFields
)) {
1114 $legacyCreditCardExpiryCheck = TRUE;
1116 if ($legacyCreditCardExpiryCheck ||
in_array('credit_card_exp_date', array_keys($this->_paymentFields
))) {
1117 $this->_params
['year'] = CRM_Core_Payment_Form
::getCreditCardExpirationYear($this->_params
);
1118 $this->_params
['month'] = CRM_Core_Payment_Form
::getCreditCardExpirationMonth($this->_params
);
1120 $this->_params
['ip_address'] = CRM_Utils_System
::ipAddress();
1121 $this->_params
['amount'] = $this->_params
['total_amount'];
1122 $this->_params
['amount_level'] = 0;
1123 $this->_params
['description'] = ts('Office Credit Card contribution');
1124 $this->_params
['currencyID'] = CRM_Utils_Array
::value('currency',
1126 CRM_Core_Config
::singleton()->defaultCurrency
1128 $this->_params
['payment_action'] = 'Sale';
1129 if (!empty($this->_params
['receive_date'])) {
1130 $this->_params
['receive_date'] = CRM_Utils_Date
::processDate($this->_params
['receive_date'], $this->_params
['receive_date_time']);
1133 if (!empty($params['soft_credit_to'])) {
1134 $this->_params
['soft_credit_to'] = $params['soft_credit_to'];
1135 $this->_params
['pcp_made_through_id'] = $params['pcp_made_through_id'];
1138 $this->_params
['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $params);
1139 $this->_params
['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $params);
1140 $this->_params
['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $params);
1142 //Add common data to formatted params
1143 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
1145 if (empty($this->_params
['invoice_id'])) {
1146 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
1149 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
1152 // At this point we've created a contact and stored its address etc
1153 // all the payment processors expect the name and address to be in the
1154 // so we copy stuff over to first_name etc.
1155 $paymentParams = $this->_params
;
1156 $paymentParams['contactID'] = $this->_contactID
;
1157 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
1159 $contributionType = new CRM_Financial_DAO_FinancialType();
1160 $contributionType->id
= $params['financial_type_id'];
1162 // Add some financial type details to the params list
1163 // if folks need to use it.
1164 $paymentParams['contributionType_name'] = $this->_params
['contributionType_name'] = $contributionType->name
;
1165 $paymentParams['contributionPageID'] = NULL;
1167 if (!empty($this->_params
['is_email_receipt'])) {
1168 $paymentParams['email'] = $this->userEmail
;
1169 $paymentParams['is_email_receipt'] = 1;
1172 $paymentParams['is_email_receipt'] = 0;
1173 $this->_params
['is_email_receipt'] = 0;
1175 if (!empty($this->_params
['receive_date'])) {
1176 $paymentParams['receive_date'] = $this->_params
['receive_date'];
1179 // For recurring contribution, create Contribution Record first.
1180 // Contribution ID, Recurring ID and Contact ID needed
1181 // When we get a callback from the payment processor, CRM-7115
1183 if (!empty($paymentParams['is_recur'])) {
1184 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processContribution($this,
1194 $paymentParams['contributionID'] = $contribution->id
;
1195 $paymentParams['contributionTypeID'] = $contribution->financial_type_id
;
1196 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
1197 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1200 if ($paymentParams['amount'] > 0.0) {
1201 // force a re-get of the payment processor in case the form changed it, CRM-7179
1202 $payment = CRM_Core_Payment
::singleton($this->_mode
, $this->_paymentProcessor
, $this, TRUE);
1204 $result = $payment->doPayment($paymentParams, 'contribute');
1206 catch (CRM_Core_Exception
$e) {
1207 $message = ts("Payment Processor Error message") . $e->getMessage();
1208 $this->cleanupDBAfterPaymentFailure($paymentParams, $message);
1209 // Set the contribution mode.
1210 $urlParams = "action=add&cid={$this->_contactID}";
1212 $urlParams .= "&mode={$this->_mode}";
1214 if (!empty($this->_ppID
)) {
1215 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
1217 CRM_Core_Error
::statusBounce($message, $urlParams, ts('Payment Processor Error'));
1221 $this->_params
= array_merge($this->_params
, $result);
1223 $this->_params
['receive_date'] = $now;
1225 if (!empty($this->_params
['is_email_receipt'])) {
1226 $this->_params
['receipt_date'] = $now;
1229 $this->_params
['receipt_date'] = CRM_Utils_Date
::processDate($this->_params
['receipt_date'],
1230 $params['receipt_date_time'], TRUE
1234 $this->set('params', $this->_params
);
1235 $this->assign('trxn_id', $result['trxn_id']);
1236 $this->assign('receive_date', $this->_params
['receive_date']);
1238 // Result has all the stuff we need
1239 // lets archive it to a financial transaction
1240 if ($contributionType->is_deductible
) {
1241 $this->assign('is_deductible', TRUE);
1242 $this->set('is_deductible', TRUE);
1245 // Set source if not set
1246 if (empty($this->_params
['source'])) {
1247 $userID = CRM_Core_Session
::singleton()->get('userID');
1248 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1251 $this->_params
['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
1254 // Build custom data getFields array
1255 $customFieldsContributionType = CRM_Core_BAO_CustomField
::getFields('Contribution', FALSE, FALSE,
1256 CRM_Utils_Array
::value('financial_type_id', $params)
1258 $customFields = CRM_Utils_Array
::crmArrayMerge($customFieldsContributionType,
1259 CRM_Core_BAO_CustomField
::getFields('Contribution', FALSE, FALSE, NULL, NULL, TRUE)
1261 $params['custom'] = CRM_Core_BAO_CustomField
::postProcess($params,
1266 if (empty($paymentParams['is_recur'])) {
1267 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processContribution($this,
1278 // Send receipt mail.
1279 if ($contribution->id
&& !empty($this->_params
['is_email_receipt'])) {
1280 $this->_params
['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $result);
1281 $this->_params
['contact_id'] = $this->_contactID
;
1282 $this->_params
['contribution_id'] = $contribution->id
;
1283 $sendReceipt = CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $this->_params
, TRUE);
1287 if ($contribution->id
&& isset($params['note'])) {
1288 CRM_Contribute_Form_AdditionalInfo
::processNote($params, $contactID, $contribution->id
, NULL);
1291 if ($contribution->id
&& isset($params['product_name'][0])) {
1292 CRM_Contribute_Form_AdditionalInfo
::processPremium($params, $contribution->id
, NULL, $this->_options
);
1295 //update pledge payment status.
1296 if ($this->_ppID
&& $contribution->id
) {
1297 // Store contribution id in payment record.
1298 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID
, 'contribution_id', $contribution->id
);
1300 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
1301 array($this->_ppID
),
1302 $contribution->contribution_status_id
,
1304 $contribution->total_amount
1308 if ($contribution->id
) {
1309 $statusMsg = ts('The contribution record has been processed.');
1310 if (!empty($this->_params
['is_email_receipt']) && $sendReceipt) {
1311 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
1313 CRM_Core_Session
::setStatus($statusMsg, ts('Complete'), 'success');
1318 * Clean up DB after payment fails.
1320 * This function removes related DB entries. Note that it has been agreed in principle,
1321 * but not implemented, that contributions should be retained as 'Failed' rather than
1324 * @todo it doesn't clean up line items.
1326 * @param array $paymentParams
1327 * @param string $message
1329 public function cleanupDBAfterPaymentFailure($paymentParams, $message) {
1330 // Make sure to cleanup db for recurring case.
1331 if (!empty($paymentParams['contributionID'])) {
1332 CRM_Core_Error
::debug_log_message($message .
1333 "contact id={$this->_contactID} (deleting contribution {$paymentParams['contributionID']}");
1334 CRM_Contribute_BAO_Contribution
::deleteContribution($paymentParams['contributionID']);
1336 if (!empty($paymentParams['contributionRecurID'])) {
1337 CRM_Core_Error
::debug_log_message($message .
1338 "contact id={$this->_contactID} (deleting recurring contribution {$paymentParams['contributionRecurID']}");
1339 CRM_Contribute_BAO_ContributionRecur
::deleteRecurContribution($paymentParams['contributionRecurID']);
1344 * Generate the data to construct a snippet based pane.
1346 * This form also assigns the showAdditionalInfo var based on historical code.
1347 * This appears to mean 'there is a pane to show'.
1349 * @param string $type
1350 * Type of Pane - this is generally used to determine the function name used to build it
1351 * - e.g CreditCard, AdditionalDetail
1352 * @param array $defaults
1355 * We aim to further refactor & simplify this but currently
1357 * - should additional info be shown?
1359 protected function generatePane($type, $defaults) {
1360 $urlParams = "snippet=4&formType={$type}";
1362 $urlParams .= "&mode={$this->_mode}";
1366 if ($type == 'CreditCard' ||
1367 $type == 'DirectDebit'
1373 'url' => CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams),
1378 // See if we need to include this paneName in the current form.
1379 if ($this->_formType
== $type ||
!empty($_POST["hidden_{$type}"]) ||
1380 CRM_Utils_Array
::value("hidden_{$type}", $defaults)
1382 $this->assign('showAdditionalInfo', TRUE);
1383 $pane['open'] = 'true';
1386 if ($type == 'CreditCard' ||
$type == 'DirectDebit') {
1387 // @todo would be good to align tpl name with form name...
1388 // @todo document why this hidden variable is required.
1389 $this->add('hidden', 'hidden_' . $type, 1);
1393 $additionalInfoFormFunction = 'build' . $type;
1394 CRM_Contribute_Form_AdditionalInfo
::$additionalInfoFormFunction($this);
1400 * Wrapper for unit testing the post process submit function.
1402 * (If we expose through api we can get default additions 'for free').
1404 * @param array $params
1406 public function testSubmit($params, $action) {
1408 'soft_credit_contact_id' => array(),
1409 'receipt_date' => '',
1410 'receipt_date_time' => '',
1411 'cancel_date' => '',
1412 'cancel_date_time' => '',
1415 $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array
::value('pledge_payment_id', $params));
1419 * @param array $submittedValues
1421 * @param int $action
1423 * - CRM_Core_Action::UPDATE
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 $this->processCreditCard($submittedValues, $lineItem, $pledgePaymentID);
1602 // Offline Contribution.
1603 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1605 // get the required field value only.
1606 $formValues = $submittedValues;
1607 $params = $ids = array();
1609 $params['contact_id'] = $this->_contactID
;
1611 $params['currency'] = $this->getCurrency($submittedValues);
1614 'financial_type_id',
1615 'contribution_status_id',
1616 'payment_instrument_id',
1621 foreach ($fields as $f) {
1622 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1626 $params['pcp'] = $pcp;
1628 if (!empty($softParams)) {
1629 $params['soft_credit'] = $softParams;
1630 $params['soft_credit_ids'] = $softIDs;
1633 // CRM-5740 if priceset is used, no need to cleanup money.
1635 $params['skipCleanMoney'] = 1;
1644 foreach ($dates as $d) {
1645 $params[$d] = CRM_Utils_Date
::processDate($formValues[$d], $formValues[$d . '_time'], TRUE);
1648 if (!empty($formValues['is_email_receipt'])) {
1649 $params['receipt_date'] = date("Y-m-d");
1652 if ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Cancelled', 'name')
1653 ||
$params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name')
1655 if (CRM_Utils_System
::isNull(CRM_Utils_Array
::value('cancel_date', $params))) {
1656 $params['cancel_date'] = date('Y-m-d');
1660 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1663 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1664 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1665 if ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Pending', 'name')) {
1666 $params['is_pay_later'] = 1;
1668 elseif ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name')) {
1669 $params['is_pay_later'] = 0;
1672 $ids['contribution'] = $params['id'] = $this->_id
;
1674 // Add Additional common information to formatted params.
1675 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($formValues, $params, $this);
1677 $params['contribution_mode'] = 'participant';
1678 $params['participant_id'] = $pId;
1679 $params['skipLineItem'] = 1;
1681 elseif ($isRelatedId) {
1682 $params['contribution_mode'] = 'membership';
1684 $params['line_item'] = $lineItem;
1685 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array
::value('id', $this->_paymentProcessor
);
1686 if (isset($submittedValues['tax_amount'])) {
1687 $params['tax_amount'] = $submittedValues['tax_amount'];
1689 //create contribution.
1690 if ($isQuickConfig) {
1691 $params['is_quick_config'] = 1;
1695 // if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1696 // if non_deductible_amount does NOT exist - then calculate it depending on:
1697 // $ContributionType->is_deductible and whether there is a product (premium).
1698 if (empty($params['non_deductible_amount'])) {
1699 $contributionType = new CRM_Financial_DAO_FinancialType();
1700 $contributionType->id
= $params['financial_type_id'];
1701 if (!$contributionType->find(TRUE)) {
1702 CRM_Core_Error
::fatal('Could not find a system table');
1704 if ($contributionType->is_deductible
) {
1706 if (isset($formValues['product_name'][0])) {
1707 $selectProduct = $formValues['product_name'][0];
1709 // if there is a product - compare the value to the contribution amount
1710 if (isset($selectProduct)) {
1711 $productDAO = new CRM_Contribute_DAO_Product();
1712 $productDAO->id
= $selectProduct;
1713 $productDAO->find(TRUE);
1714 // product value exceeds contribution amount
1715 if ($params['total_amount'] < $productDAO->price
) {
1716 $params['non_deductible_amount'] = $params['total_amount'];
1718 // product value does NOT exceed contribution amount
1720 $params['non_deductible_amount'] = $productDAO->price
;
1723 // contribution is deductible - but there is no product
1725 $params['non_deductible_amount'] = '0.00';
1728 // contribution is NOT deductible
1730 $params['non_deductible_amount'] = $params['total_amount'];
1734 $contribution = CRM_Contribute_BAO_Contribution
::create($params, $ids);
1736 // process associated membership / participant, CRM-4395
1737 $relatedComponentStatusMsg = NULL;
1738 if ($contribution->id
&& $action & CRM_Core_Action
::UPDATE
) {
1739 $relatedComponentStatusMsg = $this->updateRelatedComponent($contribution->id
,
1740 $contribution->contribution_status_id
,
1741 CRM_Utils_Array
::value('contribution_status_id',
1744 $contribution->receive_date
1749 if ($contribution->id
&& isset($formValues['note'])) {
1750 CRM_Contribute_Form_AdditionalInfo
::processNote($formValues, $this->_contactID
, $contribution->id
, $this->_noteID
);
1754 if ($contribution->id
&& isset($formValues['product_name'][0])) {
1755 CRM_Contribute_Form_AdditionalInfo
::processPremium($formValues, $contribution->id
,
1756 $this->_premiumID
, $this->_options
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 $sendReceipt = CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $formValues);
1823 $pledgePaymentId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
1828 $this->updateRelatedPledge($action, $pledgePaymentID, $contribution, $pledgePaymentId, $formValues);
1831 $statusMsg = ts('The contribution record has been saved.');
1832 if (!empty($formValues['is_email_receipt']) && $sendReceipt) {
1833 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
1836 if ($relatedComponentStatusMsg) {
1837 $statusMsg .= ' ' . $relatedComponentStatusMsg;
1840 CRM_Core_Session
::setStatus($statusMsg, ts('Saved'), 'success');
1841 return $contribution;
1842 //Offline Contribution ends.
1847 * Update related pledge payment status.
1849 * @param string $action
1850 * @param int $pledgePaymentID
1851 * @param CRM_Contribute_BAO_Contribution $contribution
1852 * @param int $pledgePaymentId
1853 * @param $formValues
1855 protected function updateRelatedPledge($action, $pledgePaymentID, $contribution, $pledgePaymentId, $formValues) {
1856 if ((($pledgePaymentID && $contribution->id
) && $action & CRM_Core_Action
::ADD
) ||
1857 (($pledgePaymentId) && $action & CRM_Core_Action
::UPDATE
)
1860 if ($pledgePaymentID) {
1861 //store contribution id in payment record.
1862 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contribution->id
);
1865 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
1871 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
1877 $adjustTotalAmount = FALSE;
1878 if (CRM_Utils_Array
::value('option_type', $formValues) == 2) {
1879 $adjustTotalAmount = TRUE;
1882 $updatePledgePaymentStatus = FALSE;
1883 //do only if either the status or the amount has changed
1884 if ($action & CRM_Core_Action
::ADD
) {
1885 $updatePledgePaymentStatus = TRUE;
1887 elseif ($action & CRM_Core_Action
::UPDATE
&& (($this->_defaults
['contribution_status_id'] != $formValues['contribution_status_id']) ||
1888 ($this->_defaults
['total_amount'] != $formValues['total_amount']))
1890 $updatePledgePaymentStatus = TRUE;
1893 if ($updatePledgePaymentStatus) {
1894 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
1895 array($pledgePaymentID),
1896 $contribution->contribution_status_id
,
1898 $contribution->total_amount
,