-
-
Notifications
You must be signed in to change notification settings - Fork 826
/
Copy pathContribution.php
2702 lines (2407 loc) · 99.2 KB
/
Contribution.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC. All rights reserved. |
| |
| This work is published under the GNU AGPLv3 license with some |
| permitted exceptions and without any warranty. For full license |
| and copyright information, see https://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
use Civi\Api4\Contribution;
use Civi\Api4\FinancialType;
use Civi\Payment\Exception\PaymentProcessorException;
/**
* This class generates form components for processing a contribution.
*/
class CRM_Contribute_Form_Contribution extends CRM_Contribute_Form_AbstractEditPayment {
use CRM_Contact_Form_ContactFormTrait;
use CRM_Contribute_Form_ContributeFormTrait;
use CRM_Financial_Form_PaymentProcessorFormTrait;
use CRM_Custom_Form_CustomDataTrait;
/**
* The id of the contribution that we are processing.
*
* @var int
*/
public $_id;
/**
* The id of the premium that we are processing.
*
* @var int
*/
public $_premiumID;
/**
* @var CRM_Contribute_DAO_ContributionProduct
*/
public $_productDAO;
/**
* The id of the note.
*
* @var int
*/
public $_noteID;
/**
* The id of the contact associated with this contribution.
*
* @var int
*/
public $_contactID;
/**
* The id of the pledge payment that we are processing.
*
* @var int
* @internal Only retrieve using $this->getPledgePaymentID().
*/
public $_ppID;
/**
* Is this contribution associated with an online.
* financial transaction
*
* @var bool
*/
public $_online = FALSE;
/**
* Stores all product options.
*
* @var array
*/
public $_options;
/**
* Storage of parameters from form
*
* @var array
*/
public $_params;
/**
* The contribution values if an existing contribution
*
* @var array
*
* @deprecated - try to use getContributionValue() instead as it is strictly a
* cached lookup on the contribution values, rather than a grab-bag.
*/
public $_values;
/**
* The pledge values if this contribution is associated with pledge
* @var array
*/
public $_pledgeValues;
public $_context;
/**
* Parameter with confusing name.
* @var string
* @todo what is it?
*/
public $_compContext;
public $_compId;
/**
* Possible From email addresses
* @var array
*/
public $_fromEmails;
/**
* ID of from email.
*
* @var int
*/
public $fromEmailId;
/**
* Store the line items if price set used.
* @var array
*/
public $_lineItems;
/**
* Line item
* @var array
* @todo explain why we use lineItem & lineItems
*/
public $_lineItem;
/**
* Soft credit info.
*
* @var array
*/
public $_softCreditInfo;
protected $_formType;
/**
* Array of the payment fields to be displayed in the payment fieldset (pane) in billingBlock.tpl
* this contains all the information to describe these fields from quickform. See CRM_Core_Form_Payment getPaymentFormFieldsMetadata
*
* @var array
*/
public $_paymentFields = [];
/**
* Price set ID.
*
* @var int
*/
public $_priceSetId;
/**
* Price set as an array
*
* @var array
*/
public $_priceSet;
/**
* Status message to be shown to the user.
*
* @var array
*/
protected $statusMessage = [];
/**
* Status message title to be shown to the user.
*
* Generally the payment processor message title is 'Complete' and offline is 'Saved'
* although this might not be a good fit with the broad range of processors.
*
* @var string
*/
protected $statusMessageTitle;
/**
* @var int
*
* Max row count for soft credits. The value here is +1 the actual number of
* rows displayed.
*/
public $_softCreditItemCount = 11;
/**
* @var bool
*/
public $submitOnce = TRUE;
/**
* Status of contribution prior to edit.
*
* @var string
*/
protected $previousContributionStatus;
/**
* Payment Instrument ID
*
* @var int
*/
public $payment_instrument_id;
/**
* @var bool
*/
private $_payNow;
private $order;
/**
* Explicitly declare the form context.
*/
public function getDefaultContext() {
return 'create';
}
public function __get($name) {
if ($name === '_contributionID') {
CRM_Core_Error::deprecatedWarning('_contributionID is not a form property - use getContributionID()');
return $this->getContributionID();
}
return NULL;
}
/**
* Set variables up before form is built.
*
* @throws \CRM_Core_Exception
*/
public function preProcess(): void {
// Check permission for action.
if (!CRM_Core_Permission::checkActionPermission('CiviContribute', $this->_action)) {
CRM_Core_Error::statusBounce(ts('You do not have permission to access this page.'));
}
if ($this->_action & CRM_Core_Action::UPDATE && !Contribution::checkAccess()
->setAction('update')
->addValue('id', $this->getContributionID())
->execute()->first()['access']) {
CRM_Core_Error::statusBounce(ts('You do not have permission to access this page.'));
}
parent::preProcess();
$this->_formType = $_GET['formType'] ?? NULL;
// Get price set id.
$this->_priceSetId = $_GET['priceSetId'] ?? NULL;
$this->set('priceSetId', $this->_priceSetId);
$this->assign('priceSetId', $this->_priceSetId);
$this->assign('taxTerm', Civi::settings()->get('tax_term'));
$this->assign('ppID', $this->getPledgePaymentID());
$this->assign('action', $this->_action);
// Get the contribution id if update
$this->assign('isUsePaymentBlock', (bool) $this->getContributionID());
if (!empty($this->_id)) {
$this->assignPaymentInfoBlock();
$this->assign('contribID', $this->_id);
}
$this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
$this->assign('context', $this->_context);
$this->_compId = CRM_Utils_Request::retrieve('compId', 'Positive', $this);
$this->_compContext = CRM_Utils_Request::retrieve('compContext', 'String', $this);
//set the contribution mode.
$this->_mode = CRM_Utils_Request::retrieve('mode', 'Alphanumeric', $this);
$this->assign('contributionMode', $this->_mode);
if ($this->_action & CRM_Core_Action::DELETE) {
return;
}
$this->_fromEmails = CRM_Core_BAO_Email::getFromEmail();
if (CRM_Core_Component::isEnabled('CiviPledge') && !$this->_formType) {
$this->preProcessPledge();
}
if ($this->_id) {
$this->showRecordLinkMesssage($this->_id);
}
$this->_values = [];
// Current contribution id.
if ($this->_id) {
$this->assignPremiumProduct($this->_id);
$this->buildValuesAndAssignOnline_Note_Type($this->_id, $this->_values);
}
if (!isset($this->_values['is_template'])) {
$this->_values['is_template'] = FALSE;
}
$this->assign('is_template', $this->_values['is_template']);
if ($this->isSubmitted()) {
// The custom data fields are added to the form by an ajax form.
// However, if they are not present in the element index they will
// not be available from `$this->getSubmittedValue()` in post process.
// We do not have to set defaults or otherwise render - just add to the element index.
$this->addCustomDataFieldsToForm('Contribution', array_filter([
'id' => $this->getContributionID(),
'financial_type_id' => $this->getFinancialTypeID(),
]));
}
$this->_lineItems = [];
if ($this->_id) {
if (!empty($this->_compId) && $this->_compContext === 'participant') {
$this->assign('compId', $this->_compId);
$lineItem = CRM_Price_BAO_LineItem::getLineItems($this->_compId);
}
else {
$lineItem = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution', 1, TRUE, TRUE);
}
// wtf?
empty($lineItem) ? NULL : $this->_lineItems[] = $lineItem;
}
$this->assign('lineItem', empty($lineItem) ? FALSE : [$lineItem]);
// Set title
if ($this->_mode && $this->_id) {
$this->_payNow = TRUE;
$this->setTitle(ts('Pay with Credit Card'));
}
elseif ($this->_values['is_template']) {
$this->setPageTitle(ts('Template Contribution'));
}
elseif ($this->_mode) {
$this->setPageTitle($this->_ppID ? ts('Credit Card Pledge Payment') : ts('Credit Card Contribution'));
}
else {
$this->setPageTitle($this->_ppID ? ts('Pledge Payment') : ts('Contribution'));
}
$this->assign('payNow', $this->_payNow);
}
private function preProcessPledge(): void {
//get the payment values associated with given pledge payment id OR check for payments due.
$this->_pledgeValues = [];
if ($this->_ppID) {
$payParams = ['id' => $this->_ppID];
CRM_Pledge_BAO_PledgePayment::retrieve($payParams, $this->_pledgeValues['pledgePayment']);
$this->_pledgeID = $this->_pledgeValues['pledgePayment']['pledge_id'] ?? NULL;
$paymentStatusID = $this->_pledgeValues['pledgePayment']['status_id'] ?? NULL;
$this->_id = $this->_pledgeValues['pledgePayment']['contribution_id'] ?? NULL;
//get all status
$allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
if (!($paymentStatusID == array_search('Pending', $allStatus) || $paymentStatusID == array_search('Overdue', $allStatus))) {
CRM_Core_Error::statusBounce(ts("Pledge payment status should be 'Pending' or 'Overdue'."));
}
//get the pledge values associated with given pledge payment.
$ids = [];
$pledgeParams = ['id' => $this->_pledgeID];
CRM_Pledge_BAO_Pledge::getValues($pledgeParams, $this->_pledgeValues, $ids);
}
else {
// Not making a pledge payment, so if adding a new contribution we should check if pledge payment(s) are due for this contact so we can alert the user. CRM-5206
if (isset($this->_contactID)) {
$contactPledges = CRM_Pledge_BAO_Pledge::getContactPledges($this->_contactID);
if (!empty($contactPledges)) {
$payments = $paymentsDue = NULL;
$multipleDue = FALSE;
foreach ($contactPledges as $key => $pledgeId) {
$payments = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId);
if ($payments) {
if ($paymentsDue) {
$multipleDue = TRUE;
break;
}
else {
$paymentsDue = $payments;
}
}
}
if ($multipleDue) {
// Show link to pledge tab since more than one pledge has a payment due
$pledgeTab = CRM_Utils_System::url('civicrm/contact/view',
"reset=1&force=1&cid={$this->_contactID}&selectedChild=pledge"
);
CRM_Core_Session::setStatus(ts('This contact has pending or overdue pledge payments. <a href="%1">Click here to view their Pledges tab</a> and verify whether this contribution should be applied as a pledge payment.', [1 => $pledgeTab]), ts('Notice'), 'alert');
}
elseif ($paymentsDue) {
// Show user link to oldest Pending or Overdue pledge payment
$ppAmountDue = CRM_Utils_Money::format($payments['amount'], $payments['currency']);
$ppSchedDate = CRM_Utils_Date::customFormat(CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $payments['id'], 'scheduled_date'));
if ($this->_mode) {
$ppUrl = CRM_Utils_System::url('civicrm/contact/view/contribution',
"reset=1&action=add&cid={$this->_contactID}&ppid={$payments['id']}&context=pledge&mode=live"
);
}
else {
$ppUrl = CRM_Utils_System::url('civicrm/contact/view/contribution',
"reset=1&action=add&cid={$this->_contactID}&ppid={$payments['id']}&context=pledge"
);
}
CRM_Core_Session::setStatus(ts('This contact has a pending or overdue pledge payment of %2 which is scheduled for %3. <a href="%1">Click here to enter a pledge payment</a>.', [
1 => $ppUrl,
2 => $ppAmountDue,
3 => $ppSchedDate,
]), ts('Notice'), 'alert');
}
}
}
}
}
/**
* Set default values.
*
* @return array
*
* @throws \CRM_Core_Exception
*/
public function setDefaultValues() {
$defaults = $this->_values;
// Set defaults for pledge payment.
if ($this->_ppID) {
$defaults['total_amount'] = $this->_pledgeValues['pledgePayment']['scheduled_amount'] ?? NULL;
$defaults['financial_type_id'] = $this->_pledgeValues['financial_type_id'] ?? NULL;
$defaults['currency'] = $this->_pledgeValues['currency'] ?? NULL;
$defaults['option_type'] = 1;
}
if ($this->_action & CRM_Core_Action::DELETE) {
return $defaults;
}
$defaults['frequency_interval'] = 1;
$defaults['frequency_unit'] = 'month';
// Set soft credit defaults.
CRM_Contribute_Form_SoftCredit::setDefaultValues($defaults, $this);
if ($this->_mode) {
// @todo - remove this function as the parent does it too.
$config = CRM_Core_Config::singleton();
// Set default country from config if no country set.
if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
$defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry;
}
if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
$defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince;
}
$billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID);
$defaults = array_merge($defaults, $billingDefaults);
}
if ($this->_id) {
$this->_contactID = $defaults['contact_id'];
}
elseif ($this->_contactID) {
$defaults['contact_id'] = $this->_contactID;
}
// Set $newCredit variable in template to control whether link to credit card mode is included.
$this->assign('newCredit', CRM_Core_Config::isEnabledBackOfficeCreditCardPayments());
// Fix the display of the monetary value, CRM-4038.
if (isset($defaults['total_amount'])) {
$total_value = $defaults['total_amount'];
$defaults['total_amount'] = CRM_Utils_Money::formatLocaleNumericRoundedForDefaultCurrency($total_value);
if (!empty($defaults['tax_amount'])) {
$componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
if (empty($componentDetails['membership']) && empty($componentDetails['participant'])) {
$defaults['total_amount'] = CRM_Utils_Money::formatLocaleNumericRoundedForDefaultCurrency($total_value - $defaults['tax_amount']);
}
}
}
$amountFields = ['non_deductible_amount', 'fee_amount'];
foreach ($amountFields as $amt) {
if (isset($defaults[$amt])) {
$defaults[$amt] = CRM_Utils_Money::formatLocaleNumericRoundedForDefaultCurrency($defaults[$amt]);
}
}
if (empty($defaults['payment_instrument_id'])) {
$defaults['payment_instrument_id'] = $this->getDefaultPaymentInstrumentId();
}
$this->assign('is_test', !empty($defaults['is_test']));
$this->assign('email', $this->getContactValue('email_primary.email'));
$this->assign('is_pay_later', !empty($defaults['is_pay_later']));
$this->assign('contribution_status_id', $defaults['contribution_status_id'] ?? NULL);
$this->assign('showOption', TRUE);
// For Premium section.
if ($this->_premiumID) {
$this->assign('showOption', FALSE);
$options = $this->_options[$this->_productDAO->product_id] ?? '';
if (!$options) {
$this->assign('showOption', TRUE);
}
if ($this->_productDAO->product_option) {
$defaults['product_name'] = [$this->_productDAO->product_id, $this->_productDAO->product_option];
}
else {
$defaults['product_name'] = [$this->_productDAO->product_id];
}
if ($this->_productDAO->fulfilled_date) {
$defaults['fulfilled_date'] = $this->_productDAO->fulfilled_date;
}
}
if (!empty($defaults['contribution_status_id']) && in_array(
CRM_Contribute_PseudoConstant::contributionStatus($defaults['contribution_status_id'], 'name'),
// Historically not 'Cancelled' hence not using CRM_Contribute_BAO_Contribution::isContributionStatusNegative.
['Refunded', 'Chargeback']
)) {
$defaults['refund_trxn_id'] = CRM_Core_BAO_FinancialTrxn::getRefundTransactionTrxnID($this->_id);
}
else {
$defaults['refund_trxn_id'] = $defaults['trxn_id'] ?? NULL;
}
if (!empty($defaults['contribution_status_id'])
&& ('Template' === CRM_Contribute_PseudoConstant::contributionStatus($defaults['contribution_status_id'], 'name'))
) {
if ($this->elementExists('contribution_status_id')) {
$this->getElement('contribution_status_id')->freeze();
}
}
if (!$this->_id && empty($defaults['receive_date'])) {
$defaults['receive_date'] = date('Y-m-d H:i:s');
}
$currency = $defaults['currency'] ?? NULL;
$this->assign('currency', $currency);
// Hack to get currency info to the js layer. CRM-11440.
CRM_Utils_Money::format(1);
$this->assign('currencySymbol', CRM_Utils_Money::$_currencySymbols[$currency] ?? NULL);
$this->assign('totalAmount', $defaults['total_amount'] ?? NULL);
// Inherit campaign from pledge.
if ($this->_ppID && !empty($this->_pledgeValues['campaign_id'])) {
$defaults['campaign_id'] = $this->_pledgeValues['campaign_id'];
}
$billing_address = '';
if (!empty($defaults['address_id'])) {
$addressDetails = CRM_Core_BAO_Address::getValues(['id' => $defaults['address_id']], FALSE, 'id');
$addressDetails = array_values($addressDetails);
$billing_address = $addressDetails[0]['display'];
}
$this->assign('billing_address', $billing_address);
$this->_defaults = $defaults;
return $defaults;
}
/**
* Build the form object.
*
* @throws \CRM_Core_Exception
*/
public function buildQuickForm() {
if ($this->_id) {
$this->add('hidden', 'id', $this->_id);
}
if ($this->_action & CRM_Core_Action::DELETE) {
$this->addButtons([
[
'type' => 'next',
'name' => ts('Delete'),
'spacing' => ' ',
'isDefault' => TRUE,
],
[
'type' => 'cancel',
'name' => ts('Cancel'),
],
]);
return;
}
$allPanes = [];
//tax rate from financialType
$this->assign('taxRates', json_encode(CRM_Core_PseudoConstant::getTaxRates()));
$this->assign('currencies', json_encode(CRM_Core_OptionGroup::values('currencies_enabled')));
// build price set form.
$buildPriceSet = FALSE;
$this->assign('invoicing', \Civi::settings()->get('invoicing'));
// This is a probably-deprecated approach to partial payments - assign here
// & if true it will be overwritten.
$this->assign('payNow', FALSE);
$buildRecurBlock = FALSE;
if (empty($this->_lineItems) &&
($this->_priceSetId || !empty($_POST['price_set_id']))
) {
$buildPriceSet = TRUE;
$this->buildPriceSet();
if (!$this->isSubmitted()) {
// This is being called in overload mode to render the price set.
return;
}
}
// use to build form during form rule.
$this->assign('buildPriceSet', $buildPriceSet);
$defaults = $this->_values;
$additionalDetailFields = [
'note',
'thankyou_date',
'invoice_id',
'non_deductible_amount',
'fee_amount',
];
foreach ($additionalDetailFields as $key) {
if (!empty($defaults[$key])) {
$defaults['hidden_AdditionalDetail'] = 1;
break;
}
}
if ($this->_productDAO) {
if ($this->_productDAO->product_id) {
$defaults['hidden_Premium'] = 1;
}
}
if ($this->_noteID &&
!CRM_Utils_System::isNull($this->_values['note'])
) {
$defaults['hidden_AdditionalDetail'] = 1;
}
if (empty($this->_payNow)) {
$allPanes = [ts('Additional Details') => $this->generatePane('AdditionalDetail', $defaults)];
//Add Premium pane only if Premium is exists.
$dao = new CRM_Contribute_DAO_Product();
$dao->is_active = 1;
if ($dao->find(TRUE)) {
$allPanes[ts('Premium Information')] = $this->generatePane('Premium', $defaults);
}
}
$this->assign('allPanes', $allPanes ?: []);
$this->payment_instrument_id = $defaults['payment_instrument_id'] ?? $this->getDefaultPaymentInstrumentId();
CRM_Core_Payment_Form::buildPaymentForm($this, $this->_paymentProcessor, FALSE, TRUE, $this->payment_instrument_id);
if (!empty($this->_recurPaymentProcessors)) {
$buildRecurBlock = TRUE;
if ($this->_ppID) {
// ppID denotes a pledge payment.
foreach ($this->_paymentProcessors as $processor) {
if (!empty($processor['is_recur']) && !empty($processor['object']) && $processor['object']->supports('recurContributionsForPledges')) {
$buildRecurBlock = TRUE;
break;
}
$buildRecurBlock = FALSE;
}
}
if ($buildRecurBlock) {
$this->buildRecur();
$this->setDefaults(['is_recur' => 0]);
}
}
$this->assign('buildRecurBlock', $buildRecurBlock);
$this->addPaymentProcessorSelect(FALSE, $buildRecurBlock);
$qfKey = $this->controller->_key;
$this->assign('qfKey', $qfKey);
$this->addFormRule(['CRM_Contribute_Form_Contribution', 'formRule'], $this);
$this->assign('formType', $this->_formType);
if ($this->_formType) {
return;
}
$this->applyFilter('__ALL__', 'trim');
//need to assign custom data subtype to the template for initial custom data load
$this->assign('customDataSubType', $this->getFinancialTypeID());
$this->assign('entityID', $this->getContributionID());
$this->assign('email', $this->getContactValue('email_primary.email'));
$contactField = $this->addEntityRef('contact_id', ts('Contributor'), ['create' => TRUE, 'api' => ['extra' => ['email']]], TRUE);
if ($this->_context !== 'standalone') {
$contactField->freeze();
}
$attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution');
// Check permissions for financial type first
CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, $this->_action);
if (empty($financialTypes)) {
CRM_Core_Error::statusBounce(ts('You do not have all the permissions needed for this page.'));
}
$financialType = $this->add('select', 'financial_type_id',
ts('Financial Type'),
['' => ts('- select -')] + $financialTypes,
TRUE,
['onChange' => "CRM.buildCustomData( 'Contribution', this.value );", 'class' => 'crm-select2']
);
$paymentInstrument = FALSE;
if (!$this->_mode) {
// payment_instrument isn't required in edit and will not be present when payment block is enabled.
$required = !$this->_id;
$checkPaymentID = array_search('Check', CRM_Contribute_BAO_Contribution::buildOptions('payment_instrument_id', 'validate'));
$paymentInstrument = $this->add('select', 'payment_instrument_id',
ts('Payment Method'),
['' => ts('- select -')] + CRM_Contribute_BAO_Contribution::buildOptions('payment_instrument_id', 'create', ['filter' => 0]),
$required,
['onChange' => "return showHideByValue('payment_instrument_id','{$checkPaymentID}','checkNumber','table-row','select',false);", 'class' => 'crm-select2']
);
}
$trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), ['class' => 'twelve'] + $attributes['trxn_id']);
//add receipt for offline contribution
$this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
$this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails, FALSE, ['class' => 'crm-select2 huge']);
$componentDetails = [];
if ($this->_id) {
$componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
}
$status = $this->getAvailableContributionStatuses();
// define the status IDs that show the cancellation info, see CRM-17589
$cancelInfo_show_ids = [];
foreach (array_keys($status) as $status_id) {
if (CRM_Contribute_BAO_Contribution::isContributionStatusNegative($status_id)) {
$cancelInfo_show_ids[] = "'$status_id'";
}
}
$this->assign('cancelInfo_show_ids', implode(',', $cancelInfo_show_ids));
$statusElement = $this->add('select', 'contribution_status_id',
ts('Contribution Status'),
$status,
FALSE,
['class' => 'crm-select2']
);
$currencyFreeze = FALSE;
if (!empty($this->_payNow) && ($this->_action & CRM_Core_Action::UPDATE)) {
$statusElement->freeze();
$currencyFreeze = TRUE;
$attributes['total_amount']['readonly'] = TRUE;
}
// CRM-16189, add Revenue Recognition Date
if (Civi::settings()->get('deferred_revenue_enabled')) {
$revenueDate = $this->add('datepicker', 'revenue_recognition_date', ts('Revenue Recognition Date'), [], FALSE, ['time' => FALSE]);
if ($this->_id && !CRM_Contribute_BAO_Contribution::allowUpdateRevenueRecognitionDate($this->_id)) {
$revenueDate->freeze();
}
}
// If contribution is a template receive date is not required and if we are in a live credit card mode
$receiveDateRequired = !$this->_values['is_template'] && !$this->_mode;
// add various dates
$this->addField('receive_date', ['entity' => 'contribution'], $receiveDateRequired, FALSE);
$this->addField('receipt_date', ['entity' => 'contribution'], FALSE, FALSE);
$this->addField('cancel_date', ['entity' => 'contribution', 'label' => ts('Cancelled / Refunded Date')], FALSE, FALSE);
if ($this->_online) {
$this->assign('hideCalender', TRUE);
}
$this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
$totalAmount = NULL;
if (empty($this->_lineItems)) {
$buildPriceSet = FALSE;
$priceSets = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviContribute');
if (!empty($priceSets) && !$this->_ppID) {
$buildPriceSet = TRUE;
}
// don't allow price set for contribution if it is related to participant, or if it is a pledge payment
// and if we already have line items for that participant. CRM-5095
if ($buildPriceSet && $this->_id) {
$pledgePaymentId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
$this->_id,
'id',
'contribution_id'
);
if ($pledgePaymentId) {
$buildPriceSet = FALSE;
}
$participantID = $componentDetails['participant'] ?? NULL;
if ($participantID) {
$participantLI = CRM_Price_BAO_LineItem::getLineItems($participantID);
if (!CRM_Utils_System::isNull($participantLI)) {
$buildPriceSet = FALSE;
}
}
}
$hasPriceSets = FALSE;
if ($buildPriceSet) {
$hasPriceSets = TRUE;
// CRM-16451: set financial type of 'Price Set' in back office contribution
// instead of selecting manually
$financialTypeIds = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviContribute', 'financial_type_id');
$element = $this->add('select', 'price_set_id', ts('Choose price set'),
['' => ts('Choose price set')] + $priceSets,
NULL,
['onchange' => 'buildAmount( this.value, ' . json_encode($financialTypeIds) . ');', 'class' => 'crm-select2']
);
if ($this->_online && !($this->_action & CRM_Core_Action::UPDATE)) {
$element->freeze();
}
}
$this->assign('hasPriceSets', $hasPriceSets);
if (!($this->_action & CRM_Core_Action::UPDATE)) {
if ($this->_online || $this->_ppID) {
$attributes['total_amount'] = array_merge($attributes['total_amount'], [
'READONLY' => TRUE,
'style' => "background-color:#EBECE4",
]);
$optionTypes = [
'1' => ts('Adjust Pledge Payment Schedule?'),
'2' => ts('Adjust Total Pledge Amount?'),
];
$this->addRadio('option_type',
NULL,
$optionTypes,
[], '<br/>'
);
$currencyFreeze = TRUE;
}
}
$totalAmount = $this->addMoney('total_amount',
ts('Total Amount'),
!$hasPriceSets,
$attributes['total_amount'],
TRUE, 'currency', NULL, $currencyFreeze
);
}
$this->add('text', 'source', ts('Contribution Source'), $attributes['source'] ?? NULL);
// CRM-7362 --add campaigns.
CRM_Campaign_BAO_Campaign::addCampaign($this, $this->_values['campaign_id'] ?? NULL);
if (empty($this->_payNow)) {
CRM_Contribute_Form_SoftCredit::buildQuickForm($this);
}
$js = NULL;
if (!$this->_mode) {
$js = ['onclick' => 'return verify( );'];
}
$mailingInfo = Civi::settings()->get('mailing_backend');
$this->assign('outBound_option', $mailingInfo['outBound_option']);
$buttons = [
[
'type' => 'upload',
'name' => ts('Save'),
'js' => $js,
'isDefault' => TRUE,
],
];
if (!$this->_id) {
$buttons[] = [
'type' => 'upload',
'name' => ts('Save and New'),
'js' => $js,
'subName' => 'new',
];
}
$buttons[] = [
'type' => 'cancel',
'name' => ts('Cancel'),
];
$this->addButtons($buttons);
// if contribution is related to membership or participant freeze Financial Type, Amount
if ($this->_id) {
$componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
$isCancelledStatus = ($this->_values['contribution_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Cancelled'));
if (!empty($componentDetails['membership']) ||
!empty($componentDetails['participant']) ||
// if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
// Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
$isCancelledStatus
) {
if ($totalAmount) {
$totalAmount->freeze();
$this->getElement('currency')->freeze();
}
if ($isCancelledStatus) {
$paymentInstrument->freeze();
$trxnId->freeze();
}
$financialType->freeze();
$freezeFinancialType = TRUE;
}
}
$this->assign('freezeFinancialType', $freezeFinancialType ?? FALSE);
if ($this->_action & CRM_Core_Action::VIEW) {
$this->freeze();
}
}
protected function isUpdate(): bool {
return $this->getAction() === CRM_Core_Action::UPDATE && $this->getContributionID();
}
/**
* @throws \CRM_Core_Exception
*/
protected function getOrder(): CRM_Financial_BAO_Order {
if (!$this->order) {
$this->initializeOrder();
}
return $this->order;
}
/**
* @throws \CRM_Core_Exception
*/
protected function initializeOrder(): void {
$this->order = new CRM_Financial_BAO_Order();
$this->order->setPriceSetID($this->getPriceSetID());
$this->order->setForm($this);
$this->order->setPriceSelectionFromUnfilteredInput($this->getSubmittedValues());
}
/**
* Get the form context.
*
* This is important for passing to the buildAmount hook as CiviDiscount checks it.
*
* @return string
*/
public function getFormContext(): string {
return 'contribution';
}
/**
* Build the price set form.
*/
private function buildPriceSet(): void {
$form = $this;
$this->_priceSet = $this->getOrder()->getPriceSetMetadata();
foreach ($this->getPriceFieldMetaData() as $id => $field) {
$options = $field['options'] ?? NULL;
if (!is_array($options)) {
continue;
}
if (!empty($options)) {
CRM_Price_BAO_PriceField::addQuickFormElement($form,
'price_' . $field['id'],
$field['id'],
FALSE,
$field['is_required'] ?? FALSE,
NULL,
$options
);
}
}
$form->assign('priceSet', $form->_priceSet);
}
/**