-
-
Notifications
You must be signed in to change notification settings - Fork 824
/
Copy pathMembership.php
1955 lines (1731 loc) · 71.2 KB
/
Membership.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\ContributionRecur;
/**
*
* @package CRM
* @copyright CiviCRM LLC https://civicrm.org/licensing
*/
/**
* This class generates form components for offline membership form.
*/
class CRM_Member_Form_Membership extends CRM_Member_Form {
/**
* IDs of relevant entities.
*
* @var array
*/
protected $ids = [];
protected $_memType = NULL;
public $_mode;
public $_contributeMode = 'direct';
protected $_recurMembershipTypes;
protected $_memTypeSelected;
/**
* Display name of the member.
*
* @var string
*/
protected $_memberDisplayName = NULL;
/**
* email of the person paying for the membership (used for receipts)
* @var string
*/
protected $_memberEmail = NULL;
/**
* Contact ID of the member.
*
* @var int
*/
public $_contactID = NULL;
/**
* Display name of the person paying for the membership (used for receipts)
*
* @var string
*/
protected $_contributorDisplayName = NULL;
/**
* Email of the person paying for the membership (used for receipts).
*
* @var string
*/
protected $_contributorEmail;
/**
* email of the person paying for the membership (used for receipts)
*
* @var int
*/
protected $_contributorContactID = NULL;
/**
* ID of the person the receipt is to go to.
*
* @var int
*/
protected $_receiptContactId = NULL;
/**
* Keep a class variable for ALL membership IDs so
* postProcess hook function can do something with it
*
* @var array
*/
protected $_membershipIDs = [];
/**
* Membership created or edited on this form.
*
* If a price set creates multiple this will be the last one created.
*
* This 'last' bias reflects historical code - but it's mostly used in the receipt
* and there is all sorts of weird and wonderful handling that potentially compensates.
*
* @var array
*/
protected $membership = [];
/**
* Set entity fields to be assigned to the form.
*/
protected function setEntityFields() {
$this->entityFields = [
'join_date' => [
'name' => 'join_date',
'description' => ts('Member Since'),
],
'start_date' => [
'name' => 'start_date',
'description' => ts('Start Date'),
],
'end_date' => [
'name' => 'end_date',
'description' => ts('End Date'),
],
];
}
/**
* Set the delete message.
*
* We do this from the constructor in order to do a translation.
*/
public function setDeleteMessage() {
$this->deleteMessage = '<span class="font-red bold">'
. ts('WARNING: Deleting this membership will also delete any related payment (contribution) records.')
. ' '
. ts('This action cannot be undone.')
. '</span><p>'
. ts('Consider modifying the membership status instead if you want to maintain an audit trail and avoid losing payment data. You can set the status to Cancelled by editing the membership and clicking the Status Override checkbox.')
. '</p><p>'
. ts("Click 'Delete' if you want to continue.") . '</p>';
}
/**
* Overriding this entity trait function as not yet tested.
*
* We continue to rely on legacy handling.
*/
public function addCustomDataToForm() {}
/**
* Overriding this entity trait function as not yet tested.
*
* We continue to rely on legacy handling.
*/
public function addFormButtons() {}
/**
* Get selected membership type from the form values.
*
* @param array $priceSet
* @param array $params
*
* @return array
* @throws \CRM_Core_Exception
*/
public static function getSelectedMemberships($priceSet, $params) {
$memTypeSelected = [];
$priceFieldIDS = self::getPriceFieldIDs($params, $priceSet);
if (isset($params['membership_type_id']) && !empty($params['membership_type_id'][1])) {
$memTypeSelected = [$params['membership_type_id'][1] => $params['membership_type_id'][1]];
}
else {
foreach ($priceFieldIDS as $priceFieldId) {
if ($id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) {
$memTypeSelected[$id] = $id;
}
}
}
return $memTypeSelected;
}
/**
* Extract price set fields and values from $params.
*
* @param array $params
* @param array $priceSet
*
* @return array
*/
public static function getPriceFieldIDs($params, $priceSet) {
$priceFieldIDS = [];
if (isset($priceSet['fields']) && is_array($priceSet['fields'])) {
foreach ($priceSet['fields'] as $fieldId => $field) {
if (!empty($params['price_' . $fieldId])) {
if (is_array($params['price_' . $fieldId])) {
foreach ($params['price_' . $fieldId] as $priceFldVal => $isSet) {
if ($isSet) {
$priceFieldIDS[] = $priceFldVal;
}
}
}
elseif (!$field['is_enter_qty']) {
$priceFieldIDS[] = $params['price_' . $fieldId];
}
}
}
}
return $priceFieldIDS;
}
/**
* Form preProcess function.
*
* @throws \CRM_Core_Exception
*/
public function preProcess() {
// This string makes up part of the class names, differentiating them (not sure why) from the membership fields.
$this->assign('formClass', 'membership');
parent::preProcess();
// get price set id.
$this->_priceSetId = $_GET['priceSetId'] ?? NULL;
$this->set('priceSetId', $this->_priceSetId);
$this->assign('priceSetId', $this->_priceSetId);
if ($this->_action & CRM_Core_Action::DELETE) {
$contributionID = CRM_Member_BAO_Membership::getMembershipContributionId($this->_id);
// check delete permission for contribution
if ($this->_id && $contributionID && !CRM_Core_Permission::checkActionPermission('CiviContribute', $this->_action)) {
CRM_Core_Error::statusBounce(ts("This Membership is linked to a contribution. You must have 'delete in CiviContribute' permission in order to delete this record."));
}
}
$mems_by_org = [];
if ($this->_action & CRM_Core_Action::ADD) {
if ($this->_contactID) {
//check whether contact has a current membership so we can alert user that they may want to do a renewal instead
$contactMemberships = [];
$memParams = ['contact_id' => $this->_contactID];
CRM_Member_BAO_Membership::getValues($memParams, $contactMemberships, TRUE);
$cMemTypes = [];
foreach ($contactMemberships as $mem) {
$cMemTypes[] = $mem['membership_type_id'];
}
if (count($cMemTypes) > 0) {
foreach ($cMemTypes as $memTypeID) {
$memberorgs[$memTypeID] = CRM_Member_BAO_MembershipType::getMembershipType($memTypeID)['member_of_contact_id'];
}
foreach ($contactMemberships as $mem) {
$mem['member_of_contact_id'] = $memberorgs[$mem['membership_type_id']] ?? NULL;
if (!empty($mem['membership_end_date'])) {
$mem['membership_end_date'] = CRM_Utils_Date::customFormat($mem['membership_end_date']);
}
$mem['membership_type'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
$mem['membership_type_id'],
'name', 'id'
);
$mem['membership_status'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus',
$mem['status_id'],
'label', 'id'
);
$mem['renewUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership',
"reset=1&action=renew&cid={$this->_contactID}&id={$mem['id']}&context=membership&selectedChild=member"
. ($this->_mode ? '&mode=live' : '')
);
$mem['membershipTab'] = CRM_Utils_System::url('civicrm/contact/view',
"reset=1&force=1&cid={$this->_contactID}&selectedChild=member"
);
$mems_by_org[$mem['member_of_contact_id']] = $mem;
}
}
}
else {
// In standalone mode we don't have a contact id yet so lookup will be done client-side with this script:
$resources = CRM_Core_Resources::singleton();
$resources->addScriptFile('civicrm', 'templates/CRM/Member/Form/MembershipStandalone.js');
$passthru = [
'typeorgs' => CRM_Member_BAO_MembershipType::getMembershipTypeOrganization(),
'memtypes' => CRM_Core_PseudoConstant::get('CRM_Member_BAO_Membership', 'membership_type_id'),
'statuses' => CRM_Core_PseudoConstant::get('CRM_Member_BAO_Membership', 'status_id'),
];
$resources->addSetting(['existingMems' => $passthru]);
}
}
$this->assign('existingContactMemberships', $mems_by_org);
if (!$this->_memType) {
$params = CRM_Utils_Request::exportValues();
if (!empty($params['membership_type_id'][1])) {
$this->_memType = $params['membership_type_id'][1];
}
}
// Add custom data to form
CRM_Custom_Form_CustomData::addToForm($this, $this->_memType);
$this->setPageTitle(ts('Membership'));
}
/**
* Set default values for the form.
*/
public function setDefaultValues() {
if ($this->_priceSetId) {
return CRM_Price_BAO_PriceSet::setDefaultPriceSet($this, $defaults);
}
$defaults = parent::setDefaultValues();
//setting default join date and receive date
if ($this->_action == CRM_Core_Action::ADD) {
$defaults['receive_date'] = CRM_Utils_Time::date('Y-m-d H:i:s');
}
$defaults['num_terms'] = 1;
if (!empty($defaults['id'])) {
$contributionId = CRM_Core_DAO::singleValueQuery("
SELECT contribution_id
FROM civicrm_membership_payment
WHERE membership_id = $this->_id
ORDER BY contribution_id
DESC limit 1");
if ($contributionId) {
$defaults['record_contribution'] = $contributionId;
}
}
else {
if ($this->_contactID) {
$defaults['contact_id'] = $this->_contactID;
}
}
//set Soft Credit Type to Gift by default
$scTypes = CRM_Core_OptionGroup::values('soft_credit_type');
$defaults['soft_credit_type_id'] = CRM_Utils_Array::value(ts('Gift'), array_flip($scTypes));
//CRM-13420
if (empty($defaults['payment_instrument_id'])) {
$defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
}
// User must explicitly choose to send a receipt in both add and update mode.
$defaults['send_receipt'] = 0;
if ($this->_action & CRM_Core_Action::UPDATE) {
// in this mode by default uncheck this checkbox
unset($defaults['record_contribution']);
}
$subscriptionCancelled = FALSE;
if (!empty($defaults['id'])) {
$subscriptionCancelled = CRM_Member_BAO_Membership::isSubscriptionCancelled((int) $this->_id);
}
$alreadyAutoRenew = FALSE;
if (!empty($defaults['contribution_recur_id']) && !$subscriptionCancelled) {
$defaults['auto_renew'] = 1;
$alreadyAutoRenew = TRUE;
}
$this->assign('alreadyAutoRenew', $alreadyAutoRenew);
$this->assign('member_is_test', $defaults['member_is_test'] ?? NULL);
$this->assign('membership_status_id', $defaults['status_id'] ?? NULL);
$this->assign('is_pay_later', !empty($defaults['is_pay_later']));
if ($this->_mode) {
$defaults = $this->getBillingDefaults($defaults);
}
//setting default join date if there is no join date
if (empty($defaults['join_date'])) {
$defaults['join_date'] = CRM_Utils_Time::date('Y-m-d');
}
$this->assign('endDate', $defaults['membership_end_date'] ?? NULL);
return $defaults;
}
/**
* Build the form object.
*
* @throws \CRM_Core_Exception
*/
public function buildQuickForm() {
$this->buildQuickEntityForm();
$this->assign('currency_symbol', CRM_Core_BAO_Country::defaultCurrencySymbol());
$isUpdateToExistingRecurringMembership = $this->isUpdateToExistingRecurringMembership();
// build price set form.
$buildPriceSet = FALSE;
if ($this->_priceSetId || !empty($_POST['price_set_id'])) {
if (!empty($_POST['price_set_id'])) {
$buildPriceSet = TRUE;
}
$getOnlyPriceSetElements = TRUE;
if (!$this->_priceSetId) {
$this->_priceSetId = $_POST['price_set_id'];
$getOnlyPriceSetElements = FALSE;
}
$this->set('priceSetId', $this->_priceSetId);
CRM_Price_BAO_PriceSet::buildPriceSet($this);
$optionsMembershipTypes = [];
foreach ($this->_priceSet['fields'] as $pField) {
if (empty($pField['options'])) {
continue;
}
foreach ($pField['options'] as $opId => $opValues) {
$optionsMembershipTypes[$opId] = CRM_Utils_Array::value('membership_type_id', $opValues, 0);
}
}
$this->assign('autoRenewOption', CRM_Price_BAO_PriceSet::checkAutoRenewForPriceSet($this->_priceSetId));
$this->assign('optionsMembershipTypes', $optionsMembershipTypes);
$this->assign('contributionType', CRM_Utils_Array::value('financial_type_id', $this->_priceSet));
// get only price set form elements.
if ($getOnlyPriceSetElements) {
return;
}
}
// use to build form during form rule.
$this->assign('buildPriceSet', $buildPriceSet);
if ($this->_action & CRM_Core_Action::ADD) {
$buildPriceSet = FALSE;
$priceSets = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviMember');
if (!empty($priceSets)) {
$buildPriceSet = TRUE;
}
if ($buildPriceSet) {
$this->add('select', 'price_set_id', ts('Choose price set'),
[
'' => ts('Choose price set'),
] + $priceSets,
NULL, ['onchange' => "buildAmount( this.value );"]
);
}
$this->assign('hasPriceSets', $buildPriceSet);
}
if ($this->_action & CRM_Core_Action::DELETE) {
$this->addButtons([
[
'type' => 'next',
'name' => ts('Delete'),
'spacing' => ' ',
'isDefault' => TRUE,
],
[
'type' => 'cancel',
'name' => ts('Cancel'),
],
]);
return;
}
$contactField = $this->addEntityRef('contact_id', ts('Member'), ['create' => TRUE, 'api' => ['extra' => ['email']]], TRUE);
if ($this->_context !== 'standalone') {
$contactField->freeze();
}
$selOrgMemType[0][0] = $selMemTypeOrg[0] = ts('- select -');
// Throw status bounce when no Membership type or priceset is present
if (empty($this->allMembershipTypeDetails) && empty($priceSets)
) {
CRM_Core_Error::statusBounce(ts("You either do not have all the permissions needed for this page, or the membership types haven't been fully configured."));
}
// retrieve all memberships
$allMembershipInfo = [];
foreach ($this->allMembershipTypeDetails as $key => $values) {
if ($this->_mode && empty($values['minimum_fee'])) {
continue;
}
else {
$memberOfContactId = $values['member_of_contact_id'] ?? NULL;
if (empty($selMemTypeOrg[$memberOfContactId])) {
$selMemTypeOrg[$memberOfContactId] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
$memberOfContactId,
'display_name',
'id'
);
$selOrgMemType[$memberOfContactId][0] = ts('- select -');
}
if (empty($selOrgMemType[$memberOfContactId][$key])) {
$selOrgMemType[$memberOfContactId][$key] = $values['name'] ?? NULL;
}
}
$totalAmount = $values['minimum_fee'] ?? NULL;
// build membership info array, which is used when membership type is selected to:
// - set the payment information block
// - set the max related block
$allMembershipInfo[$key] = [
'financial_type_id' => $values['financial_type_id'] ?? NULL,
'total_amount' => CRM_Utils_Money::formatLocaleNumericRoundedForDefaultCurrency($totalAmount),
'total_amount_numeric' => $totalAmount,
'auto_renew' => $values['auto_renew'] ?? NULL,
'tax_rate' => $values['tax_rate'],
'has_related' => isset($values['relationship_type_id']),
'max_related' => $values['max_related'] ?? NULL,
];
}
$this->assign('allMembershipInfo', json_encode($allMembershipInfo));
// show organization by default, if only one organization in
// the list
if (count($selMemTypeOrg) == 2) {
unset($selMemTypeOrg[0], $selOrgMemType[0][0]);
}
//sort membership organization and type, CRM-6099
natcasesort($selMemTypeOrg);
foreach ($selOrgMemType as $index => $orgMembershipType) {
natcasesort($orgMembershipType);
$selOrgMemType[$index] = $orgMembershipType;
}
$memTypeJs = [
'onChange' => "buildMaxRelated(this.value,true); CRM.buildCustomData('Membership', this.value);",
];
if (!empty($this->_recurPaymentProcessors)) {
$memTypeJs['onChange'] = "" . $memTypeJs['onChange'] . " buildAutoRenew(this.value, null, '{$this->_mode}');";
}
$this->add('text', 'max_related', ts('Max related'),
CRM_Core_DAO::getAttribute('CRM_Member_DAO_Membership', 'max_related')
);
$sel = &$this->addElement('hierselect',
'membership_type_id',
ts('Membership Organization and Type'),
$memTypeJs
);
$sel->setOptions([$selMemTypeOrg, $selOrgMemType]);
if ($this->_action & CRM_Core_Action::ADD) {
$this->add('number', 'num_terms', ts('Number of Terms'), ['size' => 6]);
}
$this->add('text', 'source', ts('Membership Source'),
CRM_Core_DAO::getAttribute('CRM_Member_DAO_Membership', 'source')
);
//CRM-7362 --add campaigns.
$campaignId = NULL;
if ($this->_id) {
$campaignId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_id, 'campaign_id');
}
CRM_Campaign_BAO_Campaign::addCampaign($this, $campaignId);
if (!$this->_mode) {
$this->add('select', 'status_id', ts('Membership Status'),
['' => ts('- select -')] + CRM_Member_PseudoConstant::membershipStatus(NULL, NULL, 'label')
);
$statusOverride = $this->addElement('select', 'is_override', ts('Status Override?'),
CRM_Member_StatusOverrideTypes::getSelectOptions()
);
$this->add('datepicker', 'status_override_end_date', ts('Status Override End Date'), '', FALSE, ['minDate' => CRM_Utils_Time::date('Y-m-d'), 'time' => FALSE]);
$this->addElement('checkbox', 'record_contribution', ts('Record Membership Payment?'));
$this->add('text', 'total_amount', ts('Amount'));
$this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
$this->add('datepicker', 'receive_date', ts('Contribution Date'), [], FALSE, ['time' => TRUE]);
$this->add('select', 'payment_instrument_id',
ts('Payment Method'),
['' => ts('- select -')] + CRM_Contribute_PseudoConstant::paymentInstrument(),
FALSE, ['onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);"]
);
$this->add('text', 'trxn_id', ts('Transaction ID'));
$this->addRule('trxn_id', ts('Transaction ID already exists in Database.'),
'objectExists', [
'CRM_Contribute_DAO_Contribution',
$this->_id,
'trxn_id',
]
);
$this->add('select', 'contribution_status_id',
ts('Payment Status'), CRM_Contribute_BAO_Contribution_Utils::getPendingAndCompleteStatuses()
);
$this->add('text', 'check_number', ts('Check Number'),
CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution', 'check_number')
);
}
else {
//add field for amount to allow an amount to be entered that differs from minimum
$this->add('text', 'total_amount', ts('Amount'));
}
$this->add('select', 'financial_type_id',
ts('Financial Type'),
['' => ts('- select -')] + CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, $this->_action)
);
$this->addElement('checkbox', 'is_different_contribution_contact', ts('Record Payment from a Different Contact?'));
$this->addSelect('soft_credit_type_id', ['entity' => 'contribution_soft']);
$this->addEntityRef('soft_credit_contact_id', ts('Payment From'), ['create' => TRUE]);
$this->addElement('checkbox',
'send_receipt',
ts('Send Confirmation and Receipt?'), NULL,
['onclick' => "showEmailOptions()"]
);
$this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
$this->add('textarea', 'receipt_text', ts('Receipt Message'));
// Retrieve the name and email of the contact - this will be the TO for receipt email
if ($this->_contactID) {
[$this->_memberDisplayName, $this->_memberEmail] = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
}
$this->assign('emailExists', $this->_memberEmail);
$this->assign('displayName', $this->_memberDisplayName);
if ($isUpdateToExistingRecurringMembership && CRM_Member_BAO_Membership::isCancelSubscriptionSupported($this->_id)) {
$this->assign('cancelAutoRenew',
CRM_Utils_System::url('civicrm/contribute/unsubscribe', "reset=1&mid={$this->_id}")
);
}
$this->assign('isRecur', $isUpdateToExistingRecurringMembership);
$this->addFormRule(['CRM_Member_Form_Membership', 'formRule'], $this);
$mailingInfo = Civi::settings()->get('mailing_backend');
$this->assign('isEmailEnabledForSite', ($mailingInfo['outBound_option'] != 2));
parent::buildQuickForm();
}
/**
* Validation.
*
* @param array $params
* (ref.) an assoc array of name/value pairs.
*
* @param array $files
* @param CRM_Member_Form_Membership $self
*
* @return bool|array
* mixed true or array of errors
*
* @throws \CRM_Core_Exception
* @throws CRM_Core_Exception
*/
public static function formRule($params, $files, $self) {
$errors = [];
$priceSetId = $self->getPriceSetID($params);
$priceSetDetails = $self->getPriceSetDetails($params);
$selectedMemberships = self::getSelectedMemberships($priceSetDetails[$priceSetId], $params);
if (!empty($params['price_set_id'])) {
CRM_Price_BAO_PriceField::priceSetValidation($priceSetId, $params, $errors);
$priceFieldIDS = self::getPriceFieldIDs($params, $priceSetDetails[$priceSetId]);
if (!empty($priceFieldIDS)) {
$ids = implode(',', $priceFieldIDS);
$count = CRM_Price_BAO_PriceSet::getMembershipCount($ids);
foreach ($count as $occurrence) {
if ($occurrence > 1) {
$errors['_qf_default'] = ts('Select at most one option associated with the same membership type.');
}
}
}
// Return error if empty $self->_memTypeSelected
if (empty($errors) && empty($selectedMemberships)) {
$errors['_qf_default'] = ts('Select at least one membership option.');
}
if (!$self->_mode && empty($params['record_contribution'])) {
$errors['record_contribution'] = ts('Record Membership Payment is required when you use a price set.');
}
}
else {
if (empty($params['membership_type_id'][1])) {
$errors['membership_type_id'] = ts('Please select a membership type.');
}
$numterms = $params['num_terms'] ?? NULL;
if ($numterms && intval($numterms) != $numterms) {
$errors['num_terms'] = ts('Please enter an integer for the number of terms.');
}
if (($self->_mode || isset($params['record_contribution'])) && empty($params['financial_type_id'])) {
$errors['financial_type_id'] = ts('Please enter the financial Type.');
}
}
if (!empty($errors) && (count($selectedMemberships) > 1)) {
$memberOfContacts = CRM_Member_BAO_MembershipType::getMemberOfContactByMemTypes($selectedMemberships);
$duplicateMemberOfContacts = array_count_values($memberOfContacts);
foreach ($duplicateMemberOfContacts as $countDuplicate) {
if ($countDuplicate > 1) {
$errors['_qf_default'] = ts('Please do not select more than one membership associated with the same organization.');
}
}
}
if (!empty($errors)) {
return $errors;
}
if (!empty($params['record_contribution']) && empty($params['payment_instrument_id'])) {
$errors['payment_instrument_id'] = ts('Payment Method is a required field.');
}
if (!empty($params['is_different_contribution_contact'])) {
if (empty($params['soft_credit_type_id'])) {
$errors['soft_credit_type_id'] = ts('Please Select a Soft Credit Type');
}
if (empty($params['soft_credit_contact_id'])) {
$errors['soft_credit_contact_id'] = ts('Please select a contact');
}
}
if (!empty($params['payment_processor_id'])) {
// validate payment instrument (e.g. credit card number)
CRM_Core_Payment_Form::validatePaymentInstrument($params['payment_processor_id'], $params, $errors, NULL);
}
if (!empty($params['join_date'])) {
$joinDate = CRM_Utils_Date::processDate($params['join_date']);
foreach ($selectedMemberships as $memType) {
$startDate = NULL;
if (!empty($params['start_date'])) {
$startDate = CRM_Utils_Date::processDate($params['start_date']);
}
// if end date is set, ensure that start date is also set
// and that end date is later than start date
$endDate = NULL;
if (!empty($params['end_date'])) {
$endDate = CRM_Utils_Date::processDate($params['end_date']);
}
$membershipDetails = CRM_Member_BAO_MembershipType::getMembershipType($memType);
if ($startDate && CRM_Utils_Array::value('period_type', $membershipDetails) === 'rolling') {
if ($startDate < $joinDate) {
$errors['start_date'] = ts('Start date must be the same or later than Member since.');
}
}
if ($endDate) {
if ($membershipDetails['duration_unit'] === 'lifetime') {
// Check if status is NOT cancelled or similar. For lifetime memberships, there is no automated
// process to update status based on end-date. The user must change the status now.
$result = civicrm_api3('MembershipStatus', 'get', [
'sequential' => 1,
'is_current_member' => 0,
]);
$tmp_statuses = $result['values'];
$status_ids = [];
foreach ($tmp_statuses as $cur_stat) {
$status_ids[] = $cur_stat['id'];
}
if (empty($params['status_id']) || in_array($params['status_id'], $status_ids) == FALSE) {
$errors['status_id'] = ts('Please enter a status that does NOT represent a current membership status.');
}
if (!empty($params['is_override']) && !CRM_Member_StatusOverrideTypes::isPermanent($params['is_override'])) {
$errors['is_override'] = ts('Because you set an End Date for a lifetime membership, This must be set to "Override Permanently"');
}
}
else {
if (!$startDate) {
$errors['start_date'] = ts('Start date must be set if end date is set.');
}
if ($endDate < $startDate) {
$errors['end_date'] = ts('End date must be the same or later than start date.');
}
}
}
// Default values for start and end dates if not supplied on the form.
$defaultDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($memType,
$joinDate,
$startDate,
$endDate
);
if (!$startDate) {
$startDate = CRM_Utils_Array::value('start_date',
$defaultDates
);
}
if (!$endDate) {
$endDate = CRM_Utils_Array::value('end_date',
$defaultDates
);
}
//CRM-3724, check for availability of valid membership status.
if ((empty($params['is_override']) || CRM_Member_StatusOverrideTypes::isNo($params['is_override'])) && !isset($errors['_qf_default'])) {
$calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate,
$endDate,
$joinDate,
'now',
TRUE,
$memType,
$params
);
if (empty($calcStatus)) {
$url = CRM_Utils_System::url('civicrm/admin/member/membershipStatus', 'reset=1&action=browse');
$errors['_qf_default'] = ts('There is no valid Membership Status available for selected membership dates.');
$status = ts('Oops, it looks like there is no valid membership status available for the given membership dates. You can <a href="%1">Configure Membership Status Rules</a>.', [1 => $url]);
if (!$self->_mode) {
$status .= ' ' . ts('OR You can sign up by setting Status Override? to something other than "NO".');
}
CRM_Core_Session::setStatus($status, ts('Membership Status Error'), 'error');
}
}
}
}
else {
$errors['join_date'] = ts('Please enter the Member Since.');
}
if (!empty($params['is_override']) && CRM_Member_StatusOverrideTypes::isOverridden($params['is_override']) && empty($params['status_id'])) {
$errors['status_id'] = ts('Please enter the Membership status.');
}
if (!empty($params['is_override']) && CRM_Member_StatusOverrideTypes::isUntilDate($params['is_override'])) {
if (empty($params['status_override_end_date'])) {
$errors['status_override_end_date'] = ts('Please enter the Membership override end date.');
}
}
//total amount condition arise when membership type having no
//minimum fee
if (isset($params['record_contribution'])) {
if (CRM_Utils_System::isNull($params['total_amount'])) {
$errors['total_amount'] = ts('Please enter the contribution.');
}
}
return empty($errors) ? TRUE : $errors;
}
/**
* Process the form submission.
*
* @throws \CRM_Core_Exception
*/
public function postProcess() {
if ($this->_action & CRM_Core_Action::DELETE) {
CRM_Member_BAO_Membership::del($this->_id);
return;
}
// get the submitted form values.
$this->_params = $this->controller->exportValues($this->_name);
$this->prepareStatusOverrideValues();
$this->submit();
$this->setUserContext();
}
/**
* Prepares the values related to status override.
*/
private function prepareStatusOverrideValues() {
$this->setOverrideDateValue();
$this->convertIsOverrideValue();
}
/**
* Sets status override end date to empty value if
* the selected override option is not 'until date'.
*/
private function setOverrideDateValue() {
if (!CRM_Member_StatusOverrideTypes::isUntilDate(CRM_Utils_Array::value('is_override', $this->_params))) {
$this->_params['status_override_end_date'] = '';
}
}
/**
* Convert the value of selected (status override?)
* option to TRUE if it indicate an overridden status
* or FALSE otherwise.
*/
private function convertIsOverrideValue() {
$this->_params['is_override'] = CRM_Member_StatusOverrideTypes::isOverridden($this->_params['is_override'] ?? CRM_Member_StatusOverrideTypes::NO);
}
/**
* Send email receipt.
*
* @param array $formValues
*
* @throws \CRM_Core_Exception
*
* @deprecated
* This function was shared with Batch_Entry which had limited overlap
* & needs rationalising.
*
*/
protected function emailReceipt($formValues) {
$membership = $this->getMembership();
// retrieve 'from email id' for acknowledgement
$receiptFrom = $formValues['from_email_address'] ?? NULL;
// @todo figure out how much of the stuff below is genuinely shared with the batch form & a logical shared place.
if (!empty($formValues['payment_instrument_id'])) {
$paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
$formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
}
$this->assign('module', 'Membership');
if (!empty($formValues['contribution_id'])) {
$this->assign('currency', CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $formValues['contribution_id'], 'currency'));
}
else {
$this->assign('currency', CRM_Core_Config::singleton()->defaultCurrency);
}
if (!empty($formValues['contribution_status_id'])) {
$this->assign('contributionStatusID', $formValues['contribution_status_id']);
$this->assign('contributionStatus', CRM_Contribute_PseudoConstant::contributionStatus($formValues['contribution_status_id'], 'name'));
}
if (!empty($formValues['is_renew'])) {
$this->assign('receiptType', 'membership renewal');
}
else {
$this->assign('receiptType', 'membership signup');
}
$this->assign('receive_date', CRM_Utils_Array::value('receive_date', $formValues));
$this->assign('formValues', $formValues);
$this->assign('mem_start_date', CRM_Utils_Date::formatDateOnlyLong($membership['start_date']));
if (!CRM_Utils_System::isNull($membership['end_date'])) {
$this->assign('mem_end_date', CRM_Utils_Date::formatDateOnlyLong($membership['end_date']));
}
$this->assign('membership_name', CRM_Member_PseudoConstant::membershipType($membership['membership_type_id']));
if ((empty($this->_contributorDisplayName) || empty($this->_contributorEmail))) {
// in this case the form is being called statically from the batch editing screen
// having one class in the form layer call another statically is not greate
// & we should aim to move this function to the BAO layer in future.
// however, we can assume that the contact_id passed in by the batch
// function will be the recipient
[$this->_contributorDisplayName, $this->_contributorEmail]
= CRM_Contact_BAO_Contact_Location::getEmailDetails($formValues['contact_id']);
if (empty($this->_receiptContactId)) {
$this->_receiptContactId = $formValues['contact_id'];
}
}
CRM_Core_BAO_MessageTemplate::sendTemplate(
[
'workflow' => 'membership_offline_receipt',
'from' => $receiptFrom,
'toName' => $this->_contributorDisplayName,
'toEmail' => $this->_contributorEmail,
'PDFFilename' => ts('receipt') . '.pdf',
'isEmailPdf' => Civi::settings()->get('invoice_is_email_pdf'),
'isTest' => (bool) ($this->_action & CRM_Core_Action::PREVIEW),
'modelProps' => [
'receiptText' => $this->getSubmittedValue('receipt_text'),
'contributionID' => $formValues['contribution_id'],
'contactID' => $this->_receiptContactId,
'membershipID' => $this->getMembershipID(),
],
]
);
}
/**
* Submit function.
*
* This is also accessed by unit tests.
*
* @throws \CRM_Core_Exception
*/
public function submit(): void {
$this->storeContactFields($this->_params);
$this->beginPostProcess();