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