Merge pull request #22514 from braders/feature/report-statistics-docblock
[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 = $this->getAvailableContributionStatuses();
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 $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 = $this->processFormContribution(
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 * Process the contribution.
1201 *
1202 * @todo - this form is a copy of the previously shared code on the front
1203 * end form - not all aspects of the code will be relevant to this form.
1204 *
1205 * @param array $params
1206 * @param array $result
1207 * @param array $contributionParams
1208 * Parameters to be passed to contribution create action.
1209 * This differs from params in that we are currently adding params to it and 1) ensuring they are being
1210 * passed consistently & 2) documenting them here.
1211 * - contact_id
1212 * - line_item
1213 * - is_test
1214 * - campaign_id
1215 * - contribution_page_id
1216 * - source
1217 * - payment_type_id
1218 * - thankyou_date (not all forms will set this)
1219 *
1220 * @param CRM_Financial_DAO_FinancialType $financialType
1221 * @param bool $online
1222 * Is the form a front end form? If so set a bunch of unpredictable things that should be passed in from the form.
1223 *
1224 * @param int $billingLocationID
1225 * ID of billing location type.
1226 * @param bool $isRecur
1227 * Is this recurring?
1228 *
1229 * @return \CRM_Contribute_DAO_Contribution
1230 *
1231 * @throws \CRM_Core_Exception
1232 * @throws \CiviCRM_API3_Exception
1233 */
1234 protected function processFormContribution(
1235 $params,
1236 $result,
1237 $contributionParams,
1238 $financialType,
1239 $online,
1240 $billingLocationID,
1241 $isRecur
1242 ) {
1243 $form = $this;
1244 $transaction = new CRM_Core_Transaction();
1245 $contactID = $contributionParams['contact_id'];
1246
1247 $isEmailReceipt = !empty($form->_values['is_email_receipt']);
1248 $isSeparateMembershipPayment = !empty($params['separate_membership_payment']);
1249 $pledgeID = !empty($params['pledge_id']) ? $params['pledge_id'] : $form->_values['pledge_id'] ?? NULL;
1250 if (!$isSeparateMembershipPayment && !empty($form->_values['pledge_block_id']) &&
1251 (!empty($params['is_pledge']) || $pledgeID)) {
1252 $isPledge = TRUE;
1253 }
1254 else {
1255 $isPledge = FALSE;
1256 }
1257
1258 // add these values for the recurringContrib function ,CRM-10188
1259 $params['financial_type_id'] = $financialType->id;
1260
1261 $contributionParams['address_id'] = CRM_Contribute_BAO_Contribution::createAddress($params, $billingLocationID);
1262
1263 //@todo - this is being set from the form to resolve CRM-10188 - an
1264 // eNotice caused by it not being set @ the front end
1265 // however, we then get it being over-written with null for backend contributions
1266 // a better fix would be to set the values in the respective forms rather than require
1267 // a function being shared by two forms to deal with their respective values
1268 // moving it to the BAO & not taking the $form as a param would make sense here.
1269 if (!isset($params['is_email_receipt']) && $isEmailReceipt) {
1270 $params['is_email_receipt'] = $isEmailReceipt;
1271 }
1272 $params['is_recur'] = $isRecur;
1273 $params['payment_instrument_id'] = $contributionParams['payment_instrument_id'] ?? NULL;
1274 $recurringContributionID = CRM_Contribute_Form_Contribution_Confirm::processRecurringContribution($form, $params, $contactID, $financialType);
1275
1276 $now = date('YmdHis');
1277 $receiptDate = $params['receipt_date'] ?? NULL;
1278 if ($isEmailReceipt) {
1279 $receiptDate = $now;
1280 }
1281
1282 if (isset($params['amount'])) {
1283 $contributionParams = array_merge(CRM_Contribute_Form_Contribution_Confirm::getContributionParams(
1284 $params, $financialType->id,
1285 $result, $receiptDate,
1286 $recurringContributionID), $contributionParams
1287 );
1288 $contributionParams['non_deductible_amount'] = CRM_Contribute_Form_Contribution_Confirm::getNonDeductibleAmount($params, $financialType, FALSE, $form);
1289 $contributionParams['skipCleanMoney'] = TRUE;
1290 // @todo this is the wrong place for this - it should be done as close to form submission
1291 // as possible
1292 $contributionParams['total_amount'] = $params['amount'];
1293
1294 $contribution = CRM_Contribute_BAO_Contribution::add($contributionParams);
1295
1296 if (Civi::settings()->get('invoicing')) {
1297 $dataArray = [];
1298 // @todo - interrogate the line items passed in on the params array.
1299 // No reason to assume line items will be set on the form.
1300 foreach ($form->_lineItem as $lineItemKey => $lineItemValue) {
1301 foreach ($lineItemValue as $key => $value) {
1302 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
1303 if (isset($dataArray[$value['tax_rate']])) {
1304 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + $value['tax_amount'];
1305 }
1306 else {
1307 $dataArray[$value['tax_rate']] = $value['tax_amount'];
1308 }
1309 }
1310 }
1311 }
1312 $smarty = CRM_Core_Smarty::singleton();
1313 $smarty->assign('dataArray', $dataArray);
1314 $smarty->assign('totalTaxAmount', $params['tax_amount'] ?? NULL);
1315 }
1316
1317 // lets store it in the form variable so postProcess hook can get to this and use it
1318 $form->_contributionID = $contribution->id;
1319 }
1320
1321 // process soft credit / pcp params first
1322 CRM_Contribute_BAO_ContributionSoft::formatSoftCreditParams($params, $form);
1323
1324 //CRM-13981, processing honor contact into soft-credit contribution
1325 CRM_Contribute_BAO_ContributionSoft::processSoftContribution($params, $contribution);
1326
1327 if ($isPledge) {
1328 $form = CRM_Contribute_Form_Contribution_Confirm::handlePledge($form, $params, $contributionParams, $pledgeID, $contribution, $isEmailReceipt);
1329 }
1330
1331 if ($online && $contribution) {
1332 CRM_Core_BAO_CustomValueTable::postProcess($params,
1333 'civicrm_contribution',
1334 $contribution->id,
1335 'Contribution'
1336 );
1337 }
1338 elseif ($contribution) {
1339 //handle custom data.
1340 $params['contribution_id'] = $contribution->id;
1341 if (!empty($params['custom']) &&
1342 is_array($params['custom'])
1343 ) {
1344 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
1345 }
1346 }
1347 // Save note
1348 if ($contribution && !empty($params['contribution_note'])) {
1349 $noteParams = [
1350 'entity_table' => 'civicrm_contribution',
1351 'note' => $params['contribution_note'],
1352 'entity_id' => $contribution->id,
1353 'contact_id' => $contribution->contact_id,
1354 ];
1355
1356 CRM_Core_BAO_Note::add($noteParams, []);
1357 }
1358
1359 //create contribution activity w/ individual and target
1360 //activity w/ organisation contact id when onbelf, CRM-4027
1361 $actParams = [];
1362 $targetContactID = NULL;
1363 if (!empty($params['onbehalf_contact_id'])) {
1364 $actParams = [
1365 'source_contact_id' => $params['onbehalf_contact_id'],
1366 'on_behalf' => TRUE,
1367 ];
1368 $targetContactID = $contribution->contact_id;
1369 }
1370
1371 // create an activity record
1372 if ($contribution) {
1373 CRM_Activity_BAO_Activity::addActivity($contribution, 'Contribution', $targetContactID, $actParams);
1374 }
1375
1376 $transaction->commit();
1377 return $contribution;
1378 }
1379
1380 /**
1381 * Generate the data to construct a snippet based pane.
1382 *
1383 * This form also assigns the showAdditionalInfo var based on historical code.
1384 * This appears to mean 'there is a pane to show'.
1385 *
1386 * @param string $type
1387 * Type of Pane - this is generally used to determine the function name used to build it
1388 * - e.g CreditCard, AdditionalDetail
1389 * @param array $defaults
1390 *
1391 * @return array
1392 * We aim to further refactor & simplify this but currently
1393 * - the panes array
1394 * - should additional info be shown?
1395 */
1396 protected function generatePane($type, $defaults) {
1397 $urlParams = "snippet=4&formType={$type}";
1398 if ($this->_mode) {
1399 $urlParams .= "&mode={$this->_mode}";
1400 }
1401
1402 $open = 'false';
1403 if ($type == 'CreditCard' ||
1404 $type == 'DirectDebit'
1405 ) {
1406 $open = 'true';
1407 }
1408
1409 $pane = [
1410 'url' => CRM_Utils_System::url('civicrm/contact/view/contribution', $urlParams),
1411 'open' => $open,
1412 'id' => $type,
1413 ];
1414
1415 // See if we need to include this paneName in the current form.
1416 if ($this->_formType == $type || !empty($_POST["hidden_{$type}"]) ||
1417 !empty($defaults["hidden_{$type}"])
1418 ) {
1419 $this->assign('showAdditionalInfo', TRUE);
1420 $pane['open'] = 'true';
1421 }
1422
1423 if ($type == 'CreditCard' || $type == 'DirectDebit') {
1424 // @todo would be good to align tpl name with form name...
1425 // @todo document why this hidden variable is required.
1426 $this->add('hidden', 'hidden_' . $type, 1);
1427 return $pane;
1428 }
1429 else {
1430 $additionalInfoFormFunction = 'build' . $type;
1431 CRM_Contribute_Form_AdditionalInfo::$additionalInfoFormFunction($this);
1432 return $pane;
1433 }
1434 }
1435
1436 /**
1437 * Wrapper for unit testing the post process submit function.
1438 *
1439 * (If we expose through api we can get default additions 'for free').
1440 *
1441 * @param array $params
1442 * @param int $action
1443 * @param string|null $creditCardMode
1444 *
1445 * @return CRM_Contribute_BAO_Contribution
1446 *
1447 * @throws \CRM_Core_Exception
1448 * @throws \CiviCRM_API3_Exception
1449 * @throws \Civi\Payment\Exception\PaymentProcessorException
1450 */
1451 public function testSubmit($params, $action, $creditCardMode = NULL) {
1452 $defaults = [
1453 'soft_credit_contact_id' => [],
1454 'receive_date' => date('Y-m-d H:i:s'),
1455 'receipt_date' => '',
1456 'cancel_date' => '',
1457 'hidden_Premium' => 1,
1458 ];
1459 $this->_bltID = 5;
1460 if (!empty($params['id'])) {
1461 $existingContribution = civicrm_api3('contribution', 'getsingle', [
1462 'id' => $params['id'],
1463 ]);
1464 $this->_id = $params['id'];
1465 $this->_values = $existingContribution;
1466 if (CRM_Invoicing_Utils::isInvoicingEnabled()) {
1467 $this->_values['tax_amount'] = civicrm_api3('contribution', 'getvalue', [
1468 'id' => $params['id'],
1469 'return' => 'tax_amount',
1470 ]);
1471 }
1472 }
1473 else {
1474 $existingContribution = [];
1475 }
1476
1477 $this->_defaults['contribution_status_id'] = CRM_Utils_Array::value('contribution_status_id',
1478 $existingContribution
1479 );
1480
1481 $this->_defaults['total_amount'] = CRM_Utils_Array::value('total_amount',
1482 $existingContribution
1483 );
1484
1485 if ($creditCardMode) {
1486 $this->_mode = $creditCardMode;
1487 }
1488
1489 // Required because processCreditCard calls set method on this.
1490 $_SERVER['REQUEST_METHOD'] = 'GET';
1491 $this->controller = new CRM_Core_Controller();
1492
1493 CRM_Contribute_Form_AdditionalInfo::buildPremium($this);
1494
1495 $this->_fields = [];
1496 return $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array::value('pledge_payment_id', $params));
1497
1498 }
1499
1500 /**
1501 * @param array $submittedValues
1502 *
1503 * @param int $action
1504 * Action constant
1505 * - CRM_Core_Action::UPDATE
1506 *
1507 * @param $pledgePaymentID
1508 *
1509 * @return \CRM_Contribute_BAO_Contribution
1510 *
1511 * @throws \CRM_Core_Exception
1512 * @throws \CiviCRM_API3_Exception
1513 * @throws \Civi\Payment\Exception\PaymentProcessorException
1514 */
1515 protected function submit($submittedValues, $action, $pledgePaymentID) {
1516 $pId = $contribution = $isRelatedId = FALSE;
1517 $this->_params = $submittedValues;
1518 $this->beginPostProcess();
1519 // reassign submitted form values if the any information is formatted via beginPostProcess
1520 $submittedValues = $this->_params;
1521
1522 if ($this->getPriceSetID() && $action & CRM_Core_Action::UPDATE) {
1523 $line = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution');
1524 $lineID = key($line);
1525 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array::value('price_field_id', $line[$lineID]), 'price_set_id');
1526 $quickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1527 // Why do we do this? Seems like a like a wrapper for old functionality - but single line price sets & quick
1528 // config should be treated the same.
1529 if ($quickConfig) {
1530 CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_contribution');
1531 }
1532 }
1533
1534 // Process price set and get total amount and line items.
1535 $lineItem = [];
1536 $priceSetId = $submittedValues['price_set_id'] ?? NULL;
1537 if (!$this->getPriceSetID() && !$this->_id) {
1538 $this->_priceSetId = $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1539 $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
1540 $fieldID = key($this->_priceSet['fields']);
1541 $fieldValueId = key($this->_priceSet['fields'][$fieldID]['options']);
1542 $this->_priceSet['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1543 $submittedValues['price_' . $fieldID] = 1;
1544 }
1545
1546 // Every contribution has a price-set - the only reason it shouldn't be set is if we are dealing with
1547 // quick config (very very arguably) & yet we see that this could still be quick config so this should be understood
1548 // as a point of fragility rather than a logical 'if' clause.
1549 if ($priceSetId) {
1550 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
1551 $submittedValues, $lineItem[$priceSetId], $priceSetId);
1552 // Unset tax amount for offline 'is_quick_config' contribution.
1553 // @todo WHY - quick config was conceived as a quick way to configure contribution forms.
1554 // this is an example of 'other' functionality being hung off it.
1555 if ($this->_priceSet['is_quick_config'] &&
1556 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant::getTaxRates())
1557 ) {
1558 unset($submittedValues['tax_amount']);
1559 }
1560 $submittedValues['total_amount'] = $submittedValues['amount'] ?? NULL;
1561 }
1562
1563 if ($this->_id) {
1564 if ($this->_compId) {
1565 if ($this->_context == 'participant') {
1566 $pId = $this->_compId;
1567 }
1568 elseif ($this->_context == 'membership') {
1569 $isRelatedId = TRUE;
1570 }
1571 else {
1572 $pId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'participant_id', 'contribution_id');
1573 }
1574 }
1575 else {
1576 $contributionDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
1577 if (array_key_exists('membership', $contributionDetails)) {
1578 $isRelatedId = TRUE;
1579 }
1580 elseif (array_key_exists('participant', $contributionDetails)) {
1581 $pId = $contributionDetails['participant'];
1582 }
1583 }
1584 if (!empty($this->_payNow)) {
1585 $this->_params['contribution_id'] = $this->_id;
1586 }
1587 }
1588
1589 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id) {
1590 // CRM-10117 update the line items for participants.
1591 // @todo - if we are completing a contribution then the api call
1592 // civicrm_api3('Contribution', 'completetransaction') should take care of
1593 // all associated updates rather than replicating them on the form layer.
1594 if ($pId) {
1595 $entityTable = 'participant';
1596 $entityID = $pId;
1597 $isRelatedId = FALSE;
1598 $participantParams = [
1599 'fee_amount' => $submittedValues['total_amount'],
1600 'id' => $entityID,
1601 ];
1602 CRM_Event_BAO_Participant::add($participantParams);
1603 if (empty($this->_lineItems)) {
1604 $this->_lineItems[] = CRM_Price_BAO_LineItem::getLineItems($entityID, 'participant', TRUE);
1605 }
1606 }
1607 else {
1608 $entityTable = 'contribution';
1609 $entityID = $this->_id;
1610 }
1611
1612 $lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entityTable, FALSE, TRUE, $isRelatedId);
1613 foreach (array_keys($lineItems) as $id) {
1614 $lineItems[$id]['id'] = $id;
1615 }
1616 $itemId = key($lineItems);
1617 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1618 $this->_priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1619 }
1620
1621 // @todo see above - new functionality has been inappropriately added to the quick config concept
1622 // and new functionality has been added onto the form layer rather than the BAO :-(
1623 if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
1624 //CRM-16833: Ensure tax is applied only once for membership conribution, when status changed.(e.g Pending to Completed).
1625 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
1626 if (empty($componentDetails['membership']) && empty($componentDetails['participant'])) {
1627 if (!($this->_action & CRM_Core_Action::UPDATE && (($this->_defaults['contribution_status_id'] != $submittedValues['contribution_status_id'])))) {
1628 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value('total_amount', $submittedValues));
1629 }
1630 }
1631
1632 // Update line total and total amount with tax on edit.
1633 $financialItemsId = CRM_Core_PseudoConstant::getTaxRates();
1634 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1635 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1636 }
1637 else {
1638 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1639 $submittedValues['tax_amount'] = 0;
1640 }
1641 if ($lineItems[$itemId]['tax_rate']) {
1642 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total'];
1643 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] + $lineItems[$itemId]['tax_amount'];
1644 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1645 }
1646 }
1647 // CRM-10117 update the line items for participants.
1648 if (!empty($lineItems[$itemId]['price_field_id'])) {
1649 $lineItem[$this->_priceSetId] = $lineItems;
1650 }
1651 }
1652
1653 $isQuickConfig = 0;
1654 if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
1655 $isQuickConfig = 1;
1656 }
1657 //CRM-11529 for quick config back office transactions
1658 //when financial_type_id is passed in form, update the
1659 //line items with the financial type selected in form
1660 // NOTE that this IS still a legitimate use of 'quick-config' for contributions under the current DB but
1661 // we should look at having a price field per contribution type & then there would be little reason
1662 // for the back-office contribution form postProcess to know if it is a quick-config form.
1663 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && !empty($lineItem[$this->_priceSetId])
1664 ) {
1665 foreach ($lineItem[$this->_priceSetId] as &$values) {
1666 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1667 }
1668 }
1669
1670 if (!isset($submittedValues['total_amount'])) {
1671 $submittedValues['total_amount'] = $this->_values['total_amount'] ?? NULL;
1672 // Avoid tax amount deduction on edit form and keep it original, because this will lead to error described in CRM-20676
1673 if (!$this->_id) {
1674 $submittedValues['total_amount'] -= CRM_Utils_Array::value('tax_amount', $this->_values, 0);
1675 }
1676 }
1677 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
1678
1679 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id'] ?? []));
1680 if ($this->_id && count($isEmpty) == 1 && key($isEmpty) == NULL) {
1681 civicrm_api3('ContributionSoft', 'get', ['contribution_id' => $this->_id, 'pcp_id' => ['IS NULL' => 1], 'api.ContributionSoft.delete' => 1]);
1682 }
1683
1684 // set the contact, when contact is selected
1685 if (!empty($submittedValues['contact_id'])) {
1686 $this->_contactID = $submittedValues['contact_id'];
1687 }
1688
1689 $formValues = $submittedValues;
1690
1691 // Credit Card Contribution.
1692 if ($this->_mode) {
1693 $paramsSetByPaymentProcessingSubsystem = [
1694 'trxn_id',
1695 'payment_instrument_id',
1696 'contribution_status_id',
1697 'cancel_date',
1698 'cancel_reason',
1699 ];
1700 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1701 if (isset($formValues[$key])) {
1702 unset($formValues[$key]);
1703 }
1704 }
1705 $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID);
1706 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1707 $formValues[$key] = $contribution->$key;
1708 }
1709 }
1710 else {
1711 // Offline Contribution.
1712 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1713
1714 // get the required field value only.
1715
1716 $params = [
1717 'contact_id' => $this->_contactID,
1718 'currency' => $this->getCurrency($submittedValues),
1719 'skipCleanMoney' => TRUE,
1720 'id' => $this->_id,
1721 ];
1722
1723 //format soft-credit/pcp param first
1724 CRM_Contribute_BAO_ContributionSoft::formatSoftCreditParams($submittedValues, $this);
1725 $params = array_merge($params, $submittedValues);
1726
1727 $fields = [
1728 'financial_type_id',
1729 'contribution_status_id',
1730 'payment_instrument_id',
1731 'cancel_reason',
1732 'source',
1733 'check_number',
1734 'card_type_id',
1735 'pan_truncation',
1736 ];
1737 foreach ($fields as $f) {
1738 $params[$f] = $formValues[$f] ?? NULL;
1739 }
1740
1741 $params['revenue_recognition_date'] = NULL;
1742 if (!empty($formValues['revenue_recognition_date'])) {
1743 $params['revenue_recognition_date'] = $formValues['revenue_recognition_date'];
1744 }
1745
1746 if (!empty($formValues['is_email_receipt'])) {
1747 $params['receipt_date'] = date("Y-m-d");
1748 }
1749
1750 if (CRM_Contribute_BAO_Contribution::isContributionStatusNegative($params['contribution_status_id'])
1751 ) {
1752 if (CRM_Utils_System::isNull(CRM_Utils_Array::value('cancel_date', $params))) {
1753 $params['cancel_date'] = date('YmdHis');
1754 }
1755 }
1756 else {
1757 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1758 }
1759
1760 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1761 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1762 if ($params['contribution_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending')) {
1763 $params['is_pay_later'] = 1;
1764 }
1765 elseif ($params['contribution_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed')) {
1766 // @todo - if the contribution is new then it should be Pending status & then we use
1767 // Payment.create to update to Completed.
1768 $params['is_pay_later'] = 0;
1769 }
1770
1771 // Add Additional common information to formatted params.
1772 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($formValues, $params, $this);
1773 if ($pId) {
1774 $params['contribution_mode'] = 'participant';
1775 $params['participant_id'] = $pId;
1776 $params['skipLineItem'] = 1;
1777 }
1778 $params['line_item'] = $lineItem;
1779 $params['payment_processor_id'] = $params['payment_processor'] = $this->_paymentProcessor['id'] ?? NULL;
1780 $params['tax_amount'] = CRM_Utils_Array::value('tax_amount', $submittedValues, CRM_Utils_Array::value('tax_amount', $this->_values));
1781 //create contribution.
1782 if ($isQuickConfig) {
1783 $params['is_quick_config'] = 1;
1784 }
1785 $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
1786
1787 // we are already handling note below, so to avoid duplicate notes against $contribution
1788 if (!empty($params['note']) && !empty($submittedValues['note'])) {
1789 unset($params['note']);
1790 }
1791 $contribution = CRM_Contribute_BAO_Contribution::create($params);
1792
1793 // process associated membership / participant, CRM-4395
1794 if ($contribution->id && $action & CRM_Core_Action::UPDATE) {
1795 // @todo use Payment.create to do this, remove transitioncomponents function
1796 // if contribution is being created with a completed status it should be
1797 // created pending & then Payment.create adds the payment
1798 CRM_Contribute_BAO_Contribution::transitionComponents([
1799 'contribution_id' => $contribution->id,
1800 'contribution_status_id' => $contribution->contribution_status_id,
1801 'previous_contribution_status_id' => $this->_values['contribution_status_id'] ?? NULL,
1802 'receive_date' => $contribution->receive_date,
1803 ]);
1804 }
1805
1806 array_unshift($this->statusMessage, ts('The contribution record has been saved.'));
1807
1808 $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
1809
1810 //send receipt mail.
1811 if ($contribution->id && !empty($formValues['is_email_receipt'])) {
1812 $formValues['contact_id'] = $this->_contactID;
1813 $formValues['contribution_id'] = $contribution->id;
1814
1815 $formValues += CRM_Contribute_BAO_ContributionSoft::getSoftContribution($contribution->id);
1816
1817 // to get 'from email id' for send receipt
1818 $this->fromEmailId = $formValues['from_email_address'] ?? NULL;
1819 if (CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $formValues)) {
1820 $this->statusMessage[] = ts('A receipt has been emailed to the contributor.');
1821 }
1822 }
1823
1824 $this->statusMessageTitle = ts('Saved');
1825
1826 }
1827
1828 if ($contribution->id && isset($formValues['product_name'][0])) {
1829 CRM_Contribute_Form_AdditionalInfo::processPremium($submittedValues, $contribution->id,
1830 $this->_premiumID, $this->_options
1831 );
1832 }
1833
1834 if ($contribution->id && array_key_exists('note', $submittedValues)) {
1835 CRM_Contribute_Form_AdditionalInfo::processNote($submittedValues, $this->_contactID, $contribution->id, $this->_noteID);
1836 }
1837
1838 CRM_Core_Session::setStatus(implode(' ', $this->statusMessage), $this->statusMessageTitle, 'success');
1839
1840 CRM_Contribute_BAO_Contribution::updateRelatedPledge(
1841 $action,
1842 $pledgePaymentID,
1843 $contribution->id,
1844 ($formValues['option_type'] ?? 0) == 2,
1845 $formValues['total_amount'],
1846 CRM_Utils_Array::value('total_amount', $this->_defaults),
1847 $formValues['contribution_status_id'],
1848 CRM_Utils_Array::value('contribution_status_id', $this->_defaults)
1849 );
1850 return $contribution;
1851 }
1852
1853 /**
1854 * Assign tax calculations to contribution receipts.
1855 *
1856 * @param array $submittedValues
1857 * @param int $action
1858 * @param array $lineItem
1859 */
1860 protected function invoicingPostProcessHook($submittedValues, $action, $lineItem) {
1861 if (!Civi::settings()->get('invoicing')) {
1862 return;
1863 }
1864 $taxRate = [];
1865 $getTaxDetails = FALSE;
1866
1867 foreach ($lineItem as $key => $value) {
1868 foreach ($value as $v) {
1869 if (isset($taxRate[(string) CRM_Utils_Array::value('tax_rate', $v)])) {
1870 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array::value('tax_amount', $v);
1871 }
1872 else {
1873 if (isset($v['tax_rate'])) {
1874 $taxRate[(string) $v['tax_rate']] = $v['tax_amount'] ?? NULL;
1875 $getTaxDetails = TRUE;
1876 }
1877 }
1878 }
1879 }
1880
1881 if ($action & CRM_Core_Action::UPDATE) {
1882 if (isset($submittedValues['tax_amount'])) {
1883 $totalTaxAmount = $submittedValues['tax_amount'];
1884 }
1885 else {
1886 $totalTaxAmount = $this->_values['tax_amount'];
1887 }
1888 $this->assign('totalTaxAmount', $totalTaxAmount);
1889 $this->assign('dataArray', $taxRate);
1890 }
1891 else {
1892 if (!empty($submittedValues['price_set_id'])) {
1893 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1894 $this->assign('getTaxDetails', $getTaxDetails);
1895 $this->assign('dataArray', $taxRate);
1896 $this->assign('taxTerm', Civi::settings()->get('tax_term'));
1897 }
1898 else {
1899 $this->assign('totalTaxAmount', CRM_Utils_Array::value('tax_amount', $submittedValues));
1900 }
1901 }
1902 }
1903
1904 /**
1905 * Calculate non deductible amount.
1906 *
1907 * @see https://issues.civicrm.org/jira/browse/CRM-11956
1908 * if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1909 * if non_deductible_amount does NOT exist - then calculate it depending on:
1910 * $financialType->is_deductible and whether there is a product (premium).
1911 *
1912 * @param $params
1913 * @param $formValues
1914 *
1915 * @return array
1916 */
1917 protected function calculateNonDeductibleAmount($params, $formValues) {
1918 if (!empty($params['non_deductible_amount'])) {
1919 return $params['non_deductible_amount'];
1920 }
1921
1922 $priceSetId = $params['price_set_id'] ?? NULL;
1923 // return non-deductible amount if it is set at the price field option level
1924 if ($priceSetId && !empty($params['line_item'])) {
1925 $nonDeductibleAmount = CRM_Price_BAO_PriceSet::getNonDeductibleAmountFromPriceSet($priceSetId, $params['line_item']);
1926 if (!empty($nonDeductibleAmount)) {
1927 return $nonDeductibleAmount;
1928 }
1929 }
1930
1931 $financialType = new CRM_Financial_DAO_FinancialType();
1932 $financialType->id = $params['financial_type_id'];
1933 $financialType->find(TRUE);
1934
1935 if ($financialType->is_deductible) {
1936
1937 if (isset($formValues['product_name'][0])) {
1938 $selectProduct = $formValues['product_name'][0];
1939 }
1940 // if there is a product - compare the value to the contribution amount
1941 if (isset($selectProduct)) {
1942 $productDAO = new CRM_Contribute_DAO_Product();
1943 $productDAO->id = $selectProduct;
1944 $productDAO->find(TRUE);
1945 // product value exceeds contribution amount
1946 if ($params['total_amount'] < $productDAO->price) {
1947 return $params['total_amount'];
1948 }
1949 // product value does NOT exceed contribution amount
1950 else {
1951 return $productDAO->price;
1952 }
1953 }
1954 // contribution is deductible - but there is no product
1955 else {
1956 return '0.00';
1957 }
1958 }
1959 // contribution is NOT deductible
1960 else {
1961 return $params['total_amount'];
1962 }
1963
1964 return 0;
1965 }
1966
1967 /**
1968 * Get the financial Type ID for the contribution either from the submitted values or from the contribution values if possible.
1969 *
1970 * This is important for dev/core#1728 - ie ensure that if we are returned to the form for a form
1971 * error that any custom fields based on the selected financial type are loaded.
1972 *
1973 * @return int
1974 */
1975 protected function getFinancialTypeID() {
1976 if (!empty($this->_submitValues['financial_type_id'])) {
1977 return $this->_submitValues['financial_type_id'];
1978 }
1979 if (!empty($this->_values['financial_type_id'])) {
1980 return $this->_values['financial_type_id'];
1981 }
1982 }
1983
1984 /**
1985 * Set context in session
1986 */
1987 public function setUserContext(): void {
1988 $session = CRM_Core_Session::singleton();
1989 $buttonName = $this->controller->getButtonName();
1990 if ($this->_context == 'standalone') {
1991 if ($buttonName == $this->getButtonName('upload', 'new')) {
1992 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contribute/add',
1993 'reset=1&action=add&context=standalone'
1994 ));
1995 }
1996 else {
1997 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
1998 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1999 ));
2000 }
2001 }
2002 elseif ($this->_context == 'contribution' && $this->_mode && $buttonName == $this->getButtonName('upload', 'new')) {
2003 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution',
2004 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
2005 ));
2006 }
2007 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
2008 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution',
2009 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
2010 ));
2011 }
2012 }
2013
2014 /**
2015 * Get the contribution ID.
2016 *
2017 * @return int|null
2018 */
2019 protected function getContributionID(): ?int {
2020 return $this->_id;
2021 }
2022
2023 /**
2024 * Get the selected contribution status.
2025 *
2026 * @return string|null
2027 *
2028 * @throws \API_Exception
2029 */
2030 protected function getPreviousContributionStatus(): ?string {
2031 if (!$this->getContributionID()) {
2032 return NULL;
2033 }
2034 if (!$this->previousContributionStatus) {
2035 $this->previousContributionStatus = Contribution::get(FALSE)
2036 ->addWhere('id', '=', $this->getContributionID())
2037 ->addSelect('contribution_status_id:name')
2038 ->execute()
2039 ->first()['contribution_status_id:name'];
2040 }
2041 return $this->previousContributionStatus;
2042 }
2043
2044 /**
2045 * Get the contribution statuses available on the form.
2046 *
2047 * @todo - this needs work - some returned options are invalid or do
2048 * not create good financial entities. Probably the only reason we don't just
2049 * return CRM_Contribute_BAO_Contribution_Utils::getPendingCompleteFailedAndCancelledStatuses();
2050 * is that it might exclude the current status of the contribution.
2051 *
2052 * @return array
2053 * @throws \API_Exception
2054 */
2055 protected function getAvailableContributionStatuses(): array {
2056 if (!$this->getPreviousContributionStatus()) {
2057 return CRM_Contribute_BAO_Contribution_Utils::getPendingCompleteFailedAndCancelledStatuses();
2058 }
2059 $statusNames = CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id', 'validate');
2060 $statusNamesToUnset = [
2061 // For records which represent a data template for a recurring
2062 // contribution that may not yet have a payment. This status should not
2063 // be available from forms. 'Template' contributions should only be created
2064 // in conjunction with a ContributionRecur record, and should have their
2065 // is_template field set to 1. This status excludes them from reports
2066 // that are still ignorant of the is_template field.
2067 'Template',
2068 ];
2069 switch ($this->getPreviousContributionStatus()) {
2070 case 'Completed':
2071 // [CRM-17498] Removing unsupported status change options.
2072 $statusNamesToUnset = array_merge($statusNamesToUnset, [
2073 'Pending',
2074 'Failed',
2075 'Partially paid',
2076 'Pending refund',
2077 ]);
2078 break;
2079
2080 case 'Cancelled':
2081 case 'Chargeback':
2082 case 'Refunded':
2083 $statusNamesToUnset = array_merge($statusNamesToUnset, [
2084 'Pending',
2085 'Failed',
2086 ]);
2087 break;
2088
2089 case 'Pending':
2090 case 'In Progress':
2091 $statusNamesToUnset = array_merge($statusNamesToUnset, [
2092 'Refunded',
2093 'Chargeback',
2094 ]);
2095 break;
2096
2097 case 'Failed':
2098 $statusNamesToUnset = array_merge($statusNamesToUnset, [
2099 'Pending',
2100 'Refunded',
2101 'Chargeback',
2102 'Completed',
2103 'In Progress',
2104 'Cancelled',
2105 ]);
2106 break;
2107 }
2108
2109 foreach ($statusNamesToUnset as $name) {
2110 unset($statusNames[CRM_Utils_Array::key($name, $statusNames)]);
2111 }
2112
2113 $statuses = CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id');
2114
2115 foreach ($statuses as $statusID => $label) {
2116 if (!array_key_exists($statusID, $statusNames)) {
2117 unset($statuses[$statusID]);
2118 }
2119 }
2120
2121 return $statuses;
2122 }
2123
2124 /**
2125 * Get the price set ID.
2126 *
2127 * Note that the function currently returns NULL if not submitted
2128 * but will over time be fixed to always return an ID.
2129 *
2130 * @return int|null
2131 */
2132 protected function getPriceSetID() {
2133 return $this->getSubmittedValue('price_set_id');
2134 }
2135
2136 }