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