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