1 dojo.require('dojo.data.ItemFileReadStore');
2 dojo.require('dijit.form.Form');
3 dojo.require('dijit.form.Textarea');
4 dojo.require('dijit.form.FilteringSelect');
5 dojo.require('dijit.form.ComboBox');
6 dojo.require('dijit.form.NumberSpinner');
7 dojo.require('fieldmapper.IDL');
8 dojo.require('openils.PermaCrud');
9 dojo.require('openils.widget.AutoGrid');
10 dojo.require('openils.widget.AutoFieldWidget');
11 dojo.require('dijit.form.CheckBox');
12 dojo.require('dijit.form.Button');
13 dojo.require('dojo.date');
14 dojo.require('openils.CGI');
15 dojo.require('openils.XUL');
16 dojo.require('openils.Util');
17 dojo.require('openils.Event');
19 dojo.requireLocalization('openils.actor', 'register');
20 var localeStrings = dojo.i18n.getLocalization('openils.actor', 'register');
24 var fmClasses = ['au', 'ac', 'aua', 'actsc', 'asv', 'asvq', 'asva'];
31 var uEditUsePhonePw = false;
33 var uEditCardVirtId = -1;
34 var uEditAddrVirtId = -1;
36 var userSettings = {};
37 var userSettingsToUpdate = {};
47 var uEditCloneCopyAddr; // if true, copy addrs on clone instead of link
49 var dupeUsrname = false;
50 var dupeBarcode = false;
52 if(!window.xulG) var xulG = null;
53 var lock_ready = false;
56 staff = new openils.User().user;
57 pcrud = new openils.PermaCrud();
58 cgi = new openils.CGI();
59 cloneUser = cgi.param('clone');
60 var userId = cgi.param('usr');
61 var stageUname = cgi.param('stage');
64 if(xulG.ses) openils.User.authtoken = xulG.ses;
65 if(typeof xulG.clone != 'undefined') cloneUser = xulG.clone;
66 if(typeof xulG.usr != 'undefined') userId = xulG.usr
67 if(typeof xulG.params != 'undefined') {
68 var parms = xulG.params;
69 if(typeof parms.ses != 'undefined')
70 openils.User.authtoken = parms.ses;
71 if(typeof parms.clone != 'undefined')
72 cloneUser = parms.clone;
73 if(typeof parms.usr != 'undefined')
75 if(typeof parms.stage != 'undefined')
76 stageUname = parms.stage
80 orgSettings = fieldmapper.aou.fetchOrgSettingBatch(staff.ws_ou(), [
81 'global.password_regex',
82 'global.juvenile_age_threshold',
83 'patron.password.use_phone',
84 'ui.patron.default_inet_access_level',
85 'ui.patron.default_ident_type',
86 'ui.patron.default_country',
87 'ui.patron.registration.require_address',
88 'circ.holds.behind_desk_pickup_supported',
89 'circ.patron_edit.clone.copy_address'
94 orgSettings[k] = orgSettings[k].value;
96 uEditCloneCopyAddr = orgSettings['circ.patron_edit.clone.copy_address'];
97 uEditUsePhonePw = orgSettings['patron.password.use_phone'];
98 uEditFetchUserSettings(userId);
101 patron = uEditLoadUser(userId);
104 patron = uEditLoadStageUser(stageUname);
106 patron = uEditNewPatron();
108 uEditCopyCloneData(patron);
113 var list = pcrud.search('fdoc', {fm_class:fmClasses});
116 if(!fieldDoc[doc.fm_class()])
117 fieldDoc[doc.fm_class()] = {};
118 fieldDoc[doc.fm_class()][doc.field()] = doc;
121 tbody = dojo.byId('uedit-tbody');
123 addrTemplateRows = dojo.query('tr[type=addr-template]', tbody);
124 dojo.forEach(addrTemplateRows, function(row) { row.parentNode.removeChild(row); } );
125 statCatTemplate = tbody.removeChild(dojo.byId('stat-cat-row-template'));
126 surveyTemplate = tbody.removeChild(dojo.byId('survey-row-template'));
127 surveyQuestionTemplate = tbody.removeChild(dojo.byId('survey-question-row-template'));
129 checkGrpAppPerm(); // to do the initial load
131 if(patron.isnew() && patron.addresses().length == 0)
132 uEditNewAddr(null, uEditAddrVirtId, true);
136 checkClaimsReturnCountPerm();
137 checkClaimsNoCheckoutCountPerm();
139 dojo.connect(replaceBarcode, 'onClick', replaceCardHandler);
140 dojo.connect(allCards, 'onClick', drawAllCards);
141 if(patron.cards().length > 1)
142 dojo.removeClass(dojo.byId('uedit-all-barcodes'), 'hidden');
144 var input = findWidget('ac', 'barcode');
145 if (patron.isnew()) {
146 replaceBarcode.attr('disabled', true);
148 input.widget.attr('disabled', true).attr('readOnly', true);
152 if(!patron.isnew() && !checkGrpAppPerm(patron.profile()) && patron.id() != openils.User.user.id()) {
153 // we are not allowed to edit this user, so disable the save option
154 saveButton.attr('disabled', true);
155 saveCloneButton.attr('disabled', true);
162 var noPermGroups = [];
163 // Returns true if the user is allowed to edit the selected group
164 function checkGrpAppPerm(grpId) {
169 permGroups = new openils.PermaCrud().retrieveAll('pgt');
170 var permGroupPerms = []
172 // collect the group permissions
173 dojo.forEach(permGroups,
175 if(grp.application_perm())
176 permGroupPerms.push(grp.application_perm());
180 // see which of the group application perms I do not have
181 var myPerms = fieldmapper.standardRequest(
182 ['open-ils.actor', 'open-ils.actor.user.has_work_perm_at.batch'],
183 [openils.User.authtoken, permGroupPerms]
186 var failedPerms = [];
187 for(var p in myPerms) {
188 if(myPerms[p].length == 0)
192 // identify which groups I cannot edit because I do not have permisssion
194 function checkTree(grp, failed) {
195 failed = failed || failedPerms.indexOf(grp.application_perm()) > -1;
196 if(failed) noPermGroups.push(grp.id()+'');
198 permGroups.filter(function(g) { return g.parent() == grp.id() } ),
200 checkTree(child, failed);
205 checkTree(permGroups.filter(function(g) { return g.parent() == null })[0]);
208 return noPermGroups.indexOf(grpId+'') == -1;
212 function drawAllCards() {
214 var tbody = dojo.byId('uedit-all-cards-tbody');
215 if(!allCardsTemplate) {
216 allCardsTemplate = tbody.removeChild(dojo.byId('uedit-all-cards-tr-template'));
218 while(tbody.childNodes[0])
219 tbody.removeChild(tbody.childNodes[0]);
224 [patron.card()].concat(patron.cards()), // grab the main card first
227 if(card.id() == patron.card().id())
230 var row = allCardsTemplate.cloneNode(true);
231 getByName(row, 'barcode').innerHTML = card.barcode();
232 getByName(row, 'active').appendChild(
233 openils.Util.isTrue(card.active()) ?
234 dojo.byId('true').cloneNode(true) :
235 dojo.byId('false').cloneNode(true)
238 tbody.appendChild(row);
243 allCardsDialog.show();
247 * Mark the current card inactive, create a new primary card
249 function replaceCardHandler() {
250 var input = findWidget('ac', 'barcode');
251 input.widget.attr('disabled', false).attr('readOnly', false).attr('value', null).focus();
252 replaceBarcode.attr('disabled', true);
254 // pull old card off the cards list so we don't have a dupe sitting in there
255 var old = patron.cards().filter(function(c){return (c.id() == patron.card().id())})[0];
259 var newc = new fieldmapper.ac();
260 newc.id(uEditCardVirtId--);
264 var t = patron.cards();
272 * Loads a staged user and turns them into something the editor can understand
274 function uEditLoadStageUser(stageUname) {
276 var data = fieldmapper.standardRequest(
277 ['open-ils.actor', 'open-ils.actor.user.stage.retrieve.by_username'],
278 { params : [openils.User.authtoken, stageUname] }
281 stageUser = data.user;
282 patron = uEditNewPatron();
287 // copy the data into our new user object
288 for(var key in fieldmapper.IDL.fmclasses.stgu.field_map) {
289 if(fieldmapper.IDL.fmclasses.au.field_map[key] && !fieldmapper.IDL.fmclasses.stgu.field_map[key].virtual) {
290 if(data.user[key]() !== null)
291 patron[key]( data.user[key]() );
295 // copy the data into our new address objects
296 // TODO: uses the first mailing address only
297 if(data.mailing_addresses.length) {
299 var mail_addr = new fieldmapper.aua();
300 mail_addr.id(-1); // virtual ID
303 patron.mailing_address(mail_addr);
304 var t = patron.addresses();
309 for(var key in fieldmapper.IDL.fmclasses.stgma.field_map) {
310 if(fieldmapper.IDL.fmclasses.aua.field_map[key] && !fieldmapper.IDL.fmclasses.stgma.field_map[key].virtual) {
311 if(data.mailing_addresses[0][key]() !== null)
312 mail_addr[key]( data.mailing_addresses[0][key]() );
317 // copy the data into our new address objects
318 // TODO uses the first billing address only
319 if(data.billing_addresses.length) {
321 var bill_addr = new fieldmapper.aua();
322 bill_addr.id(-2); // virtual ID
325 patron.billing_address(bill_addr);
326 var t = patron.addresses();
331 for(var key in fieldmapper.IDL.fmclasses.stgba.field_map) {
332 if(fieldmapper.IDL.fmclasses.aua.field_map[key] && !fieldmapper.IDL.fmclasses.stgba.field_map[key].virtual) {
333 if(data.billing_addresses[0][key]() !== null)
334 bill_addr[key]( data.billing_addresses[0][key]() );
339 // TODO: uses the first card only
340 if(data.cards.length) {
341 var card = new fieldmapper.ac();
342 card.id(-1); // virtual ID
343 patron.card().barcode(data.cards[0].barcode());
350 * clone the home org, phone numbers, and billing/mailing address
352 function uEditCopyCloneData(patron) {
353 cloneUserObj = uEditLoadUser(cloneUser);
363 if(!uEditCloneCopyAddr)
364 cloneFields = cloneFields.concat(['mailing_address', 'billing_address']);
369 patron[field](cloneUserObj[field]());
373 if(uEditCloneCopyAddr) {
374 var billAddr, mailAddr;
376 // copy the billing and mailing addresses into new addresses
377 function cloneAddr(addr) {
378 var newAddr = addr.clone();
380 newAddr.id(uEditAddrVirtId--);
381 newAddr.usr(patron.id());
382 patron.addresses().push(newAddr);
386 if(billAddr = cloneUserObj.billing_address())
387 patron.billing_address(cloneAddr(billAddr));
389 if(mailAddr = cloneUserObj.mailing_address()) {
390 if (billAddr && billAddr.id() == mailAddr.id()) {
391 patron.mailing_address(patron.billing_address());
393 patron.mailing_address(cloneAddr(mailAddr));
397 if(!billAddr) // if there was no billing addr, use the mailing addr
398 patron.billing_address(patron.mailing_address());
402 // link the billing and mailing addresses
403 if(patron.billing_address()) {
404 var t = patron.addresses();
406 t.push(patron.billing_address());
410 if(patron.mailing_address() && (
411 patron.addresses().length == 0 ||
412 patron.mailing_address().id() != patron.billing_address().id()) ) {
413 var t = patron.addresses();
415 t.push(patron.mailing_address());
422 function uEditFetchUserSettings(userId) {
424 var baseNode = fieldmapper.aou.findOrgUnit(staff.ws_ou());
425 var orgs = fieldmapper.aou.orgNodeTrail(baseNode);
426 orgs = orgs.map(function(node) { return node.id(); });
428 /* fetch any user setting types we need + any that offer opt-in */
429 userSettingTypes = pcrud.search('cust', {
431 {name:['circ.holds_behind_desk']},
434 select : {atevdef : ['opt_in_setting']},
436 // we only care about opt-in settings for event_defs our users encounter
437 where : {'+atevdef' : {owner : orgs}}
443 var names = userSettingTypes.map(function(obj) { return obj.name() });
445 /* fetch any values set for this user */
447 userSettings = fieldmapper.standardRequest(
448 ['open-ils.actor', 'open-ils.actor.patron.settings.retrieve.authoritative'],
449 {params : [openils.User.authtoken, userId, names]});
454 function uEditLoadUser(userId) {
455 var patron = fieldmapper.standardRequest(
456 ['open-ils.actor', 'open-ils.actor.user.fleshed.retrieve.authoritative'],
457 {params : [openils.User.authtoken, userId]}
459 openils.Event.parse_and_raise(patron);
463 function loadStaticFields() {
464 for(var idx = 0; tbody.childNodes[idx]; idx++) {
465 var row = tbody.childNodes[idx];
466 if(row.nodeType != row.ELEMENT_NODE) continue;
467 var fmcls = row.getAttribute('fmclass');
469 fleshFMRow(row, fmcls);
472 if(row.id == 'uedit-settings-divider') {
474 var template = tbody.removeChild(dojo.byId('uedit-user-setting-template'));
475 dojo.forEach(userSettingTypes, function(type) { uEditDrawSettingRow(tbody, row, template, type); } );
477 if(userSettingTypes.length > 1 || orgSettings['circ.holds.behind_desk_pickup_supported']) {
478 openils.Util.show('uedit-settings-divider', 'table-row');
485 function uEditDrawSettingRow(tbody, dividerRow, template, stype) {
486 var row = template.cloneNode(true);
487 row.setAttribute('user_setting', stype.name());
488 getByName(row, 'label').innerHTML = stype.label();
489 var cb = new dijit.form.CheckBox({scrollOnFocus:false}, getByName(row, 'widget'));
490 cb.attr('value', userSettings[stype.name()]);
491 dojo.connect(cb, 'onChange', function(newVal) { userSettingsToUpdate[stype.name()] = newVal; });
492 tbody.insertBefore(row, dividerRow.nextSibling);
493 openils.Util.show(row, 'table-row');
496 function uEditUpdateUserSettings(userId) {
497 return fieldmapper.standardRequest(
498 ['open-ils.actor', 'open-ils.actor.patron.settings.update'],
499 {params : [openils.User.authtoken, userId, userSettingsToUpdate]});
502 function loadAllAddrs() {
503 dojo.forEach(patron.addresses(),
505 uEditNewAddr(null, addr.id());
510 function loadStatCats() {
512 statCats = fieldmapper.standardRequest(
513 ['open-ils.circ', 'open-ils.circ.stat_cat.actor.retrieve.all'],
514 {params : [openils.User.authtoken, staff.ws_ou()]}
518 for(var idx in statCats) {
519 var stat = statCats[idx];
520 var row = statCatTemplate.cloneNode(true);
521 row.id = 'stat-cat-row-' + idx;
522 row.setAttribute('stat_cat_owner',stat.owner());
523 row.setAttribute('stat_cat_name',stat.name());
524 row.setAttribute('stat_cat_id',stat.id());
525 tbody.appendChild(row);
526 getByName(row, 'name').innerHTML = stat.name();
527 var valtd = getByName(row, 'widget');
528 var span = valtd.appendChild(document.createElement('span'));
529 var store = new dojo.data.ItemFileReadStore(
530 {data:fieldmapper.actsc.toStoreData(stat.entries())});
531 var comboBox = new dijit.form.ComboBox({store:store,scrollOnFocus:false}, span);
532 comboBox.labelAttr = 'value';
533 comboBox.searchAttr = 'value';
535 comboBox._wtype = 'statcat';
536 comboBox._statcat = stat.id();
537 widgetPile.push(comboBox);
539 // populate existing cats
540 var map = patron.stat_cat_entries().filter(
541 function(mp) { return (mp.stat_cat() == stat.id()) })[0];
542 if(map) comboBox.attr('value', map.stat_cat_entry());
547 function loadSurveys() {
549 surveys = fieldmapper.standardRequest(
550 ['open-ils.circ', 'open-ils.circ.survey.retrieve.all'],
551 {params : [openils.User.authtoken]}
555 for(var idx in surveys) {
556 var survey = surveys[idx];
557 var srow = surveyTemplate.cloneNode(true);
558 tbody.appendChild(srow);
559 getByName(srow, 'name').innerHTML = survey.name();
561 for(var q in survey.questions()) {
562 var quest = survey.questions()[q];
563 var qrow = surveyQuestionTemplate.cloneNode(true);
564 tbody.appendChild(qrow);
565 getByName(qrow, 'question').innerHTML = quest.question();
567 var span = getByName(qrow, 'answers').appendChild(document.createElement('span'));
568 var store = new dojo.data.ItemFileReadStore(
569 {data:fieldmapper.asva.toStoreData(quest.answers())});
570 var select = new dijit.form.FilteringSelect({store:store,scrollOnFocus:false}, span);
571 if (! openils.Util.isTrue(survey.required())) {
572 select.isValid = function() { return true; };
574 select.labelAttr = 'answer';
575 select.searchAttr = 'answer';
577 select._wtype = 'survey';
578 select._survey = survey.id();
579 select._question = quest.id();
580 widgetPile.push(select);
586 function fleshFMRow(row, fmcls, args) {
587 var fmfield = row.getAttribute('fmfield');
588 var wclass = row.getAttribute('wclass');
589 var wstyle = row.getAttribute('wstyle');
590 var wconstraints = row.getAttribute('wconstraints');
591 /* use CSS to set the zindex for widgets you want to disable. */
592 var disabled = dojo.style(row, 'zIndex') == -1 ? true : false;
594 var isPasswd2 = (fmfield == 'passwd2');
595 if(isPasswd2) fmfield = 'passwd';
596 var fieldIdl = fieldmapper.IDL.fmclasses[fmcls].field_map[fmfield];
599 var existing = dojo.query('td', row);
600 var htd = existing[0] || row.appendChild(document.createElement('td'));
601 var ltd = existing[1] || row.appendChild(document.createElement('td'));
602 var wtd = existing[2] || row.appendChild(document.createElement('td'));
604 openils.Util.addCSSClass(htd, 'uedit-help');
605 if(fieldDoc[fmcls] && fieldDoc[fmcls][fmfield]) {
606 var link = dojo.byId('uedit-help-template').cloneNode(true);
608 link.onclick = function() { ueLoadContextHelp(fmcls, fmfield) };
609 openils.Util.removeCSSClass(link, 'hidden');
610 htd.appendChild(link);
613 if(!ltd.textContent) {
614 var span = document.createElement('span');
615 ltd.appendChild(document.createTextNode(fieldIdl.label));
618 span = document.createElement('span');
619 wtd.appendChild(span);
623 case 'au' : fmObject = patron; break;
624 case 'ac' : fmObject = patron.card(); break;
626 fmObject = patron.addresses().filter(
627 function(i) { return (i.id() == args.addr) })[0];
628 if(fmObject && fmObject.usr() != patron.id())
633 var required = row.getAttribute('required') == 'required';
635 // password data is not fetched/required/displayed for existing users
636 if(!patron.isnew() && 'passwd' == fmfield)
642 constraints : (wconstraints) ? eval('('+wconstraints+')') : {}, // the ()'s prevent Invalid Label errors with eval
646 if(fmcls == 'au' && fmfield == 'passwd') {
647 if (orgSettings['global.password_regex']) {
648 dijitArgs.regExp = orgSettings['global.password_regex'];
652 // TODO RSN: Add Setting!
653 if(fmcls == 'au' && fmfield == 'dob')
654 dijitArgs.popupClass = "";
656 var value = row.getAttribute('wvalue');
658 dijitArgs.value = value;
665 widgetClass : wclass,
666 dijitArgs : dijitArgs,
667 orgDefaultsToWs : true,
668 orgLimitPerms : ['UPDATE_USER'],
671 if(fmfield == 'profile') {
672 // fetch profile groups non-async so existing expire_date is
673 // not overwritten when the profile groups arrive and update
674 wargs.forceSync = true;
675 wargs.disableQuery = {usergroup : 'f'};
676 if(!patron.isnew() && !checkGrpAppPerm(patron.profile()))
677 wargs.readOnly = true;
679 wargs.forceSync = false;
682 var widget = new openils.widget.AutoFieldWidget(wargs);
685 if(fmfield == 'profile') { trimGrpTree(ww); }
689 // now put it back before we register the widget
690 if(isPasswd2) fmfield = 'passwd2';
692 widget._wtype = fmcls;
693 widget._fmfield = fmfield;
694 widget._addr = args.addr;
695 widgetPile.push(widget);
696 attachWidgetEvents(fmcls, fmfield, widget);
700 function trimGrpTree(autoWidget) {
701 var store = autoWidget.widget.store;
703 // remove all groups that this user are not allowed to edit,
704 // except the profile group of an existing user
705 store.fetch({onItem :
707 if(!checkGrpAppPerm(item.id[0]) && patron.profile() != item.id[0])
708 store.deleteItem(item);
713 function findWidget(wtype, fmfield, callback) {
714 return widgetPile.filter(
716 if(i._wtype == wtype && i._fmfield == fmfield) {
717 if(callback) return callback(i);
725 * if the user does not have the UPDATE_PATRON_CLAIM_RETURN_COUNT,
726 * they are not allowed to directly alter the claim return count.
727 * This function checks the perm and disable/enables the widget.
729 function checkClaimsReturnCountPerm() {
730 new openils.User().getPermOrgList(
731 'UPDATE_PATRON_CLAIM_RETURN_COUNT',
733 var cr = findWidget('au', 'claims_returned_count');
734 if(orgList.indexOf(patron.home_ou()) == -1)
735 cr.widget.attr('disabled', true);
737 cr.widget.attr('disabled', false);
745 function checkClaimsNoCheckoutCountPerm() {
746 new openils.User().getPermOrgList(
747 'UPDATE_PATRON_CLAIM_NEVER_CHECKED_OUT_COUNT',
749 var cr = findWidget('au', 'claims_never_checked_out_count');
750 if(orgList.indexOf(patron.home_ou()) == -1)
751 cr.widget.attr('disabled', true);
753 cr.widget.attr('disabled', false);
761 function attachWidgetEvents(fmcls, fmfield, widget) {
767 if (lock_ready && xulG && typeof xulG.lock_tab == 'function') {
776 if (lock_ready && xulG && typeof xulG.lock_tab == 'function') {
784 if(fmfield == 'barcode') {
785 dojo.connect(widget.widget, 'onChange',
787 var barcode = this.attr('value');
789 dojo.addClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
790 fieldmapper.standardRequest(
791 ['open-ils.actor', 'open-ils.actor.barcode.exists'],
793 params: [openils.User.authtoken, barcode],
794 oncomplete : function(r) {
795 var res = openils.Util.readResponse(r);
798 dojo.removeClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
801 dojo.addClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
802 var un = findWidget('au', 'usrname');
803 if(!un.widget.attr('value'))
804 un.widget.attr('value', barcode);
819 dojo.connect(widget.widget, 'onChange',
821 var input = findWidget('au', 'usrname');
822 var usrname = input.widget.attr('value');
826 dojo.addClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
830 fieldmapper.standardRequest(
831 ['open-ils.actor', 'open-ils.actor.username.exists'],
833 params: [openils.User.authtoken, usrname],
834 oncomplete : function(r) {
835 var res = openils.Util.readResponse(r);
838 dojo.removeClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
841 dojo.addClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
851 case 'profile': // when the profile changes, update the expire date
852 dojo.connect(widget.widget, 'onChange',
855 var expireWidget = findWidget('au', 'expire_date');
856 function found(items) {
857 if(items.length == 0) return;
859 var interval = self.store.getValue(item, 'perm_interval');
860 expireWidget.widget.attr('value', dojo.date.add(new Date(),
861 'second', openils.Util.intervalToSeconds(interval)));
863 this.store.fetch({onComplete:found, query:{id:this.attr('value')}});
869 dojo.connect(widget.widget, 'onChange',
872 var oldDob = patron.dob();
873 if(dojo.date.stamp.fromISOString(oldDob) == newDob) return;
875 var juvInterval = orgSettings['global.juvenile_age_threshold'] || '18 years';
876 var juvWidget = findWidget('au', 'juvenile');
877 var base = new Date();
878 base.setTime(base.getTime() - Number(openils.Util.intervalToSeconds(juvInterval) + '000'));
880 if(newDob <= base) // older than global.juvenile_age_threshold
881 juvWidget.widget.attr('value', false);
883 juvWidget.widget.attr('value', true);
888 case 'first_given_name':
890 dojo.connect(widget.widget, 'onChange',
891 function(newVal) { uEditDupeSearch('name', newVal); });
895 dojo.connect(widget.widget, 'onChange',
896 function(newVal) { uEditDupeSearch('email', newVal); });
901 dojo.connect(widget.widget, 'onChange',
902 function(newVal) { uEditDupeSearch('ident', newVal); });
906 // if configured, use the last for digits of the day phone number as the password
907 if(uEditUsePhonePw && patron.isnew()) {
908 dojo.connect(widget.widget, 'onChange',
910 if(newVal && newVal.length >= 4) {
911 var pw1 = findWidget('au', 'passwd').widget;
912 var pw2 = findWidget('au', 'passwd2').widget;
913 pw1.attr('value', newVal.substring(newVal.length - 4));
914 pw2.attr('value', newVal.substring(newVal.length - 4));
919 case 'evening_phone':
921 dojo.connect(widget.widget, 'onChange',
922 function(newVal) { uEditDupeSearch('phone', newVal); });
926 dojo.connect(widget.widget, 'onChange',
928 checkClaimsReturnCountPerm();
929 checkClaimsNoCheckoutCountPerm();
935 dojo.connect(widget.widget, 'onChange',
937 var pw1 = findWidget('au', 'passwd').widget;
938 var pw2 = findWidget('au', 'passwd2').widget;
939 var preserved_value = pw2.attr('value');
940 // Ensure that the pw2 field match the pw1 field to validate
941 pw2.regExp = newVal.replace(/([.\\^$*+?\(\)\[\]\{\}])/g, '\\$1');
943 pw2.attr('value',preserved_value);
949 if(fmclass = 'aua') {
952 dojo.connect(widget.widget, 'onChange',
954 fieldmapper.standardRequest(
955 ['open-ils.search', 'open-ils.search.zip'],
958 oncomplete : function(r) {
959 var res = openils.Util.readResponse(r);
961 var callback = function(w) { return w._addr == widget._addr; };
962 if(res.city) findWidget('aua', 'city', callback).widget.attr('value', res.city);
963 if(res.state) findWidget('aua', 'state', callback).widget.attr('value', res.state);
964 if(res.county) findWidget('aua', 'county', callback).widget.attr('value', res.county);
965 if(res.alert) alert(res.alert);
976 dojo.connect(widget.widget, 'onChange',
978 var callback = function(w) { return w._addr == widget._addr; };
980 street1 : findWidget('aua', 'street1', callback).widget.attr('value'),
981 street2 : findWidget('aua', 'street2', callback).widget.attr('value'),
982 city : findWidget('aua', 'city', callback).widget.attr('value'),
983 post_code : findWidget('aua', 'post_code', callback).widget.attr('value')
985 if(args.street1 && args.city && args.post_code)
986 uEditDupeSearch('address', args);
994 function uEditDupeSearch(type, value) {
1000 openils.Util.hide('uedit-dupe-names-link');
1001 var fname = findWidget('au', 'first_given_name').widget.attr('value');
1002 var lname = findWidget('au', 'family_name').widget.attr('value');
1003 if( !(fname && lname) ) return;
1005 first_given_name : {value : fname, group : 0},
1006 family_name : {value : lname, group : 0},
1011 openils.Util.hide('uedit-dupe-email-link');
1012 search = {email : {value : value, group : 0}};
1016 openils.Util.hide('uedit-dupe-ident-link');
1017 search = {ident : {value : value, group : 2}};
1021 openils.Util.hide('uedit-dupe-phone-link');
1022 search = {phone : {value : value, group : 2}};
1026 openils.Util.hide('uedit-dupe-address-link');
1028 dojo.forEach(['street1', 'street2', 'city', 'post_code'],
1031 search[field] = {value : value[field], group: 1};
1037 // find possible duplicate patrons
1038 fieldmapper.standardRequest(
1039 ['open-ils.actor', 'open-ils.actor.patron.search.advanced'],
1041 params: [openils.User.authtoken, search],
1042 oncomplete : function(r) {
1043 var resp = openils.Util.readResponse(r);
1044 resp = resp.filter(function(id) { return (id != patron.id()); });
1046 if(resp && resp.length > 0) {
1048 openils.Util.hide('uedit-help-div');
1049 openils.Util.show('uedit-dupe-div');
1054 link = dojo.byId('uedit-dupe-names-link');
1055 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_NAME, [resp.length]);
1058 link = dojo.byId('uedit-dupe-email-link');
1059 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_EMAIL, [resp.length]);
1062 link = dojo.byId('uedit-dupe-ident-link');
1063 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_IDENT, [resp.length]);
1066 link = dojo.byId('uedit-dupe-phone-link');
1067 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_PHONE, [resp.length]);
1070 link = dojo.byId('uedit-dupe-address-link');
1071 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_ADDR, [resp.length]);
1075 openils.Util.show(link);
1076 link.onclick = function() {
1077 search.search_sort = js2JSON(["penalties", "family_name", "first_given_name"]);
1079 window.xulG.spawn_search(search);
1081 console.log("running XUL patron search " + js2JSON(search));
1089 function getByName(node, name) {
1090 return dojo.query('[name='+name+']', node)[0];
1094 function ueLoadContextHelp(fmcls, fmfield) {
1095 openils.Util.hide('uedit-dupe-div');
1096 openils.Util.show('uedit-help-div');
1097 dojo.byId('uedit-help-field').innerHTML = fieldmapper.IDL.fmclasses[fmcls].field_map[fmfield].label;
1098 dojo.byId('uedit-help-text').innerHTML = fieldDoc[fmcls][fmfield].string();
1102 /* creates a new patron object with card attached */
1103 function uEditNewPatron() {
1108 card.id(uEditCardVirtId--);
1112 patron.cards([card]);
1113 patron.net_access_level(orgSettings['ui.patron.default_inet_access_level'] || 1);
1114 patron.ident_type(orgSettings['ui.patron.default_ident_type']);
1115 patron.stat_cat_entries([]);
1116 patron.survey_responses([]);
1117 patron.addresses([]);
1118 uEditMakeRandomPw(patron);
1122 function uEditMakeRandomPw(patron) {
1123 if(uEditUsePhonePw) return;
1124 var rand = Math.random();
1125 rand = parseInt(rand * 10000) + '';
1126 while(rand.length < 4) rand += '0';
1128 appendClear($('ue_password_plain'),text(rand));
1129 unHideMe($('ue_password_gen'));
1131 patron.passwd(rand);
1135 function uEditWidgetVal(w) {
1136 var val = (w.getFormattedValue) ? w.getFormattedValue() : w.attr('value');
1137 if(val === '') val = null;
1141 function uEditSave() { _uEditSave(); }
1142 function uEditSaveClone() { _uEditSave(true); }
1144 function _uEditSave(doClone) {
1146 if ( (! myForm.isValid()) || dupeUsrname || dupeBarcode ) {
1147 alert(localeStrings.INVALID_FORM);
1151 for(var idx in widgetPile) {
1152 var w = widgetPile[idx];
1153 var val = uEditWidgetVal(w);
1157 if(w._fmfield != 'passwd2')
1158 patron[w._fmfield](val);
1162 patron.card()[w._fmfield](val);
1166 var addr = patron.addresses().filter(function(i){return (i.id() == w._addr)})[0];
1168 addr = new fieldmapper.aua();
1171 addr.usr(patron.id());
1172 addr.country(orgSettings['ui.patron.default_country']);
1173 var t = patron.addresses();
1176 patron.addresses(t);
1178 if(addr[w._fmfield]() != val)
1181 addr[w._fmfield](val);
1183 if(dojo.byId('uedit-billing-address-' + addr.id()).checked)
1184 patron.billing_address(addr.id());
1186 if(dojo.byId('uedit-mailing-address-' + addr.id()).checked)
1187 patron.mailing_address(addr.id());
1192 if(val == null) break;
1193 var resp = new fieldmapper.asvr();
1195 resp.survey(w._survey)
1196 resp.usr(patron.id());
1197 resp.question(w._question)
1199 var t = patron.survey_responses();
1202 patron.survey_responses(t);
1206 if(val == null) break;
1208 var map = patron.stat_cat_entries().filter(
1210 return (m.stat_cat() == w._statcat) })[0];
1213 if(map.stat_cat_entry() == val)
1217 map = new fieldmapper.actscecm();
1221 map.stat_cat(w._statcat);
1222 map.stat_cat_entry(val);
1223 map.target_usr(patron.id());
1224 var t = patron.stat_cat_entries();
1227 patron.stat_cat_entries(t);
1232 patron.ischanged(1);
1233 fieldmapper.standardRequest(
1234 ['open-ils.actor', 'open-ils.actor.patron.update'],
1236 params: [openils.User.authtoken, patron],
1237 oncomplete: function(r) {
1239 if (xulG && typeof xulG.unlock_tab == 'function') { xulG.unlock_tab(); }
1240 newPatron = openils.Util.readResponse(r);
1242 uEditUpdateUserSettings(newPatron.id());
1243 if(stageUser) uEditRemoveStage();
1244 uEditFinishSave(newPatron, doClone);
1251 function uEditRemoveStage() {
1252 var resp = fieldmapper.standardRequest(
1253 ['open-ils.actor', 'open-ils.actor.user.stage.delete'],
1254 { params : [openils.User.authtoken, stageUser.row_id()] }
1258 function uEditFinishSave(newPatron, doClone) {
1260 if(doClone && cloneUser == null)
1261 cloneUser = newPatron.id();
1265 if(xulG && typeof xulG.spawn_editor == 'function' && !patron.isnew() ) {
1266 window.xulG.spawn_editor({ses:openils.User.authtoken,clone:cloneUser});
1270 location.href = location.href.replace(/\?.*/, '') + '?clone=' + cloneUser;
1278 uEditRefreshXUL(newPatron);
1281 function uEditRefresh() {
1282 var usr = cgi.param('usr');
1283 var href = location.href.replace(/\?.*/, '');
1284 href += ((usr) ? '?usr=' + usr : '');
1285 location.href = href;
1288 function uEditRefreshXUL(newuser) {
1289 if (window.xulG && typeof window.xulG.on_save == 'function')
1290 window.xulG.on_save(newuser);
1295 * Create a new address and insert it into the DOM
1296 * @param evt ignored
1297 * @param id The address id
1298 * @param mkLinks If true, set the new address as the
1299 * mailing/billing address for the user
1301 function uEditNewAddr(evt, id, mkLinks) {
1304 id = --uEditAddrVirtId; // new address
1306 var addr = patron.addresses().filter(
1307 function(i) { return (i.id() == id) })[0];
1309 dojo.forEach(addrTemplateRows,
1312 row = tbody.insertBefore(row.cloneNode(true), dojo.byId('new-addr-row'));
1313 row.setAttribute('type', '');
1314 row.setAttribute('addr', id+'');
1316 if(row.getAttribute('fmclass')) {
1317 var widget = fleshFMRow(row, 'aua', {addr:id});
1319 // make new addresses a default address type
1320 if(id < 0 && row.getAttribute('fmfield') == 'address_type')
1321 widget.widget.attr('value', localeStrings.DEFAULT_ADDRESS_TYPE);
1323 // make new addresses valid by default
1324 if(id < 0 && row.getAttribute('fmfield') == 'valid')
1325 widget.widget.attr('value', true);
1327 // make new addresses use the org setting for default country
1328 if(id < 0 && row.getAttribute('fmfield') == 'country')
1329 widget.widget.attr('value',orgSettings['ui.patron.default_country']);
1331 } else if(row.getAttribute('name') == 'uedit-addr-pending-row') {
1333 // if it's a pending address, show the 'approve' button
1334 if(addr && openils.Util.isTrue(addr.pending())) {
1335 openils.Util.show(row, 'table-row');
1336 dojo.query('[name=approve-button]', row)[0].onclick =
1337 function() { uEditApproveAddress(addr); };
1339 if(addr.replaces()) {
1340 var div = dojo.query('[name=replaced-addr]', row)[0]
1341 var replaced = patron.addresses().filter(
1342 function(i) { return (i.id() == addr.replaces()) })[0];
1344 div.innerHTML = dojo.string.substitute(localeStrings.REPLACED_ADDRESS, [
1345 replaced.address_type() || '',
1346 replaced.street1() || '',
1347 replaced.street2() || '',
1348 replaced.city() || '',
1349 replaced.state() || '',
1350 replaced.post_code() || ''
1354 openils.Util.hide(dojo.query('[name=replaced-addr-div]', row)[0]);
1358 } else if(row.getAttribute('name') == 'uedit-addr-owner-row') {
1359 // address is owned by someone else. provide option to load the
1360 // user in a different tab
1362 if(addr && addr.usr() != patron.id()) {
1363 openils.Util.show(row, 'table-row');
1364 var link = getByName(row, 'addr-owner');
1366 // fetch the linked user so we can present their name in the UI
1368 if(cloneUserObj && cloneUserObj.id() == addr.usr()) {
1370 cloneUserObj.first_given_name(),
1371 cloneUserObj.second_given_name(),
1372 cloneUserObj.family_name()
1375 addrUser = fieldmapper.standardRequest(
1376 ['open-ils.actor', 'open-ils.actor.user.retrieve.parts'],
1378 openils.User.authtoken,
1380 ['first_given_name', 'second_given_name', 'family_name']
1385 link.innerHTML = (addrUser.map(function(name) { return (name) ? name+' ' : '' })+'').replace(/,/g,''); // TODO i18n
1386 link.onclick = function() {
1387 if(openils.XUL.isXUL()) {
1388 window.xulG.spawn_editor({ses:openils.User.authtoken, usr:addr.usr()})
1390 parent.location.href = location.href.replace(/clone=\d+/, 'usr=' + addr.usr());
1395 } else if(row.getAttribute('name') == 'uedit-addr-divider') {
1396 // link up the billing/mailing address and give the inputs IDs so we can acces the later
1399 var ba = getByName(row, 'billing_address');
1400 ba.id = 'uedit-billing-address-' + id;
1401 if(mkLinks || (patron.billing_address() && patron.billing_address().id() == id))
1405 var ma = getByName(row, 'mailing_address');
1406 ma.id = 'uedit-mailing-address-' + id;
1407 if(mkLinks || (patron.mailing_address() && patron.mailing_address().id() == id))
1410 var btn = dojo.query('[name=delete-button]', row)[0];
1411 if(btn) btn.onclick = function(){ uEditDeleteAddr(id) };
1417 function uEditApproveAddress(addr) {
1418 fieldmapper.standardRequest(
1419 ['open-ils.actor', 'open-ils.actor.user.pending_address.approve'],
1421 params: [openils.User.authtoken, addr],
1423 oncomplete : function(r) {
1424 var oldId = openils.Util.readResponse(r);
1426 // remove addrs from UI
1429 function(addr) { uEditDeleteAddr(addr.id(), true); }
1434 // remove the replaced address
1435 if(oldId != addr.id()) {
1437 patron.addresses().filter(
1438 function(i) { return (i.id() != oldId); }
1443 // fix the the new address
1445 addr.replaces(null);
1458 function uEditDeleteAddr(id, noAlert) {
1459 if (patron.isnew() && orgSettings['ui.patron.registration.require_address']) {
1460 if (dojo.query('tr[name=uedit-addr-divider]').length < 2) {
1461 alert(localeStrings.NEED_ADDRESS);
1466 if(!confirm(dojo.string.substitute(localeStrings.DELETE_ADDRESS, [id]))) return;
1468 var addr = patron.addresses().filter(function(i){return (i.id() == id)})[0];
1469 if (addr) { addr.isdeleted(1); }
1470 var m_a = patron.mailing_address();
1471 if (typeof m_a == 'object' && m_a != null) { m_a = m_a.id(); }
1472 if (m_a == id) { patron.mailing_address(null); }
1473 var b_a = patron.billing_address();
1474 if (typeof b_a == 'object' && b_a != null) { b_a = b_a.id(); }
1475 if (b_a == id) { patron.billing_address(null); }
1477 var rows = dojo.query('tr[addr='+id+']', tbody);
1478 for(var i = 0; i < rows.length; i++)
1479 rows[i].parentNode.removeChild(rows[i]);
1480 widgetPile = widgetPile.filter(function(w){return (w._addr != id)});
1483 function uEditToggleRequired() {
1484 if((tbody.className +'').match(/hide-non-required/))
1485 openils.Util.removeCSSClass(tbody, 'hide-non-required');
1487 openils.Util.addCSSClass(tbody, 'hide-non-required');
1488 openils.Util.toggle('uedit-show-required');
1489 openils.Util.toggle('uedit-show-all');
1492 function printable_output() {
1493 var temp; var s = '=-=-=-=\r\n';
1494 for (var idx in widgetPile) {
1495 var w = widgetPile[idx];
1496 var val = uEditWidgetVal(w);
1498 if (typeof w.idlField == 'undefined') {
1500 if (w._wtype == 'statcat') {
1501 var stat = statCats.filter(
1503 return (m.id() == w._statcat) })[0];
1504 label = stat.name();
1505 } else if (w._wtype == 'survey') {
1506 var survey = surveys.filter(
1508 return (m.id() == w._survey) })[0];
1509 var question = survey.questions().filter(
1511 return (m.id() == w._question) })[0];
1512 label = survey.name() + ' : ' + question.question();
1517 label = w.idlField.label;
1519 if (temp != w._wtype) {
1523 s += label + ':\t' + (typeof val == 'object' ? '' : val) + '\r\n';
1529 openils.Util.addOnLoad(load);