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