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