3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * This class generates form components for processing a contribution.
31 class CRM_Contribute_Form_Contribution
extends CRM_Contribute_Form_AbstractEditPayment
{
33 * The id of the contribution that we are processing.
40 * The id of the premium that we are processing.
44 public $_premiumID = NULL;
47 * @var CRM_Contribute_DAO_ContributionProduct
49 public $_productDAO = NULL;
59 * The id of the contact associated with this contribution.
66 * The id of the pledge payment that we are processing.
73 * Is this contribution associated with an online.
74 * financial transaction
78 public $_online = FALSE;
81 * Stores all product options.
88 * Storage of parameters from form
95 * Store the contribution Type ID
99 public $_contributionType;
102 * The contribution values if an existing contribution
107 * The pledge values if this contribution is associated with pledge
109 public $_pledgeValues;
111 public $_contributeMode = 'direct';
116 * Parameter with confusing name.
120 public $_compContext;
125 * Possible From email addresses
137 * Store the line items if price set used.
143 * @todo explain why we use lineItem & lineItems
149 * @var array soft credit info
151 public $_softCreditInfo;
153 protected $_formType;
156 * @todo what on earth does cdType stand for????
160 public $_honoreeProfileType;
163 * Array of billing panes to be displayed by billingBlock.tpl.
164 * Currently this is likely to look like
165 * array('Credit Card' => ts('Credit Card') or
166 * array('Direct Debit => ts('Direct Debit')
167 * @todo billing details (address stuff) to be added when we stop hard coding the panes in billingBlock.tpl
171 public $billingPane = array();
174 * Array of the payment fields to be displayed in the payment fieldset (pane) in billingBlock.tpl
175 * this contains all the information to describe these fields from quickform. See CRM_Core_Form_Payment getPaymentFormFieldsMetadata
179 public $_paymentFields = array();
181 * Logged in user's email.
194 * Price set as an array
201 * @todo can we define this a as protected? can we define higher up the chain
211 public $userDisplayName;
214 * Status message to be shown to the user.
218 protected $statusMessage;
221 * Status message title to be shown to the user.
223 * Generally the payment processor message title is 'Complete' and offline is 'Saved'
224 * although this might not be a good fit with the broad range of processors.
228 protected $statusMessageTitle;
231 * Set variables up before form is built.
233 public function preProcess() {
235 // Check permission for action.
236 if (!CRM_Core_Permission
::checkActionPermission('CiviContribute', $this->_action
)) {
237 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
240 // @todo - if anyone ever figures out what this _cdType subroutine is about
241 // (or even if it still applies) please add comments!!!!!!!!!!
242 $this->_cdType
= CRM_Utils_Array
::value('type', $_GET);
243 $this->assign('cdType', FALSE);
244 if ($this->_cdType
) {
245 $this->assign('cdType', TRUE);
246 CRM_Custom_Form_CustomData
::preProcess($this);
250 $this->_formType
= CRM_Utils_Array
::value('formType', $_GET);
253 $this->_priceSetId
= CRM_Utils_Array
::value('priceSetId', $_GET);
254 $this->set('priceSetId', $this->_priceSetId
);
255 $this->assign('priceSetId', $this->_priceSetId
);
257 // Get the pledge payment id
258 $this->_ppID
= CRM_Utils_Request
::retrieve('ppid', 'Positive', $this);
260 // Get the contact id
261 $this->_contactID
= CRM_Utils_Request
::retrieve('cid', 'Positive', $this);
264 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, 'add');
265 $this->assign('action', $this->_action
);
267 // Get the contribution id if update
268 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this);
269 if (!empty($this->_id
)) {
270 $this->assign('contribID', $this->_id
);
273 $this->_context
= CRM_Utils_Request
::retrieve('context', 'String', $this);
274 $this->assign('context', $this->_context
);
276 $this->_compId
= CRM_Utils_Request
::retrieve('compId', 'Positive', $this);
278 $this->_compContext
= CRM_Utils_Request
::retrieve('compContext', 'String', $this);
280 //set the contribution mode.
281 $this->_mode
= CRM_Utils_Request
::retrieve('mode', 'String', $this);
283 $this->assign('contributionMode', $this->_mode
);
284 if ($this->_action
& CRM_Core_Action
::DELETE
) {
288 $this->assign('showCheckNumber', TRUE);
290 $this->_fromEmails
= CRM_Core_BAO_Email
::getFromEmail();
291 $this->assignPaymentRelatedVariables();
293 if (in_array('CiviPledge', CRM_Core_Config
::singleton()->enableComponents
) && !$this->_formType
) {
294 $this->preProcessPledge();
298 $this->showRecordLinkMesssage($this->_id
);
300 $this->_values
= array();
302 // Current contribution id.
304 $this->assignPremiumProduct($this->_id
);
305 $this->buildValuesAndAssignOnline_Note_Type($this->_id
, $this->_values
);
308 // when custom data is included in this page
309 if (!empty($_POST['hidden_custom'])) {
310 $this->applyCustomData('Contribution', CRM_Utils_Array
::value('financial_type_id', $_POST), $this->_id
);
313 $this->_lineItems
= array();
315 if (!empty($this->_compId
) && $this->_compContext
== 'participant') {
316 $this->assign('compId', $this->_compId
);
317 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_compId
);
320 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution', 1, TRUE, TRUE);
322 empty($lineItem) ?
NULL : $this->_lineItems
[] = $lineItem;
325 $this->assign('lineItem', empty($this->_lineItems
) ?
FALSE : $this->_lineItems
);
329 $this->setPageTitle($this->_ppID ?
ts('Credit Card Pledge Payment') : ts('Credit Card Contribution'));
332 $this->setPageTitle($this->_ppID ?
ts('Pledge Payment') : ts('Contribution'));
336 CRM_Contribute_Form_SoftCredit
::preprocess($this);
341 * Set default values.
345 public function setDefaultValues() {
346 if ($this->_cdType
) {
347 // @todo document when this function would be called in this way
348 // (and whether it is valid or an overloading of this form).
349 return CRM_Custom_Form_CustomData
::setDefaultValues($this);
352 $defaults = $this->_values
;
354 // Set defaults for pledge payment.
356 $defaults['total_amount'] = CRM_Utils_Array
::value('scheduled_amount', $this->_pledgeValues
['pledgePayment']);
357 $defaults['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $this->_pledgeValues
);
358 $defaults['currency'] = CRM_Utils_Array
::value('currency', $this->_pledgeValues
);
359 $defaults['option_type'] = 1;
362 if ($this->_action
& CRM_Core_Action
::DELETE
) {
366 $defaults['frequency_interval'] = 1;
367 $defaults['frequency_unit'] = 'month';
369 // Set soft credit defaults.
370 CRM_Contribute_Form_SoftCredit
::setDefaultValues($defaults, $this);
373 $config = CRM_Core_Config
::singleton();
374 // Set default country from config if no country set.
375 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
376 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry
;
379 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
380 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince
;
383 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID
);
384 $defaults = array_merge($defaults, $billingDefaults);
388 $this->_contactID
= $defaults['contact_id'];
391 // Set $newCredit variable in template to control whether link to credit card mode is included.
392 $this->assign('newCredit', CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments());
394 // Fix the display of the monetary value, CRM-4038.
395 if (isset($defaults['total_amount'])) {
396 if (!empty($defaults['tax_amount'])) {
397 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
398 if (!(CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails))) {
399 $defaults['total_amount'] = CRM_Utils_Money
::format($defaults['total_amount'] - $defaults['tax_amount'], NULL, '%a');
403 $defaults['total_amount'] = CRM_Utils_Money
::format($defaults['total_amount'], NULL, '%a');
407 if (isset($defaults['non_deductible_amount'])) {
408 $defaults['non_deductible_amount'] = CRM_Utils_Money
::format($defaults['non_deductible_amount'], NULL, '%a');
411 if (isset($defaults['fee_amount'])) {
412 $defaults['fee_amount'] = CRM_Utils_Money
::format($defaults['fee_amount'], NULL, '%a');
415 if (isset($defaults['net_amount'])) {
416 $defaults['net_amount'] = CRM_Utils_Money
::format($defaults['net_amount'], NULL, '%a');
419 if ($this->_contributionType
) {
420 $defaults['financial_type_id'] = $this->_contributionType
;
423 if (empty($defaults['payment_instrument_id'])) {
424 $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup
::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
427 if (!empty($defaults['is_test'])) {
428 $this->assign('is_test', TRUE);
431 $this->assign('showOption', TRUE);
432 // For Premium section.
433 if ($this->_premiumID
) {
434 $this->assign('showOption', FALSE);
435 $options = isset($this->_options
[$this->_productDAO
->product_id
]) ?
$this->_options
[$this->_productDAO
->product_id
] : "";
437 $this->assign('showOption', TRUE);
439 $options_key = CRM_Utils_Array
::key($this->_productDAO
->product_option
, $options);
441 $defaults['product_name'] = array($this->_productDAO
->product_id
, trim($options_key));
444 $defaults['product_name'] = array($this->_productDAO
->product_id
);
446 if ($this->_productDAO
->fulfilled_date
) {
447 list($defaults['fulfilled_date']) = CRM_Utils_Date
::setDateDefaults($this->_productDAO
->fulfilled_date
);
451 if (isset($this->userEmail
)) {
452 $this->assign('email', $this->userEmail
);
455 if (!empty($defaults['is_pay_later'])) {
456 $this->assign('is_pay_later', TRUE);
458 $this->assign('contribution_status_id', CRM_Utils_Array
::value('contribution_status_id', $defaults));
466 foreach ($dates as $key) {
467 if (!empty($defaults[$key])) {
468 list($defaults[$key], $defaults[$key . '_time'])
469 = CRM_Utils_Date
::setDateDefaults(CRM_Utils_Array
::value($key, $defaults), 'activityDateTime');
473 if (!$this->_id
&& empty($defaults['receive_date'])) {
474 list($defaults['receive_date'],
475 $defaults['receive_date_time']
476 ) = CRM_Utils_Date
::setDateDefaults(NULL, 'activityDateTime');
479 $this->assign('receive_date', CRM_Utils_Date
::processDate(CRM_Utils_Array
::value('receive_date', $defaults),
480 CRM_Utils_Array
::value('receive_date_time', $defaults)
482 $currency = CRM_Utils_Array
::value('currency', $defaults);
483 $this->assign('currency', $currency);
484 // Hack to get currency info to the js layer. CRM-11440.
485 CRM_Utils_Money
::format(1);
486 $this->assign('currencySymbol', CRM_Utils_Array
::value($currency, CRM_Utils_Money
::$_currencySymbols));
487 $this->assign('totalAmount', CRM_Utils_Array
::value('total_amount', $defaults));
489 // Inherit campaign from pledge.
490 if ($this->_ppID
&& !empty($this->_pledgeValues
['campaign_id'])) {
491 $defaults['campaign_id'] = $this->_pledgeValues
['campaign_id'];
494 $this->_defaults
= $defaults;
499 * Build the form object.
501 public function buildQuickForm() {
502 //@todo document the purpose of cdType (if still in use)
503 if ($this->_cdType
) {
504 CRM_Custom_Form_CustomData
::buildQuickForm($this);
509 //tax rate from financialType
510 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant
::getTaxRates()));
511 $this->assign('currencies', json_encode(CRM_Core_OptionGroup
::values('currencies_enabled')));
513 // build price set form.
514 $buildPriceSet = FALSE;
515 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
516 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
517 $this->assign('invoicing', $invoicing);
519 // display tax amount on edit contribution page
520 if ($invoicing && $this->_action
& CRM_Core_Action
::UPDATE
&& isset($this->_values
['tax_amount'])) {
521 $this->assign('totalTaxAmount', $this->_values
['tax_amount']);
524 if (empty($this->_lineItems
) &&
525 ($this->_priceSetId ||
!empty($_POST['price_set_id']))
527 $buildPriceSet = TRUE;
528 $getOnlyPriceSetElements = TRUE;
529 if (!$this->_priceSetId
) {
530 $this->_priceSetId
= $_POST['price_set_id'];
531 $getOnlyPriceSetElements = FALSE;
534 $this->set('priceSetId', $this->_priceSetId
);
535 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
537 // get only price set form elements.
538 if ($getOnlyPriceSetElements) {
542 // use to build form during form rule.
543 $this->assign('buildPriceSet', $buildPriceSet);
545 $defaults = $this->_values
;
546 $additionalDetailFields = array(
550 'non_deductible_amount',
554 foreach ($additionalDetailFields as $key) {
555 if (!empty($defaults[$key])) {
556 $defaults['hidden_AdditionalDetail'] = 1;
561 if ($this->_productDAO
) {
562 if ($this->_productDAO
->product_id
) {
563 $defaults['hidden_Premium'] = 1;
567 if ($this->_noteID
&&
568 isset($this->_values
['note'])
570 $defaults['hidden_AdditionalDetail'] = 1;
574 ts('Additional Details') => 'AdditionalDetail',
577 //Add Premium pane only if Premium is exists.
578 $dao = new CRM_Contribute_DAO_Product();
581 if ($dao->find(TRUE)) {
582 $paneNames[ts('Premium Information')] = 'Premium';
585 $billingPanes = array();
587 if (CRM_Core_Payment_Form
::buildPaymentForm($this, $this->_paymentProcessor
, FALSE) == TRUE) {
588 foreach ($this->billingPane
as $name => $label) {
589 if (!empty($this->billingFieldSets
[$name]['fields'])) {
590 // @todo reduce variation so we don't have to convert 'credit_card' to 'CreditCard'
591 $billingPanes[$label] = $this->generatePane(CRM_Utils_String
::convertStringToCamel($name), $defaults);
594 if (!empty($this->_recurPaymentProcessors
)) {
595 CRM_Contribute_Form_Contribution_Main
::buildRecur($this);
596 $this->setDefaults(array('is_recur' => 0));
597 $this->assign('buildRecurBlock', TRUE);
598 $recurJs = array('onChange' => "buildRecurBlock( this.value ); return false;");
603 foreach ($paneNames as $name => $type) {
604 $allPanes[$name] = $this->generatePane($type, $defaults);
607 $qfKey = $this->controller
->_key
;
608 $this->assign('qfKey', $qfKey);
609 $this->assign('billingPanes', $billingPanes);
610 $this->assign('allPanes', $allPanes);
612 $this->addFormRule(array('CRM_Contribute_Form_Contribution', 'formRule'), $this);
614 if ($this->_formType
) {
615 $this->assign('formType', $this->_formType
);
619 $this->applyFilter('__ALL__', 'trim');
621 if ($this->_action
& CRM_Core_Action
::DELETE
) {
622 $this->addButtons(array(
625 'name' => ts('Delete'),
626 'spacing' => ' ',
631 'name' => ts('Cancel'),
638 //need to assign custom data type and subtype to the template
639 $this->assign('customDataType', 'Contribution');
640 $this->assign('customDataSubType', $this->_contributionType
);
641 $this->assign('entityID', $this->_id
);
643 if ($this->_context
== 'standalone') {
644 $this->addEntityRef('contact_id', ts('Contact'), array(
646 'api' => array('extra' => array('email')),
650 $attributes = CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Contribution');
652 $financialType = $this->add('select', 'financial_type_id',
653 ts('Financial Type'),
654 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::financialType(),
656 array('onChange' => "CRM.buildCustomData( 'Contribution', this.value );")
658 $paymentInstrument = FALSE;
660 $paymentInstrument = $this->add('select', 'payment_instrument_id',
662 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::paymentInstrument(),
663 TRUE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
667 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), array('class' => 'twelve') +
$attributes['trxn_id']);
669 //add receipt for offline contribution
670 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
672 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
674 $status = CRM_Contribute_PseudoConstant
::contributionStatus();
676 // suppressing contribution statuses that are NOT relevant to pledges (CRM-5169)
677 $statusName = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
684 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
687 elseif ((!$this->_ppID
&& $this->_id
) ||
!$this->_id
) {
688 $suppressFlag = FALSE;
690 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
691 if (CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails)) {
692 $suppressFlag = TRUE;
695 if (!$suppressFlag) {
700 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
704 unset($status[CRM_Utils_Array
::key('Overdue', $statusName)]);
709 $contributionStatus = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_id
, 'contribution_status_id');
710 $name = CRM_Utils_Array
::value($contributionStatus, $statusName);
715 unset($status[CRM_Utils_Array
::key('In Progress', $statusName)]);
716 unset($status[CRM_Utils_Array
::key('Pending', $statusName)]);
717 unset($status[CRM_Utils_Array
::key('Failed', $statusName)]);
722 unset($status[CRM_Utils_Array
::key('Refunded', $statusName)]);
733 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
739 unset($status[CRM_Utils_Array
::key('Refunded', $statusName)]);
742 $this->add('select', 'contribution_status_id',
743 ts('Contribution Status'),
749 $this->addDateTime('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
751 if ($this->_online
) {
752 $this->assign('hideCalender', TRUE);
754 $checkNumber = $this->add('text', 'check_number', ts('Check Number'), $attributes['check_number']);
756 $this->addDateTime('receipt_date', ts('Receipt Date'), FALSE, array('formatType' => 'activityDateTime'));
757 $this->addDateTime('cancel_date', ts('Cancelled / Refunded Date'), FALSE, array('formatType' => 'activityDateTime'));
759 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
761 $element = $this->add('select',
762 'payment_processor_id',
763 ts('Payment Processor'),
769 if ($this->_online
) {
773 if (empty($this->_lineItems
)) {
774 $buildPriceSet = FALSE;
775 $priceSets = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute');
776 if (!empty($priceSets) && !$this->_ppID
) {
777 $buildPriceSet = TRUE;
780 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
781 // and if we already have line items for that participant. CRM-5095
782 if ($buildPriceSet && $this->_id
) {
783 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
784 $pledgePaymentId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
789 if ($pledgePaymentId) {
790 $buildPriceSet = FALSE;
792 if ($participantID = CRM_Utils_Array
::value('participant', $componentDetails)) {
793 $participantLI = CRM_Price_BAO_LineItem
::getLineItems($participantID);
794 if (!CRM_Utils_System
::isNull($participantLI)) {
795 $buildPriceSet = FALSE;
800 $hasPriceSets = FALSE;
801 if ($buildPriceSet) {
802 $hasPriceSets = TRUE;
803 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
805 '' => ts('Choose price set'),
807 NULL, array('onchange' => "buildAmount( this.value );")
809 if ($this->_online
&& !($this->_action
& CRM_Core_Action
::UPDATE
)) {
813 $this->assign('hasPriceSets', $hasPriceSets);
814 $currencyFreeze = FALSE;
815 if (!($this->_action
& CRM_Core_Action
::UPDATE
)) {
816 if ($this->_online ||
$this->_ppID
) {
817 $attributes['total_amount'] = array_merge($attributes['total_amount'], array(
819 'style' => "background-color:#EBECE4",
821 $optionTypes = array(
822 '1' => ts('Adjust Pledge Payment Schedule?'),
823 '2' => ts('Adjust Total Pledge Amount?'),
825 $this->addRadio('option_type',
831 $currencyFreeze = TRUE;
835 $totalAmount = $this->addMoney('total_amount',
837 ($hasPriceSets) ?
FALSE : TRUE,
838 $attributes['total_amount'],
839 TRUE, 'currency', NULL, $currencyFreeze
843 $this->add('text', 'source', ts('Source'), CRM_Utils_Array
::value('source', $attributes));
845 // CRM-7362 --add campaigns.
846 CRM_Campaign_BAO_Campaign
::addCampaign($this, CRM_Utils_Array
::value('campaign_id', $this->_values
));
848 CRM_Contribute_Form_SoftCredit
::buildQuickForm($this);
852 $js = array('onclick' => "return verify( );");
855 $mailingInfo = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
858 $this->assign('outBound_option', $mailingInfo['outBound_option']);
860 $this->addButtons(array(
863 'name' => ts('Save'),
869 'name' => ts('Save and New'),
875 'name' => ts('Cancel'),
880 // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
881 // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
882 if ($this->_id
&& $this->_values
['contribution_status_id'] == array_search('Cancelled', $statusName)) {
884 $totalAmount->freeze();
886 $checkNumber->freeze();
887 $paymentInstrument->freeze();
889 $financialType->freeze();
892 // if contribution is related to membership or participant freeze Financial Type, Amount
893 if ($this->_id
&& isset($this->_values
['tax_amount'])) {
894 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
895 if (CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails)) {
897 $totalAmount->freeze();
899 $financialType->freeze();
900 $this->assign('freezeFinancialType', TRUE);
904 if ($this->_action
& CRM_Core_Action
::VIEW
) {
912 * @param array $fields
913 * The input form values.
914 * @param array $files
915 * The uploaded files if any.
919 * true if no errors, else array of errors
921 public static function formRule($fields, $files, $self) {
924 // Check for Credit Card Contribution.
926 if (empty($fields['payment_processor_id'])) {
927 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
930 // validate payment instrument (e.g. credit card number)
931 CRM_Core_Payment_Form
::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, $self);
935 // Do the amount validations.
936 if (empty($fields['total_amount']) && empty($self->_lineItems
)) {
937 if ($priceSetId = CRM_Utils_Array
::value('price_set_id', $fields)) {
938 CRM_Price_BAO_PriceField
::priceSetValidation($priceSetId, $fields, $errors);
942 $softErrors = CRM_Contribute_Form_SoftCredit
::formRule($fields, $errors, $self);
944 if (!empty($fields['total_amount']) && (!empty($fields['net_amount']) ||
!empty($fields['fee_amount']))) {
945 $sum = CRM_Utils_Rule
::cleanMoney($fields['net_amount']) + CRM_Utils_Rule
::cleanMoney($fields['fee_amount']);
946 if (CRM_Utils_Rule
::cleanMoney($fields['total_amount']) != $sum) {
947 $errors['total_amount'] = ts('The sum of fee amount and net amount must be equal to total amount');
950 // Form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
951 if ($self->_id
&& $self->_values
['contribution_status_id'] != $fields['contribution_status_id']) {
952 CRM_Contribute_BAO_Contribution
::checkStatusValidation($self->_values
, $fields, $errors);
954 // CRM-16015, add form-rule to restrict change of financial type if using price field of different financial type
955 if ($self->_id
&& $self->_values
['financial_type_id'] != $fields['financial_type_id']) {
956 CRM_Contribute_BAO_Contribution
::checkFinancialTypeChange(NULL, $self->_id
, $errors);
958 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
959 if (!empty($fields['fee_amount']) && !empty($fields['financial_type_id']) && $financialType = CRM_Contribute_BAO_Contribution
::validateFinancialType($fields['financial_type_id'])) {
960 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
963 // $trxn_id must be unique CRM-13919
964 if (!empty($fields['trxn_id'])) {
965 $queryParams = array(1 => array($fields['trxn_id'], 'String'));
966 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
968 $queryParams[2] = array((int) $self->_id
, 'Integer');
969 $query .= ' and id !=%2';
971 $tCnt = CRM_Core_DAO
::singleValueQuery($query, $queryParams);
973 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', array(1 => $fields['trxn_id']));
977 $errors = array_merge($errors, $softErrors);
982 * Process the form submission.
984 public function postProcess() {
985 if ($this->_action
& CRM_Core_Action
::DELETE
) {
986 CRM_Contribute_BAO_Contribution
::deleteContribution($this->_id
);
987 CRM_Core_Session
::singleton()->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
988 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
993 // Get the submitted form values.
994 $submittedValues = $this->controller
->exportValues($this->_name
);
995 $contribution = $this->submit($submittedValues, $this->_action
, $this->_ppID
);
996 $session = CRM_Core_Session
::singleton();
997 $buttonName = $this->controller
->getButtonName();
998 if ($this->_context
== 'standalone') {
999 if ($buttonName == $this->getButtonName('upload', 'new')) {
1000 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contribute/add',
1001 'reset=1&action=add&context=standalone'
1005 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
1006 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1010 elseif ($this->_context
== 'contribution' && $this->_mode
&& $buttonName == $this->getButtonName('upload', 'new')) {
1011 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
1012 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
1015 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1016 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
1017 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
1021 //store contribution ID if not yet set (on create)
1022 if (empty($this->_id
) && !empty($contribution->id
)) {
1023 $this->_id
= $contribution->id
;
1028 * Process credit card payment.
1030 * @param array $submittedValues
1031 * @param array $lineItem
1033 * @return bool|\CRM_Contribute_DAO_Contribution
1035 protected function processCreditCard($submittedValues, $lineItem) {
1036 $sendReceipt = $contribution = FALSE;
1038 $unsetParams = array(
1040 'payment_instrument_id',
1041 'contribution_status_id',
1045 foreach ($unsetParams as $key) {
1046 if (isset($submittedValues[$key])) {
1047 unset($submittedValues[$key]);
1050 $isTest = ($this->_mode
== 'test') ?
1 : 0;
1051 // CRM-12680 set $_lineItem if its not set
1052 if (empty($this->_lineItem
) && !empty($lineItem)) {
1053 $this->_lineItem
= $lineItem;
1056 //Get the require fields value only.
1057 $params = $this->_params
= $submittedValues;
1059 $this->_paymentProcessor
= CRM_Financial_BAO_PaymentProcessor
::getPayment($this->_params
['payment_processor_id'],
1063 // Get the payment processor id as per mode.
1064 $this->_params
['payment_processor'] = $params['payment_processor_id']
1065 = $this->_params
['payment_processor_id'] = $submittedValues['payment_processor_id'] = $this->_paymentProcessor
['id'];
1067 $now = date('YmdHis');
1070 // we need to retrieve email address
1071 if ($this->_context
== 'standalone' && !empty($submittedValues['is_email_receipt'])) {
1072 list($this->userDisplayName
,
1074 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
1075 $this->assign('displayName', $this->userDisplayName
);
1078 // Set email for primary location.
1079 $fields['email-Primary'] = 1;
1080 $params['email-Primary'] = $this->userEmail
;
1082 // now set the values for the billing location.
1083 foreach (array_keys($this->_fields
) as $name) {
1087 // also add location name to the array
1088 $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);
1090 $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
1091 $fields["address_name-{$this->_bltID}"] = 1;
1092 $ctype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
1097 $nameFields = array('first_name', 'middle_name', 'last_name');
1098 foreach ($nameFields as $name) {
1100 if (array_key_exists("billing_$name", $params)) {
1101 $params[$name] = $params["billing_{$name}"];
1102 $params['preserveDBName'] = TRUE;
1106 if (!empty($params['source'])) {
1107 unset($params['source']);
1109 $contactID = CRM_Contact_BAO_Contact
::createProfileContact($params, $fields,
1115 // add all the additional payment params we need
1116 if (!empty($this->_params
["billing_state_province_id-{$this->_bltID}"])) {
1117 $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}"]);
1119 if (!empty($this->_params
["billing_country_id-{$this->_bltID}"])) {
1120 $this->_params
["country-{$this->_bltID}"] = $this->_params
["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant
::countryIsoCode($this->_params
["billing_country_id-{$this->_bltID}"]);
1122 $legacyCreditCardExpiryCheck = FALSE;
1123 if ($this->_paymentProcessor
['payment_type'] & CRM_Core_Payment
::PAYMENT_TYPE_CREDIT_CARD
&& !isset($this->_paymentFields
)) {
1124 $legacyCreditCardExpiryCheck = TRUE;
1126 if ($legacyCreditCardExpiryCheck ||
in_array('credit_card_exp_date', array_keys($this->_paymentFields
))) {
1127 $this->_params
['year'] = CRM_Core_Payment_Form
::getCreditCardExpirationYear($this->_params
);
1128 $this->_params
['month'] = CRM_Core_Payment_Form
::getCreditCardExpirationMonth($this->_params
);
1130 $this->_params
['ip_address'] = CRM_Utils_System
::ipAddress();
1131 $this->_params
['amount'] = $this->_params
['total_amount'];
1132 $this->_params
['amount_level'] = 0;
1133 $this->_params
['description'] = ts('Office Credit Card contribution');
1134 $this->_params
['currencyID'] = CRM_Utils_Array
::value('currency',
1136 CRM_Core_Config
::singleton()->defaultCurrency
1138 $this->_params
['payment_action'] = 'Sale';
1139 if (!empty($this->_params
['receive_date'])) {
1140 $this->_params
['receive_date'] = CRM_Utils_Date
::processDate($this->_params
['receive_date'], $this->_params
['receive_date_time']);
1143 if (!empty($params['soft_credit_to'])) {
1144 $this->_params
['soft_credit_to'] = $params['soft_credit_to'];
1145 $this->_params
['pcp_made_through_id'] = $params['pcp_made_through_id'];
1148 $this->_params
['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $params);
1149 $this->_params
['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $params);
1150 $this->_params
['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $params);
1152 //Add common data to formatted params
1153 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
1155 if (empty($this->_params
['invoice_id'])) {
1156 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
1159 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
1162 // At this point we've created a contact and stored its address etc
1163 // all the payment processors expect the name and address to be in the
1164 // so we copy stuff over to first_name etc.
1165 $paymentParams = $this->_params
;
1166 $paymentParams['contactID'] = $this->_contactID
;
1167 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
1169 $financialType = new CRM_Financial_DAO_FinancialType();
1170 $financialType->id
= $params['financial_type_id'];
1172 // Add some financial type details to the params list
1173 // if folks need to use it.
1174 $paymentParams['contributionType_name'] = $this->_params
['contributionType_name'] = $financialType->name
;
1175 $paymentParams['contributionPageID'] = NULL;
1177 if (!empty($this->_params
['is_email_receipt'])) {
1178 $paymentParams['email'] = $this->userEmail
;
1179 $paymentParams['is_email_receipt'] = 1;
1182 $paymentParams['is_email_receipt'] = 0;
1183 $this->_params
['is_email_receipt'] = 0;
1185 if (!empty($this->_params
['receive_date'])) {
1186 $paymentParams['receive_date'] = $this->_params
['receive_date'];
1189 // For recurring contribution, create Contribution Record first.
1190 // Contribution ID, Recurring ID and Contact ID needed
1191 // When we get a callback from the payment processor, CRM-7115
1193 if (!empty($paymentParams['is_recur'])) {
1194 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processContribution($this,
1204 $paymentParams['contributionID'] = $contribution->id
;
1205 $paymentParams['contributionTypeID'] = $contribution->financial_type_id
;
1206 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
1207 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1210 if ($paymentParams['amount'] > 0.0) {
1211 // force a re-get of the payment processor in case the form changed it, CRM-7179
1212 $payment = CRM_Core_Payment
::singleton($this->_mode
, $this->_paymentProcessor
, $this, TRUE);
1214 $result = $payment->doPayment($paymentParams, 'contribute');
1216 catch (CRM_Core_Exception
$e) {
1217 $message = ts("Payment Processor Error message") . $e->getMessage();
1218 $this->cleanupDBAfterPaymentFailure($paymentParams, $message);
1219 // Set the contribution mode.
1220 $urlParams = "action=add&cid={$this->_contactID}";
1222 $urlParams .= "&mode={$this->_mode}";
1224 if (!empty($this->_ppID
)) {
1225 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
1227 CRM_Core_Error
::statusBounce($message, $urlParams, ts('Payment Processor Error'));
1231 $this->_params
= array_merge($this->_params
, $result);
1233 $this->_params
['receive_date'] = $now;
1235 if (!empty($this->_params
['is_email_receipt'])) {
1236 $this->_params
['receipt_date'] = $now;
1239 $this->_params
['receipt_date'] = CRM_Utils_Date
::processDate($this->_params
['receipt_date'],
1240 $params['receipt_date_time'], TRUE
1244 $this->set('params', $this->_params
);
1245 $this->assign('trxn_id', $result['trxn_id']);
1246 $this->assign('receive_date', $this->_params
['receive_date']);
1248 // Result has all the stuff we need
1249 // lets archive it to a financial transaction
1250 if ($financialType->is_deductible
) {
1251 $this->assign('is_deductible', TRUE);
1252 $this->set('is_deductible', TRUE);
1255 // Set source if not set
1256 if (empty($this->_params
['source'])) {
1257 $userID = CRM_Core_Session
::singleton()->get('userID');
1258 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1261 $this->_params
['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
1264 // Build custom data getFields array
1265 $customFieldsContributionType = CRM_Core_BAO_CustomField
::getFields('Contribution', FALSE, FALSE,
1266 CRM_Utils_Array
::value('financial_type_id', $params)
1268 $customFields = CRM_Utils_Array
::crmArrayMerge($customFieldsContributionType,
1269 CRM_Core_BAO_CustomField
::getFields('Contribution', FALSE, FALSE, NULL, NULL, TRUE)
1271 $params['custom'] = CRM_Core_BAO_CustomField
::postProcess($params,
1276 if (empty($paymentParams['is_recur'])) {
1277 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processContribution($this,
1288 // Send receipt mail.
1289 if ($contribution->id
&& !empty($this->_params
['is_email_receipt'])) {
1290 $this->_params
['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $result);
1291 $this->_params
['contact_id'] = $this->_contactID
;
1292 $this->_params
['contribution_id'] = $contribution->id
;
1293 $sendReceipt = CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $this->_params
, TRUE);
1297 if ($contribution->id
&& isset($params['note'])) {
1298 CRM_Contribute_Form_AdditionalInfo
::processNote($params, $contactID, $contribution->id
, NULL);
1301 if ($contribution->id
&& isset($params['product_name'][0])) {
1302 CRM_Contribute_Form_AdditionalInfo
::processPremium($params, $contribution->id
, NULL, $this->_options
);
1305 if ($contribution->id
) {
1306 $this->statusMessage
= ts('The contribution record has been processed.');
1307 if (!empty($this->_params
['is_email_receipt']) && $sendReceipt) {
1308 $this->statusMessage
.= ' ' . ts('A receipt has been emailed to the contributor.');
1310 $this->statusMessageTitle
= ts('Complete');
1312 return $contribution;
1316 * Clean up DB after payment fails.
1318 * This function removes related DB entries. Note that it has been agreed in principle,
1319 * but not implemented, that contributions should be retained as 'Failed' rather than
1322 * @todo it doesn't clean up line items.
1324 * @param array $paymentParams
1325 * @param string $message
1327 public function cleanupDBAfterPaymentFailure($paymentParams, $message) {
1328 // Make sure to cleanup db for recurring case.
1329 if (!empty($paymentParams['contributionID'])) {
1330 CRM_Core_Error
::debug_log_message($message .
1331 "contact id={$this->_contactID} (deleting contribution {$paymentParams['contributionID']}");
1332 CRM_Contribute_BAO_Contribution
::deleteContribution($paymentParams['contributionID']);
1334 if (!empty($paymentParams['contributionRecurID'])) {
1335 CRM_Core_Error
::debug_log_message($message .
1336 "contact id={$this->_contactID} (deleting recurring contribution {$paymentParams['contributionRecurID']}");
1337 CRM_Contribute_BAO_ContributionRecur
::deleteRecurContribution($paymentParams['contributionRecurID']);
1342 * Generate the data to construct a snippet based pane.
1344 * This form also assigns the showAdditionalInfo var based on historical code.
1345 * This appears to mean 'there is a pane to show'.
1347 * @param string $type
1348 * Type of Pane - this is generally used to determine the function name used to build it
1349 * - e.g CreditCard, AdditionalDetail
1350 * @param array $defaults
1353 * We aim to further refactor & simplify this but currently
1355 * - should additional info be shown?
1357 protected function generatePane($type, $defaults) {
1358 $urlParams = "snippet=4&formType={$type}";
1360 $urlParams .= "&mode={$this->_mode}";
1364 if ($type == 'CreditCard' ||
1365 $type == 'DirectDebit'
1371 'url' => CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams),
1376 // See if we need to include this paneName in the current form.
1377 if ($this->_formType
== $type ||
!empty($_POST["hidden_{$type}"]) ||
1378 CRM_Utils_Array
::value("hidden_{$type}", $defaults)
1380 $this->assign('showAdditionalInfo', TRUE);
1381 $pane['open'] = 'true';
1384 if ($type == 'CreditCard' ||
$type == 'DirectDebit') {
1385 // @todo would be good to align tpl name with form name...
1386 // @todo document why this hidden variable is required.
1387 $this->add('hidden', 'hidden_' . $type, 1);
1391 $additionalInfoFormFunction = 'build' . $type;
1392 CRM_Contribute_Form_AdditionalInfo
::$additionalInfoFormFunction($this);
1398 * Wrapper for unit testing the post process submit function.
1400 * (If we expose through api we can get default additions 'for free').
1402 * @param array $params
1403 * @param int $action
1405 public function testSubmit($params, $action) {
1407 'soft_credit_contact_id' => array(),
1408 'receipt_date' => '',
1409 'receipt_date_time' => '',
1410 'cancel_date' => '',
1411 'cancel_date_time' => '',
1413 if (!empty($params['id'])) {
1414 $existingContribution = civicrm_api3('contribution', 'getsingle', array(
1415 'id' => $params['id'],
1419 $existingContribution = array();
1422 $this->_defaults
['contribution_status_id'] = CRM_Utils_Array
::value('contribution_status_id',
1423 $existingContribution
1426 $this->_defaults
['total_amount'] = CRM_Utils_Array
::value('total_amount',
1427 $existingContribution
1430 $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array
::value('pledge_payment_id', $params));
1434 * @param array $submittedValues
1436 * @param int $action
1438 * - CRM_Core_Action::UPDATE
1440 * @param $pledgePaymentID
1443 * @throws \Exception
1445 protected function submit($submittedValues, $action, $pledgePaymentID) {
1446 $softParams = $softIDs = array();
1447 $pId = $contribution = $isRelatedId = FALSE;
1448 if (!empty($submittedValues['price_set_id']) && $action & CRM_Core_Action
::UPDATE
) {
1449 $line = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution');
1450 $lineID = key($line);
1451 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array
::value('price_field_id', $line[$lineID]), 'price_set_id');
1452 $quickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1454 CRM_Price_BAO_LineItem
::deleteLineItems($this->_id
, 'civicrm_contribution');
1458 // Process price set and get total amount and line items.
1459 $lineItem = array();
1460 $priceSetId = CRM_Utils_Array
::value('price_set_id', $submittedValues);
1461 if (empty($priceSetId) && !$this->_id
) {
1462 $this->_priceSetId
= $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1463 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
1464 $fieldID = key($this->_priceSet
['fields']);
1465 $fieldValueId = key($this->_priceSet
['fields'][$fieldID]['options']);
1466 $this->_priceSet
['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1467 $submittedValues['price_' . $fieldID] = 1;
1471 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
1472 $submittedValues, $lineItem[$priceSetId]);
1474 // Unset tax amount for offline 'is_quick_config' contribution.
1475 if ($this->_priceSet
['is_quick_config'] &&
1476 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant
::getTaxRates())
1478 unset($submittedValues['tax_amount']);
1480 $submittedValues['total_amount'] = CRM_Utils_Array
::value('amount', $submittedValues);
1483 if ($this->_compId
) {
1484 if ($this->_context
== 'participant') {
1485 $pId = $this->_compId
;
1487 elseif ($this->_context
== 'membership') {
1488 $isRelatedId = TRUE;
1491 $pId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id
, 'participant_id', 'contribution_id');
1495 $contributionDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1496 if (array_key_exists('membership', $contributionDetails)) {
1497 $isRelatedId = TRUE;
1499 elseif (array_key_exists('participant', $contributionDetails)) {
1500 $pId = $contributionDetails['participant'];
1504 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id
) {
1505 // CRM-10117 update the line items for participants.
1507 $entityTable = 'participant';
1509 $isRelatedId = FALSE;
1510 $participantParams = array(
1511 'fee_amount' => $submittedValues['total_amount'],
1514 CRM_Event_BAO_Participant
::add($participantParams);
1515 if (empty($this->_lineItems
)) {
1516 $this->_lineItems
[] = CRM_Price_BAO_LineItem
::getLineItems($entityID, 'participant', 1);
1520 $entityTable = 'contribution';
1521 $entityID = $this->_id
;
1524 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, $entityTable, NULL, TRUE, $isRelatedId);
1525 foreach (array_keys($lineItems) as $id) {
1526 $lineItems[$id]['id'] = $id;
1528 $itemId = key($lineItems);
1529 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1530 $this->_priceSetId
= CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1533 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1534 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule
::cleanMoney(CRM_Utils_Array
::value('total_amount', $submittedValues));
1536 // Update line total and total amount with tax on edit.
1537 $financialItemsId = CRM_Core_PseudoConstant
::getTaxRates();
1538 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1539 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1542 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1543 $submittedValues['tax_amount'] = 'null';
1545 if ($lineItems[$itemId]['tax_rate']) {
1546 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total'];
1547 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] +
$lineItems[$itemId]['tax_amount'];
1548 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1551 // CRM-10117 update the line items for participants.
1552 if (!empty($lineItems[$itemId]['price_field_id'])) {
1553 $lineItem[$this->_priceSetId
] = $lineItems;
1558 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1561 //CRM-11529 for quick config back office transactions
1562 //when financial_type_id is passed in form, update the
1563 //line items with the financial type selected in form
1564 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array
::value($this->_priceSetId
, $lineItem)
1566 foreach ($lineItem[$this->_priceSetId
] as &$values) {
1567 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1571 if (!isset($submittedValues['total_amount'])) {
1572 $submittedValues['total_amount'] = CRM_Utils_Array
::value('total_amount', $this->_values
);
1574 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
1576 if (!empty($submittedValues['pcp_made_through_id'])) {
1579 'pcp_made_through_id',
1580 'pcp_display_in_roll',
1581 'pcp_roll_nickname',
1582 'pcp_personal_note',
1584 foreach ($fields as $f) {
1585 $pcp[$f] = CRM_Utils_Array
::value($f, $submittedValues);
1589 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
1590 if ($this->_id
&& count($isEmpty) == 1 && key($isEmpty) == NULL) {
1591 //Delete existing soft credit records if soft credit list is empty on update
1592 CRM_Contribute_BAO_ContributionSoft
::del(array('contribution_id' => $this->_id
));
1595 //build soft credit params
1596 foreach ($submittedValues['soft_credit_contact_id'] as $key => $val) {
1597 if ($val && $submittedValues['soft_credit_amount'][$key]) {
1598 $softParams[$key]['contact_id'] = $val;
1599 $softParams[$key]['amount'] = CRM_Utils_Rule
::cleanMoney($submittedValues['soft_credit_amount'][$key]);
1600 $softParams[$key]['soft_credit_type_id'] = $submittedValues['soft_credit_type'][$key];
1601 if (!empty($submittedValues['soft_credit_id'][$key])) {
1602 $softIDs[] = $softParams[$key]['id'] = $submittedValues['soft_credit_id'][$key];
1608 // set the contact, when contact is selected
1609 if (!empty($submittedValues['contact_id'])) {
1610 $this->_contactID
= $submittedValues['contact_id'];
1613 // Credit Card Contribution.
1615 $contribution = $this->processCreditCard($submittedValues, $lineItem);
1618 // Offline Contribution.
1619 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1621 // get the required field value only.
1622 $formValues = $submittedValues;
1623 $params = $ids = array();
1625 $params['contact_id'] = $this->_contactID
;
1627 $params['currency'] = $this->getCurrency($submittedValues);
1630 'financial_type_id',
1631 'contribution_status_id',
1632 'payment_instrument_id',
1637 foreach ($fields as $f) {
1638 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1642 $params['pcp'] = $pcp;
1644 if (!empty($softParams)) {
1645 $params['soft_credit'] = $softParams;
1646 $params['soft_credit_ids'] = $softIDs;
1649 // CRM-5740 if priceset is used, no need to cleanup money.
1651 $params['skipCleanMoney'] = 1;
1660 foreach ($dates as $d) {
1661 $params[$d] = CRM_Utils_Date
::processDate($formValues[$d], $formValues[$d . '_time'], TRUE);
1664 if (!empty($formValues['is_email_receipt'])) {
1665 $params['receipt_date'] = date("Y-m-d");
1668 if ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Cancelled', 'name')
1669 ||
$params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name')
1671 if (CRM_Utils_System
::isNull(CRM_Utils_Array
::value('cancel_date', $params))) {
1672 $params['cancel_date'] = date('Y-m-d');
1676 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1679 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1680 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1681 if ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Pending', 'name')) {
1682 $params['is_pay_later'] = 1;
1684 elseif ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name')) {
1685 $params['is_pay_later'] = 0;
1688 $ids['contribution'] = $params['id'] = $this->_id
;
1690 // Add Additional common information to formatted params.
1691 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($formValues, $params, $this);
1693 $params['contribution_mode'] = 'participant';
1694 $params['participant_id'] = $pId;
1695 $params['skipLineItem'] = 1;
1697 elseif ($isRelatedId) {
1698 $params['contribution_mode'] = 'membership';
1700 $params['line_item'] = $lineItem;
1701 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array
::value('id', $this->_paymentProcessor
);
1702 if (isset($submittedValues['tax_amount'])) {
1703 $params['tax_amount'] = $submittedValues['tax_amount'];
1705 //create contribution.
1706 if ($isQuickConfig) {
1707 $params['is_quick_config'] = 1;
1711 // if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1712 // if non_deductible_amount does NOT exist - then calculate it depending on:
1713 // $ContributionType->is_deductible and whether there is a product (premium).
1714 if (empty($params['non_deductible_amount'])) {
1715 $contributionType = new CRM_Financial_DAO_FinancialType();
1716 $contributionType->id
= $params['financial_type_id'];
1717 if (!$contributionType->find(TRUE)) {
1718 CRM_Core_Error
::fatal('Could not find a system table');
1720 if ($contributionType->is_deductible
) {
1722 if (isset($formValues['product_name'][0])) {
1723 $selectProduct = $formValues['product_name'][0];
1725 // if there is a product - compare the value to the contribution amount
1726 if (isset($selectProduct)) {
1727 $productDAO = new CRM_Contribute_DAO_Product();
1728 $productDAO->id
= $selectProduct;
1729 $productDAO->find(TRUE);
1730 // product value exceeds contribution amount
1731 if ($params['total_amount'] < $productDAO->price
) {
1732 $params['non_deductible_amount'] = $params['total_amount'];
1734 // product value does NOT exceed contribution amount
1736 $params['non_deductible_amount'] = $productDAO->price
;
1739 // contribution is deductible - but there is no product
1741 $params['non_deductible_amount'] = '0.00';
1744 // contribution is NOT deductible
1746 $params['non_deductible_amount'] = $params['total_amount'];
1750 $contribution = CRM_Contribute_BAO_Contribution
::create($params, $ids);
1752 // process associated membership / participant, CRM-4395
1753 $relatedComponentStatusMsg = NULL;
1754 if ($contribution->id
&& $action & CRM_Core_Action
::UPDATE
) {
1755 $relatedComponentStatusMsg = $this->updateRelatedComponent($contribution->id
,
1756 $contribution->contribution_status_id
,
1757 CRM_Utils_Array
::value('contribution_status_id',
1760 $contribution->receive_date
1765 if ($contribution->id
&& isset($formValues['note'])) {
1766 CRM_Contribute_Form_AdditionalInfo
::processNote($formValues, $this->_contactID
, $contribution->id
, $this->_noteID
);
1770 if ($contribution->id
&& isset($formValues['product_name'][0])) {
1771 CRM_Contribute_Form_AdditionalInfo
::processPremium($formValues, $contribution->id
,
1772 $this->_premiumID
, $this->_options
1775 $this->statusMessage
= ts('The contribution record has been saved.');
1777 $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
1779 //send receipt mail.
1780 if ($contribution->id
&& !empty($formValues['is_email_receipt'])) {
1781 $formValues['contact_id'] = $this->_contactID
;
1782 $formValues['contribution_id'] = $contribution->id
;
1784 $formValues +
= CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
);
1786 // to get 'from email id' for send receipt
1787 $this->fromEmailId
= $formValues['from_email_address'];
1788 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $formValues)) {
1789 $this->statusMessage
.= ' ' . ts('A receipt has been emailed to the contributor.');
1793 if ($relatedComponentStatusMsg) {
1794 $this->statusMessage
.= ' ' . $relatedComponentStatusMsg;
1796 $this->statusMessageTitle
= ts('Saved');
1799 //Offline Contribution ends.
1803 CRM_Core_Session
::setStatus($this->statusMessage
, $this->statusMessageTitle
, 'success');
1805 CRM_Contribute_BAO_Contribution
::updateRelatedPledge(
1809 (CRM_Utils_Array
::value('option_type', $formValues) == 2) ?
TRUE : FALSE,
1810 $formValues['total_amount'],
1811 $this->_defaults
['total_amount'],
1812 $formValues['contribution_status_id'],
1813 $this->_defaults
['contribution_status_id']
1815 return $contribution;
1819 * Assign tax calculations to contribution receipts.
1821 * @param array $submittedValues
1822 * @param int $action
1823 * @param array $lineItem
1825 protected function invoicingPostProcessHook($submittedValues, $action, $lineItem) {
1827 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
1828 if (!CRM_Utils_Array
::value('invoicing', $invoiceSettings)) {
1832 $getTaxDetails = FALSE;
1833 if ($action & CRM_Core_Action
::ADD
) {
1836 elseif ($action & CRM_Core_Action
::UPDATE
) {
1837 $line = $this->_lineItems
;
1839 foreach ($line as $key => $value) {
1840 foreach ($value as $v) {
1841 if (isset($taxRate[(string) CRM_Utils_Array
::value('tax_rate', $v)])) {
1842 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $v);
1845 if (isset($v['tax_rate'])) {
1846 $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $v);
1847 $getTaxDetails = TRUE;
1853 if ($action & CRM_Core_Action
::UPDATE
) {
1854 if (isset($submittedValues['tax_amount'])) {
1855 $totalTaxAmount = $submittedValues['tax_amount'];
1858 $totalTaxAmount = $this->_values
['tax_amount'];
1860 $this->assign('totalTaxAmount', $totalTaxAmount);
1861 $this->assign('dataArray', $taxRate);
1864 if (!empty($submittedValues['price_set_id'])) {
1865 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1866 $this->assign('getTaxDetails', $getTaxDetails);
1867 $this->assign('dataArray', $taxRate);
1868 $this->assign('taxTerm', CRM_Utils_Array
::value('tax_term', $invoiceSettings));
1871 $this->assign('totalTaxAmount', CRM_Utils_Array
::value('tax_amount', $submittedValues));