CRM-14181, more clean and fixes to support callback
[civicrm-core.git] / CRM / Member / Form / MembershipType.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
32 * $Id$
33 *
34 */
35
36 /**
37 * This class generates form components for Membership Type
38 *
39 */
40 class CRM_Member_Form_MembershipType extends CRM_Member_Form {
41
42 /**
43 * max number of contacts we will display for membership-organisation
44 */
45 CONST MAX_CONTACTS = 50;
46
47 function preProcess() {
48 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE, 0 );
49 $this->_BAOName = 'CRM_Member_BAO_MembershipType';
50 $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'add');
51 $this->assign('action', $this->_action);
52
53 $session = CRM_Core_Session::singleton();
54 $url = CRM_Utils_System::url('civicrm/admin/member/membershipType', 'reset=1');
55 $session->pushUserContext($url);
56 }
57
58 /**
59 * This function sets the default values for the form. MobileProvider that in edit/view mode
60 * the default values are retrieved from the database
61 *
62 * @access public
63 *
64 * @return void
65 */
66 public function setDefaultValues() {
67 $defaults = parent::setDefaultValues();
68
69 // get the member org display name
70 if ( $this->_id && !empty($defaults['member_of_contact_id'])) {
71 $this->assign('member_org_id', $defaults['member_of_contact_id']);
72 }
73
74 //finding default weight to be put
75 if (!isset($defaults['weight']) || (!$defaults['weight'])) {
76 $defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Member_DAO_MembershipType');
77 }
78 //setting default relationshipType
79 if (isset($defaults['relationship_type_id'])) {
80 //$defaults['relationship_type_id'] = $defaults['relationship_type_id'].'_a_b';
81 // Set values for relation type select box
82 $relTypeIds = explode(CRM_Core_DAO::VALUE_SEPARATOR, $defaults['relationship_type_id']);
83 $relDirections = explode(CRM_Core_DAO::VALUE_SEPARATOR, $defaults['relationship_direction']);
84 $defaults['relationship_type_id'] = array();
85 foreach ($relTypeIds as $key => $value) {
86 $defaults['relationship_type_id'][] = $value . '_' . $relDirections[$key];
87 }
88 }
89
90
91 //setting default fixed_period_start_day & fixed_period_rollover_day
92 $periods = array('fixed_period_start_day', 'fixed_period_rollover_day');
93 foreach ($periods as $per) {
94 if (isset($defaults[$per])) {
95 $date = $defaults[$per];
96
97 $defaults[$per] = array();
98 if ($date > 31) {
99 $date = ($date < 999) ? '0' . $date : $date;
100 $defaults[$per]['M'] = substr($date, 0, 2);
101 $defaults[$per]['d'] = substr($date, 2, 3);
102 }
103 else {
104 //special case when only day is rollover and duration is month
105 $defaults['month_fixed_period_rollover_day']['d'] = $date;
106 }
107 }
108 }
109
110 return $defaults;
111 }
112
113 /**
114 * Function to build the form
115 *
116 * @return void
117 * @access public
118 */
119 public function buildQuickForm() {
120 parent::buildQuickForm();
121
122 if ($this->_action & CRM_Core_Action::DELETE) {
123 return;
124 }
125
126 $this->applyFilter('__ALL__', 'trim');
127 $this->add('text', 'name', ts('Name'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'name'), TRUE);
128
129 $this->addRule('name', ts('A membership type with this name already exists. Please select another name.'),
130 'objectExists', array('CRM_Member_DAO_MembershipType', $this->_id)
131 );
132 $this->add('text', 'description', ts('Description'),
133 CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'description')
134 );
135 $this->add('text', 'minimum_fee', ts('Minimum Fee'),
136 CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'minimum_fee')
137 );
138 $this->addRule('minimum_fee', ts('Please enter a monetary value for the Minimum Fee.'), 'money');
139
140 $this->addElement('select', 'duration_unit', ts('Duration'), CRM_Core_SelectValues::membershipTypeUnitList());
141
142 //period type
143 $this->addElement('select', 'period_type', ts('Period Type'), CRM_Core_SelectValues::periodType());
144
145 $this->add('text', 'duration_interval', ts('Duration Interval'),
146 CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'duration_interval')
147 );
148
149 $dataUrl = CRM_Utils_System::url(
150 "civicrm/ajax/rest",
151 "className=CRM_Contact_Page_AJAX&fnName=getContactList&json=1&context=membershipType&reset=1&org=1",
152 FALSE, NULL, FALSE
153 );
154 $this->assign('dataUrl', $dataUrl);
155
156 $memberOrg = &$this->add('text', 'member_of_contact', ts('Membership Organization'), NULL, TRUE);
157 $this->add('hidden', 'member_of_contact_id', '', array('id' => 'member_of_contact_id'));
158 if ($memberOrg->getValue()) {
159 $this->assign('member_org', $memberOrg->getValue());
160 }
161
162 //start day
163 $this->add('date', 'fixed_period_start_day', ts('Fixed Period Start Day'),
164 CRM_Core_SelectValues::date(NULL, 'M d'), FALSE
165 );
166
167 //Auto-renew Option
168 $paymentProcessor = CRM_Core_PseudoConstant::paymentProcessor(FALSE, FALSE, 'is_recur = 1');
169 $isAuthorize = FALSE;
170 $options = array();
171 if (is_array($paymentProcessor) && !empty($paymentProcessor)) {
172 $isAuthorize = TRUE;
173 $options = array(ts('No auto-renew option'), ts('Give option, but not required'), ts('Auto-renew required '));
174 }
175
176 $this->addRadio('auto_renew', ts('Auto-renew Option'), $options);
177 $this->assign('authorize', $isAuthorize);
178
179 //rollover day
180 $this->add('date', 'fixed_period_rollover_day', ts('Fixed Period Rollover Day'),
181 CRM_Core_SelectValues::date(NULL, 'M d'), FALSE
182 );
183 $this->add('date', 'month_fixed_period_rollover_day', ts('Fixed Period Rollover Day'),
184 CRM_Core_SelectValues::date(NULL, 'd'), FALSE
185 );
186
187 $this->add('select', 'financial_type_id', ts( 'Financial Type' ),
188 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::financialType()
189 );
190
191 $relTypeInd = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE);
192 if (is_array($relTypeInd)) {
193 asort($relTypeInd);
194 }
195 $memberRel = &$this->add('select', 'relationship_type_id', ts('Relationship Type'),
196 array('' => ts('- select -')) + $relTypeInd);
197 $memberRel->setMultiple(TRUE);
198
199 $this->add('select', 'visibility', ts('Visibility'), CRM_Core_SelectValues::memberVisibility());
200 $this->add('text', 'weight', ts('Order'),
201 CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'weight')
202 );
203 $this->add('checkbox', 'is_active', ts('Enabled?'));
204
205 $membershipRecords = FALSE;
206 if ($this->_action & CRM_Core_Action::UPDATE) {
207 $membershipType = new CRM_Member_BAO_Membership();
208 $membershipType->membership_type_id = $this->_id;
209 if ($membershipType->find(TRUE)) {
210 $membershipRecords = TRUE;
211 $memberRel->freeze();
212 }
213 }
214
215 $this->assign('membershipRecordsExists', $membershipRecords);
216
217 $this->add('text', 'max_related', ts('Max related'),
218 CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'max_related')
219 );
220
221 $this->addFormRule(array('CRM_Member_Form_MembershipType', 'formRule'));
222
223 $this->assign('membershipTypeId', $this->_id);
224 }
225
226 /**
227 * Function for validation
228 *
229 * @param array $params (ref.) an assoc array of name/value pairs
230 *
231 * @return mixed true or array of errors
232 * @access public
233 * @static
234 */
235 static function formRule($params) {
236 $errors = array();
237
238 if (!$params['name']) {
239 $errors['name'] = ts('Please enter a membership type name.');
240 }
241
242 if ($params['member_of_contact'] && !is_numeric($params['member_of_contact_id'])) {
243 $errors['member_of_contact'] = ts('Please select valid organization contact.');
244 }
245
246 if (empty( $params['financial_type_id'] ) ) {
247 $errors['financial_type_id'] = ts('Please enter a financial type.');
248 }
249
250 if (($params['minimum_fee'] > 0 ) && !$params['financial_type_id'] ) {
251 $errors['financial_type_id'] = ts('Please enter the financial type.');
252 }
253
254 if (empty($params['duration_unit'])) {
255 $errors['duration_unit'] = ts('Please enter a duration unit.');
256 }
257
258 if (empty($params['duration_interval']) and $params['duration_unit'] != 'lifetime') {
259 $errors['duration_interval'] = ts('Please enter a duration interval.');
260 }
261
262 if (in_array(CRM_Utils_Array::value('auto_renew', $params), array(
263 1, 2))) {
264 if (($params['duration_interval'] > 1 && $params['duration_unit'] == 'year') ||
265 ($params['duration_interval'] > 12 && $params['duration_unit'] == 'month')
266 ) {
267 $errors['duration_unit'] = ts('Automatic renewals are not supported by the currently available payment processors when the membership duration is greater than 1 year / 12 months.');
268 }
269 }
270
271 if (empty($params['period_type'])) {
272 $errors['period_type'] = ts('Please select a period type.');
273 }
274
275 if ($params['period_type'] == 'fixed' &&
276 $params['duration_unit'] == 'day'
277 ) {
278 $errors['period_type'] = ts('Period type should be Rolling when duration unit is Day');
279 }
280
281 if (($params['period_type'] == 'fixed') &&
282 ($params['duration_unit'] == 'year')
283 ) {
284 $periods = array('fixed_period_start_day', 'fixed_period_rollover_day');
285 foreach ($periods as $period) {
286 $month = $params[$period]['M'];
287 $date = $params[$period]['d'];
288 if (!$month || !$date) {
289 switch ($period) {
290 case 'fixed_period_start_day':
291 $errors[$period] = ts('Please enter a valid fixed period start day');
292 break;
293
294 case 'fixed_period_rollover_day':
295 $errors[$period] = ts('Please enter a valid fixed period rollover day');
296 break;
297 }
298 }
299 }
300 }
301
302 if ($params['fixed_period_start_day'] && !empty($params['fixed_period_start_day'])) {
303 $params['fixed_period_start_day']['Y'] = date('Y');
304 if (!CRM_Utils_Rule::qfDate($params['fixed_period_start_day'])) {
305 $errors['fixed_period_start_day'] = ts('Please enter valid Fixed Period Start Day');
306 }
307 }
308
309 if ($params['fixed_period_rollover_day'] && !empty($params['fixed_period_rollover_day'])) {
310 $params['fixed_period_rollover_day']['Y'] = date('Y');
311 if (!CRM_Utils_Rule::qfDate($params['fixed_period_rollover_day'])) {
312 $errors['fixed_period_rollover_day'] = ts('Please enter valid Fixed Period Rollover Day');
313 }
314 }
315
316 return empty($errors) ? TRUE : $errors;
317 }
318
319 /**
320 * Function to process the form
321 *
322 * @access public
323 *
324 * @return void
325 */
326 public function postProcess() {
327 if ($this->_action & CRM_Core_Action::DELETE) {
328 try{
329 CRM_Member_BAO_MembershipType::del($this->_id);
330 }
331 catch(CRM_Core_Exception $e) {
332 CRM_Core_Error::statusBounce($e->getMessage(), NULL, ts('Membership Type Not Deleted'));
333 }
334 CRM_Core_Session::setStatus(ts('Selected membership type has been deleted.'), ts('Record Deleted'), 'success');
335 }
336 else {
337 $buttonName = $this->controller->getButtonName();
338 $submitted = $this->controller->exportValues($this->_name);
339
340 $fields = array(
341 'name',
342 'weight',
343 'is_active',
344 'member_of_contact_id',
345 'visibility',
346 'period_type',
347 'minimum_fee',
348 'description',
349 'auto_renew',
350 'duration_unit',
351 'duration_interval',
352 'financial_type_id',
353 'fixed_period_start_day',
354 'fixed_period_rollover_day',
355 'month_fixed_period_rollover_day',
356 'max_related'
357 );
358
359 $params = $ids = array();
360 foreach ($fields as $fld) {
361 $params[$fld] = CRM_Utils_Array::value($fld, $submitted, 'NULL');
362 }
363
364 //clean money.
365 if ($params['minimum_fee']) {
366 $params['minimum_fee'] = CRM_Utils_Rule::cleanMoney($params['minimum_fee']);
367 }
368
369 $hasRelTypeVal = FALSE;
370 if (!CRM_Utils_System::isNull($submitted['relationship_type_id'])) {
371 // To insert relation ids and directions with value separator
372 $relTypeDirs = $submitted['relationship_type_id'];
373 $relIds = $relDirection = array();
374 foreach ($relTypeDirs as $key => $value) {
375 $relationId = explode('_', $value);
376 if (count($relationId) == 3 &&
377 is_numeric($relationId[0])
378 ) {
379 $relIds[] = $relationId[0];
380 $relDirection[] = $relationId[1] . '_' . $relationId[2];
381 }
382 }
383 if (!empty($relIds)) {
384 $hasRelTypeVal = TRUE;
385 $params['relationship_type_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $relIds);
386 $params['relationship_direction'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $relDirection);
387 }
388 }
389 if (!$hasRelTypeVal) {
390 $params['relationship_type_id'] = $params['relationship_direction'] = $params['max_related'] = 'NULL';
391 }
392
393 if ($params['duration_unit'] == 'lifetime' &&
394 empty($params['duration_interval'])
395 ) {
396 $params['duration_interval'] = 1;
397 }
398
399 $periods = array('fixed_period_start_day', 'fixed_period_rollover_day');
400 foreach ($periods as $per) {
401 if (!empty($params[$per]['M']) && !empty($params[$per]['d'])) {
402 $mon = $params[$per]['M'];
403 $dat = $params[$per]['d'];
404 $mon = ($mon < 10) ? '0' . $mon : $mon;
405 $dat = ($dat < 10) ? '0' . $dat : $dat;
406 $params[$per] = $mon . $dat;
407 }
408 else if($per == 'fixed_period_rollover_day' && !empty($params['month_fixed_period_rollover_day'])){
409 $params['fixed_period_rollover_day'] = $params['month_fixed_period_rollover_day']['d'];
410 unset($params['month_fixed_period_rollover_day']);
411 }
412 else {
413 $params[$per] = 'NULL';
414 }
415 }
416 $oldWeight = NULL;
417
418 if ($this->_id) {
419 $oldWeight = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
420 $this->_id, 'weight', 'id'
421 );
422 }
423 $params['weight'] = CRM_Utils_Weight::updateOtherWeights('CRM_Member_DAO_MembershipType',
424 $oldWeight, $params['weight']
425 );
426
427 if ($this->_action & CRM_Core_Action::UPDATE) {
428 $ids['membershipType'] = $this->_id;
429 }
430
431 $membershipType = CRM_Member_BAO_MembershipType::add($params, $ids);
432
433 CRM_Core_Session::setStatus(ts('The membership type \'%1\' has been saved.',
434 array(1 => $membershipType->name)
435 ), ts('Saved'), 'success');
436 $session = CRM_Core_Session::singleton();
437 if ($buttonName == $this->getButtonName('upload', 'new')) {
438 $session->replaceUserContext(
439 CRM_Utils_System::url('civicrm/admin/member/membershipType/add', 'action=add&reset=1')
440 );
441 }
442 }
443 }
444
445 public static function checkPreviousPriceField($previousID, $priceSetId, $membershipTypeId, &$optionsIds) {
446 if ($previousID) {
447 $editedFieldParams = array(
448 'price_set_id ' => $priceSetId,
449 'name' => $previousID,
450 );
451 $editedResults = array();
452 CRM_Price_BAO_PriceField::retrieve($editedFieldParams, $editedResults);
453 if (!empty($editedResults)) {
454 $editedFieldParams = array(
455 'price_field_id' => $editedResults['id'],
456 'membership_type_id' => $membershipTypeId,
457 );
458 $editedResults = array();
459 CRM_Price_BAO_PriceFieldValue::retrieve($editedFieldParams, $editedResults);
460 $optionsIds['option_id'][1] = CRM_Utils_Array::value('id', $editedResults);
461 }
462 }
463 }
464 }
465