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;
54 var already_locked = false;
57 staff = new openils.User().user;
58 pcrud = new openils.PermaCrud();
59 cgi = new openils.CGI();
60 cloneUser = cgi.param('clone');
61 var userId = cgi.param('usr');
62 var stageUname = cgi.param('stage');
65 if(xulG.ses) openils.User.authtoken = xulG.ses;
66 if(typeof xulG.clone != 'undefined') cloneUser = xulG.clone;
67 if(typeof xulG.usr != 'undefined') userId = xulG.usr
68 if(typeof xulG.params != 'undefined') {
69 var parms = xulG.params;
70 if(typeof parms.ses != 'undefined')
71 openils.User.authtoken = parms.ses;
72 if(typeof parms.clone != 'undefined')
73 cloneUser = parms.clone;
74 if(typeof parms.usr != 'undefined')
76 if(typeof parms.stage != 'undefined')
77 stageUname = parms.stage
81 orgSettings = fieldmapper.aou.fetchOrgSettingBatch(staff.ws_ou(), [
82 'global.password_regex',
83 'global.juvenile_age_threshold',
84 'patron.password.use_phone',
85 'ui.patron.default_inet_access_level',
86 'ui.patron.default_ident_type',
87 'ui.patron.default_country',
88 'ui.patron.registration.require_address',
89 'circ.holds.behind_desk_pickup_supported',
90 'circ.patron_edit.clone.copy_address'
95 orgSettings[k] = orgSettings[k].value;
97 uEditCloneCopyAddr = orgSettings['circ.patron_edit.clone.copy_address'];
98 uEditUsePhonePw = orgSettings['patron.password.use_phone'];
99 uEditFetchUserSettings(userId);
102 patron = uEditLoadUser(userId);
105 patron = uEditLoadStageUser(stageUname);
107 patron = uEditNewPatron();
109 uEditCopyCloneData(patron);
114 var list = pcrud.search('fdoc', {fm_class:fmClasses});
117 if(!fieldDoc[doc.fm_class()])
118 fieldDoc[doc.fm_class()] = {};
119 fieldDoc[doc.fm_class()][doc.field()] = doc;
122 tbody = dojo.byId('uedit-tbody');
124 addrTemplateRows = dojo.query('tr[type=addr-template]', tbody);
125 dojo.forEach(addrTemplateRows, function(row) { row.parentNode.removeChild(row); } );
126 statCatTemplate = tbody.removeChild(dojo.byId('stat-cat-row-template'));
127 surveyTemplate = tbody.removeChild(dojo.byId('survey-row-template'));
128 surveyQuestionTemplate = tbody.removeChild(dojo.byId('survey-question-row-template'));
130 checkGrpAppPerm(); // to do the initial load
132 if(patron.isnew() && patron.addresses().length == 0)
133 uEditNewAddr(null, uEditAddrVirtId, true);
137 checkClaimsReturnCountPerm();
138 checkClaimsNoCheckoutCountPerm();
140 dojo.connect(replaceBarcode, 'onClick', replaceCardHandler);
141 dojo.connect(allCards, 'onClick', drawAllCards);
142 if(patron.cards().length > 1)
143 dojo.removeClass(dojo.byId('uedit-all-barcodes'), 'hidden');
145 var input = findWidget('ac', 'barcode');
146 if (patron.isnew()) {
147 replaceBarcode.attr('disabled', true);
149 input.widget.attr('disabled', true).attr('readOnly', true);
153 if(!patron.isnew() && !checkGrpAppPerm(patron.profile()) && patron.id() != openils.User.user.id()) {
154 // we are not allowed to edit this user, so disable the save option
155 saveButton.attr('disabled', true);
156 saveCloneButton.attr('disabled', true);
163 var noPermGroups = [];
164 // Returns true if the user is allowed to edit the selected group
165 function checkGrpAppPerm(grpId) {
170 permGroups = new openils.PermaCrud().retrieveAll('pgt');
171 var permGroupPerms = []
173 // collect the group permissions
174 dojo.forEach(permGroups,
176 if(grp.application_perm())
177 permGroupPerms.push(grp.application_perm());
181 // see which of the group application perms I do not have
182 var myPerms = fieldmapper.standardRequest(
183 ['open-ils.actor', 'open-ils.actor.user.has_work_perm_at.batch'],
184 [openils.User.authtoken, permGroupPerms]
187 var failedPerms = [];
188 for(var p in myPerms) {
189 if(myPerms[p].length == 0)
193 // identify which groups I cannot edit because I do not have permisssion
195 function checkTree(grp, failed) {
196 failed = failed || failedPerms.indexOf(grp.application_perm()) > -1;
197 if(failed) noPermGroups.push(grp.id()+'');
199 permGroups.filter(function(g) { return g.parent() == grp.id() } ),
201 checkTree(child, failed);
206 checkTree(permGroups.filter(function(g) { return g.parent() == null })[0]);
209 return noPermGroups.indexOf(grpId+'') == -1;
213 function drawAllCards() {
215 var tbody = dojo.byId('uedit-all-cards-tbody');
216 if(!allCardsTemplate) {
217 allCardsTemplate = tbody.removeChild(dojo.byId('uedit-all-cards-tr-template'));
219 while(tbody.childNodes[0])
220 tbody.removeChild(tbody.childNodes[0]);
225 [patron.card()].concat(patron.cards()), // grab the main card first
228 if(card.id() == patron.card().id())
231 var row = allCardsTemplate.cloneNode(true);
232 getByName(row, 'barcode').innerHTML = card.barcode();
233 getByName(row, 'active').appendChild(
234 openils.Util.isTrue(card.active()) ?
235 dojo.byId('true').cloneNode(true) :
236 dojo.byId('false').cloneNode(true)
239 tbody.appendChild(row);
244 allCardsDialog.show();
248 * Mark the current card inactive, create a new primary card
250 function replaceCardHandler() {
251 var input = findWidget('ac', 'barcode');
252 input.widget.attr('disabled', false).attr('readOnly', false).attr('value', null).focus();
253 replaceBarcode.attr('disabled', true);
255 // pull old card off the cards list so we don't have a dupe sitting in there
256 var old = patron.cards().filter(function(c){return (c.id() == patron.card().id())})[0];
260 var newc = new fieldmapper.ac();
261 newc.id(uEditCardVirtId--);
265 var t = patron.cards();
273 * Loads a staged user and turns them into something the editor can understand
275 function uEditLoadStageUser(stageUname) {
277 var data = fieldmapper.standardRequest(
278 ['open-ils.actor', 'open-ils.actor.user.stage.retrieve.by_username'],
279 { params : [openils.User.authtoken, stageUname] }
282 stageUser = data.user;
283 patron = uEditNewPatron();
288 // copy the data into our new user object
289 for(var key in fieldmapper.IDL.fmclasses.stgu.field_map) {
290 if(fieldmapper.IDL.fmclasses.au.field_map[key] && !fieldmapper.IDL.fmclasses.stgu.field_map[key].virtual) {
291 if(data.user[key]() !== null)
292 patron[key]( data.user[key]() );
296 // copy the data into our new address objects
297 // TODO: uses the first mailing address only
298 if(data.mailing_addresses.length) {
300 var mail_addr = new fieldmapper.aua();
301 mail_addr.id(-1); // virtual ID
304 patron.mailing_address(mail_addr);
305 var t = patron.addresses();
310 for(var key in fieldmapper.IDL.fmclasses.stgma.field_map) {
311 if(fieldmapper.IDL.fmclasses.aua.field_map[key] && !fieldmapper.IDL.fmclasses.stgma.field_map[key].virtual) {
312 if(data.mailing_addresses[0][key]() !== null)
313 mail_addr[key]( data.mailing_addresses[0][key]() );
318 // copy the data into our new address objects
319 // TODO uses the first billing address only
320 if(data.billing_addresses.length) {
322 var bill_addr = new fieldmapper.aua();
323 bill_addr.id(-2); // virtual ID
326 patron.billing_address(bill_addr);
327 var t = patron.addresses();
332 for(var key in fieldmapper.IDL.fmclasses.stgba.field_map) {
333 if(fieldmapper.IDL.fmclasses.aua.field_map[key] && !fieldmapper.IDL.fmclasses.stgba.field_map[key].virtual) {
334 if(data.billing_addresses[0][key]() !== null)
335 bill_addr[key]( data.billing_addresses[0][key]() );
340 // TODO: uses the first card only
341 if(data.cards.length) {
342 var card = new fieldmapper.ac();
343 card.id(-1); // virtual ID
344 patron.card().barcode(data.cards[0].barcode());
351 * clone the home org, phone numbers, and billing/mailing address
353 function uEditCopyCloneData(patron) {
354 cloneUserObj = uEditLoadUser(cloneUser);
364 if(!uEditCloneCopyAddr)
365 cloneFields = cloneFields.concat(['mailing_address', 'billing_address']);
370 patron[field](cloneUserObj[field]());
374 if(uEditCloneCopyAddr) {
375 var billAddr, mailAddr;
377 // copy the billing and mailing addresses into new addresses
378 function cloneAddr(addr) {
379 var newAddr = addr.clone();
381 newAddr.id(uEditAddrVirtId--);
382 newAddr.usr(patron.id());
383 patron.addresses().push(newAddr);
387 if(billAddr = cloneUserObj.billing_address())
388 patron.billing_address(cloneAddr(billAddr));
390 if(mailAddr = cloneUserObj.mailing_address()) {
391 if (billAddr && billAddr.id() == mailAddr.id()) {
392 patron.mailing_address(patron.billing_address());
394 patron.mailing_address(cloneAddr(mailAddr));
398 if(!billAddr) // if there was no billing addr, use the mailing addr
399 patron.billing_address(patron.mailing_address());
403 // link the billing and mailing addresses
404 if(patron.billing_address()) {
405 var t = patron.addresses();
407 t.push(patron.billing_address());
411 if(patron.mailing_address() && (
412 patron.addresses().length == 0 ||
413 patron.mailing_address().id() != patron.billing_address().id()) ) {
414 var t = patron.addresses();
416 t.push(patron.mailing_address());
423 function uEditFetchUserSettings(userId) {
425 var baseNode = fieldmapper.aou.findOrgUnit(staff.ws_ou());
426 var orgs = fieldmapper.aou.orgNodeTrail(baseNode);
427 orgs = orgs.map(function(node) { return node.id(); });
429 /* fetch any user setting types we need + any that offer opt-in */
430 userSettingTypes = pcrud.search('cust', {
432 {name:['circ.holds_behind_desk']},
435 select : {atevdef : ['opt_in_setting']},
437 // we only care about opt-in settings for event_defs our users encounter
438 where : {'+atevdef' : {owner : orgs}}
444 var names = userSettingTypes.map(function(obj) { return obj.name() });
446 /* fetch any values set for this user */
448 userSettings = fieldmapper.standardRequest(
449 ['open-ils.actor', 'open-ils.actor.patron.settings.retrieve.authoritative'],
450 {params : [openils.User.authtoken, userId, names]});
455 function uEditLoadUser(userId) {
456 var patron = fieldmapper.standardRequest(
457 ['open-ils.actor', 'open-ils.actor.user.fleshed.retrieve.authoritative'],
458 {params : [openils.User.authtoken, userId]}
460 openils.Event.parse_and_raise(patron);
464 function loadStaticFields() {
465 for(var idx = 0; tbody.childNodes[idx]; idx++) {
466 var row = tbody.childNodes[idx];
467 if(row.nodeType != row.ELEMENT_NODE) continue;
468 var fmcls = row.getAttribute('fmclass');
470 fleshFMRow(row, fmcls);
473 if(row.id == 'uedit-settings-divider') {
475 var template = tbody.removeChild(dojo.byId('uedit-user-setting-template'));
476 dojo.forEach(userSettingTypes, function(type) { uEditDrawSettingRow(tbody, row, template, type); } );
478 if(userSettingTypes.length > 1 || orgSettings['circ.holds.behind_desk_pickup_supported']) {
479 openils.Util.show('uedit-settings-divider', 'table-row');
486 function uEditDrawSettingRow(tbody, dividerRow, template, stype) {
487 var row = template.cloneNode(true);
488 row.setAttribute('user_setting', stype.name());
489 getByName(row, 'label').innerHTML = stype.label();
490 var cb = new dijit.form.CheckBox({scrollOnFocus:false}, getByName(row, 'widget'));
491 cb.attr('value', userSettings[stype.name()]);
492 dojo.connect(cb, 'onChange', function(newVal) { userSettingsToUpdate[stype.name()] = newVal; });
493 tbody.insertBefore(row, dividerRow.nextSibling);
494 openils.Util.show(row, 'table-row');
497 function uEditUpdateUserSettings(userId) {
498 return fieldmapper.standardRequest(
499 ['open-ils.actor', 'open-ils.actor.patron.settings.update'],
500 {params : [openils.User.authtoken, userId, userSettingsToUpdate]});
503 function loadAllAddrs() {
504 dojo.forEach(patron.addresses(),
506 uEditNewAddr(null, addr.id());
511 function loadStatCats() {
513 statCats = fieldmapper.standardRequest(
514 ['open-ils.circ', 'open-ils.circ.stat_cat.actor.retrieve.all'],
515 {params : [openils.User.authtoken, staff.ws_ou()]}
519 for(var idx in statCats) {
520 var stat = statCats[idx];
521 var row = statCatTemplate.cloneNode(true);
522 row.id = 'stat-cat-row-' + idx;
523 row.setAttribute('stat_cat_owner',stat.owner());
524 row.setAttribute('stat_cat_name',stat.name());
525 row.setAttribute('stat_cat_id',stat.id());
526 tbody.appendChild(row);
527 getByName(row, 'name').innerHTML = stat.name();
528 var valtd = getByName(row, 'widget');
529 var span = valtd.appendChild(document.createElement('span'));
530 var store = new dojo.data.ItemFileReadStore(
531 {data:fieldmapper.actsc.toStoreData(stat.entries())});
532 var comboBox = new dijit.form.ComboBox({store:store,scrollOnFocus:false}, span);
533 comboBox.labelAttr = 'value';
534 comboBox.searchAttr = 'value';
536 comboBox._wtype = 'statcat';
537 comboBox._statcat = stat.id();
538 widgetPile.push(comboBox);
540 // populate existing cats
541 var map = patron.stat_cat_entries().filter(
542 function(mp) { return (mp.stat_cat() == stat.id()) })[0];
543 if(map) comboBox.attr('value', map.stat_cat_entry());
548 function loadSurveys() {
550 surveys = fieldmapper.standardRequest(
551 ['open-ils.circ', 'open-ils.circ.survey.retrieve.all'],
552 {params : [openils.User.authtoken]}
556 for(var idx in surveys) {
557 var survey = surveys[idx];
558 var srow = surveyTemplate.cloneNode(true);
559 tbody.appendChild(srow);
560 getByName(srow, 'name').innerHTML = survey.name();
562 for(var q in survey.questions()) {
563 var quest = survey.questions()[q];
564 var qrow = surveyQuestionTemplate.cloneNode(true);
565 tbody.appendChild(qrow);
566 getByName(qrow, 'question').innerHTML = quest.question();
568 var span = getByName(qrow, 'answers').appendChild(document.createElement('span'));
569 var store = new dojo.data.ItemFileReadStore(
570 {data:fieldmapper.asva.toStoreData(quest.answers())});
571 var select = new dijit.form.FilteringSelect({store:store,scrollOnFocus:false}, span);
572 if (! openils.Util.isTrue(survey.required())) {
573 select.isValid = function() { return true; };
575 select.labelAttr = 'answer';
576 select.searchAttr = 'answer';
578 select._wtype = 'survey';
579 select._survey = survey.id();
580 select._question = quest.id();
581 widgetPile.push(select);
587 function fleshFMRow(row, fmcls, args) {
588 var fmfield = row.getAttribute('fmfield');
589 var wclass = row.getAttribute('wclass');
590 var wstyle = row.getAttribute('wstyle');
591 var wconstraints = row.getAttribute('wconstraints');
592 /* use CSS to set the zindex for widgets you want to disable. */
593 var disabled = dojo.style(row, 'zIndex') == -1 ? true : false;
595 var isPasswd2 = (fmfield == 'passwd2');
596 if(isPasswd2) fmfield = 'passwd';
597 var fieldIdl = fieldmapper.IDL.fmclasses[fmcls].field_map[fmfield];
600 var existing = dojo.query('td', row);
601 var htd = existing[0] || row.appendChild(document.createElement('td'));
602 var ltd = existing[1] || row.appendChild(document.createElement('td'));
603 var wtd = existing[2] || row.appendChild(document.createElement('td'));
605 openils.Util.addCSSClass(htd, 'uedit-help');
606 if(fieldDoc[fmcls] && fieldDoc[fmcls][fmfield]) {
607 var link = dojo.byId('uedit-help-template').cloneNode(true);
609 link.onclick = function() { ueLoadContextHelp(fmcls, fmfield) };
610 openils.Util.removeCSSClass(link, 'hidden');
611 htd.appendChild(link);
614 if(!ltd.textContent) {
615 var span = document.createElement('span');
616 ltd.appendChild(document.createTextNode(fieldIdl.label));
619 span = document.createElement('span');
620 wtd.appendChild(span);
624 case 'au' : fmObject = patron; break;
625 case 'ac' : fmObject = patron.card(); break;
627 fmObject = patron.addresses().filter(
628 function(i) { return (i.id() == args.addr) })[0];
629 if(fmObject && fmObject.usr() != patron.id())
634 var required = row.getAttribute('required') == 'required';
636 // password data is not fetched/required/displayed for existing users
637 if(!patron.isnew() && 'passwd' == fmfield)
643 constraints : (wconstraints) ? eval('('+wconstraints+')') : {}, // the ()'s prevent Invalid Label errors with eval
647 if(fmcls == 'au' && fmfield == 'passwd') {
648 if (orgSettings['global.password_regex']) {
649 dijitArgs.regExp = orgSettings['global.password_regex'];
653 // TODO RSN: Add Setting!
654 if(fmcls == 'au' && fmfield == 'dob')
655 dijitArgs.popupClass = "";
657 var value = row.getAttribute('wvalue');
659 dijitArgs.value = value;
666 widgetClass : wclass,
667 dijitArgs : dijitArgs,
668 orgDefaultsToWs : true,
669 orgLimitPerms : ['UPDATE_USER'],
672 if(fmfield == 'profile') {
673 // fetch profile groups non-async so existing expire_date is
674 // not overwritten when the profile groups arrive and update
675 wargs.forceSync = true;
676 wargs.disableQuery = {usergroup : 'f'};
677 if(!patron.isnew() && !checkGrpAppPerm(patron.profile()))
678 wargs.readOnly = true;
680 wargs.forceSync = false;
683 var widget = new openils.widget.AutoFieldWidget(wargs);
686 if(fmfield == 'profile') { trimGrpTree(ww); }
690 // now put it back before we register the widget
691 if(isPasswd2) fmfield = 'passwd2';
693 widget._wtype = fmcls;
694 widget._fmfield = fmfield;
695 widget._addr = args.addr;
696 widgetPile.push(widget);
697 attachWidgetEvents(fmcls, fmfield, widget);
701 function trimGrpTree(autoWidget) {
702 var store = autoWidget.widget.store;
704 // remove all groups that this user are not allowed to edit,
705 // except the profile group of an existing user
706 store.fetch({onItem :
708 if(!checkGrpAppPerm(item.id[0]) && patron.profile() != item.id[0])
709 store.deleteItem(item);
714 function findWidget(wtype, fmfield, callback) {
715 return widgetPile.filter(
717 if(i._wtype == wtype && i._fmfield == fmfield) {
718 if(callback) return callback(i);
726 * if the user does not have the UPDATE_PATRON_CLAIM_RETURN_COUNT,
727 * they are not allowed to directly alter the claim return count.
728 * This function checks the perm and disable/enables the widget.
730 function checkClaimsReturnCountPerm() {
731 new openils.User().getPermOrgList(
732 'UPDATE_PATRON_CLAIM_RETURN_COUNT',
734 var cr = findWidget('au', 'claims_returned_count');
735 if(orgList.indexOf(patron.home_ou()) == -1)
736 cr.widget.attr('disabled', true);
738 cr.widget.attr('disabled', false);
746 function checkClaimsNoCheckoutCountPerm() {
747 new openils.User().getPermOrgList(
748 'UPDATE_PATRON_CLAIM_NEVER_CHECKED_OUT_COUNT',
750 var cr = findWidget('au', 'claims_never_checked_out_count');
751 if(orgList.indexOf(patron.home_ou()) == -1)
752 cr.widget.attr('disabled', true);
754 cr.widget.attr('disabled', false);
762 function attachWidgetEvents(fmcls, fmfield, widget) {
768 if (lock_ready && xulG && typeof xulG.lock_tab == 'function') {
769 if (! already_locked) {
771 already_locked = true;
780 if (lock_ready && xulG && typeof xulG.lock_tab == 'function') {
781 if (! already_locked) {
783 already_locked = true;
791 if(fmfield == 'barcode') {
792 dojo.connect(widget.widget, 'onChange',
794 var barcode = this.attr('value');
796 dojo.addClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
797 fieldmapper.standardRequest(
798 ['open-ils.actor', 'open-ils.actor.barcode.exists'],
800 params: [openils.User.authtoken, barcode],
801 oncomplete : function(r) {
802 var res = openils.Util.readResponse(r);
805 dojo.removeClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
808 dojo.addClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
809 var un = findWidget('au', 'usrname');
810 if(!un.widget.attr('value'))
811 un.widget.attr('value', barcode);
826 dojo.connect(widget.widget, 'onChange',
828 var input = findWidget('au', 'usrname');
829 var usrname = input.widget.attr('value');
833 dojo.addClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
837 fieldmapper.standardRequest(
838 ['open-ils.actor', 'open-ils.actor.username.exists'],
840 params: [openils.User.authtoken, usrname],
841 oncomplete : function(r) {
842 var res = openils.Util.readResponse(r);
845 dojo.removeClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
848 dojo.addClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
858 case 'profile': // when the profile changes, update the expire date
859 dojo.connect(widget.widget, 'onChange',
862 var expireWidget = findWidget('au', 'expire_date');
863 function found(items) {
864 if(items.length == 0) return;
866 var interval = self.store.getValue(item, 'perm_interval');
867 expireWidget.widget.attr('value', dojo.date.add(new Date(),
868 'second', openils.Util.intervalToSeconds(interval)));
870 this.store.fetch({onComplete:found, query:{id:this.attr('value')}});
876 dojo.connect(widget.widget, 'onChange',
879 var oldDob = patron.dob();
880 if(dojo.date.stamp.fromISOString(oldDob) == newDob) return;
882 var juvInterval = orgSettings['global.juvenile_age_threshold'] || '18 years';
883 var juvWidget = findWidget('au', 'juvenile');
884 var base = new Date();
885 base.setTime(base.getTime() - Number(openils.Util.intervalToSeconds(juvInterval) + '000'));
887 if(newDob <= base) // older than global.juvenile_age_threshold
888 juvWidget.widget.attr('value', false);
890 juvWidget.widget.attr('value', true);
895 case 'first_given_name':
897 dojo.connect(widget.widget, 'onChange',
898 function(newVal) { uEditDupeSearch('name', newVal); });
902 dojo.connect(widget.widget, 'onChange',
903 function(newVal) { uEditDupeSearch('email', newVal); });
908 dojo.connect(widget.widget, 'onChange',
909 function(newVal) { uEditDupeSearch('ident', newVal); });
913 // if configured, use the last for digits of the day phone number as the password
914 if(uEditUsePhonePw && patron.isnew()) {
915 dojo.connect(widget.widget, 'onChange',
917 if(newVal && newVal.length >= 4) {
918 var pw1 = findWidget('au', 'passwd').widget;
919 var pw2 = findWidget('au', 'passwd2').widget;
920 pw1.attr('value', newVal.substring(newVal.length - 4));
921 pw2.attr('value', newVal.substring(newVal.length - 4));
926 case 'evening_phone':
928 dojo.connect(widget.widget, 'onChange',
929 function(newVal) { uEditDupeSearch('phone', newVal); });
933 dojo.connect(widget.widget, 'onChange',
935 checkClaimsReturnCountPerm();
936 checkClaimsNoCheckoutCountPerm();
942 dojo.connect(widget.widget, 'onChange',
944 var pw1 = findWidget('au', 'passwd').widget;
945 var pw2 = findWidget('au', 'passwd2').widget;
946 var preserved_value = pw2.attr('value');
947 // Ensure that the pw2 field match the pw1 field to validate
948 pw2.regExp = newVal.replace(/([.\\^$*+?\(\)\[\]\{\}])/g, '\\$1');
950 pw2.attr('value',preserved_value);
956 if(fmclass = 'aua') {
959 dojo.connect(widget.widget, 'onChange',
961 fieldmapper.standardRequest(
962 ['open-ils.search', 'open-ils.search.zip'],
965 oncomplete : function(r) {
966 var res = openils.Util.readResponse(r);
968 var callback = function(w) { return w._addr == widget._addr; };
969 if(res.city) findWidget('aua', 'city', callback).widget.attr('value', res.city);
970 if(res.state) findWidget('aua', 'state', callback).widget.attr('value', res.state);
971 if(res.county) findWidget('aua', 'county', callback).widget.attr('value', res.county);
972 if(res.alert) alert(res.alert);
983 dojo.connect(widget.widget, 'onChange',
985 var callback = function(w) { return w._addr == widget._addr; };
987 street1 : findWidget('aua', 'street1', callback).widget.attr('value'),
988 street2 : findWidget('aua', 'street2', callback).widget.attr('value'),
989 city : findWidget('aua', 'city', callback).widget.attr('value'),
990 post_code : findWidget('aua', 'post_code', callback).widget.attr('value')
992 if(args.street1 && args.city && args.post_code)
993 uEditDupeSearch('address', args);
1001 function uEditDupeSearch(type, value) {
1007 openils.Util.hide('uedit-dupe-names-link');
1008 var fname = findWidget('au', 'first_given_name').widget.attr('value');
1009 var lname = findWidget('au', 'family_name').widget.attr('value');
1010 if( !(fname && lname) ) return;
1012 first_given_name : {value : fname, group : 0},
1013 family_name : {value : lname, group : 0},
1018 openils.Util.hide('uedit-dupe-email-link');
1019 search = {email : {value : value, group : 0}};
1023 openils.Util.hide('uedit-dupe-ident-link');
1024 search = {ident : {value : value, group : 2}};
1028 openils.Util.hide('uedit-dupe-phone-link');
1029 search = {phone : {value : value, group : 2}};
1033 openils.Util.hide('uedit-dupe-address-link');
1035 dojo.forEach(['street1', 'street2', 'city', 'post_code'],
1038 search[field] = {value : value[field], group: 1};
1044 // find possible duplicate patrons
1045 fieldmapper.standardRequest(
1046 ['open-ils.actor', 'open-ils.actor.patron.search.advanced'],
1048 params: [openils.User.authtoken, search],
1049 oncomplete : function(r) {
1050 var resp = openils.Util.readResponse(r);
1051 resp = resp.filter(function(id) { return (id != patron.id()); });
1053 if(resp && resp.length > 0) {
1055 openils.Util.hide('uedit-help-div');
1056 openils.Util.show('uedit-dupe-div');
1061 link = dojo.byId('uedit-dupe-names-link');
1062 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_NAME, [resp.length]);
1065 link = dojo.byId('uedit-dupe-email-link');
1066 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_EMAIL, [resp.length]);
1069 link = dojo.byId('uedit-dupe-ident-link');
1070 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_IDENT, [resp.length]);
1073 link = dojo.byId('uedit-dupe-phone-link');
1074 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_PHONE, [resp.length]);
1077 link = dojo.byId('uedit-dupe-address-link');
1078 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_ADDR, [resp.length]);
1082 openils.Util.show(link);
1083 link.onclick = function() {
1084 search.search_sort = js2JSON(["penalties", "family_name", "first_given_name"]);
1086 window.xulG.spawn_search(search);
1088 console.log("running XUL patron search " + js2JSON(search));
1096 function getByName(node, name) {
1097 return dojo.query('[name='+name+']', node)[0];
1101 function ueLoadContextHelp(fmcls, fmfield) {
1102 openils.Util.hide('uedit-dupe-div');
1103 openils.Util.show('uedit-help-div');
1104 dojo.byId('uedit-help-field').innerHTML = fieldmapper.IDL.fmclasses[fmcls].field_map[fmfield].label;
1105 dojo.byId('uedit-help-text').innerHTML = fieldDoc[fmcls][fmfield].string();
1109 /* creates a new patron object with card attached */
1110 function uEditNewPatron() {
1115 card.id(uEditCardVirtId--);
1119 patron.cards([card]);
1120 patron.net_access_level(orgSettings['ui.patron.default_inet_access_level'] || 1);
1121 patron.ident_type(orgSettings['ui.patron.default_ident_type']);
1122 patron.stat_cat_entries([]);
1123 patron.survey_responses([]);
1124 patron.addresses([]);
1125 uEditMakeRandomPw(patron);
1129 function uEditMakeRandomPw(patron) {
1130 if(uEditUsePhonePw) return;
1131 var rand = Math.random();
1132 rand = parseInt(rand * 10000) + '';
1133 while(rand.length < 4) rand += '0';
1135 appendClear($('ue_password_plain'),text(rand));
1136 unHideMe($('ue_password_gen'));
1138 patron.passwd(rand);
1142 function uEditWidgetVal(w) {
1143 var val = (w.getFormattedValue) ? w.getFormattedValue() : w.attr('value');
1144 if(val === '') val = null;
1148 function uEditSave() { _uEditSave(); }
1149 function uEditSaveClone() { _uEditSave(true); }
1151 function _uEditSave(doClone) {
1153 if ( (! myForm.isValid()) || dupeUsrname || dupeBarcode ) {
1154 alert(localeStrings.INVALID_FORM);
1158 for(var idx in widgetPile) {
1159 var w = widgetPile[idx];
1160 var val = uEditWidgetVal(w);
1164 if(w._fmfield != 'passwd2')
1165 patron[w._fmfield](val);
1169 patron.card()[w._fmfield](val);
1173 var addr = patron.addresses().filter(function(i){return (i.id() == w._addr)})[0];
1175 addr = new fieldmapper.aua();
1178 addr.usr(patron.id());
1179 addr.country(orgSettings['ui.patron.default_country']);
1180 var t = patron.addresses();
1183 patron.addresses(t);
1185 if(addr[w._fmfield]() != val)
1188 addr[w._fmfield](val);
1190 if(dojo.byId('uedit-billing-address-' + addr.id()).checked)
1191 patron.billing_address(addr.id());
1193 if(dojo.byId('uedit-mailing-address-' + addr.id()).checked)
1194 patron.mailing_address(addr.id());
1199 if(val == null) break;
1200 var resp = new fieldmapper.asvr();
1202 resp.survey(w._survey)
1203 resp.usr(patron.id());
1204 resp.question(w._question)
1206 var t = patron.survey_responses();
1209 patron.survey_responses(t);
1213 if(val == null) break;
1215 var map = patron.stat_cat_entries().filter(
1217 return (m.stat_cat() == w._statcat) })[0];
1220 if(map.stat_cat_entry() == val)
1224 map = new fieldmapper.actscecm();
1228 map.stat_cat(w._statcat);
1229 map.stat_cat_entry(val);
1230 map.target_usr(patron.id());
1231 var t = patron.stat_cat_entries();
1234 patron.stat_cat_entries(t);
1239 patron.ischanged(1);
1240 fieldmapper.standardRequest(
1241 ['open-ils.actor', 'open-ils.actor.patron.update'],
1243 params: [openils.User.authtoken, patron],
1244 oncomplete: function(r) {
1246 if (xulG && typeof xulG.unlock_tab == 'function') {
1248 already_locked = false;
1250 newPatron = openils.Util.readResponse(r);
1252 uEditUpdateUserSettings(newPatron.id());
1253 if(stageUser) uEditRemoveStage();
1254 uEditFinishSave(newPatron, doClone);
1261 function uEditRemoveStage() {
1262 var resp = fieldmapper.standardRequest(
1263 ['open-ils.actor', 'open-ils.actor.user.stage.delete'],
1264 { params : [openils.User.authtoken, stageUser.row_id()] }
1268 function uEditFinishSave(newPatron, doClone) {
1270 if(doClone && cloneUser == null)
1271 cloneUser = newPatron.id();
1275 if(xulG && typeof xulG.spawn_editor == 'function' && !patron.isnew() ) {
1276 window.xulG.spawn_editor({ses:openils.User.authtoken,clone:cloneUser});
1280 location.href = location.href.replace(/\?.*/, '') + '?clone=' + cloneUser;
1288 uEditRefreshXUL(newPatron);
1291 function uEditRefresh() {
1292 var usr = cgi.param('usr');
1293 var href = location.href.replace(/\?.*/, '');
1294 href += ((usr) ? '?usr=' + usr : '');
1295 location.href = href;
1298 function uEditRefreshXUL(newuser) {
1299 if (window.xulG && typeof window.xulG.on_save == 'function')
1300 window.xulG.on_save(newuser);
1305 * Create a new address and insert it into the DOM
1306 * @param evt ignored
1307 * @param id The address id
1308 * @param mkLinks If true, set the new address as the
1309 * mailing/billing address for the user
1311 function uEditNewAddr(evt, id, mkLinks) {
1314 id = --uEditAddrVirtId; // new address
1316 var addr = patron.addresses().filter(
1317 function(i) { return (i.id() == id) })[0];
1319 dojo.forEach(addrTemplateRows,
1322 row = tbody.insertBefore(row.cloneNode(true), dojo.byId('new-addr-row'));
1323 row.setAttribute('type', '');
1324 row.setAttribute('addr', id+'');
1326 if(row.getAttribute('fmclass')) {
1327 var widget = fleshFMRow(row, 'aua', {addr:id});
1329 // make new addresses a default address type
1330 if(id < 0 && row.getAttribute('fmfield') == 'address_type')
1331 widget.widget.attr('value', localeStrings.DEFAULT_ADDRESS_TYPE);
1333 // make new addresses valid by default
1334 if(id < 0 && row.getAttribute('fmfield') == 'valid')
1335 widget.widget.attr('value', true);
1337 // make new addresses use the org setting for default country
1338 if(id < 0 && row.getAttribute('fmfield') == 'country')
1339 widget.widget.attr('value',orgSettings['ui.patron.default_country']);
1341 } else if(row.getAttribute('name') == 'uedit-addr-pending-row') {
1343 // if it's a pending address, show the 'approve' button
1344 if(addr && openils.Util.isTrue(addr.pending())) {
1345 openils.Util.show(row, 'table-row');
1346 dojo.query('[name=approve-button]', row)[0].onclick =
1347 function() { uEditApproveAddress(addr); };
1349 if(addr.replaces()) {
1350 var div = dojo.query('[name=replaced-addr]', row)[0]
1351 var replaced = patron.addresses().filter(
1352 function(i) { return (i.id() == addr.replaces()) })[0];
1354 div.innerHTML = dojo.string.substitute(localeStrings.REPLACED_ADDRESS, [
1355 replaced.address_type() || '',
1356 replaced.street1() || '',
1357 replaced.street2() || '',
1358 replaced.city() || '',
1359 replaced.state() || '',
1360 replaced.post_code() || ''
1364 openils.Util.hide(dojo.query('[name=replaced-addr-div]', row)[0]);
1368 } else if(row.getAttribute('name') == 'uedit-addr-owner-row') {
1369 // address is owned by someone else. provide option to load the
1370 // user in a different tab
1372 if(addr && addr.usr() != patron.id()) {
1373 openils.Util.show(row, 'table-row');
1374 var link = getByName(row, 'addr-owner');
1376 // fetch the linked user so we can present their name in the UI
1378 if(cloneUserObj && cloneUserObj.id() == addr.usr()) {
1380 cloneUserObj.first_given_name(),
1381 cloneUserObj.second_given_name(),
1382 cloneUserObj.family_name()
1385 addrUser = fieldmapper.standardRequest(
1386 ['open-ils.actor', 'open-ils.actor.user.retrieve.parts'],
1388 openils.User.authtoken,
1390 ['first_given_name', 'second_given_name', 'family_name']
1395 link.innerHTML = (addrUser.map(function(name) { return (name) ? name+' ' : '' })+'').replace(/,/g,''); // TODO i18n
1396 link.onclick = function() {
1397 if(openils.XUL.isXUL()) {
1398 window.xulG.spawn_editor({ses:openils.User.authtoken, usr:addr.usr()})
1400 parent.location.href = location.href.replace(/clone=\d+/, 'usr=' + addr.usr());
1405 } else if(row.getAttribute('name') == 'uedit-addr-divider') {
1406 // link up the billing/mailing address and give the inputs IDs so we can acces the later
1409 var ba = getByName(row, 'billing_address');
1410 ba.id = 'uedit-billing-address-' + id;
1411 if(mkLinks || (patron.billing_address() && patron.billing_address().id() == id))
1415 var ma = getByName(row, 'mailing_address');
1416 ma.id = 'uedit-mailing-address-' + id;
1417 if(mkLinks || (patron.mailing_address() && patron.mailing_address().id() == id))
1420 var btn = dojo.query('[name=delete-button]', row)[0];
1421 if(btn) btn.onclick = function(){ uEditDeleteAddr(id) };
1427 function uEditApproveAddress(addr) {
1428 fieldmapper.standardRequest(
1429 ['open-ils.actor', 'open-ils.actor.user.pending_address.approve'],
1431 params: [openils.User.authtoken, addr],
1433 oncomplete : function(r) {
1434 var oldId = openils.Util.readResponse(r);
1436 // remove addrs from UI
1439 function(addr) { uEditDeleteAddr(addr.id(), true); }
1444 // remove the replaced address
1445 if(oldId != addr.id()) {
1447 patron.addresses().filter(
1448 function(i) { return (i.id() != oldId); }
1453 // fix the the new address
1455 addr.replaces(null);
1468 function uEditDeleteAddr(id, noAlert) {
1469 if (patron.isnew() && orgSettings['ui.patron.registration.require_address']) {
1470 if (dojo.query('tr[name=uedit-addr-divider]').length < 2) {
1471 alert(localeStrings.NEED_ADDRESS);
1476 if(!confirm(dojo.string.substitute(localeStrings.DELETE_ADDRESS, [id]))) return;
1478 var addr = patron.addresses().filter(function(i){return (i.id() == id)})[0];
1479 if (addr) { addr.isdeleted(1); }
1480 var m_a = patron.mailing_address();
1481 if (typeof m_a == 'object' && m_a != null) { m_a = m_a.id(); }
1482 if (m_a == id) { patron.mailing_address(null); }
1483 var b_a = patron.billing_address();
1484 if (typeof b_a == 'object' && b_a != null) { b_a = b_a.id(); }
1485 if (b_a == id) { patron.billing_address(null); }
1487 var rows = dojo.query('tr[addr='+id+']', tbody);
1488 for(var i = 0; i < rows.length; i++)
1489 rows[i].parentNode.removeChild(rows[i]);
1490 widgetPile = widgetPile.filter(function(w){return (w._addr != id)});
1493 function uEditToggleRequired() {
1494 if((tbody.className +'').match(/hide-non-required/))
1495 openils.Util.removeCSSClass(tbody, 'hide-non-required');
1497 openils.Util.addCSSClass(tbody, 'hide-non-required');
1498 openils.Util.toggle('uedit-show-required');
1499 openils.Util.toggle('uedit-show-all');
1502 function printable_output() {
1503 var temp; var s = '=-=-=-=\r\n';
1504 for (var idx in widgetPile) {
1505 var w = widgetPile[idx];
1506 var val = uEditWidgetVal(w);
1508 if (typeof w.idlField == 'undefined') {
1510 if (w._wtype == 'statcat') {
1511 var stat = statCats.filter(
1513 return (m.id() == w._statcat) })[0];
1514 label = stat.name();
1515 } else if (w._wtype == 'survey') {
1516 var survey = surveys.filter(
1518 return (m.id() == w._survey) })[0];
1519 var question = survey.questions().filter(
1521 return (m.id() == w._question) })[0];
1522 label = survey.name() + ' : ' + question.question();
1527 label = w.idlField.label;
1529 if (temp != w._wtype) {
1533 s += label + ':\t' + (typeof val == 'object' ? '' : val) + '\r\n';
1539 openils.Util.addOnLoad(load);