3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
28 use Civi\Payment\Exception\PaymentProcessorException
;
31 * This class generates form components for processing a contribution.
33 class CRM_Contribute_Form_Contribution
extends CRM_Contribute_Form_AbstractEditPayment
{
35 * The id of the contribution that we are processing.
42 * The id of the premium that we are processing.
46 public $_premiumID = NULL;
49 * @var CRM_Contribute_DAO_ContributionProduct
51 public $_productDAO = NULL;
61 * The id of the contact associated with this contribution.
68 * The id of the pledge payment that we are processing.
75 * Is this contribution associated with an online.
76 * financial transaction
80 public $_online = FALSE;
83 * Stores all product options.
90 * Storage of parameters from form
97 * Store the contribution Type ID
101 public $_contributionType;
104 * The contribution values if an existing contribution
109 * The pledge values if this contribution is associated with pledge
111 public $_pledgeValues;
113 public $_contributeMode = 'direct';
118 * Parameter with confusing name.
122 public $_compContext;
127 * Possible From email addresses
139 * Store the line items if price set used.
145 * @todo explain why we use lineItem & lineItems
151 * @var array soft credit info
153 public $_softCreditInfo;
155 protected $_formType;
157 public $_honoreeProfileType;
160 * Array of the payment fields to be displayed in the payment fieldset (pane) in billingBlock.tpl
161 * this contains all the information to describe these fields from quickform. See CRM_Core_Form_Payment getPaymentFormFieldsMetadata
165 public $_paymentFields = array();
167 * Logged in user's email.
179 * Price set as an array
189 public $userDisplayName;
192 * Status message to be shown to the user.
196 protected $statusMessage = array();
199 * Status message title to be shown to the user.
201 * Generally the payment processor message title is 'Complete' and offline is 'Saved'
202 * although this might not be a good fit with the broad range of processors.
206 protected $statusMessageTitle;
209 * Set variables up before form is built.
211 public function preProcess() {
212 // Check permission for action.
213 if (!CRM_Core_Permission
::checkActionPermission('CiviContribute', $this->_action
)) {
214 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
217 parent
::preProcess();
219 $this->_formType
= CRM_Utils_Array
::value('formType', $_GET);
222 $this->_priceSetId
= CRM_Utils_Array
::value('priceSetId', $_GET);
223 $this->set('priceSetId', $this->_priceSetId
);
224 $this->assign('priceSetId', $this->_priceSetId
);
226 // Get the pledge payment id
227 $this->_ppID
= CRM_Utils_Request
::retrieve('ppid', 'Positive', $this);
229 $this->assign('action', $this->_action
);
231 // Get the contribution id if update
232 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this);
233 if (!empty($this->_id
)) {
234 $this->assign('contribID', $this->_id
);
237 $this->_context
= CRM_Utils_Request
::retrieve('context', 'String', $this);
238 $this->assign('context', $this->_context
);
240 $this->_compId
= CRM_Utils_Request
::retrieve('compId', 'Positive', $this);
242 $this->_compContext
= CRM_Utils_Request
::retrieve('compContext', 'String', $this);
244 //set the contribution mode.
245 $this->_mode
= CRM_Utils_Request
::retrieve('mode', 'String', $this);
247 $this->assign('contributionMode', $this->_mode
);
248 if ($this->_action
& CRM_Core_Action
::DELETE
) {
252 $this->assign('showCheckNumber', TRUE);
254 $this->_fromEmails
= CRM_Core_BAO_Email
::getFromEmail();
255 $this->assignPaymentRelatedVariables();
257 if (in_array('CiviPledge', CRM_Core_Config
::singleton()->enableComponents
) && !$this->_formType
) {
258 $this->preProcessPledge();
262 $this->showRecordLinkMesssage($this->_id
);
264 $this->_values
= array();
266 // Current contribution id.
268 $this->assignPremiumProduct($this->_id
);
269 $this->buildValuesAndAssignOnline_Note_Type($this->_id
, $this->_values
);
272 // when custom data is included in this page
273 if (!empty($_POST['hidden_custom'])) {
274 $this->applyCustomData('Contribution', CRM_Utils_Array
::value('financial_type_id', $_POST), $this->_id
);
277 $this->_lineItems
= array();
279 if (!empty($this->_compId
) && $this->_compContext
== 'participant') {
280 $this->assign('compId', $this->_compId
);
281 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_compId
);
284 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution', 1, TRUE, TRUE);
286 empty($lineItem) ?
NULL : $this->_lineItems
[] = $lineItem;
289 $this->assign('lineItem', empty($this->_lineItems
) ?
FALSE : $this->_lineItems
);
293 $this->setPageTitle($this->_ppID ?
ts('Credit Card Pledge Payment') : ts('Credit Card Contribution'));
296 $this->setPageTitle($this->_ppID ?
ts('Pledge Payment') : ts('Contribution'));
300 CRM_Contribute_Form_SoftCredit
::preprocess($this);
305 * Set default values.
309 public function setDefaultValues() {
311 $defaults = $this->_values
;
313 // Set defaults for pledge payment.
315 $defaults['total_amount'] = CRM_Utils_Array
::value('scheduled_amount', $this->_pledgeValues
['pledgePayment']);
316 $defaults['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $this->_pledgeValues
);
317 $defaults['currency'] = CRM_Utils_Array
::value('currency', $this->_pledgeValues
);
318 $defaults['option_type'] = 1;
321 if ($this->_action
& CRM_Core_Action
::DELETE
) {
325 $defaults['frequency_interval'] = 1;
326 $defaults['frequency_unit'] = 'month';
328 // Set soft credit defaults.
329 CRM_Contribute_Form_SoftCredit
::setDefaultValues($defaults, $this);
332 // @todo - remove this function as the parent does it too.
333 $config = CRM_Core_Config
::singleton();
334 // Set default country from config if no country set.
335 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
336 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry
;
339 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
340 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince
;
343 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID
);
344 $defaults = array_merge($defaults, $billingDefaults);
348 $this->_contactID
= $defaults['contact_id'];
351 // Set $newCredit variable in template to control whether link to credit card mode is included.
352 $this->assign('newCredit', CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments());
354 // Fix the display of the monetary value, CRM-4038.
355 if (isset($defaults['total_amount'])) {
356 if (!empty($defaults['tax_amount'])) {
357 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
358 if (!(CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails))) {
359 $defaults['total_amount'] = CRM_Utils_Money
::format($defaults['total_amount'] - $defaults['tax_amount'], NULL, '%a');
363 $defaults['total_amount'] = CRM_Utils_Money
::format($defaults['total_amount'], NULL, '%a');
367 if (isset($defaults['non_deductible_amount'])) {
368 $defaults['non_deductible_amount'] = CRM_Utils_Money
::format($defaults['non_deductible_amount'], NULL, '%a');
371 if (isset($defaults['fee_amount'])) {
372 $defaults['fee_amount'] = CRM_Utils_Money
::format($defaults['fee_amount'], NULL, '%a');
375 if (isset($defaults['net_amount'])) {
376 $defaults['net_amount'] = CRM_Utils_Money
::format($defaults['net_amount'], NULL, '%a');
379 if ($this->_contributionType
) {
380 $defaults['financial_type_id'] = $this->_contributionType
;
383 if (empty($defaults['payment_instrument_id'])) {
384 $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup
::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
387 if (!empty($defaults['is_test'])) {
388 $this->assign('is_test', TRUE);
391 $this->assign('showOption', TRUE);
392 // For Premium section.
393 if ($this->_premiumID
) {
394 $this->assign('showOption', FALSE);
395 $options = isset($this->_options
[$this->_productDAO
->product_id
]) ?
$this->_options
[$this->_productDAO
->product_id
] : "";
397 $this->assign('showOption', TRUE);
399 $options_key = CRM_Utils_Array
::key($this->_productDAO
->product_option
, $options);
401 $defaults['product_name'] = array($this->_productDAO
->product_id
, trim($options_key));
404 $defaults['product_name'] = array($this->_productDAO
->product_id
);
406 if ($this->_productDAO
->fulfilled_date
) {
407 list($defaults['fulfilled_date']) = CRM_Utils_Date
::setDateDefaults($this->_productDAO
->fulfilled_date
);
411 if (isset($this->userEmail
)) {
412 $this->assign('email', $this->userEmail
);
415 if (!empty($defaults['is_pay_later'])) {
416 $this->assign('is_pay_later', TRUE);
418 $this->assign('contribution_status_id', CRM_Utils_Array
::value('contribution_status_id', $defaults));
419 if (CRM_Utils_Array
::value('contribution_status_id', $defaults) == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Refunded')) {
420 $defaults['refund_trxn_id'] = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionTrxnID($this->_id
);
423 $defaults['refund_trxn_id'] = isset($defaults['trxn_id']) ?
$defaults['trxn_id'] : NULL;
431 foreach ($dates as $key) {
432 if (!empty($defaults[$key])) {
433 list($defaults[$key], $defaults[$key . '_time'])
434 = CRM_Utils_Date
::setDateDefaults(CRM_Utils_Array
::value($key, $defaults), 'activityDateTime');
438 if (!$this->_id
&& empty($defaults['receive_date'])) {
439 list($defaults['receive_date'],
440 $defaults['receive_date_time']
441 ) = CRM_Utils_Date
::setDateDefaults(NULL, 'activityDateTime');
444 $this->assign('receive_date', CRM_Utils_Date
::processDate(CRM_Utils_Array
::value('receive_date', $defaults),
445 CRM_Utils_Array
::value('receive_date_time', $defaults)
447 $currency = CRM_Utils_Array
::value('currency', $defaults);
448 $this->assign('currency', $currency);
449 // Hack to get currency info to the js layer. CRM-11440.
450 CRM_Utils_Money
::format(1);
451 $this->assign('currencySymbol', CRM_Utils_Array
::value($currency, CRM_Utils_Money
::$_currencySymbols));
452 $this->assign('totalAmount', CRM_Utils_Array
::value('total_amount', $defaults));
454 // Inherit campaign from pledge.
455 if ($this->_ppID
&& !empty($this->_pledgeValues
['campaign_id'])) {
456 $defaults['campaign_id'] = $this->_pledgeValues
['campaign_id'];
459 $this->_defaults
= $defaults;
464 * Build the form object.
466 public function buildQuickForm() {
467 // FIXME: This probably needs to be done in preprocess
468 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()
469 && $this->_action
& CRM_Core_Action
::UPDATE
470 && CRM_Utils_Array
::value('financial_type_id', $this->_values
)
472 $financialTypeID = CRM_Contribute_PseudoConstant
::financialType($this->_values
['financial_type_id']);
473 CRM_Financial_BAO_FinancialType
::checkPermissionedLineItems($this->_id
, 'edit');
474 if (!CRM_Core_Permission
::check('edit contributions of type ' . $financialTypeID)) {
475 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
480 //tax rate from financialType
481 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant
::getTaxRates()));
482 $this->assign('currencies', json_encode(CRM_Core_OptionGroup
::values('currencies_enabled')));
484 // build price set form.
485 $buildPriceSet = FALSE;
486 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
487 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
488 $this->assign('invoicing', $invoicing);
490 // display tax amount on edit contribution page
491 if ($invoicing && $this->_action
& CRM_Core_Action
::UPDATE
&& isset($this->_values
['tax_amount'])) {
492 $this->assign('totalTaxAmount', $this->_values
['tax_amount']);
495 if (empty($this->_lineItems
) &&
496 ($this->_priceSetId ||
!empty($_POST['price_set_id']))
498 $buildPriceSet = TRUE;
499 $getOnlyPriceSetElements = TRUE;
500 if (!$this->_priceSetId
) {
501 $this->_priceSetId
= $_POST['price_set_id'];
502 $getOnlyPriceSetElements = FALSE;
505 $this->set('priceSetId', $this->_priceSetId
);
506 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
508 // get only price set form elements.
509 if ($getOnlyPriceSetElements) {
513 // use to build form during form rule.
514 $this->assign('buildPriceSet', $buildPriceSet);
516 $defaults = $this->_values
;
517 $additionalDetailFields = array(
521 'non_deductible_amount',
525 foreach ($additionalDetailFields as $key) {
526 if (!empty($defaults[$key])) {
527 $defaults['hidden_AdditionalDetail'] = 1;
532 if ($this->_productDAO
) {
533 if ($this->_productDAO
->product_id
) {
534 $defaults['hidden_Premium'] = 1;
538 if ($this->_noteID
&&
539 isset($this->_values
['note'])
541 $defaults['hidden_AdditionalDetail'] = 1;
545 ts('Additional Details') => 'AdditionalDetail',
548 //Add Premium pane only if Premium is exists.
549 $dao = new CRM_Contribute_DAO_Product();
552 if ($dao->find(TRUE)) {
553 $paneNames[ts('Premium Information')] = 'Premium';
557 if (CRM_Core_Payment_Form
::buildPaymentForm($this, $this->_paymentProcessor
, FALSE, TRUE) == TRUE) {
558 if (!empty($this->_recurPaymentProcessors
)) {
559 $buildRecurBlock = TRUE;
561 // ppID denotes a pledge payment.
562 foreach ($this->_paymentProcessors
as $processor) {
563 if (!empty($processor['is_recur']) && !empty($processor['object']) && $processor['object']->supports('recurContributionsForPledges')) {
564 $buildRecurBlock = TRUE;
567 $buildRecurBlock = FALSE;
570 if ($buildRecurBlock) {
571 CRM_Contribute_Form_Contribution_Main
::buildRecur($this);
572 $this->setDefaults(array('is_recur' => 0));
573 $this->assign('buildRecurBlock', TRUE);
574 $recurJs = array('onChange' => "buildRecurBlock( this.value ); return false;");
580 foreach ($paneNames as $name => $type) {
581 $allPanes[$name] = $this->generatePane($type, $defaults);
584 $qfKey = $this->controller
->_key
;
585 $this->assign('qfKey', $qfKey);
586 $this->assign('allPanes', $allPanes);
588 $this->addFormRule(array('CRM_Contribute_Form_Contribution', 'formRule'), $this);
590 if ($this->_formType
) {
591 $this->assign('formType', $this->_formType
);
595 $this->applyFilter('__ALL__', 'trim');
597 if ($this->_action
& CRM_Core_Action
::DELETE
) {
598 $this->addButtons(array(
601 'name' => ts('Delete'),
602 'spacing' => ' ',
607 'name' => ts('Cancel'),
614 //need to assign custom data type and subtype to the template
615 $this->assign('customDataType', 'Contribution');
616 $this->assign('customDataSubType', $this->_contributionType
);
617 $this->assign('entityID', $this->_id
);
619 if ($this->_context
== 'standalone') {
620 $this->addEntityRef('contact_id', ts('Contact'), array(
622 'api' => array('extra' => array('email')),
626 $attributes = CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Contribution');
628 // Check permissions for financial type first
629 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes, $this->_action
);
630 if (empty($financialTypes)) {
631 CRM_Core_Error
::statusBounce(ts('You do not have all the permissions needed for this page.'));
633 $financialType = $this->add('select', 'financial_type_id',
634 ts('Financial Type'),
635 array('' => ts('- select -')) +
$financialTypes,
637 array('onChange' => "CRM.buildCustomData( 'Contribution', this.value );")
640 $paymentInstrument = FALSE;
642 $paymentInstrument = $this->add('select', 'payment_instrument_id',
643 ts('Payment Method'),
644 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant
::paymentInstrument(),
645 TRUE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
649 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), array('class' => 'twelve') +
$attributes['trxn_id']);
651 //add receipt for offline contribution
652 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
654 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
656 $status = CRM_Contribute_PseudoConstant
::contributionStatus();
658 // suppressing contribution statuses that are NOT relevant to pledges (CRM-5169)
659 $statusName = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
666 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
669 elseif ((!$this->_ppID
&& $this->_id
) ||
!$this->_id
) {
670 $suppressFlag = FALSE;
672 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
673 if (CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails)) {
674 $suppressFlag = TRUE;
677 if (!$suppressFlag) {
682 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
686 unset($status[CRM_Utils_Array
::key('Overdue', $statusName)]);
690 // define the status IDs that show the cancellation info, see CRM-17589
691 $cancelInfo_show_ids = array();
692 foreach ($statusName as $status_id => $status_name) {
693 if ($status_name == 'Cancelled' ||
$status_name == 'Refunded') {
694 $cancelInfo_show_ids[] = "'$status_id'";
697 $this->assign('cancelInfo_show_ids', implode(',', $cancelInfo_show_ids));
700 $contributionStatus = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_id
, 'contribution_status_id');
701 $name = CRM_Utils_Array
::value($contributionStatus, $statusName);
706 unset($status[CRM_Utils_Array
::key('In Progress', $statusName)]);
707 unset($status[CRM_Utils_Array
::key('Pending', $statusName)]);
708 unset($status[CRM_Utils_Array
::key('Failed', $statusName)]);
713 unset($status[CRM_Utils_Array
::key('Refunded', $statusName)]);
724 unset($status[CRM_Utils_Array
::key($suppress, $statusName)]);
730 unset($status[CRM_Utils_Array
::key('Refunded', $statusName)]);
733 $this->add('select', 'contribution_status_id',
734 ts('Contribution Status'),
740 $this->addDateTime('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
742 if ($this->_online
) {
743 $this->assign('hideCalender', TRUE);
745 $checkNumber = $this->add('text', 'check_number', ts('Check Number'), $attributes['check_number']);
747 $this->addDateTime('receipt_date', ts('Receipt Date'), FALSE, array('formatType' => 'activityDateTime'));
748 $this->addDateTime('cancel_date', ts('Cancelled / Refunded Date'), FALSE, array('formatType' => 'activityDateTime'));
750 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
751 $this->add('text', 'refund_trxn_id', ts('Transaction ID for the refund payment'));
752 $element = $this->add('select',
753 'payment_processor_id',
754 ts('Payment Processor'),
760 if ($this->_online
) {
765 if (empty($this->_lineItems
)) {
766 $buildPriceSet = FALSE;
767 $priceSets = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute');
768 if (!empty($priceSets) && !$this->_ppID
) {
769 $buildPriceSet = TRUE;
772 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
773 // and if we already have line items for that participant. CRM-5095
774 if ($buildPriceSet && $this->_id
) {
775 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
776 $pledgePaymentId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
781 if ($pledgePaymentId) {
782 $buildPriceSet = FALSE;
784 if ($participantID = CRM_Utils_Array
::value('participant', $componentDetails)) {
785 $participantLI = CRM_Price_BAO_LineItem
::getLineItems($participantID);
786 if (!CRM_Utils_System
::isNull($participantLI)) {
787 $buildPriceSet = FALSE;
792 $hasPriceSets = FALSE;
793 if ($buildPriceSet) {
794 $hasPriceSets = TRUE;
795 // CRM-16451: set financial type of 'Price Set' in back office contribution
796 // instead of selecting manually
797 $financialTypeIds = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviContribute', 'financial_type_id');
798 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
800 '' => ts('Choose price set'),
802 NULL, array('onchange' => "buildAmount( this.value, " . json_encode($financialTypeIds) . ");")
804 if ($this->_online
&& !($this->_action
& CRM_Core_Action
::UPDATE
)) {
808 $this->assign('hasPriceSets', $hasPriceSets);
809 $currencyFreeze = FALSE;
810 if (!($this->_action
& CRM_Core_Action
::UPDATE
)) {
811 if ($this->_online ||
$this->_ppID
) {
812 $attributes['total_amount'] = array_merge($attributes['total_amount'], array(
814 'style' => "background-color:#EBECE4",
816 $optionTypes = array(
817 '1' => ts('Adjust Pledge Payment Schedule?'),
818 '2' => ts('Adjust Total Pledge Amount?'),
820 $this->addRadio('option_type',
826 $currencyFreeze = TRUE;
830 $totalAmount = $this->addMoney('total_amount',
832 ($hasPriceSets) ?
FALSE : TRUE,
833 $attributes['total_amount'],
834 TRUE, 'currency', NULL, $currencyFreeze
838 $this->add('text', 'source', ts('Source'), CRM_Utils_Array
::value('source', $attributes));
840 // CRM-7362 --add campaigns.
841 CRM_Campaign_BAO_Campaign
::addCampaign($this, CRM_Utils_Array
::value('campaign_id', $this->_values
));
843 CRM_Contribute_Form_SoftCredit
::buildQuickForm($this);
847 $js = array('onclick' => "return verify( );");
850 $mailingInfo = Civi
::settings()->get('mailing_backend');
851 $this->assign('outBound_option', $mailingInfo['outBound_option']);
853 $this->addButtons(array(
856 'name' => ts('Save'),
862 'name' => ts('Save and New'),
868 'name' => ts('Cancel'),
873 // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
874 // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
875 if ($this->_id
&& $this->_values
['contribution_status_id'] == array_search('Cancelled', $statusName)) {
877 $totalAmount->freeze();
879 $checkNumber->freeze();
880 $paymentInstrument->freeze();
882 $financialType->freeze();
885 // if contribution is related to membership or participant freeze Financial Type, Amount
886 if ($this->_id
&& isset($this->_values
['tax_amount'])) {
887 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
888 if (CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails)) {
890 $totalAmount->freeze();
892 $financialType->freeze();
893 $this->assign('freezeFinancialType', TRUE);
897 if ($this->_action
& CRM_Core_Action
::VIEW
) {
905 * @param array $fields
906 * The input form values.
907 * @param array $files
908 * The uploaded files if any.
912 * true if no errors, else array of errors
914 public static function formRule($fields, $files, $self) {
916 // Check for Credit Card Contribution.
918 if (empty($fields['payment_processor_id'])) {
919 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
922 // validate payment instrument (e.g. credit card number)
923 CRM_Core_Payment_Form
::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, NULL);
927 // Do the amount validations.
928 if (empty($fields['total_amount']) && empty($self->_lineItems
)) {
929 if ($priceSetId = CRM_Utils_Array
::value('price_set_id', $fields)) {
930 CRM_Price_BAO_PriceField
::priceSetValidation($priceSetId, $fields, $errors);
934 $softErrors = CRM_Contribute_Form_SoftCredit
::formRule($fields, $errors, $self);
936 if (!empty($fields['total_amount']) && (!empty($fields['net_amount']) ||
!empty($fields['fee_amount']))) {
937 $sum = CRM_Utils_Rule
::cleanMoney($fields['net_amount']) + CRM_Utils_Rule
::cleanMoney($fields['fee_amount']);
938 // For taxable contribution we need to deduct taxable amount from
939 // (net amount + fee amount) before comparing it with total amount
940 if (!empty($self->_values
['tax_amount'])) {
941 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($self->_id
);
942 if (!(CRM_Utils_Array
::value('membership', $componentDetails) ||
943 CRM_Utils_Array
::value('participant', $componentDetails))
945 $sum = CRM_Utils_Money
::format($sum - $self->_values
['tax_amount'], NULL, '%a');
948 if (CRM_Utils_Rule
::cleanMoney($fields['total_amount']) != $sum) {
949 $errors['total_amount'] = ts('The sum of fee amount and net amount must be equal to total amount');
953 //CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
954 CRM_Contribute_BAO_ContributionRecur
::validateRecurContribution($fields, $files, $self, $errors);
956 // Form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
957 if (($self->_action
& CRM_Core_Action
::UPDATE
)
959 && $self->_values
['contribution_status_id'] != $fields['contribution_status_id']
961 CRM_Contribute_BAO_Contribution
::checkStatusValidation($self->_values
, $fields, $errors);
963 // CRM-16015, add form-rule to restrict change of financial type if using price field of different financial type
964 if (($self->_action
& CRM_Core_Action
::UPDATE
)
966 && $self->_values
['financial_type_id'] != $fields['financial_type_id']
968 CRM_Contribute_BAO_Contribution
::checkFinancialTypeChange(NULL, $self->_id
, $errors);
970 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
971 if (!empty($fields['fee_amount']) && !empty($fields['financial_type_id']) && $financialType = CRM_Contribute_BAO_Contribution
::validateFinancialType($fields['financial_type_id'])) {
972 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
975 // $trxn_id must be unique CRM-13919
976 if (!empty($fields['trxn_id'])) {
977 $queryParams = array(1 => array($fields['trxn_id'], 'String'));
978 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
980 $queryParams[2] = array((int) $self->_id
, 'Integer');
981 $query .= ' and id !=%2';
983 $tCnt = CRM_Core_DAO
::singleValueQuery($query, $queryParams);
985 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', array(1 => $fields['trxn_id']));
989 $errors = array_merge($errors, $softErrors);
994 * Process the form submission.
996 public function postProcess() {
997 if ($this->_action
& CRM_Core_Action
::DELETE
) {
998 CRM_Contribute_BAO_Contribution
::deleteContribution($this->_id
);
999 CRM_Core_Session
::singleton()->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
1000 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1004 // Get the submitted form values.
1005 $submittedValues = $this->controller
->exportValues($this->_name
);
1008 $contribution = $this->submit($submittedValues, $this->_action
, $this->_ppID
);
1010 catch (PaymentProcessorException
$e) {
1011 // Set the contribution mode.
1012 $urlParams = "action=add&cid={$this->_contactID}";
1014 $urlParams .= "&mode={$this->_mode}";
1016 if (!empty($this->_ppID
)) {
1017 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
1020 CRM_Core_Error
::statusBounce($e->getMessage(), $urlParams, ts('Payment Processor Error'));
1022 $session = CRM_Core_Session
::singleton();
1023 $buttonName = $this->controller
->getButtonName();
1024 if ($this->_context
== 'standalone') {
1025 if ($buttonName == $this->getButtonName('upload', 'new')) {
1026 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contribute/add',
1027 'reset=1&action=add&context=standalone'
1031 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
1032 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1036 elseif ($this->_context
== 'contribution' && $this->_mode
&& $buttonName == $this->getButtonName('upload', 'new')) {
1037 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
1038 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
1041 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1042 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/contribution',
1043 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
1047 //store contribution ID if not yet set (on create)
1048 if (empty($this->_id
) && !empty($contribution->id
)) {
1049 $this->_id
= $contribution->id
;
1054 * Process credit card payment.
1056 * @param array $submittedValues
1057 * @param array $lineItem
1059 * @param int $contactID
1062 * @return bool|\CRM_Contribute_DAO_Contribution
1063 * @throws \CRM_Core_Exception
1064 * @throws \Civi\Payment\Exception\PaymentProcessorException
1066 protected function processCreditCard($submittedValues, $lineItem, $contactID) {
1067 $isTest = ($this->_mode
== 'test') ?
1 : 0;
1068 // CRM-12680 set $_lineItem if its not set
1069 // @todo - I don't believe this would ever BE set. I can't find anywhere in the code.
1070 // It would be better to pass line item out to functions than $this->_lineItem as
1071 // we don't know what is being changed where.
1072 if (empty($this->_lineItem
) && !empty($lineItem)) {
1073 $this->_lineItem
= $lineItem;
1076 $this->_paymentObject
= Civi\Payment\System
::singleton()->getById($submittedValues['payment_processor_id']);
1077 $this->_paymentProcessor
= $this->_paymentObject
->getPaymentProcessor();
1079 // Set source if not set
1080 if (empty($submittedValues['source'])) {
1081 $userID = CRM_Core_Session
::singleton()->get('userID');
1082 $userSortName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1085 $submittedValues['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
1088 $params = $submittedValues;
1089 $this->_params
= array_merge($this->_params
, $submittedValues);
1091 // Mapping requiring documentation.
1092 $this->_params
['payment_processor'] = $submittedValues['payment_processor_id'];
1094 $now = date('YmdHis');
1096 // we need to retrieve email address
1097 if ($this->_context
== 'standalone' && !empty($submittedValues['is_email_receipt'])) {
1098 list($this->userDisplayName
,
1100 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contactID);
1101 $this->assign('displayName', $this->userDisplayName
);
1104 $this->_contributorEmail
= $this->userEmail
;
1105 $this->_contributorContactID
= $contactID;
1106 $this->processBillingAddress();
1107 if (!empty($params['source'])) {
1108 unset($params['source']);
1111 $this->_params
['amount'] = $this->_params
['total_amount'];
1112 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
1113 // function to get correct amount level consistently. Remove setting of the amount level in
1114 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
1115 // to cover all variants.
1116 $this->_params
['amount_level'] = 0;
1117 $this->_params
['description'] = ts("Contribution submitted by a staff person using contributor's credit card");
1118 $this->_params
['currencyID'] = CRM_Utils_Array
::value('currency',
1120 CRM_Core_Config
::singleton()->defaultCurrency
1123 if (!empty($this->_params
['receive_date'])) {
1124 $this->_params
['receive_date'] = CRM_Utils_Date
::processDate($this->_params
['receive_date'], $this->_params
['receive_date_time']);
1127 $this->_params
['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $params);
1128 $this->_params
['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $params);
1129 $this->_params
['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $params);
1131 //Add common data to formatted params
1132 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($params, $this->_params
, $this);
1134 if (empty($this->_params
['invoice_id'])) {
1135 $this->_params
['invoiceID'] = md5(uniqid(rand(), TRUE));
1138 $this->_params
['invoiceID'] = $this->_params
['invoice_id'];
1141 // At this point we've created a contact and stored its address etc
1142 // all the payment processors expect the name and address to be in the
1143 // so we copy stuff over to first_name etc.
1144 $paymentParams = $this->_params
;
1145 $paymentParams['contactID'] = $contactID;
1146 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $paymentParams, TRUE);
1148 $financialType = new CRM_Financial_DAO_FinancialType();
1149 $financialType->id
= $params['financial_type_id'];
1150 $financialType->find(TRUE);
1152 // Add some financial type details to the params list
1153 // if folks need to use it.
1154 $paymentParams['contributionType_name'] = $this->_params
['contributionType_name'] = $financialType->name
;
1155 $paymentParams['contributionPageID'] = NULL;
1157 if (!empty($this->_params
['is_email_receipt'])) {
1158 $paymentParams['email'] = $this->userEmail
;
1159 $paymentParams['is_email_receipt'] = 1;
1162 $paymentParams['is_email_receipt'] = 0;
1163 $this->_params
['is_email_receipt'] = 0;
1165 if (!empty($this->_params
['receive_date'])) {
1166 $paymentParams['receive_date'] = $this->_params
['receive_date'];
1169 $this->_params
['receive_date'] = $now;
1171 if (!empty($this->_params
['is_email_receipt'])) {
1172 $this->_params
['receipt_date'] = $now;
1175 $this->_params
['receipt_date'] = CRM_Utils_Date
::processDate($this->_params
['receipt_date'],
1176 $params['receipt_date_time'], TRUE
1180 $this->set('params', $this->_params
);
1182 $this->assign('receive_date', $this->_params
['receive_date']);
1184 // Result has all the stuff we need
1185 // lets archive it to a financial transaction
1186 if ($financialType->is_deductible
) {
1187 $this->assign('is_deductible', TRUE);
1188 $this->set('is_deductible', TRUE);
1190 $contributionParams = array(
1191 'contact_id' => $contactID,
1192 'line_item' => $lineItem,
1193 'is_test' => $isTest,
1194 'campaign_id' => CRM_Utils_Array
::value('campaign_id', $this->_params
),
1195 'contribution_page_id' => CRM_Utils_Array
::value('contribution_page_id', $this->_params
),
1196 'source' => CRM_Utils_Array
::value('source', $paymentParams, CRM_Utils_Array
::value('description', $paymentParams)),
1197 'thankyou_date' => CRM_Utils_Array
::value('thankyou_date', $this->_params
),
1200 if (empty($paymentParams['is_pay_later'])) {
1201 // @todo look up payment_instrument_id on payment processor table.
1202 $contributionParams['payment_instrument_id'] = 1;
1205 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processFormContribution($this,
1208 $contributionParams,
1212 CRM_Utils_Array
::value('is_recur', $this->_params
)
1215 $paymentParams['contributionID'] = $contribution->id
;
1216 $paymentParams['contributionTypeID'] = $contribution->financial_type_id
;
1217 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
1218 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1220 if ($paymentParams['amount'] > 0.0) {
1221 // force a re-get of the payment processor in case the form changed it, CRM-7179
1222 // NOTE - I expect this is obsolete.
1223 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
1225 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id');
1226 $result = $payment->doPayment($paymentParams, 'contribute');
1227 $this->assign('trxn_id', $result['trxn_id']);
1228 $contribution->trxn_id
= $result['trxn_id'];
1229 /* Our scenarios here are
1230 * 1) the payment failed & an Exception should have been thrown
1231 * 2) the payment succeeded but the payment is not immediate (for example a recurring payment
1232 * with a delayed start)
1233 * 3) the payment succeeded with an immediate payment.
1235 * The doPayment function ensures that payment_status_id is always set
1236 * as historically we have had to guess from the context - ie doDirectPayment
1237 * = error or success, unless it is a recurring contribution in which case it is pending.
1239 if ($result['payment_status_id'] == array_search('Completed', $statuses)) {
1241 civicrm_api3('contribution', 'completetransaction', array(
1242 'id' => $contribution->id
,
1243 'trxn_id' => $result['trxn_id'],
1244 'payment_processor_id' => $this->_paymentProcessor
['id'],
1245 'is_transactional' => FALSE,
1246 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $result),
1248 // This has now been set to 1 in the DB - declare it here also
1249 $contribution->contribution_status_id
= 1;
1251 catch (CiviCRM_API3_Exception
$e) {
1252 if ($e->getErrorCode() != 'contribution_completed') {
1253 throw new CRM_Core_Exception('Failed to update contribution in database');
1258 // Save the trxn_id.
1259 $contribution->save();
1262 catch (PaymentProcessorException
$e) {
1263 CRM_Contribute_BAO_Contribution
::failPayment($contribution->id
, $paymentParams['contactID'], $e->getMessage());
1264 throw new PaymentProcessorException($e->getMessage());
1267 // Send receipt mail.
1268 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1269 if ($contribution->id
&& !empty($this->_params
['is_email_receipt'])) {
1270 $this->_params
['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $result);
1271 $this->_params
['contact_id'] = $contactID;
1272 $this->_params
['contribution_id'] = $contribution->id
;
1273 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $this->_params
, TRUE)) {
1274 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1278 return $contribution;
1282 * Generate the data to construct a snippet based pane.
1284 * This form also assigns the showAdditionalInfo var based on historical code.
1285 * This appears to mean 'there is a pane to show'.
1287 * @param string $type
1288 * Type of Pane - this is generally used to determine the function name used to build it
1289 * - e.g CreditCard, AdditionalDetail
1290 * @param array $defaults
1293 * We aim to further refactor & simplify this but currently
1295 * - should additional info be shown?
1297 protected function generatePane($type, $defaults) {
1298 $urlParams = "snippet=4&formType={$type}";
1300 $urlParams .= "&mode={$this->_mode}";
1304 if ($type == 'CreditCard' ||
1305 $type == 'DirectDebit'
1311 'url' => CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams),
1316 // See if we need to include this paneName in the current form.
1317 if ($this->_formType
== $type ||
!empty($_POST["hidden_{$type}"]) ||
1318 CRM_Utils_Array
::value("hidden_{$type}", $defaults)
1320 $this->assign('showAdditionalInfo', TRUE);
1321 $pane['open'] = 'true';
1324 if ($type == 'CreditCard' ||
$type == 'DirectDebit') {
1325 // @todo would be good to align tpl name with form name...
1326 // @todo document why this hidden variable is required.
1327 $this->add('hidden', 'hidden_' . $type, 1);
1331 $additionalInfoFormFunction = 'build' . $type;
1332 CRM_Contribute_Form_AdditionalInfo
::$additionalInfoFormFunction($this);
1338 * Wrapper for unit testing the post process submit function.
1340 * (If we expose through api we can get default additions 'for free').
1342 * @param array $params
1343 * @param int $action
1344 * @param string|null $creditCardMode
1346 * @throws \CiviCRM_API3_Exception
1348 public function testSubmit($params, $action, $creditCardMode = NULL) {
1350 'soft_credit_contact_id' => array(),
1351 'receipt_date' => '',
1352 'receipt_date_time' => '',
1353 'cancel_date' => '',
1354 'cancel_date_time' => '',
1355 'hidden_Premium' => 1,
1358 if (!empty($params['id'])) {
1359 $existingContribution = civicrm_api3('contribution', 'getsingle', array(
1360 'id' => $params['id'],
1362 $this->_id
= $params['id'];
1365 $existingContribution = array();
1368 $this->_defaults
['contribution_status_id'] = CRM_Utils_Array
::value('contribution_status_id',
1369 $existingContribution
1372 $this->_defaults
['total_amount'] = CRM_Utils_Array
::value('total_amount',
1373 $existingContribution
1376 if ($creditCardMode) {
1377 $this->_mode
= $creditCardMode;
1380 // Required because processCreditCard calls set method on this.
1381 $_SERVER['REQUEST_METHOD'] = 'GET';
1382 $this->controller
= new CRM_Core_Controller();
1384 CRM_Contribute_Form_AdditionalInfo
::buildPremium($this);
1386 $this->_fields
= array();
1387 $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array
::value('pledge_payment_id', $params));
1392 * @param array $submittedValues
1394 * @param int $action
1396 * - CRM_Core_Action::UPDATE
1398 * @param $pledgePaymentID
1401 * @throws \Exception
1403 protected function submit($submittedValues, $action, $pledgePaymentID) {
1404 $softParams = $softIDs = array();
1405 $pId = $contribution = $isRelatedId = FALSE;
1406 $this->_params
= $submittedValues;
1407 $this->beginPostProcess();
1409 if (!empty($submittedValues['price_set_id']) && $action & CRM_Core_Action
::UPDATE
) {
1410 $line = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'contribution');
1411 $lineID = key($line);
1412 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array
::value('price_field_id', $line[$lineID]), 'price_set_id');
1413 $quickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1414 // Why do we do this? Seems like a like a wrapper for old functionality - but single line price sets & quick
1415 // config should be treated the same.
1417 CRM_Price_BAO_LineItem
::deleteLineItems($this->_id
, 'civicrm_contribution');
1421 // Process price set and get total amount and line items.
1422 $lineItem = array();
1423 $priceSetId = CRM_Utils_Array
::value('price_set_id', $submittedValues);
1424 if (empty($priceSetId) && !$this->_id
) {
1425 $this->_priceSetId
= $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1426 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
1427 $fieldID = key($this->_priceSet
['fields']);
1428 $fieldValueId = key($this->_priceSet
['fields'][$fieldID]['options']);
1429 $this->_priceSet
['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1430 $submittedValues['price_' . $fieldID] = 1;
1433 // Every contribution has a price-set - the only reason it shouldn't be set is if we are dealing with
1434 // quick config (very very arguably) & yet we see that this could still be quick config so this should be understood
1435 // as a point of fragility rather than a logical 'if' clause.
1437 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
1438 $submittedValues, $lineItem[$priceSetId]);
1439 // Unset tax amount for offline 'is_quick_config' contribution.
1440 // @todo WHY - quick config was conceived as a quick way to configure contribution forms.
1441 // this is an example of 'other' functionality being hung off it.
1442 if ($this->_priceSet
['is_quick_config'] &&
1443 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant
::getTaxRates())
1445 unset($submittedValues['tax_amount']);
1447 $submittedValues['total_amount'] = CRM_Utils_Array
::value('amount', $submittedValues);
1450 if ($this->_compId
) {
1451 if ($this->_context
== 'participant') {
1452 $pId = $this->_compId
;
1454 elseif ($this->_context
== 'membership') {
1455 $isRelatedId = TRUE;
1458 $pId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id
, 'participant_id', 'contribution_id');
1462 $contributionDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1463 if (array_key_exists('membership', $contributionDetails)) {
1464 $isRelatedId = TRUE;
1466 elseif (array_key_exists('participant', $contributionDetails)) {
1467 $pId = $contributionDetails['participant'];
1472 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id
) {
1473 // CRM-10117 update the line items for participants.
1474 // @todo - if we are completing a contribution then the api call
1475 // civicrm_api3('Contribution', 'completetransaction') should take care of
1476 // all associated updates rather than replicating them on the form layer.
1478 $entityTable = 'participant';
1480 $isRelatedId = FALSE;
1481 $participantParams = array(
1482 'fee_amount' => $submittedValues['total_amount'],
1485 CRM_Event_BAO_Participant
::add($participantParams);
1486 if (empty($this->_lineItems
)) {
1487 $this->_lineItems
[] = CRM_Price_BAO_LineItem
::getLineItems($entityID, 'participant', 1);
1491 $entityTable = 'contribution';
1492 $entityID = $this->_id
;
1495 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($entityID, $entityTable, NULL, TRUE, $isRelatedId);
1496 foreach (array_keys($lineItems) as $id) {
1497 $lineItems[$id]['id'] = $id;
1499 $itemId = key($lineItems);
1500 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1501 $this->_priceSetId
= CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1504 // @todo see above - new functionality has been inappropriately added to the quick config concept
1505 // and new functionality has been added onto the form layer rather than the BAO :-(
1506 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1507 //CRM-16833: Ensure tax is applied only once for membership conribution, when status changed.(e.g Pending to Completed).
1508 $componentDetails = CRM_Contribute_BAO_Contribution
::getComponentDetails($this->_id
);
1509 if (!(CRM_Utils_Array
::value('membership', $componentDetails) || CRM_Utils_Array
::value('participant', $componentDetails))) {
1510 if (!($this->_action
& CRM_Core_Action
::UPDATE
&& (($this->_defaults
['contribution_status_id'] != $submittedValues['contribution_status_id'])))) {
1511 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule
::cleanMoney(CRM_Utils_Array
::value('total_amount', $submittedValues));
1515 // Update line total and total amount with tax on edit.
1516 $financialItemsId = CRM_Core_PseudoConstant
::getTaxRates();
1517 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1518 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1521 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1522 $submittedValues['tax_amount'] = 'null';
1524 if ($lineItems[$itemId]['tax_rate']) {
1525 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total'];
1526 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] +
$lineItems[$itemId]['tax_amount'];
1527 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1530 // CRM-10117 update the line items for participants.
1531 if (!empty($lineItems[$itemId]['price_field_id'])) {
1532 $lineItem[$this->_priceSetId
] = $lineItems;
1537 if ($this->_priceSetId
&& CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config')) {
1540 //CRM-11529 for quick config back office transactions
1541 //when financial_type_id is passed in form, update the
1542 //line items with the financial type selected in form
1543 // NOTE that this IS still a legitimate use of 'quick-config' for contributions under the current DB but
1544 // we should look at having a price field per contribution type & then there would be little reason
1545 // for the back-office contribution form postProcess to know if it is a quick-config form.
1546 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array
::value($this->_priceSetId
, $lineItem)
1548 foreach ($lineItem[$this->_priceSetId
] as &$values) {
1549 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1553 if (!isset($submittedValues['total_amount'])) {
1554 $submittedValues['total_amount'] = CRM_Utils_Array
::value('total_amount', $this->_values
);
1556 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
1558 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
1559 if ($this->_id
&& count($isEmpty) == 1 && key($isEmpty) == NULL) {
1560 //Delete existing soft credit records if soft credit list is empty on update
1561 CRM_Contribute_BAO_ContributionSoft
::del(array('contribution_id' => $this->_id
, 'pcp_id' => 0));
1564 // set the contact, when contact is selected
1565 if (!empty($submittedValues['contact_id'])) {
1566 $this->_contactID
= $submittedValues['contact_id'];
1569 $formValues = $submittedValues;
1571 // Credit Card Contribution.
1573 $paramsSetByPaymentProcessingSubsystem = array(
1575 'payment_instrument_id',
1576 'contribution_status_id',
1580 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1581 if (isset($formValues[$key])) {
1582 unset($formValues[$key]);
1585 $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID
);
1586 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1587 $formValues[$key] = $contribution->$key;
1591 // Offline Contribution.
1592 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1594 // get the required field value only.
1596 $params = $ids = array();
1598 $params['contact_id'] = $this->_contactID
;
1599 $params['currency'] = $this->getCurrency($submittedValues);
1601 //format soft-credit/pcp param first
1602 CRM_Contribute_BAO_ContributionSoft
::formatSoftCreditParams($submittedValues, $this);
1603 $params = array_merge($params, $submittedValues);
1606 'financial_type_id',
1607 'contribution_status_id',
1608 'payment_instrument_id',
1613 foreach ($fields as $f) {
1614 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1617 // CRM-5740 if priceset is used, no need to cleanup money.
1619 $params['skipCleanMoney'] = 1;
1628 foreach ($dates as $d) {
1629 $params[$d] = CRM_Utils_Date
::processDate($formValues[$d], $formValues[$d . '_time'], TRUE);
1632 if (!empty($formValues['is_email_receipt'])) {
1633 $params['receipt_date'] = date("Y-m-d");
1636 if ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Cancelled', 'name')
1637 ||
$params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name')
1639 if (CRM_Utils_System
::isNull(CRM_Utils_Array
::value('cancel_date', $params))) {
1640 $params['cancel_date'] = date('YmdHis');
1644 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1647 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1648 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1649 if ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Pending', 'name')) {
1650 $params['is_pay_later'] = 1;
1652 elseif ($params['contribution_status_id'] == CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name')) {
1653 $params['is_pay_later'] = 0;
1656 $ids['contribution'] = $params['id'] = $this->_id
;
1658 // Add Additional common information to formatted params.
1659 CRM_Contribute_Form_AdditionalInfo
::postProcessCommon($formValues, $params, $this);
1661 $params['contribution_mode'] = 'participant';
1662 $params['participant_id'] = $pId;
1663 $params['skipLineItem'] = 1;
1665 elseif ($isRelatedId) {
1666 $params['contribution_mode'] = 'membership';
1668 $params['line_item'] = $lineItem;
1669 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array
::value('id', $this->_paymentProcessor
);
1670 if (isset($submittedValues['tax_amount'])) {
1671 $params['tax_amount'] = $submittedValues['tax_amount'];
1673 //create contribution.
1674 if ($isQuickConfig) {
1675 $params['is_quick_config'] = 1;
1677 $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
1679 // we are already handling note below, so to avoid duplicate notes against $contribution
1680 if (!empty($params['note']) && !empty($submittedValues['note'])) {
1681 unset($params['note']);
1683 $contribution = CRM_Contribute_BAO_Contribution
::create($params, $ids);
1685 // process associated membership / participant, CRM-4395
1686 if ($contribution->id
&& $action & CRM_Core_Action
::UPDATE
) {
1687 $this->statusMessage
[] = $this->updateRelatedComponent($contribution->id
,
1688 $contribution->contribution_status_id
,
1689 CRM_Utils_Array
::value('contribution_status_id',
1692 $contribution->receive_date
1696 array_unshift($this->statusMessage
, ts('The contribution record has been saved.'));
1698 $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
1700 //send receipt mail.
1701 if ($contribution->id
&& !empty($formValues['is_email_receipt'])) {
1702 $formValues['contact_id'] = $this->_contactID
;
1703 $formValues['contribution_id'] = $contribution->id
;
1705 $formValues +
= CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
);
1707 // to get 'from email id' for send receipt
1708 $this->fromEmailId
= $formValues['from_email_address'];
1709 if (CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $formValues)) {
1710 $this->statusMessage
[] = ts('A receipt has been emailed to the contributor.');
1714 $this->statusMessageTitle
= ts('Saved');
1718 if ($contribution->id
&& isset($formValues['product_name'][0])) {
1719 CRM_Contribute_Form_AdditionalInfo
::processPremium($submittedValues, $contribution->id
,
1720 $this->_premiumID
, $this->_options
1724 if ($contribution->id
&& !empty($submittedValues['note'])) {
1725 CRM_Contribute_Form_AdditionalInfo
::processNote($submittedValues, $this->_contactID
, $contribution->id
, $this->_noteID
);
1728 CRM_Core_Session
::setStatus(implode(' ', $this->statusMessage
), $this->statusMessageTitle
, 'success');
1730 CRM_Contribute_BAO_Contribution
::updateRelatedPledge(
1734 (CRM_Utils_Array
::value('option_type', $formValues) == 2) ?
TRUE : FALSE,
1735 $formValues['total_amount'],
1736 CRM_Utils_Array
::value('total_amount', $this->_defaults
),
1737 $formValues['contribution_status_id'],
1738 CRM_Utils_Array
::value('contribution_status_id', $this->_defaults
)
1740 return $contribution;
1744 * Assign tax calculations to contribution receipts.
1746 * @param array $submittedValues
1747 * @param int $action
1748 * @param array $lineItem
1750 protected function invoicingPostProcessHook($submittedValues, $action, $lineItem) {
1752 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
1753 if (!CRM_Utils_Array
::value('invoicing', $invoiceSettings)) {
1757 $getTaxDetails = FALSE;
1758 if ($action & CRM_Core_Action
::ADD
) {
1761 elseif ($action & CRM_Core_Action
::UPDATE
) {
1762 $line = $this->_lineItems
;
1764 foreach ($line as $key => $value) {
1765 foreach ($value as $v) {
1766 if (isset($taxRate[(string) CRM_Utils_Array
::value('tax_rate', $v)])) {
1767 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $v);
1770 if (isset($v['tax_rate'])) {
1771 $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $v);
1772 $getTaxDetails = TRUE;
1778 if ($action & CRM_Core_Action
::UPDATE
) {
1779 if (isset($submittedValues['tax_amount'])) {
1780 $totalTaxAmount = $submittedValues['tax_amount'];
1783 $totalTaxAmount = $this->_values
['tax_amount'];
1785 $this->assign('totalTaxAmount', $totalTaxAmount);
1786 $this->assign('dataArray', $taxRate);
1789 if (!empty($submittedValues['price_set_id'])) {
1790 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1791 $this->assign('getTaxDetails', $getTaxDetails);
1792 $this->assign('dataArray', $taxRate);
1793 $this->assign('taxTerm', CRM_Utils_Array
::value('tax_term', $invoiceSettings));
1796 $this->assign('totalTaxAmount', CRM_Utils_Array
::value('tax_amount', $submittedValues));
1802 * Calculate non deductible amount.
1805 * if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1806 * if non_deductible_amount does NOT exist - then calculate it depending on:
1807 * $financialType->is_deductible and whether there is a product (premium).
1810 * @param $formValues
1814 protected function calculateNonDeductibleAmount($params, $formValues) {
1815 if (!empty($params['non_deductible_amount'])) {
1816 return $params['non_deductible_amount'];
1819 $financialType = new CRM_Financial_DAO_FinancialType();
1820 $financialType->id
= $params['financial_type_id'];
1821 $financialType->find(TRUE);
1823 if ($financialType->is_deductible
) {
1825 if (isset($formValues['product_name'][0])) {
1826 $selectProduct = $formValues['product_name'][0];
1828 // if there is a product - compare the value to the contribution amount
1829 if (isset($selectProduct)) {
1830 $productDAO = new CRM_Contribute_DAO_Product();
1831 $productDAO->id
= $selectProduct;
1832 $productDAO->find(TRUE);
1833 // product value exceeds contribution amount
1834 if ($params['total_amount'] < $productDAO->price
) {
1835 return $params['total_amount'];
1837 // product value does NOT exceed contribution amount
1839 return $productDAO->price
;
1842 // contribution is deductible - but there is no product
1847 // contribution is NOT deductible
1849 return $params['total_amount'];