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);
155 var noPermGroups = [];
156 // Returns true if the user is allowed to edit the selected group
157 function checkGrpAppPerm(grpId) {
162 permGroups = new openils.PermaCrud().retrieveAll('pgt');
163 var permGroupPerms = []
165 // collect the group permissions
166 dojo.forEach(permGroups,
168 if(grp.application_perm())
169 permGroupPerms.push(grp.application_perm());
173 // see which of the group application perms I do not have
174 var myPerms = fieldmapper.standardRequest(
175 ['open-ils.actor', 'open-ils.actor.user.has_work_perm_at.batch'],
176 [openils.User.authtoken, permGroupPerms]
179 var failedPerms = [];
180 for(var p in myPerms) {
181 if(myPerms[p].length == 0)
185 // identify which groups I cannot edit because I do not have permisssion
187 function checkTree(grp, failed) {
188 failed = failed || failedPerms.indexOf(grp.application_perm()) > -1;
189 if(failed) noPermGroups.push(grp.id()+'');
191 permGroups.filter(function(g) { return g.parent() == grp.id() } ),
193 checkTree(child, failed);
198 checkTree(permGroups.filter(function(g) { return g.parent() == null })[0]);
201 return noPermGroups.indexOf(grpId+'') == -1;
205 function drawAllCards() {
207 var tbody = dojo.byId('uedit-all-cards-tbody');
208 if(!allCardsTemplate) {
209 allCardsTemplate = tbody.removeChild(dojo.byId('uedit-all-cards-tr-template'));
211 while(tbody.childNodes[0])
212 tbody.removeChild(tbody.childNodes[0]);
217 [patron.card()].concat(patron.cards()), // grab the main card first
220 if(card.id() == patron.card().id())
223 var row = allCardsTemplate.cloneNode(true);
224 getByName(row, 'barcode').innerHTML = card.barcode();
225 getByName(row, 'active').appendChild(
226 openils.Util.isTrue(card.active()) ?
227 dojo.byId('true').cloneNode(true) :
228 dojo.byId('false').cloneNode(true)
231 tbody.appendChild(row);
236 allCardsDialog.show();
240 * Mark the current card inactive, create a new primary card
242 function replaceCardHandler() {
243 var input = findWidget('ac', 'barcode');
244 input.widget.attr('disabled', false).attr('readOnly', false).attr('value', null).focus();
245 replaceBarcode.attr('disabled', true);
247 // pull old card off the cards list so we don't have a dupe sitting in there
248 var old = patron.cards().filter(function(c){return (c.id() == patron.card().id())})[0];
252 var newc = new fieldmapper.ac();
253 newc.id(uEditCardVirtId--);
257 var t = patron.cards();
265 * Loads a staged user and turns them into something the editor can understand
267 function uEditLoadStageUser(stageUname) {
269 var data = fieldmapper.standardRequest(
270 ['open-ils.actor', 'open-ils.actor.user.stage.retrieve.by_username'],
271 { params : [openils.User.authtoken, stageUname] }
274 stageUser = data.user;
275 patron = uEditNewPatron();
280 // copy the data into our new user object
281 for(var key in fieldmapper.IDL.fmclasses.stgu.field_map) {
282 if(fieldmapper.IDL.fmclasses.au.field_map[key] && !fieldmapper.IDL.fmclasses.stgu.field_map[key].virtual) {
283 if(data.user[key]() !== null)
284 patron[key]( data.user[key]() );
288 // copy the data into our new address objects
289 // TODO: uses the first mailing address only
290 if(data.mailing_addresses.length) {
292 var mail_addr = new fieldmapper.aua();
293 mail_addr.id(-1); // virtual ID
296 patron.mailing_address(mail_addr);
297 var t = patron.addresses();
302 for(var key in fieldmapper.IDL.fmclasses.stgma.field_map) {
303 if(fieldmapper.IDL.fmclasses.aua.field_map[key] && !fieldmapper.IDL.fmclasses.stgma.field_map[key].virtual) {
304 if(data.mailing_addresses[0][key]() !== null)
305 mail_addr[key]( data.mailing_addresses[0][key]() );
310 // copy the data into our new address objects
311 // TODO uses the first billing address only
312 if(data.billing_addresses.length) {
314 var bill_addr = new fieldmapper.aua();
315 bill_addr.id(-2); // virtual ID
318 patron.billing_address(bill_addr);
319 var t = patron.addresses();
324 for(var key in fieldmapper.IDL.fmclasses.stgba.field_map) {
325 if(fieldmapper.IDL.fmclasses.aua.field_map[key] && !fieldmapper.IDL.fmclasses.stgba.field_map[key].virtual) {
326 if(data.billing_addresses[0][key]() !== null)
327 bill_addr[key]( data.billing_addresses[0][key]() );
332 // TODO: uses the first card only
333 if(data.cards.length) {
334 var card = new fieldmapper.ac();
335 card.id(-1); // virtual ID
336 patron.card().barcode(data.cards[0].barcode());
343 * clone the home org, phone numbers, and billing/mailing address
345 function uEditCopyCloneData(patron) {
346 cloneUserObj = uEditLoadUser(cloneUser);
356 if(!uEditCloneCopyAddr)
357 cloneFields = cloneFields.concat(['mailing_address', 'billing_address']);
362 patron[field](cloneUserObj[field]());
366 if(uEditCloneCopyAddr) {
367 var billAddr, mailAddr;
369 // copy the billing and mailing addresses into new addresses
370 function cloneAddr(addr) {
371 var newAddr = addr.clone();
373 newAddr.id(uEditAddrVirtId--);
374 newAddr.usr(patron.id());
375 patron.addresses().push(newAddr);
379 if(billAddr = cloneUserObj.billing_address())
380 patron.billing_address(cloneAddr(billAddr));
382 if(mailAddr = cloneUserObj.mailing_address()) {
383 if (billAddr && billAddr.id() == mailAddr.id()) {
384 patron.mailing_address(patron.billing_address());
386 patron.mailing_address(cloneAddr(mailAddr));
390 if(!billAddr) // if there was no billing addr, use the mailing addr
391 patron.billing_address(patron.mailing_address());
395 // link the billing and mailing addresses
396 if(patron.billing_address()) {
397 var t = patron.addresses();
399 t.push(patron.billing_address());
403 if(patron.mailing_address() && (
404 patron.addresses().length == 0 ||
405 patron.mailing_address().id() != patron.billing_address().id()) ) {
406 var t = patron.addresses();
408 t.push(patron.mailing_address());
415 function uEditFetchUserSettings(userId) {
417 var baseNode = fieldmapper.aou.findOrgUnit(staff.ws_ou());
418 var orgs = fieldmapper.aou.orgNodeTrail(baseNode);
419 orgs = orgs.map(function(node) { return node.id(); });
421 /* fetch any user setting types we need + any that offer opt-in */
422 userSettingTypes = pcrud.search('cust', {
424 {name:['circ.holds_behind_desk']},
427 select : {atevdef : ['opt_in_setting']},
429 // we only care about opt-in settings for event_defs our users encounter
430 where : {'+atevdef' : {owner : orgs}}
436 var names = userSettingTypes.map(function(obj) { return obj.name() });
438 /* fetch any values set for this user */
440 userSettings = fieldmapper.standardRequest(
441 ['open-ils.actor', 'open-ils.actor.patron.settings.retrieve.authoritative'],
442 {params : [openils.User.authtoken, userId, names]});
447 function uEditLoadUser(userId) {
448 var patron = fieldmapper.standardRequest(
449 ['open-ils.actor', 'open-ils.actor.user.fleshed.retrieve.authoritative'],
450 {params : [openils.User.authtoken, userId]}
452 openils.Event.parse_and_raise(patron);
456 function loadStaticFields() {
457 for(var idx = 0; tbody.childNodes[idx]; idx++) {
458 var row = tbody.childNodes[idx];
459 if(row.nodeType != row.ELEMENT_NODE) continue;
460 var fmcls = row.getAttribute('fmclass');
462 fleshFMRow(row, fmcls);
465 if(row.id == 'uedit-settings-divider') {
467 var template = tbody.removeChild(dojo.byId('uedit-user-setting-template'));
468 dojo.forEach(userSettingTypes, function(type) { uEditDrawSettingRow(tbody, row, template, type); } );
470 if(userSettingTypes.length > 1 || orgSettings['circ.holds.behind_desk_pickup_supported']) {
471 openils.Util.show('uedit-settings-divider', 'table-row');
478 function uEditDrawSettingRow(tbody, dividerRow, template, stype) {
479 var row = template.cloneNode(true);
480 row.setAttribute('user_setting', stype.name());
481 getByName(row, 'label').innerHTML = stype.label();
482 var cb = new dijit.form.CheckBox({scrollOnFocus:false}, getByName(row, 'widget'));
483 cb.attr('value', userSettings[stype.name()]);
484 dojo.connect(cb, 'onChange', function(newVal) { userSettingsToUpdate[stype.name()] = newVal; });
485 tbody.insertBefore(row, dividerRow.nextSibling);
486 openils.Util.show(row, 'table-row');
489 function uEditUpdateUserSettings(userId) {
490 return fieldmapper.standardRequest(
491 ['open-ils.actor', 'open-ils.actor.patron.settings.update'],
492 {params : [openils.User.authtoken, userId, userSettingsToUpdate]});
495 function loadAllAddrs() {
496 dojo.forEach(patron.addresses(),
498 uEditNewAddr(null, addr.id());
503 function loadStatCats() {
505 statCats = fieldmapper.standardRequest(
506 ['open-ils.circ', 'open-ils.circ.stat_cat.actor.retrieve.all'],
507 {params : [openils.User.authtoken, staff.ws_ou()]}
511 for(var idx in statCats) {
512 var stat = statCats[idx];
513 var row = statCatTemplate.cloneNode(true);
514 row.id = 'stat-cat-row-' + idx;
515 row.setAttribute('stat_cat_owner',stat.owner());
516 row.setAttribute('stat_cat_name',stat.name());
517 row.setAttribute('stat_cat_id',stat.id());
518 tbody.appendChild(row);
519 getByName(row, 'name').innerHTML = stat.name();
520 var valtd = getByName(row, 'widget');
521 var span = valtd.appendChild(document.createElement('span'));
522 var store = new dojo.data.ItemFileReadStore(
523 {data:fieldmapper.actsc.toStoreData(stat.entries())});
524 var comboBox = new dijit.form.ComboBox({store:store,scrollOnFocus:false}, span);
525 comboBox.labelAttr = 'value';
526 comboBox.searchAttr = 'value';
528 comboBox._wtype = 'statcat';
529 comboBox._statcat = stat.id();
530 widgetPile.push(comboBox);
532 // populate existing cats
533 var map = patron.stat_cat_entries().filter(
534 function(mp) { return (mp.stat_cat() == stat.id()) })[0];
535 if(map) comboBox.attr('value', map.stat_cat_entry());
540 function loadSurveys() {
542 surveys = fieldmapper.standardRequest(
543 ['open-ils.circ', 'open-ils.circ.survey.retrieve.all'],
544 {params : [openils.User.authtoken]}
548 for(var idx in surveys) {
549 var survey = surveys[idx];
550 var srow = surveyTemplate.cloneNode(true);
551 tbody.appendChild(srow);
552 getByName(srow, 'name').innerHTML = survey.name();
554 for(var q in survey.questions()) {
555 var quest = survey.questions()[q];
556 var qrow = surveyQuestionTemplate.cloneNode(true);
557 tbody.appendChild(qrow);
558 getByName(qrow, 'question').innerHTML = quest.question();
560 var span = getByName(qrow, 'answers').appendChild(document.createElement('span'));
561 var store = new dojo.data.ItemFileReadStore(
562 {data:fieldmapper.asva.toStoreData(quest.answers())});
563 var select = new dijit.form.FilteringSelect({store:store,scrollOnFocus:false}, span);
564 if (! openils.Util.isTrue(survey.required())) {
565 select.isValid = function() { return true; };
567 select.labelAttr = 'answer';
568 select.searchAttr = 'answer';
570 select._wtype = 'survey';
571 select._survey = survey.id();
572 select._question = quest.id();
573 widgetPile.push(select);
579 function fleshFMRow(row, fmcls, args) {
580 var fmfield = row.getAttribute('fmfield');
581 var wclass = row.getAttribute('wclass');
582 var wstyle = row.getAttribute('wstyle');
583 var wconstraints = row.getAttribute('wconstraints');
584 /* use CSS to set the zindex for widgets you want to disable. */
585 var disabled = dojo.style(row, 'zIndex') == -1 ? true : false;
587 var isPasswd2 = (fmfield == 'passwd2');
588 if(isPasswd2) fmfield = 'passwd';
589 var fieldIdl = fieldmapper.IDL.fmclasses[fmcls].field_map[fmfield];
592 var existing = dojo.query('td', row);
593 var htd = existing[0] || row.appendChild(document.createElement('td'));
594 var ltd = existing[1] || row.appendChild(document.createElement('td'));
595 var wtd = existing[2] || row.appendChild(document.createElement('td'));
597 openils.Util.addCSSClass(htd, 'uedit-help');
598 if(fieldDoc[fmcls] && fieldDoc[fmcls][fmfield]) {
599 var link = dojo.byId('uedit-help-template').cloneNode(true);
601 link.onclick = function() { ueLoadContextHelp(fmcls, fmfield) };
602 openils.Util.removeCSSClass(link, 'hidden');
603 htd.appendChild(link);
606 if(!ltd.textContent) {
607 var span = document.createElement('span');
608 ltd.appendChild(document.createTextNode(fieldIdl.label));
611 span = document.createElement('span');
612 wtd.appendChild(span);
616 case 'au' : fmObject = patron; break;
617 case 'ac' : fmObject = patron.card(); break;
619 fmObject = patron.addresses().filter(
620 function(i) { return (i.id() == args.addr) })[0];
621 if(fmObject && fmObject.usr() != patron.id())
626 var required = row.getAttribute('required') == 'required';
628 // password data is not fetched/required/displayed for existing users
629 if(!patron.isnew() && 'passwd' == fmfield)
635 constraints : (wconstraints) ? eval('('+wconstraints+')') : {}, // the ()'s prevent Invalid Label errors with eval
639 if(fmcls == 'au' && fmfield == 'passwd') {
640 if (orgSettings['global.password_regex']) {
641 dijitArgs.regExp = orgSettings['global.password_regex'];
645 // TODO RSN: Add Setting!
646 if(fmcls == 'au' && fmfield == 'dob')
647 dijitArgs.popupClass = "";
649 var value = row.getAttribute('wvalue');
651 dijitArgs.value = value;
658 widgetClass : wclass,
659 dijitArgs : dijitArgs,
660 orgDefaultsToWs : true,
661 orgLimitPerms : ['UPDATE_USER'],
664 if(fmfield == 'profile') {
665 // fetch profile groups non-async so existing expire_date is
666 // not overwritten when the profile groups arrive and update
667 wargs.forceSync = true;
668 wargs.disableQuery = {usergroup : 'f'};
669 if(!patron.isnew() && !checkGrpAppPerm(patron.profile()))
670 wargs.readOnly = true;
672 wargs.forceSync = false;
675 var widget = new openils.widget.AutoFieldWidget(wargs);
678 if(fmfield == 'profile') { trimGrpTree(ww); }
682 // now put it back before we register the widget
683 if(isPasswd2) fmfield = 'passwd2';
685 widget._wtype = fmcls;
686 widget._fmfield = fmfield;
687 widget._addr = args.addr;
688 widgetPile.push(widget);
689 attachWidgetEvents(fmcls, fmfield, widget);
693 function trimGrpTree(autoWidget) {
694 var store = autoWidget.widget.store;
696 // remove all groups that this user are not allowed to edit,
697 // except the profile group of an existing user
698 store.fetch({onItem :
700 if(!checkGrpAppPerm(item.id[0]) && patron.profile() != item.id[0])
701 store.deleteItem(item);
706 function findWidget(wtype, fmfield, callback) {
707 return widgetPile.filter(
709 if(i._wtype == wtype && i._fmfield == fmfield) {
710 if(callback) return callback(i);
718 * if the user does not have the UPDATE_PATRON_CLAIM_RETURN_COUNT,
719 * they are not allowed to directly alter the claim return count.
720 * This function checks the perm and disable/enables the widget.
722 function checkClaimsReturnCountPerm() {
723 new openils.User().getPermOrgList(
724 'UPDATE_PATRON_CLAIM_RETURN_COUNT',
726 var cr = findWidget('au', 'claims_returned_count');
727 if(orgList.indexOf(patron.home_ou()) == -1)
728 cr.widget.attr('disabled', true);
730 cr.widget.attr('disabled', false);
738 function checkClaimsNoCheckoutCountPerm() {
739 new openils.User().getPermOrgList(
740 'UPDATE_PATRON_CLAIM_NEVER_CHECKED_OUT_COUNT',
742 var cr = findWidget('au', 'claims_never_checked_out_count');
743 if(orgList.indexOf(patron.home_ou()) == -1)
744 cr.widget.attr('disabled', true);
746 cr.widget.attr('disabled', false);
754 function attachWidgetEvents(fmcls, fmfield, widget) {
760 if (lock_ready && xulG && typeof xulG.lock_tab == 'function') {
769 if (lock_ready && xulG && typeof xulG.lock_tab == 'function') {
777 if(fmfield == 'barcode') {
778 dojo.connect(widget.widget, 'onChange',
780 var barcode = this.attr('value');
782 dojo.addClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
783 fieldmapper.standardRequest(
784 ['open-ils.actor', 'open-ils.actor.barcode.exists'],
786 params: [openils.User.authtoken, barcode],
787 oncomplete : function(r) {
788 var res = openils.Util.readResponse(r);
791 dojo.removeClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
794 dojo.addClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
795 var un = findWidget('au', 'usrname');
796 if(!un.widget.attr('value'))
797 un.widget.attr('value', barcode);
812 dojo.connect(widget.widget, 'onChange',
814 var input = findWidget('au', 'usrname');
815 var usrname = input.widget.attr('value');
819 dojo.addClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
823 fieldmapper.standardRequest(
824 ['open-ils.actor', 'open-ils.actor.username.exists'],
826 params: [openils.User.authtoken, usrname],
827 oncomplete : function(r) {
828 var res = openils.Util.readResponse(r);
831 dojo.removeClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
834 dojo.addClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
844 case 'profile': // when the profile changes, update the expire date
845 dojo.connect(widget.widget, 'onChange',
848 var expireWidget = findWidget('au', 'expire_date');
849 function found(items) {
850 if(items.length == 0) return;
852 var interval = self.store.getValue(item, 'perm_interval');
853 expireWidget.widget.attr('value', dojo.date.add(new Date(),
854 'second', openils.Util.intervalToSeconds(interval)));
856 this.store.fetch({onComplete:found, query:{id:this.attr('value')}});
862 dojo.connect(widget.widget, 'onChange',
865 var oldDob = patron.dob();
866 if(dojo.date.stamp.fromISOString(oldDob) == newDob) return;
868 var juvInterval = orgSettings['global.juvenile_age_threshold'] || '18 years';
869 var juvWidget = findWidget('au', 'juvenile');
870 var base = new Date();
871 base.setTime(base.getTime() - Number(openils.Util.intervalToSeconds(juvInterval) + '000'));
873 if(newDob <= base) // older than global.juvenile_age_threshold
874 juvWidget.widget.attr('value', false);
876 juvWidget.widget.attr('value', true);
881 case 'first_given_name':
883 dojo.connect(widget.widget, 'onChange',
884 function(newVal) { uEditDupeSearch('name', newVal); });
888 dojo.connect(widget.widget, 'onChange',
889 function(newVal) { uEditDupeSearch('email', newVal); });
894 dojo.connect(widget.widget, 'onChange',
895 function(newVal) { uEditDupeSearch('ident', newVal); });
899 // if configured, use the last for digits of the day phone number as the password
900 if(uEditUsePhonePw && patron.isnew()) {
901 dojo.connect(widget.widget, 'onChange',
903 if(newVal && newVal.length >= 4) {
904 var pw1 = findWidget('au', 'passwd').widget;
905 var pw2 = findWidget('au', 'passwd2').widget;
906 pw1.attr('value', newVal.substring(newVal.length - 4));
907 pw2.attr('value', newVal.substring(newVal.length - 4));
912 case 'evening_phone':
914 dojo.connect(widget.widget, 'onChange',
915 function(newVal) { uEditDupeSearch('phone', newVal); });
919 dojo.connect(widget.widget, 'onChange',
921 checkClaimsReturnCountPerm();
922 checkClaimsNoCheckoutCountPerm();
928 dojo.connect(widget.widget, 'onChange',
930 var pw1 = findWidget('au', 'passwd').widget;
931 var pw2 = findWidget('au', 'passwd2').widget;
932 var preserved_value = pw2.attr('value');
933 // Ensure that the pw2 field match the pw1 field to validate
934 pw2.regExp = newVal.replace(/([.\\^$*+?\(\)\[\]\{\}])/g, '\\$1');
936 pw2.attr('value',preserved_value);
942 if(fmclass = 'aua') {
945 dojo.connect(widget.widget, 'onChange',
947 fieldmapper.standardRequest(
948 ['open-ils.search', 'open-ils.search.zip'],
951 oncomplete : function(r) {
952 var res = openils.Util.readResponse(r);
954 var callback = function(w) { return w._addr == widget._addr; };
955 if(res.city) findWidget('aua', 'city', callback).widget.attr('value', res.city);
956 if(res.state) findWidget('aua', 'state', callback).widget.attr('value', res.state);
957 if(res.county) findWidget('aua', 'county', callback).widget.attr('value', res.county);
958 if(res.alert) alert(res.alert);
969 dojo.connect(widget.widget, 'onChange',
971 var callback = function(w) { return w._addr == widget._addr; };
973 street1 : findWidget('aua', 'street1', callback).widget.attr('value'),
974 street2 : findWidget('aua', 'street2', callback).widget.attr('value'),
975 city : findWidget('aua', 'city', callback).widget.attr('value'),
976 post_code : findWidget('aua', 'post_code', callback).widget.attr('value')
978 if(args.street1 && args.city && args.post_code)
979 uEditDupeSearch('address', args);
987 function uEditDupeSearch(type, value) {
993 openils.Util.hide('uedit-dupe-names-link');
994 var fname = findWidget('au', 'first_given_name').widget.attr('value');
995 var lname = findWidget('au', 'family_name').widget.attr('value');
996 if( !(fname && lname) ) return;
998 first_given_name : {value : fname, group : 0},
999 family_name : {value : lname, group : 0},
1004 openils.Util.hide('uedit-dupe-email-link');
1005 search = {email : {value : value, group : 0}};
1009 openils.Util.hide('uedit-dupe-ident-link');
1010 search = {ident : {value : value, group : 2}};
1014 openils.Util.hide('uedit-dupe-phone-link');
1015 search = {phone : {value : value, group : 2}};
1019 openils.Util.hide('uedit-dupe-address-link');
1021 dojo.forEach(['street1', 'street2', 'city', 'post_code'],
1024 search[field] = {value : value[field], group: 1};
1030 // find possible duplicate patrons
1031 fieldmapper.standardRequest(
1032 ['open-ils.actor', 'open-ils.actor.patron.search.advanced'],
1034 params: [openils.User.authtoken, search],
1035 oncomplete : function(r) {
1036 var resp = openils.Util.readResponse(r);
1037 resp = resp.filter(function(id) { return (id != patron.id()); });
1039 if(resp && resp.length > 0) {
1041 openils.Util.hide('uedit-help-div');
1042 openils.Util.show('uedit-dupe-div');
1047 link = dojo.byId('uedit-dupe-names-link');
1048 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_NAME, [resp.length]);
1051 link = dojo.byId('uedit-dupe-email-link');
1052 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_EMAIL, [resp.length]);
1055 link = dojo.byId('uedit-dupe-ident-link');
1056 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_IDENT, [resp.length]);
1059 link = dojo.byId('uedit-dupe-phone-link');
1060 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_PHONE, [resp.length]);
1063 link = dojo.byId('uedit-dupe-address-link');
1064 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_ADDR, [resp.length]);
1068 openils.Util.show(link);
1069 link.onclick = function() {
1070 search.search_sort = js2JSON(["penalties", "family_name", "first_given_name"]);
1072 window.xulG.spawn_search(search);
1074 console.log("running XUL patron search " + js2JSON(search));
1082 function getByName(node, name) {
1083 return dojo.query('[name='+name+']', node)[0];
1087 function ueLoadContextHelp(fmcls, fmfield) {
1088 openils.Util.hide('uedit-dupe-div');
1089 openils.Util.show('uedit-help-div');
1090 dojo.byId('uedit-help-field').innerHTML = fieldmapper.IDL.fmclasses[fmcls].field_map[fmfield].label;
1091 dojo.byId('uedit-help-text').innerHTML = fieldDoc[fmcls][fmfield].string();
1095 /* creates a new patron object with card attached */
1096 function uEditNewPatron() {
1101 card.id(uEditCardVirtId--);
1105 patron.cards([card]);
1106 patron.net_access_level(orgSettings['ui.patron.default_inet_access_level'] || 1);
1107 patron.ident_type(orgSettings['ui.patron.default_ident_type']);
1108 patron.stat_cat_entries([]);
1109 patron.survey_responses([]);
1110 patron.addresses([]);
1111 uEditMakeRandomPw(patron);
1115 function uEditMakeRandomPw(patron) {
1116 if(uEditUsePhonePw) return;
1117 var rand = Math.random();
1118 rand = parseInt(rand * 10000) + '';
1119 while(rand.length < 4) rand += '0';
1121 appendClear($('ue_password_plain'),text(rand));
1122 unHideMe($('ue_password_gen'));
1124 patron.passwd(rand);
1128 function uEditWidgetVal(w) {
1129 var val = (w.getFormattedValue) ? w.getFormattedValue() : w.attr('value');
1130 if(val === '') val = null;
1134 function uEditSave() { _uEditSave(); }
1135 function uEditSaveClone() { _uEditSave(true); }
1137 function _uEditSave(doClone) {
1139 if ( (! myForm.isValid()) || dupeUsrname || dupeBarcode ) {
1140 alert(localeStrings.INVALID_FORM);
1144 for(var idx in widgetPile) {
1145 var w = widgetPile[idx];
1146 var val = uEditWidgetVal(w);
1150 if(w._fmfield != 'passwd2')
1151 patron[w._fmfield](val);
1155 patron.card()[w._fmfield](val);
1159 var addr = patron.addresses().filter(function(i){return (i.id() == w._addr)})[0];
1161 addr = new fieldmapper.aua();
1164 addr.usr(patron.id());
1165 addr.country(orgSettings['ui.patron.default_country']);
1166 var t = patron.addresses();
1169 patron.addresses(t);
1171 if(addr[w._fmfield]() != val)
1174 addr[w._fmfield](val);
1176 if(dojo.byId('uedit-billing-address-' + addr.id()).checked)
1177 patron.billing_address(addr.id());
1179 if(dojo.byId('uedit-mailing-address-' + addr.id()).checked)
1180 patron.mailing_address(addr.id());
1185 if(val == null) break;
1186 var resp = new fieldmapper.asvr();
1188 resp.survey(w._survey)
1189 resp.usr(patron.id());
1190 resp.question(w._question)
1192 var t = patron.survey_responses();
1195 patron.survey_responses(t);
1199 if(val == null) break;
1201 var map = patron.stat_cat_entries().filter(
1203 return (m.stat_cat() == w._statcat) })[0];
1206 if(map.stat_cat_entry() == val)
1210 map = new fieldmapper.actscecm();
1214 map.stat_cat(w._statcat);
1215 map.stat_cat_entry(val);
1216 map.target_usr(patron.id());
1217 var t = patron.stat_cat_entries();
1220 patron.stat_cat_entries(t);
1225 patron.ischanged(1);
1226 fieldmapper.standardRequest(
1227 ['open-ils.actor', 'open-ils.actor.patron.update'],
1229 params: [openils.User.authtoken, patron],
1230 oncomplete: function(r) {
1232 if (xulG && typeof xulG.unlock_tab == 'function') { xulG.unlock_tab(); }
1233 newPatron = openils.Util.readResponse(r);
1235 uEditUpdateUserSettings(newPatron.id());
1236 if(stageUser) uEditRemoveStage();
1237 uEditFinishSave(newPatron, doClone);
1244 function uEditRemoveStage() {
1245 var resp = fieldmapper.standardRequest(
1246 ['open-ils.actor', 'open-ils.actor.user.stage.delete'],
1247 { params : [openils.User.authtoken, stageUser.row_id()] }
1251 function uEditFinishSave(newPatron, doClone) {
1253 if(doClone && cloneUser == null)
1254 cloneUser = newPatron.id();
1258 if(xulG && typeof xulG.spawn_editor == 'function' && !patron.isnew() ) {
1259 window.xulG.spawn_editor({ses:openils.User.authtoken,clone:cloneUser});
1263 location.href = location.href.replace(/\?.*/, '') + '?clone=' + cloneUser;
1271 uEditRefreshXUL(newPatron);
1274 function uEditRefresh() {
1275 var usr = cgi.param('usr');
1276 var href = location.href.replace(/\?.*/, '');
1277 href += ((usr) ? '?usr=' + usr : '');
1278 location.href = href;
1281 function uEditRefreshXUL(newuser) {
1282 if (window.xulG && typeof window.xulG.on_save == 'function')
1283 window.xulG.on_save(newuser);
1288 * Create a new address and insert it into the DOM
1289 * @param evt ignored
1290 * @param id The address id
1291 * @param mkLinks If true, set the new address as the
1292 * mailing/billing address for the user
1294 function uEditNewAddr(evt, id, mkLinks) {
1297 id = --uEditAddrVirtId; // new address
1299 var addr = patron.addresses().filter(
1300 function(i) { return (i.id() == id) })[0];
1302 dojo.forEach(addrTemplateRows,
1305 row = tbody.insertBefore(row.cloneNode(true), dojo.byId('new-addr-row'));
1306 row.setAttribute('type', '');
1307 row.setAttribute('addr', id+'');
1309 if(row.getAttribute('fmclass')) {
1310 var widget = fleshFMRow(row, 'aua', {addr:id});
1312 // make new addresses a default address type
1313 if(id < 0 && row.getAttribute('fmfield') == 'address_type')
1314 widget.widget.attr('value', localeStrings.DEFAULT_ADDRESS_TYPE);
1316 // make new addresses valid by default
1317 if(id < 0 && row.getAttribute('fmfield') == 'valid')
1318 widget.widget.attr('value', true);
1320 // make new addresses use the org setting for default country
1321 if(id < 0 && row.getAttribute('fmfield') == 'country')
1322 widget.widget.attr('value',orgSettings['ui.patron.default_country']);
1324 } else if(row.getAttribute('name') == 'uedit-addr-pending-row') {
1326 // if it's a pending address, show the 'approve' button
1327 if(addr && openils.Util.isTrue(addr.pending())) {
1328 openils.Util.show(row, 'table-row');
1329 dojo.query('[name=approve-button]', row)[0].onclick =
1330 function() { uEditApproveAddress(addr); };
1332 if(addr.replaces()) {
1333 var div = dojo.query('[name=replaced-addr]', row)[0]
1334 var replaced = patron.addresses().filter(
1335 function(i) { return (i.id() == addr.replaces()) })[0];
1337 div.innerHTML = dojo.string.substitute(localeStrings.REPLACED_ADDRESS, [
1338 replaced.address_type() || '',
1339 replaced.street1() || '',
1340 replaced.street2() || '',
1341 replaced.city() || '',
1342 replaced.state() || '',
1343 replaced.post_code() || ''
1347 openils.Util.hide(dojo.query('[name=replaced-addr-div]', row)[0]);
1351 } else if(row.getAttribute('name') == 'uedit-addr-owner-row') {
1352 // address is owned by someone else. provide option to load the
1353 // user in a different tab
1355 if(addr && addr.usr() != patron.id()) {
1356 openils.Util.show(row, 'table-row');
1357 var link = getByName(row, 'addr-owner');
1359 // fetch the linked user so we can present their name in the UI
1361 if(cloneUserObj && cloneUserObj.id() == addr.usr()) {
1363 cloneUserObj.first_given_name(),
1364 cloneUserObj.second_given_name(),
1365 cloneUserObj.family_name()
1368 addrUser = fieldmapper.standardRequest(
1369 ['open-ils.actor', 'open-ils.actor.user.retrieve.parts'],
1371 openils.User.authtoken,
1373 ['first_given_name', 'second_given_name', 'family_name']
1378 link.innerHTML = (addrUser.map(function(name) { return (name) ? name+' ' : '' })+'').replace(/,/g,''); // TODO i18n
1379 link.onclick = function() {
1380 if(openils.XUL.isXUL()) {
1381 window.xulG.spawn_editor({ses:openils.User.authtoken, usr:addr.usr()})
1383 parent.location.href = location.href.replace(/clone=\d+/, 'usr=' + addr.usr());
1388 } else if(row.getAttribute('name') == 'uedit-addr-divider') {
1389 // link up the billing/mailing address and give the inputs IDs so we can acces the later
1392 var ba = getByName(row, 'billing_address');
1393 ba.id = 'uedit-billing-address-' + id;
1394 if(mkLinks || (patron.billing_address() && patron.billing_address().id() == id))
1398 var ma = getByName(row, 'mailing_address');
1399 ma.id = 'uedit-mailing-address-' + id;
1400 if(mkLinks || (patron.mailing_address() && patron.mailing_address().id() == id))
1403 var btn = dojo.query('[name=delete-button]', row)[0];
1404 if(btn) btn.onclick = function(){ uEditDeleteAddr(id) };
1410 function uEditApproveAddress(addr) {
1411 fieldmapper.standardRequest(
1412 ['open-ils.actor', 'open-ils.actor.user.pending_address.approve'],
1414 params: [openils.User.authtoken, addr],
1416 oncomplete : function(r) {
1417 var oldId = openils.Util.readResponse(r);
1419 // remove addrs from UI
1422 function(addr) { uEditDeleteAddr(addr.id(), true); }
1427 // remove the replaced address
1428 if(oldId != addr.id()) {
1430 patron.addresses().filter(
1431 function(i) { return (i.id() != oldId); }
1436 // fix the the new address
1438 addr.replaces(null);
1451 function uEditDeleteAddr(id, noAlert) {
1452 if (patron.isnew() && orgSettings['ui.patron.registration.require_address']) {
1453 if (dojo.query('tr[name=uedit-addr-divider]').length < 2) {
1454 alert(localeStrings.NEED_ADDRESS);
1459 if(!confirm(dojo.string.substitute(localeStrings.DELETE_ADDRESS, [id]))) return;
1461 var addr = patron.addresses().filter(function(i){return (i.id() == id)})[0];
1462 if (addr) { addr.isdeleted(1); }
1463 var m_a = patron.mailing_address();
1464 if (typeof m_a == 'object' && m_a != null) { m_a = m_a.id(); }
1465 if (m_a == id) { patron.mailing_address(null); }
1466 var b_a = patron.billing_address();
1467 if (typeof b_a == 'object' && b_a != null) { b_a = b_a.id(); }
1468 if (b_a == id) { patron.billing_address(null); }
1470 var rows = dojo.query('tr[addr='+id+']', tbody);
1471 for(var i = 0; i < rows.length; i++)
1472 rows[i].parentNode.removeChild(rows[i]);
1473 widgetPile = widgetPile.filter(function(w){return (w._addr != id)});
1476 function uEditToggleRequired() {
1477 if((tbody.className +'').match(/hide-non-required/))
1478 openils.Util.removeCSSClass(tbody, 'hide-non-required');
1480 openils.Util.addCSSClass(tbody, 'hide-non-required');
1481 openils.Util.toggle('uedit-show-required');
1482 openils.Util.toggle('uedit-show-all');
1485 function printable_output() {
1486 var temp; var s = '=-=-=-=\r\n';
1487 for (var idx in widgetPile) {
1488 var w = widgetPile[idx];
1489 var val = uEditWidgetVal(w);
1491 if (typeof w.idlField == 'undefined') {
1493 if (w._wtype == 'statcat') {
1494 var stat = statCats.filter(
1496 return (m.id() == w._statcat) })[0];
1497 label = stat.name();
1498 } else if (w._wtype == 'survey') {
1499 var survey = surveys.filter(
1501 return (m.id() == w._survey) })[0];
1502 var question = survey.questions().filter(
1504 return (m.id() == w._question) })[0];
1505 label = survey.name() + ' : ' + question.question();
1510 label = w.idlField.label;
1512 if (temp != w._wtype) {
1516 s += label + ':\t' + (typeof val == 'object' ? '' : val) + '\r\n';
1522 openils.Util.addOnLoad(load);