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