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