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