fixed bug which caused the user editor to alert errors
[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                 /* do we need to display the parent / gurdian field? */
98                 uEditCheckDOB(uEditFindFieldByKey('dob'));
99
100                 $('ue_barcode').disabled = true;
101                 unHideMe($('ue_mark_card_lost'));
102                 unHideMe($('ue_reset_pw'));
103                 uEditCheckEditPerm();
104         }
105
106         if(PERMS['BAR_PATRON'] == -1) 
107                 $('ue_barred').disabled = true;
108 }
109
110
111 /* if this user does not have permission to put users into
112         the edited users group, they do not have permission to 
113         edit this user */
114 function uEditCheckEditPerm() {
115
116         var perm = uEditFindGroupPerm(groupsCache[patron.profile()]);   
117         /*
118         _debug("editing user with group app perm "+patron.profile()+' : '+
119                 groupsCache[patron.profile()].name() +', and perm = ' + perm);
120                 */
121
122         if(PERMS[perm] != -1) return;
123
124         /* we can edit our own account, but not others in our group */
125         if( patron.id() != USER.id() ){
126                 _debug("we are not allowed to edit this user");
127         
128                 $('ue_save').disabled = true;
129                 $('ue_save_clone').disabled = true;
130         
131                 uEditIterateFields(
132                         function(f) {
133                                 if( f && f.widget && f.widget.node )
134                                         f.widget.node.disabled = true;
135                         }       
136                 );      
137
138         }
139
140         var node = $('ue_profile').parentNode;
141         node.removeChild($('ue_profile'));
142         node.appendChild(elem('span',null,groupsCache[patron.profile()].name()));
143
144         var field = uEditFindFieldByKey('profile');
145         field.required = false;
146         removeCSSClass(field.widget.node, CSS_INVALID_DATA);
147         uEditCheckErrors();
148 }
149
150
151 /* creates a new patron object with card attached */
152 var uEditCardVirtId = -1;
153 function uEditNewPatron() {
154         var patron = new au(); 
155         patron.isnew(1);
156         patron.id(-1);
157         card = new ac();
158         card.id(uEditCardVirtId--);
159         card.isnew(1);
160         patron.card(card);
161         patron.cards([card]);
162         patron.stat_cat_entries([]);
163         patron.survey_responses([]);
164         patron.addresses([]);
165         patron.home_ou(USER.ws_ou());
166         uEditMakeRandomPw(patron);
167         return patron;
168 }
169
170 function uEditMakeRandomPw(patron) {
171         var rand  = Math.random();
172         rand = parseInt(rand * 10000) + '';
173         while(rand.length < 4) rand += '0';
174         appendClear($('ue_password_plain'),text(rand));
175         unHideMe($('ue_password_gen'));
176         patron.passwd(rand);
177         return rand;
178 }
179
180 function uEditResetPw() { 
181         var pw = uEditMakeRandomPw(patron);     
182         $('ue_password1').value = pw;
183         $('ue_password2').value = pw;
184 }
185
186 function uEditClone(clone) {
187
188         var cloneUser = fetchFleshedUser(clone);
189         patron.usrgroup(cloneUser.usrgroup());
190
191         if( cloneUser.day_phone() )
192                 $('ue_day_phone').value = cloneUser.day_phone();
193         if( cloneUser.evening_phone() )
194                 $('ue_night_phone').value = cloneUser.evening_phone();
195         if( cloneUser.other_phone() )
196                 $('ue_other_phone').value = cloneUser.other_phone();
197         setSelector($('ue_org_selector'), cloneUser.home_ou());
198
199
200         setSelector($('ue_profile'), cloneUser.profile());
201
202         /* force the expire date to be set */
203         $('ue_profile').onchange();
204
205         for( var a in cloneUser.addresses() ) {
206                 var addr = cloneUser.addresses()[a];
207                 if( cloneUser.mailing_address && 
208                                 addr.id() == cloneUser.mailing_address().id() )
209                         patron.mailing_address(addr);
210                 if( cloneUser.billing_address() &&
211                                 addr.id() == cloneUser.billing_address().id() )
212                         patron.billing_address(addr);
213                 patron.addresses().push(addr);
214         }
215
216         uEditBuildAddrs(patron);
217 }
218
219
220 /* Creates a new blank address, 
221         adds it to the user and the fields array */
222 var uEditVirtualAddrId = -1;
223 function uEditCreateNewAddr() {
224         var addr = new aua();
225
226         addr.id(uEditVirtualAddrId--);
227         addr.isnew(1);
228         addr.usr(patron.id());
229         addr.country(defaultCountry);
230
231         if(!patron.addresses()) 
232                 patron.addresses([]);
233
234         if(patron.addresses().length == 0) {
235                 patron.mailing_address(addr);
236                 patron.billing_address(addr);
237         }
238
239         addr.valid(1);
240         addr.within_city_limits(1);
241
242         uEditBuildAddrFields(patron, addr);
243         patron.addresses().push(addr);
244         uEditIterateFields(function(f) { uEditCheckValid(f); });
245         uEditCheckErrors();
246 }
247
248
249 /* kicks off the UI drawing */
250 function uEditDraw(identTypes, groups, statCats, surveys, netLevels ) {
251         hideMe($('uedit_loading'));
252         unHideMe($('ue_maintd'));
253
254         dataFields = [];
255         uEditDrawIDTypes(identTypes);
256         uEditDrawGroups(groups, null, null, true);
257         uEditDrawStatCats(statCats);
258         uEditDrawSurveys(surveys);
259         uEditDrawNetLevels(netLevels);
260         uEditDefineData(patron);
261
262         uEditIterateFields(function(f) { uEditActivateField(f) });
263         uEditIterateFields(function(f) { uEditCheckValid(f); });
264         uEditCheckErrors();
265 }
266
267
268 /** Applies the event handlers and sets the data for the field */
269 function uEditActivateField(field) {
270
271         if( field.widget.id ) {
272                 field.widget.node = $(field.widget.id);
273
274         } else {
275                 field.widget.node = 
276                         $n(field.widget.base, field.widget.name);
277         }
278
279         uEditSetOnchange(field);
280
281         if(field.widget.onblur) {
282                 field.widget.node.onblur = 
283                         function() { field.widget.onblur(field); };
284         }
285
286         field.widget.node.disabled = field.widget.disabled;
287         if(field.object == null) return;
288         var val = field.object[field.key]();
289         if(val == null) return;
290
291         if( field.widget.type == 'input' )
292                 field.widget.node.value = val;
293
294         if( field.widget.type == 'select' )
295                 setSelector(field.widget.node, val);
296
297         if( field.widget.type == 'checkbox' )
298                 field.widget.node.checked = 
299                         (val && val != 'f') ? true : false;
300
301         if( field.widget.onload ) 
302                 field.widget.onload(val);
303 }
304
305
306 /* set up the onchange event for the field */
307 function uEditSetOnchange(field) {
308         var func = function() {uEditOnChange( field );}
309         field.widget.node.onchange = func;
310
311         if(field.widget.type != 'select')
312                 field.widget.node.onkeyup = func;
313 }
314
315 /* find the current value of the field object's widget */
316 function uEditNodeVal(field) {
317         if(field.widget.type == 'input')
318                 return field.widget.node.value;
319
320         if(field.widget.type == 'checkbox')
321                 return field.widget.node.checked;
322
323         if(field.widget.type == 'select')
324                 return getSelectorVal(field.widget.node);
325 }
326
327
328 /* update a field value */
329 function uEditOnChange(field) {
330
331         var newval = uEditNodeVal(field);
332         field.object[field.key](newval);
333         field.object.ischanged(1);
334
335         if(field.widget.onpostchange)
336                 field.widget.onpostchange(field, newval);
337
338         //_debug(field.key+' = '+newval);
339
340         uEditIterateFields(function(f) { uEditCheckValid(f); });
341         uEditCheckErrors();
342 }
343
344
345 function uEditCheckValid(field) {
346         var newval = uEditNodeVal(field);
347
348         if(newval) {
349
350                 if(field.widget.regex) { 
351                         if(newval.match(field.widget.regex)) 
352                                 removeCSSClass(field.widget.node, CSS_INVALID_DATA);
353                         else
354                                 addCSSClass(field.widget.node, CSS_INVALID_DATA);
355
356                 } else {
357                         removeCSSClass(field.widget.node, CSS_INVALID_DATA);
358                 }
359
360         } else {
361
362                 if(field.required) {
363                         addCSSClass(field.widget.node, CSS_INVALID_DATA);
364
365                 } else {
366                         removeCSSClass(field.widget.node, CSS_INVALID_DATA);
367                 }
368         }
369
370 }
371
372 /* find a field object by object key */
373 function uEditFindFieldByKey(key) {
374         var fields = grep( dataFields,
375                 function(item) { return (item.key == key); });
376         return (fields) ? fields[0] : null;
377 }
378
379 /* find a list of fields by object key */
380 function uEditFindFieldsByKey(key) {
381         return grep( dataFields,
382                 function(item) { return (item.key == key); });
383 }
384
385 /* find a field object by widget id */
386 function uEditFindFieldByWId(id) {
387         var fields = grep( dataFields,
388                 function(item) { return (item.widget.id == id); });
389         return (fields) ? fields[0] : null;
390 }
391
392
393 function uEditIterateFields(callback) {
394         for( var f in dataFields ) 
395                 callback(dataFields[f]);
396 }
397
398
399 function uEditGetErrorStrings() {
400         var errors = [];
401         uEditIterateFields(
402                 function(field) { 
403                         if(field.errkey) {
404                                 if( !field.object.isdeleted() ) {
405                                         if( field.widget.node.className.indexOf(CSS_INVALID_DATA) != -1) {
406                                                 var str = $(field.errkey).innerHTML;
407                                                 if(str) errors.push(str);
408                                         }
409                                 }
410                         }
411                 }
412         );
413
414         /* munge up something for all of the required surveys 
415                 (which are not registered with the fields) */
416         if( patron.isnew() ) {
417                 var sel = $('ue_survey_table');
418
419                 if( sel ) {
420                         var rows = sel.getElementsByTagName('tr');
421
422                         for( var r in rows ) {
423                 
424                                 var row = rows[r];
425                                 var sel = $n(row, 'ue_survey_answer');
426                                 if(!sel) continue;
427                                 var qstn = row.getAttribute('question');
428                 
429                                 if(qstn) {
430                                         qstn            = surveyQuestionsCache[qstn];
431                                         survey  = surveysCache[qstn.survey()];
432                                         var val = getSelectorVal(sel);
433                                         if(!val && isTrue(survey.required()))
434                                                 errors.push($('ue_bad_survey').innerHTML + ' : ' + qstn.question());
435                                 }
436                         }
437                 }
438         }
439
440         /* ------------------------------------------------------------ */
441
442         if(errors[0]) return errors;
443         return null;
444 }
445
446 function uEditAlertErrors() {
447         var errors = uEditGetErrorStrings();
448         if(!errors) return false;
449         alert(errors.join("\n"));
450         return true;
451 }
452
453
454 /* send the user to the database */
455 function uEditSaveUser(cloneme) {
456
457         if(uEditGetErrorStrings()) {
458                 uEditAlertErrors();
459                 return;
460         }
461
462         /* null is unique in the db, but '' is not */
463         if( ! patron.ident_value() ) patron.ident_value(null);
464         //if( ! patron.ident_type2() ) patron.ident_type2(null);
465         if( ! patron.ident_value2() ) patron.ident_value2(null);
466         patron.ident_type2(null);
467
468         if(! patron.dob() ) patron.dob(null);
469
470         _debug("Saving patron with card: " + js2JSON(patron.card()));
471         _debug("Saving full patron: " + js2JSON(patron));
472
473         //for( var c in patron
474
475         var req = new Request(UPDATE_PATRON, SESSION, patron);
476         req.alertEvent = false;
477         req.send(true);
478         var newuser = req.result();
479
480         var evt;
481         if( (evt = checkILSEvent(newuser)) || ! newuser ) {
482                 if(evt) {
483                         var j = js2JSON(newuser); 
484                         alert(j);
485                         _debug("USER UPDATE FAILED:\n" + j);
486                 }
487                 return;
488         } 
489
490         alert($('ue_success').innerHTML);
491
492         if(cloneme) {
493                 /* if the user we just created was a clone, and we want to clone it,
494                 we really want to clone the original */
495                 if( clone ) cloneme = clone;
496                 else cloneme = newuser.id();
497         }
498
499
500         if( cloneme ) {
501
502                 if(window.xulG &&
503                         typeof window.xulG.spawn_editor == 'function' && 
504
505                         !patron.isnew() ) {
506                                 _debug("xulG clone spawning new interface...");
507                                 window.xulG.spawn_editor({ses:cgi.param('ses'),clone:cloneme});
508                                 uEditRefresh();
509
510                 } else {
511
512                         var href = location.href;
513                         href = href.replace(/\&?usr=\d+/, '');
514                         href = href.replace(/\&?clone=\d+/, '');
515                         href += '&clone=' + cloneme;
516                         location.href = href;
517                 }
518
519         } else {
520
521                 uEditRefresh();
522         }
523
524         uEditRefreshXUL(newuser);
525 }
526
527
528 function uEditRefreshXUL(newuser) {
529         if (window.xulG && typeof window.xulG.on_save == 'function') 
530                 window.xulG.on_save(newuser);
531 }
532
533 function uEditRefresh() {
534         var href = location.href;
535         href = href.replace(/\&?clone=\d+/, '');
536         location.href = href;
537 }
538
539
540 function uEditCancel() {
541         var href = location.href;
542         href = href.replace(/\&?usr=\d+/, '');
543         href = href.replace(/\&?clone=\d+/, '');
544         var id = cgi.param('usr')
545         /* reload the current user if available */
546         if( id ) href += "&usr=" + id;
547         location.href = href;
548 }
549
550
551 var uEditDupHashes = {};
552 var uEditDupTemplate;
553
554 function uEditRunDupeSearch(type, search_hash) {
555
556         if(!patron.isnew()) return;
557
558         _debug('dup search: ' + js2JSON(search_hash));
559
560         var req = new Request(PATRON_SEARCH, SESSION, search_hash);
561
562         var container = $('dup_div_container');
563         if(!uEditDupTemplate)
564                 uEditDupTemplate = container.removeChild($('dup_div'));
565
566         /* clear any existing dups for this type */
567         iterate( container.getElementsByTagName('div'),
568                 function(d) {
569                         if( d.getAttribute('type') == type ) {
570                                 container.removeChild(d)
571                                 return;
572                         }
573                 }
574         );
575
576         req.callback(
577                 function(r) {
578                         uEditHandleDupResults( r.getResultObject(), search_hash, type, container );
579                 }
580         );
581         req.send();
582 }
583
584
585 function uEditHandleDupResults(ids, search_hash, type, container) {
586
587         _debug('dup search results: ' + js2JSON(ids));
588
589         if(!(ids && ids[0]))  /* no results */
590                 return uEditDupHashes[type] = null;
591
592         /* add a dup link to the UI and plug in the data */
593         var node = uEditDupTemplate.cloneNode(true);
594         container.appendChild(node);
595         node.setAttribute('type', type);
596
597         var link = $n(node, 'link');
598         link.setAttribute('type', type);
599         unHideMe(link);
600         $n(node,'count').appendChild(text(ids.length));
601
602         for( var o in search_hash ) 
603                 $n(node, 'data').appendChild(
604                         text(search_hash[o].value + ' '));
605
606         uEditDupHashes[type] = search_hash;
607
608         switch(type) {
609                 case 'ident' :
610                         if(confirm($('ue_dup_ident1').innerHTML)) 
611                                 uEditShowSearch(null, type);
612                         break;
613         }
614 }
615
616
617 function uEditShowSearch(link,type) {
618         if(!type) type = link.getAttribute('type');
619         if(window.xulG)
620                 window.xulG.spawn_search(uEditDupHashes[type]); 
621         else alert('Search would be:\n' + js2JSON(uEditDupHashes[type]));
622 }
623
624 function uEditMarkCardLost() {
625
626         for( var c in patron.cards() ) {
627
628                 var card = patron.cards()[c];
629                 if( patron.card().id() == card.id() ) {
630
631                         /* de-activite the current card */
632                         card.ischanged(1);
633                         card.active(0);
634
635                         if( !card.barcode() ) {
636                                 /* a card exists in the array with no barcode */
637                                 ueRemoveCard(card.id());
638
639                         } else if( card.isnew() && card.active() == 0 ) {
640                                 /* a new card was created, then never used, removing.. */
641                                 _debug("removing new inactive card "+card.barcode());
642                                 ueRemoveCard(card.id());
643                         }
644
645                         /* create a new card for the patron */
646                         var newcard = new ac();
647                         newcard.id(uEditCardVirtId--);
648                         newcard.isnew(1);
649                         patron.card(newcard);
650                         patron.cards().push(newcard);
651
652
653                         /* reset the widget */
654                         var field = uEditFindFieldByWId('ue_barcode');
655                         field.widget.node.disabled = false;
656                         field.widget.node.value = "";
657                         field.widget.node.onchange();
658                         field.object = newcard;
659                         _debug("uEditMarkCardLost(): created new card object for user");
660                 }
661         }
662 }
663
664
665 function ueRemoveCard(id) {
666         _debug("removing card from cards() array: " + id);
667         var cds = grep( patron.cards(), function(c){return (c.id() != id)});
668         if(!cds) cds = [];
669         for( var j = 0; j < cds.length; j++ )
670                 _debug("patron card array now has :  "+cds[j].id());
671         patron.cards(cds);
672 }
673
674
675
676 function compactArray(arr) {
677         var a = [];
678         for( var i = 0; arr && i < arr.length; i++ ) {
679                 if( arr[i] != null )
680                         a.push(arr[i]);
681         }
682         return a;
683 }