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