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