Convert membership date fields to datepicker & form to entity form
[civicrm-core.git] / CRM / Member / Form.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
32 */
33
34 /**
35 * Base class for offline membership / membership type / membership renewal and membership status forms
36 *
37 */
38 class CRM_Member_Form extends CRM_Contribute_Form_AbstractEditPayment {
39
40 use CRM_Core_Form_EntityFormTrait;
41 /**
42 * The id of the object being edited / created
43 *
44 * @var int
45 */
46 public $_id;
47
48 /**
49 * Membership Type ID
50 * @var
51 */
52 protected $_memType;
53
54 /**
55 * Array of from email ids
56 * @var array
57 */
58 protected $_fromEmails = array();
59
60 /**
61 * Details of all enabled membership types.
62 *
63 * @var array
64 */
65 protected $allMembershipTypeDetails = array();
66
67 /**
68 * Array of membership type IDs and whether they permit autorenewal.
69 *
70 * @var array
71 */
72 protected $membershipTypeRenewalStatus = array();
73
74 /**
75 * Price set ID configured for the form.
76 *
77 * @var int
78 */
79 public $_priceSetId;
80
81 /**
82 * Price set details as an array.
83 *
84 * @var array
85 */
86 public $_priceSet;
87
88 /**
89 * Explicitly declare the entity api name.
90 */
91 public function getDefaultEntity() {
92 return 'Membership';
93 }
94
95 /**
96 * Values submitted to the form, processed along the way.
97 *
98 * @var array
99 */
100 protected $_params = array();
101
102 /**
103 * Fields for the entity to be assigned to the template.
104 *
105 * Fields may have keys
106 * - name (required to show in tpl from the array)
107 * - description (optional, will appear below the field)
108 * - not-auto-addable - this class will not attempt to add the field using addField.
109 * (this will be automatically set if the field does not have html in it's metadata
110 * or is not a core field on the form's entity).
111 * - help (option) add help to the field - e.g ['id' => 'id-source', 'file' => 'CRM/Contact/Form/Contact']]
112 * - template - use a field specific template to render this field
113 * - required
114 * - is_freeze (field should be frozen).
115 *
116 * @var array
117 */
118 protected $entityFields = [];
119
120 public function preProcess() {
121 // Check for edit permission.
122 if (!CRM_Core_Permission::checkActionPermission('CiviMember', $this->_action)) {
123 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
124 }
125 if (!CRM_Member_BAO_Membership::statusAvailabilty()) {
126 // all possible statuses are disabled - redirect back to contact form
127 CRM_Core_Error::statusBounce(ts('There are no configured membership statuses. You cannot add this membership until your membership statuses are correctly configured'));
128 }
129
130 parent::preProcess();
131 $params = array();
132 $params['context'] = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this, FALSE, 'membership');
133 $params['id'] = CRM_Utils_Request::retrieve('id', 'Positive', $this);
134 $params['mode'] = CRM_Utils_Request::retrieve('mode', 'Alphanumeric', $this);
135
136 $this->setContextVariables($params);
137
138 $this->assign('context', $this->_context);
139 $this->assign('membershipMode', $this->_mode);
140 $this->allMembershipTypeDetails = CRM_Member_BAO_Membership::buildMembershipTypeValues($this, array(), TRUE);
141 foreach ($this->allMembershipTypeDetails as $index => $membershipType) {
142 if ($membershipType['auto_renew']) {
143 $this->_recurMembershipTypes[$index] = $membershipType;
144 $this->membershipTypeRenewalStatus[$index] = $membershipType['auto_renew'];
145 }
146 }
147 }
148
149 /**
150 * Set default values for the form. MobileProvider that in edit/view mode
151 * the default values are retrieved from the database
152 *
153 *
154 * @return array
155 * defaults
156 */
157 public function setDefaultValues() {
158 $defaults = array();
159 if (isset($this->_id)) {
160 $params = array('id' => $this->_id);
161 CRM_Member_BAO_Membership::retrieve($params, $defaults);
162 if (isset($defaults['minimum_fee'])) {
163 $defaults['minimum_fee'] = CRM_Utils_Money::format($defaults['minimum_fee'], NULL, '%a');
164 }
165
166 if (isset($defaults['status'])) {
167 $this->assign('membershipStatus', $defaults['status']);
168 }
169
170 if (!empty($defaults['is_override'])) {
171 $defaults['is_override'] = CRM_Member_StatusOverrideTypes::PERMANENT;
172 }
173 if (!empty($defaults['status_override_end_date'])) {
174 $defaults['is_override'] = CRM_Member_StatusOverrideTypes::UNTIL_DATE;
175 }
176 }
177
178 if ($this->_action & CRM_Core_Action::ADD) {
179 $defaults['is_active'] = 1;
180 }
181
182 if (isset($defaults['member_of_contact_id']) &&
183 $defaults['member_of_contact_id']
184 ) {
185 $defaults['member_org'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
186 $defaults['member_of_contact_id'], 'display_name'
187 );
188 }
189 if (!empty($defaults['membership_type_id'])) {
190 $this->_memType = $defaults['membership_type_id'];
191 }
192 if (is_numeric($this->_memType)) {
193 $defaults['membership_type_id'] = array();
194 $defaults['membership_type_id'][0] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
195 $this->_memType,
196 'member_of_contact_id',
197 'id'
198 );
199 $defaults['membership_type_id'][1] = $this->_memType;
200 }
201 else {
202 $defaults['membership_type_id'] = $this->_memType;
203 }
204 return $defaults;
205 }
206
207 /**
208 * Build the form object.
209 */
210 public function buildQuickForm() {
211 $this->assignSalesTaxMetadataToTemplate();
212
213 $this->addPaymentProcessorSelect(TRUE, FALSE, TRUE);
214 CRM_Core_Payment_Form::buildPaymentForm($this, $this->_paymentProcessor, FALSE, TRUE, $this->getDefaultPaymentInstrumentId());
215 // Build the form for auto renew. This is displayed when in credit card mode or update mode.
216 // The reason for showing it in update mode is not that clear.
217 if ($this->_mode || ($this->_action & CRM_Core_Action::UPDATE)) {
218 if (!empty($this->_recurPaymentProcessors)) {
219 $this->assign('allowAutoRenew', TRUE);
220 }
221
222 $autoRenewElement = $this->addElement('checkbox', 'auto_renew', ts('Membership renewed automatically'),
223 NULL, array('onclick' => "showHideByValue('auto_renew','','send-receipt','table-row','radio',true); showHideNotice( );")
224 );
225 if ($this->_action & CRM_Core_Action::UPDATE) {
226 $autoRenewElement->freeze();
227 }
228
229 $this->assign('recurProcessor', json_encode($this->_recurPaymentProcessors));
230 $this->addElement('checkbox',
231 'auto_renew',
232 ts('Membership renewed automatically')
233 );
234
235 }
236 $this->assign('autoRenewOptions', json_encode($this->membershipTypeRenewalStatus));
237
238 if ($this->_action & CRM_Core_Action::RENEW) {
239 $this->addButtons(array(
240 array(
241 'type' => 'upload',
242 'name' => ts('Renew'),
243 'isDefault' => TRUE,
244 ),
245 array(
246 'type' => 'cancel',
247 'name' => ts('Cancel'),
248 ),
249 ));
250 }
251 elseif ($this->_action & CRM_Core_Action::DELETE) {
252 $this->addButtons(array(
253 array(
254 'type' => 'next',
255 'name' => ts('Delete'),
256 'isDefault' => TRUE,
257 ),
258 array(
259 'type' => 'cancel',
260 'name' => ts('Cancel'),
261 ),
262 ));
263 }
264 else {
265 $this->addButtons(array(
266 array(
267 'type' => 'upload',
268 'name' => ts('Save'),
269 'isDefault' => TRUE,
270 ),
271 array(
272 'type' => 'upload',
273 'name' => ts('Save and New'),
274 'subName' => 'new',
275 ),
276 array(
277 'type' => 'cancel',
278 'name' => ts('Cancel'),
279 ),
280 ));
281 }
282 }
283
284 /**
285 * Extract values from the contact create boxes on the form and assign appropriately to
286 *
287 * - $this->_contributorEmail,
288 * - $this->_memberEmail &
289 * - $this->_contributionName
290 * - $this->_memberName
291 * - $this->_contactID (effectively memberContactId but changing might have spin-off effects)
292 * - $this->_contributorContactId - id of the contributor
293 * - $this->_receiptContactId
294 *
295 * If the member & contributor are the same then the values will be the same. But if different people paid
296 * then they weill differ
297 *
298 * @param array $formValues
299 * values from form. The important values we are looking for are.
300 * - contact_id
301 * - soft_credit_contact_id
302 */
303 public function storeContactFields($formValues) {
304 // in a 'standalone form' (contact id not in the url) the contact will be in the form values
305 if (!empty($formValues['contact_id'])) {
306 $this->_contactID = $formValues['contact_id'];
307 }
308
309 list($this->_memberDisplayName,
310 $this->_memberEmail
311 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
312
313 //CRM-10375 Where the payer differs to the member the payer should get the email.
314 // here we store details in order to do that
315 if (!empty($formValues['soft_credit_contact_id'])) {
316 $this->_receiptContactId = $this->_contributorContactID = $formValues['soft_credit_contact_id'];
317 list($this->_contributorDisplayName,
318 $this->_contributorEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contributorContactID);
319 }
320 else {
321 $this->_receiptContactId = $this->_contributorContactID = $this->_contactID;
322 $this->_contributorDisplayName = $this->_memberDisplayName;
323 $this->_contributorEmail = $this->_memberEmail;
324 }
325 }
326
327 /**
328 * Set variables in a way that can be accessed from different places.
329 *
330 * This is part of refactoring for unit testability on the submit function.
331 *
332 * @param array $params
333 */
334 protected function setContextVariables($params) {
335 $variables = array(
336 'action' => '_action',
337 'context' => '_context',
338 'id' => '_id',
339 'cid' => '_contactID',
340 'mode' => '_mode',
341 );
342 foreach ($variables as $paramKey => $classVar) {
343 if (isset($params[$paramKey]) && !isset($this->$classVar)) {
344 $this->$classVar = $params[$paramKey];
345 }
346 }
347
348 if ($this->_id) {
349 $this->_memType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_id, 'membership_type_id');
350 $this->_membershipIDs[] = $this->_id;
351 }
352 $this->_fromEmails = CRM_Core_BAO_Email::getFromEmail();
353 }
354
355 /**
356 * Create a recurring contribution record.
357 *
358 * Recurring contribution parameters are set explicitly rather than merging paymentParams because it's hard
359 * to know the downstream impacts if we keep passing around the same array.
360 *
361 * @param $paymentParams
362 *
363 * @return array
364 * @throws \CiviCRM_API3_Exception
365 */
366 protected function processRecurringContribution($paymentParams) {
367 $membershipID = $paymentParams['membership_type_id'][1];
368 $contributionRecurParams = array(
369 'contact_id' => $paymentParams['contactID'],
370 'amount' => $paymentParams['total_amount'],
371 'contribution_status_id' => 'Pending',
372 'payment_processor_id' => $paymentParams['payment_processor_id'],
373 'campaign_id' => $paymentParams['campaign_id'],
374 'financial_type_id' => $paymentParams['financial_type_id'],
375 'is_email_receipt' => $paymentParams['is_email_receipt'],
376 'payment_instrument_id' => $paymentParams['payment_instrument_id'],
377 'invoice_id' => $paymentParams['invoice_id'],
378 );
379
380 $mapping = array(
381 'frequency_interval' => 'duration_interval',
382 'frequency_unit' => 'duration_unit',
383 );
384 $membershipType = civicrm_api3('MembershipType', 'getsingle', array(
385 'id' => $membershipID,
386 'return' => $mapping,
387 ));
388
389 $returnParams = array('is_recur' => TRUE);
390 foreach ($mapping as $recurringFieldName => $membershipTypeFieldName) {
391 $contributionRecurParams[$recurringFieldName] = $membershipType[$membershipTypeFieldName];
392 $returnParams[$recurringFieldName] = $membershipType[$membershipTypeFieldName];
393 }
394
395 $contributionRecur = civicrm_api3('ContributionRecur', 'create', $contributionRecurParams);
396 $returnParams['contributionRecurID'] = $contributionRecur['id'];
397 return $returnParams;
398 }
399
400 /**
401 * Ensure price parameters are set.
402 *
403 * If they are not set it means a quick config option has been chosen so we
404 * fill them in here to make the two flows the same. They look like 'price_2' => 2 etc.
405 *
406 * @param array $formValues
407 */
408 protected function ensurePriceParamsAreSet(&$formValues) {
409 foreach ($formValues as $key => $value) {
410 if ((substr($key, 0, 6) == 'price_') && is_numeric(substr($key, 6))) {
411 return;
412 }
413 }
414 $priceFields = CRM_Member_BAO_Membership::setQuickConfigMembershipParameters(
415 $formValues['membership_type_id'][0],
416 $formValues['membership_type_id'][1],
417 CRM_Utils_Array::value('total_amount', $formValues),
418 $this->_priceSetId
419 );
420 $formValues = array_merge($formValues, $priceFields['price_fields']);
421 }
422
423 /**
424 * Get the details for the selected price set.
425 *
426 * @param array $params
427 * Parameters submitted to the form.
428 *
429 * @return array
430 */
431 protected static function getPriceSetDetails($params) {
432 $priceSetID = CRM_Utils_Array::value('price_set_id', $params);
433 if ($priceSetID) {
434 return CRM_Price_BAO_PriceSet::getSetDetail($priceSetID);
435 }
436 else {
437 $priceSet = CRM_Price_BAO_PriceSet::getDefaultPriceSet('membership');
438 $priceSet = reset($priceSet);
439 return CRM_Price_BAO_PriceSet::getSetDetail($priceSet['setID']);
440 }
441 }
442
443 /**
444 * Get the selected price set id.
445 *
446 * @param array $params
447 * Parameters submitted to the form.
448 *
449 * @return int
450 */
451 protected static function getPriceSetID($params) {
452 $priceSetID = CRM_Utils_Array::value('price_set_id', $params);
453 if (!$priceSetID) {
454 $priceSetDetails = self::getPriceSetDetails($params);
455 return key($priceSetDetails);
456 }
457 return $priceSetID;
458 }
459
460 /**
461 * Store parameters relating to price sets.
462 *
463 * @param array $formValues
464 *
465 * @return array
466 */
467 protected function setPriceSetParameters($formValues) {
468 $this->_priceSetId = self::getPriceSetID($formValues);
469 $priceSetDetails = self::getPriceSetDetails($formValues);
470 $this->_priceSet = $priceSetDetails[$this->_priceSetId];
471 // process price set and get total amount and line items.
472 $this->ensurePriceParamsAreSet($formValues);
473 return $formValues;
474 }
475
476 /**
477 * Wrapper function for unit tests.
478 *
479 * @param array $formValues
480 */
481 public function testSubmit($formValues) {
482 $this->setContextVariables($formValues);
483 $this->_memType = $formValues['membership_type_id'][1];
484 $this->_params = $formValues;
485 $this->submit();
486 }
487
488 }