]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/actor/user/register.js
forward-ported the functionality for use-last-4-of-phone-as-default-password based...
[working/Evergreen.git] / Open-ILS / web / js / ui / default / actor / user / register.js
1 dojo.require('dojo.data.ItemFileReadStore');
2 dojo.require('dijit.form.Textarea');
3 dojo.require('dijit.form.FilteringSelect');
4 dojo.require('dijit.form.ComboBox');
5 dojo.require('dijit.form.NumberSpinner');
6 dojo.require('fieldmapper.IDL');
7 dojo.require('openils.PermaCrud');
8 dojo.require('openils.widget.AutoGrid');
9 dojo.require('openils.widget.AutoFieldWidget');
10 dojo.require('dijit.form.CheckBox');
11 dojo.require('dijit.form.Button');
12 dojo.require('dojo.date');
13 dojo.require('openils.CGI');
14 dojo.require('openils.XUL');
15 dojo.require('openils.Util');
16 dojo.require('openils.Event');
17
18 dojo.requireLocalization('openils.actor', 'register');
19 var localeStrings = dojo.i18n.getLocalization('openils.actor', 'register');
20
21
22 var pcrud;
23 var fmClasses = ['au', 'ac', 'aua', 'actsc', 'asv', 'asvq', 'asva'];
24 var fieldDoc = {};
25 var statCats;
26 var statCatTempate;
27 var surveys;
28 var staff;
29 var patron;
30 var uEditUsePhonePw = false;
31 var widgetPile = [];
32 var uEditCardVirtId = -1;
33 var uEditAddrVirtId = -1;
34 var orgSettings = {};
35 var userSettings = {};
36 var userSettingsToUpdate = {};
37 var userSettingTypes;
38 var tbody;
39 var addrTemplateRows;
40 var cgi;
41 var cloneUser;
42 var cloneUserObj;
43 var stageUser;
44 var optInSettings;
45
46
47 if(!window.xulG) var xulG = null;
48
49
50 function load() {
51     staff = new openils.User().user;
52     pcrud = new openils.PermaCrud();
53     cgi = new openils.CGI();
54     cloneUser = cgi.param('clone');
55     var userId = cgi.param('usr');
56     var stageUname = cgi.param('stage');
57
58     if(xulG) {
59             if(xulG.ses) openils.User.authtoken = xulG.ses;
60             if(xulG.clone !== null) cloneUser = xulG.clone;
61         if(xulG.usr !== null) userId = xulG.usr
62         if(xulG.params) {
63             var parms = xulG.params;
64                 if(parms.ses) 
65                 openils.User.authtoken = parms.ses;
66                 if(parms.clone) 
67                 cloneUser = parms.clone;
68             if(parms.usr !== null)
69                 userId = parms.usr;
70             if(parms.stage !== null)
71                 stageUname = parms.stage
72         }
73     }
74
75     orgSettings = fieldmapper.aou.fetchOrgSettingBatch(staff.ws_ou(), [
76         'global.juvenile_age_threshold',
77         'patron.password.use_phone',
78         'ui.patron.default_inet_access_level',
79         'circ.holds.behind_desk_pickup_supported'
80     ]);
81     for(k in orgSettings)
82         if(orgSettings[k])
83             orgSettings[k] = orgSettings[k].value;
84
85     uEditUsePhonePw = orgSettings['patron.password.use_phone'];
86     uEditFetchUserSettings(userId);
87
88     if(userId) {
89         patron = uEditLoadUser(userId);
90     } else {
91         if(stageUname) {
92             patron = uEditLoadStageUser(stageUname);
93         } else {
94             patron = uEditNewPatron();
95             if(cloneUser) 
96                 uEditCopyCloneData(patron);
97         }
98     }
99
100
101     var list = pcrud.search('fdoc', {fm_class:fmClasses});
102     for(var i in list) {
103         var doc = list[i];
104         if(!fieldDoc[doc.fm_class()])
105             fieldDoc[doc.fm_class()] = {};
106         fieldDoc[doc.fm_class()][doc.field()] = doc;
107     }
108
109     tbody = dojo.byId('uedit-tbody');
110
111     addrTemplateRows = dojo.query('tr[type=addr-template]', tbody);
112     dojo.forEach(addrTemplateRows, function(row) { row.parentNode.removeChild(row); } );
113     statCatTemplate = tbody.removeChild(dojo.byId('stat-cat-row-template'));
114     surveyTemplate = tbody.removeChild(dojo.byId('survey-row-template'));
115     surveyQuestionTemplate = tbody.removeChild(dojo.byId('survey-question-row-template'));
116
117     loadStaticFields();
118     if(patron.isnew() && patron.addresses().length == 0) 
119         uEditNewAddr(null, uEditAddrVirtId, true);
120     else loadAllAddrs();
121     loadStatCats();
122     loadSurveys();
123     checkClaimsReturnCountPerm();
124     checkClaimsNoCheckoutCountPerm();
125 }
126
127
128 /**
129  * Loads a staged user and turns them into something the editor can understand
130  */
131 function uEditLoadStageUser(stageUname) {
132
133     var data = fieldmapper.standardRequest(
134         ['open-ils.actor', 'open-ils.actor.user.stage.retrieve.by_username'],
135         { params : [openils.User.authtoken, stageUname] }
136     );
137
138     stageUser = data.user;
139     patron = uEditNewPatron();
140
141     if(!stageUser) 
142         return patron;
143
144     // copy the data into our new user object
145     for(var key in fieldmapper.IDL.fmclasses.stgu.field_map) {
146         if(fieldmapper.IDL.fmclasses.au.field_map[key] && !fieldmapper.IDL.fmclasses.stgu.field_map[key].virtual) {
147             if(data.user[key]() !== null)
148                 patron[key]( data.user[key]() );
149         }
150     }
151
152     // copy the data into our new address objects
153     // TODO: uses the first mailing address only
154     if(data.mailing_addresses.length) {
155
156         var mail_addr = new fieldmapper.aua();
157         mail_addr.id(-1); // virtual ID
158         mail_addr.usr(-1);
159         mail_addr.isnew(1);
160         patron.mailing_address(mail_addr);
161         patron.addresses().push(mail_addr);
162
163         for(var key in fieldmapper.IDL.fmclasses.stgma.field_map) {
164             if(fieldmapper.IDL.fmclasses.aua.field_map[key] && !fieldmapper.IDL.fmclasses.stgma.field_map[key].virtual) {
165                 if(data.mailing_addresses[0][key]() !== null)
166                     mail_addr[key]( data.mailing_addresses[0][key]() );
167             }
168         }
169     }
170     
171     // copy the data into our new address objects
172     // TODO uses the first billing address only
173     if(data.billing_addresses.length) {
174
175         var bill_addr = new fieldmapper.aua();
176         bill_addr.id(-2); // virtual ID
177         bill_addr.usr(-1);
178         bill_addr.isnew(1);
179         patron.billing_address(bill_addr);
180         patron.addresses().push(bill_addr);
181
182         for(var key in fieldmapper.IDL.fmclasses.stgba.field_map) {
183             if(fieldmapper.IDL.fmclasses.aua.field_map[key] && !fieldmapper.IDL.fmclasses.stgba.field_map[key].virtual) {
184                 if(data.billing_addresses[0][key]() !== null)
185                     bill_addr[key]( data.billing_addresses[0][key]() );
186             }
187         }
188     }
189
190     // TODO: uses the first card only
191     if(data.cards.length) {
192         var card = new fieldmapper.ac();
193         card.id(-1); // virtual ID
194         patron.card().barcode(data.cards[0].barcode());
195     }
196
197     return patron;
198 }
199
200 /*
201  * clone the home org, phone numbers, and billing/mailing address
202  */
203 function uEditCopyCloneData(patron) {
204     cloneUserObj = uEditLoadUser(cloneUser);
205
206     dojo.forEach( [
207         'home_ou', 
208         'day_phone', 
209         'evening_phone', 
210         'other_phone',
211         'billing_address',
212         'usrgroup',
213         'mailing_address' ], 
214         function(field) {
215             patron[field](cloneUserObj[field]());
216         }
217     );
218
219     // don't grab all addresses().  the only ones we can link to are billing/mailing
220     if(patron.billing_address())
221         patron.addresses().push(patron.billing_address());
222
223     if(patron.mailing_address() && (
224             patron.addresses().length == 0 || 
225             patron.mailing_address().id() != patron.billing_address().id()) )
226         patron.addresses().push(patron.mailing_address());
227 }
228
229
230 function uEditFetchUserSettings(userId) {
231     
232     var baseNode = fieldmapper.aou.findOrgUnit(staff.ws_ou());
233     var orgs = fieldmapper.aou.orgNodeTrail(baseNode);
234     orgs = orgs.map(function(node) { return node.id(); });
235
236     /* fetch any user setting types we need + any that offer opt-in */
237     userSettingTypes = pcrud.search('cust', {
238         '-or' : [
239             {name:['circ.holds_behind_desk']}, 
240             {name : {
241                 'in': {
242                     select : {atevdef : ['opt_in_setting']}, 
243                     from : 'atevdef',
244                     // we only care about opt-in settings for event_defs our users encounter
245                     where : {'+atevdef' : {owner : orgs}}
246                 }
247             }}
248         ]
249     });
250
251     var names = userSettingTypes.map(function(obj) { return obj.name() });
252
253     /* fetch any values set for this user */
254     userSettings = fieldmapper.standardRequest(
255         ['open-ils.actor', 'open-ils.actor.patron.settings.retrieve'],
256         {params : [openils.User.authtoken, userId, names]});
257 }
258
259
260 function uEditLoadUser(userId) {
261     var patron = fieldmapper.standardRequest(
262         ['open-ils.actor', 'open-ils.actor.user.fleshed.retrieve'],
263         {params : [openils.User.authtoken, userId]}
264     );
265     openils.Event.parse_and_raise(patron);
266     return patron;
267 }
268
269 function loadStaticFields() {
270     for(var idx = 0; tbody.childNodes[idx]; idx++) {
271         var row = tbody.childNodes[idx];
272         if(row.nodeType != row.ELEMENT_NODE) continue;
273         var fmcls = row.getAttribute('fmclass');
274         if(fmcls) {
275             fleshFMRow(row, fmcls);
276         } else {
277
278             if(row.id == 'uedit-settings-divider') {
279
280                 var template = tbody.removeChild(dojo.byId('uedit-user-setting-template'));
281                 dojo.forEach(userSettingTypes, function(type) { uEditDrawSettingRow(tbody, row, template, type); } );
282
283                 if(userSettingTypes.length > 1 || orgSettings['circ.holds.behind_desk_pickup_supported']) {
284                     openils.Util.show('uedit-settings-divider', 'table-row');
285                 }
286             }
287         }
288     }
289 }
290
291 function uEditDrawSettingRow(tbody, dividerRow, template, stype) {
292     var row = template.cloneNode(true);
293     row.setAttribute('user_setting', stype.name());
294     getByName(row, 'label').innerHTML = stype.label();
295     var cb = new dijit.form.CheckBox({}, getByName(row, 'widget'));
296     cb.attr('value', userSettings[stype.name()]);
297     dojo.connect(cb, 'onChange', function(newVal) { userSettingsToUpdate[stype.name()] = newVal; });
298     tbody.insertBefore(row, dividerRow.nextSibling);
299     openils.Util.show(row, 'table-row');
300 }
301
302 function uEditUpdateUserSettings(userId) {
303     return fieldmapper.standardRequest(
304         ['open-ils.actor', 'open-ils.actor.patron.settings.update'],
305         {params : [openils.User.authtoken, userId, userSettingsToUpdate]});
306 }
307
308 function loadAllAddrs() {
309     dojo.forEach(patron.addresses(),
310         function(addr) {
311             uEditNewAddr(null, addr.id());
312         }
313     );
314 }
315
316 function loadStatCats() {
317
318     statCats = fieldmapper.standardRequest(
319         ['open-ils.circ', 'open-ils.circ.stat_cat.actor.retrieve.all'],
320         {params : [openils.User.authtoken, staff.ws_ou()]}
321     );
322
323     // draw stat cats
324     for(var idx in statCats) {
325         var stat = statCats[idx];
326         var row = statCatTemplate.cloneNode(true);
327         row.id = 'stat-cat-row-' + idx;
328         tbody.appendChild(row);
329         getByName(row, 'name').innerHTML = stat.name();
330         var valtd = getByName(row, 'widget');
331         var span = valtd.appendChild(document.createElement('span'));
332         var store = new dojo.data.ItemFileReadStore(
333                 {data:fieldmapper.actsc.toStoreData(stat.entries())});
334         var comboBox = new dijit.form.ComboBox({store:store}, span);
335         comboBox.labelAttr = 'value';
336         comboBox.searchAttr = 'value';
337
338         comboBox._wtype = 'statcat';
339         comboBox._statcat = stat.id();
340         widgetPile.push(comboBox); 
341
342         // populate existing cats
343         var map = patron.stat_cat_entries().filter(
344             function(mp) { return (mp.stat_cat() == stat.id()) })[0];
345         if(map) comboBox.attr('value', map.stat_cat_entry()); 
346
347     }
348 }
349
350 function loadSurveys() {
351
352     surveys = fieldmapper.standardRequest(
353         ['open-ils.circ', 'open-ils.circ.survey.retrieve.all'],
354         {params : [openils.User.authtoken]}
355     );
356
357     // draw surveys
358     for(var idx in surveys) {
359         var survey = surveys[idx];
360         var srow = surveyTemplate.cloneNode(true);
361         tbody.appendChild(srow);
362         getByName(srow, 'name').innerHTML = survey.name();
363
364         for(var q in survey.questions()) {
365             var quest = survey.questions()[q];
366             var qrow = surveyQuestionTemplate.cloneNode(true);
367             tbody.appendChild(qrow);
368             getByName(qrow, 'question').innerHTML = quest.question();
369
370             var span = getByName(qrow, 'answers').appendChild(document.createElement('span'));
371             var store = new dojo.data.ItemFileReadStore(
372                 {data:fieldmapper.asva.toStoreData(quest.answers())});
373             var select = new dijit.form.FilteringSelect({store:store}, span);
374             select.labelAttr = 'answer';
375             select.searchAttr = 'answer';
376
377             select._wtype = 'survey';
378             select._survey = survey.id();
379             select._question = quest.id();
380             widgetPile.push(select); 
381         }
382     }
383 }
384
385
386 function fleshFMRow(row, fmcls, args) {
387     var fmfield = row.getAttribute('fmfield');
388     var wclass = row.getAttribute('wclass');
389     var wstyle = row.getAttribute('wstyle');
390     var wconstraints = row.getAttribute('wconstraints');
391
392     var isPasswd2 = (fmfield == 'passwd2');
393     if(isPasswd2) fmfield = 'passwd';
394     var fieldIdl = fieldmapper.IDL.fmclasses[fmcls].field_map[fmfield];
395     if(!args) args = {};
396
397     var existing = dojo.query('td', row);
398     var htd = existing[0] || row.appendChild(document.createElement('td'));
399     var ltd = existing[1] || row.appendChild(document.createElement('td'));
400     var wtd = existing[2] || row.appendChild(document.createElement('td'));
401
402     openils.Util.addCSSClass(htd, 'uedit-help');
403     if(fieldDoc[fmcls] && fieldDoc[fmcls][fmfield]) {
404         var link = dojo.byId('uedit-help-template').cloneNode(true);
405         link.id = '';
406         link.onclick = function() { ueLoadContextHelp(fmcls, fmfield) };
407         openils.Util.removeCSSClass(link, 'hidden');
408         htd.appendChild(link);
409     }
410
411     if(!ltd.textContent) {
412         var span = document.createElement('span');
413         ltd.appendChild(document.createTextNode(fieldIdl.label));
414     }
415
416     span = document.createElement('span');
417     wtd.appendChild(span);
418
419     var fmObject = null;
420     var disabled = false;
421     switch(fmcls) {
422         case 'au' : fmObject = patron; break;
423         case 'ac' : fmObject = patron.card(); break;
424         case 'aua' : 
425             fmObject = patron.addresses().filter(
426                 function(i) { return (i.id() == args.addr) })[0];
427             if(fmObject && fmObject.usr() != patron.id())
428                 disabled = true;
429             break;
430     }
431
432     var required = row.getAttribute('required') == 'required';
433
434     // password data is not fetched/required/displayed for existing users
435     if(!patron.isnew() && 'passwd' == fmfield)
436         required = false;
437
438     var dijitArgs = {
439         style: wstyle, 
440         required : required,
441         constraints : (wconstraints) ? eval('('+wconstraints+')') : {}, // the ()'s prevent Invalid Label errors with eval
442         disabled : disabled
443     };
444
445     // TODO RSN: Add Setting!
446     if(fmcls == 'au' && fmfield == 'dob')
447         dijitArgs.popupClass = "";
448
449     var value = row.getAttribute('wvalue');
450     if(value !== null)
451         dijitArgs.value = value;
452
453     // fetch profile groups non-async so existing expire_date is
454     // not overwritten when the profile groups arrive and update
455     var sync = (fmfield == 'profile') ? true : false;
456
457     var widget = new openils.widget.AutoFieldWidget({
458         forceSync : sync,
459         idlField : fieldIdl,
460         fmObject : fmObject,
461         fmClass : fmcls,
462         parentNode : span,
463         widgetClass : wclass,
464         dijitArgs : dijitArgs,
465         orgDefaultsToWs : true,
466         orgLimitPerms : ['UPDATE_USER'],
467     });
468
469     widget.build();
470
471     // now put it back before we register the widget
472     if(isPasswd2) fmfield = 'passwd2';
473
474     widget._wtype = fmcls;
475     widget._fmfield = fmfield;
476     widget._addr = args.addr;
477     widgetPile.push(widget);
478     attachWidgetEvents(fmcls, fmfield, widget);
479     return widget;
480 }
481
482 function findWidget(wtype, fmfield, callback) {
483     return widgetPile.filter(
484         function(i){
485             if(i._wtype == wtype && i._fmfield == fmfield) {
486                 if(callback) return callback(i);
487                 return true;
488             }
489         }
490     ).pop();
491 }
492
493 /**
494  * if the user does not have the UPDATE_PATRON_CLAIM_RETURN_COUNT, 
495  * they are not allowed to directly alter the claim return count. 
496  * This function checks the perm and disable/enables the widget.
497  */
498 function checkClaimsReturnCountPerm() {
499     new openils.User().getPermOrgList(
500         'UPDATE_PATRON_CLAIM_RETURN_COUNT',
501         function(orgList) { 
502             var cr = findWidget('au', 'claims_returned_count');
503             if(orgList.indexOf(patron.home_ou()) == -1) 
504                 cr.widget.attr('disabled', true);
505             else
506                 cr.widget.attr('disabled', false);
507         },
508         true, 
509         true
510     );
511 }
512
513
514 function checkClaimsNoCheckoutCountPerm() {
515     new openils.User().getPermOrgList(
516         'UPDATE_PATRON_CLAIM_NEVER_CHECKED_OUT_COUNT',
517         function(orgList) { 
518             var cr = findWidget('au', 'claims_never_checked_out_count');
519             if(orgList.indexOf(patron.home_ou()) == -1) 
520                 cr.widget.attr('disabled', true);
521             else
522                 cr.widget.attr('disabled', false);
523         },
524         true, 
525         true
526     );
527 }
528
529
530 function attachWidgetEvents(fmcls, fmfield, widget) {
531
532     if(fmcls == 'ac') {
533         if(fmfield == 'barcode') {
534             dojo.connect(widget.widget, 'onChange',
535                 function() {
536                     var un = findWidget('au', 'usrname');
537                     if(!un.widget.attr('value'))
538                         un.widget.attr('value', this.attr('value'));
539                 }
540             );
541             return;
542         }
543     }
544
545     if(fmcls == 'au') {
546         switch(fmfield) {
547
548             case 'profile': // when the profile changes, update the expire date
549                 dojo.connect(widget.widget, 'onChange', 
550                     function() {
551                         var self = this;
552                         var expireWidget = findWidget('au', 'expire_date');
553                         function found(items) {
554                             if(items.length == 0) return;
555                             var item = items[0];
556                             var interval = self.store.getValue(item, 'perm_interval');
557                             expireWidget.widget.attr('value', dojo.date.add(new Date(), 
558                                 'second', openils.Util.intervalToSeconds(interval)));
559                         }
560                         this.store.fetch({onComplete:found, query:{id:this.attr('value')}});
561                     }
562                 );
563                 return;
564
565             case 'dob':
566                 dojo.connect(widget.widget, 'onChange',
567                     function(newDob) {
568                         if(!newDob) return;
569                         var oldDob = patron.dob();
570                         if(dojo.date.stamp.fromISOString(oldDob) == newDob) return;
571
572                         var juvInterval = orgSettings['global.juvenile_age_threshold'] || '18 years';
573                         var juvWidget = findWidget('au', 'juvenile');
574                         var base = new Date();
575                         base.setTime(base.getTime() - Number(openils.Util.intervalToSeconds(juvInterval) + '000'));
576
577                         if(newDob <= base) // older than global.juvenile_age_threshold
578                             juvWidget.widget.attr('value', false);
579                         else
580                             juvWidget.widget.attr('value', true);
581                     }
582                 );
583                 return;
584
585             case 'first_given_name':
586             case 'family_name':
587                 dojo.connect(widget.widget, 'onChange',
588                     function(newVal) { uEditDupeSearch('name', newVal); });
589                 return;
590
591             case 'email':
592                 dojo.connect(widget.widget, 'onChange',
593                     function(newVal) { uEditDupeSearch('email', newVal); });
594                 return;
595
596             case 'ident_value':
597             case 'ident_value2':
598                 dojo.connect(widget.widget, 'onChange',
599                     function(newVal) { uEditDupeSearch('ident', newVal); });
600                 return;
601
602             case 'day_phone':
603                 // if configured, use the last for digits of the day phone number as the password
604                 if(uEditUsePhonePw && patron.isnew()) {
605                     dojo.connect(widget.widget, 'onChange',
606                         function(newVal) {
607                             if(newVal && newVal.length >= 4) {
608                                 var pw1 = findWidget('au', 'passwd').widget;
609                                 var pw2 = findWidget('au', 'passwd2').widget;
610                                 pw1.attr('value', newVal.substring(newVal.length - 4));
611                                 pw2.attr('value', newVal.substring(newVal.length - 4));
612                             }
613                         }
614                     );
615                 }
616             case 'evening_phone':
617             case 'other_phone':
618                 dojo.connect(widget.widget, 'onChange',
619                     function(newVal) { uEditDupeSearch('phone', newVal); });
620                 return;
621
622             case 'home_ou':
623                 dojo.connect(widget.widget, 'onChange',
624                     function(newVal) { 
625                         checkClaimsReturnCountPerm(); 
626                         checkClaimsNoCheckoutCountPerm();
627                     }
628                 );
629                 return;
630
631         }
632     }
633
634     if(fmclass = 'aua') {
635         switch(fmfield) {
636             case 'post_code':
637                 dojo.connect(widget.widget, 'onChange',
638                     function(e) { 
639                         fieldmapper.standardRequest(
640                             ['open-ils.search', 'open-ils.search.zip'],
641                             {   async: true,
642                                 params: [e],
643                                 oncomplete : function(r) {
644                                     var res = openils.Util.readResponse(r);
645                                     if(!res) return;
646                                     var callback = function(w) { return w._addr == widget._addr; };
647                                     if(res.city) findWidget('aua', 'city', callback).widget.attr('value', res.city);
648                                     if(res.state) findWidget('aua', 'state', callback).widget.attr('value', res.state);
649                                     if(res.county) findWidget('aua', 'county', callback).widget.attr('value', res.county);
650                                     if(res.alert) alert(res.alert);
651                                 }
652                             }
653                         );
654                     }
655                 );
656                 return;
657
658             case 'street1':
659             case 'street2':
660             case 'city':
661                 dojo.connect(widget.widget, 'onChange',
662                     function(e) {
663                         var callback = function(w) { return w._addr == widget._addr; };
664                         var args = {
665                             street1 : findWidget('aua', 'street1', callback).widget.attr('value'),
666                             street2 : findWidget('aua', 'street2', callback).widget.attr('value'),
667                             city : findWidget('aua', 'city', callback).widget.attr('value'),
668                             post_code : findWidget('aua', 'post_code', callback).widget.attr('value')
669                         };
670                         if(args.street1 && args.city && args.post_code)
671                             uEditDupeSearch('address', args); 
672                     }
673                 );
674                 return;
675         }
676     }
677 }
678
679 function uEditDupeSearch(type, value) {
680     if(!value) return;
681     var search;
682     switch(type) {
683
684         case 'name':
685             openils.Util.hide('uedit-dupe-names-link');
686             var fname = findWidget('au', 'first_given_name').widget.attr('value');
687             var lname = findWidget('au', 'family_name').widget.attr('value');
688             if( !(fname && lname) ) return;
689             search = {
690                 first_given_name : {value : fname, group : 0},
691                 family_name : {value : lname, group : 0},
692             };
693             break;
694
695         case 'email':
696             openils.Util.hide('uedit-dupe-email-link');
697             search = {email : {value : value, group : 0}};
698             break;
699
700         case 'ident':
701             openils.Util.hide('uedit-dupe-ident-link');
702             search = {ident : {value : value, group : 2}};
703             break;
704
705         case 'phone':
706             openils.Util.hide('uedit-dupe-phone-link');
707             search = {phone : {value : value, group : 2}};
708             break;
709
710         case 'address':
711             openils.Util.hide('uedit-dupe-address-link');
712             search = {};
713             dojo.forEach(['street1', 'street2', 'city', 'post_code'],
714                 function(field) {
715                     if(value[field])
716                         search[field] = {value : value[field], group: 1};
717                 }
718             );
719             break;
720     }
721
722     // find possible duplicate patrons
723     fieldmapper.standardRequest(
724         ['open-ils.actor', 'open-ils.actor.patron.search.advanced'],
725         {   async: true,
726             params: [openils.User.authtoken, search],
727             oncomplete : function(r) {
728                 var resp = openils.Util.readResponse(r);
729                 resp = resp.filter(function(id) { return (id != patron.id()); });
730
731                 if(resp && resp.length > 0) {
732
733                     openils.Util.hide('uedit-help-div');
734                     openils.Util.show('uedit-dupe-div');
735                     var link;
736
737                     switch(type) {
738                         case 'name':
739                             link = dojo.byId('uedit-dupe-names-link');
740                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_NAME, [resp.length]);
741                             break;
742                         case 'email':
743                             link = dojo.byId('uedit-dupe-email-link');
744                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_EMAIL, [resp.length]);
745                             break;
746                         case 'ident':
747                             link = dojo.byId('uedit-dupe-ident-link');
748                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_IDENT, [resp.length]);
749                             break;
750                         case 'phone':
751                             link = dojo.byId('uedit-dupe-phone-link');
752                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_PHONE, [resp.length]);
753                             break;
754                         case 'address':
755                             link = dojo.byId('uedit-dupe-address-link');
756                             link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_ADDR, [resp.length]);
757                             break;
758                     }
759
760                     openils.Util.show(link);
761                     link.onclick = function() {
762                         search.search_sort = js2JSON(["penalties", "family_name", "first_given_name"]);
763                         if(window.xulG)
764                             window.xulG.spawn_search(search);
765                         else
766                             console.log("running XUL patron search " + js2JSON(search));
767                     }
768                 }
769             }
770         }
771     );
772 }
773
774 function getByName(node, name) {
775     return dojo.query('[name='+name+']', node)[0];
776 }
777
778
779 function ueLoadContextHelp(fmcls, fmfield) {
780     openils.Util.hide('uedit-dupe-div');
781     openils.Util.show('uedit-help-div');
782     dojo.byId('uedit-help-field').innerHTML = fieldmapper.IDL.fmclasses[fmcls].field_map[fmfield].label;
783     dojo.byId('uedit-help-text').innerHTML = fieldDoc[fmcls][fmfield].string();
784 }
785
786
787 /* creates a new patron object with card attached */
788 function uEditNewPatron() {
789     patron = new au();
790     patron.isnew(1);
791     patron.id(-1);
792     card = new ac();
793     card.id(uEditCardVirtId);
794     card.isnew(1);
795     patron.active(1);
796     patron.card(card);
797     patron.cards([card]);
798     patron.net_access_level(orgSettings['ui.patron.default_inet_access_level'] || 1);
799     patron.stat_cat_entries([]);
800     patron.survey_responses([]);
801     patron.addresses([]);
802     uEditMakeRandomPw(patron);
803     return patron;
804 }
805
806 function uEditMakeRandomPw(patron) {
807     if(uEditUsePhonePw) return;
808     var rand  = Math.random();
809     rand = parseInt(rand * 10000) + '';
810     while(rand.length < 4) rand += '0';
811 /*
812     appendClear($('ue_password_plain'),text(rand));
813     unHideMe($('ue_password_gen'));
814 */
815     patron.passwd(rand);
816     return rand;
817 }
818
819 function uEditWidgetVal(w) {
820     var val = (w.getFormattedValue) ? w.getFormattedValue() : w.attr('value');
821     if(val === '') val = null;
822     return val;
823 }
824
825 function uEditSave() { _uEditSave(); }
826 function uEditSaveClone() { _uEditSave(true); }
827
828 function _uEditSave(doClone) {
829
830     for(var idx in widgetPile) {
831         var w = widgetPile[idx];
832         var val = uEditWidgetVal(w);
833
834         switch(w._wtype) {
835             case 'au':
836                 if(w._fmfield != 'passwd2')
837                     patron[w._fmfield](val);
838                 break;
839
840             case 'ac':
841                 patron.card()[w._fmfield](val);
842                 break;
843
844             case 'aua':
845                 var addr = patron.addresses().filter(function(i){return (i.id() == w._addr)})[0];
846                 if(!addr) {
847                     addr = new fieldmapper.aua();
848                     addr.id(w._addr);
849                     addr.isnew(1);
850                     addr.usr(patron.id());
851                     patron.addresses().push(addr);
852                 } else {
853                     if(addr[w._fmfield]() != val)
854                         addr.ischanged(1);
855                 }
856                 addr[w._fmfield](val);
857
858                 if(dojo.byId('uedit-billing-address-' + addr.id()).checked) 
859                     patron.billing_address(addr.id());
860
861                 if(dojo.byId('uedit-mailing-address-' + addr.id()).checked)
862                     patron.mailing_address(addr.id());
863
864                 break;
865
866             case 'survey':
867                 if(val == null) break;
868                 var resp = new fieldmapper.asvr();
869                 resp.isnew(1);
870                 resp.survey(w._survey)
871                 resp.usr(patron.id());
872                 resp.question(w._question)
873                 resp.answer(val);
874                 patron.survey_responses().push(resp);
875                 break;
876
877             case 'statcat':
878                 if(val == null) break;
879
880                 var map = patron.stat_cat_entries().filter(
881                     function(m){
882                         return (m.stat_cat() == w._statcat) })[0];
883
884                 if(map) {
885                     if(map.stat_cat_entry() == val) 
886                         break;
887                     map.ischanged(1);
888                 } else {
889                     map = new fieldmapper.actscecm();
890                     map.isnew(1);
891                 }
892
893                 map.stat_cat(w._statcat);
894                 map.stat_cat_entry(val);
895                 map.target_usr(patron.id());
896                 patron.stat_cat_entries().push(map);
897                 break;
898         }
899     }
900
901     patron.ischanged(1);
902     fieldmapper.standardRequest(
903         ['open-ils.actor', 'open-ils.actor.patron.update'],
904         {   async: true,
905             params: [openils.User.authtoken, patron],
906             oncomplete: function(r) {
907                 newPatron = openils.Util.readResponse(r);
908                 if(newPatron) {
909                     uEditUpdateUserSettings(newPatron.id());
910                     if(stageUser) uEditRemoveStage();
911                     uEditFinishSave(newPatron, doClone);
912                 }
913             }
914         }
915     );
916 }
917
918 function uEditRemoveStage() {
919     var resp = fieldmapper.standardRequest(
920         ['open-ils.actor', 'open-ils.actor.user.stage.delete'],
921         { params : [openils.User.authtoken, stageUser.row_id()] }
922     )
923 }
924
925 function uEditFinishSave(newPatron, doClone) {
926
927     if(doClone && cloneUser == null)
928         cloneUser = newPatron.id();
929
930         if( doClone ) {
931
932                 if(xulG && typeof xulG.spawn_editor == 'function' && !patron.isnew() ) {
933             window.xulG.spawn_editor({ses:openils.User.authtoken,clone:cloneUser});
934             uEditRefresh();
935
936                 } else {
937                         location.href = location.href.replace(/\?.*/, '') + '?clone=' + cloneUser;
938                 }
939
940         } else {
941
942                 uEditRefresh();
943         }
944
945         uEditRefreshXUL(newPatron);
946 }
947
948 function uEditRefresh() {
949     var usr = cgi.param('usr');
950     var href = location.href.replace(/\?.*/, '');
951     href += ((usr) ? '?usr=' + usr : '');
952     location.href = href;
953 }
954
955 function uEditRefreshXUL(newuser) {
956         if (window.xulG && typeof window.xulG.on_save == 'function') 
957                 window.xulG.on_save(newuser);
958 }
959
960
961 /**
962  * Create a new address and insert it into the DOM
963  * @param evt ignored
964  * @param id The address id
965  * @param mkLinks If true, set the new address as the 
966  *  mailing/billing address for the user
967  */
968 function uEditNewAddr(evt, id, mkLinks) {
969
970     if(id == null) 
971         id = --uEditAddrVirtId; // new address
972
973     var addr =  patron.addresses().filter(
974         function(i) { return (i.id() == id) })[0];
975
976     dojo.forEach(addrTemplateRows, 
977         function(row) {
978
979             row = tbody.insertBefore(row.cloneNode(true), dojo.byId('new-addr-row'));
980             row.setAttribute('type', '');
981             row.setAttribute('addr', id+'');
982
983             if(row.getAttribute('fmclass')) {
984                 var widget = fleshFMRow(row, 'aua', {addr:id});
985
986                 // make new addresses valid by default
987                 if(id < 0 && row.getAttribute('fmfield') == 'valid') 
988                     widget.widget.attr('value', true); 
989
990             } else if(row.getAttribute('name') == 'uedit-addr-pending-row') {
991
992                 // if it's a pending address, show the 'approve' button
993                 if(addr && openils.Util.isTrue(addr.pending())) {
994                     openils.Util.show(row, 'table-row');
995                     dojo.query('[name=approve-button]', row)[0].onclick = 
996                         function() { uEditApproveAddress(addr); };
997
998                     if(addr.replaces()) {
999                         var div = dojo.query('[name=replaced-addr]', row)[0]
1000                         var replaced =  patron.addresses().filter(
1001                             function(i) { return (i.id() == addr.replaces()) })[0];
1002
1003                         div.innerHTML = dojo.string.substitute(localeStrings.REPLACED_ADDRESS, [
1004                             replaced.address_type() || '',
1005                             replaced.street1() || '',
1006                             replaced.street2() || '',
1007                             replaced.city() || '',
1008                             replaced.state() || '',
1009                             replaced.post_code() || ''
1010                         ]);
1011
1012                     } else {
1013                         openils.Util.hide(dojo.query('[name=replaced-addr-div]', row)[0]);
1014                     }
1015                 }
1016
1017             } else if(row.getAttribute('name') == 'uedit-addr-owner-row') {
1018                 // address is owned by someone else.  provide option to load the
1019                 // user in a different tab
1020                 
1021                 if(addr && addr.usr() != patron.id()) {
1022                     openils.Util.show(row, 'table-row');
1023                     var link = getByName(row, 'addr-owner');
1024
1025                     // fetch the linked user so we can present their name in the UI
1026                     var addrUser;
1027                     if(cloneUserObj && cloneUserObj.id() == addr.usr()) {
1028                         addrUser = [
1029                             cloneUserObj.first_given_name(), 
1030                             cloneUserObj.second_given_name(), 
1031                             cloneUserObj.family_name()
1032                         ];
1033                     } else {
1034                         addrUser = fieldmapper.standardRequest(
1035                             ['open-ils.actor', 'open-ils.actor.user.retrieve.parts'],
1036                             {params: [
1037                                 openils.User.authtoken, 
1038                                 addr.usr(), 
1039                                 ['first_given_name', 'second_given_name', 'family_name']
1040                             ]}
1041                         );
1042                     }
1043
1044                     link.innerHTML = (addrUser.map(function(name) { return (name) ? name+' ' : '' })+'').replace(/,/g,''); // TODO i18n
1045                     link.onclick = function() {
1046                         if(openils.XUL.isXUL()) { 
1047                             window.xulG.spawn_editor({ses:openils.User.authtoken, usr:addr.usr()})
1048                         } else {
1049                             parent.location.href = location.href.replace(/clone=\d+/, 'usr=' + addr.usr());
1050                         }
1051                     }
1052                 }
1053
1054             } else if(row.getAttribute('name') == 'uedit-addr-divider') {
1055                 // link up the billing/mailing address and give the inputs IDs so we can acces the later
1056                 
1057                 // billing address
1058                 var ba = getByName(row, 'billing_address');
1059                 ba.id = 'uedit-billing-address-' + id;
1060                 if(mkLinks || (patron.billing_address() && patron.billing_address().id() == id))
1061                     ba.checked = true;
1062
1063                 // mailing address
1064                 var ma = getByName(row, 'mailing_address');
1065                 ma.id = 'uedit-mailing-address-' + id;
1066                 if(mkLinks || (patron.mailing_address() && patron.mailing_address().id() == id))
1067                     ma.checked = true;
1068
1069             } else {
1070                 var btn = dojo.query('[name=delete-button]', row)[0];
1071                 if(btn) btn.onclick = function(){ uEditDeleteAddr(id) };
1072             }
1073         }
1074     );
1075 }
1076
1077 function uEditApproveAddress(addr) {
1078     fieldmapper.standardRequest(
1079         ['open-ils.actor', 'open-ils.actor.user.pending_address.approve'],
1080         {   async: true,
1081             params:  [openils.User.authtoken, addr],
1082
1083             oncomplete : function(r) {
1084                 var oldId = openils.Util.readResponse(r);
1085                     
1086                 // remove addrs from UI
1087                 dojo.forEach(
1088                     patron.addresses(), 
1089                     function(addr) { uEditDeleteAddr(addr.id(), true); }
1090                 );
1091
1092                 if(oldId != null) {
1093                     
1094                     // remove the replaced address 
1095                     if(oldId != addr.id()) {
1096                                 patron.addresses(
1097                             patron.addresses().filter(
1098                                                 function(i) { return (i.id() != oldId); }
1099                                         )
1100                                 );
1101                     }
1102                     
1103                     // fix the the new address
1104                     addr.id(oldId);
1105                     addr.replaces(null);
1106                     addr.pending('f');
1107
1108                 }
1109
1110                 // redraw addrs
1111                 loadAllAddrs();
1112             }
1113         }
1114     );
1115 }
1116
1117
1118 function uEditDeleteAddr(id, noAlert) {
1119     if(!noAlert) {
1120         if(!confirm('Delete address ' + id)) return; /* XXX i18n */
1121     }
1122     var rows = dojo.query('tr[addr='+id+']', tbody);
1123     for(var i = 0; i < rows.length; i++)
1124         rows[i].parentNode.removeChild(rows[i]);
1125     widgetPile = widgetPile.filter(function(w){return (w._addr != id)});
1126 }
1127
1128 function uEditToggleRequired() {
1129     if((tbody.className +'').match(/hide-non-required/)) 
1130         openils.Util.removeCSSClass(tbody, 'hide-non-required');
1131     else
1132         openils.Util.addCSSClass(tbody, 'hide-non-required');
1133     openils.Util.toggle('uedit-show-required');
1134     openils.Util.toggle('uedit-show-all');
1135 }
1136
1137
1138
1139 openils.Util.addOnLoad(load);