]> git.evergreen-ils.org Git - Evergreen.git/blob - Evergreen/xul/staff_client/server/patron/ue.js
Another monster i18n patch from Craig Ricciuto
[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.stat_cat_entries([]);
233         patron.survey_responses([]);
234         patron.addresses([]);
235         patron.home_ou(USER.ws_ou());
236         uEditMakeRandomPw(patron);
237         return patron;
238 }
239
240 function uEditMakeRandomPw(patron) {
241         var rand  = Math.random();
242         rand = parseInt(rand * 10000) + '';
243         while(rand.length < 4) rand += '0';
244         appendClear($('ue_password_plain'),text(rand));
245         unHideMe($('ue_password_gen'));
246         patron.passwd(rand);
247         return rand;
248 }
249
250 function uEditResetPw() { 
251         var pw = uEditMakeRandomPw(patron);     
252         $('ue_password1').value = pw;
253         $('ue_password2').value = pw;
254     $('ue_password1').onchange();
255 }
256
257 function uEditClone(clone) {
258
259         var cloneUser = fetchFleshedUser(clone);
260         patron.usrgroup(cloneUser.usrgroup());
261
262         if( cloneUser.day_phone() ) {
263                 $('ue_day_phone').value = cloneUser.day_phone();
264             $('ue_day_phone').onchange();
265     }
266
267         if( cloneUser.evening_phone() ) {
268                 $('ue_night_phone').value = cloneUser.evening_phone();
269                 $('ue_night_phone').onchange();
270     }
271
272         if( cloneUser.other_phone() ) {
273                 $('ue_other_phone').value = cloneUser.other_phone();
274                 $('ue_other_phone').onchange();
275     }
276
277         setSelector($('ue_org_selector'), cloneUser.home_ou());
278         setSelector($('ue_profile'), cloneUser.profile());
279
280         /* force the expire date to be set */
281         $('ue_profile').onchange();
282         $('ue_org_selector').onchange();
283
284         for( var a in cloneUser.addresses() ) {
285                 var addr = cloneUser.addresses()[a];
286                 if( cloneUser.mailing_address && 
287                                 addr.id() == cloneUser.mailing_address().id() )
288                         patron.mailing_address(addr);
289                 if( cloneUser.billing_address() &&
290                                 addr.id() == cloneUser.billing_address().id() )
291                         patron.billing_address(addr);
292                 patron.addresses().push(addr);
293         }
294
295         uEditBuildAddrs(patron);
296 }
297
298
299 /* Creates a new blank address, 
300         adds it to the user and the fields array */
301 var uEditVirtualAddrId = -1;
302 function uEditCreateNewAddr() {
303         var addr = new aua();
304
305         addr.id(uEditVirtualAddrId--);
306         addr.isnew(1);
307         addr.usr(patron.id());
308         addr.country(defaultCountry);
309
310         if(!patron.addresses()) 
311                 patron.addresses([]);
312
313         if(patron.addresses().length == 0) {
314                 patron.mailing_address(addr);
315                 patron.billing_address(addr);
316         }
317
318         addr.valid(1);
319         addr.within_city_limits(1);
320
321         uEditBuildAddrFields(patron, addr);
322         patron.addresses().push(addr);
323         uEditIterateFields(function(f) { uEditCheckValid(f); });
324         uEditCheckErrors();
325 }
326
327
328 /* kicks off the UI drawing */
329 function uEditDraw(identTypes, groups, statCats, surveys, netLevels ) {
330         hideMe($('uedit_loading'));
331         unHideMe($('ue_maintd'));
332
333         dataFields = [];
334         uEditDrawIDTypes(identTypes);
335         uEditDrawGroups(groups, null, null, true);
336         uEditDrawStatCats(statCats);
337         uEditDrawSurveys(surveys);
338         uEditDrawNetLevels(netLevels);
339         uEditDefineData(patron);
340
341         uEditIterateFields(function(f) { uEditActivateField(f) });
342         uEditIterateFields(function(f) { uEditCheckValid(f); });
343         uEditCheckErrors();
344 }
345
346
347 /** Applies the event handlers and sets the data for the field */
348 function uEditActivateField(field) {
349
350         if( field.widget.id ) {
351                 field.widget.node = $(field.widget.id);
352
353         } else {
354                 field.widget.node = 
355                         $n(field.widget.base, field.widget.name);
356         }
357
358         uEditSetOnchange(field);
359
360         if(field.widget.onblur) {
361                 field.widget.node.onblur = 
362                         function() { field.widget.onblur(field); };
363         }
364
365         field.widget.node.disabled = field.widget.disabled;
366         if(field.object == null) return;
367         var val = field.object[field.key]();
368         if(val == null) return;
369
370         if( field.widget.type == 'input' )
371                 field.widget.node.value = val;
372
373         if( field.widget.type == 'select' )
374                 setSelector(field.widget.node, val);
375
376         if( field.widget.type == 'checkbox' )
377                 field.widget.node.checked = 
378                         (val && val != 'f') ? true : false;
379
380         if( field.widget.onload ) 
381                 field.widget.onload(val);
382 }
383
384
385 /* set up the onchange event for the field */
386 function uEditSetOnchange(field) {
387         var func = function() {uEditOnChange( field );}
388         field.widget.node.onchange = func;
389
390         if(field.widget.type != 'select')
391                 field.widget.node.onkeyup = func;
392 }
393
394 /* find the current value of the field object's widget */
395 function uEditNodeVal(field) {
396         if(field.widget.type == 'input')
397                 return field.widget.node.value;
398
399         if(field.widget.type == 'checkbox')
400                 return field.widget.node.checked;
401
402         if(field.widget.type == 'select')
403                 return getSelectorVal(field.widget.node);
404 }
405
406
407 /* update a field value */
408 function uEditOnChange(field) {
409
410         var newval = uEditNodeVal(field);
411         field.object[field.key](newval);
412         field.object.ischanged(1);
413
414         if(field.widget.onpostchange)
415                 field.widget.onpostchange(field, newval);
416
417         //_debug(field.key+' = '+newval);
418
419         uEditIterateFields(function(f) { uEditCheckValid(f); });
420         uEditCheckErrors();
421
422    uEditSetUnload();
423 }
424
425
426 function uEditCheckValid(field) {
427         var newval = uEditNodeVal(field);
428
429         if(newval) {
430
431                 if(field.widget.regex) { 
432                         if(newval.match(field.widget.regex)) 
433                                 removeCSSClass(field.widget.node, CSS_INVALID_DATA);
434                         else
435                                 addCSSClass(field.widget.node, CSS_INVALID_DATA);
436
437                 } else {
438                         removeCSSClass(field.widget.node, CSS_INVALID_DATA);
439                 }
440
441         } else {
442
443                 if(field.required) {
444                         addCSSClass(field.widget.node, CSS_INVALID_DATA);
445
446                 } else {
447                         removeCSSClass(field.widget.node, CSS_INVALID_DATA);
448                 }
449         }
450
451 }
452
453 /* find a field object by object key */
454 function uEditFindFieldByKey(key) {
455         var fields = grep( dataFields,
456                 function(item) { return (item.key == key); });
457         return (fields) ? fields[0] : null;
458 }
459
460 /* find a list of fields by object key */
461 function uEditFindFieldsByKey(key) {
462         return grep( dataFields,
463                 function(item) { return (item.key == key); });
464 }
465
466 /* find a field object by widget id */
467 function uEditFindFieldByWId(id) {
468         var fields = grep( dataFields,
469                 function(item) { return (item.widget.id == id); });
470         return (fields) ? fields[0] : null;
471 }
472
473
474 function uEditIterateFields(callback) {
475         for( var f in dataFields ) 
476                 callback(dataFields[f]);
477 }
478
479
480 function uEditGetErrorStrings() {
481         var errors = [];
482         uEditIterateFields(
483                 function(field) { 
484                         if(field.errkey) {
485                                 if( !field.object.isdeleted() ) {
486                                         if( field.widget.node.className.indexOf(CSS_INVALID_DATA) != -1) {
487                                                 var str = $(field.errkey).innerHTML;
488                                                 if(str) errors.push(str);
489                                         }
490                                 }
491                         }
492                 }
493         );
494
495         /* munge up something for all of the required surveys 
496                 (which are not registered with the fields) */
497         if( patron.isnew() ) {
498                 var sel = $('ue_survey_table');
499
500                 if( sel ) {
501                         var rows = sel.getElementsByTagName('tr');
502
503                         for( var r in rows ) {
504                 
505                                 var row = rows[r];
506                                 var sel = $n(row, 'ue_survey_answer');
507                                 if(!sel) continue;
508                                 var qstn = row.getAttribute('question');
509                 
510                                 if(qstn) {
511                                         qstn            = surveyQuestionsCache[qstn];
512                                         survey  = surveysCache[qstn.survey()];
513                                         var val = getSelectorVal(sel);
514                                         if(!val && isTrue(survey.required()))
515                                                 errors.push($('ue_bad_survey').innerHTML + ' : ' + qstn.question());
516                                 }
517                         }
518                 }
519         }
520
521         /* ------------------------------------------------------------ */
522
523         if(errors[0]) return errors;
524         return null;
525 }
526
527 function uEditAlertErrors() {
528         var errors = uEditGetErrorStrings();
529         if(!errors) return false;
530         alert(errors.join("\n"));
531         return true;
532 }
533
534
535 /* send the user to the database */
536 function uEditSaveUser(cloneme) {
537
538         if(uEditGetErrorStrings()) {
539                 uEditAlertErrors();
540                 return;
541         }
542
543         /* null is unique in the db, but '' is not */
544         if( ! patron.ident_value() ) patron.ident_value(null);
545         //if( ! patron.ident_type2() ) patron.ident_type2(null);
546         if( ! patron.ident_value2() ) patron.ident_value2(null);
547         patron.ident_type2(null);
548
549         if(! patron.dob() ) patron.dob(null);
550
551         _debug("Saving patron with card: " + js2JSON(patron.card()));
552         _debug("Saving full patron: " + js2JSON(patron));
553
554         //for( var c in patron
555
556         var req = new Request(UPDATE_PATRON, SESSION, patron);
557         req.alertEvent = false;
558         req.send(true);
559         var newuser = req.result();
560
561    uEditClearUnload();
562
563         var evt;
564         if( (evt = checkILSEvent(newuser)) || ! newuser ) {
565                 if(evt) {
566             evt = newuser;
567             if( evt.textcode == 'XACT_COLLISION' ) {
568                 if( confirmId('ue_xact_collision') )
569                     location.href = location.href;
570                 return;
571             }
572             var j = js2JSON(evt);
573                         alert(j);
574                         _debug("USER UPDATE FAILED:\n" + j);
575                 }
576                 return;
577         } 
578
579         alert($('ue_success').innerHTML);
580
581         if(cloneme) {
582                 /* if the user we just created was a clone, and we want to clone it,
583                 we really want to clone the original */
584                 if( clone ) cloneme = clone;
585                 else cloneme = newuser.id();
586         }
587
588
589         if( cloneme ) {
590
591                 if(window.xulG &&
592                         typeof window.xulG.spawn_editor == 'function' && 
593
594                         !patron.isnew() ) {
595                                 _debug("xulG clone spawning new interface...");
596                                 var ses = cgi.param('ses'); 
597                                 if (xulG) if (xulG.ses) ses = xulG.ses;
598                                 if (xulG) if (xulG.params) if (xulG.params.ses) ses = xulG.params.ses;
599                                 window.xulG.spawn_editor({ses:ses,clone:cloneme});
600                                 uEditRefresh();
601
602                 } else {
603
604                         var href = location.href;
605                         href = href.replace(/\&?usr=\d+/, '');
606                         href = href.replace(/\&?clone=\d+/, '');
607                         href += '&clone=' + cloneme;
608                         location.href = href;
609                 }
610
611         } else {
612
613                 uEditRefresh();
614         }
615
616         uEditRefreshXUL(newuser);
617 }
618
619
620 function uEditRefreshXUL(newuser) {
621         if (window.xulG && typeof window.xulG.on_save == 'function') 
622                 window.xulG.on_save(newuser);
623 }
624
625 function uEditRefresh() {
626         var href = location.href;
627         href = href.replace(/\&?clone=\d+/, '');
628         location.href = href;
629 }
630
631
632 function uEditCancel() {
633         var href = location.href;
634         href = href.replace(/\&?usr=\d+/, '');
635         href = href.replace(/\&?clone=\d+/, '');
636         var id = cgi.param('usr'); 
637         if (xulG) if (xulG.usr) id = xulG.usr;
638         if (xulG) if (xulG.params) if (xulG.params.usr) id = xulG.params.usr;
639         /* reload the current user if available */
640         if( id ) href += "&usr=" + id;
641         location.href = href;
642 }
643
644
645 var uEditDupHashes = {};
646 var uEditDupTemplate;
647
648 function uEditRunDupeSearch(type, search_hash) {
649
650         if(!patron.isnew()) return;
651
652         _debug('dup search: ' + js2JSON(search_hash));
653
654         var req = new Request(PATRON_SEARCH, SESSION, search_hash);
655
656         var container = $('dup_div_container');
657         if(!uEditDupTemplate)
658                 uEditDupTemplate = container.removeChild($('dup_div'));
659
660         /* clear any existing dups for this type */
661         iterate( container.getElementsByTagName('div'),
662                 function(d) {
663                         if( d.getAttribute('type') == type ) {
664                                 container.removeChild(d)
665                                 return;
666                         }
667                 }
668         );
669
670         req.callback(
671                 function(r) {
672                         uEditHandleDupResults( r.getResultObject(), search_hash, type, container );
673                 }
674         );
675         req.send();
676 }
677
678
679 function uEditHandleDupResults(ids, search_hash, type, container) {
680
681         _debug('dup search results: ' + js2JSON(ids));
682
683         if(!(ids && ids[0]))  /* no results */
684                 return uEditDupHashes[type] = null;
685
686         /* add a dup link to the UI and plug in the data */
687         var node = uEditDupTemplate.cloneNode(true);
688         container.appendChild(node);
689         node.setAttribute('type', type);
690
691         var link = $n(node, 'link');
692         link.setAttribute('type', type);
693         unHideMe(link);
694         $n(node,'count').appendChild(text(ids.length));
695
696         for( var o in search_hash ) 
697                 $n(node, 'data').appendChild(
698                         text(search_hash[o].value + ' '));
699
700         uEditDupHashes[type] = search_hash;
701
702         switch(type) {
703                 case 'ident' :
704                         if(confirm($('ue_dup_ident1').innerHTML)) 
705                                 uEditShowSearch(null, type);
706                         break;
707         }
708 }
709
710
711 function uEditShowSearch(link,type) {
712         if(!type) type = link.getAttribute('type');
713         if(window.xulG)
714                 window.xulG.spawn_search(uEditDupHashes[type]); 
715         else alert($("patronStrings").getString('web.staff.patron.ue.uedit_show_search.search_would_be', js2JSON(uEditDupHashes[type])));
716 }
717
718 function uEditMarkCardLost() {
719
720         for( var c in patron.cards() ) {
721
722                 var card = patron.cards()[c];
723                 if( patron.card().id() == card.id() ) {
724
725                         /* de-activite the current card */
726                         card.ischanged(1);
727                         card.active(0);
728
729                         if( !card.barcode() ) {
730                                 /* a card exists in the array with no barcode */
731                                 ueRemoveCard(card.id());
732
733                         } else if( card.isnew() && card.active() == 0 ) {
734                                 /* a new card was created, then never used, removing.. */
735                                 _debug("removing new inactive card "+card.barcode());
736                                 ueRemoveCard(card.id());
737                         }
738
739                         /* create a new card for the patron */
740                         var newcard = new ac();
741                         newcard.id(uEditCardVirtId--);
742                         newcard.isnew(1);
743                         patron.card(newcard);
744                         patron.cards().push(newcard);
745
746
747                         /* reset the widget */
748                         var field = uEditFindFieldByWId('ue_barcode');
749                         field.widget.node.disabled = false;
750                         field.widget.node.value = "";
751                         field.widget.node.onchange();
752                         field.object = newcard;
753                         _debug("uEditMarkCardLost(): created new card object for user");
754                 }
755         }
756 }
757
758
759 function ueRemoveCard(id) {
760         _debug("removing card from cards() array: " + id);
761         var cds = grep( patron.cards(), function(c){return (c.id() != id)});
762         if(!cds) cds = [];
763         for( var j = 0; j < cds.length; j++ )
764                 _debug("patron card array now has :  "+cds[j].id());
765         patron.cards(cds);
766 }
767
768
769
770 function compactArray(arr) {
771         var a = [];
772         for( var i = 0; arr && i < arr.length; i++ ) {
773                 if( arr[i] != null )
774                         a.push(arr[i]);
775         }
776         return a;
777 }