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