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