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