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