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