be024fea76466e7d728a8a658d68b056d8050579
[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).once('click', function() {
153                 // We want to do this just once, the first time the controls are shown.
154                 this.populateStartDates();
155                 this.populateDuration();
156             }, this);
157             this.get(UEP.BASE).one('.'+CSS.SEARCHOPTIONS+' .'+CSS.COLLAPSIBLEHEADING).on('click', function(){
158                 this.get(UEP.BASE).one('.'+CSS.SEARCHOPTIONS+' .'+CSS.COLLAPSIBLEHEADING).toggleClass(CSS.ACTIVE);
159                 this.get(UEP.BASE).one('.'+CSS.SEARCHOPTIONS+' .'+CSS.COLLAPSIBLEAREA).toggleClass(CSS.HIDDEN);
160                 if (this.get(UEP.BASE).one('.'+CSS.SEARCHOPTIONS+' .'+CSS.COLLAPSIBLEAREA).hasClass(CSS.HIDDEN)) {
161                     this.get(UEP.BASE).one('.'+CSS.SEARCHOPTIONS+' .'+CSS.COLLAPSIBLEHEADING).one('img').setAttribute('src', M.util.image_url(collapsedimage, 'moodle'));
162                 } else {
163                     this.get(UEP.BASE).one('.'+CSS.SEARCHOPTIONS+' .'+CSS.COLLAPSIBLEHEADING).one('img').setAttribute('src', M.util.image_url('t/expanded', 'moodle'));
164                 }
165             }, this);
166             this.populateAssignableRoles();
167         },
168         populateAssignableRoles : function() {
169             this.on('assignablerolesloaded', function(){
170                 var roles = this.get(UEP.ASSIGNABLEROLES);
171                 var s = this.get(UEP.BASE).one('.'+CSS.ENROLMENTOPTION+'.'+CSS.ROLE+' select');
172                 var v = this.get(UEP.DEFAULTROLE);
173                 var index = 0, count = 0;
174                 for (var i in roles) {
175                     count++;
176                     var option = create('<option value="'+i+'">'+roles[i]+'</option>');
177                     if (i == v) {
178                         index = count;
179                     }
180                     s.append(option);
181                 }
182                 s.set('selectedIndex', index);
183             }, this);
184             this.getAssignableRoles();
185         },
186         populateStartDates : function() {
187             var select = this.get(UEP.BASE).one('.'+CSS.ENROLMENTOPTION+'.'+CSS.STARTDATE+' select');
188             var defaultvalue = this.get(UEP.DEFAULTSTARTDATE);
189             var options = this.get(UEP.OPTIONSTARTDATE);
190             var index = 0, count = 0;
191             for (var i in options) {
192                 count++;
193                 var option = create('<option value="'+i+'">'+options[i]+'</option>');
194                 if (i == defaultvalue) {
195                     index = count;
196                 }
197                 select.append(option);
198             }
199             select.set('selectedIndex', index);
200         },
201         populateDuration : function() {
202             var select = this.get(UEP.BASE).one('.'+CSS.ENROLMENTOPTION+'.'+CSS.DURATION+' select');
203             var defaultvalue = this.get(UEP.DEFAULTDURATION);
204             var index = 0, count = 0;
205             for (var i = 1; i <= 365; i++) {
206                 count++;
207                 var option = create('<option value="'+i+'">'+M.util.get_string('durationdays', 'enrol', i)+'</option>');
208                 if (i == defaultvalue) {
209                     index = count;
210                 }
211                 select.append(option);
212             }
213             select.set('selectedIndex', index);
214         },
215         getAssignableRoles : function(){
216             Y.io(M.cfg.wwwroot+'/enrol/ajax.php', {
217                 method:'POST',
218                 data:'id='+this.get(UEP.COURSEID)+'&action=getassignable&sesskey='+M.cfg.sesskey,
219                 on: {
220                     complete: function(tid, outcome, args) {
221                         try {
222                             var roles = Y.JSON.parse(outcome.responseText);
223                             this.set(UEP.ASSIGNABLEROLES, roles.response);
224                         } catch (e) {
225                             new M.core.exception(e);
226                         }
227                         this.getAssignableRoles = function() {
228                             this.fire('assignablerolesloaded');
229                         };
230                         this.getAssignableRoles();
231                     }
232                 },
233                 context:this
234             });
235         },
236         preSearch : function(e) {
237             this.search(null, false);
238             /*
239             var value = this.get(UEP.SEARCH).get('value');
240             if (value.length < 3 || value == this.get(UEP.LASTSEARCH)) {
241                 return;
242             }
243             this.set(UEP.LASTSEARCH, value);
244             if (this._searchTimeout) {
245                 clearTimeout(this._searchTimeout);
246                 this._searchTimeout = null;
247             }
248             var self = this;
249             this._searchTimeout = setTimeout(function(){
250                 self._searchTimeout = null;
251                 self.search(null, false);
252             }, 300);
253             */
254         },
255         show : function(e) {
256             e.preventDefault();
257             e.halt();
259             var base = this.get(UEP.BASE);
260             base.removeClass(CSS.HIDDEN);
261             var x = (base.get('winWidth') - 400)/2;
262             var y = (parseInt(base.get('winHeight'))-base.get('offsetHeight'))/2 + parseInt(base.get('docScrollY'));
263             if (y < parseInt(base.get('winHeight'))*0.1) {
264                 y = parseInt(base.get('winHeight'))*0.1;
265             }
266             base.setXY([x,y]);
268             if (this.get(UEP.USERS)===null) {
269                 this.search(e, false);
270             }
272             this._escCloseEvent = Y.on('key', this.hide, document.body, 'down:27', this);
273         },
274         hide : function(e) {
275             if (this._escCloseEvent) {
276                 this._escCloseEvent.detach();
277                 this._escCloseEvent = null;
278             }
279             this.get(UEP.BASE).addClass(CSS.HIDDEN);
280             if (this.get(UEP.REQUIREREFRESH)) {
281                 window.location = this.get(UEP.URL);
282             }
283         },
284         search : function(e, append) {
285             if (e) {
286                 e.halt();
287                 e.preventDefault();
288             }
289             var on, params;
290             if (append) {
291                 this.set(UEP.PAGE, this.get(UEP.PAGE)+1);
292             } else {
293                 this.set(UEP.USERCOUNT, 0);
294                 this.set(UEP.PAGE, 0);
295             }
296             params = this.get(UEP.PARAMS);
297             params['sesskey'] = M.cfg.sesskey;
298             params['action'] = 'searchusers';
299             params['search'] = this.get(UEP.SEARCH).get('value');
300             params['page'] = this.get(UEP.PAGE);
301             if (this.get(UEP.MULTIPLE)) {
302                 alert('oh no there are multiple');
303             } else {
304                 var instance = this.get(UEP.INSTANCES)[0];
305                 params['enrolid'] = instance.id;
306             }
307             Y.io(M.cfg.wwwroot+this.get(UEP.AJAXURL), {
308                 method:'POST',
309                 data:build_querystring(params),
310                 on : {
311                     start : this.displayLoading,
312                     complete: this.processSearchResults,
313                     end : this.removeLoading
314                 },
315                 context:this,
316                 arguments:{
317                     append:append,
318                     enrolid:params['enrolid']
319                 }
320             });
321         },
322         displayLoading : function() {
323             this._loadingNode.removeClass(CSS.HIDDEN);
324         },
325         removeLoading : function() {
326             this._loadingNode.addClass(CSS.HIDDEN);
327         },
328         processSearchResults : function(tid, outcome, args) {
329             try {
330                 var result = Y.JSON.parse(outcome.responseText);
331                 if (result.error) {
332                     return new M.core.ajaxException(result);
333                 }
334             } catch (e) {
335                 new M.core.exception(e);
336             }
337             if (!result.success) {
338                 this.setContent = M.str.enrol.errajaxsearch;
339             }
340             var users;
341             if (!args.append) {
342                 users = create('<div class="'+CSS.USERS+'"></div>');
343             } else {
344                 users = this.get(UEP.BASE).one('.'+CSS.SEARCHRESULTS+' .'+CSS.USERS);
345             }
346             var count = this.get(UEP.USERCOUNT);
347             for (var i in result.response.users) {
348                 count++;
349                 var user = result.response.users[i];
350                 users.append(create('<div class="'+CSS.USER+' clearfix" rel="'+user.id+'"></div>')
351                     .addClass((count%2)?CSS.ODD:CSS.EVEN)
352                     .append(create('<div class="'+CSS.COUNT+'">'+count+'</div>'))
353                     .append(create('<div class="'+CSS.PICTURE+'"></div>')
354                         .append(create(user.picture)))
355                     .append(create('<div class="'+CSS.DETAILS+'"></div>')
356                         .append(create('<div class="'+CSS.FULLNAME+'">'+user.fullname+'</div>'))
357                         .append(create('<div class="'+CSS.EXTRAFIELDS+'">'+user.extrafields+'</div>')))
358                     .append(create('<div class="'+CSS.OPTIONS+'"></div>')
359                         .append(create('<input type="button" class="'+CSS.ENROL+'" value="'+M.str.enrol.enrol+'" />')))
360                 );
361             }
362             this.set(UEP.USERCOUNT, count);
363             if (!args.append) {
364                 var usersstr = (result.response.totalusers == '1')?M.str.enrol.ajaxoneuserfound:M.util.get_string('ajaxxusersfound','enrol', result.response.totalusers);
365                 var content = create('<div class="'+CSS.SEARCHRESULTS+'"></div>')
366                     .append(create('<div class="'+CSS.TOTALUSERS+'">'+usersstr+'</div>'))
367                     .append(users);
368                 if (result.response.totalusers > (this.get(UEP.PAGE)+1)*25) {
369                     var fetchmore = create('<div class="'+CSS.MORERESULTS+'"><a href="#">'+M.str.enrol.ajaxnext25+'</a></div>');
370                     fetchmore.on('click', this.search, this, true);
371                     content.append(fetchmore)
372                 }
373                 this.setContent(content);
374                 Y.delegate("click", this.enrolUser, users, '.'+CSS.USER+' .'+CSS.ENROL, this, args);
375             } else {
376                 if (result.response.totalusers <= (this.get(UEP.PAGE)+1)*25) {
377                     this.get(UEP.BASE).one('.'+CSS.MORERESULTS).remove();
378                 }
379             }
380         },
381         enrolUser : function(e, args) {
382             var user = e.currentTarget.ancestor('.'+CSS.USER);
383             var params = [];
384             params['id'] = this.get(UEP.COURSEID);
385             params['userid'] = user.getAttribute("rel");
386             params['enrolid'] = args.enrolid;
387             params['sesskey'] = M.cfg.sesskey;
388             params['action'] = 'enrol';
389             params['role'] = this.get(UEP.BASE).one('.'+CSS.ENROLMENTOPTION+'.'+CSS.ROLE+' select').get('value');
390             params['startdate'] = this.get(UEP.BASE).one('.'+CSS.ENROLMENTOPTION+'.'+CSS.STARTDATE+' select').get('value');
391             params['duration'] = this.get(UEP.BASE).one('.'+CSS.ENROLMENTOPTION+'.'+CSS.DURATION+' select').get('value');
392             if (this.get(UEP.DISABLEGRADEHISTORY) != true) {
393                 params['recovergrades'] = this.get(UEP.BASE).one('#'+CSS.RECOVERGRADES).get('checked')?1:0;
394             } else {
395                 params['recovergrades'] = 0;
396             }
398             Y.io(M.cfg.wwwroot+this.get(UEP.AJAXURL), {
399                 method:'POST',
400                 data:build_querystring(params),
401                 on: {
402                     start : this.displayLoading,
403                     complete : function(tid, outcome, args) {
404                         try {
405                             var result = Y.JSON.parse(outcome.responseText);
406                             if (result.error) {
407                                 return new M.core.ajaxException(result);
408                             } else {
409                                 args.userNode.addClass(CSS.ENROLLED);
410                                 args.userNode.one('.'+CSS.ENROL).remove();
411                                 this.set(UEP.REQUIREREFRESH, true);
412                             }
413                         } catch (e) {
414                             new M.core.exception(e);
415                         }
416                     },
417                     end : this.removeLoading
418                 },
419                 context:this,
420                 arguments:{
421                     params : params,
422                     userNode : user
423                 }
424             });
426         },
427         setContent: function(content) {
428             this.get(UEP.BASE).one('.'+CSS.CONTENT+' .'+CSS.AJAXCONTENT).setContent(content);
429         }
430     }, {
431         NAME : UEP.NAME,
432         ATTRS : {
433             url : {
434                 validator : Y.Lang.isString
435             },
436             ajaxurl : {
437                 validator : Y.Lang.isString
438             },
439             base : {
440                 setter : function(node) {
441                     var n = Y.one(node);
442                     if (!n) {
443                         Y.fail(UEP.NAME+': invalid base node set');
444                     }
445                     return n;
446                 }
447             },
448             users : {
449                 validator : Y.Lang.isArray,
450                 value : null
451             },
452             courseid : {
453                 value : null
454             },
455             params : {
456                 validator : Y.Lang.isArray,
457                 value : []
458             },
459             instances : {
460                 validator : Y.Lang.isArray,
461                 setter : function(instances) {
462                     var i,ia = [], count=0;
463                     for (i in instances) {
464                         ia.push(instances[i]);
465                         count++;
466                     }
467                     this.set(UEP.MULTIPLE, (count>1));
468                 }
469             },
470             multiple : {
471                 validator : Y.Lang.isBool,
472                 value : false
473             },
474             page : {
475                 validator : Y.Lang.isNumber,
476                 value : 0
477             },
478             userCount : {
479                 value : 0,
480                 validator : Y.Lang.isNumber
481             },
482             requiresRefresh : {
483                 value : false,
484                 validator : Y.Lang.isBool
485             },
486             search : {
487                 setter : function(node) {
488                     var n = Y.one(node);
489                     if (!n) {
490                         Y.fail(UEP.NAME+': invalid search node set');
491                     }
492                     return n;
493                 }
494             },
495             lastPreSearchValue : {
496                 value : '',
497                 validator : Y.Lang.isString
498             },
499             strings  : {
500                 value : {},
501                 validator : Y.Lang.isObject
502             },
503             defaultRole : {
504                 value : 0
505             },
506             defaultStartDate : {
507                 value : 2,
508                 validator : Y.Lang.isNumber
509             },
510             defaultDuration : {
511                 value : ''
512             },
513             assignableRoles : {
514                 value : []
515             },
516             optionsStartDate : {
517                 value : []
518             },
519             disableGradeHistory : {
520                 value : 0
521             },
522             recoverGradesDefault : {
523                 value : ''
524             }
525         }
526     });
527     Y.augment(USERENROLLER, Y.EventTarget);
529     M.enrol_manual = M.enrol_manual || {};
530     M.enrol_manual.quickenrolment = {
531         init : function(cfg) {
532             new USERENROLLER(cfg);
533         }
534     }
536 }, '@VERSION@', {requires:['base','node', 'overlay', 'io-base', 'test', 'json-parse', 'event-delegate', 'dd-plugin', 'event-key', 'moodle-enrol-notification']});