1773369618c724cbb9b4a47c67f64b37873ddf89
[civicrm-core.git] / CRM / Member / Form / MembershipRenewal.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
32 * $Id$
33 *
34 */
35
36 /**
37 * This class generates form components for Membership Renewal
38 *
39 */
40 class CRM_Member_Form_MembershipRenewal extends CRM_Member_Form {
41
42 /**
43 * Display name of the member.
44 *
45 * @var string
46 */
47 protected $_memberDisplayName = NULL;
48
49 /**
50 * email of the person paying for the membership (used for receipts)
51 */
52 protected $_memberEmail = NULL;
53
54 /**
55 * Contact ID of the member.
56 *
57 *
58 * @var int
59 */
60 public $_contactID = NULL;
61
62 /**
63 * Display name of the person paying for the membership (used for receipts)
64 *
65 * @var string
66 */
67 protected $_contributorDisplayName = NULL;
68
69 /**
70 * email of the person paying for the membership (used for receipts)
71 */
72 protected $_contributorEmail = NULL;
73
74 /**
75 * email of the person paying for the membership (used for receipts)
76 *
77 * @var int
78 */
79 protected $_contributorContactID = NULL;
80
81 /**
82 * ID of the person the receipt is to go to
83 *
84 * @var int
85 */
86 protected $_receiptContactId = NULL;
87
88 /**
89 * context would be set to standalone if the contact is use is being selected from
90 * the form rather than in the URL
91 */
92 public $_context;
93
94 /**
95 * An array to hold a list of datefields on the form
96 * so that they can be converted to ISO in a consistent manner
97 *
98 * @var array
99 */
100 protected $_dateFields = array(
101 'receive_date' => array('default' => 'now'),
102 );
103
104 public function preProcess() {
105
106 // This string makes up part of the class names, differentiating them (not sure why) from the membership fields.
107 $this->assign('formClass', 'membershiprenew');
108 parent::preProcess();
109 // check for edit permission
110 if (!CRM_Core_Permission::check('edit memberships')) {
111 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
112 }
113
114 $this->assign('endDate', CRM_Utils_Date::customFormat(CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
115 $this->_id, 'end_date'
116 )
117 ));
118 $this->assign('membershipStatus',
119 CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus',
120 CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
121 $this->_id, 'status_id'
122 ),
123 'name'
124 )
125 );
126
127 if ($this->_mode) {
128 $membershipFee = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'minimum_fee');
129 if (!$membershipFee) {
130 $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.');
131 CRM_Core_Session::setStatus($statusMsg, '', 'info');
132 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership',
133 "reset=1&action=renew&cid={$this->_contactID}&id={$this->_id}&context=membership"
134 ));
135 }
136 }
137
138 // when custom data is included in this page
139 if (!empty($_POST['hidden_custom'])) {
140 CRM_Custom_Form_CustomData::preProcess($this);
141 CRM_Custom_Form_CustomData::buildQuickForm($this);
142 CRM_Custom_Form_CustomData::setDefaultValues($this);
143 }
144
145 CRM_Utils_System::setTitle(ts('Renew Membership'));
146 }
147
148 /**
149 * Set default values for the form.
150 * the default values are retrieved from the database
151 *
152 * @return array
153 * Default values.
154 */
155 public function setDefaultValues() {
156
157 $defaults = parent::setDefaultValues();
158 $this->_memType = $defaults['membership_type_id'];
159
160 // set renewal_date and receive_date to today in correct input format (setDateDefaults uses today if no value passed)
161 list($now, $currentTime) = CRM_Utils_Date::setDateDefaults();
162 $defaults['renewal_date'] = $now;
163 $defaults['receive_date'] = $now;
164 $defaults['receive_date_time'] = $currentTime;
165
166 if ($defaults['id']) {
167 $defaults['record_contribution'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment',
168 $defaults['id'],
169 'contribution_id',
170 'membership_id'
171 );
172 }
173
174 if (is_numeric($this->_memType)) {
175 $defaults['membership_type_id'] = array();
176 $defaults['membership_type_id'][0] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
177 $this->_memType,
178 'member_of_contact_id',
179 'id'
180 );
181 $defaults['membership_type_id'][1] = $this->_memType;
182 }
183 else {
184 $defaults['membership_type_id'] = $this->_memType;
185 }
186
187 $defaults['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'financial_type_id');
188
189 //CRM-13420
190 if (empty($defaults['payment_instrument_id'])) {
191 $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
192 }
193
194 $defaults['total_amount'] = CRM_Utils_Money::format(CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
195 $this->_memType,
196 'minimum_fee'
197 ), NULL, '%a');
198
199 $defaults['record_contribution'] = 0;
200 $defaults['num_terms'] = 1;
201 $defaults['send_receipt'] = 0;
202
203 //set Soft Credit Type to Gift by default
204 $scTypes = CRM_Core_OptionGroup::values("soft_credit_type");
205 $defaults['soft_credit_type_id'] = CRM_Utils_Array::value(ts('Gift'), array_flip($scTypes));
206
207 $renewalDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('renewal_date', $defaults),
208 NULL, NULL, 'Y-m-d'
209 );
210 $this->assign('renewalDate', $renewalDate);
211 $this->assign('member_is_test', CRM_Utils_Array::value('member_is_test', $defaults));
212
213 if ($this->_mode) {
214 // set default country from config if no country set
215 $config = CRM_Core_Config::singleton();
216 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
217 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry;
218 }
219
220 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
221 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince;
222 }
223
224 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID);
225 $defaults = array_merge($defaults, $billingDefaults);
226
227 }
228 return $defaults;
229 }
230
231 /**
232 * Build the form object.
233 */
234 public function buildQuickForm() {
235
236 parent::buildQuickForm();
237
238 $defaults = parent::setDefaultValues();
239 $this->_memType = $defaults['membership_type_id'];
240 $this->assign('customDataType', 'Membership');
241 $this->assign('customDataSubType', $this->_memType);
242 $this->assign('entityID', $this->_id);
243 $selOrgMemType[0][0] = $selMemTypeOrg[0] = ts('- select -');
244
245 $allMembershipInfo = array();
246
247 // auto renew options if enabled for the membership
248 $options = CRM_Core_SelectValues::memberAutoRenew();
249
250 foreach ($this->allMembershipTypeDetails as $key => $values) {
251 if (!empty($values['is_active'])) {
252 if ($this->_mode && empty($values['minimum_fee'])) {
253 continue;
254 }
255 else {
256 $memberOfContactId = CRM_Utils_Array::value('member_of_contact_id', $values);
257 if (empty($selMemTypeOrg[$memberOfContactId])) {
258 $selMemTypeOrg[$memberOfContactId] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
259 $memberOfContactId,
260 'display_name',
261 'id'
262 );
263
264 $selOrgMemType[$memberOfContactId][0] = ts('- select -');
265 }
266 if (empty($selOrgMemType[$memberOfContactId][$key])) {
267 $selOrgMemType[$memberOfContactId][$key] = CRM_Utils_Array::value('name', $values);
268 }
269 }
270
271 // build membership info array, which is used to set the payment information block when
272 // membership type is selected.
273 $allMembershipInfo[$key] = array(
274 'financial_type_id' => CRM_Utils_Array::value('financial_type_id', $values),
275 'total_amount' => CRM_Utils_Money::format($values['minimum_fee'], NULL, '%a'),
276 'total_amount_numeric' => CRM_Utils_Array::value('minimum_fee', $values),
277 );
278
279 if (!empty($values['auto_renew'])) {
280 $allMembershipInfo[$key]['auto_renew'] = $options[$values['auto_renew']];
281 }
282 }
283 }
284
285 $this->assign('allMembershipInfo', json_encode($allMembershipInfo));
286
287 if ($this->_memType) {
288 $this->assign('orgName', $selMemTypeOrg[$this->allMembershipTypeDetails[$this->_memType]['member_of_contact_id']]);
289 $this->assign('memType', $this->allMembershipTypeDetails[$this->_memType]['name']);
290 }
291
292 // force select of organization by default, if only one organization in
293 // the list
294 if (count($selMemTypeOrg) == 2) {
295 unset($selMemTypeOrg[0], $selOrgMemType[0][0]);
296 }
297 //sort membership organization and type, CRM-6099
298 natcasesort($selMemTypeOrg);
299 foreach ($selOrgMemType as $index => $orgMembershipType) {
300 natcasesort($orgMembershipType);
301 $selOrgMemType[$index] = $orgMembershipType;
302 }
303
304 $js = array('onChange' => "setPaymentBlock(); CRM.buildCustomData('Membership', this.value);");
305 $sel = &$this->addElement('hierselect',
306 'membership_type_id',
307 ts('Renewal Membership Organization and Type'), $js
308 );
309
310 $sel->setOptions(array($selMemTypeOrg, $selOrgMemType));
311 $elements = array();
312 if ($sel) {
313 $elements[] = $sel;
314 }
315
316 $this->applyFilter('__ALL__', 'trim');
317
318 $this->addDate('renewal_date', ts('Date Renewal Entered'), FALSE, array('formatType' => 'activityDate'));
319
320 $this->add('select', 'financial_type_id', ts('Financial Type'),
321 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::financialType()
322 );
323 if (CRM_Core_Permission::access('CiviContribute') && !$this->_mode) {
324 $this->addElement('checkbox', 'record_contribution', ts('Record Renewal Payment?'), NULL, array('onclick' => "checkPayment();"));
325
326 $this->add('text', 'total_amount', ts('Amount'));
327 $this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
328
329 $this->addDate('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
330
331 $this->add('text', 'num_terms', ts('Extend Membership by'), array('onchange' => "setPaymentBlock();"), TRUE);
332 $this->addRule('num_terms', ts('Please enter a whole number for how many periods to renew.'), 'integer');
333
334 $this->add('select', 'payment_instrument_id', ts('Paid By'),
335 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(),
336 FALSE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
337 );
338
339 $this->add('text', 'trxn_id', ts('Transaction ID'));
340 $this->addRule('trxn_id', ts('Transaction ID already exists in Database.'),
341 'objectExists', array('CRM_Contribute_DAO_Contribution', $this->_id, 'trxn_id')
342 );
343
344 $this->add('select', 'contribution_status_id', ts('Payment Status'),
345 CRM_Contribute_PseudoConstant::contributionStatus()
346 );
347
348 $this->add('text', 'check_number', ts('Check Number'),
349 CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution', 'check_number')
350 );
351 }
352 else {
353 $this->add('text', 'total_amount', ts('Amount'));
354 $this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
355 }
356 $this->addElement('checkbox', 'send_receipt', ts('Send Confirmation and Receipt?'), NULL,
357 array('onclick' => "showHideByValue( 'send_receipt', '', 'notice', 'table-row', 'radio', false ); showHideByValue( 'send_receipt', '', 'fromEmail', 'table-row', 'radio',false);")
358 );
359
360 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
361
362 $this->add('textarea', 'receipt_text_renewal', ts('Renewal Message'));
363
364 // Retrieve the name and email of the contact - this will be the TO for receipt email
365 list($this->_contributorDisplayName,
366 $this->_contributorEmail
367 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
368 $this->assign('email', $this->_contributorEmail);
369 // The member form uses emailExists. Assigning both while we transition / synchronise.
370 $this->assign('emailExists', $this->_contributorEmail);
371
372 $mailingInfo = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
373 'mailing_backend'
374 );
375 $this->assign('outBound_option', $mailingInfo['outBound_option']);
376
377 if (CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_id, 'contribution_recur_id')) {
378 if (CRM_Member_BAO_Membership::isCancelSubscriptionSupported($this->_id)) {
379 $this->assign('cancelAutoRenew',
380 CRM_Utils_System::url('civicrm/contribute/unsubscribe', "reset=1&mid={$this->_id}")
381 );
382 }
383 }
384 $this->addFormRule(array('CRM_Member_Form_MembershipRenewal', 'formRule'));
385 $this->addElement('checkbox', 'is_different_contribution_contact', ts('Record Payment from a Different
386 Contact?'));
387 $this->addSelect('soft_credit_type_id', array('entity' => 'contribution_soft'));
388 $this->addEntityRef('soft_credit_contact_id', ts('Payment From'), array('create' => TRUE));
389 }
390
391 /**
392 * Validation.
393 *
394 * @param array $params
395 * (ref.) an assoc array of name/value pairs.
396 *
397 * @return bool|array
398 * mixed true or array of errors
399 */
400 public static function formRule($params) {
401 $errors = array();
402 if ($params['membership_type_id'][0] == 0) {
403 $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.');
404 }
405 if ($params['membership_type_id'][1] == 0) {
406 $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.');
407 }
408
409 //total amount condition arise when membership type having no
410 //minimum fee
411 if (isset($params['record_contribution'])) {
412 if (!$params['financial_type_id']) {
413 $errors['financial_type_id'] = ts('Please select a Financial Type.');
414 }
415 if (!$params['total_amount']) {
416 $errors['total_amount'] = ts('Please enter a Contribution Amount.');
417 }
418 if (empty($params['payment_instrument_id'])) {
419 $errors['payment_instrument_id'] = ts('Paid By is a required field.');
420 }
421 }
422 return empty($errors) ? TRUE : $errors;
423 }
424
425 /**
426 * Process the renewal form.
427 *
428 *
429 * @return void
430 */
431 public function postProcess() {
432 // get the submitted form values.
433 $this->_params = $formValues = $this->controller->exportValues($this->_name);
434
435 $statusMsg = $this->submit($formValues);
436
437 CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
438 }
439
440 /**
441 * Determine if the form has a pending status.
442 *
443 * @deprecated
444 *
445 * @param CRM_Core_Form $form
446 * @param int $membershipID
447 *
448 * @return bool
449 */
450 public static function extractPendingFormValue($form, $membershipID) {
451 $membershipTypeDetails = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($membershipID);
452 $pending = FALSE;
453 // @todo function was shared by 2 not-very-related forms & the below may include irrelevant stuff.
454 if (CRM_Utils_Array::value('minimum_fee', $membershipTypeDetails) > 0.0) {
455 if (((isset($form->_contributeMode) && $form->_contributeMode == 'notify') || !empty($form->_params['is_pay_later'])
456 ) &&
457 (($form->_values['is_monetary'] && $form->_amount > 0.0) ||
458 CRM_Utils_Array::value('record_contribution', $form->_params)
459 )
460 ) {
461 $pending = TRUE;
462 }
463 }
464 return $pending;
465 }
466
467 /**
468 * Process form submission.
469 *
470 * This function is also accessed by a unit test.
471 *
472 * @param array $formValues
473 * Submitted values.
474 *
475 * @return array
476 */
477 protected function submit($formValues) {
478 $this->storeContactFields($formValues);
479 // use values from screen
480
481 if ($formValues['membership_type_id'][1] <> 0) {
482 $defaults['receipt_text_renewal'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
483 $formValues['membership_type_id'][1],
484 'receipt_text_renewal'
485 );
486 }
487
488 $now = CRM_Utils_Date::getToday(NULL, 'YmdHis');
489 $this->convertDateFieldsToMySQL($formValues);
490 $this->assign('receive_date', $formValues['receive_date']);
491
492 if (!empty($this->_params['send_receipt'])) {
493 $formValues['receipt_date'] = $now;
494 $this->assign('receipt_date', CRM_Utils_Date::mysqlToIso($formValues['receipt_date']));
495 }
496 else {
497 $formValues['receipt_date'] = NULL;
498 }
499
500 if ($this->_mode) {
501 $formValues['total_amount'] = CRM_Utils_Array::value('total_amount', $formValues,
502 CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'minimum_fee')
503 );
504 if (empty($formValues['financial_type_id'])) {
505 $formValues['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'financial_type_id');
506 }
507
508 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($formValues['payment_processor_id']);
509
510 $fields = array();
511
512 // set email for primary location.
513 $fields['email-Primary'] = 1;
514 $formValues['email-5'] = $formValues['email-Primary'] = $this->_contributorEmail;
515 $formValues['register_date'] = $now;
516
517 // now set the values for the billing location.
518 foreach ($this->_fields as $name => $dontCare) {
519 $fields[$name] = 1;
520 }
521
522 // also add location name to the array
523 $formValues["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_middle_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_last_name', $formValues);
524
525 $formValues["address_name-{$this->_bltID}"] = trim($formValues["address_name-{$this->_bltID}"]);
526
527 $fields["address_name-{$this->_bltID}"] = 1;
528
529 $fields["email-{$this->_bltID}"] = 1;
530
531 $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type');
532
533 $nameFields = array('first_name', 'middle_name', 'last_name');
534
535 foreach ($nameFields as $name) {
536 $fields[$name] = 1;
537 if (array_key_exists("billing_$name", $formValues)) {
538 $formValues[$name] = $formValues["billing_{$name}"];
539 $formValues['preserveDBName'] = TRUE;
540 }
541 }
542
543 //here we are setting up the billing contact - if different from the member they are already created
544 // but they will get billing details assigned
545 CRM_Contact_BAO_Contact::createProfileContact($formValues, $fields,
546 $this->_contributorContactID, NULL, NULL, $ctype
547 );
548
549 // add all the additional payment params we need
550 $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"]
551 = CRM_Core_PseudoConstant::stateProvinceAbbreviation($formValues["billing_state_province_id-{$this->_bltID}"]);
552 $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"]
553 = CRM_Core_PseudoConstant::countryIsoCode($formValues["billing_country_id-{$this->_bltID}"]);
554
555 $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($formValues);
556 $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($formValues);
557 $this->_params['description'] = ts('Office Credit Card Membership Renewal Contribution');
558 $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
559 $this->_params['amount'] = $formValues['total_amount'];
560 $this->_params['currencyID'] = CRM_Core_Config::singleton()->defaultCurrency;
561 $paymentParams['invoiceID'] = $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
562
563 // at this point we've created a contact and stored its address etc
564 // all the payment processors expect the name and address to be in the passed params
565 // so we copy stuff over to first_name etc.
566 $paymentParams = $this->_params;
567 if (!empty($this->_params['send_receipt'])) {
568 $paymentParams['email'] = $this->_contributorEmail;
569 }
570
571 $paymentParams['contactID'] = $this->_contributorContactID;
572
573 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
574
575 $payment = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
576
577 if (!empty($paymentParams['auto_renew'])) {
578 $contributionRecurParams = $this->processRecurringContribution($paymentParams);
579 $paymentParams = array_merge($paymentParams, $contributionRecurParams);
580 }
581 $result = $payment->doDirectPayment($paymentParams);
582
583 if (is_a($result, 'CRM_Core_Error')) {
584 CRM_Core_Error::displaySessionError($result);
585 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership',
586 "reset=1&action=renew&cid={$this->_contactID}&id={$this->_id}&context=membership&mode={$this->_mode}"
587 ));
588 }
589
590 if ($result) {
591 $this->_params = array_merge($this->_params, $result);
592 }
593 $formValues['contribution_status_id'] = 1;
594 $formValues['invoice_id'] = $this->_params['invoiceID'];
595 $formValues['trxn_id'] = $result['trxn_id'];
596 $formValues['payment_instrument_id'] = 1;
597 $formValues['is_test'] = ($this->_mode == 'live') ? 0 : 1;
598 $this->set('params', $this->_params);
599 $this->assign('trxn_id', $result['trxn_id']);
600 }
601
602 $renewalDate = !empty($formValues['renewal_date']) ? $renewalDate = CRM_Utils_Date::processDate($formValues['renewal_date']) : NULL;
603
604 // This set is probably obsolete.
605 $this->set('renewalDate', $renewalDate);
606
607 $this->_membershipId = $this->_id;
608
609 $customFieldsFormatted = CRM_Core_BAO_CustomField::postProcess($formValues,
610 $this->_id,
611 'Membership'
612 );
613
614 // check for test membership.
615 $isTestMembership = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_membershipId, 'is_test');
616
617 // chk for renewal for multiple terms CRM-8750
618 $numRenewTerms = 1;
619 if (is_numeric(CRM_Utils_Array::value('num_terms', $formValues))) {
620 $numRenewTerms = $formValues['num_terms'];
621 }
622
623 //if contribution status is pending then set pay later
624 if ($formValues['contribution_status_id'] == array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus())) {
625 $this->_params['is_pay_later'] = 1;
626 }
627
628 // These variable sets prior to renewMembership may not be required for this form. They were in
629 // a function this form shared with other forms.
630 $contributionRecurID = isset($this->_params['contributionRecurID']) ? $this->_params['contributionRecurID'] : NULL;
631 $membershipSource = NULL;
632 if (!empty($this->_params['membership_source'])) {
633 $membershipSource = $this->_params['membership_source'];
634 }
635 $isPayLater = NULL;
636 if (isset($this->_params)) {
637 $isPayLater = CRM_Utils_Array::value('is_pay_later', $this->_params);
638 }
639 $campaignId = NULL;
640 if (isset($this->_values) && is_array($this->_values) && !empty($this->_values)) {
641 $campaignId = CRM_Utils_Array::value('campaign_id', $this->_params);
642 if (!array_key_exists('campaign_id', $this->_params)) {
643 $campaignId = CRM_Utils_Array::value('campaign_id', $this->_values);
644 }
645 }
646
647 list($renewMembership) = CRM_Member_BAO_Membership::renewMembership(
648 $this->_contactID, $formValues['membership_type_id'][1], $isTestMembership,
649 $renewalDate, NULL, $customFieldsFormatted, $numRenewTerms, $this->_membershipId,
650 self::extractPendingFormValue($this, $formValues['membership_type_id'][1]),
651 $contributionRecurID, $membershipSource, $isPayLater, $campaignId
652 );
653
654 $endDate = CRM_Utils_Date::processDate($renewMembership->end_date);
655
656 list($userName) = CRM_Contact_BAO_Contact_Location::getEmailDetails(CRM_Core_Session::singleton()->get('userID'));
657
658 $memType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $renewMembership->membership_type_id, 'name');
659
660 if (!empty($formValues['record_contribution']) || $this->_mode) {
661 // set the source
662 $formValues['contribution_source'] = "{$memType} Membership: Offline membership renewal (by {$userName})";
663
664 //create line items
665 $lineItem = array();
666
667 $priceSetId = CRM_Member_BAO_Membership::createLineItems($this, $formValues['membership_type_id']);
668 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
669 $this->_params, $lineItem[$priceSetId]
670 );
671 //CRM-11529 for quick config backoffice transactions
672 //when financial_type_id is passed in form, update the
673 //line items with the financial type selected in form
674 if ($submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $formValues)) {
675 foreach ($lineItem[$priceSetId] as &$li) {
676 $li['financial_type_id'] = $submittedFinancialType;
677 }
678 }
679 $formValues['total_amount'] = CRM_Utils_Array::value('amount', $this->_params);
680 if (!empty($lineItem)) {
681 $formValues['lineItems'] = $lineItem;
682 $formValues['processPriceSet'] = TRUE;
683 }
684
685 //assign contribution contact id to the field expected by recordMembershipContribution
686 if ($this->_contributorContactID != $this->_contactID) {
687 $formValues['contribution_contact_id'] = $this->_contributorContactID;
688 if (!empty($this->_params['soft_credit_type_id'])) {
689 $formValues['soft_credit'] = array(
690 'soft_credit_type_id' => $this->_params['soft_credit_type_id'],
691 'contact_id' => $this->_contactID,
692 );
693 }
694 }
695 $formValues['contact_id'] = $this->_contactID;
696 //recordMembershipContribution receives params as a reference & adds one variable. This is
697 // not a great pattern & ideally it would not receive as a reference. We assign our params as a
698 // temporary variable to avoid e-notice & to make it clear to future refactorer that
699 // this function is NOT reliant on that var being set
700 $temporaryParams = array_merge($formValues, array('membership_id' => $renewMembership->id));
701 CRM_Member_BAO_Membership::recordMembershipContribution($temporaryParams);
702 }
703
704 $receiptSend = FALSE;
705 if (!empty($formValues['send_receipt'])) {
706 $receiptSend = TRUE;
707
708 $receiptFrom = $formValues['from_email_address'];
709
710 if (!empty($formValues['payment_instrument_id'])) {
711 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
712 $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
713 }
714 //get the group Tree
715 $this->_groupTree = CRM_Core_BAO_CustomGroup::getTree('Membership', $this, $this->_id, FALSE, $this->_memType);
716
717 // retrieve custom data
718 $customFields = $customValues = $fo = array();
719 foreach ($this->_groupTree as $groupID => $group) {
720 if ($groupID == 'info') {
721 continue;
722 }
723 foreach ($group['fields'] as $k => $field) {
724 $field['title'] = $field['label'];
725 $customFields["custom_{$k}"] = $field;
726 }
727 }
728 $members = array(array('member_id', '=', $this->_membershipId, 0, 0));
729 // check whether its a test drive
730 if ($this->_mode == 'test') {
731 $members[] = array('member_test', '=', 1, 0, 0);
732 }
733 CRM_Core_BAO_UFGroup::getValues($this->_contactID, $customFields, $customValues, FALSE, $members);
734
735 $this->assign_by_ref('formValues', $formValues);
736 if (!empty($formValues['contribution_id'])) {
737 $this->assign('contributionID', $formValues['contribution_id']);
738 }
739 $this->assign('membershipID', $this->_id);
740 $this->assign('contactID', $this->_contactID);
741 $this->assign('module', 'Membership');
742 $this->assign('receiptType', 'membership renewal');
743 $this->assign('mem_start_date', CRM_Utils_Date::customFormat($renewMembership->start_date));
744 $this->assign('mem_end_date', CRM_Utils_Date::customFormat($renewMembership->end_date));
745 $this->assign('membership_name', CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
746 $renewMembership->membership_type_id
747 ));
748 $this->assign('customValues', $customValues);
749 if ($this->_mode) {
750 if (!empty($this->_params['billing_first_name'])) {
751 $name = $this->_params['billing_first_name'];
752 }
753
754 if (!empty($this->_params['billing_middle_name'])) {
755 $name .= " {$this->_params['billing_middle_name']}";
756 }
757
758 if (!empty($this->_params['billing_last_name'])) {
759 $name .= " {$this->_params['billing_last_name']}";
760 }
761 $this->assign('billingName', $name);
762
763 // assign the address formatted up for display
764 $addressParts = array(
765 "street_address-{$this->_bltID}",
766 "city-{$this->_bltID}",
767 "postal_code-{$this->_bltID}",
768 "state_province-{$this->_bltID}",
769 "country-{$this->_bltID}",
770 );
771 $addressFields = array();
772 foreach ($addressParts as $part) {
773 list($n, $id) = explode('-', $part);
774 if (isset($this->_params['billing_' . $part])) {
775 $addressFields[$n] = $this->_params['billing_' . $part];
776 }
777 }
778 $this->assign('address', CRM_Utils_Address::format($addressFields));
779 $date = CRM_Utils_Date::format($this->_params['credit_card_exp_date']);
780 $date = CRM_Utils_Date::mysqlToIso($date);
781 $this->assign('credit_card_exp_date', $date);
782 $this->assign('credit_card_number',
783 CRM_Utils_System::mungeCreditCard($this->_params['credit_card_number'])
784 );
785 $this->assign('credit_card_type', $this->_params['credit_card_type']);
786 $this->assign('contributeMode', 'direct');
787 $this->assign('isAmountzero', 0);
788 $this->assign('is_pay_later', 0);
789 $this->assign('isPrimary', 1);
790 $this->assign('receipt_text_renewal', $this->_params['receipt_text']);
791 if ($this->_mode == 'test') {
792 $this->assign('action', '1024');
793 }
794 }
795
796 list($mailSend) = CRM_Core_BAO_MessageTemplate::sendTemplate(
797 array(
798 'groupName' => 'msg_tpl_workflow_membership',
799 'valueName' => 'membership_offline_receipt',
800 'contactId' => $this->_receiptContactId,
801 'from' => $receiptFrom,
802 'toName' => $this->_contributorDisplayName,
803 'toEmail' => $this->_contributorEmail,
804 'isTest' => $this->_mode == 'test',
805 )
806 );
807 }
808
809 $statusMsg = ts('%1 membership for %2 has been renewed.', array(1 => $memType, 2 => $this->_memberDisplayName));
810
811 if ($endDate) {
812 $statusMsg .= ' ' . ts('The new membership End Date is %1.', array(1 => CRM_Utils_Date::customFormat(substr($endDate, 0, 8))));
813 }
814
815 if ($receiptSend && $mailSend) {
816 $statusMsg .= ' ' . ts('A renewal confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
817 return $statusMsg;
818 }
819 return $statusMsg;
820 }
821
822 /**
823 * Wrapper function for unit tests.
824 *
825 * @param array $formValues
826 */
827 public function testSubmit($formValues) {
828 $this->_memType = $formValues['membership_type_id'][1];
829 $this->submit($formValues);
830 }
831
832 }