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