c1963aa674f3933a741a3cc8d8cfcb90a8b05564
[moodle.git] / enrol / manual / yui / quickenrolment / quickenrolment.js
1 YUI.add('moodle-enrol_manual-quickenrolment', function(Y) {
3     var UEP = {
4         NAME : 'Enrolment Manager',
5         /** Properties **/
6         BASE : 'base',
7         SEARCH : 'search',
8         PARAMS : 'params',
9         URL : 'url',
10         AJAXURL : 'ajaxurl',
11         MULTIPLE : 'multiple',
12         PAGE : 'page',
13         COURSEID : 'courseid',
14         USERS : 'users',
15         USERCOUNT : 'userCount',
16         REQUIREREFRESH : 'requiresRefresh',
17         LASTSEARCH : 'lastPreSearchValue',
18         INSTANCES : 'instances',
19         OPTIONSTARTDATE : 'optionsStartDate',
20         DEFAULTROLE : 'defaultRole',
21         DEFAULTSTARTDATE : 'defaultStartDate',
22         DEFAULTDURATION : 'defaultDuration',
23         ASSIGNABLEROLES : 'assignableRoles',
24         DISABLEGRADEHISTORY : 'disableGradeHistory',
25         RECOVERGRADESDEFAULT : 'recoverGradesDefault'
26     };
27     /** CSS classes for nodes in structure **/
28     var CSS = {
29         PANEL : 'user-enroller-panel',
30         WRAP : 'uep-wrap',
31         HEADER : 'uep-header',
32         CONTENT : 'uep-content',
33         AJAXCONTENT : 'uep-ajax-content',
34         SEARCHRESULTS : 'uep-search-results',
35         TOTALUSERS : 'totalusers',
36         USERS : 'users',
37         USER : 'user',
38         MORERESULTS : 'uep-more-results',
39         LIGHTBOX : 'uep-loading-lightbox',
40         LOADINGICON : 'loading-icon',
41         FOOTER : 'uep-footer',
42         ENROL : 'enrol',
43         ENROLLED : 'enrolled',
44         COUNT : 'count',
45         PICTURE : 'picture',
46         DETAILS : 'details',
47         FULLNAME : 'fullname',
48         EXTRAFIELDS : 'extrafields',
49         OPTIONS : 'options',
50         ODD  : 'odd',
51         EVEN : 'even',
52         HIDDEN : 'hidden',
53         RECOVERGRADES : 'recovergrades',
54         RECOVERGRADESTITLE : 'recovergradestitle',
55         SEARCHOPTIONS : 'uep-searchoptions',
56         COLLAPSIBLEHEADING : 'collapsibleheading',
57         COLLAPSIBLEAREA : 'collapsiblearea',
58         ENROLMENTOPTION : 'uep-enrolment-option',
59         SEARCHCONTROLS : 'uep-controls',
60         ROLE : 'role',
61         STARTDATE : 'startdate',
62         DURATION : 'duration',
63         ACTIVE : 'active',
64         SEARCH : 'uep-search',
65         CLOSE : 'close',
66         CLOSEBTN : 'close-button'
67     };
68     var create = Y.Node.create;
70     var USERENROLLER = function(config) {
71         USERENROLLER.superclass.constructor.apply(this, arguments);
72     };
73     Y.extend(USERENROLLER, Y.Base, {
74         _searchTimeout : null,
75         _loadingNode : null,
76         _escCloseEvent : null,
77         initializer : function(config) {
78             var recovergrades = null;
79             if (this.get(UEP.DISABLEGRADEHISTORY) != true) {
80                 recovergrades = create('<div class="'+CSS.ENROLMENTOPTION+' '+CSS.RECOVERGRADES+'"></div>')
81                     .append(create('<label class="'+CSS.RECOVERGRADESTITLE+'" for="'+CSS.RECOVERGRADES+'">'+M.str.enrol.recovergrades+'</label>'))
82                     .append(create('<input type="checkbox" id="'+CSS.RECOVERGRADES+'" name="'+CSS.RECOVERGRADES+'"'+ this.get(UEP.RECOVERGRADESDEFAULT) +' />'))
83             }
85             this.set(UEP.BASE, create('<div class="'+CSS.PANEL+' '+CSS.HIDDEN+'"></div>')
86                 .append(create('<div class="'+CSS.WRAP+'"></div>')
87                     .append(create('<div class="'+CSS.HEADER+' header"></div>')
88                         .append(create('<div class="'+CSS.CLOSE+'"></div>'))
89                         .append(create('<h2>'+M.str.enrol.enrolusers+'</h2>')))
90                     .append(create('<div class="'+CSS.CONTENT+'"></div>')
91                         .append(create('<div class="'+CSS.SEARCHCONTROLS+'"></div>')
92                             .append(create('<div class="'+CSS.ENROLMENTOPTION+' '+CSS.ROLE+'">'+M.str.role.assignroles+'</div>')
93                                     .append(create('<select><option value="">'+M.str.enrol.none+'</option></select>'))
94                             )
95                             .append(create('<div class="'+CSS.SEARCHOPTIONS+'"></div>')
96                                 .append(create('<div class="'+CSS.COLLAPSIBLEHEADING+'"><img alt="" />'+M.str.enrol.enrolmentoptions+'</div>'))
97                                 .append(create('<div class="'+CSS.COLLAPSIBLEAREA+' '+CSS.HIDDEN+'"></div>')
98                                     .append(recovergrades)
99                                     .append(create('<div class="'+CSS.ENROLMENTOPTION+' '+CSS.STARTDATE+'">'+M.str.moodle.startingfrom+'</div>')
100                                         .append(create('<select></select>')))
101                                     .append(create('<div class="'+CSS.ENROLMENTOPTION+' '+CSS.DURATION+'">'+M.str.enrol.enrolperiod+'</div>')
102                                         .append(create('<select><option value="0" selected="selected">'+M.str.enrol.unlimitedduration+'</option></select>')))
103                                 )
104                             )
105                         )
106                         .append(create('<div class="'+CSS.AJAXCONTENT+'"></div>'))
107                         .append(create('<div class="'+CSS.LIGHTBOX+' '+CSS.HIDDEN+'"></div>')
108                             .append(create('<img alt="loading" class="'+CSS.LOADINGICON+'" />')
109                                 .setAttribute('src', M.util.image_url('i/loading', 'moodle')))
110                             .setStyle('opacity', 0.5)))
111                     .append(create('<div class="'+CSS.FOOTER+'"></div>')
112                         .append(create('<div class="'+CSS.SEARCH+'"><label>'+M.str.enrol.usersearch+'</label></div>')
113                             .append(create('<input type="text" id="enrolusersearch" value="" />'))
114                         )
115                         .append(create('<div class="'+CSS.CLOSEBTN+'"></div>')
116                             .append(create('<input type="button" value="'+M.str.enrol.finishenrollingusers+'" />'))
117                         )
118                     )
119                 )
120             );
122             this.set(UEP.SEARCH, this.get(UEP.BASE).one('#enrolusersearch'));
123             Y.all('.enrol_manual_plugin input').each(function(node){
124                 if (node.getAttribute('type', 'submit')) {
125                     node.on('click', this.show, this);
126                 }
127             }, this);
128             this.get(UEP.BASE).one('.'+CSS.HEADER+' .'+CSS.CLOSE).on('click', this.hide, this);
129             this.get(UEP.BASE).one('.'+CSS.FOOTER+' .'+CSS.CLOSEBTN+' input').on('click', this.hide, this);
130             this._loadingNode = this.get(UEP.BASE).one('.'+CSS.CONTENT+' .'+CSS.LIGHTBOX);
131             var params = this.get(UEP.PARAMS);
132             params['id'] = this.get(UEP.COURSEID);
133             this.set(UEP.PARAMS, params);
135             Y.on('key', this.preSearch, this.get(UEP.SEARCH), 'down:13', this);
137             Y.one(document.body).append(this.get(UEP.BASE));
139             var base = this.get(UEP.BASE);
140             base.plug(Y.Plugin.Drag);
141             base.dd.addHandle('.'+CSS.HEADER+' h2');
142             base.one('.'+CSS.HEADER+' h2').setStyle('cursor', 'move');
144             var collapsedimage = 't/collapsed'; // ltr mode
145             if ( Y.one(document.body).hasClass('dir-rtl') ) {
146                 collapsedimage = 't/collapsed_rtl';
147             } else {
148                 collapsedimage = 't/collapsed';
149             }
151             this.get(UEP.BASE).one('.'+CSS.SEARCHOPTIONS+' .'+CSS.COLLAPSIBLEHEADING).one('img').setAttribute('src', M.util.image_url(collapsedimage, 'moodle'));
152             this.get(UEP.BASE).one('.'+CSS.SEARCHOPTIONS+' .'+CSS.COLLAPSIBLEHEADING).on('click', function(){
153                 this.get(UEP.BASE).one('.'+CSS.SEARCHOPTIONS+' .'+CSS.COLLAPSIBLEHEADING).toggleClass(CSS.ACTIVE);
154                 this.get(UEP.BASE).one('.'+CSS.SEARCHOPTIONS+' .'+CSS.COLLAPSIBLEAREA).toggleClass(CSS.HIDDEN);
155                 if (this.get(UEP.BASE).one('.'+CSS.SEARCHOPTIONS+' .'+CSS.COLLAPSIBLEAREA).hasClass(CSS.HIDDEN)) {
156                     this.get(UEP.BASE).one('.'+CSS.SEARCHOPTIONS+' .'+CSS.COLLAPSIBLEHEADING).one('img').setAttribute('src', M.util.image_url(collapsedimage, 'moodle'));
157                 } else {
158                     this.get(UEP.BASE).one('.'+CSS.SEARCHOPTIONS+' .'+CSS.COLLAPSIBLEHEADING).one('img').setAttribute('src', M.util.image_url('t/expanded', 'moodle'));
159                 }
160             }, this);
162             this.populateAssignableRoles();
163             this.populateStartDates();
164             this.populateDuration();
165         },
166         populateAssignableRoles : function() {
167             this.on('assignablerolesloaded', function(){
168                 var roles = this.get(UEP.ASSIGNABLEROLES);
169                 var s = this.get(UEP.BASE).one('.'+CSS.ENROLMENTOPTION+'.'+CSS.ROLE+' select');
170                 var v = this.get(UEP.DEFAULTROLE);
171                 var index = 0, count = 0;
172                 for (var i in roles) {
173                     count++;
174                     var option = create('<option value="'+i+'">'+roles[i]+'</option>');
175                     if (i == v) {
176                         index = count;
177                     }
178                     s.append(option);
179                 }
180                 s.set('selectedIndex', index);
181             }, this);
182             this.getAssignableRoles();
183         },
184         populateStartDates : function() {
185             var select = this.get(UEP.BASE).one('.'+CSS.ENROLMENTOPTION+'.'+CSS.STARTDATE+' select');
186             var defaultvalue = this.get(UEP.DEFAULTSTARTDATE);
187             var options = this.get(UEP.OPTIONSTARTDATE);
188             var index = 0, count = 0;
189             for (var i in options) {
190                 count++;
191                 var option = create('<option value="'+i+'">'+options[i]+'</option>');
192                 if (i == defaultvalue) {
193                     index = count;
194                 }
195                 select.append(option);
196             }
197             select.set('selectedIndex', index);
198         },
199         populateDuration : function() {
200             var select = this.get(UEP.BASE).one('.'+CSS.ENROLMENTOPTION+'.'+CSS.DURATION+' select');
201             var defaultvalue = this.get(UEP.DEFAULTDURATION);
202             var index = 0, count = 0;
203             for (var i = 1; i <= 365; i++) {
204                 count++;
205                 var option = create('<option value="'+i+'">'+M.util.get_string('durationdays', 'enrol', i)+'</option>');
206                 if (i == defaultvalue) {
207                     index = count;
208                 }
209                 select.append(option);
210             }
211             select.set('selectedIndex', index);
212         },
213         getAssignableRoles : function(){
214             Y.io(M.cfg.wwwroot+'/enrol/ajax.php', {
215                 method:'POST',
216                 data:'id='+this.get(UEP.COURSEID)+'&action=getassignable&sesskey='+M.cfg.sesskey,
217                 on: {
218                     complete: function(tid, outcome, args) {
219                         try {
220                             var roles = Y.JSON.parse(outcome.responseText);
221                             this.set(UEP.ASSIGNABLEROLES, roles.response);
222                         } catch (e) {
223                             new M.core.exception(e);
224                         }
225                         this.getAssignableRoles = function() {
226                             this.fire('assignablerolesloaded');
227                         };
228                         this.getAssignableRoles();
229                     }
230                 },
231                 context:this
232             });
233         },
234         preSearch : function(e) {
235             this.search(null, false);
236             /*
237             var value = this.get(UEP.SEARCH).get('value');
238             if (value.length < 3 || value == this.get(UEP.LASTSEARCH)) {
239                 return;
240             }
241             this.set(UEP.LASTSEARCH, value);
242             if (this._searchTimeout) {
243                 clearTimeout(this._searchTimeout);
244                 this._searchTimeout = null;
245             }
246             var self = this;
247             this._searchTimeout = setTimeout(function(){
248                 self._searchTimeout = null;
249                 self.search(null, false);
250             }, 300);
251             */
252         },
253         show : function(e) {
254             e.preventDefault();
255             e.halt();
257             var base = this.get(UEP.BASE);
258             base.removeClass(CSS.HIDDEN);
259             var x = (base.get('winWidth') - 400)/2;
260             var y = (parseInt(base.get('winHeight'))-base.get('offsetHeight'))/2 + parseInt(base.get('docScrollY'));
261             if (y < parseInt(base.get('winHeight'))*0.1) {
262                 y = parseInt(base.get('winHeight'))*0.1;
263             }
264             base.setXY([x,y]);
266             if (this.get(UEP.USERS)===null) {
267                 this.search(e, false);
268             }
270             this._escCloseEvent = Y.on('key', this.hide, document.body, 'down:27', this);
271         },
272         hide : function(e) {
273             if (this._escCloseEvent) {
274                 this._escCloseEvent.detach();
275                 this._escCloseEvent = null;
276             }
277             this.get(UEP.BASE).addClass(CSS.HIDDEN);
278             if (this.get(UEP.REQUIREREFRESH)) {
279                 window.location = this.get(UEP.URL);
280             }
281         },
282         search : function(e, append) {
283             if (e) {
284                 e.halt();
285                 e.preventDefault();
286             }
287             var on, params;
288             if (append) {
289                 this.set(UEP.PAGE, this.get(UEP.PAGE)+1);
290             } else {
291                 this.set(UEP.USERCOUNT, 0);
292                 this.set(UEP.PAGE, 0);
293             }
294             params = this.get(UEP.PARAMS);
295             params['sesskey'] = M.cfg.sesskey;
296             params['action'] = 'searchusers';
297             params['search'] = this.get(UEP.SEARCH).get('value');
298             params['page'] = this.get(UEP.PAGE);
299             if (this.get(UEP.MULTIPLE)) {
300                 alert('oh no there are multiple');
301             } else {
302                 var instance = this.get(UEP.INSTANCES)[0];
303                 params['enrolid'] = instance.id;
304             }
305             Y.io(M.cfg.wwwroot+this.get(UEP.AJAXURL), {
306                 method:'POST',
307                 data:build_querystring(params),
308                 on : {
309                     start : this.displayLoading,
310                     complete: this.processSearchResults,
311                     end : this.removeLoading
312                 },
313                 context:this,
314                 arguments:{
315                     append:append,
316                     enrolid:params['enrolid']
317                 }
318             });
319         },
320         displayLoading : function() {
321             this._loadingNode.removeClass(CSS.HIDDEN);
322         },
323         removeLoading : function() {
324             this._loadingNode.addClass(CSS.HIDDEN);
325         },
326         processSearchResults : function(tid, outcome, args) {
327             try {
328                 var result = Y.JSON.parse(outcome.responseText);
329                 if (result.error) {
330                     return new M.core.ajaxException(result);
331                 }
332             } catch (e) {
333                 new M.core.exception(e);
334             }
335             if (!result.success) {
336                 this.setContent = M.str.enrol.errajaxsearch;
337             }
338             var users;
339             if (!args.append) {
340                 users = create('<div class="'+CSS.USERS+'"></div>');
341             } else {
342                 users = this.get(UEP.BASE).one('.'+CSS.SEARCHRESULTS+' .'+CSS.USERS);
343             }
344             var count = this.get(UEP.USERCOUNT);
345             for (var i in result.response.users) {
346                 count++;
347                 var user = result.response.users[i];
348                 users.append(create('<div class="'+CSS.USER+' clearfix" rel="'+user.id+'"></div>')
349                     .addClass((count%2)?CSS.ODD:CSS.EVEN)
350                     .append(create('<div class="'+CSS.COUNT+'">'+count+'</div>'))
351                     .append(create('<div class="'+CSS.PICTURE+'"></div>')
352                         .append(create(user.picture)))
353                     .append(create('<div class="'+CSS.DETAILS+'"></div>')
354                         .append(create('<div class="'+CSS.FULLNAME+'">'+user.fullname+'</div>'))
355                         .append(create('<div class="'+CSS.EXTRAFIELDS+'">'+user.extrafields+'</div>')))
356                     .append(create('<div class="'+CSS.OPTIONS+'"></div>')
357                         .append(create('<input type="button" class="'+CSS.ENROL+'" value="'+M.str.enrol.enrol+'" />')))
358                 );
359             }
360             this.set(UEP.USERCOUNT, count);
361             if (!args.append) {
362                 var usersstr = (result.response.totalusers == '1')?M.str.enrol.ajaxoneuserfound:M.util.get_string('ajaxxusersfound','enrol', result.response.totalusers);
363                 var content = create('<div class="'+CSS.SEARCHRESULTS+'"></div>')
364                     .append(create('<div class="'+CSS.TOTALUSERS+'">'+usersstr+'</div>'))
365                     .append(users);
366                 if (result.response.totalusers > (this.get(UEP.PAGE)+1)*25) {
367                     var fetchmore = create('<div class="'+CSS.MORERESULTS+'"><a href="#">'+M.str.enrol.ajaxnext25+'</a></div>');
368                     fetchmore.on('click', this.search, this, true);
369                     content.append(fetchmore)
370                 }
371                 this.setContent(content);
372                 Y.delegate("click", this.enrolUser, users, '.'+CSS.USER+' .'+CSS.ENROL, this, args);
373             } else {
374                 if (result.response.totalusers <= (this.get(UEP.PAGE)+1)*25) {
375                     this.get(UEP.BASE).one('.'+CSS.MORERESULTS).remove();
376                 }
377             }
378         },
379         enrolUser : function(e, args) {
380             var user = e.currentTarget.ancestor('.'+CSS.USER);
381             var params = [];
382             params['id'] = this.get(UEP.COURSEID);
383             params['userid'] = user.getAttribute("rel");
384             params['enrolid'] = args.enrolid;
385             params['sesskey'] = M.cfg.sesskey;
386             params['action'] = 'enrol';
387             params['role'] = this.get(UEP.BASE).one('.'+CSS.ENROLMENTOPTION+'.'+CSS.ROLE+' select').get('value');
388             params['startdate'] = this.get(UEP.BASE).one('.'+CSS.ENROLMENTOPTION+'.'+CSS.STARTDATE+' select').get('value');
389             params['duration'] = this.get(UEP.BASE).one('.'+CSS.ENROLMENTOPTION+'.'+CSS.DURATION+' select').get('value');
390             if (this.get(UEP.DISABLEGRADEHISTORY) != true) {
391                 params['recovergrades'] = this.get(UEP.BASE).one('#'+CSS.RECOVERGRADES).get('checked')?1:0;
392             } else {
393                 params['recovergrades'] = 0;
394             }
396             Y.io(M.cfg.wwwroot+this.get(UEP.AJAXURL), {
397                 method:'POST',
398                 data:build_querystring(params),
399                 on: {
400                     start : this.displayLoading,
401                     complete : function(tid, outcome, args) {
402                         try {
403                             var result = Y.JSON.parse(outcome.responseText);
404                             if (result.error) {
405                                 return new M.core.ajaxException(result);
406                             } else {
407                                 args.userNode.addClass(CSS.ENROLLED);
408                                 args.userNode.one('.'+CSS.ENROL).remove();
409                                 this.set(UEP.REQUIREREFRESH, true);
410                             }
411                         } catch (e) {
412                             new M.core.exception(e);
413                         }
414                     },
415                     end : this.removeLoading
416                 },
417                 context:this,
418                 arguments:{
419                     params : params,
420                     userNode : user
421                 }
422             });
424         },
425         setContent: function(content) {
426             this.get(UEP.BASE).one('.'+CSS.CONTENT+' .'+CSS.AJAXCONTENT).setContent(content);
427         }
428     }, {
429         NAME : UEP.NAME,
430         ATTRS : {
431             url : {
432                 validator : Y.Lang.isString
433             },
434             ajaxurl : {
435                 validator : Y.Lang.isString
436             },
437             base : {
438                 setter : function(node) {
439                     var n = Y.one(node);
440                     if (!n) {
441                         Y.fail(UEP.NAME+': invalid base node set');
442                     }
443                     return n;
444                 }
445             },
446             users : {
447                 validator : Y.Lang.isArray,
448                 value : null
449             },
450             courseid : {
451                 value : null
452             },
453             params : {
454                 validator : Y.Lang.isArray,
455                 value : []
456             },
457             instances : {
458                 validator : Y.Lang.isArray,
459                 setter : function(instances) {
460                     var i,ia = [], count=0;
461                     for (i in instances) {
462                         ia.push(instances[i]);
463                         count++;
464                     }
465                     this.set(UEP.MULTIPLE, (count>1));
466                 }
467             },
468             multiple : {
469                 validator : Y.Lang.isBool,
470                 value : false
471             },
472             page : {
473                 validator : Y.Lang.isNumber,
474                 value : 0
475             },
476             userCount : {
477                 value : 0,
478                 validator : Y.Lang.isNumber
479             },
480             requiresRefresh : {
481                 value : false,
482                 validator : Y.Lang.isBool
483             },
484             search : {
485                 setter : function(node) {
486                     var n = Y.one(node);
487                     if (!n) {
488                         Y.fail(UEP.NAME+': invalid search node set');
489                     }
490                     return n;
491                 }
492             },
493             lastPreSearchValue : {
494                 value : '',
495                 validator : Y.Lang.isString
496             },
497             strings  : {
498                 value : {},
499                 validator : Y.Lang.isObject
500             },
501             defaultRole : {
502                 value : 0
503             },
504             defaultStartDate : {
505                 value : 2,
506                 validator : Y.Lang.isNumber
507             },
508             defaultDuration : {
509                 value : ''
510             },
511             assignableRoles : {
512                 value : []
513             },
514             optionsStartDate : {
515                 value : []
516             },
517             disableGradeHistory : {
518                 value : 0
519             },
520             recoverGradesDefault : {
521                 value : ''
522             }
523         }
524     });
525     Y.augment(USERENROLLER, Y.EventTarget);
527     M.enrol_manual = M.enrol_manual || {};
528     M.enrol_manual.quickenrolment = {
529         init : function(cfg) {
530             new USERENROLLER(cfg);
531         }
532     }
534 }, '@VERSION@', {requires:['base','node', 'overlay', 'io-base', 'test', 'json-parse', 'event-delegate', 'dd-plugin', 'event-key', 'moodle-enrol-notification']});