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