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