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