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