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