Merge pull request #7672 from eileenmcnaughton/index
[civicrm-core.git] / CRM / Contribute / Form / Contribution.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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 public $_honoreeProfileType;
158
159 /**
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
162 *
163 * @var array
164 */
165 public $_paymentFields = array();
166 /**
167 * Logged in user's email.
168 * @var string
169 */
170 public $userEmail;
171
172 /**
173 * Price set ID
174 * @var integer
175 */
176 public $_priceSetId;
177
178 /**
179 * Price set as an array
180 * @var array
181 */
182 public $_priceSet;
183
184 /**
185 * User display name
186 *
187 * @var string
188 */
189 public $userDisplayName;
190
191 /**
192 * Status message to be shown to the user.
193 *
194 * @var array
195 */
196 protected $statusMessage = array();
197
198 /**
199 * Status message title to be shown to the user.
200 *
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.
203 *
204 * @var string
205 */
206 protected $statusMessageTitle;
207
208 /**
209 * Set variables up before form is built.
210 */
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.'));
215 }
216
217 parent::preProcess();
218
219 $this->_formType = CRM_Utils_Array::value('formType', $_GET);
220
221 // Get price set id.
222 $this->_priceSetId = CRM_Utils_Array::value('priceSetId', $_GET);
223 $this->set('priceSetId', $this->_priceSetId);
224 $this->assign('priceSetId', $this->_priceSetId);
225
226 // Get the pledge payment id
227 $this->_ppID = CRM_Utils_Request::retrieve('ppid', 'Positive', $this);
228
229 $this->assign('action', $this->_action);
230
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);
235 }
236
237 $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
238 $this->assign('context', $this->_context);
239
240 $this->_compId = CRM_Utils_Request::retrieve('compId', 'Positive', $this);
241
242 $this->_compContext = CRM_Utils_Request::retrieve('compContext', 'String', $this);
243
244 //set the contribution mode.
245 $this->_mode = CRM_Utils_Request::retrieve('mode', 'String', $this);
246
247 $this->assign('contributionMode', $this->_mode);
248 if ($this->_action & CRM_Core_Action::DELETE) {
249 return;
250 }
251
252 $this->assign('showCheckNumber', TRUE);
253
254 $this->_fromEmails = CRM_Core_BAO_Email::getFromEmail();
255 $this->assignPaymentRelatedVariables();
256
257 if (in_array('CiviPledge', CRM_Core_Config::singleton()->enableComponents) && !$this->_formType) {
258 $this->preProcessPledge();
259 }
260
261 if ($this->_id) {
262 $this->showRecordLinkMesssage($this->_id);
263 }
264 $this->_values = array();
265
266 // Current contribution id.
267 if ($this->_id) {
268 $this->assignPremiumProduct($this->_id);
269 $this->buildValuesAndAssignOnline_Note_Type($this->_id, $this->_values);
270 }
271
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);
275 }
276
277 $this->_lineItems = array();
278 if ($this->_id) {
279 if (!empty($this->_compId) && $this->_compContext == 'participant') {
280 $this->assign('compId', $this->_compId);
281 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->_compId);
282 }
283 else {
284 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution', 1, TRUE, TRUE);
285 }
286 empty($lineItem) ? NULL : $this->_lineItems[] = $lineItem;
287 }
288
289 $this->assign('lineItem', empty($this->_lineItems) ? FALSE : $this->_lineItems);
290
291 // Set title
292 if ($this->_mode) {
293 $this->setPageTitle($this->_ppID ? ts('Credit Card Pledge Payment') : ts('Credit Card Contribution'));
294 }
295 else {
296 $this->setPageTitle($this->_ppID ? ts('Pledge Payment') : ts('Contribution'));
297 }
298
299 if ($this->_id) {
300 CRM_Contribute_Form_SoftCredit::preprocess($this);
301 }
302 }
303
304 /**
305 * Set default values.
306 *
307 * @return array
308 */
309 public function setDefaultValues() {
310
311 $defaults = $this->_values;
312
313 // Set defaults for pledge payment.
314 if ($this->_ppID) {
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;
319 }
320
321 if ($this->_action & CRM_Core_Action::DELETE) {
322 return $defaults;
323 }
324
325 $defaults['frequency_interval'] = 1;
326 $defaults['frequency_unit'] = 'month';
327
328 // Set soft credit defaults.
329 CRM_Contribute_Form_SoftCredit::setDefaultValues($defaults, $this);
330
331 if ($this->_mode) {
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;
337 }
338
339 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
340 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince;
341 }
342
343 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID);
344 $defaults = array_merge($defaults, $billingDefaults);
345 }
346
347 if ($this->_id) {
348 $this->_contactID = $defaults['contact_id'];
349 }
350
351 // Set $newCredit variable in template to control whether link to credit card mode is included.
352 $this->assign('newCredit', CRM_Core_Config::isEnabledBackOfficeCreditCardPayments());
353
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');
360 }
361 }
362 else {
363 $defaults['total_amount'] = CRM_Utils_Money::format($defaults['total_amount'], NULL, '%a');
364 }
365 }
366
367 if (isset($defaults['non_deductible_amount'])) {
368 $defaults['non_deductible_amount'] = CRM_Utils_Money::format($defaults['non_deductible_amount'], NULL, '%a');
369 }
370
371 if (isset($defaults['fee_amount'])) {
372 $defaults['fee_amount'] = CRM_Utils_Money::format($defaults['fee_amount'], NULL, '%a');
373 }
374
375 if (isset($defaults['net_amount'])) {
376 $defaults['net_amount'] = CRM_Utils_Money::format($defaults['net_amount'], NULL, '%a');
377 }
378
379 if ($this->_contributionType) {
380 $defaults['financial_type_id'] = $this->_contributionType;
381 }
382
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'));
385 }
386
387 if (!empty($defaults['is_test'])) {
388 $this->assign('is_test', TRUE);
389 }
390
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] : "";
396 if (!$options) {
397 $this->assign('showOption', TRUE);
398 }
399 $options_key = CRM_Utils_Array::key($this->_productDAO->product_option, $options);
400 if ($options_key) {
401 $defaults['product_name'] = array($this->_productDAO->product_id, trim($options_key));
402 }
403 else {
404 $defaults['product_name'] = array($this->_productDAO->product_id);
405 }
406 if ($this->_productDAO->fulfilled_date) {
407 list($defaults['fulfilled_date']) = CRM_Utils_Date::setDateDefaults($this->_productDAO->fulfilled_date);
408 }
409 }
410
411 if (isset($this->userEmail)) {
412 $this->assign('email', $this->userEmail);
413 }
414
415 if (!empty($defaults['is_pay_later'])) {
416 $this->assign('is_pay_later', TRUE);
417 }
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);
421 }
422 else {
423 $defaults['refund_trxn_id'] = isset($defaults['trxn_id']) ? $defaults['trxn_id'] : NULL;
424 }
425 $dates = array(
426 'receive_date',
427 'receipt_date',
428 'cancel_date',
429 'thankyou_date',
430 );
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');
435 }
436 }
437
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');
442 }
443
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)
446 ));
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));
453
454 // Inherit campaign from pledge.
455 if ($this->_ppID && !empty($this->_pledgeValues['campaign_id'])) {
456 $defaults['campaign_id'] = $this->_pledgeValues['campaign_id'];
457 }
458
459 $this->_defaults = $defaults;
460 return $defaults;
461 }
462
463 /**
464 * Build the form object.
465 */
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)
471 ) {
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.'));
476 }
477 }
478 $allPanes = array();
479 $recurJs = NULL;
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')));
483
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);
489
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']);
493 }
494
495 if (empty($this->_lineItems) &&
496 ($this->_priceSetId || !empty($_POST['price_set_id']))
497 ) {
498 $buildPriceSet = TRUE;
499 $getOnlyPriceSetElements = TRUE;
500 if (!$this->_priceSetId) {
501 $this->_priceSetId = $_POST['price_set_id'];
502 $getOnlyPriceSetElements = FALSE;
503 }
504
505 $this->set('priceSetId', $this->_priceSetId);
506 CRM_Price_BAO_PriceSet::buildPriceSet($this);
507
508 // get only price set form elements.
509 if ($getOnlyPriceSetElements) {
510 return;
511 }
512 }
513 // use to build form during form rule.
514 $this->assign('buildPriceSet', $buildPriceSet);
515
516 $defaults = $this->_values;
517 $additionalDetailFields = array(
518 'note',
519 'thankyou_date',
520 'invoice_id',
521 'non_deductible_amount',
522 'fee_amount',
523 'net_amount',
524 );
525 foreach ($additionalDetailFields as $key) {
526 if (!empty($defaults[$key])) {
527 $defaults['hidden_AdditionalDetail'] = 1;
528 break;
529 }
530 }
531
532 if ($this->_productDAO) {
533 if ($this->_productDAO->product_id) {
534 $defaults['hidden_Premium'] = 1;
535 }
536 }
537
538 if ($this->_noteID &&
539 isset($this->_values['note'])
540 ) {
541 $defaults['hidden_AdditionalDetail'] = 1;
542 }
543
544 $paneNames = array(
545 ts('Additional Details') => 'AdditionalDetail',
546 );
547
548 //Add Premium pane only if Premium is exists.
549 $dao = new CRM_Contribute_DAO_Product();
550 $dao->is_active = 1;
551
552 if ($dao->find(TRUE)) {
553 $paneNames[ts('Premium Information')] = 'Premium';
554 }
555
556 if ($this->_mode) {
557 if (CRM_Core_Payment_Form::buildPaymentForm($this, $this->_paymentProcessor, FALSE, TRUE) == TRUE) {
558 if (!empty($this->_recurPaymentProcessors)) {
559 $buildRecurBlock = TRUE;
560 if ($this->_ppID) {
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;
565 break;
566 }
567 $buildRecurBlock = FALSE;
568 }
569 }
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;");
575 }
576 }
577 }
578 }
579
580 foreach ($paneNames as $name => $type) {
581 $allPanes[$name] = $this->generatePane($type, $defaults);
582 }
583
584 $qfKey = $this->controller->_key;
585 $this->assign('qfKey', $qfKey);
586 $this->assign('allPanes', $allPanes);
587
588 $this->addFormRule(array('CRM_Contribute_Form_Contribution', 'formRule'), $this);
589
590 if ($this->_formType) {
591 $this->assign('formType', $this->_formType);
592 return;
593 }
594
595 $this->applyFilter('__ALL__', 'trim');
596
597 if ($this->_action & CRM_Core_Action::DELETE) {
598 $this->addButtons(array(
599 array(
600 'type' => 'next',
601 'name' => ts('Delete'),
602 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
603 'isDefault' => TRUE,
604 ),
605 array(
606 'type' => 'cancel',
607 'name' => ts('Cancel'),
608 ),
609 )
610 );
611 return;
612 }
613
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);
618
619 if ($this->_context == 'standalone') {
620 $this->addEntityRef('contact_id', ts('Contact'), array(
621 'create' => TRUE,
622 'api' => array('extra' => array('email')),
623 ), TRUE);
624 }
625
626 $attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution');
627
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.'));
632 }
633 $financialType = $this->add('select', 'financial_type_id',
634 ts('Financial Type'),
635 array('' => ts('- select -')) + $financialTypes,
636 TRUE,
637 array('onChange' => "CRM.buildCustomData( 'Contribution', this.value );")
638 );
639
640 $paymentInstrument = FALSE;
641 if (!$this->_mode) {
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);")
646 );
647 }
648
649 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), array('class' => 'twelve') + $attributes['trxn_id']);
650
651 //add receipt for offline contribution
652 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
653
654 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
655
656 $status = CRM_Contribute_PseudoConstant::contributionStatus();
657
658 // suppressing contribution statuses that are NOT relevant to pledges (CRM-5169)
659 $statusName = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
660 if ($this->_ppID) {
661 foreach (array(
662 'Cancelled',
663 'Failed',
664 'In Progress',
665 ) as $suppress) {
666 unset($status[CRM_Utils_Array::key($suppress, $statusName)]);
667 }
668 }
669 elseif ((!$this->_ppID && $this->_id) || !$this->_id) {
670 $suppressFlag = FALSE;
671 if ($this->_id) {
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;
675 }
676 }
677 if (!$suppressFlag) {
678 foreach (array(
679 'Overdue',
680 'In Progress',
681 ) as $suppress) {
682 unset($status[CRM_Utils_Array::key($suppress, $statusName)]);
683 }
684 }
685 else {
686 unset($status[CRM_Utils_Array::key('Overdue', $statusName)]);
687 }
688 }
689
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'";
695 }
696 }
697 $this->assign('cancelInfo_show_ids', implode(',', $cancelInfo_show_ids));
698
699 if ($this->_id) {
700 $contributionStatus = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_id, 'contribution_status_id');
701 $name = CRM_Utils_Array::value($contributionStatus, $statusName);
702 switch ($name) {
703 case 'Completed':
704 case 'Cancelled':
705 case 'Refunded':
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)]);
709 break;
710
711 case 'Pending':
712 case 'In Progress':
713 unset($status[CRM_Utils_Array::key('Refunded', $statusName)]);
714 break;
715
716 case 'Failed':
717 foreach (array(
718 'Pending',
719 'Refunded',
720 'Completed',
721 'In Progress',
722 'Cancelled',
723 ) as $suppress) {
724 unset($status[CRM_Utils_Array::key($suppress, $statusName)]);
725 }
726 break;
727 }
728 }
729 else {
730 unset($status[CRM_Utils_Array::key('Refunded', $statusName)]);
731 }
732
733 $this->add('select', 'contribution_status_id',
734 ts('Contribution Status'),
735 $status,
736 FALSE
737 );
738
739 // add various dates
740 $this->addDateTime('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
741
742 if ($this->_online) {
743 $this->assign('hideCalender', TRUE);
744 }
745 $checkNumber = $this->add('text', 'check_number', ts('Check Number'), $attributes['check_number']);
746
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'));
749
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'),
755 $this->_processors,
756 NULL,
757 $recurJs
758 );
759
760 if ($this->_online) {
761 $element->freeze();
762 }
763
764 $totalAmount = NULL;
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;
770 }
771
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',
777 $this->_id,
778 'id',
779 'contribution_id'
780 );
781 if ($pledgePaymentId) {
782 $buildPriceSet = FALSE;
783 }
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;
788 }
789 }
790 }
791
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'),
799 array(
800 '' => ts('Choose price set'),
801 ) + $priceSets,
802 NULL, array('onchange' => "buildAmount( this.value, " . json_encode($financialTypeIds) . ");")
803 );
804 if ($this->_online && !($this->_action & CRM_Core_Action::UPDATE)) {
805 $element->freeze();
806 }
807 }
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(
813 'READONLY' => TRUE,
814 'style' => "background-color:#EBECE4",
815 ));
816 $optionTypes = array(
817 '1' => ts('Adjust Pledge Payment Schedule?'),
818 '2' => ts('Adjust Total Pledge Amount?'),
819 );
820 $this->addRadio('option_type',
821 NULL,
822 $optionTypes,
823 array(), '<br/>'
824 );
825
826 $currencyFreeze = TRUE;
827 }
828 }
829
830 $totalAmount = $this->addMoney('total_amount',
831 ts('Total Amount'),
832 ($hasPriceSets) ? FALSE : TRUE,
833 $attributes['total_amount'],
834 TRUE, 'currency', NULL, $currencyFreeze
835 );
836 }
837
838 $this->add('text', 'source', ts('Source'), CRM_Utils_Array::value('source', $attributes));
839
840 // CRM-7362 --add campaigns.
841 CRM_Campaign_BAO_Campaign::addCampaign($this, CRM_Utils_Array::value('campaign_id', $this->_values));
842
843 CRM_Contribute_Form_SoftCredit::buildQuickForm($this);
844
845 $js = NULL;
846 if (!$this->_mode) {
847 $js = array('onclick' => "return verify( );");
848 }
849
850 $mailingInfo = Civi::settings()->get('mailing_backend');
851 $this->assign('outBound_option', $mailingInfo['outBound_option']);
852
853 $this->addButtons(array(
854 array(
855 'type' => 'upload',
856 'name' => ts('Save'),
857 'js' => $js,
858 'isDefault' => TRUE,
859 ),
860 array(
861 'type' => 'upload',
862 'name' => ts('Save and New'),
863 'js' => $js,
864 'subName' => 'new',
865 ),
866 array(
867 'type' => 'cancel',
868 'name' => ts('Cancel'),
869 ),
870 )
871 );
872
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)) {
876 if ($totalAmount) {
877 $totalAmount->freeze();
878 }
879 $checkNumber->freeze();
880 $paymentInstrument->freeze();
881 $trxnId->freeze();
882 $financialType->freeze();
883 }
884
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)) {
889 if ($totalAmount) {
890 $totalAmount->freeze();
891 }
892 $financialType->freeze();
893 $this->assign('freezeFinancialType', TRUE);
894 }
895 }
896
897 if ($this->_action & CRM_Core_Action::VIEW) {
898 $this->freeze();
899 }
900 }
901
902 /**
903 * Global form rule.
904 *
905 * @param array $fields
906 * The input form values.
907 * @param array $files
908 * The uploaded files if any.
909 * @param $self
910 *
911 * @return bool|array
912 * true if no errors, else array of errors
913 */
914 public static function formRule($fields, $files, $self) {
915 $errors = array();
916 // Check for Credit Card Contribution.
917 if ($self->_mode) {
918 if (empty($fields['payment_processor_id'])) {
919 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
920 }
921 else {
922 // validate payment instrument (e.g. credit card number)
923 CRM_Core_Payment_Form::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, NULL);
924 }
925 }
926
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);
931 }
932 }
933
934 $softErrors = CRM_Contribute_Form_SoftCredit::formRule($fields, $errors, $self);
935
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))
944 ) {
945 $sum = CRM_Utils_Money::format($sum - $self->_values['tax_amount'], NULL, '%a');
946 }
947 }
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');
950 }
951 }
952
953 //CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
954 CRM_Contribute_BAO_ContributionRecur::validateRecurContribution($fields, $files, $self, $errors);
955
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)
958 && $self->_id
959 && $self->_values['contribution_status_id'] != $fields['contribution_status_id']
960 ) {
961 CRM_Contribute_BAO_Contribution::checkStatusValidation($self->_values, $fields, $errors);
962 }
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)
965 && $self->_id
966 && $self->_values['financial_type_id'] != $fields['financial_type_id']
967 ) {
968 CRM_Contribute_BAO_Contribution::checkFinancialTypeChange(NULL, $self->_id, $errors);
969 }
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;
973 }
974
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';
979 if ($self->_id) {
980 $queryParams[2] = array((int) $self->_id, 'Integer');
981 $query .= ' and id !=%2';
982 }
983 $tCnt = CRM_Core_DAO::singleValueQuery($query, $queryParams);
984 if ($tCnt) {
985 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', array(1 => $fields['trxn_id']));
986 }
987 }
988
989 $errors = array_merge($errors, $softErrors);
990 return $errors;
991 }
992
993 /**
994 * Process the form submission.
995 */
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"
1001 ));
1002 return;
1003 }
1004 // Get the submitted form values.
1005 $submittedValues = $this->controller->exportValues($this->_name);
1006
1007 try {
1008 $contribution = $this->submit($submittedValues, $this->_action, $this->_ppID);
1009 }
1010 catch (PaymentProcessorException $e) {
1011 // Set the contribution mode.
1012 $urlParams = "action=add&cid={$this->_contactID}";
1013 if ($this->_mode) {
1014 $urlParams .= "&mode={$this->_mode}";
1015 }
1016 if (!empty($this->_ppID)) {
1017 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
1018 }
1019
1020 CRM_Core_Error::statusBounce($e->getMessage(), $urlParams, ts('Payment Processor Error'));
1021 }
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'
1028 ));
1029 }
1030 else {
1031 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
1032 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1033 ));
1034 }
1035 }
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}"
1039 ));
1040 }
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}"
1044 ));
1045 }
1046
1047 //store contribution ID if not yet set (on create)
1048 if (empty($this->_id) && !empty($contribution->id)) {
1049 $this->_id = $contribution->id;
1050 }
1051 }
1052
1053 /**
1054 * Process credit card payment.
1055 *
1056 * @param array $submittedValues
1057 * @param array $lineItem
1058 *
1059 * @param int $contactID
1060 * Contact ID
1061 *
1062 * @return bool|\CRM_Contribute_DAO_Contribution
1063 * @throws \CRM_Core_Exception
1064 * @throws \Civi\Payment\Exception\PaymentProcessorException
1065 */
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;
1074 }
1075
1076 $this->_paymentObject = Civi\Payment\System::singleton()->getById($submittedValues['payment_processor_id']);
1077 $this->_paymentProcessor = $this->_paymentObject->getPaymentProcessor();
1078
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,
1083 'sort_name'
1084 );
1085 $submittedValues['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
1086 }
1087
1088 $params = $submittedValues;
1089 $this->_params = array_merge($this->_params, $submittedValues);
1090
1091 // Mapping requiring documentation.
1092 $this->_params['payment_processor'] = $submittedValues['payment_processor_id'];
1093
1094 $now = date('YmdHis');
1095
1096 // we need to retrieve email address
1097 if ($this->_context == 'standalone' && !empty($submittedValues['is_email_receipt'])) {
1098 list($this->userDisplayName,
1099 $this->userEmail
1100 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
1101 $this->assign('displayName', $this->userDisplayName);
1102 }
1103
1104 $this->_contributorEmail = $this->userEmail;
1105 $this->_contributorContactID = $contactID;
1106 $this->processBillingAddress();
1107 if (!empty($params['source'])) {
1108 unset($params['source']);
1109 }
1110
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',
1119 $this->_params,
1120 CRM_Core_Config::singleton()->defaultCurrency
1121 );
1122
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']);
1125 }
1126
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);
1130
1131 //Add common data to formatted params
1132 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params, $this);
1133
1134 if (empty($this->_params['invoice_id'])) {
1135 $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
1136 }
1137 else {
1138 $this->_params['invoiceID'] = $this->_params['invoice_id'];
1139 }
1140
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);
1147
1148 $financialType = new CRM_Financial_DAO_FinancialType();
1149 $financialType->id = $params['financial_type_id'];
1150 $financialType->find(TRUE);
1151
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;
1156
1157 if (!empty($this->_params['is_email_receipt'])) {
1158 $paymentParams['email'] = $this->userEmail;
1159 $paymentParams['is_email_receipt'] = 1;
1160 }
1161 else {
1162 $paymentParams['is_email_receipt'] = 0;
1163 $this->_params['is_email_receipt'] = 0;
1164 }
1165 if (!empty($this->_params['receive_date'])) {
1166 $paymentParams['receive_date'] = $this->_params['receive_date'];
1167 }
1168
1169 $this->_params['receive_date'] = $now;
1170
1171 if (!empty($this->_params['is_email_receipt'])) {
1172 $this->_params['receipt_date'] = $now;
1173 }
1174 else {
1175 $this->_params['receipt_date'] = CRM_Utils_Date::processDate($this->_params['receipt_date'],
1176 $params['receipt_date_time'], TRUE
1177 );
1178 }
1179
1180 $this->set('params', $this->_params);
1181
1182 $this->assign('receive_date', $this->_params['receive_date']);
1183
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);
1189 }
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),
1198 );
1199
1200 if (empty($paymentParams['is_pay_later'])) {
1201 // @todo look up payment_instrument_id on payment processor table.
1202 $contributionParams['payment_instrument_id'] = 1;
1203 }
1204
1205 $contribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution($this,
1206 $this->_params,
1207 NULL,
1208 $contributionParams,
1209 $financialType,
1210 FALSE,
1211 $this->_bltID,
1212 CRM_Utils_Array::value('is_recur', $this->_params)
1213 );
1214
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;
1219
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);
1224 try {
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.
1234 *
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.
1238 */
1239 if ($result['payment_status_id'] == array_search('Completed', $statuses)) {
1240 try {
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),
1247 ));
1248 // This has now been set to 1 in the DB - declare it here also
1249 $contribution->contribution_status_id = 1;
1250 }
1251 catch (CiviCRM_API3_Exception $e) {
1252 if ($e->getErrorCode() != 'contribution_completed') {
1253 throw new CRM_Core_Exception('Failed to update contribution in database');
1254 }
1255 }
1256 }
1257 else {
1258 // Save the trxn_id.
1259 $contribution->save();
1260 }
1261 }
1262 catch (PaymentProcessorException $e) {
1263 CRM_Contribute_BAO_Contribution::failPayment($contribution->id, $paymentParams['contactID'], $e->getMessage());
1264 throw new PaymentProcessorException($e->getMessage());
1265 }
1266 }
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.');
1275 }
1276 }
1277
1278 return $contribution;
1279 }
1280
1281 /**
1282 * Generate the data to construct a snippet based pane.
1283 *
1284 * This form also assigns the showAdditionalInfo var based on historical code.
1285 * This appears to mean 'there is a pane to show'.
1286 *
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
1291 *
1292 * @return array
1293 * We aim to further refactor & simplify this but currently
1294 * - the panes array
1295 * - should additional info be shown?
1296 */
1297 protected function generatePane($type, $defaults) {
1298 $urlParams = "snippet=4&formType={$type}";
1299 if ($this->_mode) {
1300 $urlParams .= "&mode={$this->_mode}";
1301 }
1302
1303 $open = 'false';
1304 if ($type == 'CreditCard' ||
1305 $type == 'DirectDebit'
1306 ) {
1307 $open = 'true';
1308 }
1309
1310 $pane = array(
1311 'url' => CRM_Utils_System::url('civicrm/contact/view/contribution', $urlParams),
1312 'open' => $open,
1313 'id' => $type,
1314 );
1315
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)
1319 ) {
1320 $this->assign('showAdditionalInfo', TRUE);
1321 $pane['open'] = 'true';
1322 }
1323
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);
1328 return $pane;
1329 }
1330 else {
1331 $additionalInfoFormFunction = 'build' . $type;
1332 CRM_Contribute_Form_AdditionalInfo::$additionalInfoFormFunction($this);
1333 return $pane;
1334 }
1335 }
1336
1337 /**
1338 * Wrapper for unit testing the post process submit function.
1339 *
1340 * (If we expose through api we can get default additions 'for free').
1341 *
1342 * @param array $params
1343 * @param int $action
1344 * @param string|null $creditCardMode
1345 *
1346 * @throws \CiviCRM_API3_Exception
1347 */
1348 public function testSubmit($params, $action, $creditCardMode = NULL) {
1349 $defaults = array(
1350 'soft_credit_contact_id' => array(),
1351 'receipt_date' => '',
1352 'receipt_date_time' => '',
1353 'cancel_date' => '',
1354 'cancel_date_time' => '',
1355 'hidden_Premium' => 1,
1356 );
1357 $this->_bltID = 5;
1358 if (!empty($params['id'])) {
1359 $existingContribution = civicrm_api3('contribution', 'getsingle', array(
1360 'id' => $params['id'],
1361 ));
1362 $this->_id = $params['id'];
1363 }
1364 else {
1365 $existingContribution = array();
1366 }
1367
1368 $this->_defaults['contribution_status_id'] = CRM_Utils_Array::value('contribution_status_id',
1369 $existingContribution
1370 );
1371
1372 $this->_defaults['total_amount'] = CRM_Utils_Array::value('total_amount',
1373 $existingContribution
1374 );
1375
1376 if ($creditCardMode) {
1377 $this->_mode = $creditCardMode;
1378 }
1379
1380 // Required because processCreditCard calls set method on this.
1381 $_SERVER['REQUEST_METHOD'] = 'GET';
1382 $this->controller = new CRM_Core_Controller();
1383
1384 CRM_Contribute_Form_AdditionalInfo::buildPremium($this);
1385
1386 $this->_fields = array();
1387 $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array::value('pledge_payment_id', $params));
1388
1389 }
1390
1391 /**
1392 * @param array $submittedValues
1393 *
1394 * @param int $action
1395 * Action constant
1396 * - CRM_Core_Action::UPDATE
1397 *
1398 * @param $pledgePaymentID
1399 *
1400 * @return array
1401 * @throws \Exception
1402 */
1403 protected function submit($submittedValues, $action, $pledgePaymentID) {
1404 $softParams = $softIDs = array();
1405 $pId = $contribution = $isRelatedId = FALSE;
1406 $this->_params = $submittedValues;
1407 $this->beginPostProcess();
1408
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.
1416 if ($quickConfig) {
1417 CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_contribution');
1418 }
1419 }
1420
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;
1431 }
1432
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.
1436 if ($priceSetId) {
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())
1444 ) {
1445 unset($submittedValues['tax_amount']);
1446 }
1447 $submittedValues['total_amount'] = CRM_Utils_Array::value('amount', $submittedValues);
1448 }
1449 if ($this->_id) {
1450 if ($this->_compId) {
1451 if ($this->_context == 'participant') {
1452 $pId = $this->_compId;
1453 }
1454 elseif ($this->_context == 'membership') {
1455 $isRelatedId = TRUE;
1456 }
1457 else {
1458 $pId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'participant_id', 'contribution_id');
1459 }
1460 }
1461 else {
1462 $contributionDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
1463 if (array_key_exists('membership', $contributionDetails)) {
1464 $isRelatedId = TRUE;
1465 }
1466 elseif (array_key_exists('participant', $contributionDetails)) {
1467 $pId = $contributionDetails['participant'];
1468 }
1469 }
1470 }
1471
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.
1477 if ($pId) {
1478 $entityTable = 'participant';
1479 $entityID = $pId;
1480 $isRelatedId = FALSE;
1481 $participantParams = array(
1482 'fee_amount' => $submittedValues['total_amount'],
1483 'id' => $entityID,
1484 );
1485 CRM_Event_BAO_Participant::add($participantParams);
1486 if (empty($this->_lineItems)) {
1487 $this->_lineItems[] = CRM_Price_BAO_LineItem::getLineItems($entityID, 'participant', 1);
1488 }
1489 }
1490 else {
1491 $entityTable = 'contribution';
1492 $entityID = $this->_id;
1493 }
1494
1495 $lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entityTable, NULL, TRUE, $isRelatedId);
1496 foreach (array_keys($lineItems) as $id) {
1497 $lineItems[$id]['id'] = $id;
1498 }
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');
1502 }
1503
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));
1512 }
1513 }
1514
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']];
1519 }
1520 else {
1521 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1522 $submittedValues['tax_amount'] = 'null';
1523 }
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'];
1528 }
1529 }
1530 // CRM-10117 update the line items for participants.
1531 if (!empty($lineItems[$itemId]['price_field_id'])) {
1532 $lineItem[$this->_priceSetId] = $lineItems;
1533 }
1534 }
1535
1536 $isQuickConfig = 0;
1537 if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
1538 $isQuickConfig = 1;
1539 }
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)
1547 ) {
1548 foreach ($lineItem[$this->_priceSetId] as &$values) {
1549 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1550 }
1551 }
1552
1553 if (!isset($submittedValues['total_amount'])) {
1554 $submittedValues['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_values);
1555 }
1556 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
1557
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));
1562 }
1563
1564 // set the contact, when contact is selected
1565 if (!empty($submittedValues['contact_id'])) {
1566 $this->_contactID = $submittedValues['contact_id'];
1567 }
1568
1569 $formValues = $submittedValues;
1570
1571 // Credit Card Contribution.
1572 if ($this->_mode) {
1573 $paramsSetByPaymentProcessingSubsystem = array(
1574 'trxn_id',
1575 'payment_instrument_id',
1576 'contribution_status_id',
1577 'cancel_date',
1578 'cancel_reason',
1579 );
1580 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1581 if (isset($formValues[$key])) {
1582 unset($formValues[$key]);
1583 }
1584 }
1585 $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID);
1586 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1587 $formValues[$key] = $contribution->$key;
1588 }
1589 }
1590 else {
1591 // Offline Contribution.
1592 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1593
1594 // get the required field value only.
1595
1596 $params = $ids = array();
1597
1598 $params['contact_id'] = $this->_contactID;
1599 $params['currency'] = $this->getCurrency($submittedValues);
1600
1601 //format soft-credit/pcp param first
1602 CRM_Contribute_BAO_ContributionSoft::formatSoftCreditParams($submittedValues, $this);
1603 $params = array_merge($params, $submittedValues);
1604
1605 $fields = array(
1606 'financial_type_id',
1607 'contribution_status_id',
1608 'payment_instrument_id',
1609 'cancel_reason',
1610 'source',
1611 'check_number',
1612 );
1613 foreach ($fields as $f) {
1614 $params[$f] = CRM_Utils_Array::value($f, $formValues);
1615 }
1616
1617 // CRM-5740 if priceset is used, no need to cleanup money.
1618 if ($priceSetId) {
1619 $params['skipCleanMoney'] = 1;
1620 }
1621
1622 $dates = array(
1623 'receive_date',
1624 'receipt_date',
1625 'cancel_date',
1626 );
1627
1628 foreach ($dates as $d) {
1629 $params[$d] = CRM_Utils_Date::processDate($formValues[$d], $formValues[$d . '_time'], TRUE);
1630 }
1631
1632 if (!empty($formValues['is_email_receipt'])) {
1633 $params['receipt_date'] = date("Y-m-d");
1634 }
1635
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')
1638 ) {
1639 if (CRM_Utils_System::isNull(CRM_Utils_Array::value('cancel_date', $params))) {
1640 $params['cancel_date'] = date('YmdHis');
1641 }
1642 }
1643 else {
1644 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1645 }
1646
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;
1651 }
1652 elseif ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
1653 $params['is_pay_later'] = 0;
1654 }
1655
1656 $ids['contribution'] = $params['id'] = $this->_id;
1657
1658 // Add Additional common information to formatted params.
1659 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($formValues, $params, $this);
1660 if ($pId) {
1661 $params['contribution_mode'] = 'participant';
1662 $params['participant_id'] = $pId;
1663 $params['skipLineItem'] = 1;
1664 }
1665 elseif ($isRelatedId) {
1666 $params['contribution_mode'] = 'membership';
1667 }
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'];
1672 }
1673 //create contribution.
1674 if ($isQuickConfig) {
1675 $params['is_quick_config'] = 1;
1676 }
1677 $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
1678
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']);
1682 }
1683 $contribution = CRM_Contribute_BAO_Contribution::create($params, $ids);
1684
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',
1690 $this->_values
1691 ),
1692 $contribution->receive_date
1693 );
1694 }
1695
1696 array_unshift($this->statusMessage, ts('The contribution record has been saved.'));
1697
1698 $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
1699
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;
1704
1705 $formValues += CRM_Contribute_BAO_ContributionSoft::getSoftContribution($contribution->id);
1706
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.');
1711 }
1712 }
1713
1714 $this->statusMessageTitle = ts('Saved');
1715
1716 }
1717
1718 if ($contribution->id && isset($formValues['product_name'][0])) {
1719 CRM_Contribute_Form_AdditionalInfo::processPremium($submittedValues, $contribution->id,
1720 $this->_premiumID, $this->_options
1721 );
1722 }
1723
1724 if ($contribution->id && !empty($submittedValues['note'])) {
1725 CRM_Contribute_Form_AdditionalInfo::processNote($submittedValues, $this->_contactID, $contribution->id, $this->_noteID);
1726 }
1727
1728 CRM_Core_Session::setStatus(implode(' ', $this->statusMessage), $this->statusMessageTitle, 'success');
1729
1730 CRM_Contribute_BAO_Contribution::updateRelatedPledge(
1731 $action,
1732 $pledgePaymentID,
1733 $contribution->id,
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)
1739 );
1740 return $contribution;
1741 }
1742
1743 /**
1744 * Assign tax calculations to contribution receipts.
1745 *
1746 * @param array $submittedValues
1747 * @param int $action
1748 * @param array $lineItem
1749 */
1750 protected function invoicingPostProcessHook($submittedValues, $action, $lineItem) {
1751
1752 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
1753 if (!CRM_Utils_Array::value('invoicing', $invoiceSettings)) {
1754 return;
1755 }
1756 $taxRate = array();
1757 $getTaxDetails = FALSE;
1758 if ($action & CRM_Core_Action::ADD) {
1759 $line = $lineItem;
1760 }
1761 elseif ($action & CRM_Core_Action::UPDATE) {
1762 $line = $this->_lineItems;
1763 }
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);
1768 }
1769 else {
1770 if (isset($v['tax_rate'])) {
1771 $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array::value('tax_amount', $v);
1772 $getTaxDetails = TRUE;
1773 }
1774 }
1775 }
1776 }
1777
1778 if ($action & CRM_Core_Action::UPDATE) {
1779 if (isset($submittedValues['tax_amount'])) {
1780 $totalTaxAmount = $submittedValues['tax_amount'];
1781 }
1782 else {
1783 $totalTaxAmount = $this->_values['tax_amount'];
1784 }
1785 $this->assign('totalTaxAmount', $totalTaxAmount);
1786 $this->assign('dataArray', $taxRate);
1787 }
1788 else {
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));
1794 }
1795 else {
1796 $this->assign('totalTaxAmount', CRM_Utils_Array::value('tax_amount', $submittedValues));
1797 }
1798 }
1799 }
1800
1801 /**
1802 * Calculate non deductible amount.
1803 *
1804 * CRM-11956
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).
1808 *
1809 * @param $params
1810 * @param $formValues
1811 *
1812 * @return array
1813 */
1814 protected function calculateNonDeductibleAmount($params, $formValues) {
1815 if (!empty($params['non_deductible_amount'])) {
1816 return $params['non_deductible_amount'];
1817 }
1818
1819 $financialType = new CRM_Financial_DAO_FinancialType();
1820 $financialType->id = $params['financial_type_id'];
1821 $financialType->find(TRUE);
1822
1823 if ($financialType->is_deductible) {
1824
1825 if (isset($formValues['product_name'][0])) {
1826 $selectProduct = $formValues['product_name'][0];
1827 }
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'];
1836 }
1837 // product value does NOT exceed contribution amount
1838 else {
1839 return $productDAO->price;
1840 }
1841 }
1842 // contribution is deductible - but there is no product
1843 else {
1844 return '0.00';
1845 }
1846 }
1847 // contribution is NOT deductible
1848 else {
1849 return $params['total_amount'];
1850 }
1851
1852 return 0;
1853 }
1854
1855 }