Merge pull request #23311 from colemanw/unusedEvent
[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
e47077ce 12use Civi\Api4\Contribution;
7758bd2b
EM
13use Civi\Payment\Exception\PaymentProcessorException;
14
6a488035 15/**
22ab45ae 16 * This class generates form components for processing a contribution.
6a488035
TO
17 */
18class CRM_Contribute_Form_Contribution extends CRM_Contribute_Form_AbstractEditPayment {
6a488035 19 /**
fe482240 20 * The id of the contribution that we are processing.
6a488035
TO
21 *
22 * @var int
6a488035
TO
23 */
24 public $_id;
25
26 /**
fe482240 27 * The id of the premium that we are processing.
6a488035
TO
28 *
29 * @var int
6a488035
TO
30 */
31 public $_premiumID = NULL;
4691b077
EM
32
33 /**
34 * @var CRM_Contribute_DAO_ContributionProduct
35 */
6a488035
TO
36 public $_productDAO = NULL;
37
38 /**
fe482240 39 * The id of the note.
6a488035
TO
40 *
41 * @var int
6a488035
TO
42 */
43 public $_noteID;
44
45 /**
fe482240 46 * The id of the contact associated with this contribution.
6a488035
TO
47 *
48 * @var int
6a488035
TO
49 */
50 public $_contactID;
51
52 /**
fe482240 53 * The id of the pledge payment that we are processing.
6a488035
TO
54 *
55 * @var int
6a488035
TO
56 */
57 public $_ppID;
58
6a488035 59 /**
fe482240 60 * Is this contribution associated with an online.
6a488035
TO
61 * financial transaction
62 *
b67daa72 63 * @var bool
6a488035
TO
64 */
65 public $_online = FALSE;
66
67 /**
bf56a083 68 * Stores all product options.
6a488035
TO
69 *
70 * @var array
6a488035
TO
71 */
72 public $_options;
73
4691b077
EM
74 /**
75 * Storage of parameters from form
76 *
77 * @var array
4691b077
EM
78 */
79 public $_params;
80
6a488035
TO
81 /**
82 * The contribution values if an existing contribution
1330f57a 83 * @var array
6a488035
TO
84 */
85 public $_values;
86
87 /**
88 * The pledge values if this contribution is associated with pledge
1330f57a 89 * @var array
6a488035
TO
90 */
91 public $_pledgeValues;
92
93 public $_contributeMode = 'direct';
94
95 public $_context;
96
5032bf07 97 /**
fe482240 98 * Parameter with confusing name.
5032bf07 99 * @var string
1330f57a 100 * @todo what is it?
5032bf07
EM
101 */
102 public $_compContext;
103
6a488035
TO
104 public $_compId;
105
5032bf07
EM
106 /**
107 * Possible From email addresses
108 * @var array
109 */
110 public $_fromEmails;
d77a0a58
EM
111
112 /**
9f266042 113 * ID of from email.
114 *
115 * @var int
d77a0a58
EM
116 */
117 public $fromEmailId;
d424ffde
CW
118
119 /**
6a488035 120 * Store the line items if price set used.
1330f57a 121 * @var array
6a488035
TO
122 */
123 public $_lineItems;
124
d77a0a58 125 /**
100fef9d 126 * Line item
d77a0a58 127 * @var array
1330f57a 128 * @todo explain why we use lineItem & lineItems
d77a0a58
EM
129 */
130 public $_lineItem;
131
17db9f82 132 /**
5ba7d840 133 * Soft credit info.
134 *
135 * @var array
17db9f82
KJ
136 */
137 public $_softCreditInfo;
138
6a488035 139 protected $_formType;
efe42cdc 140
459091e1 141 /**
100fef9d 142 * Array of the payment fields to be displayed in the payment fieldset (pane) in billingBlock.tpl
459091e1
EM
143 * this contains all the information to describe these fields from quickform. See CRM_Core_Form_Payment getPaymentFormFieldsMetadata
144 *
145 * @var array
146 */
be2fb01f 147 public $_paymentFields = [];
4691b077 148 /**
28a4070b 149 * Logged in user's email.
4691b077
EM
150 * @var string
151 */
152 public $userEmail;
153
154 /**
9f266042 155 * Price set ID.
156 *
157 * @var int
4691b077
EM
158 */
159 public $_priceSetId;
160
4691b077
EM
161 /**
162 * Price set as an array
163 * @var array
164 */
165 public $_priceSet;
166
d77a0a58
EM
167 /**
168 * User display name
169 *
170 * @var string
171 */
172 public $userDisplayName;
353ffa53 173
7e5961cf
EM
174 /**
175 * Status message to be shown to the user.
176 *
3e6a1f4a 177 * @var array
7e5961cf 178 */
be2fb01f 179 protected $statusMessage = [];
7e5961cf
EM
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
e56e813e
BS
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
88aae6d4
A
199 /**
200 * @var bool
201 */
202 public $submitOnce = TRUE;
203
e47077ce
EM
204 /**
205 * Status of contribution prior to edit.
206 *
207 * @var string
208 */
209 protected $previousContributionStatus;
210
b25212e8
PN
211 /**
212 * Explicitly declare the form context.
213 */
214 public function getDefaultContext() {
215 return 'create';
216 }
217
6a488035 218 /**
22ab45ae 219 * Set variables up before form is built.
f174ed0b 220 *
221 * @throws \CRM_Core_Exception
222 * @throws \CiviCRM_API3_Exception
6a488035
TO
223 */
224 public function preProcess() {
28a4070b 225 // Check permission for action.
6a488035 226 if (!CRM_Core_Permission::checkActionPermission('CiviContribute', $this->_action)) {
beb414cc 227 CRM_Core_Error::statusBounce(ts('You do not have permission to access this page.'));
6a488035 228 }
6a488035 229
42e8b05c
EM
230 parent::preProcess();
231
9c1bc317 232 $this->_formType = $_GET['formType'] ?? NULL;
6a488035 233
28a4070b 234 // Get price set id.
9c1bc317 235 $this->_priceSetId = $_GET['priceSetId'] ?? NULL;
6a488035
TO
236 $this->set('priceSetId', $this->_priceSetId);
237 $this->assign('priceSetId', $this->_priceSetId);
238
28a4070b 239 // Get the pledge payment id
6a488035
TO
240 $this->_ppID = CRM_Utils_Request::retrieve('ppid', 'Positive', $this);
241
6a488035
TO
242 $this->assign('action', $this->_action);
243
28a4070b 244 // Get the contribution id if update
b4e8c2b4 245 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive');
59691709 246 $this->assign('isUsePaymentBlock', !empty($this->_id));
6a488035 247 if (!empty($this->_id)) {
c485e792 248 $this->assignPaymentInfoBlock();
6a488035
TO
249 $this->assign('contribID', $this->_id);
250 }
251
edc80cda 252 $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
6a488035
TO
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.
19046166 260 $this->_mode = CRM_Utils_Request::retrieve('mode', 'Alphanumeric', $this);
6a488035
TO
261
262 $this->assign('contributionMode', $this->_mode);
459091e1
EM
263 if ($this->_action & CRM_Core_Action::DELETE) {
264 return;
265 }
6a488035 266
6a488035 267 $this->_fromEmails = CRM_Core_BAO_Email::getFromEmail();
6a488035 268
e46f73c7 269 if (CRM_Core_Component::isEnabled('CiviPledge') && !$this->_formType) {
6a488035
TO
270 $this->preProcessPledge();
271 }
272
d5397f2f
PJ
273 if ($this->_id) {
274 $this->showRecordLinkMesssage($this->_id);
275 }
be2fb01f 276 $this->_values = [];
6a488035 277
bf56a083 278 // Current contribution id.
6a488035
TO
279 if ($this->_id) {
280 $this->assignPremiumProduct($this->_id);
281 $this->buildValuesAndAssignOnline_Note_Type($this->_id, $this->_values);
282 }
aca8f88c
MW
283 if (!isset($this->_values['is_template'])) {
284 $this->_values['is_template'] = FALSE;
285 }
286 $this->assign('is_template', $this->_values['is_template']);
6a488035
TO
287
288 // when custom data is included in this page
a7488080 289 if (!empty($_POST['hidden_custom'])) {
c6a8691e 290 $this->applyCustomData('Contribution', $this->getFinancialTypeID(), $this->_id);
6a488035
TO
291 }
292
be2fb01f 293 $this->_lineItems = [];
6a488035 294 if ($this->_id) {
f174ed0b 295 if (!empty($this->_compId) && $this->_compContext === 'participant') {
6a488035
TO
296 $this->assign('compId', $this->_compId);
297 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->_compId);
298 }
299 else {
0b71718c 300 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution', 1, TRUE, TRUE);
6a488035 301 }
f1662cbd 302 // wtf?
6a488035
TO
303 empty($lineItem) ? NULL : $this->_lineItems[] = $lineItem;
304 }
305
be2fb01f 306 $this->assign('lineItem', empty($lineItem) ? FALSE : [$lineItem]);
6a488035
TO
307
308 // Set title
29cb4724 309 if ($this->_mode && $this->_id) {
17d83f50 310 $this->_payNow = TRUE;
311 $this->assign('payNow', $this->_payNow);
7e2e2551 312 $this->setTitle(ts('Pay with Credit Card'));
29cb4724 313 }
7d238e35
JJ
314 elseif (!empty($this->_values['is_template'])) {
315 $this->setPageTitle(ts('Template Contribution'));
316 }
29cb4724 317 elseif ($this->_mode) {
e2046b33
CW
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'));
6a488035 322 }
6a488035
TO
323 }
324
28a4070b
EM
325 /**
326 * Set default values.
327 *
328 * @return array
f174ed0b 329 *
330 * @throws \CRM_Core_Exception
28a4070b 331 */
00be9182 332 public function setDefaultValues() {
6a488035
TO
333 $defaults = $this->_values;
334
bf56a083 335 // Set defaults for pledge payment.
6a488035 336 if ($this->_ppID) {
9c1bc317
CW
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;
6a488035
TO
340 $defaults['option_type'] = 1;
341 }
342
6a488035
TO
343 if ($this->_action & CRM_Core_Action::DELETE) {
344 return $defaults;
345 }
346
7fe22c48
EM
347 $defaults['frequency_interval'] = 1;
348 $defaults['frequency_unit'] = 'month';
349
bf56a083 350 // Set soft credit defaults.
17db9f82 351 CRM_Contribute_Form_SoftCredit::setDefaultValues($defaults, $this);
dfbad3f7 352
6a488035 353 if ($this->_mode) {
99cdd94d 354 // @todo - remove this function as the parent does it too.
6a488035 355 $config = CRM_Core_Config::singleton();
bf56a083 356 // Set default country from config if no country set.
a7488080 357 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
6a488035
TO
358 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry;
359 }
5a230af7 360
a7488080 361 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
6a488035
TO
362 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince;
363 }
364
cc8ff73d
DG
365 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID);
366 $defaults = array_merge($defaults, $billingDefaults);
6a488035
TO
367 }
368
369 if ($this->_id) {
370 $this->_contactID = $defaults['contact_id'];
371 }
c1af62ca 372 elseif ($this->_contactID) {
373 $defaults['contact_id'] = $this->_contactID;
374 }
5a230af7 375
bf56a083 376 // Set $newCredit variable in template to control whether link to credit card mode is included.
9be1374d 377 $this->assign('newCredit', CRM_Core_Config::isEnabledBackOfficeCreditCardPayments());
5a230af7 378
bf56a083 379 // Fix the display of the monetary value, CRM-4038.
6a488035 380 if (isset($defaults['total_amount'])) {
0bf170de 381 $total_value = $defaults['total_amount'];
48845185 382 $defaults['total_amount'] = CRM_Utils_Money::formatLocaleNumericRoundedForDefaultCurrency($total_value);
049db839 383 if (!empty($defaults['tax_amount'])) {
b6f65362 384 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
b99f3e96 385 if (empty($componentDetails['membership']) && empty($componentDetails['participant'])) {
48845185 386 $defaults['total_amount'] = CRM_Utils_Money::formatLocaleNumericRoundedForDefaultCurrency($total_value - $defaults['tax_amount']);
b6f65362 387 }
049db839 388 }
6a488035
TO
389 }
390
be2fb01f 391 $amountFields = ['non_deductible_amount', 'fee_amount'];
3ac2ffb6 392 foreach ($amountFields as $amt) {
393 if (isset($defaults[$amt])) {
d90d1031 394 $defaults[$amt] = CRM_Utils_Money::formatLocaleNumericRoundedForDefaultCurrency($defaults[$amt]);
3ac2ffb6 395 }
6a488035
TO
396 }
397
a7488080 398 if (empty($defaults['payment_instrument_id'])) {
794d4fc0 399 $defaults['payment_instrument_id'] = $this->getDefaultPaymentInstrumentId();
d96cf288 400 }
6a488035 401
a7488080 402 if (!empty($defaults['is_test'])) {
6a488035
TO
403 $this->assign('is_test', TRUE);
404 }
405
6a488035 406 $this->assign('showOption', TRUE);
bf56a083 407 // For Premium section.
6a488035
TO
408 if ($this->_premiumID) {
409 $this->assign('showOption', FALSE);
77c21b32 410 $options = $this->_options[$this->_productDAO->product_id] ?? "";
6a488035
TO
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) {
be2fb01f 416 $defaults['product_name'] = [$this->_productDAO->product_id, trim($options_key)];
6a488035
TO
417 }
418 else {
be2fb01f 419 $defaults['product_name'] = [$this->_productDAO->product_id];
6a488035
TO
420 }
421 if ($this->_productDAO->fulfilled_date) {
a69cf1d1 422 $defaults['fulfilled_date'] = $this->_productDAO->fulfilled_date;
6a488035
TO
423 }
424 }
425
426 if (isset($this->userEmail)) {
427 $this->assign('email', $this->userEmail);
428 }
429
a7488080 430 if (!empty($defaults['is_pay_later'])) {
6a488035
TO
431 $this->assign('is_pay_later', TRUE);
432 }
433 $this->assign('contribution_status_id', CRM_Utils_Array::value('contribution_status_id', $defaults));
d682fc35 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.
be2fb01f 437 ['Refunded', 'Chargeback']
d682fc35 438 )) {
99cdd94d 439 $defaults['refund_trxn_id'] = CRM_Core_BAO_FinancialTrxn::getRefundTransactionTrxnID($this->_id);
440 }
441 else {
77c21b32 442 $defaults['refund_trxn_id'] = $defaults['trxn_id'] ?? NULL;
99cdd94d 443 }
6a488035 444
8cc574cf 445 if (!$this->_id && empty($defaults['receive_date'])) {
b25212e8 446 $defaults['receive_date'] = date('Y-m-d H:i:s');
6a488035
TO
447 }
448
9c1bc317 449 $currency = $defaults['currency'] ?? NULL;
6a488035 450 $this->assign('currency', $currency);
bf56a083 451 // Hack to get currency info to the js layer. CRM-11440.
6a488035
TO
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
bf56a083 456 // Inherit campaign from pledge.
8cc574cf 457 if ($this->_ppID && !empty($this->_pledgeValues['campaign_id'])) {
6a488035
TO
458 $defaults['campaign_id'] = $this->_pledgeValues['campaign_id'];
459 }
460
461 $this->_defaults = $defaults;
462 return $defaults;
463 }
464
465 /**
fe482240 466 * Build the form object.
f174ed0b 467 *
468 * @throws \CiviCRM_API3_Exception
469 * @throws \CRM_Core_Exception
e47077ce 470 * @throws \API_Exception
6a488035
TO
471 */
472 public function buildQuickForm() {
5774b54f
PF
473 if ($this->_id) {
474 $this->add('hidden', 'id', $this->_id);
475 }
476
3db2d5ef 477 if ($this->_action & CRM_Core_Action::DELETE) {
be2fb01f 478 $this->addButtons([
1330f57a
SL
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 ]);
3db2d5ef
JP
490 return;
491 }
492
e3fa3fea 493 // FIXME: This probably needs to be done in preprocess
40c655aa
E
494 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()
495 && $this->_action & CRM_Core_Action::UPDATE
b99f3e96 496 && !empty($this->_values['financial_type_id'])
66af7c48 497 ) {
e3fa3fea 498 $financialTypeID = CRM_Contribute_PseudoConstant::financialType($this->_values['financial_type_id']);
59ccc8cd 499 CRM_Financial_BAO_FinancialType::checkPermissionedLineItems($this->_id, 'edit');
e3fa3fea 500 if (!CRM_Core_Permission::check('edit contributions of type ' . $financialTypeID)) {
beb414cc 501 CRM_Core_Error::statusBounce(ts('You do not have permission to access this page.'));
e3fa3fea
E
502 }
503 }
be2fb01f 504 $allPanes = [];
b15c60e1 505
6daab7fa 506 //tax rate from financialType
a1e457ff 507 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant::getTaxRates()));
049db839 508 $this->assign('currencies', json_encode(CRM_Core_OptionGroup::values('currencies_enabled')));
6a488035
TO
509
510 // build price set form.
511 $buildPriceSet = FALSE;
d0df87f2 512 $invoicing = CRM_Invoicing_Utils::isInvoicingEnabled();
59691709
EM
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);
b15c60e1 517 $buildRecurBlock = FALSE;
518
6a488035 519 if (empty($this->_lineItems) &&
8cc574cf 520 ($this->_priceSetId || !empty($_POST['price_set_id']))
6a488035
TO
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);
9da8dc8c 530 CRM_Price_BAO_PriceSet::buildPriceSet($this);
6a488035
TO
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
6a488035 540 $defaults = $this->_values;
be2fb01f 541 $additionalDetailFields = [
6a488035
TO
542 'note',
543 'thankyou_date',
544 'invoice_id',
545 'non_deductible_amount',
546 'fee_amount',
be2fb01f 547 ];
6a488035
TO
548 foreach ($additionalDetailFields as $key) {
549 if (!empty($defaults[$key])) {
550 $defaults['hidden_AdditionalDetail'] = 1;
551 break;
552 }
553 }
554
6a488035
TO
555 if ($this->_productDAO) {
556 if ($this->_productDAO->product_id) {
557 $defaults['hidden_Premium'] = 1;
558 }
559 }
560
561 if ($this->_noteID &&
5888a52d 562 !CRM_Utils_System::isNull($this->_values['note'])
6a488035
TO
563 ) {
564 $defaults['hidden_AdditionalDetail'] = 1;
565 }
566
be2fb01f 567 $paneNames = [];
b9a90a9c 568 if (empty($this->_payNow)) {
569 $paneNames[ts('Additional Details')] = 'AdditionalDetail';
570 }
6a488035
TO
571
572 //Add Premium pane only if Premium is exists.
573 $dao = new CRM_Contribute_DAO_Product();
574 $dao->is_active = 1;
575
b9a90a9c 576 if ($dao->find(TRUE) && empty($this->_payNow)) {
6a488035
TO
577 $paneNames[ts('Premium Information')] = 'Premium';
578 }
579
a576ecfa 580 $this->payment_instrument_id = CRM_Utils_Array::value('payment_instrument_id', $defaults, $this->getDefaultPaymentInstrumentId());
3148d4cd
JM
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;
4f3c361d 590 }
3148d4cd 591 $buildRecurBlock = FALSE;
794d4fc0 592 }
3148d4cd
JM
593 }
594 if ($buildRecurBlock) {
595 CRM_Contribute_Form_Contribution_Main::buildRecur($this);
596 $this->setDefaults(['is_recur' => 0]);
597 $this->assign('buildRecurBlock', TRUE);
6a488035
TO
598 }
599 }
b15c60e1 600 $this->addPaymentProcessorSelect(FALSE, $buildRecurBlock);
6a488035 601
6a488035 602 foreach ($paneNames as $name => $type) {
a5399a39 603 $allPanes[$name] = $this->generatePane($type, $defaults);
6a488035 604 }
5e27919e 605
6a488035
TO
606 $qfKey = $this->controller->_key;
607 $this->assign('qfKey', $qfKey);
608 $this->assign('allPanes', $allPanes);
6a488035 609
be2fb01f 610 $this->addFormRule(['CRM_Contribute_Form_Contribution', 'formRule'], $this);
3e7fde97 611 $this->assign('formType', $this->_formType);
6c75c831 612
6a488035 613 if ($this->_formType) {
6a488035
TO
614 return;
615 }
616
617 $this->applyFilter('__ALL__', 'trim');
5a230af7 618
6a488035
TO
619 //need to assign custom data type and subtype to the template
620 $this->assign('customDataType', 'Contribution');
c6a8691e 621 $this->assign('customDataSubType', $this->getFinancialTypeID());
6a488035
TO
622 $this->assign('entityID', $this->_id);
623
d0c83583 624 $contactField = $this->addEntityRef('contact_id', ts('Contributor'), ['create' => TRUE, 'api' => ['extra' => ['email']]], TRUE);
f174ed0b 625 if ($this->_context !== 'standalone') {
c1af62ca 626 $contactField->freeze();
6a488035
TO
627 }
628
629 $attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution');
630
e3fa3fea 631 // Check permissions for financial type first
573fd305 632 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, $this->_action);
b19a01c7 633 if (empty($financialTypes)) {
b55aa3de 634 CRM_Core_Error::statusBounce(ts('You do not have all the permissions needed for this page.'));
b19a01c7 635 }
6a488035
TO
636 $financialType = $this->add('select', 'financial_type_id',
637 ts('Financial Type'),
be2fb01f 638 ['' => ts('- select -')] + $financialTypes,
79ca865b 639 TRUE,
be2fb01f 640 ['onChange' => "CRM.buildCustomData( 'Contribution', this.value );"]
6a488035 641 );
e3fa3fea 642
d77a0a58 643 $paymentInstrument = FALSE;
6a488035 644 if (!$this->_mode) {
c485e792 645 // payment_instrument isn't required in edit and will not be present when payment block is enabled.
91768280 646 $required = !$this->_id;
81936ec3 647 $checkPaymentID = array_search('Check', CRM_Contribute_BAO_Contribution::buildOptions('payment_instrument_id', 'validate'));
6a488035 648 $paymentInstrument = $this->add('select', 'payment_instrument_id',
4db803dd 649 ts('Payment Method'),
81936ec3 650 ['' => ts('- select -')] + CRM_Contribute_BAO_Contribution::buildOptions('payment_instrument_id', 'create'),
be2fb01f 651 $required, ['onChange' => "return showHideByValue('payment_instrument_id','{$checkPaymentID}','checkNumber','table-row','select',false);"]
6a488035
TO
652 );
653 }
654
be2fb01f 655 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), ['class' => 'twelve'] + $attributes['trxn_id']);
6a488035
TO
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
6bc9ca96 662 $componentDetails = [];
7fe7b63d 663 if ($this->_id) {
7fe7b63d 664 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
6a488035 665 }
e50c797d 666 $status = $this->getAvailableContributionStatuses();
b6545333 667
d4849da4 668 // define the status IDs that show the cancellation info, see CRM-17589
be2fb01f 669 $cancelInfo_show_ids = [];
7fe7b63d 670 foreach (array_keys($status) as $status_id) {
d682fc35 671 if (CRM_Contribute_BAO_Contribution::isContributionStatusNegative($status_id)) {
d4849da4 672 $cancelInfo_show_ids[] = "'$status_id'";
673 }
674 }
675 $this->assign('cancelInfo_show_ids', implode(',', $cancelInfo_show_ids));
676
29cb4724 677 $statusElement = $this->add('select', 'contribution_status_id',
6a488035
TO
678 ts('Contribution Status'),
679 $status,
680 FALSE
681 );
682
29cb4724 683 $currencyFreeze = FALSE;
b9a90a9c 684 if (!empty($this->_payNow) && ($this->_action & CRM_Core_Action::UPDATE)) {
29cb4724 685 $statusElement->freeze();
686 $currencyFreeze = TRUE;
687 $attributes['total_amount']['readonly'] = TRUE;
688 }
689
46d173ef 690 // CRM-16189, add Revenue Recognition Date
a17bec97 691 if (Civi::settings()->get('deferred_revenue_enabled')) {
b3bf6844 692 $revenueDate = $this->add('datepicker', 'revenue_recognition_date', ts('Revenue Recognition Date'), [], FALSE, ['time' => FALSE]);
cb8ce66b
PN
693 if ($this->_id && !CRM_Contribute_BAO_Contribution::allowUpdateRevenueRecognitionDate($this->_id)) {
694 $revenueDate->freeze();
695 }
46d173ef
PN
696 }
697
6a488035 698 // add various dates
be2fb01f
CW
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);
6a488035
TO
702
703 if ($this->_online) {
704 $this->assign('hideCalender', TRUE);
705 }
6a488035 706
6a488035 707 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
e02d7e96 708
6a488035
TO
709 $totalAmount = NULL;
710 if (empty($this->_lineItems)) {
711 $buildPriceSet = FALSE;
9da8dc8c 712 $priceSets = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviContribute');
6a488035
TO
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) {
6a488035
TO
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;
6a3d8d2d
WA
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');
6a488035 742 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
be2fb01f 743 [
21dfd5f5 744 '' => ts('Choose price set'),
be2fb01f
CW
745 ] + $priceSets,
746 NULL, ['onchange' => "buildAmount( this.value, " . json_encode($financialTypeIds) . ");"]
5a230af7 747 );
6a488035
TO
748 if ($this->_online && !($this->_action & CRM_Core_Action::UPDATE)) {
749 $element->freeze();
750 }
751 }
752 $this->assign('hasPriceSets', $hasPriceSets);
6a488035 753 if (!($this->_action & CRM_Core_Action::UPDATE)) {
d37ade2e 754 if ($this->_online || $this->_ppID) {
be2fb01f 755 $attributes['total_amount'] = array_merge($attributes['total_amount'], [
d37ade2e 756 'READONLY' => TRUE,
21dfd5f5 757 'style' => "background-color:#EBECE4",
be2fb01f
CW
758 ]);
759 $optionTypes = [
d37ade2e 760 '1' => ts('Adjust Pledge Payment Schedule?'),
761 '2' => ts('Adjust Total Pledge Amount?'),
be2fb01f 762 ];
d37ade2e 763 $this->addRadio('option_type',
764 NULL,
765 $optionTypes,
be2fb01f 766 [], '<br/>'
d37ade2e 767 );
768
769 $currencyFreeze = TRUE;
770 }
6a488035
TO
771 }
772
773 $totalAmount = $this->addMoney('total_amount',
774 ts('Total Amount'),
91768280 775 !$hasPriceSets,
6a488035
TO
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
161a2fe7 783 // CRM-7362 --add campaigns.
6a488035
TO
784 CRM_Campaign_BAO_Campaign::addCampaign($this, CRM_Utils_Array::value('campaign_id', $this->_values));
785
b9a90a9c 786 if (empty($this->_payNow)) {
787 CRM_Contribute_Form_SoftCredit::buildQuickForm($this);
788 }
0baed70b 789
6a488035
TO
790 $js = NULL;
791 if (!$this->_mode) {
be2fb01f 792 $js = ['onclick' => "return verify( );"];
6a488035
TO
793 }
794
aaffa79f 795 $mailingInfo = Civi::settings()->get('mailing_backend');
6a488035
TO
796 $this->assign('outBound_option', $mailingInfo['outBound_option']);
797
be2fb01f 798 $this->addButtons([
1330f57a
SL
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 ]);
6a488035 816
b6f65362 817 // if contribution is related to membership or participant freeze Financial Type, Amount
6bc9ca96 818 if ($this->_id) {
b6f65362 819 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
6bc9ca96 820 $isCancelledStatus = ($this->_values['contribution_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Cancelled'));
821
de6c59ca
CW
822 if (!empty($componentDetails['membership']) ||
823 !empty($componentDetails['participant']) ||
6bc9ca96 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 ) {
b5527a9a 828 if ($totalAmount) {
a13f3d8c 829 $totalAmount->freeze();
6bc9ca96 830 $this->getElement('currency')->freeze();
831 }
832 if ($isCancelledStatus) {
833 $paymentInstrument->freeze();
834 $trxnId->freeze();
b5527a9a 835 }
b6f65362 836 $financialType->freeze();
b6f65362 837 $this->assign('freezeFinancialType', TRUE);
838 }
839 }
840
6a488035
TO
841 if ($this->_action & CRM_Core_Action::VIEW) {
842 $this->freeze();
843 }
844 }
845
846 /**
fe482240 847 * Global form rule.
6a488035 848 *
014c4014
TO
849 * @param array $fields
850 * The input form values.
851 * @param array $files
852 * The uploaded files if any.
e8cf95b4 853 * @param self $self
2a6da8d7 854 *
72b3a70c
CW
855 * @return bool|array
856 * true if no errors, else array of errors
6a488035 857 */
1cf3816f 858 public static function formRule($fields, $files, $self) {
be2fb01f 859 $errors = [];
161a2fe7 860 // Check for Credit Card Contribution.
6a488035
TO
861 if ($self->_mode) {
862 if (empty($fields['payment_processor_id'])) {
863 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
864 }
34089500 865 else {
866 // validate payment instrument (e.g. credit card number)
1d1fee72 867 CRM_Core_Payment_Form::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, NULL);
34089500 868 }
6a488035
TO
869 }
870
161a2fe7 871 // Do the amount validations.
a7488080 872 if (empty($fields['total_amount']) && empty($self->_lineItems)) {
6a488035 873 if ($priceSetId = CRM_Utils_Array::value('price_set_id', $fields)) {
9da8dc8c 874 CRM_Price_BAO_PriceField::priceSetValidation($priceSetId, $fields, $errors);
6a488035
TO
875 }
876 }
877
b326919b 878 $softErrors = CRM_Contribute_Form_SoftCredit::formRule($fields, $errors, $self);
d37ade2e 879
577d1236
WA
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
161a2fe7 883 // Form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
58d33659
PN
884 if (($self->_action & CRM_Core_Action::UPDATE)
885 && $self->_id
886 && $self->_values['contribution_status_id'] != $fields['contribution_status_id']
887 ) {
6a488035
TO
888 CRM_Contribute_BAO_Contribution::checkStatusValidation($self->_values, $fields, $errors);
889 }
4d47ad17 890 // CRM-16015, add form-rule to restrict change of financial type if using price field of different financial type
58d33659
PN
891 if (($self->_action & CRM_Core_Action::UPDATE)
892 && $self->_id
893 && $self->_values['financial_type_id'] != $fields['financial_type_id']
894 ) {
4d47ad17
PN
895 CRM_Contribute_BAO_Contribution::checkFinancialTypeChange(NULL, $self->_id, $errors);
896 }
6a488035 897 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
34089500 898 if (!empty($fields['fee_amount']) && !empty($fields['financial_type_id']) && $financialType = CRM_Contribute_BAO_Contribution::validateFinancialType($fields['financial_type_id'])) {
51fa20cb 899 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
6a488035 900 }
133e2c99 901
7272e4fa
DG
902 // $trxn_id must be unique CRM-13919
903 if (!empty($fields['trxn_id'])) {
be2fb01f 904 $queryParams = [1 => [$fields['trxn_id'], 'String']];
7272e4fa
DG
905 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
906 if ($self->_id) {
be2fb01f 907 $queryParams[2] = [(int) $self->_id, 'Integer'];
7272e4fa
DG
908 $query .= ' and id !=%2';
909 }
910 $tCnt = CRM_Core_DAO::singleValueQuery($query, $queryParams);
911 if ($tCnt) {
be2fb01f 912 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', [1 => $fields['trxn_id']]);
133e2c99 913 }
7272e4fa 914 }
3adac159 915 // CRM-16189
bd4fe93c 916 $order = new CRM_Financial_BAO_Order();
917 $order->setPriceSelectionFromUnfilteredInput($fields);
918 if (isset($fields['total_amount'])) {
68cbdd09 919 $order->setOverrideTotalAmount((float) CRM_Utils_Rule::cleanMoney($fields['total_amount']));
bd4fe93c 920 }
921 $lineItems = $order->getLineItems();
96039749 922 try {
bd4fe93c 923 CRM_Financial_BAO_FinancialAccount::checkFinancialTypeHasDeferred($fields, $self->_id, $lineItems);
96039749
PN
924 }
925 catch (CRM_Core_Exception $e) {
c9b68130 926 $errors['financial_type_id'] = ' ';
96039749 927 $errors['_qf_default'] = $e->getMessage();
3adac159 928 }
ac0c89ed 929 $errors = array_merge($errors, $softErrors);
6a488035
TO
930 return $errors;
931 }
932
933 /**
fe482240 934 * Process the form submission.
6a488035
TO
935 */
936 public function postProcess() {
6a488035
TO
937 if ($this->_action & CRM_Core_Action::DELETE) {
938 CRM_Contribute_BAO_Contribution::deleteContribution($this->_id);
c1cc3e0c 939 CRM_Core_Session::singleton()->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
6a488035
TO
940 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
941 ));
942 return;
943 }
77c081c2 944 // Get the submitted form values.
6a488035 945 $submittedValues = $this->controller->exportValues($this->_name);
7758bd2b
EM
946
947 try {
7758bd2b
EM
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 }
e5777079 962 $this->setUserContext();
6a488035 963
f75f0921
EM
964 //store contribution ID if not yet set (on create)
965 if (empty($this->_id) && !empty($contribution->id)) {
966 $this->_id = $contribution->id;
6a488035 967 }
94c8aed1 968 if (!empty($this->_id) && CRM_Core_Permission::access('CiviMember')) {
be2fb01f 969 $membershipPaymentCount = civicrm_api3('MembershipPayment', 'getCount', ['contribution_id' => $this->_id]);
5a53dd1f 970 if ($membershipPaymentCount) {
94c8aed1
E
971 $this->ajaxResponse['updateTabs']['#tab_member'] = CRM_Contact_BAO_Contact::getCountComponent('membership', $this->_contactID);
972 }
973 }
5a53dd1f 974 if (!empty($this->_id) && CRM_Core_Permission::access('CiviEvent')) {
be2fb01f 975 $participantPaymentCount = civicrm_api3('ParticipantPayment', 'getCount', ['contribution_id' => $this->_id]);
5a53dd1f
E
976 if ($participantPaymentCount) {
977 $this->ajaxResponse['updateTabs']['#tab_participant'] = CRM_Contact_BAO_Contact::getCountComponent('participant', $this->_contactID);
978 }
979 }
f75f0921 980 }
6a488035 981
f75f0921
EM
982 /**
983 * Process credit card payment.
984 *
985 * @param array $submittedValues
986 * @param array $lineItem
456b0145 987 *
7126b55c
EM
988 * @param int $contactID
989 * Contact ID
990 *
456b0145 991 * @return bool|\CRM_Contribute_DAO_Contribution
12fde6ae 992 *
f8453bef 993 * @throws \CRM_Core_Exception
7758bd2b 994 * @throws \Civi\Payment\Exception\PaymentProcessorException
12fde6ae 995 * @throws \CiviCRM_API3_Exception
456b0145 996 */
7126b55c 997 protected function processCreditCard($submittedValues, $lineItem, $contactID) {
549cf0b9 998 $isTest = ($this->_mode == 'test') ? 1 : 0;
f75f0921 999 // CRM-12680 set $_lineItem if its not set
bf4253e7
EM
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.
f75f0921
EM
1003 if (empty($this->_lineItem) && !empty($lineItem)) {
1004 $this->_lineItem = $lineItem;
6a488035 1005 }
6a488035 1006
bf4253e7
EM
1007 $this->_paymentObject = Civi\Payment\System::singleton()->getById($submittedValues['payment_processor_id']);
1008 $this->_paymentProcessor = $this->_paymentObject->getPaymentProcessor();
c52884b2 1009
7758bd2b
EM
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 );
be2fb01f 1016 $submittedValues['source'] = ts('Submit Credit Card Payment by: %1', [1 => $userSortName]);
7758bd2b
EM
1017 }
1018
3b8e6c3f 1019 $params = $submittedValues;
1020 $this->_params = array_merge($this->_params, $submittedValues);
77e18ec7 1021
bf4253e7
EM
1022 // Mapping requiring documentation.
1023 $this->_params['payment_processor'] = $submittedValues['payment_processor_id'];
1024
f75f0921 1025 $now = date('YmdHis');
5a230af7 1026
3b8e6c3f 1027 $this->_contributorEmail = $this->userEmail;
1028 $this->_contributorContactID = $contactID;
1029 $this->processBillingAddress();
f75f0921
EM
1030 if (!empty($params['source'])) {
1031 unset($params['source']);
6a488035 1032 }
c52884b2 1033
f75f0921 1034 $this->_params['amount'] = $this->_params['total_amount'];
c039f658 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.
f75f0921 1039 $this->_params['amount_level'] = 0;
e47238e5 1040 $this->_params['description'] = ts("Contribution submitted by a staff person using contributor's credit card");
f75f0921
EM
1041 $this->_params['currencyID'] = CRM_Utils_Array::value('currency',
1042 $this->_params,
1043 CRM_Core_Config::singleton()->defaultCurrency
1044 );
aefd7f6b 1045
9c1bc317
CW
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;
3f662d9d 1049
f75f0921
EM
1050 //Add common data to formatted params
1051 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params, $this);
6a488035 1052
f75f0921
EM
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 }
6a488035 1059
f75f0921
EM
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;
7126b55c 1064 $paymentParams['contactID'] = $contactID;
f75f0921 1065 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
6a488035 1066
67256e0c
EM
1067 $financialType = new CRM_Financial_DAO_FinancialType();
1068 $financialType->id = $params['financial_type_id'];
11829025 1069 $financialType->find(TRUE);
6a488035 1070
f75f0921
EM
1071 // Add some financial type details to the params list
1072 // if folks need to use it.
67256e0c 1073 $paymentParams['contributionType_name'] = $this->_params['contributionType_name'] = $financialType->name;
f75f0921 1074 $paymentParams['contributionPageID'] = NULL;
6a488035 1075
f75f0921
EM
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 }
6a488035 1087
f75f0921
EM
1088 if (!empty($this->_params['is_email_receipt'])) {
1089 $this->_params['receipt_date'] = $now;
1090 }
6a488035 1091
f75f0921 1092 $this->set('params', $this->_params);
8f3a9b39
EM
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'));
6a488035 1096
f75f0921
EM
1097 // Result has all the stuff we need
1098 // lets archive it to a financial transaction
67256e0c 1099 if ($financialType->is_deductible) {
f75f0921
EM
1100 $this->assign('is_deductible', TRUE);
1101 $this->set('is_deductible', TRUE);
1102 }
be2fb01f 1103 $contributionParams = [
6b409353 1104 'id' => $this->_params['contribution_id'] ?? NULL,
3febe800 1105 'contact_id' => $contactID,
1106 'line_item' => $lineItem,
1107 'is_test' => $isTest,
6b409353
CW
1108 'campaign_id' => $this->_params['campaign_id'] ?? NULL,
1109 'contribution_page_id' => $this->_params['contribution_page_id'] ?? NULL,
3febe800 1110 'source' => CRM_Utils_Array::value('source', $paymentParams, CRM_Utils_Array::value('description', $paymentParams)),
6b409353 1111 'thankyou_date' => $this->_params['thankyou_date'] ?? NULL,
be2fb01f 1112 ];
16f3bd02 1113 $contributionParams['payment_instrument_id'] = $this->_paymentProcessor['payment_instrument_id'];
6a488035 1114
2414241f 1115 $contribution = $this->processFormContribution(
7758bd2b
EM
1116 $this->_params,
1117 NULL,
3febe800 1118 $contributionParams,
7758bd2b 1119 $financialType,
7758bd2b 1120 FALSE,
449f4c90 1121 $this->_bltID,
1122 CRM_Utils_Array::value('is_recur', $this->_params)
7758bd2b 1123 );
6a488035 1124
7758bd2b 1125 $paymentParams['contributionID'] = $contribution->id;
7758bd2b
EM
1126 $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
1127 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
6a488035 1128
7758bd2b
EM
1129 if ($paymentParams['amount'] > 0.0) {
1130 // force a re-get of the payment processor in case the form changed it, CRM-7179
9d8f43b1
EM
1131 // NOTE - I expect this is obsolete.
1132 $payment = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
7758bd2b 1133 try {
003e9340 1134 $completeStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
7758bd2b
EM
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 *
7c85dc65 1144 * The doPayment function ensures that payment_status_id is always set
7758bd2b
EM
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 */
003e9340 1148 if ($result['payment_status_id'] == $completeStatusId) {
760278d3 1149 try {
be2fb01f 1150 civicrm_api3('contribution', 'completetransaction', [
760278d3
EM
1151 'id' => $contribution->id,
1152 'trxn_id' => $result['trxn_id'],
1153 'payment_processor_id' => $this->_paymentProcessor['id'],
1154 'is_transactional' => FALSE,
6b409353
CW
1155 'fee_amount' => $result['fee_amount'] ?? NULL,
1156 'card_type_id' => $paymentParams['card_type_id'] ?? NULL,
1157 'pan_truncation' => $paymentParams['pan_truncation'] ?? NULL,
0af52f61 1158 'is_email_receipt' => FALSE,
be2fb01f 1159 ]);
760278d3
EM
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') {
f30b037a 1165 \Civi::log()->error('CRM_Contribute_Form_Contribution::processCreditCard CiviCRM_API3_Exception: ' . $e->getMessage());
760278d3
EM
1166 throw new CRM_Core_Exception('Failed to update contribution in database');
1167 }
1168 }
7758bd2b
EM
1169 }
1170 else {
1171 // Save the trxn_id.
1172 $contribution->save();
1173 }
1174 }
1175 catch (PaymentProcessorException $e) {
06d062ce 1176 CRM_Contribute_BAO_Contribution::failPayment($contribution->id, $paymentParams['contactID'], $e->getMessage());
7758bd2b
EM
1177 throw new PaymentProcessorException($e->getMessage());
1178 }
1179 }
f75f0921 1180 // Send receipt mail.
e390a377 1181 array_unshift($this->statusMessage, ts('The contribution record has been saved.'));
f75f0921 1182 if ($contribution->id && !empty($this->_params['is_email_receipt'])) {
9c1bc317 1183 $this->_params['trxn_id'] = $result['trxn_id'] ?? NULL;
7126b55c 1184 $this->_params['contact_id'] = $contactID;
f75f0921 1185 $this->_params['contribution_id'] = $contribution->id;
c52884b2 1186 if (CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $this->_params, TRUE)) {
3e6a1f4a 1187 $this->statusMessage[] = ts('A receipt has been emailed to the contributor.');
6a488035 1188 }
28d44c9f 1189 }
c52884b2 1190
5e27919e 1191 return $contribution;
6a488035 1192 }
5a230af7 1193
2414241f
EM
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 );
a281a8ea 1283 $contributionParams['non_deductible_amount'] = CRM_Contribute_Form_Contribution_Confirm::getNonDeductibleAmount($params, $financialType, FALSE, $form);
2414241f
EM
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
f75f0921
EM
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}";
6a488035
TO
1395 }
1396
f75f0921
EM
1397 $open = 'false';
1398 if ($type == 'CreditCard' ||
1399 $type == 'DirectDebit'
1400 ) {
1401 $open = 'true';
6a488035 1402 }
6a488035 1403
be2fb01f 1404 $pane = [
f75f0921
EM
1405 'url' => CRM_Utils_System::url('civicrm/contact/view/contribution', $urlParams),
1406 'open' => $open,
1407 'id' => $type,
be2fb01f 1408 ];
6a488035 1409
f75f0921
EM
1410 // See if we need to include this paneName in the current form.
1411 if ($this->_formType == $type || !empty($_POST["hidden_{$type}"]) ||
b99f3e96 1412 !empty($defaults["hidden_{$type}"])
f75f0921
EM
1413 ) {
1414 $this->assign('showAdditionalInfo', TRUE);
1415 $pane['open'] = 'true';
6a488035
TO
1416 }
1417
f75f0921
EM
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;
6a488035
TO
1423 }
1424 else {
f75f0921
EM
1425 $additionalInfoFormFunction = 'build' . $type;
1426 CRM_Contribute_Form_AdditionalInfo::$additionalInfoFormFunction($this);
1427 return $pane;
6a488035 1428 }
f75f0921 1429 }
6a488035 1430
f75f0921
EM
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
5e27919e 1437 * @param int $action
39f47c0d
EM
1438 * @param string|null $creditCardMode
1439 *
12fde6ae 1440 * @return CRM_Contribute_BAO_Contribution
1441 *
1442 * @throws \CRM_Core_Exception
39f47c0d 1443 * @throws \CiviCRM_API3_Exception
12fde6ae 1444 * @throws \Civi\Payment\Exception\PaymentProcessorException
f75f0921 1445 */
39f47c0d 1446 public function testSubmit($params, $action, $creditCardMode = NULL) {
be2fb01f
CW
1447 $defaults = [
1448 'soft_credit_contact_id' => [],
6298b166 1449 'receive_date' => date('Y-m-d H:i:s'),
f75f0921 1450 'receipt_date' => '',
f75f0921 1451 'cancel_date' => '',
43bf07d6 1452 'hidden_Premium' => 1,
be2fb01f 1453 ];
739a8336 1454 $this->_bltID = 5;
5e27919e 1455 if (!empty($params['id'])) {
be2fb01f 1456 $existingContribution = civicrm_api3('contribution', 'getsingle', [
5e27919e 1457 'id' => $params['id'],
be2fb01f 1458 ]);
55e55e84 1459 $this->_id = $params['id'];
0f07bb06 1460 $this->_values = $existingContribution;
5d288dc4 1461 if (CRM_Invoicing_Utils::isInvoicingEnabled()) {
be2fb01f 1462 $this->_values['tax_amount'] = civicrm_api3('contribution', 'getvalue', [
7c002a4d 1463 'id' => $params['id'],
1464 'return' => 'tax_amount',
be2fb01f 1465 ]);
7c002a4d 1466 }
5e27919e
EM
1467 }
1468 else {
be2fb01f 1469 $existingContribution = [];
5e27919e
EM
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 );
6a488035 1479
39f47c0d
EM
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
3e6a1f4a
EM
1488 CRM_Contribute_Form_AdditionalInfo::buildPremium($this);
1489
be2fb01f 1490 $this->_fields = [];
0495f30c 1491 return $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array::value('pledge_payment_id', $params));
43bf07d6 1492
f75f0921 1493 }
c1cc3e0c 1494
f75f0921
EM
1495 /**
1496 * @param array $submittedValues
1497 *
bdbc1044
EM
1498 * @param int $action
1499 * Action constant
1500 * - CRM_Core_Action::UPDATE
1501 *
5e27919e
EM
1502 * @param $pledgePaymentID
1503 *
12fde6ae 1504 * @return \CRM_Contribute_BAO_Contribution
1505 *
1506 * @throws \CRM_Core_Exception
1507 * @throws \CiviCRM_API3_Exception
1508 * @throws \Civi\Payment\Exception\PaymentProcessorException
f75f0921 1509 */
31760f81 1510 protected function submit($submittedValues, $action, $pledgePaymentID) {
f75f0921 1511 $pId = $contribution = $isRelatedId = FALSE;
3b8e6c3f 1512 $this->_params = $submittedValues;
1513 $this->beginPostProcess();
a55e39e9 1514 // reassign submitted form values if the any information is formatted via beginPostProcess
1515 $submittedValues = $this->_params;
3e6a1f4a 1516
32b88e1e 1517 if ($this->getPriceSetID() && $action & CRM_Core_Action::UPDATE) {
f75f0921
EM
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');
2b308818
DG
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.
f75f0921
EM
1524 if ($quickConfig) {
1525 CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_contribution');
1526 }
6a488035 1527 }
f75f0921
EM
1528
1529 // Process price set and get total amount and line items.
be2fb01f 1530 $lineItem = [];
9c1bc317 1531 $priceSetId = $submittedValues['price_set_id'] ?? NULL;
32b88e1e 1532 if (!$this->getPriceSetID() && !$this->_id) {
f75f0921
EM
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;
6a488035 1539 }
6a488035 1540
2b308818
DG
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.
f75f0921
EM
1544 if ($priceSetId) {
1545 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
bdcbbfea 1546 $submittedValues, $lineItem[$priceSetId], $priceSetId);
f75f0921 1547 // Unset tax amount for offline 'is_quick_config' contribution.
2b308818
DG
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.
f75f0921
EM
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 }
9c1bc317 1555 $submittedValues['total_amount'] = $submittedValues['amount'] ?? NULL;
6a488035 1556 }
189f0360 1557
f75f0921
EM
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 }
c1cc3e0c 1569 }
f75f0921
EM
1570 else {
1571 $contributionDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
1572 if (array_key_exists('membership', $contributionDetails)) {
1573 $isRelatedId = TRUE;
c1cc3e0c 1574 }
f75f0921
EM
1575 elseif (array_key_exists('participant', $contributionDetails)) {
1576 $pId = $contributionDetails['participant'];
c1cc3e0c 1577 }
6a488035 1578 }
17d83f50 1579 if (!empty($this->_payNow)) {
1580 $this->_params['contribution_id'] = $this->_id;
1581 }
6a488035 1582 }
2b308818 1583
f75f0921
EM
1584 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id) {
1585 // CRM-10117 update the line items for participants.
2b308818
DG
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.
f75f0921
EM
1589 if ($pId) {
1590 $entityTable = 'participant';
1591 $entityID = $pId;
1592 $isRelatedId = FALSE;
be2fb01f 1593 $participantParams = [
f75f0921
EM
1594 'fee_amount' => $submittedValues['total_amount'],
1595 'id' => $entityID,
be2fb01f 1596 ];
f75f0921
EM
1597 CRM_Event_BAO_Participant::add($participantParams);
1598 if (empty($this->_lineItems)) {
77dbdcbc 1599 $this->_lineItems[] = CRM_Price_BAO_LineItem::getLineItems($entityID, 'participant', TRUE);
f75f0921
EM
1600 }
1601 }
1602 else {
1603 $entityTable = 'contribution';
1604 $entityID = $this->_id;
1605 }
6a488035 1606
77dbdcbc 1607 $lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entityTable, FALSE, TRUE, $isRelatedId);
f75f0921
EM
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 }
6a488035 1615
2b308818
DG
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 :-(
f75f0921 1618 if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
f85b8063
KJ
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);
b99f3e96 1621 if (empty($componentDetails['membership']) && empty($componentDetails['participant'])) {
f85b8063
KJ
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 }
6a488035 1626
f75f0921
EM
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'] = "";
9f907d9f 1634 $submittedValues['tax_amount'] = 0;
f75f0921
EM
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 }
6a488035
TO
1646 }
1647
f75f0921
EM
1648 $isQuickConfig = 0;
1649 if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
1650 $isQuickConfig = 1;
6a488035 1651 }
f75f0921
EM
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
2b308818
DG
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.
b99f3e96 1658 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && !empty($lineItem[$this->_priceSetId])
f75f0921
EM
1659 ) {
1660 foreach ($lineItem[$this->_priceSetId] as &$values) {
1661 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1662 }
6a488035
TO
1663 }
1664
f75f0921 1665 if (!isset($submittedValues['total_amount'])) {
9c1bc317 1666 $submittedValues['total_amount'] = $this->_values['total_amount'] ?? NULL;
7c002a4d 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 }
6a488035 1671 }
f75f0921 1672 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
6a488035 1673
0eb9f5f0 1674 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id'] ?? []));
f75f0921 1675 if ($this->_id && count($isEmpty) == 1 && key($isEmpty) == NULL) {
e11eeed7 1676 civicrm_api3('ContributionSoft', 'get', ['contribution_id' => $this->_id, 'pcp_id' => ['IS NULL' => 1], 'api.ContributionSoft.delete' => 1]);
f75f0921 1677 }
c1cc3e0c 1678
f75f0921
EM
1679 // set the contact, when contact is selected
1680 if (!empty($submittedValues['contact_id'])) {
1681 $this->_contactID = $submittedValues['contact_id'];
c1cc3e0c 1682 }
7a13735b 1683
3e6a1f4a 1684 $formValues = $submittedValues;
96025800 1685
f75f0921 1686 // Credit Card Contribution.
a5399a39 1687 if ($this->_mode) {
be2fb01f 1688 $paramsSetByPaymentProcessingSubsystem = [
bf4253e7
EM
1689 'trxn_id',
1690 'payment_instrument_id',
1691 'contribution_status_id',
1692 'cancel_date',
1693 'cancel_reason',
be2fb01f 1694 ];
bf4253e7
EM
1695 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1696 if (isset($formValues[$key])) {
1697 unset($formValues[$key]);
1698 }
1699 }
7126b55c 1700 $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID);
bf4253e7
EM
1701 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1702 $formValues[$key] = $contribution->$key;
1703 }
a5399a39 1704 }
f75f0921
EM
1705 else {
1706 // Offline Contribution.
1707 $submittedValues = $this->unsetCreditCardFields($submittedValues);
a5399a39 1708
f75f0921 1709 // get the required field value only.
3e6a1f4a 1710
66ea9833 1711 $params = [
1712 'contact_id' => $this->_contactID,
1713 'currency' => $this->getCurrency($submittedValues),
1714 'skipCleanMoney' => TRUE,
1715 'id' => $this->_id,
1716 ];
a5399a39 1717
7a13735b 1718 //format soft-credit/pcp param first
1719 CRM_Contribute_BAO_ContributionSoft::formatSoftCreditParams($submittedValues, $this);
1720 $params = array_merge($params, $submittedValues);
1721
be2fb01f 1722 $fields = [
f75f0921
EM
1723 'financial_type_id',
1724 'contribution_status_id',
1725 'payment_instrument_id',
1726 'cancel_reason',
1727 'source',
1728 'check_number',
a55e39e9 1729 'card_type_id',
1730 'pan_truncation',
be2fb01f 1731 ];
f75f0921 1732 foreach ($fields as $f) {
9c1bc317 1733 $params[$f] = $formValues[$f] ?? NULL;
f75f0921 1734 }
a5399a39 1735
46d173ef 1736 $params['revenue_recognition_date'] = NULL;
b3bf6844
AF
1737 if (!empty($formValues['revenue_recognition_date'])) {
1738 $params['revenue_recognition_date'] = $formValues['revenue_recognition_date'];
46d173ef 1739 }
f75f0921
EM
1740
1741 if (!empty($formValues['is_email_receipt'])) {
1742 $params['receipt_date'] = date("Y-m-d");
1743 }
1744
d682fc35 1745 if (CRM_Contribute_BAO_Contribution::isContributionStatusNegative($params['contribution_status_id'])
f75f0921
EM
1746 ) {
1747 if (CRM_Utils_System::isNull(CRM_Utils_Array::value('cancel_date', $params))) {
b53052cb 1748 $params['cancel_date'] = date('YmdHis');
f75f0921
EM
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
f527e012 1757 if ($params['contribution_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending')) {
f75f0921
EM
1758 $params['is_pay_later'] = 1;
1759 }
f527e012 1760 elseif ($params['contribution_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed')) {
a9f512d8 1761 // @todo - if the contribution is new then it should be Pending status & then we use
1762 // Payment.create to update to Completed.
f75f0921
EM
1763 $params['is_pay_later'] = 0;
1764 }
1765
f75f0921
EM
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 }
f75f0921 1773 $params['line_item'] = $lineItem;
9c1bc317 1774 $params['payment_processor_id'] = $params['payment_processor'] = $this->_paymentProcessor['id'] ?? NULL;
2e813c49 1775 $params['tax_amount'] = CRM_Utils_Array::value('tax_amount', $submittedValues, CRM_Utils_Array::value('tax_amount', $this->_values));
f75f0921
EM
1776 //create contribution.
1777 if ($isQuickConfig) {
1778 $params['is_quick_config'] = 1;
1779 }
07dd658b 1780 $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
f75f0921 1781
7fd21004 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 }
66ea9833 1786 $contribution = CRM_Contribute_BAO_Contribution::create($params);
f75f0921
EM
1787
1788 // process associated membership / participant, CRM-4395
bdbc1044 1789 if ($contribution->id && $action & CRM_Core_Action::UPDATE) {
a9f512d8 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
436f3267 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 ]);
f75f0921
EM
1799 }
1800
3e6a1f4a 1801 array_unshift($this->statusMessage, ts('The contribution record has been saved.'));
f75f0921 1802
6d4f5b21 1803 $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
f75f0921
EM
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
9c1bc317 1813 $this->fromEmailId = $formValues['from_email_address'] ?? NULL;
5e27919e 1814 if (CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $formValues)) {
3e6a1f4a 1815 $this->statusMessage[] = ts('A receipt has been emailed to the contributor.');
5e27919e 1816 }
f75f0921
EM
1817 }
1818
7e5961cf
EM
1819 $this->statusMessageTitle = ts('Saved');
1820
f75f0921 1821 }
5e27919e 1822
99af166d 1823 if ($contribution->id && isset($formValues['product_name'][0])) {
2dcbf765 1824 CRM_Contribute_Form_AdditionalInfo::processPremium($submittedValues, $contribution->id,
945f423d
EM
1825 $this->_premiumID, $this->_options
1826 );
1827 }
1828
dce847cf 1829 if ($contribution->id && array_key_exists('note', $submittedValues)) {
945f423d
EM
1830 CRM_Contribute_Form_AdditionalInfo::processNote($submittedValues, $this->_contactID, $contribution->id, $this->_noteID);
1831 }
1832
3e6a1f4a 1833 CRM_Core_Session::setStatus(implode(' ', $this->statusMessage), $this->statusMessageTitle, 'success');
7e5961cf 1834
5e27919e
EM
1835 CRM_Contribute_BAO_Contribution::updateRelatedPledge(
1836 $action,
1837 $pledgePaymentID,
1838 $contribution->id,
3ec3dcbe 1839 ($formValues['option_type'] ?? 0) == 2,
5e27919e 1840 $formValues['total_amount'],
3e6a1f4a 1841 CRM_Utils_Array::value('total_amount', $this->_defaults),
5e27919e 1842 $formValues['contribution_status_id'],
3e6a1f4a 1843 CRM_Utils_Array::value('contribution_status_id', $this->_defaults)
5e27919e
EM
1844 );
1845 return $contribution;
2e03ce51
EM
1846 }
1847
6d4f5b21
EM
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) {
fe4d1285 1856 if (!Civi::settings()->get('invoicing')) {
6d4f5b21
EM
1857 return;
1858 }
be2fb01f 1859 $taxRate = [];
6d4f5b21 1860 $getTaxDetails = FALSE;
f1662cbd 1861
1862 foreach ($lineItem as $key => $value) {
6d4f5b21
EM
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'])) {
9c1bc317 1869 $taxRate[(string) $v['tax_rate']] = $v['tax_amount'] ?? NULL;
6d4f5b21
EM
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);
530f1e12 1891 $this->assign('taxTerm', Civi::settings()->get('tax_term'));
6d4f5b21
EM
1892 }
1893 else {
1894 $this->assign('totalTaxAmount', CRM_Utils_Array::value('tax_amount', $submittedValues));
1895 }
1896 }
1897 }
1898
07dd658b
EM
1899 /**
1900 * Calculate non deductible amount.
1901 *
0e480632 1902 * @see https://issues.civicrm.org/jira/browse/CRM-11956
07dd658b
EM
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 }
5afce5ad 1916
9c1bc317 1917 $priceSetId = $params['price_set_id'] ?? NULL;
5afce5ad 1918 // return non-deductible amount if it is set at the price field option level
05465712 1919 if ($priceSetId && !empty($params['line_item'])) {
1920 $nonDeductibleAmount = CRM_Price_BAO_PriceSet::getNonDeductibleAmountFromPriceSet($priceSetId, $params['line_item']);
1921 if (!empty($nonDeductibleAmount)) {
5afce5ad 1922 return $nonDeductibleAmount;
1923 }
1924 }
07dd658b 1925
f70eb51f
EM
1926 $financialType = new CRM_Financial_DAO_FinancialType();
1927 $financialType->id = $params['financial_type_id'];
11829025 1928 $financialType->find(TRUE);
07dd658b 1929
f70eb51f
EM
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'];
07dd658b 1943 }
f70eb51f 1944 // product value does NOT exceed contribution amount
07dd658b 1945 else {
f70eb51f 1946 return $productDAO->price;
07dd658b
EM
1947 }
1948 }
f70eb51f 1949 // contribution is deductible - but there is no product
07dd658b 1950 else {
f70eb51f 1951 return '0.00';
07dd658b
EM
1952 }
1953 }
f70eb51f
EM
1954 // contribution is NOT deductible
1955 else {
1956 return $params['total_amount'];
1957 }
1958
07dd658b
EM
1959 return 0;
1960 }
1961
c6a8691e 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
e5777079
MW
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
e47077ce
EM
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 *
21adcaec 2021 * @return string|null
e47077ce
EM
2022 *
2023 * @throws \API_Exception
2024 */
21adcaec
EM
2025 protected function getPreviousContributionStatus(): ?string {
2026 if (!$this->getContributionID()) {
2027 return NULL;
2028 }
e47077ce
EM
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
e50c797d
EM
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');
81a49da2 2055 $statusNamesToUnset = array_diff([
e50c797d
EM
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',
81a49da2
EM
2063 'Partially paid',
2064 'Pending refund',
2065 ], [$this->getPreviousContributionStatus()]);
e50c797d
EM
2066 switch ($this->getPreviousContributionStatus()) {
2067 case 'Completed':
2068 // [CRM-17498] Removing unsupported status change options.
2069 $statusNamesToUnset = array_merge($statusNamesToUnset, [
2070 'Pending',
2071 'Failed',
e50c797d
EM
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
32b88e1e
EM
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
6a488035 2131}