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