added evergreen branch of user editor
[Evergreen.git] / Evergreen / xul / staff_client / server / patron / ue.js
1 var cgi                                                 = null;
2 var clone                                               = false;
3 var patron                                              = null;
4 var counter                                             = 0;
5 var identTypesCache                     = {};
6 var statCatsCache                               = {};
7 var surveysCache                                = {};
8 var surveyQuestionsCache        = {};
9 var surveyAnswersCache          = {};
10 var userCache                                   = {};
11 var groupsCache                         = {};
12 var netLevelsCache                      = {};
13 //var guardianNote                              = null; 
14
15
16 /* fetch the necessary data to start off */
17 function uEditInit() {
18
19         _debug('uEditInit(): ' + location.search);
20
21         cgi             = new CGI();
22         session = cgi.param('ses');
23         clone           = cgi.param('clone');
24         if(!session) throw "User session is not defined";
25
26         fetchUser(session);
27         $('uedit_user').appendChild(text(USER.usrname()));
28
29         setTimeout( function() { 
30                 uEditBuild(); uEditShowPage('uedit_userid'); }, 20 );
31 }
32
33 /* ------------------------------------------------------------------------------ */
34 /* Fetch code
35 /* ------------------------------------------------------------------------------ */
36 function uEditFetchIdentTypes() {
37         _debug("uEditFetchIdentTypes()");
38         var req = new Request(FETCH_ID_TYPES);
39         req.send(true);
40         return req.result();
41 }
42
43 function uEditFetchStatCats() {
44         _debug("uEditFetchStatCats()");
45         var req = new Request(SC_FETCH_ALL, SESSION);
46         req.send(true);
47         return req.result();
48 }
49
50 function uEditFetchSurveys() {
51         _debug("uEditFetchSurveys()");
52         var req = new Request(SV_FETCH_ALL, SESSION);
53         req.send(true);
54         return req.result();
55 }
56
57 function uEditFetchGroups() {
58         _debug("uEditFetchGroups()");
59         var req = new Request(FETCH_GROUPS);
60         req.send(true);
61         return req.result();
62 }
63
64 function uEditFetchNetLevels() {
65         _debug("uEditFetchNetLevels()");
66         var req = new Request(FETCH_NET_LEVELS, SESSION);
67         req.send(true);
68         return req.result();
69 }
70
71 /* ------------------------------------------------------------------------------ */
72
73
74
75 /* fetches necessary and builds the UI */
76 function uEditBuild() {
77         fetchHighestPermOrgs( SESSION, USER.id(), myPerms );
78
79         uEditBuildLibSelector();
80         patron = fetchFleshedUser(cgi.param('usr'));
81         if(!patron) patron = uEditNewPatron(); 
82         
83         uEditDraw( 
84                 uEditFetchIdentTypes(),
85                 uEditFetchGroups(),
86                 uEditFetchStatCats(),
87                 uEditFetchSurveys(),
88                 uEditFetchNetLevels()
89                 );
90
91         if(patron.isnew()) {
92                 if(clone) uEditClone(clone);
93                 else uEditCreateNewAddr();
94
95         } else {
96
97                 $('ue_barcode').disabled = true;
98                 unHideMe($('ue_mark_card_lost'));
99                 unHideMe($('ue_reset_pw'));
100                 uEditCheckEditPerm();
101         }
102
103         if(PERMS['BAR_PATRON'] == -1) 
104                 $('ue_barred').disabled = true;
105 }
106
107
108 /* if this user does not have permission to put users into
109         the edited users group, they do not have permission to 
110         edit this user */
111 function uEditCheckEditPerm() {
112
113         var perm = uEditFindGroupPerm(groupsCache[patron.profile()]);   
114         _debug("editing user with group app perm "+patron.profile()+' : '+
115                 groupsCache[patron.profile()].name() +', and perm = ' + perm);
116
117         if(PERMS[perm] != -1) return;
118
119         /* we can edit our own account, but not others in our group */
120         if( patron.id() != USER.id() ){
121                 _debug("we are not allowed to edit this user");
122         
123                 $('ue_save').disabled = true;
124                 $('ue_save_clone').disabled = true;
125         
126                 uEditIterateFields(
127                         function(f) {
128                                 if( f && f.widget && f.widget.node )
129                                         f.widget.node.disabled = true;
130                         }       
131                 );      
132
133         }
134
135         var node = $('ue_profile').parentNode;
136         node.removeChild($('ue_profile'));
137         node.appendChild(elem('span',null,groupsCache[patron.profile()].name()));
138
139         var field = uEditFindFieldByKey('profile');
140         field.required = false;
141         removeCSSClass(field.widget.node, CSS_INVALID_DATA);
142         uEditCheckErrors();
143 }
144
145
146 /* creates a new patron object with card attached */
147 var uEditCardVirtId = -1;
148 function uEditNewPatron() {
149         var patron = new au(); 
150         patron.isnew(1);
151         patron.id(-1);
152         card = new ac();
153         card.id(uEditCardVirtId--);
154         card.isnew(1);
155         patron.card(card);
156         patron.cards([card]);
157         patron.stat_cat_entries([]);
158         patron.survey_responses([]);
159         patron.addresses([]);
160         patron.home_ou(USER.ws_ou());
161         uEditMakeRandomPw(patron);
162         return patron;
163 }
164
165 function uEditMakeRandomPw(patron) {
166         var rand  = Math.random();
167         rand = parseInt(rand * 10000) + '';
168         while(rand.length < 4) rand += '0';
169         appendClear($('ue_password_plain'),text(rand));
170         unHideMe($('ue_password_gen'));
171         patron.passwd(rand);
172         return rand;
173 }
174
175 function uEditResetPw() { 
176         var pw = uEditMakeRandomPw(patron);     
177         $('ue_password1').value = pw;
178         $('ue_password2').value = pw;
179 }
180
181 function uEditClone(clone) {
182
183         var cloneUser = fetchFleshedUser(clone);
184         patron.usrgroup(cloneUser.usrgroup());
185
186         if( cloneUser.day_phone() )
187                 $('ue_day_phone').value = cloneUser.day_phone();
188         if( cloneUser.evening_phone() )
189                 $('ue_night_phone').value = cloneUser.evening_phone();
190         if( cloneUser.other_phone() )
191                 $('ue_other_phone').value = cloneUser.other_phone();
192         setSelector($('ue_org_selector'), cloneUser.home_ou());
193
194
195         setSelector($('ue_profile'), cloneUser.profile());
196
197         /* force the expire date to be set */
198         $('ue_profile').onchange();
199
200         for( var a in cloneUser.addresses() ) {
201                 var addr = cloneUser.addresses()[a];
202                 if( cloneUser.mailing_address && 
203                                 addr.id() == cloneUser.mailing_address().id() )
204                         patron.mailing_address(addr);
205                 if( cloneUser.billing_address() &&
206                                 addr.id() == cloneUser.billing_address().id() )
207                         patron.billing_address(addr);
208                 patron.addresses().push(addr);
209         }
210
211         uEditBuildAddrs(patron);
212 }
213
214
215 /* Creates a new blank address, 
216         adds it to the user and the fields array */
217 var uEditVirtualAddrId = -1;
218 function uEditCreateNewAddr() {
219         var addr = new aua();
220
221         addr.id(uEditVirtualAddrId--);
222         addr.isnew(1);
223         addr.usr(patron.id());
224         addr.country(defaultCountry);
225
226         if(!patron.addresses()) 
227                 patron.addresses([]);
228
229         if(patron.addresses().length == 0) {
230                 patron.mailing_address(addr);
231                 patron.billing_address(addr);
232         }
233
234         addr.valid(1);
235         addr.within_city_limits(1);
236
237         uEditBuildAddrFields(patron, addr);
238         patron.addresses().push(addr);
239         uEditIterateFields(function(f) { uEditCheckValid(f); });
240         uEditCheckErrors();
241 }
242
243
244 /* kicks off the UI drawing */
245 function uEditDraw(identTypes, groups, statCats, surveys, netLevels ) {
246         hideMe($('uedit_loading'));
247         unHideMe($('ue_maintd'));
248
249         dataFields = [];
250         uEditDrawIDTypes(identTypes);
251         uEditDrawGroups(groups);
252         uEditDrawStatCats(statCats);
253         uEditDrawSurveys(surveys);
254         uEditDrawNetLevels(netLevels);
255         uEditDefineData(patron);
256
257         uEditIterateFields(function(f) { uEditActivateField(f) });
258         uEditIterateFields(function(f) { uEditCheckValid(f); });
259         uEditCheckErrors();
260 }
261
262
263 /** Applies the event handlers and sets the data for the field */
264 function uEditActivateField(field) {
265
266         if( field.widget.id ) {
267                 field.widget.node = $(field.widget.id);
268
269         } else {
270                 field.widget.node = 
271                         $n(field.widget.base, field.widget.name);
272         }
273
274         uEditSetOnchange(field);
275
276         if(field.widget.onblur) {
277                 field.widget.node.onblur = 
278                         function() { field.widget.onblur(field); };
279         }
280
281         field.widget.node.disabled = field.widget.disabled;
282         if(field.object == null) return;
283         var val = field.object[field.key]();
284         if(val == null) return;
285
286         if( field.widget.type == 'input' )
287                 field.widget.node.value = val;
288
289         if( field.widget.type == 'select' )
290                 setSelector(field.widget.node, val);
291
292         if( field.widget.type == 'checkbox' )
293                 field.widget.node.checked = 
294                         (val && val != 'f') ? true : false;
295
296         if( field.widget.onload ) 
297                 field.widget.onload(val);
298 }
299
300
301 /* set up the onchange event for the field */
302 function uEditSetOnchange(field) {
303         var func = function() {uEditOnChange( field );}
304         field.widget.node.onchange = func;
305
306         if(field.widget.type != 'select')
307                 field.widget.node.onkeyup = func;
308 }
309
310 /* find the current value of the field object's widget */
311 function uEditNodeVal(field) {
312         if(field.widget.type == 'input')
313                 return field.widget.node.value;
314
315         if(field.widget.type == 'checkbox')
316                 return field.widget.node.checked;
317
318         if(field.widget.type == 'select')
319                 return getSelectorVal(field.widget.node);
320 }
321
322
323 /* update a field value */
324 function uEditOnChange(field) {
325
326         var newval = uEditNodeVal(field);
327         field.object[field.key](newval);
328         field.object.ischanged(1);
329
330         if(field.widget.onpostchange)
331                 field.widget.onpostchange(field, newval);
332
333
334         uEditIterateFields(function(f) { uEditCheckValid(f); });
335         uEditCheckErrors();
336 }
337
338
339 function uEditCheckValid(field) {
340         var newval = uEditNodeVal(field);
341
342         if(newval) {
343
344                 if(field.widget.regex) { 
345                         if(newval.match(field.widget.regex)) 
346                                 removeCSSClass(field.widget.node, CSS_INVALID_DATA);
347                         else
348                                 addCSSClass(field.widget.node, CSS_INVALID_DATA);
349
350                 } else {
351                         removeCSSClass(field.widget.node, CSS_INVALID_DATA);
352                 }
353
354         } else {
355
356                 if(field.required) {
357                         addCSSClass(field.widget.node, CSS_INVALID_DATA);
358
359                 } else {
360                         removeCSSClass(field.widget.node, CSS_INVALID_DATA);
361                 }
362         }
363 }
364
365 /* find a field object by object key */
366 function uEditFindFieldByKey(key) {
367         var fields = grep( dataFields,
368                 function(item) { return (item.key == key); });
369         return (fields) ? fields[0] : null;
370 }
371
372 /* find a list of fields by object key */
373 function uEditFindFieldsByKey(key) {
374         return grep( dataFields,
375                 function(item) { return (item.key == key); });
376 }
377
378 /* find a field object by widget id */
379 function uEditFindFieldByWId(id) {
380         var fields = grep( dataFields,
381                 function(item) { return (item.widget.id == id); });
382         return (fields) ? fields[0] : null;
383 }
384
385
386 function uEditIterateFields(callback) {
387         for( var f in dataFields ) 
388                 callback(dataFields[f]);
389 }
390
391
392 function uEditGetErrorStrings() {
393         var errors = [];
394         uEditIterateFields(
395                 function(field) { 
396                         if(field.errkey) {
397                                 if( field.widget.node.className.indexOf(CSS_INVALID_DATA) != -1) {
398                                         var str = $(field.errkey).innerHTML;
399                                         if(str) errors.push(str);
400                                 }
401                         }
402                 }
403         );
404
405         /* munge up something for all of the required surveys 
406                 (which are not registered with the fields) */
407         if( patron.isnew() ) {
408                 var sel = $('ue_survey_table');
409
410                 if( sel ) {
411                         var rows = sel.getElementsByTagName('tr');
412
413                         for( var r in rows ) {
414                 
415                                 var row = rows[r];
416                                 var sel = $n(row, 'ue_survey_answer');
417                                 if(!sel) continue;
418                                 var qstn = row.getAttribute('question');
419                 
420                                 if(qstn) {
421                                         qstn            = surveyQuestionsCache[qstn];
422                                         survey  = surveysCache[qstn.survey()];
423                                         var val = getSelectorVal(sel);
424                                         if(!val && isTrue(survey.required()))
425                                                 errors.push($('ue_bad_survey').innerHTML + ' : ' + qstn.question());
426                                 }
427                         }
428                 }
429         }
430
431         /* ------------------------------------------------------------ */
432
433         if(errors[0]) return errors;
434         return null;
435 }
436
437 function uEditAlertErrors() {
438         var errors = uEditGetErrorStrings();
439         if(!errors) return false;
440         alert(errors.join("\n"));
441         return true;
442 }
443
444
445 /* send the user to the database */
446 function uEditSaveUser(cloneme) {
447
448         if(uEditGetErrorStrings()) {
449                 uEditAlertErrors();
450                 return;
451         }
452
453         /* null is unique in the db, but '' is not */
454         if( ! patron.ident_value() ) patron.ident_value(null);
455         //if( ! patron.ident_type2() ) patron.ident_type2(null);
456         if( ! patron.ident_value2() ) patron.ident_value2(null);
457         patron.ident_type2(null);
458
459         if(! patron.dob() ) patron.dob(null);
460
461         var req = new Request(UPDATE_PATRON, SESSION, patron);
462         req.alertEvent = false;
463         req.send(true);
464         var newuser = req.result();
465
466         var evt;
467         if( (evt = checkILSEvent(newuser)) || ! newuser ) {
468                 if(evt) alert(js2JSON(newuser));
469                 return;
470         } 
471
472         alert($('ue_success').innerHTML);
473
474         if(cloneme) {
475                 /* if the user we just created was a clone, and we want to clone it,
476                 we really want to clone the original */
477                 if( clone ) cloneme = clone;
478                 else cloneme = newuser.id();
479         }
480
481         if (window.xulG && typeof window.xulG.on_save == 'function') {
482                 _debug("xulG funcs defined...");
483                 if( !patron.isnew() && cloneme ) {
484                         _debug("calling spawn_editor to clone user...");
485                         window.xulG.spawn_editor({ses:cgi.param('ses'),clone:cloneme});
486                 }
487                 window.xulG.on_save(newuser, cloneme); 
488
489         } else {
490
491                 _debug("xulG funcs not defined, refreshing page..");
492                 var href = location.href;
493
494                 href = href.replace(/\&?usr=\d+/, '');
495                 href = href.replace(/\&?clone=\d+/, '');
496
497                 if( cloneme ) href += '&clone=' + cloneme;
498                 location.href = href;
499         }
500 }
501
502 function uEditCancel() {
503         var href = location.href;
504         href = href.replace(/\&?usr=\d+/, '');
505         href = href.replace(/\&?clone=\d+/, '');
506         var id = cgi.param('usr')
507         /* reload the current user if available */
508         if( id ) href += "&usr=" + id;
509         location.href = href;
510 }
511
512
513 var uEditDupHashes = {};
514 var uEditDupTemplate;
515
516 function uEditRunDupeSearch(type, search_hash) {
517
518         if(!patron.isnew()) return;
519
520         _debug('dup search: ' + js2JSON(search_hash));
521
522         var req = new Request(PATRON_SEARCH, SESSION, search_hash);
523
524         var container = $('dup_div_container');
525         if(!uEditDupTemplate)
526                 uEditDupTemplate = container.removeChild($('dup_div'));
527
528         /* clear any existing dups for this type */
529         iterate( container.getElementsByTagName('div'),
530                 function(d) {
531                         if( d.getAttribute('type') == type ) {
532                                 container.removeChild(d)
533                                 return;
534                         }
535                 }
536         );
537
538         req.callback(
539                 function(r) {
540                         uEditHandleDupResults( r.getResultObject(), search_hash, type, container );
541                 }
542         );
543         req.send();
544 }
545
546
547 function uEditHandleDupResults(ids, search_hash, type, container) {
548
549         _debug('dup search results: ' + js2JSON(ids));
550
551         if(!(ids && ids[0]))  /* no results */
552                 return uEditDupHashes[type] = null;
553
554         /* add a dup link to the UI and plug in the data */
555         var node = uEditDupTemplate.cloneNode(true);
556         container.appendChild(node);
557         node.setAttribute('type', type);
558
559         var link = $n(node, 'link');
560         link.setAttribute('type', type);
561         unHideMe(link);
562         $n(node,'count').appendChild(text(ids.length));
563
564         for( var o in search_hash ) 
565                 $n(node, 'data').appendChild(
566                         text(search_hash[o].value + ' '));
567
568         uEditDupHashes[type] = search_hash;
569
570         switch(type) {
571                 case 'ident' :
572                         if(confirm($('ue_dup_ident1').innerHTML)) 
573                                 uEditShowSearch(null, type);
574                         break;
575         }
576 }
577
578
579 function uEditShowSearch(link,type) {
580         if(!type) type = link.getAttribute('type');
581         if(window.xulG)
582                 window.xulG.spawn_search(uEditDupHashes[type]); 
583         else alert('Search would be:\n' + js2JSON(uEditDupHashes[type]));
584 }
585
586 function uEditMarkCardLost() {
587
588         for( var c in patron.cards() ) {
589
590                 var card = patron.cards()[c];
591                 if( patron.card().id() == card.id() ) {
592
593                         /* de-activite the current card */
594                         card.ischanged(1);
595                         card.active(0);
596
597                         /* create a new card for the patron */
598                         var newcard = new ac();
599                         newcard.id(uEditCardVirtId--);
600                         newcard.isnew(1);
601                         patron.card(newcard);
602                         patron.cards().push(newcard);
603
604
605                         /* reset the widget */
606                         var field = uEditFindFieldByWId('ue_barcode');
607                         field.widget.node.disabled = false;
608                         field.widget.node.value = "";
609                         field.widget.node.onchange();
610                         field.object = newcard;
611                 }
612         }
613 }
614
615
616 function compactArray(arr) {
617         var a = [];
618         for( var i = 0; arr && i < arr.length; i++ ) {
619                 if( arr[i] != null )
620                         a.push(arr[i]);
621         }
622         return a;
623 }