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