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