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