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