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