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