]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/actor/user/register.js
finished dupe patron search plugin
[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('fieldmapper.IDL');
6 dojo.require('openils.PermaCrud');
7 dojo.require('openils.widget.AutoGrid');
8 dojo.require('openils.widget.AutoFieldWidget');
9 dojo.require('dijit.form.CheckBox');
10 dojo.require('dijit.form.Button');
11 dojo.require('dojo.date');
12 dojo.require('openils.CGI');
13 dojo.require('openils.XUL');
14
15 var pcrud;
16 var fmClasses = ['au', 'ac', 'aua', 'actsc', 'asv', 'asvq', 'asva'];
17 var fieldDoc = {};
18 var statCats;
19 var statCatTempate;
20 var surveys;
21 var staff;
22 var patron;
23 var uEditUsePhonePw = false;
24 var widgetPile = [];
25 var uEditCardVirtId = -1;
26 var uEditAddrVirtId = -1;
27 var orgSettings = {};
28 var tbody;
29 var addrTemplateRows;
30 var cgi;
31 var cloneUser;
32
33
34 if(!window.xulG) var xulG = null;
35
36
37 function load() {
38     staff = new openils.User().user;
39     pcrud = new openils.PermaCrud();
40     cgi = new openils.CGI();
41     cloneUser = cgi.param('clone');
42     var userId = cgi.param('usr');
43
44     if(xulG) {
45             if(xulG.ses) openils.User.authtoken = xulG.ses;
46             if(xulG.clone !== null) cloneUser = xulG.clone;
47         if(xulG.usr !== null) userId = xulG.usr
48         if(xulG.params) {
49             var parms = xulG.params;
50                 if(parms.ses) 
51                 openils.User.authtoken = parms.ses;
52                 if(parms.clone) 
53                 cloneUser = parms.clone;
54             if(parms.usr !== null)
55                 userId = parms.usr
56         }
57     }
58
59     orgSettings = fieldmapper.aou.fetchOrgSettingBatch(staff.ws_ou(), [
60         'global.juvenile_age_threshold',
61         'patron.password.use_phone',
62         'ui.patron.default_inet_access_level'
63     ]);
64     for(k in orgSettings)
65         if(orgSettings[k])
66             orgSettings[k] = orgSettings[k].value;
67
68     uEditLoadUser(userId);
69
70     var list = pcrud.search('fdoc', {fm_class:fmClasses});
71     for(var i in list) {
72         var doc = list[i];
73         if(!fieldDoc[doc.fm_class()])
74             fieldDoc[doc.fm_class()] = {};
75         fieldDoc[doc.fm_class()][doc.field()] = doc;
76     }
77
78     tbody = dojo.byId('uedit-tbody');
79
80     addrTemplateRows = dojo.query('tr[type=addr-template]', tbody);
81     dojo.forEach(addrTemplateRows, function(row) { row.parentNode.removeChild(row); } );
82     statCatTemplate = tbody.removeChild(dojo.byId('stat-cat-row-template'));
83     surveyTemplate = tbody.removeChild(dojo.byId('survey-row-template'));
84     surveyQuestionTemplate = tbody.removeChild(dojo.byId('survey-question-row-template'));
85
86     loadStaticFields();
87     if(patron.isnew()) 
88         uEditNewAddr(null, uEditAddrVirtId);
89     else loadAllAddrs();
90     loadStatCats();
91     loadSurveys();
92 }
93
94 function uEditLoadUser(userId) {
95     if(!userId) return uEditNewPatron();
96     patron = fieldmapper.standardRequest(
97         ['open-ils.actor', 'open-ils.actor.user.fleshed.retrieve'],
98         {params : [openils.User.authtoken, userId]}
99     );
100 }
101
102 function loadStaticFields() {
103     for(var idx = 0; tbody.childNodes[idx]; idx++) {
104         var row = tbody.childNodes[idx];
105         if(row.nodeType != row.ELEMENT_NODE) continue;
106         var fmcls = row.getAttribute('fmclass');
107         if(!fmcls) continue;
108         fleshFMRow(row, fmcls);
109     }
110 }
111
112 function loadAllAddrs() {
113     dojo.forEach(patron.addresses(),
114         function(addr) {
115             uEditNewAddr(null, addr.id());
116         }
117     );
118 }
119
120 function loadStatCats() {
121
122     statCats = fieldmapper.standardRequest(
123         ['open-ils.circ', 'open-ils.circ.stat_cat.actor.retrieve.all'],
124         {params : [openils.User.authtoken, staff.ws_ou()]}
125     );
126
127     // draw stat cats
128     for(var idx in statCats) {
129         var stat = statCats[idx];
130         var row = statCatTemplate.cloneNode(true);
131         row.id = 'stat-cat-row-' + idx;
132         tbody.appendChild(row);
133         getByName(row, 'name').innerHTML = stat.name();
134         var valtd = getByName(row, 'widget');
135         var span = valtd.appendChild(document.createElement('span'));
136         var store = new dojo.data.ItemFileReadStore(
137                 {data:fieldmapper.actsc.toStoreData(stat.entries())});
138         var comboBox = new dijit.form.ComboBox({store:store}, span);
139         comboBox.labelAttr = 'value';
140         comboBox.searchAttr = 'value';
141
142         comboBox._wtype = 'statcat';
143         comboBox._statcat = stat.id();
144         widgetPile.push(comboBox); 
145
146         // populate existing cats
147         var map = patron.stat_cat_entries().filter(
148             function(mp) { return (mp.stat_cat() == stat.id()) })[0];
149         if(map) comboBox.attr('value', map.stat_cat_entry()); 
150
151     }
152 }
153
154 function loadSurveys() {
155
156     surveys = fieldmapper.standardRequest(
157         ['open-ils.circ', 'open-ils.circ.survey.retrieve.all'],
158         {params : [openils.User.authtoken]}
159     );
160
161     // draw surveys
162     for(var idx in surveys) {
163         var survey = surveys[idx];
164         var srow = surveyTemplate.cloneNode(true);
165         tbody.appendChild(srow);
166         getByName(srow, 'name').innerHTML = survey.name();
167
168         for(var q in survey.questions()) {
169             var quest = survey.questions()[q];
170             var qrow = surveyQuestionTemplate.cloneNode(true);
171             tbody.appendChild(qrow);
172             getByName(qrow, 'question').innerHTML = quest.question();
173
174             var span = getByName(qrow, 'answers').appendChild(document.createElement('span'));
175             var store = new dojo.data.ItemFileReadStore(
176                 {data:fieldmapper.asva.toStoreData(quest.answers())});
177             var select = new dijit.form.FilteringSelect({store:store}, span);
178             select.labelAttr = 'answer';
179             select.searchAttr = 'answer';
180
181             select._wtype = 'survey';
182             select._survey = survey.id();
183             select._question = quest.id();
184             widgetPile.push(select); 
185         }
186     }
187 }
188
189
190 function fleshFMRow(row, fmcls, args) {
191     var fmfield = row.getAttribute('fmfield');
192     var wclass = row.getAttribute('wclass');
193     var wstyle = row.getAttribute('wstyle');
194     var fieldIdl = fieldmapper.IDL.fmclasses[fmcls].field_map[fmfield];
195     if(!args) args = {};
196
197     var existing = dojo.query('td', row);
198     var htd = existing[0] || row.appendChild(document.createElement('td'));
199     var ltd = existing[1] || row.appendChild(document.createElement('td'));
200     var wtd = existing[2] || row.appendChild(document.createElement('td'));
201
202     openils.Util.addCSSClass(htd, 'uedit-help');
203     if(fieldDoc[fmcls] && fieldDoc[fmcls][fmfield]) {
204         var link = dojo.byId('uedit-help-template').cloneNode(true);
205         link.id = '';
206         link.onclick = function() { ueLoadContextHelp(fmcls, fmfield) };
207         openils.Util.removeCSSClass(link, 'hidden');
208         htd.appendChild(link);
209     }
210
211     if(!ltd.textContent) {
212         var span = document.createElement('span');
213         ltd.appendChild(document.createTextNode(fieldIdl.label));
214     }
215
216     span = document.createElement('span');
217     wtd.appendChild(span);
218
219     var fmObject = null;
220     switch(fmcls) {
221         case 'au' : fmObject = patron; break;
222         case 'ac' : fmObject = patron.card(); break;
223         case 'aua' : 
224             fmObject = patron.addresses().filter(
225                 function(i) { return (i.id() == args.addr) })[0];
226             break;
227     }
228     
229     var required = row.getAttribute('required') == 'required';
230     var widget = new openils.widget.AutoFieldWidget({
231         idlField : fieldIdl,
232         fmObject : fmObject,
233         fmClass : fmcls,
234         parentNode : span,
235         widgetClass : wclass,
236         dijitArgs : {
237             style: wstyle, 
238             required : required
239         },
240         orgLimitPerms : ['UPDATE_USER'],
241     });
242
243     widget.build();
244
245     widget._wtype = fmcls;
246     widget._fmfield = fmfield;
247     widget._addr = args.addr;
248     widgetPile.push(widget);
249     attachWidgetEvents(fmcls, fmfield, widget);
250     return widget;
251 }
252
253 function findWidget(wtype, fmfield, callback) {
254     return widgetPile.filter(
255         function(i){
256             if(i._wtype == wtype && i._fmfield == fmfield) {
257                 if(callback) return callback(i);
258                 return true;
259             }
260         }
261     ).pop();
262 }
263
264 function attachWidgetEvents(fmcls, fmfield, widget) {
265
266     if(fmcls == 'ac') {
267         if(fmfield == 'barcode') {
268             dojo.connect(widget.widget, 'onChange',
269                 function() {
270                     var un = findWidget('au', 'usrname');
271                     if(!un.widget.attr('value'))
272                         un.widget.attr('value', this.attr('value'));
273                 }
274             );
275             return;
276         }
277     }
278
279     if(fmcls == 'au') {
280         switch(fmfield) {
281
282             case 'profile': // when the profile changes, update the expire date
283                 dojo.connect(widget.widget, 'onChange', 
284                     function() {
285                         var self = this;
286                         var expireWidget = findWidget('au', 'expire_date');
287                         function found(items) {
288                             if(items.length == 0) return;
289                             var item = items[0];
290                             var interval = self.store.getValue(item, 'perm_interval');
291                             expireWidget.widget.attr('value', dojo.date.add(new Date(), 
292                                 'second', openils.Util.intervalToSeconds(interval)));
293                         }
294                         this.store.fetch({onComplete:found, query:{id:this.attr('value')}});
295                     }
296                 );
297                 return;
298
299             case 'dob':
300                 dojo.connect(widget.widget, 'onChange',
301                     function(newDob) {
302                         if(!newDob) return;
303                         var oldDob = patron.dob();
304                         if(dojo.date.stamp.fromISOString(oldDob) == newDob) return;
305
306                         var juvInterval = orgSettings['global.juvenile_age_threshold'] || '18 years';
307                         var juvWidget = findWidget('au', 'juvenile');
308                         var base = new Date();
309                         base.setTime(base.getTime() - Number(openils.Util.intervalToSeconds(juvInterval) + '000'));
310
311                         if(newDob <= base) // older than global.juvenile_age_threshold
312                             juvWidget.widget.attr('value', false);
313                         else
314                             juvWidget.widget.attr('value', true);
315                     }
316                 );
317                 return;
318
319             case 'first_given_name':
320             case 'family_name':
321                 dojo.connect(widget.widget, 'onChange',
322                     function(newVal) { uEditDupeSearch('name', newVal); });
323                 return;
324
325             case 'email':
326                 dojo.connect(widget.widget, 'onChange',
327                     function(newVal) { uEditDupeSearch('email', newVal); });
328                 return;
329
330             case 'ident_value':
331             case 'ident_value2':
332                 dojo.connect(widget.widget, 'onChange',
333                     function(newVal) { uEditDupeSearch('ident', newVal); });
334                 return;
335
336         }
337     }
338
339     if(fmclass = 'aua') {
340         switch(fmfield) {
341             case 'post_code':
342                 dojo.connect(widget.widget, 'onChange',
343                     function(e) { 
344                         fieldmapper.standardRequest(
345                             ['open-ils.search', 'open-ils.search.zip'],
346                             {   async: true,
347                                 params: [e],
348                                 oncomplete : function(r) {
349                                     var res = openils.Util.readResponse(r);
350                                     var callback = function(w) { return w._addr == widget._addr; };
351                                     if(res.city) findWidget('aua', 'city', callback).widget.attr('value', res.city);
352                                     if(res.state) findWidget('aua', 'state', callback).widget.attr('value', res.state);
353                                     if(res.county) findWidget('aua', 'county', callback).widget.attr('value', res.county);
354                                     if(res.alert) alert(res.alert);
355                                 }
356                             }
357                         );
358                     }
359                 );
360                 return;
361         }
362     }
363 }
364
365 function uEditDupeSearch(type, value) {
366     var search;
367     switch(type) {
368
369         case 'name':
370             openils.Util.hide('uedit-dupe-names-link');
371             var fname = findWidget('au', 'first_given_name').widget.attr('value');
372             var lname = findWidget('au', 'family_name').widget.attr('value');
373             if( !(fname && lname) ) return;
374             search = {
375                 first_given_name : {value : fname, group : 0},
376                 family_name : {value : lname, group : 0},
377             };
378             break;
379
380         case 'email':
381             openils.Util.hide('uedit-dupe-email-link');
382             search = {email : {value : value, group : 0}};
383             break;
384
385         case 'ident':
386             openils.Util.hide('uedit-dupe-ident-link');
387             search = {ident : {value : value, group : 2}};
388             break;
389     }
390
391     fieldmapper.standardRequest(
392         ['open-ils.actor', 'open-ils.actor.patron.search.advanced'],
393         {   async: true,
394             params: [openils.User.authtoken, search],
395             oncomplete : function(r) {
396                 var resp = openils.Util.readResponse(r);
397
398                 if(resp && resp.length > 0) {
399                     openils.Util.hide('uedit-help-div');
400                     openils.Util.show('uedit-dupe-div');
401                     var link;
402                     switch(type) {
403                         case 'name':
404                             link = dojo.byId('uedit-dupe-names-link');
405                             link.innerHTML = 'Found ' + resp.length + ' patrons with the same name';
406                             break;
407                         case 'email':
408                             link = dojo.byId('uedit-dupe-email-link');
409                             link.innerHTML = 'Found ' + resp.length + ' patrons with the same email';
410                             break;
411                         case 'ident':
412                             link = dojo.byId('uedit-dupe-ident-link');
413                             link.innerHTML = 'Found ' + resp.length + ' patrosn with the same identification';
414                             break;
415                     }
416
417                     openils.Util.show(link);
418                     link.onclick = function() {
419                         if(window.xulG)
420                             window.xulG.spawn_search(search);
421                         else
422                             console.log("running XUL patron search " + js2JSON(search));
423                     }
424                 }
425             }
426         }
427     );
428 }
429
430 function getByName(node, name) {
431     return dojo.query('[name='+name+']', node)[0];
432 }
433
434
435 function ueLoadContextHelp(fmcls, fmfield) {
436     openils.Util.hide('uedit-dupe-div');
437     openils.Util.show('uedit-help-div');
438     dojo.byId('uedit-help-field').innerHTML = fieldmapper.IDL.fmclasses[fmcls].field_map[fmfield].label;
439     dojo.byId('uedit-help-text').innerHTML = fieldDoc[fmcls][fmfield].string();
440 }
441
442
443 /* creates a new patron object with card attached */
444 function uEditNewPatron() {
445     patron = new au();
446     patron.isnew(1);
447     patron.id(-1);
448     card = new ac();
449     card.id(uEditCardVirtId);
450     card.isnew(1);
451     patron.card(card);
452     patron.cards([card]);
453     patron.net_access_level(orgSettings['ui.patron.default_inet_access_level'] || 1);
454     patron.stat_cat_entries([]);
455     patron.survey_responses([]);
456     patron.addresses([]);
457     uEditMakeRandomPw(patron);
458 }
459
460 function uEditMakeRandomPw(patron) {
461     if(uEditUsePhonePw) return;
462     var rand  = Math.random();
463     rand = parseInt(rand * 10000) + '';
464     while(rand.length < 4) rand += '0';
465 /*
466     appendClear($('ue_password_plain'),text(rand));
467     unHideMe($('ue_password_gen'));
468 */
469     patron.passwd(rand);
470     return rand;
471 }
472
473 function uEditWidgetVal(w) {
474     var val = (w.getFormattedValue) ? w.getFormattedValue() : w.attr('value');
475     if(val === '') val = null;
476     return val;
477 }
478
479 function uEditSave() { _uEditSave(); }
480 function uEditSaveClone() { _uEditSave(true); }
481
482 function _uEditSave(doClone) {
483
484     for(var idx in widgetPile) {
485         var w = widgetPile[idx];
486         var val = uEditWidgetVal(w);
487
488         switch(w._wtype) {
489             case 'au':
490                 patron[w._fmfield](val);
491                 break;
492
493             case 'ac':
494                 patron.card()[w._fmfield](val);
495                 break;
496
497             case 'aua':
498                 var addr = patron.addresses().filter(function(i){return (i.id() == w._addr)})[0];
499                 if(!addr) {
500                     addr = new fieldmapper.aua();
501                     addr.id(w._addr);
502                     addr.isnew(1);
503                     addr.usr(patron.id());
504                     patron.addresses().push(addr);
505                 } else {
506                     if(addr[w._fmfield]() != val)
507                         addr.ischanged(1);
508                 }
509                 addr[w._fmfield](val);
510                 break;
511
512             case 'survey':
513                 if(val == null) break;
514                 var resp = new fieldmapper.asvr();
515                 resp.isnew(1);
516                 resp.survey(w._survey)
517                 resp.usr(patron.id());
518                 resp.question(w._question)
519                 resp.answer(val);
520                 patron.survey_responses().push(resp);
521                 break;
522
523             case 'statcat':
524                 if(val == null) break;
525
526                 var map = patron.stat_cat_entries().filter(
527                     function(m){
528                         return (m.stat_cat() == w._statcat) })[0];
529
530                 if(map) {
531                     if(map.stat_cat_entry() == val) 
532                         break;
533                     map.ischanged(1);
534                 } else {
535                     map = new fieldmapper.actscecm();
536                     map.isnew(1);
537                 }
538
539                 map.stat_cat(w._statcat);
540                 map.stat_cat_entry(val);
541                 map.target_usr(patron.id());
542                 patron.stat_cat_entries().push(map);
543                 break;
544         }
545     }
546
547     patron.ischanged(1);
548     fieldmapper.standardRequest(
549         ['open-ils.actor', 'open-ils.actor.patron.update'],
550         {   async: true,
551             params: [openils.User.authtoken, patron],
552             oncomplete: function(r) {
553                 newPatron = openils.Util.readResponse(r);
554                 if(newPatron) uEditFinishSave(newPatron, doClone);
555             }
556         }
557     );
558 }
559
560 function uEditFinishSave(newPatron, doClone) {
561
562     if(doClone &&cloneUser == null)
563         cloneUser = newPatron.id();
564
565         if( doClone ) {
566
567                 if(xulG && typeof xulG.spawn_editor == 'function' && !patron.isnew() ) {
568             window.xulG.spawn_editor({ses:openils.User.authtoken,clone:cloneUser});
569             uEditRefresh();
570
571                 } else {
572                         location.href = href.replace(/\?.*/, '') + '?clone=' + cloneUser;
573                 }
574
575         } else {
576
577                 uEditRefresh();
578         }
579
580         uEditRefreshXUL(newPatron);
581 }
582
583 function uEditRefresh() {
584     var usr = cgi.param('usr');
585     var href = location.href.replace(/\?.*/, '');
586     href += ((usr) ? '?usr=' + usr : '');
587     location.href = href;
588 }
589
590 function uEditRefreshXUL(newuser) {
591         if (window.xulG && typeof window.xulG.on_save == 'function') 
592                 window.xulG.on_save(newuser);
593 }
594
595
596 function uEditNewAddr(evt, id) {
597     if(id == null) id = --uEditAddrVirtId;
598     dojo.forEach(addrTemplateRows, 
599         function(row) {
600
601             row = tbody.insertBefore(row.cloneNode(true), dojo.byId('new-addr-row'));
602             row.setAttribute('type', '');
603             row.setAttribute('addr', id+'');
604
605             if(row.getAttribute('fmclass')) {
606                 fleshFMRow(row, 'aua', {addr:id});
607
608             } else if(row.getAttribute('name') == 'uedit-addr-pending-row') {
609
610                 var addr =  patron.addresses().filter(
611                     function(i) { return (i.id() == id) })[0];
612                 
613                 // if it's a pending address, show the 'approve' button
614                 if(addr && openils.Util.isTrue(addr.pending())) {
615                     openils.Util.show(row, 'table-row');
616                     dojo.query('[name=approve-button]', row)[0].onclick = 
617                         function() { uEditApproveAddress(addr); };
618
619                     if(addr.replaces()) {
620                         var div = dojo.query('[name=replaced-addr]', row)[0]
621                         div.innerHTML = addr.replaces();
622                     } else {
623                         openils.Util.hide(dojo.query('[name=replaced-addr-div]', row)[0]);
624                     }
625                 }
626
627             } else {
628                 var btn = dojo.query('[name=delete-button]', row)[0];
629                 if(btn) btn.onclick = function(){ uEditDeleteAddr(id) };
630             }
631         }
632     );
633 }
634
635 function uEditApproveAddress(addr) {
636     fieldmapper.standardRequest(
637         ['open-ils.actor', 'open-ils.actor.user.pending_address.approve'],
638         {   async: true,
639             params:  [openils.User.authtoken, addr],
640
641             oncomplete : function(r) {
642                 var oldId = openils.Util.readResponse(r);
643                     
644                 // remove addrs from UI
645                 dojo.forEach(
646                     patron.addresses(), 
647                     function(addr) { uEditDeleteAddr(addr.id(), true); }
648                 );
649
650                 if(oldId != null) {
651                     
652                     // remove the replaced address 
653                     if(oldId != addr.id()) {
654                                 patron.addresses(
655                             patron.addresses().filter(
656                                                 function(i) { return (i.id() != oldId); }
657                                         )
658                                 );
659                     }
660                     
661                     // fix the the new address
662                     addr.id(oldId);
663                     addr.replaces(null);
664                     addr.pending('f');
665
666                 }
667
668                 // redraw addrs
669                 loadAllAddrs();
670             }
671         }
672     );
673 }
674
675
676 function uEditDeleteAddr(id, noAlert) {
677     if(!noAlert) {
678         if(!confirm('Delete address ' + id)) return; /* XXX i18n */
679     }
680     var rows = dojo.query('tr[addr='+id+']', tbody);
681     for(var i = 0; i < rows.length; i++)
682         rows[i].parentNode.removeChild(rows[i]);
683     widgetPile = widgetPile.filter(function(w){return (w._addr != id)});
684 }
685
686 function uEditToggleRequired() {
687     if((tbody.className +'').match(/hide-non-required/)) 
688         openils.Util.removeCSSClass(tbody, 'hide-non-required');
689     else
690         openils.Util.addCSSClass(tbody, 'hide-non-required');
691     openils.Util.toggle('uedit-show-required');
692     openils.Util.toggle('uedit-show-all');
693 }
694
695
696
697 openils.Util.addOnLoad(load);