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