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