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