07daaa7368dfe1ba3858f43dc0554ad98aff3075
[civicrm-core.git] / CRM / Contribute / Form / Contribution.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 use Civi\Payment\Exception\PaymentProcessorException;
29
30 /**
31 * This class generates form components for processing a contribution.
32 */
33 class CRM_Contribute_Form_Contribution extends CRM_Contribute_Form_AbstractEditPayment {
34 /**
35 * The id of the contribution that we are processing.
36 *
37 * @var int
38 */
39 public $_id;
40
41 /**
42 * The id of the premium that we are processing.
43 *
44 * @var int
45 */
46 public $_premiumID = NULL;
47
48 /**
49 * @var CRM_Contribute_DAO_ContributionProduct
50 */
51 public $_productDAO = NULL;
52
53 /**
54 * The id of the note.
55 *
56 * @var int
57 */
58 public $_noteID;
59
60 /**
61 * The id of the contact associated with this contribution.
62 *
63 * @var int
64 */
65 public $_contactID;
66
67 /**
68 * The id of the pledge payment that we are processing.
69 *
70 * @var int
71 */
72 public $_ppID;
73
74 /**
75 * Is this contribution associated with an online.
76 * financial transaction
77 *
78 * @var boolean
79 */
80 public $_online = FALSE;
81
82 /**
83 * Stores all product options.
84 *
85 * @var array
86 */
87 public $_options;
88
89 /**
90 * Storage of parameters from form
91 *
92 * @var array
93 */
94 public $_params;
95
96 /**
97 * Store the contribution Type ID
98 *
99 * @var array
100 */
101 public $_contributionType;
102
103 /**
104 * The contribution values if an existing contribution
105 */
106 public $_values;
107
108 /**
109 * The pledge values if this contribution is associated with pledge
110 */
111 public $_pledgeValues;
112
113 public $_contributeMode = 'direct';
114
115 public $_context;
116
117 /**
118 * Parameter with confusing name.
119 * @todo what is it?
120 * @var string
121 */
122 public $_compContext;
123
124 public $_compId;
125
126 /**
127 * Possible From email addresses
128 * @var array
129 */
130 public $_fromEmails;
131
132 /**
133 * ID of from email
134 * @var integer
135 */
136 public $fromEmailId;
137
138 /**
139 * Store the line items if price set used.
140 */
141 public $_lineItems;
142
143 /**
144 * Line item
145 * @todo explain why we use lineItem & lineItems
146 * @var array
147 */
148 public $_lineItem;
149
150 /**
151 * @var array soft credit info
152 */
153 public $_softCreditInfo;
154
155 protected $_formType;
156
157 /**
158 * Array of the payment fields to be displayed in the payment fieldset (pane) in billingBlock.tpl
159 * this contains all the information to describe these fields from quickform. See CRM_Core_Form_Payment getPaymentFormFieldsMetadata
160 *
161 * @var array
162 */
163 public $_paymentFields = array();
164 /**
165 * Logged in user's email.
166 * @var string
167 */
168 public $userEmail;
169
170 /**
171 * Price set ID
172 * @var integer
173 */
174 public $_priceSetId;
175
176 /**
177 * Price set as an array
178 * @var array
179 */
180 public $_priceSet;
181
182 /**
183 * User display name
184 *
185 * @var string
186 */
187 public $userDisplayName;
188
189 /**
190 * Status message to be shown to the user.
191 *
192 * @var array
193 */
194 protected $statusMessage = array();
195
196 /**
197 * Status message title to be shown to the user.
198 *
199 * Generally the payment processor message title is 'Complete' and offline is 'Saved'
200 * although this might not be a good fit with the broad range of processors.
201 *
202 * @var string
203 */
204 protected $statusMessageTitle;
205
206 /**
207 * Explicitly declare the form context.
208 */
209 public function getDefaultContext() {
210 return 'create';
211 }
212
213 /**
214 * Set variables up before form is built.
215 */
216 public function preProcess() {
217 // Check permission for action.
218 if (!CRM_Core_Permission::checkActionPermission('CiviContribute', $this->_action)) {
219 // @todo replace with throw new CRM_Core_Exception().
220 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
221 }
222
223 parent::preProcess();
224
225 $this->_formType = CRM_Utils_Array::value('formType', $_GET);
226
227 // Get price set id.
228 $this->_priceSetId = CRM_Utils_Array::value('priceSetId', $_GET);
229 $this->set('priceSetId', $this->_priceSetId);
230 $this->assign('priceSetId', $this->_priceSetId);
231
232 // Get the pledge payment id
233 $this->_ppID = CRM_Utils_Request::retrieve('ppid', 'Positive', $this);
234
235 $this->assign('action', $this->_action);
236
237 // Get the contribution id if update
238 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
239 if (!empty($this->_id)) {
240 $this->assignPaymentInfoBlock();
241 $this->assign('contribID', $this->_id);
242 $this->assign('isUsePaymentBlock', TRUE);
243 }
244
245 $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
246 $this->assign('context', $this->_context);
247
248 $this->_compId = CRM_Utils_Request::retrieve('compId', 'Positive', $this);
249
250 $this->_compContext = CRM_Utils_Request::retrieve('compContext', 'String', $this);
251
252 //set the contribution mode.
253 $this->_mode = CRM_Utils_Request::retrieve('mode', 'String', $this);
254
255 $this->assign('contributionMode', $this->_mode);
256 if ($this->_action & CRM_Core_Action::DELETE) {
257 return;
258 }
259
260 $this->_fromEmails = CRM_Core_BAO_Email::getFromEmail();
261
262 if (in_array('CiviPledge', CRM_Core_Config::singleton()->enableComponents) && !$this->_formType) {
263 $this->preProcessPledge();
264 }
265
266 if ($this->_id) {
267 $this->showRecordLinkMesssage($this->_id);
268 }
269 $this->_values = array();
270
271 // Current contribution id.
272 if ($this->_id) {
273 $this->assignPremiumProduct($this->_id);
274 $this->buildValuesAndAssignOnline_Note_Type($this->_id, $this->_values);
275 }
276
277 // when custom data is included in this page
278 if (!empty($_POST['hidden_custom'])) {
279 $this->applyCustomData('Contribution', CRM_Utils_Array::value('financial_type_id', $_POST), $this->_id);
280 }
281
282 $this->_lineItems = array();
283 if ($this->_id) {
284 if (!empty($this->_compId) && $this->_compContext == 'participant') {
285 $this->assign('compId', $this->_compId);
286 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->_compId);
287 }
288 else {
289 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution', 1, TRUE, TRUE);
290 }
291 // wtf?
292 empty($lineItem) ? NULL : $this->_lineItems[] = $lineItem;
293 }
294
295 $this->assign('lineItem', empty($lineItem) ? FALSE : array($lineItem));
296
297 // Set title
298 if ($this->_mode && $this->_id) {
299 $this->_payNow = TRUE;
300 $this->assign('payNow', $this->_payNow);
301 CRM_Utils_System::setTitle(ts('Pay with Credit Card'));
302 }
303 elseif ($this->_mode) {
304 $this->setPageTitle($this->_ppID ? ts('Credit Card Pledge Payment') : ts('Credit Card Contribution'));
305 }
306 else {
307 $this->setPageTitle($this->_ppID ? ts('Pledge Payment') : ts('Contribution'));
308 }
309 }
310
311 /**
312 * Set default values.
313 *
314 * @return array
315 */
316 public function setDefaultValues() {
317 $defaults = $this->_values;
318
319 // Set defaults for pledge payment.
320 if ($this->_ppID) {
321 $defaults['total_amount'] = CRM_Utils_Array::value('scheduled_amount', $this->_pledgeValues['pledgePayment']);
322 $defaults['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $this->_pledgeValues);
323 $defaults['currency'] = CRM_Utils_Array::value('currency', $this->_pledgeValues);
324 $defaults['option_type'] = 1;
325 }
326
327 if ($this->_action & CRM_Core_Action::DELETE) {
328 return $defaults;
329 }
330
331 $defaults['frequency_interval'] = 1;
332 $defaults['frequency_unit'] = 'month';
333
334 // Set soft credit defaults.
335 CRM_Contribute_Form_SoftCredit::setDefaultValues($defaults, $this);
336
337 if ($this->_mode) {
338 // @todo - remove this function as the parent does it too.
339 $config = CRM_Core_Config::singleton();
340 // Set default country from config if no country set.
341 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
342 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry;
343 }
344
345 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
346 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince;
347 }
348
349 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID);
350 $defaults = array_merge($defaults, $billingDefaults);
351 }
352
353 if ($this->_id) {
354 $this->_contactID = $defaults['contact_id'];
355 }
356
357 // Set $newCredit variable in template to control whether link to credit card mode is included.
358 $this->assign('newCredit', CRM_Core_Config::isEnabledBackOfficeCreditCardPayments());
359
360 // Fix the display of the monetary value, CRM-4038.
361 if (isset($defaults['total_amount'])) {
362 if (!empty($defaults['tax_amount'])) {
363 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
364 if (!(CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails))) {
365 $defaults['total_amount'] = CRM_Utils_Money::format($defaults['total_amount'] - $defaults['tax_amount'], NULL, '%a');
366 }
367 }
368 else {
369 $defaults['total_amount'] = CRM_Utils_Money::format($defaults['total_amount'], NULL, '%a');
370 }
371 }
372
373 $amountFields = array('non_deductible_amount', 'fee_amount', 'net_amount');
374 foreach ($amountFields as $amt) {
375 if (isset($defaults[$amt])) {
376 $defaults[$amt] = CRM_Utils_Money::format($defaults[$amt], NULL, '%a');
377 }
378 }
379
380 if ($this->_contributionType) {
381 $defaults['financial_type_id'] = $this->_contributionType;
382 }
383
384 if (empty($defaults['payment_instrument_id'])) {
385 $defaults['payment_instrument_id'] = $this->getDefaultPaymentInstrumentId();
386 }
387
388 if (!empty($defaults['is_test'])) {
389 $this->assign('is_test', TRUE);
390 }
391
392 $this->assign('showOption', TRUE);
393 // For Premium section.
394 if ($this->_premiumID) {
395 $this->assign('showOption', FALSE);
396 $options = isset($this->_options[$this->_productDAO->product_id]) ? $this->_options[$this->_productDAO->product_id] : "";
397 if (!$options) {
398 $this->assign('showOption', TRUE);
399 }
400 $options_key = CRM_Utils_Array::key($this->_productDAO->product_option, $options);
401 if ($options_key) {
402 $defaults['product_name'] = array($this->_productDAO->product_id, trim($options_key));
403 }
404 else {
405 $defaults['product_name'] = array($this->_productDAO->product_id);
406 }
407 if ($this->_productDAO->fulfilled_date) {
408 list($defaults['fulfilled_date']) = CRM_Utils_Date::setDateDefaults($this->_productDAO->fulfilled_date);
409 }
410 }
411
412 if (isset($this->userEmail)) {
413 $this->assign('email', $this->userEmail);
414 }
415
416 if (!empty($defaults['is_pay_later'])) {
417 $this->assign('is_pay_later', TRUE);
418 }
419 $this->assign('contribution_status_id', CRM_Utils_Array::value('contribution_status_id', $defaults));
420 if (!empty($defaults['contribution_status_id']) && in_array(
421 CRM_Contribute_PseudoConstant::contributionStatus($defaults['contribution_status_id'], 'name'),
422 // Historically not 'Cancelled' hence not using CRM_Contribute_BAO_Contribution::isContributionStatusNegative.
423 array('Refunded', 'Chargeback')
424 )) {
425 $defaults['refund_trxn_id'] = CRM_Core_BAO_FinancialTrxn::getRefundTransactionTrxnID($this->_id);
426 }
427 else {
428 $defaults['refund_trxn_id'] = isset($defaults['trxn_id']) ? $defaults['trxn_id'] : NULL;
429 }
430
431 if (!$this->_id && empty($defaults['receive_date'])) {
432 $defaults['receive_date'] = date('Y-m-d H:i:s');
433 }
434
435 $currency = CRM_Utils_Array::value('currency', $defaults);
436 $this->assign('currency', $currency);
437 // Hack to get currency info to the js layer. CRM-11440.
438 CRM_Utils_Money::format(1);
439 $this->assign('currencySymbol', CRM_Utils_Array::value($currency, CRM_Utils_Money::$_currencySymbols));
440 $this->assign('totalAmount', CRM_Utils_Array::value('total_amount', $defaults));
441
442 // Inherit campaign from pledge.
443 if ($this->_ppID && !empty($this->_pledgeValues['campaign_id'])) {
444 $defaults['campaign_id'] = $this->_pledgeValues['campaign_id'];
445 }
446
447 $this->_defaults = $defaults;
448 return $defaults;
449 }
450
451 /**
452 * Build the form object.
453 */
454 public function buildQuickForm() {
455 if ($this->_action & CRM_Core_Action::DELETE) {
456 $this->addButtons(array(
457 array(
458 'type' => 'next',
459 'name' => ts('Delete'),
460 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
461 'isDefault' => TRUE,
462 ),
463 array(
464 'type' => 'cancel',
465 'name' => ts('Cancel'),
466 ),
467 )
468 );
469 return;
470 }
471
472 // FIXME: This probably needs to be done in preprocess
473 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()
474 && $this->_action & CRM_Core_Action::UPDATE
475 && CRM_Utils_Array::value('financial_type_id', $this->_values)
476 ) {
477 $financialTypeID = CRM_Contribute_PseudoConstant::financialType($this->_values['financial_type_id']);
478 CRM_Financial_BAO_FinancialType::checkPermissionedLineItems($this->_id, 'edit');
479 if (!CRM_Core_Permission::check('edit contributions of type ' . $financialTypeID)) {
480 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
481 }
482 }
483 $allPanes = array();
484
485 //tax rate from financialType
486 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant::getTaxRates()));
487 $this->assign('currencies', json_encode(CRM_Core_OptionGroup::values('currencies_enabled')));
488
489 // build price set form.
490 $buildPriceSet = FALSE;
491 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
492 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
493 $this->assign('invoicing', $invoicing);
494
495 $buildRecurBlock = FALSE;
496
497 // display tax amount on edit contribution page
498 if ($invoicing && $this->_action & CRM_Core_Action::UPDATE && isset($this->_values['tax_amount'])) {
499 $this->assign('totalTaxAmount', $this->_values['tax_amount']);
500 }
501
502 if (empty($this->_lineItems) &&
503 ($this->_priceSetId || !empty($_POST['price_set_id']))
504 ) {
505 $buildPriceSet = TRUE;
506 $getOnlyPriceSetElements = TRUE;
507 if (!$this->_priceSetId) {
508 $this->_priceSetId = $_POST['price_set_id'];
509 $getOnlyPriceSetElements = FALSE;
510 }
511
512 $this->set('priceSetId', $this->_priceSetId);
513 CRM_Price_BAO_PriceSet::buildPriceSet($this);
514
515 // get only price set form elements.
516 if ($getOnlyPriceSetElements) {
517 return;
518 }
519 }
520 // use to build form during form rule.
521 $this->assign('buildPriceSet', $buildPriceSet);
522
523 $defaults = $this->_values;
524 $additionalDetailFields = array(
525 'note',
526 'thankyou_date',
527 'invoice_id',
528 'non_deductible_amount',
529 'fee_amount',
530 'net_amount',
531 );
532 foreach ($additionalDetailFields as $key) {
533 if (!empty($defaults[$key])) {
534 $defaults['hidden_AdditionalDetail'] = 1;
535 break;
536 }
537 }
538
539 if ($this->_productDAO) {
540 if ($this->_productDAO->product_id) {
541 $defaults['hidden_Premium'] = 1;
542 }
543 }
544
545 if ($this->_noteID &&
546 !CRM_Utils_System::isNull($this->_values['note'])
547 ) {
548 $defaults['hidden_AdditionalDetail'] = 1;
549 }
550
551 $paneNames = array();
552 if (empty($this->_payNow)) {
553 $paneNames[ts('Additional Details')] = 'AdditionalDetail';
554 }
555
556 //Add Premium pane only if Premium is exists.
557 $dao = new CRM_Contribute_DAO_Product();
558 $dao->is_active = 1;
559
560 if ($dao->find(TRUE) && empty($this->_payNow)) {
561 $paneNames[ts('Premium Information')] = 'Premium';
562 }
563
564 $this->payment_instrument_id = CRM_Utils_Array::value('payment_instrument_id', $defaults, $this->getDefaultPaymentInstrumentId());
565 if (CRM_Core_Payment_Form::buildPaymentForm($this, $this->_paymentProcessor, FALSE, TRUE, $this->payment_instrument_id) == TRUE) {
566 if (!empty($this->_recurPaymentProcessors)) {
567 $buildRecurBlock = TRUE;
568 if ($this->_ppID) {
569 // ppID denotes a pledge payment.
570 foreach ($this->_paymentProcessors as $processor) {
571 if (!empty($processor['is_recur']) && !empty($processor['object']) && $processor['object']->supports('recurContributionsForPledges')) {
572 $buildRecurBlock = TRUE;
573 break;
574 }
575 $buildRecurBlock = FALSE;
576 }
577 }
578 if ($buildRecurBlock) {
579 CRM_Contribute_Form_Contribution_Main::buildRecur($this);
580 $this->setDefaults(array('is_recur' => 0));
581 $this->assign('buildRecurBlock', TRUE);
582 }
583 }
584 }
585 $this->addPaymentProcessorSelect(FALSE, $buildRecurBlock);
586
587 foreach ($paneNames as $name => $type) {
588 $allPanes[$name] = $this->generatePane($type, $defaults);
589 }
590
591 $qfKey = $this->controller->_key;
592 $this->assign('qfKey', $qfKey);
593 $this->assign('allPanes', $allPanes);
594
595 $this->addFormRule(array('CRM_Contribute_Form_Contribution', 'formRule'), $this);
596
597 if ($this->_formType) {
598 $this->assign('formType', $this->_formType);
599 return;
600 }
601
602 $this->applyFilter('__ALL__', 'trim');
603
604 //need to assign custom data type and subtype to the template
605 $this->assign('customDataType', 'Contribution');
606 $this->assign('customDataSubType', $this->_contributionType);
607 $this->assign('entityID', $this->_id);
608
609 if ($this->_context == 'standalone') {
610 $this->addEntityRef('contact_id', ts('Contact'), array(
611 'create' => TRUE,
612 'api' => array('extra' => array('email')),
613 ), TRUE);
614 }
615
616 $attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution');
617
618 // Check permissions for financial type first
619 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, $this->_action);
620 if (empty($financialTypes)) {
621 CRM_Core_Error::statusBounce(ts('You do not have all the permissions needed for this page.'));
622 }
623 $financialType = $this->add('select', 'financial_type_id',
624 ts('Financial Type'),
625 array('' => ts('- select -')) + $financialTypes,
626 TRUE,
627 array('onChange' => "CRM.buildCustomData( 'Contribution', this.value );")
628 );
629
630 $paymentInstrument = FALSE;
631 if (!$this->_mode) {
632 // payment_instrument isn't required in edit and will not be present when payment block is enabled.
633 $required = $this->_id ? FALSE : TRUE;
634 $checkPaymentID = array_search('Check', CRM_Contribute_PseudoConstant::paymentInstrument('name'));
635 $paymentInstrument = $this->add('select', 'payment_instrument_id',
636 ts('Payment Method'),
637 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(),
638 $required, array('onChange' => "return showHideByValue('payment_instrument_id','{$checkPaymentID}','checkNumber','table-row','select',false);")
639 );
640 }
641
642 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), array('class' => 'twelve') + $attributes['trxn_id']);
643
644 //add receipt for offline contribution
645 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
646
647 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
648
649 $component = 'contribution';
650 $componentDetails = [];
651 if ($this->_id) {
652 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
653 if (CRM_Utils_Array::value('membership', $componentDetails)) {
654 $component = 'membership';
655 }
656 elseif (CRM_Utils_Array::value('participant', $componentDetails)) {
657 $component = 'participant';
658 }
659 }
660 if ($this->_ppID) {
661 $component = 'pledge';
662 }
663 $status = CRM_Contribute_BAO_Contribution_Utils::getContributionStatuses($component, $this->_id);
664
665 // define the status IDs that show the cancellation info, see CRM-17589
666 $cancelInfo_show_ids = array();
667 foreach (array_keys($status) as $status_id) {
668 if (CRM_Contribute_BAO_Contribution::isContributionStatusNegative($status_id)) {
669 $cancelInfo_show_ids[] = "'$status_id'";
670 }
671 }
672 $this->assign('cancelInfo_show_ids', implode(',', $cancelInfo_show_ids));
673
674 $statusElement = $this->add('select', 'contribution_status_id',
675 ts('Contribution Status'),
676 $status,
677 FALSE
678 );
679
680 $currencyFreeze = FALSE;
681 if (!empty($this->_payNow) && ($this->_action & CRM_Core_Action::UPDATE)) {
682 $statusElement->freeze();
683 $currencyFreeze = TRUE;
684 $attributes['total_amount']['readonly'] = TRUE;
685 }
686
687 // CRM-16189, add Revenue Recognition Date
688 if (CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled')) {
689 $revenueDate = $this->add('date', 'revenue_recognition_date', ts('Revenue Recognition Date'), CRM_Core_SelectValues::date(NULL, 'M Y', NULL, 5));
690 if ($this->_id && !CRM_Contribute_BAO_Contribution::allowUpdateRevenueRecognitionDate($this->_id)) {
691 $revenueDate->freeze();
692 }
693 }
694
695 // add various dates
696 $this->addField('receive_date', array('entity' => 'contribution'), FALSE, FALSE);
697 $this->addField('receipt_date', array('entity' => 'contribution'), FALSE, FALSE);
698 $this->addField('cancel_date', array('entity' => 'contribution', 'label' => ts('Cancelled / Refunded Date')), FALSE, FALSE);
699
700 if ($this->_online) {
701 $this->assign('hideCalender', TRUE);
702 }
703
704 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
705
706 $totalAmount = NULL;
707 if (empty($this->_lineItems)) {
708 $buildPriceSet = FALSE;
709 $priceSets = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviContribute');
710 if (!empty($priceSets) && !$this->_ppID) {
711 $buildPriceSet = TRUE;
712 }
713
714 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
715 // and if we already have line items for that participant. CRM-5095
716 if ($buildPriceSet && $this->_id) {
717 $pledgePaymentId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
718 $this->_id,
719 'id',
720 'contribution_id'
721 );
722 if ($pledgePaymentId) {
723 $buildPriceSet = FALSE;
724 }
725 if ($participantID = CRM_Utils_Array::value('participant', $componentDetails)) {
726 $participantLI = CRM_Price_BAO_LineItem::getLineItems($participantID);
727 if (!CRM_Utils_System::isNull($participantLI)) {
728 $buildPriceSet = FALSE;
729 }
730 }
731 }
732
733 $hasPriceSets = FALSE;
734 if ($buildPriceSet) {
735 $hasPriceSets = TRUE;
736 // CRM-16451: set financial type of 'Price Set' in back office contribution
737 // instead of selecting manually
738 $financialTypeIds = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviContribute', 'financial_type_id');
739 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
740 array(
741 '' => ts('Choose price set'),
742 ) + $priceSets,
743 NULL, array('onchange' => "buildAmount( this.value, " . json_encode($financialTypeIds) . ");")
744 );
745 if ($this->_online && !($this->_action & CRM_Core_Action::UPDATE)) {
746 $element->freeze();
747 }
748 }
749 $this->assign('hasPriceSets', $hasPriceSets);
750 if (!($this->_action & CRM_Core_Action::UPDATE)) {
751 if ($this->_online || $this->_ppID) {
752 $attributes['total_amount'] = array_merge($attributes['total_amount'], array(
753 'READONLY' => TRUE,
754 'style' => "background-color:#EBECE4",
755 ));
756 $optionTypes = array(
757 '1' => ts('Adjust Pledge Payment Schedule?'),
758 '2' => ts('Adjust Total Pledge Amount?'),
759 );
760 $this->addRadio('option_type',
761 NULL,
762 $optionTypes,
763 array(), '<br/>'
764 );
765
766 $currencyFreeze = TRUE;
767 }
768 }
769
770 $totalAmount = $this->addMoney('total_amount',
771 ts('Total Amount'),
772 ($hasPriceSets) ? FALSE : TRUE,
773 $attributes['total_amount'],
774 TRUE, 'currency', NULL, $currencyFreeze
775 );
776 }
777
778 $this->add('text', 'source', ts('Source'), CRM_Utils_Array::value('source', $attributes));
779
780 // CRM-7362 --add campaigns.
781 CRM_Campaign_BAO_Campaign::addCampaign($this, CRM_Utils_Array::value('campaign_id', $this->_values));
782
783 if (empty($this->_payNow)) {
784 CRM_Contribute_Form_SoftCredit::buildQuickForm($this);
785 }
786
787 $js = NULL;
788 if (!$this->_mode) {
789 $js = array('onclick' => "return verify( );");
790 }
791
792 $mailingInfo = Civi::settings()->get('mailing_backend');
793 $this->assign('outBound_option', $mailingInfo['outBound_option']);
794
795 $this->addButtons(array(
796 array(
797 'type' => 'upload',
798 'name' => ts('Save'),
799 'js' => $js,
800 'isDefault' => TRUE,
801 ),
802 array(
803 'type' => 'upload',
804 'name' => ts('Save and New'),
805 'js' => $js,
806 'subName' => 'new',
807 ),
808 array(
809 'type' => 'cancel',
810 'name' => ts('Cancel'),
811 ),
812 )
813 );
814
815 // if contribution is related to membership or participant freeze Financial Type, Amount
816 if ($this->_id) {
817 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
818 $isCancelledStatus = ($this->_values['contribution_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Cancelled'));
819
820 if (CRM_Utils_Array::value('membership', $componentDetails) ||
821 CRM_Utils_Array::value('participant', $componentDetails) ||
822 // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
823 // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
824 $isCancelledStatus
825 ) {
826 if ($totalAmount) {
827 $totalAmount->freeze();
828 $this->getElement('currency')->freeze();
829 }
830 if ($isCancelledStatus) {
831 $paymentInstrument->freeze();
832 $trxnId->freeze();
833 }
834 $financialType->freeze();
835 $this->assign('freezeFinancialType', TRUE);
836 }
837 }
838
839 if ($this->_action & CRM_Core_Action::VIEW) {
840 $this->freeze();
841 }
842 }
843
844 /**
845 * Global form rule.
846 *
847 * @param array $fields
848 * The input form values.
849 * @param array $files
850 * The uploaded files if any.
851 * @param $self
852 *
853 * @return bool|array
854 * true if no errors, else array of errors
855 */
856 public static function formRule($fields, $files, $self) {
857 $errors = array();
858 // Check for Credit Card Contribution.
859 if ($self->_mode) {
860 if (empty($fields['payment_processor_id'])) {
861 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
862 }
863 else {
864 // validate payment instrument (e.g. credit card number)
865 CRM_Core_Payment_Form::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, NULL);
866 }
867 }
868
869 // Do the amount validations.
870 if (empty($fields['total_amount']) && empty($self->_lineItems)) {
871 if ($priceSetId = CRM_Utils_Array::value('price_set_id', $fields)) {
872 CRM_Price_BAO_PriceField::priceSetValidation($priceSetId, $fields, $errors);
873 }
874 }
875
876 $softErrors = CRM_Contribute_Form_SoftCredit::formRule($fields, $errors, $self);
877
878 if (!empty($fields['total_amount']) && (!empty($fields['net_amount']) || !empty($fields['fee_amount']))) {
879 $sum = CRM_Utils_Rule::cleanMoney($fields['net_amount']) + CRM_Utils_Rule::cleanMoney($fields['fee_amount']);
880 if (CRM_Utils_Rule::cleanMoney($fields['total_amount']) != $sum) {
881 $errors['total_amount'] = ts('The sum of fee amount and net amount must be equal to total amount');
882 }
883 }
884
885 //CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
886 CRM_Contribute_BAO_ContributionRecur::validateRecurContribution($fields, $files, $self, $errors);
887
888 // Form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
889 if (($self->_action & CRM_Core_Action::UPDATE)
890 && $self->_id
891 && $self->_values['contribution_status_id'] != $fields['contribution_status_id']
892 ) {
893 CRM_Contribute_BAO_Contribution::checkStatusValidation($self->_values, $fields, $errors);
894 }
895 // CRM-16015, add form-rule to restrict change of financial type if using price field of different financial type
896 if (($self->_action & CRM_Core_Action::UPDATE)
897 && $self->_id
898 && $self->_values['financial_type_id'] != $fields['financial_type_id']
899 ) {
900 CRM_Contribute_BAO_Contribution::checkFinancialTypeChange(NULL, $self->_id, $errors);
901 }
902 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
903 if (!empty($fields['fee_amount']) && !empty($fields['financial_type_id']) && $financialType = CRM_Contribute_BAO_Contribution::validateFinancialType($fields['financial_type_id'])) {
904 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
905 }
906
907 // $trxn_id must be unique CRM-13919
908 if (!empty($fields['trxn_id'])) {
909 $queryParams = array(1 => array($fields['trxn_id'], 'String'));
910 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
911 if ($self->_id) {
912 $queryParams[2] = array((int) $self->_id, 'Integer');
913 $query .= ' and id !=%2';
914 }
915 $tCnt = CRM_Core_DAO::singleValueQuery($query, $queryParams);
916 if ($tCnt) {
917 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', array(1 => $fields['trxn_id']));
918 }
919 }
920 if (!empty($fields['revenue_recognition_date'])
921 && count(array_filter($fields['revenue_recognition_date'])) == 1
922 ) {
923 $errors['revenue_recognition_date'] = ts('Month and Year are required field for Revenue Recognition.');
924 }
925 // CRM-16189
926 try {
927 CRM_Financial_BAO_FinancialAccount::checkFinancialTypeHasDeferred($fields, $self->_id, $self->_priceSet['fields']);
928 }
929 catch (CRM_Core_Exception $e) {
930 $errors['financial_type_id'] = ' ';
931 $errors['_qf_default'] = $e->getMessage();
932 }
933 $errors = array_merge($errors, $softErrors);
934 return $errors;
935 }
936
937 /**
938 * Process the form submission.
939 */
940 public function postProcess() {
941 if ($this->_action & CRM_Core_Action::DELETE) {
942 CRM_Contribute_BAO_Contribution::deleteContribution($this->_id);
943 CRM_Core_Session::singleton()->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
944 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
945 ));
946 return;
947 }
948 // Get the submitted form values.
949 $submittedValues = $this->controller->exportValues($this->_name);
950
951 try {
952 $contribution = $this->submit($submittedValues, $this->_action, $this->_ppID);
953 }
954 catch (PaymentProcessorException $e) {
955 // Set the contribution mode.
956 $urlParams = "action=add&cid={$this->_contactID}";
957 if ($this->_mode) {
958 $urlParams .= "&mode={$this->_mode}";
959 }
960 if (!empty($this->_ppID)) {
961 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
962 }
963
964 CRM_Core_Error::statusBounce($e->getMessage(), $urlParams, ts('Payment Processor Error'));
965 }
966 $session = CRM_Core_Session::singleton();
967 $buttonName = $this->controller->getButtonName();
968 if ($this->_context == 'standalone') {
969 if ($buttonName == $this->getButtonName('upload', 'new')) {
970 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contribute/add',
971 'reset=1&action=add&context=standalone'
972 ));
973 }
974 else {
975 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
976 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
977 ));
978 }
979 }
980 elseif ($this->_context == 'contribution' && $this->_mode && $buttonName == $this->getButtonName('upload', 'new')) {
981 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution',
982 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
983 ));
984 }
985 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
986 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution',
987 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
988 ));
989 }
990
991 //store contribution ID if not yet set (on create)
992 if (empty($this->_id) && !empty($contribution->id)) {
993 $this->_id = $contribution->id;
994 }
995 if (!empty($this->_id) && CRM_Core_Permission::access('CiviMember')) {
996 $membershipPaymentCount = civicrm_api3('MembershipPayment', 'getCount', array('contribution_id' => $this->_id));
997 if ($membershipPaymentCount) {
998 $this->ajaxResponse['updateTabs']['#tab_member'] = CRM_Contact_BAO_Contact::getCountComponent('membership', $this->_contactID);
999 }
1000 }
1001 if (!empty($this->_id) && CRM_Core_Permission::access('CiviEvent')) {
1002 $participantPaymentCount = civicrm_api3('ParticipantPayment', 'getCount', array('contribution_id' => $this->_id));
1003 if ($participantPaymentCount) {
1004 $this->ajaxResponse['updateTabs']['#tab_participant'] = CRM_Contact_BAO_Contact::getCountComponent('participant', $this->_contactID);
1005 }
1006 }
1007 }
1008
1009 /**
1010 * Process credit card payment.
1011 *
1012 * @param array $submittedValues
1013 * @param array $lineItem
1014 *
1015 * @param int $contactID
1016 * Contact ID
1017 *
1018 * @return bool|\CRM_Contribute_DAO_Contribution
1019 * @throws \CRM_Core_Exception
1020 * @throws \Civi\Payment\Exception\PaymentProcessorException
1021 */
1022 protected function processCreditCard($submittedValues, $lineItem, $contactID) {
1023 $isTest = ($this->_mode == 'test') ? 1 : 0;
1024 // CRM-12680 set $_lineItem if its not set
1025 // @todo - I don't believe this would ever BE set. I can't find anywhere in the code.
1026 // It would be better to pass line item out to functions than $this->_lineItem as
1027 // we don't know what is being changed where.
1028 if (empty($this->_lineItem) && !empty($lineItem)) {
1029 $this->_lineItem = $lineItem;
1030 }
1031
1032 $this->_paymentObject = Civi\Payment\System::singleton()->getById($submittedValues['payment_processor_id']);
1033 $this->_paymentProcessor = $this->_paymentObject->getPaymentProcessor();
1034
1035 // Set source if not set
1036 if (empty($submittedValues['source'])) {
1037 $userID = CRM_Core_Session::singleton()->get('userID');
1038 $userSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1039 'sort_name'
1040 );
1041 $submittedValues['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
1042 }
1043
1044 $params = $submittedValues;
1045 $this->_params = array_merge($this->_params, $submittedValues);
1046
1047 // Mapping requiring documentation.
1048 $this->_params['payment_processor'] = $submittedValues['payment_processor_id'];
1049
1050 $now = date('YmdHis');
1051
1052 // we need to retrieve email address
1053 if ($this->_context == 'standalone' && !empty($submittedValues['is_email_receipt'])) {
1054 list($this->userDisplayName,
1055 $this->userEmail
1056 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
1057 $this->assign('displayName', $this->userDisplayName);
1058 }
1059
1060 $this->_contributorEmail = $this->userEmail;
1061 $this->_contributorContactID = $contactID;
1062 $this->processBillingAddress();
1063 if (!empty($params['source'])) {
1064 unset($params['source']);
1065 }
1066
1067 $this->_params['amount'] = $this->_params['total_amount'];
1068 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
1069 // function to get correct amount level consistently. Remove setting of the amount level in
1070 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
1071 // to cover all variants.
1072 $this->_params['amount_level'] = 0;
1073 $this->_params['description'] = ts("Contribution submitted by a staff person using contributor's credit card");
1074 $this->_params['currencyID'] = CRM_Utils_Array::value('currency',
1075 $this->_params,
1076 CRM_Core_Config::singleton()->defaultCurrency
1077 );
1078
1079 $this->_params['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $params);
1080 $this->_params['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $params);
1081 $this->_params['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $params);
1082
1083 //Add common data to formatted params
1084 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params, $this);
1085
1086 if (empty($this->_params['invoice_id'])) {
1087 $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
1088 }
1089 else {
1090 $this->_params['invoiceID'] = $this->_params['invoice_id'];
1091 }
1092
1093 // At this point we've created a contact and stored its address etc
1094 // all the payment processors expect the name and address to be in the
1095 // so we copy stuff over to first_name etc.
1096 $paymentParams = $this->_params;
1097 $paymentParams['contactID'] = $contactID;
1098 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
1099
1100 $financialType = new CRM_Financial_DAO_FinancialType();
1101 $financialType->id = $params['financial_type_id'];
1102 $financialType->find(TRUE);
1103
1104 // Add some financial type details to the params list
1105 // if folks need to use it.
1106 $paymentParams['contributionType_name'] = $this->_params['contributionType_name'] = $financialType->name;
1107 $paymentParams['contributionPageID'] = NULL;
1108
1109 if (!empty($this->_params['is_email_receipt'])) {
1110 $paymentParams['email'] = $this->userEmail;
1111 $paymentParams['is_email_receipt'] = 1;
1112 }
1113 else {
1114 $paymentParams['is_email_receipt'] = 0;
1115 $this->_params['is_email_receipt'] = 0;
1116 }
1117 if (!empty($this->_params['receive_date'])) {
1118 $paymentParams['receive_date'] = $this->_params['receive_date'];
1119 }
1120
1121 if (!empty($this->_params['is_email_receipt'])) {
1122 $this->_params['receipt_date'] = $now;
1123 }
1124
1125 $this->set('params', $this->_params);
1126
1127 $this->assign('receive_date', $this->_params['receive_date']);
1128
1129 // Result has all the stuff we need
1130 // lets archive it to a financial transaction
1131 if ($financialType->is_deductible) {
1132 $this->assign('is_deductible', TRUE);
1133 $this->set('is_deductible', TRUE);
1134 }
1135 $contributionParams = array(
1136 'id' => CRM_Utils_Array::value('contribution_id', $this->_params),
1137 'contact_id' => $contactID,
1138 'line_item' => $lineItem,
1139 'is_test' => $isTest,
1140 'campaign_id' => CRM_Utils_Array::value('campaign_id', $this->_params),
1141 'contribution_page_id' => CRM_Utils_Array::value('contribution_page_id', $this->_params),
1142 'source' => CRM_Utils_Array::value('source', $paymentParams, CRM_Utils_Array::value('description', $paymentParams)),
1143 'thankyou_date' => CRM_Utils_Array::value('thankyou_date', $this->_params),
1144 );
1145 $contributionParams['payment_instrument_id'] = $this->_paymentProcessor['payment_instrument_id'];
1146
1147 $contribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution($this,
1148 $this->_params,
1149 NULL,
1150 $contributionParams,
1151 $financialType,
1152 FALSE,
1153 $this->_bltID,
1154 CRM_Utils_Array::value('is_recur', $this->_params)
1155 );
1156
1157 $paymentParams['contributionID'] = $contribution->id;
1158 $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
1159 $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
1160 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
1161
1162 if ($paymentParams['amount'] > 0.0) {
1163 // force a re-get of the payment processor in case the form changed it, CRM-7179
1164 // NOTE - I expect this is obsolete.
1165 $payment = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
1166 try {
1167 $statuses = CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id');
1168 $result = $payment->doPayment($paymentParams, 'contribute');
1169 $this->assign('trxn_id', $result['trxn_id']);
1170 $contribution->trxn_id = $result['trxn_id'];
1171 /* Our scenarios here are
1172 * 1) the payment failed & an Exception should have been thrown
1173 * 2) the payment succeeded but the payment is not immediate (for example a recurring payment
1174 * with a delayed start)
1175 * 3) the payment succeeded with an immediate payment.
1176 *
1177 * The doPayment function ensures that payment_status_id is always set
1178 * as historically we have had to guess from the context - ie doDirectPayment
1179 * = error or success, unless it is a recurring contribution in which case it is pending.
1180 */
1181 if ($result['payment_status_id'] == array_search('Completed', $statuses)) {
1182 try {
1183 civicrm_api3('contribution', 'completetransaction', array(
1184 'id' => $contribution->id,
1185 'trxn_id' => $result['trxn_id'],
1186 'payment_processor_id' => $this->_paymentProcessor['id'],
1187 'is_transactional' => FALSE,
1188 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result),
1189 'card_type_id' => CRM_Utils_Array::value('card_type_id', $paymentParams),
1190 'pan_truncation' => CRM_Utils_Array::value('pan_truncation', $paymentParams),
1191 'is_email_receipt' => FALSE,
1192 ));
1193 // This has now been set to 1 in the DB - declare it here also
1194 $contribution->contribution_status_id = 1;
1195 }
1196 catch (CiviCRM_API3_Exception $e) {
1197 if ($e->getErrorCode() != 'contribution_completed') {
1198 throw new CRM_Core_Exception('Failed to update contribution in database');
1199 }
1200 }
1201 }
1202 else {
1203 // Save the trxn_id.
1204 $contribution->save();
1205 }
1206 }
1207 catch (PaymentProcessorException $e) {
1208 CRM_Contribute_BAO_Contribution::failPayment($contribution->id, $paymentParams['contactID'], $e->getMessage());
1209 throw new PaymentProcessorException($e->getMessage());
1210 }
1211 }
1212 // Send receipt mail.
1213 array_unshift($this->statusMessage, ts('The contribution record has been saved.'));
1214 if ($contribution->id && !empty($this->_params['is_email_receipt'])) {
1215 $this->_params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
1216 $this->_params['contact_id'] = $contactID;
1217 $this->_params['contribution_id'] = $contribution->id;
1218 if (CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $this->_params, TRUE)) {
1219 $this->statusMessage[] = ts('A receipt has been emailed to the contributor.');
1220 }
1221 }
1222
1223 return $contribution;
1224 }
1225
1226 /**
1227 * Generate the data to construct a snippet based pane.
1228 *
1229 * This form also assigns the showAdditionalInfo var based on historical code.
1230 * This appears to mean 'there is a pane to show'.
1231 *
1232 * @param string $type
1233 * Type of Pane - this is generally used to determine the function name used to build it
1234 * - e.g CreditCard, AdditionalDetail
1235 * @param array $defaults
1236 *
1237 * @return array
1238 * We aim to further refactor & simplify this but currently
1239 * - the panes array
1240 * - should additional info be shown?
1241 */
1242 protected function generatePane($type, $defaults) {
1243 $urlParams = "snippet=4&formType={$type}";
1244 if ($this->_mode) {
1245 $urlParams .= "&mode={$this->_mode}";
1246 }
1247
1248 $open = 'false';
1249 if ($type == 'CreditCard' ||
1250 $type == 'DirectDebit'
1251 ) {
1252 $open = 'true';
1253 }
1254
1255 $pane = array(
1256 'url' => CRM_Utils_System::url('civicrm/contact/view/contribution', $urlParams),
1257 'open' => $open,
1258 'id' => $type,
1259 );
1260
1261 // See if we need to include this paneName in the current form.
1262 if ($this->_formType == $type || !empty($_POST["hidden_{$type}"]) ||
1263 CRM_Utils_Array::value("hidden_{$type}", $defaults)
1264 ) {
1265 $this->assign('showAdditionalInfo', TRUE);
1266 $pane['open'] = 'true';
1267 }
1268
1269 if ($type == 'CreditCard' || $type == 'DirectDebit') {
1270 // @todo would be good to align tpl name with form name...
1271 // @todo document why this hidden variable is required.
1272 $this->add('hidden', 'hidden_' . $type, 1);
1273 return $pane;
1274 }
1275 else {
1276 $additionalInfoFormFunction = 'build' . $type;
1277 CRM_Contribute_Form_AdditionalInfo::$additionalInfoFormFunction($this);
1278 return $pane;
1279 }
1280 }
1281
1282 /**
1283 * Wrapper for unit testing the post process submit function.
1284 *
1285 * (If we expose through api we can get default additions 'for free').
1286 *
1287 * @param array $params
1288 * @param int $action
1289 * @param string|null $creditCardMode
1290 *
1291 * @throws \CiviCRM_API3_Exception
1292 */
1293 public function testSubmit($params, $action, $creditCardMode = NULL) {
1294 $defaults = array(
1295 'soft_credit_contact_id' => array(),
1296 'receive_date' => date('Y-m-d H:i:s'),
1297 'receipt_date' => '',
1298 'cancel_date' => '',
1299 'hidden_Premium' => 1,
1300 );
1301 $this->_bltID = 5;
1302 if (!empty($params['id'])) {
1303 $existingContribution = civicrm_api3('contribution', 'getsingle', array(
1304 'id' => $params['id'],
1305 ));
1306 $this->_id = $params['id'];
1307 $this->_values = $existingContribution;
1308 if (CRM_Contribute_BAO_Contribution::checkContributeSettings('invoicing')) {
1309 $this->_values['tax_amount'] = civicrm_api3('contribution', 'getvalue', array(
1310 'id' => $params['id'],
1311 'return' => 'tax_amount',
1312 ));
1313 }
1314 }
1315 else {
1316 $existingContribution = array();
1317 }
1318
1319 $this->_defaults['contribution_status_id'] = CRM_Utils_Array::value('contribution_status_id',
1320 $existingContribution
1321 );
1322
1323 $this->_defaults['total_amount'] = CRM_Utils_Array::value('total_amount',
1324 $existingContribution
1325 );
1326
1327 if ($creditCardMode) {
1328 $this->_mode = $creditCardMode;
1329 }
1330
1331 // Required because processCreditCard calls set method on this.
1332 $_SERVER['REQUEST_METHOD'] = 'GET';
1333 $this->controller = new CRM_Core_Controller();
1334
1335 CRM_Contribute_Form_AdditionalInfo::buildPremium($this);
1336
1337 $this->_fields = array();
1338 return $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array::value('pledge_payment_id', $params));
1339
1340 }
1341
1342 /**
1343 * @param array $submittedValues
1344 *
1345 * @param int $action
1346 * Action constant
1347 * - CRM_Core_Action::UPDATE
1348 *
1349 * @param $pledgePaymentID
1350 *
1351 * @return array
1352 * @throws \Exception
1353 */
1354 protected function submit($submittedValues, $action, $pledgePaymentID) {
1355 $pId = $contribution = $isRelatedId = FALSE;
1356 $this->_params = $submittedValues;
1357 $this->beginPostProcess();
1358 // reassign submitted form values if the any information is formatted via beginPostProcess
1359 $submittedValues = $this->_params;
1360
1361 if (!empty($submittedValues['price_set_id']) && $action & CRM_Core_Action::UPDATE) {
1362 $line = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution');
1363 $lineID = key($line);
1364 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array::value('price_field_id', $line[$lineID]), 'price_set_id');
1365 $quickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1366 // Why do we do this? Seems like a like a wrapper for old functionality - but single line price sets & quick
1367 // config should be treated the same.
1368 if ($quickConfig) {
1369 CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_contribution');
1370 }
1371 }
1372
1373 // Process price set and get total amount and line items.
1374 $lineItem = array();
1375 $priceSetId = CRM_Utils_Array::value('price_set_id', $submittedValues);
1376 if (empty($priceSetId) && !$this->_id) {
1377 $this->_priceSetId = $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1378 $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
1379 $fieldID = key($this->_priceSet['fields']);
1380 $fieldValueId = key($this->_priceSet['fields'][$fieldID]['options']);
1381 $this->_priceSet['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1382 $submittedValues['price_' . $fieldID] = 1;
1383 }
1384
1385 // Every contribution has a price-set - the only reason it shouldn't be set is if we are dealing with
1386 // quick config (very very arguably) & yet we see that this could still be quick config so this should be understood
1387 // as a point of fragility rather than a logical 'if' clause.
1388 if ($priceSetId) {
1389 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
1390 $submittedValues, $lineItem[$priceSetId], NULL, $priceSetId);
1391 // Unset tax amount for offline 'is_quick_config' contribution.
1392 // @todo WHY - quick config was conceived as a quick way to configure contribution forms.
1393 // this is an example of 'other' functionality being hung off it.
1394 if ($this->_priceSet['is_quick_config'] &&
1395 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant::getTaxRates())
1396 ) {
1397 unset($submittedValues['tax_amount']);
1398 }
1399 $submittedValues['total_amount'] = CRM_Utils_Array::value('amount', $submittedValues);
1400 }
1401
1402 if ($this->_id) {
1403 if ($this->_compId) {
1404 if ($this->_context == 'participant') {
1405 $pId = $this->_compId;
1406 }
1407 elseif ($this->_context == 'membership') {
1408 $isRelatedId = TRUE;
1409 }
1410 else {
1411 $pId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'participant_id', 'contribution_id');
1412 }
1413 }
1414 else {
1415 $contributionDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
1416 if (array_key_exists('membership', $contributionDetails)) {
1417 $isRelatedId = TRUE;
1418 }
1419 elseif (array_key_exists('participant', $contributionDetails)) {
1420 $pId = $contributionDetails['participant'];
1421 }
1422 }
1423 if (!empty($this->_payNow)) {
1424 $this->_params['contribution_id'] = $this->_id;
1425 }
1426 }
1427
1428 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id) {
1429 // CRM-10117 update the line items for participants.
1430 // @todo - if we are completing a contribution then the api call
1431 // civicrm_api3('Contribution', 'completetransaction') should take care of
1432 // all associated updates rather than replicating them on the form layer.
1433 if ($pId) {
1434 $entityTable = 'participant';
1435 $entityID = $pId;
1436 $isRelatedId = FALSE;
1437 $participantParams = array(
1438 'fee_amount' => $submittedValues['total_amount'],
1439 'id' => $entityID,
1440 );
1441 CRM_Event_BAO_Participant::add($participantParams);
1442 if (empty($this->_lineItems)) {
1443 $this->_lineItems[] = CRM_Price_BAO_LineItem::getLineItems($entityID, 'participant', TRUE);
1444 }
1445 }
1446 else {
1447 $entityTable = 'contribution';
1448 $entityID = $this->_id;
1449 }
1450
1451 $lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entityTable, FALSE, TRUE, $isRelatedId);
1452 foreach (array_keys($lineItems) as $id) {
1453 $lineItems[$id]['id'] = $id;
1454 }
1455 $itemId = key($lineItems);
1456 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1457 $this->_priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1458 }
1459
1460 // @todo see above - new functionality has been inappropriately added to the quick config concept
1461 // and new functionality has been added onto the form layer rather than the BAO :-(
1462 if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
1463 //CRM-16833: Ensure tax is applied only once for membership conribution, when status changed.(e.g Pending to Completed).
1464 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
1465 if (!(CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails))) {
1466 if (!($this->_action & CRM_Core_Action::UPDATE && (($this->_defaults['contribution_status_id'] != $submittedValues['contribution_status_id'])))) {
1467 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value('total_amount', $submittedValues));
1468 }
1469 }
1470
1471 // Update line total and total amount with tax on edit.
1472 $financialItemsId = CRM_Core_PseudoConstant::getTaxRates();
1473 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1474 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1475 }
1476 else {
1477 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1478 $submittedValues['tax_amount'] = 'null';
1479 }
1480 if ($lineItems[$itemId]['tax_rate']) {
1481 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total'];
1482 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] + $lineItems[$itemId]['tax_amount'];
1483 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1484 }
1485 }
1486 // CRM-10117 update the line items for participants.
1487 if (!empty($lineItems[$itemId]['price_field_id'])) {
1488 $lineItem[$this->_priceSetId] = $lineItems;
1489 }
1490 }
1491
1492 $isQuickConfig = 0;
1493 if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
1494 $isQuickConfig = 1;
1495 }
1496 //CRM-11529 for quick config back office transactions
1497 //when financial_type_id is passed in form, update the
1498 //line items with the financial type selected in form
1499 // NOTE that this IS still a legitimate use of 'quick-config' for contributions under the current DB but
1500 // we should look at having a price field per contribution type & then there would be little reason
1501 // for the back-office contribution form postProcess to know if it is a quick-config form.
1502 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array::value($this->_priceSetId, $lineItem)
1503 ) {
1504 foreach ($lineItem[$this->_priceSetId] as &$values) {
1505 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1506 }
1507 }
1508
1509 if (!isset($submittedValues['total_amount'])) {
1510 $submittedValues['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_values);
1511 // Avoid tax amount deduction on edit form and keep it original, because this will lead to error described in CRM-20676
1512 if (!$this->_id) {
1513 $submittedValues['total_amount'] -= CRM_Utils_Array::value('tax_amount', $this->_values, 0);
1514 }
1515 }
1516 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
1517
1518 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
1519 if ($this->_id && count($isEmpty) == 1 && key($isEmpty) == NULL) {
1520 civicrm_api3('ContributionSoft', 'get', array('contribution_id' => $this->_id, 'pcp_id' => NULL, 'api.ContributionSoft.delete' => 1));
1521 }
1522
1523 // set the contact, when contact is selected
1524 if (!empty($submittedValues['contact_id'])) {
1525 $this->_contactID = $submittedValues['contact_id'];
1526 }
1527
1528 $formValues = $submittedValues;
1529
1530 // Credit Card Contribution.
1531 if ($this->_mode) {
1532 $paramsSetByPaymentProcessingSubsystem = array(
1533 'trxn_id',
1534 'payment_instrument_id',
1535 'contribution_status_id',
1536 'cancel_date',
1537 'cancel_reason',
1538 );
1539 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1540 if (isset($formValues[$key])) {
1541 unset($formValues[$key]);
1542 }
1543 }
1544 $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID);
1545 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1546 $formValues[$key] = $contribution->$key;
1547 }
1548 }
1549 else {
1550 // Offline Contribution.
1551 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1552
1553 // get the required field value only.
1554
1555 $params = [
1556 'contact_id' => $this->_contactID,
1557 'currency' => $this->getCurrency($submittedValues),
1558 'skipCleanMoney' => TRUE,
1559 'id' => $this->_id,
1560 ];
1561
1562 //format soft-credit/pcp param first
1563 CRM_Contribute_BAO_ContributionSoft::formatSoftCreditParams($submittedValues, $this);
1564 $params = array_merge($params, $submittedValues);
1565
1566 $fields = array(
1567 'financial_type_id',
1568 'contribution_status_id',
1569 'payment_instrument_id',
1570 'cancel_reason',
1571 'source',
1572 'check_number',
1573 'card_type_id',
1574 'pan_truncation',
1575 );
1576 foreach ($fields as $f) {
1577 $params[$f] = CRM_Utils_Array::value($f, $formValues);
1578 }
1579
1580 $params['revenue_recognition_date'] = NULL;
1581 if (!empty($formValues['revenue_recognition_date'])
1582 && count(array_filter($formValues['revenue_recognition_date'])) == 2
1583 ) {
1584 $params['revenue_recognition_date'] = CRM_Utils_Date::processDate(
1585 '01-' . implode('-', $formValues['revenue_recognition_date'])
1586 );
1587 }
1588
1589 if (!empty($formValues['is_email_receipt'])) {
1590 $params['receipt_date'] = date("Y-m-d");
1591 }
1592
1593 if (CRM_Contribute_BAO_Contribution::isContributionStatusNegative($params['contribution_status_id'])
1594 ) {
1595 if (CRM_Utils_System::isNull(CRM_Utils_Array::value('cancel_date', $params))) {
1596 $params['cancel_date'] = date('YmdHis');
1597 }
1598 }
1599 else {
1600 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1601 }
1602
1603 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1604 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1605 if ($params['contribution_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending')) {
1606 $params['is_pay_later'] = 1;
1607 }
1608 elseif ($params['contribution_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed')) {
1609 $params['is_pay_later'] = 0;
1610 }
1611
1612 // Add Additional common information to formatted params.
1613 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($formValues, $params, $this);
1614 if ($pId) {
1615 $params['contribution_mode'] = 'participant';
1616 $params['participant_id'] = $pId;
1617 $params['skipLineItem'] = 1;
1618 }
1619 elseif ($isRelatedId) {
1620 $params['contribution_mode'] = 'membership';
1621 }
1622 $params['line_item'] = $lineItem;
1623 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array::value('id', $this->_paymentProcessor);
1624 $params['tax_amount'] = CRM_Utils_Array::value('tax_amount', $submittedValues, CRM_Utils_Array::value('tax_amount', $this->_values));
1625 //create contribution.
1626 if ($isQuickConfig) {
1627 $params['is_quick_config'] = 1;
1628 }
1629 $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
1630
1631 // we are already handling note below, so to avoid duplicate notes against $contribution
1632 if (!empty($params['note']) && !empty($submittedValues['note'])) {
1633 unset($params['note']);
1634 }
1635 $contribution = CRM_Contribute_BAO_Contribution::create($params);
1636
1637 // process associated membership / participant, CRM-4395
1638 if ($contribution->id && $action & CRM_Core_Action::UPDATE) {
1639 $this->statusMessage[] = CRM_Contribute_BAO_Contribution::transitionComponentWithReturnMessage($contribution->id,
1640 $contribution->contribution_status_id,
1641 CRM_Utils_Array::value('contribution_status_id',
1642 $this->_values
1643 ),
1644 $contribution->receive_date
1645 );
1646 }
1647
1648 array_unshift($this->statusMessage, ts('The contribution record has been saved.'));
1649
1650 $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
1651
1652 //send receipt mail.
1653 if ($contribution->id && !empty($formValues['is_email_receipt'])) {
1654 $formValues['contact_id'] = $this->_contactID;
1655 $formValues['contribution_id'] = $contribution->id;
1656
1657 $formValues += CRM_Contribute_BAO_ContributionSoft::getSoftContribution($contribution->id);
1658
1659 // to get 'from email id' for send receipt
1660 $this->fromEmailId = CRM_Utils_Array::value('from_email_address', $formValues);
1661 if (CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $formValues)) {
1662 $this->statusMessage[] = ts('A receipt has been emailed to the contributor.');
1663 }
1664 }
1665
1666 $this->statusMessageTitle = ts('Saved');
1667
1668 }
1669
1670 if ($contribution->id && isset($formValues['product_name'][0])) {
1671 CRM_Contribute_Form_AdditionalInfo::processPremium($submittedValues, $contribution->id,
1672 $this->_premiumID, $this->_options
1673 );
1674 }
1675
1676 if ($contribution->id && array_key_exists('note', $submittedValues)) {
1677 CRM_Contribute_Form_AdditionalInfo::processNote($submittedValues, $this->_contactID, $contribution->id, $this->_noteID);
1678 }
1679
1680 CRM_Core_Session::setStatus(implode(' ', $this->statusMessage), $this->statusMessageTitle, 'success');
1681
1682 CRM_Contribute_BAO_Contribution::updateRelatedPledge(
1683 $action,
1684 $pledgePaymentID,
1685 $contribution->id,
1686 (CRM_Utils_Array::value('option_type', $formValues) == 2) ? TRUE : FALSE,
1687 $formValues['total_amount'],
1688 CRM_Utils_Array::value('total_amount', $this->_defaults),
1689 $formValues['contribution_status_id'],
1690 CRM_Utils_Array::value('contribution_status_id', $this->_defaults)
1691 );
1692 return $contribution;
1693 }
1694
1695 /**
1696 * Assign tax calculations to contribution receipts.
1697 *
1698 * @param array $submittedValues
1699 * @param int $action
1700 * @param array $lineItem
1701 */
1702 protected function invoicingPostProcessHook($submittedValues, $action, $lineItem) {
1703
1704 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
1705 if (!CRM_Utils_Array::value('invoicing', $invoiceSettings)) {
1706 return;
1707 }
1708 $taxRate = array();
1709 $getTaxDetails = FALSE;
1710
1711 foreach ($lineItem as $key => $value) {
1712 foreach ($value as $v) {
1713 if (isset($taxRate[(string) CRM_Utils_Array::value('tax_rate', $v)])) {
1714 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array::value('tax_amount', $v);
1715 }
1716 else {
1717 if (isset($v['tax_rate'])) {
1718 $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array::value('tax_amount', $v);
1719 $getTaxDetails = TRUE;
1720 }
1721 }
1722 }
1723 }
1724
1725 if ($action & CRM_Core_Action::UPDATE) {
1726 if (isset($submittedValues['tax_amount'])) {
1727 $totalTaxAmount = $submittedValues['tax_amount'];
1728 }
1729 else {
1730 $totalTaxAmount = $this->_values['tax_amount'];
1731 }
1732 $this->assign('totalTaxAmount', $totalTaxAmount);
1733 $this->assign('dataArray', $taxRate);
1734 }
1735 else {
1736 if (!empty($submittedValues['price_set_id'])) {
1737 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1738 $this->assign('getTaxDetails', $getTaxDetails);
1739 $this->assign('dataArray', $taxRate);
1740 $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
1741 }
1742 else {
1743 $this->assign('totalTaxAmount', CRM_Utils_Array::value('tax_amount', $submittedValues));
1744 }
1745 }
1746 }
1747
1748 /**
1749 * Calculate non deductible amount.
1750 *
1751 * CRM-11956
1752 * if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1753 * if non_deductible_amount does NOT exist - then calculate it depending on:
1754 * $financialType->is_deductible and whether there is a product (premium).
1755 *
1756 * @param $params
1757 * @param $formValues
1758 *
1759 * @return array
1760 */
1761 protected function calculateNonDeductibleAmount($params, $formValues) {
1762 if (!empty($params['non_deductible_amount'])) {
1763 return $params['non_deductible_amount'];
1764 }
1765
1766 $priceSetId = CRM_Utils_Array::value('price_set_id', $params);
1767 // return non-deductible amount if it is set at the price field option level
1768 if ($priceSetId && !empty($params['line_item'])) {
1769 $nonDeductibleAmount = CRM_Price_BAO_PriceSet::getNonDeductibleAmountFromPriceSet($priceSetId, $params['line_item']);
1770 if (!empty($nonDeductibleAmount)) {
1771 return $nonDeductibleAmount;
1772 }
1773 }
1774
1775 $financialType = new CRM_Financial_DAO_FinancialType();
1776 $financialType->id = $params['financial_type_id'];
1777 $financialType->find(TRUE);
1778
1779 if ($financialType->is_deductible) {
1780
1781 if (isset($formValues['product_name'][0])) {
1782 $selectProduct = $formValues['product_name'][0];
1783 }
1784 // if there is a product - compare the value to the contribution amount
1785 if (isset($selectProduct)) {
1786 $productDAO = new CRM_Contribute_DAO_Product();
1787 $productDAO->id = $selectProduct;
1788 $productDAO->find(TRUE);
1789 // product value exceeds contribution amount
1790 if ($params['total_amount'] < $productDAO->price) {
1791 return $params['total_amount'];
1792 }
1793 // product value does NOT exceed contribution amount
1794 else {
1795 return $productDAO->price;
1796 }
1797 }
1798 // contribution is deductible - but there is no product
1799 else {
1800 return '0.00';
1801 }
1802 }
1803 // contribution is NOT deductible
1804 else {
1805 return $params['total_amount'];
1806 }
1807
1808 return 0;
1809 }
1810
1811 }