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