-
-
Notifications
You must be signed in to change notification settings - Fork 825
/
Copy pathMembershipRenewal.php
893 lines (764 loc) · 33.7 KB
/
MembershipRenewal.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
<?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 |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC https://civicrm.org/licensing
*/
/**
* This class generates form components for Membership Renewal
*/
class CRM_Member_Form_MembershipRenewal extends CRM_Member_Form {
/**
* 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 = NULL;
/**
* 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;
/**
* context would be set to standalone if the contact is use is being selected from
* the form rather than in the URL
*
* @var string
*/
public $_context;
/**
* End date of renewed membership.
*
* @var string
*/
protected $endDate = NULL;
/**
* Has an email been sent.
*
* @var string
*/
protected $isMailSent = FALSE;
/**
* The name of the renewed membership type.
*
* @var string
*/
protected $membershipTypeName = '';
/**
* Set entity fields to be assigned to the form.
*/
protected function setEntityFields() {
}
/**
* Set the delete message.
*
* We do this from the constructor in order to do a translation.
*/
public function setDeleteMessage() {
}
/**
* Set the renewal notification status message.
*/
public function setRenewalMessage() {
$statusMsg = ts('%1 membership for %2 has been renewed.', [1 => $this->membershipTypeName, 2 => $this->_memberDisplayName]);
if ($this->isMailSent) {
$statusMsg .= ' ' . ts('A renewal confirmation and receipt has been sent to %1.', [1 => $this->_contributorEmail]);
}
CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
}
/**
* Preprocess form.
*
* @throws \CRM_Core_Exception
* @throws \CiviCRM_API3_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', 'membershiprenew');
parent::preProcess();
$this->assign('endDate', CRM_Utils_Date::customFormat(CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
$this->_id, 'end_date'
)
));
$this->assign('membershipStatus',
CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus',
CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
$this->_id, 'status_id'
),
'name'
)
);
if ($this->_mode) {
$membershipFee = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'minimum_fee');
if (!$membershipFee) {
$statusMsg = ts('Membership Renewal using a credit card requires a Membership fee. Since there is no fee associated with the selected membership type, you can use the normal renewal mode.');
CRM_Core_Session::setStatus($statusMsg, '', 'info');
CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership',
"reset=1&action=renew&cid={$this->_contactID}&id={$this->_id}&context=membership"
));
}
}
// when custom data is included in this page
if (!empty($_POST['hidden_custom'])) {
CRM_Custom_Form_CustomData::preProcess($this, NULL, $this->_memType, 1, 'Membership', $this->_id);
CRM_Custom_Form_CustomData::buildQuickForm($this);
CRM_Custom_Form_CustomData::setDefaultValues($this);
}
CRM_Utils_System::setTitle(ts('Renew Membership'));
parent::preProcess();
}
/**
* Set default values for the form.
* the default values are retrieved from the database
*
* @return array
* Default values.
* @throws \CRM_Core_Exception
*/
public function setDefaultValues() {
$defaults = parent::setDefaultValues();
// set renewal_date and receive_date to today in correct input format (setDateDefaults uses today if no value passed)
$now = date('Y-m-d');
$defaults['renewal_date'] = $now;
$defaults['receive_date'] = $now . ' ' . date('H:i:s');
if ($defaults['id']) {
$defaults['record_contribution'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment',
$defaults['id'],
'contribution_id',
'membership_id'
);
}
$defaults['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'financial_type_id');
//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'));
}
$defaults['total_amount'] = CRM_Utils_Money::format(CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
$this->_memType,
'minimum_fee'
), NULL, '%a');
$defaults['record_contribution'] = 0;
$defaults['num_terms'] = 1;
$defaults['send_receipt'] = 0;
//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));
$renewalDate = $defaults['renewal_date'] ?? NULL;
$this->assign('renewalDate', $renewalDate);
$this->assign('member_is_test', CRM_Utils_Array::value('member_is_test', $defaults));
if ($this->_mode) {
$defaults = $this->getBillingDefaults($defaults);
}
return $defaults;
}
/**
* Build the form object.
*
* @throws \CRM_Core_Exception
*/
public function buildQuickForm() {
parent::buildQuickForm();
$defaults = parent::setDefaultValues();
$this->assign('customDataType', 'Membership');
$this->assign('customDataSubType', $this->_memType);
$this->assign('entityID', $this->_id);
$selOrgMemType[0][0] = $selMemTypeOrg[0] = ts('- select -');
$allMembershipInfo = [];
// CRM-21485
if (is_array($defaults['membership_type_id'])) {
$defaults['membership_type_id'] = $defaults['membership_type_id'][1];
}
//CRM-16950
$taxRate = $this->getTaxRateForFinancialType($this->allMembershipTypeDetails[$defaults['membership_type_id']]['financial_type_id']);
$contactField = $this->addEntityRef('contact_id', ts('Member'), ['create' => TRUE, 'api' => ['extra' => ['email']]], TRUE);
$contactField->freeze();
// auto renew options if enabled for the membership
$options = CRM_Core_SelectValues::memberAutoRenew();
foreach ($this->allMembershipTypeDetails as $key => $values) {
if (!empty($values['is_active'])) {
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;
}
}
//CRM-16950
$taxAmount = NULL;
$totalAmount = $values['minimum_fee'] ?? NULL;
// @todo - feels a bug - we use taxRate from the form default rather than from the specified type?!?
if ($this->getTaxRateForFinancialType($values['financial_type_id'])) {
$taxAmount = ($taxRate / 100) * CRM_Utils_Array::value('minimum_fee', $values);
$totalAmount = $totalAmount + $taxAmount;
}
// build membership info array, which is used to set the payment information block when
// membership type is selected.
$allMembershipInfo[$key] = [
'financial_type_id' => $values['financial_type_id'] ?? NULL,
'total_amount' => CRM_Utils_Money::format($totalAmount, NULL, '%a'),
'total_amount_numeric' => $totalAmount,
'tax_message' => $taxAmount ? ts("Includes %1 amount of %2", [1 => $this->getSalesTaxTerm(), 2 => CRM_Utils_Money::format($taxAmount)]) : $taxAmount,
];
if (!empty($values['auto_renew'])) {
$allMembershipInfo[$key]['auto_renew'] = $options[$values['auto_renew']];
}
}
}
$this->assign('allMembershipInfo', json_encode($allMembershipInfo));
if ($this->_memType) {
$this->assign('orgName', $selMemTypeOrg[$this->allMembershipTypeDetails[$this->_memType]['member_of_contact_id']]);
$this->assign('memType', $this->allMembershipTypeDetails[$this->_memType]['name']);
}
// force select of 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;
}
$js = ['onChange' => "setPaymentBlock(); CRM.buildCustomData('Membership', this.value);"];
$sel = &$this->addElement('hierselect',
'membership_type_id',
ts('Renewal Membership Organization and Type'), $js
);
$sel->setOptions([$selMemTypeOrg, $selOrgMemType]);
$elements = [];
if ($sel) {
$elements[] = $sel;
}
$this->applyFilter('__ALL__', 'trim');
$this->add('datepicker', 'renewal_date', ts('Date Renewal Entered'), [], FALSE, ['time' => FALSE]);
$this->add('select', 'financial_type_id', ts('Financial Type'),
['' => ts('- select -')] + CRM_Contribute_PseudoConstant::financialType()
);
$this->add('number', 'num_terms', ts('Extend Membership by'), ['onchange' => "setPaymentBlock();"], TRUE);
$this->addRule('num_terms', ts('Please enter a whole number for how many periods to renew.'), 'integer');
if (CRM_Core_Permission::access('CiviContribute') && !$this->_mode) {
$this->addElement('checkbox', 'record_contribution', ts('Record Renewal Payment?'), NULL, ['onclick' => "checkPayment();"]);
$this->add('text', 'total_amount', ts('Amount'));
$this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
$this->add('datepicker', 'receive_date', ts('Received'), [], 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::getContributionStatuses('membership')
);
$this->add('text', 'check_number', ts('Check Number'),
CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution', 'check_number')
);
}
else {
$this->add('text', 'total_amount', ts('Amount'));
$this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
}
$this->addElement('checkbox', 'send_receipt', ts('Send Confirmation and Receipt?'), NULL,
['onclick' => "showHideByValue( 'send_receipt', '', 'notice', 'table-row', 'radio', false ); showHideByValue( 'send_receipt', '', 'fromEmail', 'table-row', 'radio',false);"]
);
$this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
$this->add('textarea', 'receipt_text_renewal', ts('Renewal Message'));
// Retrieve the name and email of the contact - this will be the TO for receipt email
list($this->_contributorDisplayName,
$this->_contributorEmail
) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
$this->assign('email', $this->_contributorEmail);
// The member form uses emailExists. Assigning both while we transition / synchronise.
$this->assign('emailExists', $this->_contributorEmail);
$mailingInfo = Civi::settings()->get('mailing_backend');
$this->assign('outBound_option', $mailingInfo['outBound_option']);
if (CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_id, 'contribution_recur_id')) {
if (CRM_Member_BAO_Membership::isCancelSubscriptionSupported($this->_id)) {
$this->assign('cancelAutoRenew',
CRM_Utils_System::url('civicrm/contribute/unsubscribe', "reset=1&mid={$this->_id}")
);
}
}
$this->addFormRule(['CRM_Member_Form_MembershipRenewal', 'formRule'], $this);
$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]);
}
/**
* Validation.
*
* @param array $params
* (ref.) an assoc array of name/value pairs.
* @param $files
* @param $self
*
* @return bool|array
* mixed true or array of errors
* @throws \CRM_Core_Exception
*/
public static function formRule($params, $files, $self) {
$errors = [];
if ($params['membership_type_id'][0] == 0) {
$errors['membership_type_id'] = ts('Oops. It looks like you are trying to change the membership type while renewing the membership. Please click the "change membership type" link, and select a Membership Organization.');
}
if ($params['membership_type_id'][1] == 0) {
$errors['membership_type_id'] = ts('Oops. It looks like you are trying to change the membership type while renewing the membership. Please click the "change membership type" link and select a Membership Type from the list.');
}
// CRM-20571
// Get the Join Date from Membership info as it is not available in the Renewal form
$joinDate = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $self->_id, 'join_date');
// CRM-20571: Check if the renewal date is not before Join Date, if it is then add to 'errors' array
// The fields in Renewal form come into this routine in $params array. 'renewal_date' is in the form
// We process both the dates before comparison using CRM utils so that they are in same date format
if (isset($params['renewal_date'])) {
if ($params['renewal_date'] < $joinDate) {
$errors['renewal_date'] = ts('Renewal date must be the same or later than Member since (Join Date).');
}
}
//total amount condition arise when membership type having no
//minimum fee
if (isset($params['record_contribution'])) {
if (!$params['financial_type_id']) {
$errors['financial_type_id'] = ts('Please select a Financial Type.');
}
if (!$params['total_amount']) {
$errors['total_amount'] = ts('Please enter a Contribution Amount.');
}
if (empty($params['payment_instrument_id'])) {
$errors['payment_instrument_id'] = ts('Payment Method is a required field.');
}
}
return empty($errors) ? TRUE : $errors;
}
/**
* Process the renewal form.
*
* @throws \CRM_Core_Exception
* @throws \CiviCRM_API3_Exception
*/
public function postProcess() {
// get the submitted form values.
$this->_params = $this->controller->exportValues($this->_name);
$this->assignBillingName();
try {
$this->submit();
$this->setRenewalMessage();
}
catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
CRM_Core_Session::singleton()->setStatus($e->getMessage());
CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership',
"reset=1&action=renew&cid={$this->_contactID}&id={$this->_id}&context=membership&mode={$this->_mode}"
));
}
}
/**
* Process form submission.
*
* This function is also accessed by a unit test.
*
* @throws \CRM_Core_Exception
* @throws \CiviCRM_API3_Exception
*/
protected function submit() {
$this->storeContactFields($this->_params);
$this->beginPostProcess();
$now = CRM_Utils_Date::getToday(NULL, 'YmdHis');
$this->assign('receive_date', CRM_Utils_Array::value('receive_date', $this->_params, date('Y-m-d H:i:s')));
$this->processBillingAddress();
list($userName) = CRM_Contact_BAO_Contact_Location::getEmailDetails(CRM_Core_Session::singleton()->get('userID'));
$this->_params['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_params,
CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'minimum_fee')
);
$this->_membershipId = $this->_id;
$customFieldsFormatted = CRM_Core_BAO_CustomField::postProcess($this->_params,
$this->_id,
'Membership'
);
if (empty($this->_params['financial_type_id'])) {
$this->_params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'financial_type_id');
}
$contributionRecurID = NULL;
$this->assign('membershipID', $this->_id);
$this->assign('contactID', $this->_contactID);
$this->assign('module', 'Membership');
$this->assign('receiptType', 'membership renewal');
$this->_params['currencyID'] = CRM_Core_Config::singleton()->defaultCurrency;
$this->_params['invoice_id'] = $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
if (!empty($this->_params['send_receipt'])) {
$this->_params['receipt_date'] = $now;
$this->assign('receipt_date', CRM_Utils_Date::mysqlToIso($this->_params['receipt_date']));
}
else {
$this->_params['receipt_date'] = NULL;
}
if ($this->_mode) {
$this->_params['register_date'] = $now;
$this->_params['description'] = ts("Contribution submitted by a staff person using member's credit card for renewal");
$this->_params['amount'] = $this->_params['total_amount'];
$this->_params['payment_instrument_id'] = $this->_paymentProcessor['payment_instrument_id'];
$this->_params['receive_date'] = $now;
// at this point we've created a contact and stored its address etc
// all the payment processors expect the name and address to be in the passed params
// so we copy stuff over to first_name etc.
$paymentParams = $this->_params;
if (!empty($this->_params['send_receipt'])) {
$paymentParams['email'] = $this->_contributorEmail;
}
$paymentParams['contactID'] = $this->_contributorContactID;
CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
if (!empty($this->_params['auto_renew'])) {
$contributionRecurParams = $this->processRecurringContribution([
'contact_id' => $this->_contributorContactID,
'amount' => $this->_params['total_amount'],
'contribution_status_id' => 'Pending',
'payment_processor_id' => $this->_params['payment_processor_id'],
'financial_type_id' => $this->_params['financial_type_id'],
'is_email_receipt' => !empty($this->_params['send_receipt']),
'payment_instrument_id' => $this->_params['payment_instrument_id'],
'invoice_id' => $this->_params['invoice_id'],
], $membershipID = $paymentParams['membership_type_id'][1]);
$contributionRecurID = $contributionRecurParams['contributionRecurID'];
$paymentParams = array_merge($paymentParams, $contributionRecurParams);
}
$payment = $this->_paymentProcessor['object'];
$result = $payment->doPayment($paymentParams);
$this->_params = array_merge($this->_params, $result);
$this->_params['contribution_status_id'] = $result['payment_status_id'];
$this->_params['trxn_id'] = $result['trxn_id'];
$this->_params['is_test'] = ($this->_mode === 'live') ? 0 : 1;
$this->set('params', $this->_params);
$this->assign('trxn_id', $result['trxn_id']);
}
$renewalDate = !empty($this->_params['renewal_date']) ? $renewalDate = $this->_params['renewal_date'] : NULL;
// check for test membership.
$isTestMembership = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_membershipId, 'is_test');
// chk for renewal for multiple terms CRM-8750
$numRenewTerms = 1;
if (is_numeric(CRM_Utils_Array::value('num_terms', $this->_params))) {
$numRenewTerms = $this->_params['num_terms'];
}
//if contribution status is pending then set pay later
$this->_params['is_pay_later'] = FALSE;
if ($this->_params['contribution_status_id'] == array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'label'))) {
$this->_params['is_pay_later'] = 1;
}
$pending = ($this->_params['contribution_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending'));
$membership = $this->processMembership(
$this->_contactID, $this->_params['membership_type_id'][1], $isTestMembership,
$renewalDate, $customFieldsFormatted, $numRenewTerms, $this->_membershipId,
$pending,
$contributionRecurID, $this->_params['is_pay_later']);
$this->endDate = CRM_Utils_Date::processDate($membership->end_date);
$this->membershipTypeName = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $membership->membership_type_id,
'name');
if (!empty($this->_params['record_contribution']) || $this->_mode) {
// set the source
$this->_params['contribution_source'] = "{$this->membershipTypeName} Membership: Offline membership renewal (by {$userName})";
//create line items
$lineItem = [];
$this->_params = $this->setPriceSetParameters($this->_params);
$order = new CRM_Financial_BAO_Order();
$order->setPriceSelectionFromUnfilteredInput($this->_params);
$order->setPriceSetID(self::getPriceSetID($this->_params));
$order->setOverrideTotalAmount($this->_params['total_amount']);
$order->setOverrideFinancialTypeID((int) $this->_params['financial_type_id']);
$this->_params['lineItems'][$this->_priceSetId] = $order->getLineItems();
// This is one of those weird & wonderful legacy params we aim to get rid of.
$this->_params['processPriceSet'] = TRUE;
$this->_params['tax_amount'] = $order->getTotalTaxAmount();
//assign contribution contact id to the field expected by recordMembershipContribution
if ($this->_contributorContactID != $this->_contactID) {
$this->_params['contribution_contact_id'] = $this->_contributorContactID;
if (!empty($this->_params['soft_credit_type_id'])) {
$this->_params['soft_credit'] = [
'soft_credit_type_id' => $this->_params['soft_credit_type_id'],
'contact_id' => $this->_contactID,
];
}
}
$this->_params['contact_id'] = $this->_contactID;
//recordMembershipContribution receives params as a reference & adds one variable. This is
// not a great pattern & ideally it would not receive as a reference. We assign our params as a
// temporary variable to avoid e-notice & to make it clear to future refactorer that
// this function is NOT reliant on that var being set
$temporaryParams = array_merge($this->_params, [
'membership_id' => $membership->id,
'contribution_recur_id' => $contributionRecurID,
]);
//Remove `tax_amount` if it is not calculated.
// ?? WHY - I haven't been able to figure out...
if (CRM_Utils_Array::value('tax_amount', $temporaryParams) === 0.0) {
unset($temporaryParams['tax_amount']);
}
CRM_Member_BAO_Membership::recordMembershipContribution($temporaryParams);
}
if (!empty($this->_params['send_receipt'])) {
$this->sendReceipt($membership);
}
}
/**
* Send a receipt.
*
* @param array $membership
*
* @throws \CRM_Core_Exception
*/
protected function sendReceipt($membership) {
$receiptFrom = $this->_params['from_email_address'];
if (!empty($this->_params['payment_instrument_id'])) {
$paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
$this->_params['paidBy'] = $paymentInstrument[$this->_params['payment_instrument_id']];
}
//get the group Tree
$this->_groupTree = CRM_Core_BAO_CustomGroup::getTree('Membership', NULL, $this->_id, FALSE, $this->_memType);
// retrieve custom data
$customFields = $customValues = $fo = [];
foreach ($this->_groupTree as $groupID => $group) {
if ($groupID === 'info') {
continue;
}
foreach ($group['fields'] as $k => $field) {
$field['title'] = $field['label'];
$customFields["custom_{$k}"] = $field;
}
}
$members = [['member_id', '=', $this->_membershipId, 0, 0]];
// check whether its a test drive
if ($this->_mode === 'test') {
$members[] = ['member_test', '=', 1, 0, 0];
}
CRM_Core_BAO_UFGroup::getValues($this->_contactID, $customFields, $customValues, FALSE, $members);
$this->assign_by_ref('formValues', $this->_params);
if (!empty($this->_params['contribution_id'])) {
$this->assign('contributionID', $this->_params['contribution_id']);
}
$this->assign('membership_name', CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
$membership->membership_type_id
));
$this->assign('customValues', $customValues);
$this->assign('mem_start_date', CRM_Utils_Date::customFormat($membership->start_date));
$this->assign('mem_end_date', CRM_Utils_Date::customFormat($membership->end_date));
if ($this->_mode) {
$this->assign('address', CRM_Utils_Address::getFormattedBillingAddressFieldsFromParameters(
$this->_params,
$this->_bltID
));
$this->assign('contributeMode', 'direct');
$this->assign('isAmountzero', 0);
$this->assign('is_pay_later', 0);
$this->assign('isPrimary', 1);
$this->assign('receipt_text_renewal', $this->_params['receipt_text']);
if ($this->_mode === 'test') {
$this->assign('action', '1024');
}
}
list($this->isMailSent) = CRM_Core_BAO_MessageTemplate::sendTemplate(
[
'groupName' => 'msg_tpl_workflow_membership',
'valueName' => 'membership_offline_receipt',
'contactId' => $this->_receiptContactId,
'from' => $receiptFrom,
'toName' => $this->_contributorDisplayName,
'toEmail' => $this->_contributorEmail,
'isTest' => $this->_mode === 'test',
]
);
}
/**
* Process membership.
*
* This is duplicated from the BAO class - on the basis that it's actually easier to divide & conquer when
* it comes to clearing up really bad code.
*
* @param int $contactID
* @param int $membershipTypeID
* @param bool $is_test
* @param string $changeToday
* @param $customFieldsFormatted
* @param $numRenewTerms
* @param int $membershipID
* @param $pending
* @param int $contributionRecurID
* @param $membershipSource
* @param $isPayLater
*
* @return CRM_Member_BAO_Membership
* @throws \CRM_Core_Exception
* @throws \CiviCRM_API3_Exception
*/
public function processMembership($contactID, $membershipTypeID, $is_test, $changeToday, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $contributionRecurID, $isPayLater) {
$updateStatusId = FALSE;
$allStatus = CRM_Member_PseudoConstant::membershipStatus();
$format = '%Y%m%d';
$membershipTypeDetails = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($membershipTypeID);
$ids = [];
// CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
// is the same as the parent org of an existing membership of the contact
$currentMembership = CRM_Member_BAO_Membership::getContactMembership($contactID, $membershipTypeID,
$is_test, $membershipID, TRUE
);
// Do NOT do anything.
//1. membership with status : PENDING/CANCELLED (CRM-2395)
//2. Paylater/IPN renew. CRM-4556.
if ($pending || in_array($currentMembership['status_id'], [
array_search('Pending', $allStatus),
// CRM-15475
array_search('Cancelled', CRM_Member_PseudoConstant::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
])) {
$memParams = [
'id' => $currentMembership['id'],
'status_id' => $currentMembership['status_id'],
'start_date' => $currentMembership['start_date'],
'end_date' => $currentMembership['end_date'],
'join_date' => $currentMembership['join_date'],
'membership_type_id' => $membershipTypeID,
'max_related' => !empty($membershipTypeDetails['max_related']) ? $membershipTypeDetails['max_related'] : NULL,
'membership_activity_status' => ($pending || $isPayLater) ? 'Scheduled' : 'Completed',
];
if ($contributionRecurID) {
$memParams['contribution_recur_id'] = $contributionRecurID;
}
// @todo stop passing $ids - it is empty
return CRM_Member_BAO_Membership::create($memParams, $ids);
}
// Check and fix the membership if it is STALE
CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
// Now Renew the membership
if (!$currentMembership['is_current_member']) {
// membership is not CURRENT
// CRM-7297 Membership Upsell - calculate dates based on new membership type
$dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($currentMembership['id'],
$changeToday,
$membershipTypeID,
$numRenewTerms
);
$currentMembership['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
foreach (['start_date', 'end_date'] as $dateType) {
$currentMembership[$dateType] = $dates[$dateType] ?? NULL;
}
$currentMembership['is_test'] = $is_test;
$currentMembership['source'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
$currentMembership['id'],
'source'
);
if (!empty($currentMembership['id'])) {
$ids['membership'] = $currentMembership['id'];
}
$memParams = $currentMembership;
$memParams['membership_type_id'] = $membershipTypeID;
//set the log start date.
$memParams['log_start_date'] = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
}
else {
// CURRENT Membership
$membership = new CRM_Member_DAO_Membership();
$membership->id = $currentMembership['id'];
$membership->find(TRUE);
// CRM-7297 Membership Upsell - calculate dates based on new membership type
$dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id,
$changeToday,
$membershipTypeID,
$numRenewTerms
);
// Insert renewed dates for CURRENT membership
$memParams = [];
$memParams['join_date'] = $membership->join_date;
$memParams['start_date'] = $membership->start_date;
$memParams['end_date'] = $dates['end_date'] ?? NULL;
$memParams['membership_type_id'] = $membershipTypeID;
//set the log start date.
$memParams['log_start_date'] = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
if (empty($membership->source)) {
$memParams['source'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
$currentMembership['id'],
'source'
);
}
if (!empty($currentMembership['id'])) {
$ids['membership'] = $currentMembership['id'];
}
$memParams['membership_activity_status'] = ($pending || $isPayLater) ? 'Scheduled' : 'Completed';
}
//CRM-4555
if ($pending) {
$updateStatusId = array_search('Pending', $allStatus);
}
// Putting this in an IF is precautionary as it seems likely that it would be ignored if empty, but
// perhaps shouldn't be?
if ($contributionRecurID) {
$memParams['contribution_recur_id'] = $contributionRecurID;
}
//CRM-4555
//if we decided status here and want to skip status
//calculation in create( ); then need to pass 'skipStatusCal'.
if ($updateStatusId) {
$memParams['status_id'] = $updateStatusId;
$memParams['skipStatusCal'] = TRUE;
}
//since we are renewing,
//make status override false.
$memParams['is_override'] = FALSE;
$params['modified_id'] = $contactID;
$memParams['custom'] = $customFieldsFormatted;
// @todo stop passing $ids (membership and userId may be set by this point)
$membership = CRM_Member_BAO_Membership::create($memParams, $ids);
// not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
// related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
$membership->find(TRUE);
return $membership;
}
}