096e45e65254bc327427cad20afe14df65d3f8c2
[civicrm-core.git] / CRM / Member / Form / MembershipRenewal.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2019
32 */
33
34 /**
35 * This class generates form components for Membership Renewal
36 */
37 class CRM_Member_Form_MembershipRenewal extends CRM_Member_Form {
38
39 /**
40 * Display name of the member.
41 *
42 * @var string
43 */
44 protected $_memberDisplayName = NULL;
45
46 /**
47 * email of the person paying for the membership (used for receipts)
48 * @var string
49 */
50 protected $_memberEmail = NULL;
51
52 /**
53 * Contact ID of the member.
54 *
55 *
56 * @var int
57 */
58 public $_contactID = NULL;
59
60 /**
61 * Display name of the person paying for the membership (used for receipts)
62 *
63 * @var string
64 */
65 protected $_contributorDisplayName = NULL;
66
67 /**
68 * email of the person paying for the membership (used for receipts)
69 * @var string
70 */
71 protected $_contributorEmail = NULL;
72
73 /**
74 * email of the person paying for the membership (used for receipts)
75 *
76 * @var int
77 */
78 protected $_contributorContactID = NULL;
79
80 /**
81 * ID of the person the receipt is to go to
82 *
83 * @var int
84 */
85 protected $_receiptContactId = NULL;
86
87 /**
88 * context would be set to standalone if the contact is use is being selected from
89 * the form rather than in the URL
90 * @var string
91 */
92 public $_context;
93
94 /**
95 * End date of renewed membership.
96 *
97 * @var string
98 */
99 protected $endDate = NULL;
100
101 /**
102 * Has an email been sent.
103 *
104 * @var string
105 */
106 protected $isMailSent = FALSE;
107
108 /**
109 * The name of the renewed membership type.
110 *
111 * @var string
112 */
113 protected $membershipTypeName = '';
114
115 /**
116 * Set entity fields to be assigned to the form.
117 */
118 protected function setEntityFields() {}
119
120 /**
121 * Set the delete message.
122 *
123 * We do this from the constructor in order to do a translation.
124 */
125 public function setDeleteMessage() {}
126
127 /**
128 * Pre-process form.
129 *
130 * @throws \Exception
131 */
132 public function preProcess() {
133
134 // This string makes up part of the class names, differentiating them (not sure why) from the membership fields.
135 $this->assign('formClass', 'membershiprenew');
136 parent::preProcess();
137
138 $this->assign('endDate', CRM_Utils_Date::customFormat(CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
139 $this->_id, 'end_date'
140 )
141 ));
142 $this->assign('membershipStatus',
143 CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus',
144 CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
145 $this->_id, 'status_id'
146 ),
147 'name'
148 )
149 );
150
151 if ($this->_mode) {
152 $membershipFee = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'minimum_fee');
153 if (!$membershipFee) {
154 $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.');
155 CRM_Core_Session::setStatus($statusMsg, '', 'info');
156 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership',
157 "reset=1&action=renew&cid={$this->_contactID}&id={$this->_id}&context=membership"
158 ));
159 }
160 }
161
162 // when custom data is included in this page
163 if (!empty($_POST['hidden_custom'])) {
164 CRM_Custom_Form_CustomData::preProcess($this, NULL, $this->_memType, 1, 'Membership', $this->_id);
165 CRM_Custom_Form_CustomData::buildQuickForm($this);
166 CRM_Custom_Form_CustomData::setDefaultValues($this);
167 }
168
169 CRM_Utils_System::setTitle(ts('Renew Membership'));
170
171 parent::preProcess();
172 }
173
174 /**
175 * Set default values for the form.
176 * the default values are retrieved from the database
177 *
178 * @return array
179 * Default values.
180 */
181 public function setDefaultValues() {
182
183 $defaults = parent::setDefaultValues();
184
185 // set renewal_date and receive_date to today in correct input format (setDateDefaults uses today if no value passed)
186 $now = date('Y-m-d');
187 $defaults['renewal_date'] = $now;
188 $defaults['receive_date'] = $now . ' ' . date('H:i:s');
189
190 if ($defaults['id']) {
191 $defaults['record_contribution'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment',
192 $defaults['id'],
193 'contribution_id',
194 'membership_id'
195 );
196 }
197
198 $defaults['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'financial_type_id');
199
200 //CRM-13420
201 if (empty($defaults['payment_instrument_id'])) {
202 $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
203 }
204
205 $defaults['total_amount'] = CRM_Utils_Money::format(CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
206 $this->_memType,
207 'minimum_fee'
208 ), NULL, '%a');
209
210 $defaults['record_contribution'] = 0;
211 $defaults['num_terms'] = 1;
212 $defaults['send_receipt'] = 0;
213
214 //set Soft Credit Type to Gift by default
215 $scTypes = CRM_Core_OptionGroup::values("soft_credit_type");
216 $defaults['soft_credit_type_id'] = CRM_Utils_Array::value(ts('Gift'), array_flip($scTypes));
217
218 $renewalDate = CRM_Utils_Array::value('renewal_date', $defaults);
219 $this->assign('renewalDate', $renewalDate);
220 $this->assign('member_is_test', CRM_Utils_Array::value('member_is_test', $defaults));
221
222 if ($this->_mode) {
223 $defaults = $this->getBillingDefaults($defaults);
224 }
225 return $defaults;
226 }
227
228 /**
229 * Build the form object.
230 */
231 public function buildQuickForm() {
232
233 parent::buildQuickForm();
234
235 $defaults = parent::setDefaultValues();
236 $this->assign('customDataType', 'Membership');
237 $this->assign('customDataSubType', $this->_memType);
238 $this->assign('entityID', $this->_id);
239 $selOrgMemType[0][0] = $selMemTypeOrg[0] = ts('- select -');
240
241 $allMembershipInfo = [];
242
243 // CRM-21485
244 if (is_array($defaults['membership_type_id'])) {
245 $defaults['membership_type_id'] = $defaults['membership_type_id'][1];
246 }
247
248 //CRM-16950
249 $taxRate = $this->getTaxRateForFinancialType($this->allMembershipTypeDetails[$defaults['membership_type_id']]['financial_type_id']);
250
251 // auto renew options if enabled for the membership
252 $options = CRM_Core_SelectValues::memberAutoRenew();
253
254 foreach ($this->allMembershipTypeDetails as $key => $values) {
255 if (!empty($values['is_active'])) {
256 if ($this->_mode && empty($values['minimum_fee'])) {
257 continue;
258 }
259 else {
260 $memberOfContactId = CRM_Utils_Array::value('member_of_contact_id', $values);
261 if (empty($selMemTypeOrg[$memberOfContactId])) {
262 $selMemTypeOrg[$memberOfContactId] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
263 $memberOfContactId,
264 'display_name',
265 'id'
266 );
267
268 $selOrgMemType[$memberOfContactId][0] = ts('- select -');
269 }
270 if (empty($selOrgMemType[$memberOfContactId][$key])) {
271 $selOrgMemType[$memberOfContactId][$key] = CRM_Utils_Array::value('name', $values);
272 }
273 }
274
275 //CRM-16950
276 $taxAmount = NULL;
277 $totalAmount = CRM_Utils_Array::value('minimum_fee', $values);
278 // @todo - feels a bug - we use taxRate from the form default rather than from the specified type?!?
279 if ($this->getTaxRateForFinancialType($values['financial_type_id'])) {
280 $taxAmount = ($taxRate / 100) * CRM_Utils_Array::value('minimum_fee', $values);
281 $totalAmount = $totalAmount + $taxAmount;
282 }
283
284 // build membership info array, which is used to set the payment information block when
285 // membership type is selected.
286 $allMembershipInfo[$key] = [
287 'financial_type_id' => CRM_Utils_Array::value('financial_type_id', $values),
288 'total_amount' => CRM_Utils_Money::format($totalAmount, NULL, '%a'),
289 'total_amount_numeric' => $totalAmount,
290 'tax_message' => $taxAmount ? ts("Includes %1 amount of %2", [1 => $this->getSalesTaxTerm(), 2 => CRM_Utils_Money::format($taxAmount)]) : $taxAmount,
291 ];
292
293 if (!empty($values['auto_renew'])) {
294 $allMembershipInfo[$key]['auto_renew'] = $options[$values['auto_renew']];
295 }
296 }
297 }
298
299 $this->assign('allMembershipInfo', json_encode($allMembershipInfo));
300
301 if ($this->_memType) {
302 $this->assign('orgName', $selMemTypeOrg[$this->allMembershipTypeDetails[$this->_memType]['member_of_contact_id']]);
303 $this->assign('memType', $this->allMembershipTypeDetails[$this->_memType]['name']);
304 }
305
306 // force select of organization by default, if only one organization in
307 // the list
308 if (count($selMemTypeOrg) == 2) {
309 unset($selMemTypeOrg[0], $selOrgMemType[0][0]);
310 }
311 //sort membership organization and type, CRM-6099
312 natcasesort($selMemTypeOrg);
313 foreach ($selOrgMemType as $index => $orgMembershipType) {
314 natcasesort($orgMembershipType);
315 $selOrgMemType[$index] = $orgMembershipType;
316 }
317
318 $js = ['onChange' => "setPaymentBlock(); CRM.buildCustomData('Membership', this.value);"];
319 $sel = &$this->addElement('hierselect',
320 'membership_type_id',
321 ts('Renewal Membership Organization and Type'), $js
322 );
323
324 $sel->setOptions([$selMemTypeOrg, $selOrgMemType]);
325 $elements = [];
326 if ($sel) {
327 $elements[] = $sel;
328 }
329
330 $this->applyFilter('__ALL__', 'trim');
331
332 $this->add('datepicker', 'renewal_date', ts('Date Renewal Entered'), [], FALSE, ['time' => FALSE]);
333
334 $this->add('select', 'financial_type_id', ts('Financial Type'),
335 ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::financialType()
336 );
337
338 $this->add('number', 'num_terms', ts('Extend Membership by'), ['onchange' => "setPaymentBlock();"], TRUE);
339 $this->addRule('num_terms', ts('Please enter a whole number for how many periods to renew.'), 'integer');
340
341 if (CRM_Core_Permission::access('CiviContribute') && !$this->_mode) {
342 $this->addElement('checkbox', 'record_contribution', ts('Record Renewal Payment?'), NULL, ['onclick' => "checkPayment();"]);
343
344 $this->add('text', 'total_amount', ts('Amount'));
345 $this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
346
347 $this->add('datepicker', 'receive_date', ts('Received'), [], FALSE, ['time' => TRUE]);
348
349 $this->add('select', 'payment_instrument_id', ts('Payment Method'),
350 ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::paymentInstrument(),
351 FALSE, ['onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);"]
352 );
353
354 $this->add('text', 'trxn_id', ts('Transaction ID'));
355 $this->addRule('trxn_id', ts('Transaction ID already exists in Database.'),
356 'objectExists', ['CRM_Contribute_DAO_Contribution', $this->_id, 'trxn_id']
357 );
358
359 $this->add('select', 'contribution_status_id', ts('Payment Status'),
360 CRM_Contribute_BAO_Contribution_Utils::getContributionStatuses('membership')
361 );
362
363 $this->add('text', 'check_number', ts('Check Number'),
364 CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution', 'check_number')
365 );
366 }
367 else {
368 $this->add('text', 'total_amount', ts('Amount'));
369 $this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
370 }
371 $this->addElement('checkbox', 'send_receipt', ts('Send Confirmation and Receipt?'), NULL,
372 ['onclick' => "showHideByValue( 'send_receipt', '', 'notice', 'table-row', 'radio', false ); showHideByValue( 'send_receipt', '', 'fromEmail', 'table-row', 'radio',false);"]
373 );
374
375 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
376
377 $this->add('textarea', 'receipt_text_renewal', ts('Renewal Message'));
378
379 // Retrieve the name and email of the contact - this will be the TO for receipt email
380 list($this->_contributorDisplayName,
381 $this->_contributorEmail
382 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
383 $this->assign('email', $this->_contributorEmail);
384 // The member form uses emailExists. Assigning both while we transition / synchronise.
385 $this->assign('emailExists', $this->_contributorEmail);
386
387 $mailingInfo = Civi::settings()->get('mailing_backend');
388 $this->assign('outBound_option', $mailingInfo['outBound_option']);
389
390 if (CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_id, 'contribution_recur_id')) {
391 if (CRM_Member_BAO_Membership::isCancelSubscriptionSupported($this->_id)) {
392 $this->assign('cancelAutoRenew',
393 CRM_Utils_System::url('civicrm/contribute/unsubscribe', "reset=1&mid={$this->_id}")
394 );
395 }
396 }
397 $this->addFormRule(['CRM_Member_Form_MembershipRenewal', 'formRule'], $this);
398 $this->addElement('checkbox', 'is_different_contribution_contact', ts('Record Payment from a Different Contact?'));
399 $this->addSelect('soft_credit_type_id', ['entity' => 'contribution_soft']);
400 $this->addEntityRef('soft_credit_contact_id', ts('Payment From'), ['create' => TRUE]);
401 }
402
403 /**
404 * Validation.
405 *
406 * @param array $params
407 * (ref.) an assoc array of name/value pairs.
408 * @param $files
409 * @param $self
410 *
411 * @return bool|array
412 * mixed true or array of errors
413 */
414 public static function formRule($params, $files, $self) {
415 $errors = [];
416 if ($params['membership_type_id'][0] == 0) {
417 $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.');
418 }
419 if ($params['membership_type_id'][1] == 0) {
420 $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.');
421 }
422
423 // CRM-20571
424 // Get the Join Date from Membership info as it is not available in the Renewal form
425 $joinDate = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $self->_id, 'join_date');
426
427 // CRM-20571: Check if the renewal date is not before Join Date, if it is then add to 'errors' array
428 // The fields in Renewal form come into this routine in $params array. 'renewal_date' is in the form
429 // We process both the dates before comparison using CRM utils so that they are in same date format
430 if (isset($params['renewal_date'])) {
431 if ($params['renewal_date'] < $joinDate) {
432 $errors['renewal_date'] = ts('Renewal date must be the same or later than Member since (Join Date).');
433 }
434 }
435
436 //total amount condition arise when membership type having no
437 //minimum fee
438 if (isset($params['record_contribution'])) {
439 if (!$params['financial_type_id']) {
440 $errors['financial_type_id'] = ts('Please select a Financial Type.');
441 }
442 if (!$params['total_amount']) {
443 $errors['total_amount'] = ts('Please enter a Contribution Amount.');
444 }
445 if (empty($params['payment_instrument_id'])) {
446 $errors['payment_instrument_id'] = ts('Payment Method is a required field.');
447 }
448 }
449 return empty($errors) ? TRUE : $errors;
450 }
451
452 /**
453 * Process the renewal form.
454 */
455 public function postProcess() {
456 // get the submitted form values.
457 $this->_params = $this->controller->exportValues($this->_name);
458 $this->assignBillingName();
459
460 try {
461 $this->submit();
462 $statusMsg = ts('%1 membership for %2 has been renewed.', [1 => $this->membershipTypeName, 2 => $this->_memberDisplayName]);
463
464 if ($this->endDate) {
465 $statusMsg .= ' ' . ts('The new membership End Date is %1.', [
466 1 => CRM_Utils_Date::customFormat(substr($this->endDate, 0, 8)),
467 ]);
468 }
469
470 if ($this->isMailSent) {
471 $statusMsg .= ' ' . ts('A renewal confirmation and receipt has been sent to %1.', [
472 1 => $this->_contributorEmail,
473 ]);
474 return $statusMsg;
475 }
476 return $statusMsg;
477 }
478 catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
479 CRM_Core_Session::singleton()->setStatus($e->getMessage());
480 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership',
481 "reset=1&action=renew&cid={$this->_contactID}&id={$this->_id}&context=membership&mode={$this->_mode}"
482 ));
483 }
484
485 CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
486 }
487
488 /**
489 * Process form submission.
490 *
491 * This function is also accessed by a unit test.
492 */
493 protected function submit() {
494 $this->storeContactFields($this->_params);
495 $this->beginPostProcess();
496 $now = CRM_Utils_Date::getToday(NULL, 'YmdHis');
497 $this->assign('receive_date', CRM_Utils_Array::value('receive_date', $this->_params, date('Y-m-d H:i:s')));
498 $this->processBillingAddress();
499 list($userName) = CRM_Contact_BAO_Contact_Location::getEmailDetails(CRM_Core_Session::singleton()->get('userID'));
500 $this->_params['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_params,
501 CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'minimum_fee')
502 );
503 $this->_membershipId = $this->_id;
504 $customFieldsFormatted = CRM_Core_BAO_CustomField::postProcess($this->_params,
505 $this->_id,
506 'Membership'
507 );
508 if (empty($this->_params['financial_type_id'])) {
509 $this->_params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'financial_type_id');
510 }
511 $contributionRecurID = NULL;
512 $this->assign('membershipID', $this->_id);
513 $this->assign('contactID', $this->_contactID);
514 $this->assign('module', 'Membership');
515 $this->assign('receiptType', 'membership renewal');
516 $this->_params['currencyID'] = CRM_Core_Config::singleton()->defaultCurrency;
517 $this->_params['invoice_id'] = $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
518
519 if (!empty($this->_params['send_receipt'])) {
520 $this->_params['receipt_date'] = $now;
521 $this->assign('receipt_date', CRM_Utils_Date::mysqlToIso($this->_params['receipt_date']));
522 }
523 else {
524 $this->_params['receipt_date'] = NULL;
525 }
526
527 if ($this->_mode) {
528 $this->_params['register_date'] = $now;
529 $this->_params['description'] = ts("Contribution submitted by a staff person using member's credit card for renewal");
530 $this->_params['amount'] = $this->_params['total_amount'];
531 $this->_params['payment_instrument_id'] = $this->_paymentProcessor['payment_instrument_id'];
532
533 // at this point we've created a contact and stored its address etc
534 // all the payment processors expect the name and address to be in the passed params
535 // so we copy stuff over to first_name etc.
536 $paymentParams = $this->_params;
537 if (!empty($this->_params['send_receipt'])) {
538 $paymentParams['email'] = $this->_contributorEmail;
539 }
540 $paymentParams['is_email_receipt'] = !empty($this->_params['send_receipt']);
541
542 $paymentParams['contactID'] = $this->_contributorContactID;
543
544 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
545
546 $payment = $this->_paymentProcessor['object'];
547
548 if (!empty($this->_params['auto_renew'])) {
549 $contributionRecurParams = $this->processRecurringContribution($paymentParams);
550 $contributionRecurID = $contributionRecurParams['contributionRecurID'];
551 $paymentParams = array_merge($paymentParams, $contributionRecurParams);
552 }
553
554 $result = $payment->doPayment($paymentParams);
555 $this->_params = array_merge($this->_params, $result);
556
557 $this->_params['contribution_status_id'] = $result['payment_status_id'];
558 $this->_params['trxn_id'] = $result['trxn_id'];
559 $this->_params['is_test'] = ($this->_mode == 'live') ? 0 : 1;
560 $this->set('params', $this->_params);
561 $this->assign('trxn_id', $result['trxn_id']);
562 }
563
564 $renewalDate = !empty($this->_params['renewal_date']) ? $renewalDate = $this->_params['renewal_date'] : NULL;
565
566 // check for test membership.
567 $isTestMembership = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_membershipId, 'is_test');
568
569 // chk for renewal for multiple terms CRM-8750
570 $numRenewTerms = 1;
571 if (is_numeric(CRM_Utils_Array::value('num_terms', $this->_params))) {
572 $numRenewTerms = $this->_params['num_terms'];
573 }
574
575 //if contribution status is pending then set pay later
576 $this->_params['is_pay_later'] = FALSE;
577 if ($this->_params['contribution_status_id'] == array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus())) {
578 $this->_params['is_pay_later'] = 1;
579 }
580
581 // These variable sets prior to membership may not be required for this form. They were in
582 // a function this form shared with other forms.
583 $membershipSource = NULL;
584 if (!empty($this->_params['membership_source'])) {
585 $membershipSource = $this->_params['membership_source'];
586 }
587
588 $isPending = ($this->_params['contribution_status_id'] == 2) ? TRUE : FALSE;
589
590 list($membership) = CRM_Member_BAO_Membership::processMembership(
591 $this->_contactID, $this->_params['membership_type_id'][1], $isTestMembership,
592 $renewalDate, NULL, $customFieldsFormatted, $numRenewTerms, $this->_membershipId,
593 $isPending,
594 $contributionRecurID, $membershipSource, $this->_params['is_pay_later'], CRM_Utils_Array::value('campaign_id',
595 $this->_params)
596 );
597
598 $this->endDate = CRM_Utils_Date::processDate($membership->end_date);
599
600 $this->membershipTypeName = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $membership->membership_type_id,
601 'name');
602
603 if (!empty($this->_params['record_contribution']) || $this->_mode) {
604 // set the source
605 $this->_params['contribution_source'] = "{$this->membershipTypeName} Membership: Offline membership renewal (by {$userName})";
606
607 //create line items
608 $lineItem = [];
609 $this->_params = $this->setPriceSetParameters($this->_params);
610 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
611 $this->_params, $lineItem[$this->_priceSetId], NULL, $this->_priceSetId
612 );
613 //CRM-11529 for quick config backoffice transactions
614 //when financial_type_id is passed in form, update the
615 //line items with the financial type selected in form
616 if ($submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $this->_params)) {
617 foreach ($lineItem[$this->_priceSetId] as &$li) {
618 $li['financial_type_id'] = $submittedFinancialType;
619 }
620 }
621
622 if (!empty($lineItem)) {
623 $this->_params['lineItems'] = $lineItem;
624 $this->_params['processPriceSet'] = TRUE;
625 }
626
627 //assign contribution contact id to the field expected by recordMembershipContribution
628 if ($this->_contributorContactID != $this->_contactID) {
629 $this->_params['contribution_contact_id'] = $this->_contributorContactID;
630 if (!empty($this->_params['soft_credit_type_id'])) {
631 $this->_params['soft_credit'] = [
632 'soft_credit_type_id' => $this->_params['soft_credit_type_id'],
633 'contact_id' => $this->_contactID,
634 ];
635 }
636 }
637 $this->_params['contact_id'] = $this->_contactID;
638 //recordMembershipContribution receives params as a reference & adds one variable. This is
639 // not a great pattern & ideally it would not receive as a reference. We assign our params as a
640 // temporary variable to avoid e-notice & to make it clear to future refactorer that
641 // this function is NOT reliant on that var being set
642 $temporaryParams = array_merge($this->_params, [
643 'membership_id' => $membership->id,
644 'contribution_recur_id' => $contributionRecurID,
645 ]);
646 //Remove `tax_amount` if it is not calculated.
647 if (CRM_Utils_Array::value('tax_amount', $temporaryParams) === 0) {
648 unset($temporaryParams['tax_amount']);
649 }
650 CRM_Member_BAO_Membership::recordMembershipContribution($temporaryParams);
651 }
652
653 if (!empty($this->_params['send_receipt'])) {
654
655 $receiptFrom = $this->_params['from_email_address'];
656
657 if (!empty($this->_params['payment_instrument_id'])) {
658 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
659 $this->_params['paidBy'] = $paymentInstrument[$this->_params['payment_instrument_id']];
660 }
661 //get the group Tree
662 $this->_groupTree = CRM_Core_BAO_CustomGroup::getTree('Membership', NULL, $this->_id, FALSE, $this->_memType);
663
664 // retrieve custom data
665 $customFields = $customValues = $fo = [];
666 foreach ($this->_groupTree as $groupID => $group) {
667 if ($groupID == 'info') {
668 continue;
669 }
670 foreach ($group['fields'] as $k => $field) {
671 $field['title'] = $field['label'];
672 $customFields["custom_{$k}"] = $field;
673 }
674 }
675 $members = [['member_id', '=', $this->_membershipId, 0, 0]];
676 // check whether its a test drive
677 if ($this->_mode == 'test') {
678 $members[] = ['member_test', '=', 1, 0, 0];
679 }
680 CRM_Core_BAO_UFGroup::getValues($this->_contactID, $customFields, $customValues, FALSE, $members);
681
682 $this->assign_by_ref('formValues', $this->_params);
683 if (!empty($this->_params['contribution_id'])) {
684 $this->assign('contributionID', $this->_params['contribution_id']);
685 }
686
687 $this->assign('membership_name', CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
688 $membership->membership_type_id
689 ));
690 $this->assign('customValues', $customValues);
691 $this->assign('mem_start_date', CRM_Utils_Date::customFormat($membership->start_date));
692 $this->assign('mem_end_date', CRM_Utils_Date::customFormat($membership->end_date));
693 if ($this->_mode) {
694 $this->assign('address', CRM_Utils_Address::getFormattedBillingAddressFieldsFromParameters(
695 $this->_params,
696 $this->_bltID
697 ));
698 $this->assign('contributeMode', 'direct');
699 $this->assign('isAmountzero', 0);
700 $this->assign('is_pay_later', 0);
701 $this->assign('isPrimary', 1);
702 $this->assign('receipt_text_renewal', $this->_params['receipt_text']);
703 if ($this->_mode == 'test') {
704 $this->assign('action', '1024');
705 }
706 }
707
708 list($this->isMailSent) = CRM_Core_BAO_MessageTemplate::sendTemplate(
709 [
710 'groupName' => 'msg_tpl_workflow_membership',
711 'valueName' => 'membership_offline_receipt',
712 'contactId' => $this->_receiptContactId,
713 'from' => $receiptFrom,
714 'toName' => $this->_contributorDisplayName,
715 'toEmail' => $this->_contributorEmail,
716 'isTest' => $this->_mode == 'test',
717 ]
718 );
719 }
720 }
721
722 }