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
52 var dupeUsrname = false;
53 var dupeBarcode = false;
55 if(!window.xulG) var xulG = null;
56 var lock_ready = false;
57 var already_locked = false;
60 staff = new openils.User().user;
61 pcrud = new openils.PermaCrud();
62 cgi = new openils.CGI();
63 cloneUser = cgi.param('clone');
64 var userId = cgi.param('usr');
65 var stageUname = cgi.param('stage');
67 saveButton.attr("label", localeStrings.SAVE);
68 saveCloneButton.attr("label", localeStrings.SAVE_CLONE);
69 replaceBarcode.attr("label", localeStrings.REPLACE_BARCODE);
70 dojo.byId('uedit-show-required').innerHTML = localeStrings.SHOW_REQUIRED;
71 dojo.byId('uedit-show-suggested').innerHTML = localeStrings.SHOW_SUGGESTED;
72 dojo.byId('uedit-show-all').innerHTML = localeStrings.SHOW_ALL;
73 dojo.byId('uedit-dupe-barcode-warning').innerHTML = localeStrings.BARCODE_IN_USE;
74 allCards.attr("label", localeStrings.SEE_ALL);
75 dojo.byId('uedit-dupe-username-warning').innerHTML = localeStrings.DUPE_USERNAME;
76 generatePassword.attr("label", localeStrings.RESET_PASSWORD);
77 dojo.byId('verifyPassword').innerHTML = localeStrings.VERIFY_PASSWORD;
78 dojo.byId('parentGuardian').innerHTML = localeStrings.PARENT_OR_GUARDIAN;
79 dojo.byId('userSettings').innerHTML = localeStrings.USER_SETTINGS;
80 dojo.byId('statCats').innerHTML = localeStrings.STAT_CATS;
81 dojo.byId('uedit-all-cards-barcode').innerHTML = localeStrings.ALL_CARDS_BARCODE;
82 dojo.byId('uedit-all-cards-active').innerHTML = localeStrings.ALL_CARDS_ACTIVE;
83 dojo.byId('uedit-all-cards-primary').innerHTML = localeStrings.ALL_CARDS_PRIMARY;
84 allCardsClose.attr("label", localeStrings.ALL_CARDS_CLOSE);
85 allCardsApply.attr("label", localeStrings.ALL_CARDS_APPLY);
87 dojo.query("td[name='addressHeader']").forEach( function(item) { item.innerHTML = localeStrings.ADDRESS_HEADER; });
88 dojo.query("span[name='mailingAddress']").forEach( function(item) { item.innerHTML = localeStrings.ADDRESS_MAILING; });
89 dojo.query("span[name='billingAddress']").forEach( function(item) { item.innerHTML = localeStrings.ADDRESS_BILLING; });
90 dojo.query("span[name='addressPending']").forEach( function(item) { item.innerHTML = localeStrings.ADDRESS_PENDING; });
91 dojo.query("button[name='approve-button']").forEach( function(item) { item.innerHTML = localeStrings.ADDRESS_APPROVE; });
92 dojo.query("span[name='address-already-owned']").forEach( function(item) { item.innerHTML = localeStrings.ADDRESS_OWNED; });
93 dojo.query("button[name='addressNew']").forEach( function(item) { item.innerHTML = localeStrings.ADDRESS_NEW; });
96 if(xulG.ses) openils.User.authtoken = xulG.ses;
97 if(typeof xulG.clone != 'undefined') cloneUser = xulG.clone;
98 if(typeof xulG.usr != 'undefined') userId = xulG.usr
99 if(typeof xulG.params != 'undefined') {
100 var parms = xulG.params;
101 if(typeof parms.ses != 'undefined')
102 openils.User.authtoken = parms.ses;
103 if(typeof parms.clone != 'undefined')
104 cloneUser = parms.clone;
105 if(typeof parms.usr != 'undefined')
107 if(typeof parms.stage != 'undefined')
108 stageUname = parms.stage
112 orgSettings = fieldmapper.aou.fetchOrgSettingBatch(staff.ws_ou(), [
113 'global.password_regex',
114 'global.juvenile_age_threshold',
115 'patron.password.use_phone',
116 'ui.patron.default_inet_access_level',
117 'ui.patron.default_ident_type',
118 'ui.patron.default_country',
119 'ui.patron.registration.require_address',
120 'circ.holds.behind_desk_pickup_supported',
121 'circ.patron_edit.clone.copy_address',
122 'ui.patron.edit.au.second_given_name.show',
123 'ui.patron.edit.au.second_given_name.suggest',
124 'ui.patron.edit.au.suffix.show',
125 'ui.patron.edit.au.suffix.suggest',
126 'ui.patron.edit.au.alias.show',
127 'ui.patron.edit.au.alias.suggest',
128 'ui.patron.edit.au.dob.require',
129 'ui.patron.edit.au.dob.show',
130 'ui.patron.edit.au.dob.suggest',
131 'ui.patron.edit.au.dob.calendar',
132 'ui.patron.edit.au.juvenile.show',
133 'ui.patron.edit.au.juvenile.suggest',
134 'ui.patron.edit.au.ident_value.show',
135 'ui.patron.edit.au.ident_value.suggest',
136 'ui.patron.edit.au.ident_value2.show',
137 'ui.patron.edit.au.ident_value2.suggest',
138 'ui.patron.edit.au.email.require',
139 'ui.patron.edit.au.email.show',
140 'ui.patron.edit.au.email.suggest',
141 'ui.patron.edit.au.email.regex',
142 'ui.patron.edit.au.email.example',
143 'ui.patron.edit.au.day_phone.require',
144 'ui.patron.edit.au.day_phone.show',
145 'ui.patron.edit.au.day_phone.suggest',
146 'ui.patron.edit.au.day_phone.regex',
147 'ui.patron.edit.au.day_phone.example',
148 'ui.patron.edit.au.evening_phone.require',
149 'ui.patron.edit.au.evening_phone.show',
150 'ui.patron.edit.au.evening_phone.suggest',
151 'ui.patron.edit.au.evening_phone.regex',
152 'ui.patron.edit.au.evening_phone.example',
153 'ui.patron.edit.au.other_phone.require',
154 'ui.patron.edit.au.other_phone.show',
155 'ui.patron.edit.au.other_phone.suggest',
156 'ui.patron.edit.au.other_phone.regex',
157 'ui.patron.edit.au.other_phone.example',
158 'ui.patron.edit.phone.regex',
159 'ui.patron.edit.phone.example',
160 'ui.patron.edit.au.active.show',
161 'ui.patron.edit.au.active.suggest',
162 'ui.patron.edit.au.barred.show',
163 'ui.patron.edit.au.barred.suggest',
164 'ui.patron.edit.au.master_account.show',
165 'ui.patron.edit.au.master_account.suggest',
166 'ui.patron.edit.au.claims_returned_count.show',
167 'ui.patron.edit.au.claims_returned_count.suggest',
168 'ui.patron.edit.au.claims_never_checked_out_count.show',
169 'ui.patron.edit.au.claims_never_checked_out_count.suggest',
170 'ui.patron.edit.au.alert_message.show',
171 'ui.patron.edit.au.alert_message.suggest',
172 'ui.patron.edit.aua.post_code.regex',
173 'ui.patron.edit.aua.post_code.example',
174 'ui.patron.edit.aua.county.require',
176 'ui.patron.edit.default_suggested',
177 'opac.barcode_regex',
178 'opac.username_regex'
181 for(k in orgSettings)
183 orgSettings[k] = orgSettings[k].value;
185 uEditCloneCopyAddr = orgSettings['circ.patron_edit.clone.copy_address'];
186 uEditUsePhonePw = orgSettings['patron.password.use_phone'];
187 uEditFetchUserSettings(userId);
190 patron = uEditLoadUser(userId);
193 patron = uEditLoadStageUser(stageUname);
195 patron = uEditNewPatron();
197 uEditCopyCloneData(patron);
202 var list = pcrud.search('fdoc', {fm_class:fmClasses});
205 if(!fieldDoc[doc.fm_class()])
206 fieldDoc[doc.fm_class()] = {};
207 fieldDoc[doc.fm_class()][doc.field()] = doc;
210 list = pcrud.search('aout', {can_have_users: 'true'});
213 homeOuTypes[type.id()] = true;
216 tbody = dojo.byId('uedit-tbody');
218 if(orgSettings['ui.patron.edit.default_suggested'])
219 uEditToggleRequired(2);
221 addrTemplateRows = dojo.query('tr[type=addr-template]', tbody);
222 dojo.forEach(addrTemplateRows, function(row) { row.parentNode.removeChild(row); } );
223 statCatTemplate = tbody.removeChild(dojo.byId('stat-cat-row-template'));
224 surveyTemplate = tbody.removeChild(dojo.byId('survey-row-template'));
225 surveyQuestionTemplate = tbody.removeChild(dojo.byId('survey-question-row-template'));
227 checkGrpAppPerm(); // to do the initial load
231 if(patron.isnew() && patron.addresses().length == 0)
232 uEditNewAddr(null, uEditAddrVirtId, true);
236 checkClaimsReturnCountPerm();
237 checkClaimsNoCheckoutCountPerm();
239 dojo.connect(replaceBarcode, 'onClick', replaceCardHandler);
240 dojo.connect(allCards, 'onClick', drawAllCards);
242 dojo.addClass(dojo.byId('uedit-all-barcodes'), 'hidden');
244 new openils.User().getPermOrgList(
245 'UPDATE_PATRON_ACTIVE_CARD',
247 if(orgList.indexOf(patron.home_ou()) != -1)
248 cardPerms['UPDATE_PATRON_ACTIVE_CARD'] = true;
253 new openils.User().getPermOrgList(
254 'UPDATE_PATRON_PRIMARY_CARD',
256 if(orgList.indexOf(patron.home_ou()) != -1)
257 cardPerms['UPDATE_PATRON_PRIMARY_CARD'] = true;
264 var input = findWidget('ac', 'barcode');
265 if (patron.isnew()) {
266 replaceBarcode.attr('disabled', true);
268 input.widget.attr('disabled', true).attr('readOnly', true);
271 dojo.connect(generatePassword, 'onClick', generatePasswordHandler);
273 if(!patron.isnew() && !checkGrpAppPerm(patron.profile()) && patron.id() != openils.User.user.id()) {
274 // we are not allowed to edit this user, so disable the save option
275 saveButton.attr('disabled', true);
276 saveCloneButton.attr('disabled', true);
283 var noPermGroups = [];
284 // Returns true if the user is allowed to edit the selected group
285 function checkGrpAppPerm(grpId) {
290 permGroups = new openils.PermaCrud().retrieveAll('pgt');
291 var permGroupPerms = []
293 // collect the group permissions
294 dojo.forEach(permGroups,
296 if(grp.application_perm())
297 permGroupPerms.push(grp.application_perm());
301 // see which of the group application perms I do not have
302 var myPerms = fieldmapper.standardRequest(
303 ['open-ils.actor', 'open-ils.actor.user.has_work_perm_at.batch'],
304 [openils.User.authtoken, permGroupPerms]
307 var failedPerms = [];
308 for(var p in myPerms) {
309 if(myPerms[p].length == 0)
313 // identify which groups I cannot edit because I do not have permisssion
315 function checkTree(grp, failed) {
316 failed = failed || failedPerms.indexOf(grp.application_perm()) > -1;
317 if(failed) noPermGroups.push(grp.id()+'');
319 permGroups.filter(function(g) { return g.parent() == grp.id() } ),
321 checkTree(child, failed);
326 checkTree(permGroups.filter(function(g) { return g.parent() == null })[0]);
329 return noPermGroups.indexOf(grpId+'') == -1;
333 function drawAllCards() {
335 var tbody = dojo.byId('uedit-all-cards-tbody');
336 if(!allCardsTemplate) {
337 allCardsTemplate = tbody.removeChild(dojo.byId('uedit-all-cards-tr-template'));
339 while(tbody.childNodes[0])
340 tbody.removeChild(tbody.childNodes[0]);
343 if(cardPerms['UPDATE_PATRON_ACTIVE_CARD'] || cardPerms['UPDATE_PATRON_PRIMARY_CARD']) {
344 dojo.removeClass(dojo.byId('uedit-apply-card-changes'), 'hidden');
346 dojo.addClass(dojo.byId('uedit-apply-card-changes'), 'hidden');
351 patron.cards().filter(function(c) { return c.id() == patron.card().id(); }).concat(patron.cards()), // grab the main card first
354 if(card.id() == patron.card().id())
357 var row = allCardsTemplate.cloneNode(true);
358 row.setAttribute("cardid", card.id());
360 getByName(row, 'barcode').innerHTML = card.barcode();
361 if(cardPerms['UPDATE_PATRON_ACTIVE_CARD']) {
362 row.active_checkbox = new dijit.form.CheckBox({
364 checked: openils.Util.isTrue(card.active())
365 }, getByName(row, 'active'));
367 getByName(row, 'active').appendChild(
368 openils.Util.isTrue(card.active()) ?
369 dojo.byId('true').cloneNode(true) :
370 dojo.byId('false').cloneNode(true)
373 if(cardPerms['UPDATE_PATRON_PRIMARY_CARD']) {
374 row.primary_radiobutton = new dijit.form.RadioButton({
376 checked: card.id() == patron.card().id(),
379 }, getByName(row, 'primary'));
381 getByName(row, 'primary').appendChild(
382 openils.Util.isTrue(card.id() == patron.card().id()) ?
383 dojo.byId('true').cloneNode(true) :
384 dojo.byId('false').cloneNode(true)
387 tbody.appendChild(row);
392 allCardsDialog.show();
395 function applyCardChanges() {
396 var cardrows = dojo.query('[cardid]', allCardsDialog.domNode);
397 dojo.forEach(cardrows,
399 if(cardPerms['UPDATE_PATRON_ACTIVE_CARD']) {
400 var active = row.active_checkbox.checked ? 't' : 'f'
401 if(row.card.active() != active) {
402 row.card.active(active);
403 row.card.ischanged(1);
406 if(cardPerms['UPDATE_PATRON_PRIMARY_CARD']) {
407 if(row.primary_radiobutton.checked && row.card.id() != patron.card().id()) {
408 patron.card(row.card);
413 allCardsDialog.hide();
417 * Mark the current card inactive, create a new primary card
419 function replaceCardHandler() {
420 var input = findWidget('ac', 'barcode');
421 input.widget.attr('disabled', false).attr('readOnly', false).attr('value', null).focus();
422 replaceBarcode.attr('disabled', true);
424 // pull old card off the cards list so we don't have a dupe sitting in there
425 if (patron.cards().length > 0) {
426 var old = patron.cards().filter(function(c){return (c.id() == patron.card().id())})[0];
431 var newc = new fieldmapper.ac();
432 newc.id(uEditCardVirtId--);
437 var t = patron.cards();
444 * Generate a random password for the patron.
446 function generatePasswordHandler() {
447 uEditMakeRandomPw(patron);
448 var f = findWidget('au', 'passwd');
449 f.widget.attr('value', patron.passwd());
450 f = findWidget('au', 'passwd2');
451 f.widget.attr('value', patron.passwd());
455 * Loads a staged user and turns them into something the editor can understand
457 function uEditLoadStageUser(stageUname) {
459 var data = fieldmapper.standardRequest(
460 ['open-ils.actor', 'open-ils.actor.user.stage.retrieve.by_username'],
461 { params : [openils.User.authtoken, stageUname] }
464 stageUser = data.user;
465 patron = uEditNewPatron();
470 // copy the data into our new user object
471 for(var key in fieldmapper.IDL.fmclasses.stgu.field_map) {
472 if(fieldmapper.IDL.fmclasses.au.field_map[key] && !fieldmapper.IDL.fmclasses.stgu.field_map[key].virtual) {
473 if(data.user[key]() !== null)
474 patron[key]( data.user[key]() );
478 // copy the data into our new address objects
479 // TODO: uses the first mailing address only
480 if(data.mailing_addresses.length) {
482 var mail_addr = new fieldmapper.aua();
483 mail_addr.id(-1); // virtual ID
486 patron.mailing_address(mail_addr);
487 var t = patron.addresses();
492 for(var key in fieldmapper.IDL.fmclasses.stgma.field_map) {
493 if(fieldmapper.IDL.fmclasses.aua.field_map[key] && !fieldmapper.IDL.fmclasses.stgma.field_map[key].virtual) {
494 if(data.mailing_addresses[0][key]() !== null)
495 mail_addr[key]( data.mailing_addresses[0][key]() );
500 // copy the data into our new address objects
501 // TODO uses the first billing address only
502 if(data.billing_addresses.length) {
504 var bill_addr = new fieldmapper.aua();
505 bill_addr.id(-2); // virtual ID
508 patron.billing_address(bill_addr);
509 var t = patron.addresses();
514 for(var key in fieldmapper.IDL.fmclasses.stgba.field_map) {
515 if(fieldmapper.IDL.fmclasses.aua.field_map[key] && !fieldmapper.IDL.fmclasses.stgba.field_map[key].virtual) {
516 if(data.billing_addresses[0][key]() !== null)
517 bill_addr[key]( data.billing_addresses[0][key]() );
522 // TODO: uses the first card only
523 if(data.cards.length) {
524 var card = new fieldmapper.ac();
525 card.id(-1); // virtual ID
526 patron.card().barcode(data.cards[0].barcode());
533 * clone the home org, phone numbers, and billing/mailing address
535 function uEditCopyCloneData(patron) {
536 cloneUserObj = uEditLoadUser(cloneUser);
546 if(!uEditCloneCopyAddr)
547 cloneFields = cloneFields.concat(['mailing_address', 'billing_address']);
552 patron[field](cloneUserObj[field]());
556 if(uEditCloneCopyAddr) {
557 var billAddr, mailAddr;
559 // copy the billing and mailing addresses into new addresses
560 function cloneAddr(addr) {
561 var newAddr = addr.clone();
563 newAddr.id(uEditAddrVirtId--);
564 newAddr.usr(patron.id());
565 patron.addresses().push(newAddr);
569 if(billAddr = cloneUserObj.billing_address())
570 patron.billing_address(cloneAddr(billAddr));
572 if(mailAddr = cloneUserObj.mailing_address()) {
573 if (billAddr && billAddr.id() == mailAddr.id()) {
574 patron.mailing_address(patron.billing_address());
576 patron.mailing_address(cloneAddr(mailAddr));
580 if(!billAddr) // if there was no billing addr, use the mailing addr
581 patron.billing_address(patron.mailing_address());
585 // link the billing and mailing addresses
586 if(patron.billing_address()) {
587 var t = patron.addresses();
589 t.push(patron.billing_address());
593 if(patron.mailing_address() && (
594 patron.addresses().length == 0 ||
595 patron.mailing_address().id() != patron.billing_address().id()) ) {
596 var t = patron.addresses();
598 t.push(patron.mailing_address());
605 function uEditFetchUserSettings(userId) {
607 var baseNode = fieldmapper.aou.findOrgUnit(staff.ws_ou());
608 var orgs = fieldmapper.aou.orgNodeTrail(baseNode);
609 orgs = orgs.map(function(node) { return node.id(); });
611 /* fetch any user setting types we need + any that offer opt-in */
612 userSettingTypes = pcrud.search('cust', {
614 {name:['circ.holds_behind_desk', 'circ.collections.exempt']},
617 select : {atevdef : ['opt_in_setting']},
619 // we only care about opt-in settings for event_defs our users encounter
620 where : {'+atevdef' : {owner : orgs}}
626 var names = userSettingTypes.map(function(obj) { return obj.name() });
628 /* fetch any values set for this user */
630 userSettings = fieldmapper.standardRequest(
631 ['open-ils.actor', 'open-ils.actor.patron.settings.retrieve.authoritative'],
632 {params : [openils.User.authtoken, userId, names]});
637 function uEditLoadUser(userId) {
638 var patron = fieldmapper.standardRequest(
639 ['open-ils.actor', 'open-ils.actor.user.fleshed.retrieve.authoritative'],
640 {params : [openils.User.authtoken, userId]}
642 openils.Event.parse_and_raise(patron);
646 function loadStaticFields() {
647 for(var idx = 0; tbody.childNodes[idx]; idx++) {
648 var row = tbody.childNodes[idx];
649 if(row.nodeType != row.ELEMENT_NODE) continue;
650 var fmcls = row.getAttribute('fmclass');
652 fleshFMRow(row, fmcls);
655 if(row.id == 'uedit-settings-divider') {
657 var template = tbody.removeChild(dojo.byId('uedit-user-setting-template'));
658 dojo.forEach(userSettingTypes, function(type) { uEditDrawSettingRow(tbody, row, template, type); } );
660 if(userSettingTypes.length > 1 || orgSettings['circ.holds.behind_desk_pickup_supported']) {
661 openils.Util.show('uedit-settings-divider', 'table-row');
668 function uEditDrawSettingRow(tbody, dividerRow, template, stype) {
669 var row = template.cloneNode(true);
670 row.setAttribute('user_setting', stype.name());
671 getByName(row, 'label').innerHTML = stype.label();
672 var cb = new dijit.form.CheckBox({scrollOnFocus:false}, getByName(row, 'widget'));
673 cb.attr('value', userSettings[stype.name()]);
674 dojo.connect(cb, 'onChange', function(newVal) { userSettingsToUpdate[stype.name()] = newVal; });
675 tbody.insertBefore(row, dividerRow.nextSibling);
676 openils.Util.show(row, 'table-row');
678 if(stype.name() == 'circ.collections.exempt') {
679 checkCollectionsExemptPerm(cb);
683 function uEditUpdateUserSettings(userId) {
684 return fieldmapper.standardRequest(
685 ['open-ils.actor', 'open-ils.actor.patron.settings.update'],
686 {params : [openils.User.authtoken, userId, userSettingsToUpdate]});
689 function loadAllAddrs() {
690 dojo.forEach(patron.addresses(),
692 uEditNewAddr(null, addr.id());
697 function loadStatCats() {
699 statCats = fieldmapper.standardRequest(
700 ['open-ils.circ', 'open-ils.circ.stat_cat.actor.retrieve.all'],
701 {params : [openils.User.authtoken, staff.ws_ou()]}
705 for(var idx in statCats) {
706 var stat = statCats[idx];
707 var row = statCatTemplate.cloneNode(true);
708 row.id = 'stat-cat-row-' + idx;
709 row.setAttribute('stat_cat_owner',stat.owner());
710 row.setAttribute('stat_cat_name',stat.name());
711 row.setAttribute('stat_cat_id',stat.id());
712 tbody.appendChild(row);
713 getByName(row, 'name').innerHTML = stat.name();
714 var valtd = getByName(row, 'widget');
715 var span = valtd.appendChild(document.createElement('span'));
716 var store = new dojo.data.ItemFileReadStore(
717 {data:fieldmapper.actsc.toStoreData(stat.entries())});
718 var comboBox = new dijit.form.ComboBox({store:store,scrollOnFocus:false,fetchProperties:{sort:[{attribute: 'value'}]}}, span);
719 comboBox.labelAttr = 'value';
720 comboBox.searchAttr = 'value';
722 comboBox._wtype = 'statcat';
723 comboBox._statcat = stat.id();
724 widgetPile.push(comboBox);
726 // populate existing cats
727 var map = patron.stat_cat_entries().filter(
728 function(mp) { return (mp.stat_cat() == stat.id()) })[0];
729 if(map) comboBox.attr('value', map.stat_cat_entry());
734 function loadSurveys() {
736 surveys = fieldmapper.standardRequest(
737 ['open-ils.circ', 'open-ils.circ.survey.retrieve.all'],
738 {params : [openils.User.authtoken]}
742 for(var idx in surveys) {
743 var survey = surveys[idx];
744 var required = openils.Util.isTrue(survey.required());
745 var srow = surveyTemplate.cloneNode(true);
746 if(required) srow.setAttribute('required','required');
747 tbody.appendChild(srow);
748 getByName(srow, 'name').innerHTML = survey.name();
750 for(var q in survey.questions()) {
751 var quest = survey.questions()[q];
752 var qrow = surveyQuestionTemplate.cloneNode(true);
753 if(required) qrow.setAttribute('required','required');
754 tbody.appendChild(qrow);
755 getByName(qrow, 'question').innerHTML = quest.question();
757 var span = getByName(qrow, 'answers').appendChild(document.createElement('span'));
758 var store = new dojo.data.ItemFileReadStore(
759 {data:fieldmapper.asva.toStoreData(quest.answers())});
760 var select = new dijit.form.FilteringSelect({store:store,scrollOnFocus:false}, span);
762 select.isValid = function() { return true; };
764 select.labelAttr = 'answer';
765 select.searchAttr = 'answer';
767 select._wtype = 'survey';
768 select._survey = survey.id();
769 select._question = quest.id();
770 widgetPile.push(select);
776 function fleshFMRow(row, fmcls, args) {
777 var fmfield = row.getAttribute('fmfield');
778 var wclass = row.getAttribute('wclass');
779 var wstyle = row.getAttribute('wstyle');
780 var wconstraints = row.getAttribute('wconstraints');
781 /* use CSS to set the zindex for widgets you want to disable. */
782 var disabled = dojo.style(row, 'zIndex') == -1 ? true : false;
783 var isphone = (fmcls == 'au') && (fmfield.search('_phone') != -1);
785 var isPasswd2 = (fmfield == 'passwd2');
786 if(isPasswd2) fmfield = 'passwd';
787 var fieldIdl = fieldmapper.IDL.fmclasses[fmcls].field_map[fmfield];
790 var existing = dojo.query('td', row);
791 var htd = existing[0] || row.appendChild(document.createElement('td'));
792 var ltd = existing[1] || row.appendChild(document.createElement('td'));
793 var wtd = existing[2] || row.appendChild(document.createElement('td'));
794 var ftd = existing[3] || row.appendChild(document.createElement('td'));
796 openils.Util.addCSSClass(htd, 'uedit-help');
797 if(fieldDoc[fmcls] && fieldDoc[fmcls][fmfield]) {
798 var link = dojo.byId('uedit-help-template').cloneNode(true);
800 link.onclick = function() { ueLoadContextHelp(fmcls, fmfield) };
801 openils.Util.removeCSSClass(link, 'hidden');
802 htd.appendChild(link);
805 if(!ltd.textContent) {
806 ltd.appendChild(document.createTextNode(fieldIdl.label));
809 if(!ftd.textContent) {
810 if(orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.example']) {
811 ftd.appendChild(document.createTextNode(localeStrings.EXAMPLE + orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.example']));
813 else if(isphone && orgSettings['ui.patron.edit.phone.example']) {
814 ftd.appendChild(document.createTextNode(localeStrings.EXAMPLE + orgSettings['ui.patron.edit.phone.example']));
816 else if(fieldIdl.datatype == 'timestamp') {
817 ftd.appendChild(document.createTextNode(localeStrings.EXAMPLE + dojo.date.locale.format(new Date(1970,0,31),{selector: "date", fullYear: true, datePattern: (orgSettings['format.date'] ? orgSettings['format.date'] : null)})));
821 var span = document.createElement('span');
822 wtd.appendChild(span);
826 case 'au' : fmObject = patron; break;
827 case 'ac' : if(!editCard) editCard = patron.card(); fmObject = editCard; break;
829 fmObject = patron.addresses().filter(
830 function(i) { return (i.id() == args.addr) })[0];
831 if(fmObject && fmObject.usr() != patron.id())
836 // Adjust required value by org settings
837 var curRequired = row.getAttribute('required');
838 var required = curRequired == 'required';
839 if(orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.require']) {
840 row.setAttribute('required', 'required');
843 else if (curRequired != 'required' && orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.show']) {
844 row.setAttribute('required', 'show');
846 else if (curRequired != 'required' && curRequired != 'show' && orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.suggest']) {
847 row.setAttribute('required', 'suggested');
850 // password data is not fetched/required/displayed for existing users
851 if(!patron.isnew() && 'passwd' == fmfield)
857 constraints : (wconstraints) ? eval('('+wconstraints+')') : {}, // the ()'s prevent Invalid Label errors with eval
861 // Org settings provided regex?
862 if(orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.regex']) {
863 dijitArgs.regExp = orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.regex'];
865 else if(isphone && orgSettings['ui.patron.edit.phone.regex']) {
866 dijitArgs.regExp = orgSettings['ui.patron.edit.phone.regex'];
869 if(fmcls == 'au' && fmfield == 'passwd') {
870 if (orgSettings['global.password_regex']) {
871 dijitArgs.regExp = orgSettings['global.password_regex'];
875 if(fmcls == 'au' && fmfield == 'dob' && !orgSettings['ui.patron.edit.au.dob.calendar'])
876 dijitArgs.popupClass = "";
878 var value = row.getAttribute('wvalue');
880 dijitArgs.value = value;
887 widgetClass : wclass,
888 dijitArgs : dijitArgs,
889 orgDefaultsToWs : true,
890 orgLimitPerms : ['UPDATE_USER'],
893 if(fmfield == 'profile') {
894 // fetch profile groups non-async so existing expire_date is
895 // not overwritten when the profile groups arrive and update
896 wargs.forceSync = true;
897 wargs.disableQuery = {usergroup : 'f'};
898 if(!patron.isnew() && !checkGrpAppPerm(patron.profile()))
899 wargs.readOnly = true;
901 wargs.forceSync = false;
904 if(fmcls == 'au' && fmfield == 'home_ou'){
905 wargs.labelAttr = 'name';
906 wargs.searchAttr = 'name';
909 var widget = new openils.widget.AutoFieldWidget(wargs);
912 if(fmfield == 'profile') { trimGrpTree(ww); }
916 // now put it back before we register the widget
917 if(isPasswd2) fmfield = 'passwd2';
919 widget._wtype = fmcls;
920 widget._fmfield = fmfield;
921 widget._addr = args.addr;
922 widgetPile.push(widget);
923 attachWidgetEvents(fmcls, fmfield, widget);
927 function trimGrpTree(autoWidget) {
928 var store = autoWidget.widget.store;
930 // remove all groups that this user are not allowed to edit,
931 // except the profile group of an existing user
932 store.fetch({onItem :
934 if(!checkGrpAppPerm(item.id[0]) && patron.profile() != item.id[0])
935 store.deleteItem(item);
940 function findWidget(wtype, fmfield, callback) {
941 return widgetPile.filter(
943 if(i._wtype == wtype && i._fmfield == fmfield) {
944 if(callback) return callback(i);
952 * if the user does not have the UPDATE_PATRON_CLAIM_RETURN_COUNT,
953 * they are not allowed to directly alter the claim return count.
954 * This function checks the perm and disable/enables the widget.
956 function checkClaimsReturnCountPerm() {
957 new openils.User().getPermOrgList(
958 'UPDATE_PATRON_CLAIM_RETURN_COUNT',
960 var cr = findWidget('au', 'claims_returned_count');
961 if(orgList.indexOf(patron.home_ou()) == -1)
962 cr.widget.attr('disabled', true);
964 cr.widget.attr('disabled', false);
972 function checkClaimsNoCheckoutCountPerm() {
973 new openils.User().getPermOrgList(
974 'UPDATE_PATRON_CLAIM_NEVER_CHECKED_OUT_COUNT',
976 var cr = findWidget('au', 'claims_never_checked_out_count');
977 if(orgList.indexOf(patron.home_ou()) == -1)
978 cr.widget.attr('disabled', true);
980 cr.widget.attr('disabled', false);
987 var collectExemptCBox;
988 function checkCollectionsExemptPerm(cbox) {
989 if(cbox) collectExemptCBox = cbox;
990 new openils.User().getPermOrgList(
991 'UPDATE_PATRON_COLLECTIONS_EXEMPT',
993 if(orgList.indexOf(patron.home_ou()) == -1)
994 collectExemptCBox.attr('disabled', true);
996 collectExemptCBox.attr('disabled', false);
1003 function usePhonePw(newVal) {
1006 matches = RegExp(this.regExp).exec(newVal);
1007 if(matches.length > 1) newPw = matches[1];
1009 if(!newPw && newVal && newVal.length >= 4) {
1010 newPw = newVal.substring(newVal.length - 4);
1013 var p1 = findWidget('au', 'passwd');
1014 var p2 = findWidget('au', 'passwd2');
1016 p1.widget.attr('value', newPw);
1017 p2.widget.attr('value', newPw);
1025 function attachWidgetEvents(fmcls, fmfield, widget) {
1031 netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
1032 if (!(ev.altKey || ev.ctrlKey || ev.metaKey)) {
1033 if (lock_ready && xulG && typeof xulG.lock_tab == 'function') {
1034 if (! already_locked) {
1036 already_locked = true;
1046 if (lock_ready && xulG && typeof xulG.lock_tab == 'function') {
1047 if (! already_locked) {
1049 already_locked = true;
1057 if(fmfield == 'barcode') {
1058 dojo.connect(widget.widget, 'onChange',
1060 var barcode = this.attr('value');
1061 dupeBarcode = false;
1062 dojo.addClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
1063 fieldmapper.standardRequest(
1064 ['open-ils.actor', 'open-ils.actor.barcode.exists'],
1066 params: [openils.User.authtoken, barcode],
1067 oncomplete : function(r) {
1068 var res = openils.Util.readResponse(r);
1071 dojo.removeClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
1073 dupeBarcode = false;
1074 dojo.addClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
1075 editCard.barcode(barcode); // Keep the "All" interface up to date
1076 var un = findWidget('au', 'usrname');
1077 if(!un.widget.attr('value'))
1078 un.widget.attr('value', barcode);
1093 widget.widget.isValid = function() {
1095 if(this.attr("value").match(/\s/)) {
1098 // Can look like a barcode (for initial value)
1099 if(orgSettings['opac.barcode_regex']) {
1100 var test_regexp = new RegExp(orgSettings['opac.barcode_regex']);
1101 if(test_regexp.test(this.attr("value"))) {
1105 // Can look like a username
1106 if(orgSettings['opac.username_regex']) {
1107 var test_regexp = new RegExp(orgSettings['opac.username_regex']);
1108 if(test_regexp.test(this.attr("value"))) {
1112 // If we know what a barcode and username look like and we got here, reject
1113 if(orgSettings['opac.barcode_regex'] && orgSettings['opac.username_regex'])
1115 // Otherwise we don't have enough info to say either way, let it through.
1118 dojo.connect(widget.widget, 'onChange',
1120 var input = findWidget('au', 'usrname');
1121 var usrname = input.widget.attr('value');
1124 dupeUsrname = false;
1125 dojo.addClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
1129 fieldmapper.standardRequest(
1130 ['open-ils.actor', 'open-ils.actor.username.exists'],
1132 params: [openils.User.authtoken, usrname],
1133 oncomplete : function(r) {
1134 var res = openils.Util.readResponse(r);
1137 dojo.removeClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
1139 dupeUsrname = false;
1140 dojo.addClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
1150 case 'profile': // when the profile changes, update the expire date
1151 dojo.connect(widget.widget, 'onChange',
1154 var expireWidget = findWidget('au', 'expire_date');
1155 function found(items) {
1156 if(items.length == 0) return;
1157 var item = items[0];
1158 var interval = self.store.getValue(item, 'perm_interval');
1159 expireWidget.widget.attr('value', dojo.date.add(new Date(),
1160 'second', openils.Util.intervalToSeconds(interval)));
1162 this.store.fetch({onComplete:found, query:{id:this.attr('value')}});
1168 widget.widget.isValid = function() {
1169 return this.attr("value") < new Date();
1171 dojo.connect(widget.widget, 'onChange',
1174 var oldDob = patron.dob();
1175 if(dojo.date.stamp.fromISOString(oldDob) == newDob) return;
1177 var juvInterval = orgSettings['global.juvenile_age_threshold'] || '18 years';
1178 var juvWidget = findWidget('au', 'juvenile');
1179 var base = new Date();
1180 base.setTime(base.getTime() - Number(openils.Util.intervalToSeconds(juvInterval) + '000'));
1182 if(newDob <= base) // older than global.juvenile_age_threshold
1183 juvWidget.widget.attr('value', false);
1185 juvWidget.widget.attr('value', true);
1190 case 'first_given_name':
1192 dojo.connect(widget.widget, 'onChange',
1193 function(newVal) { uEditDupeSearch('name', newVal); });
1197 dojo.connect(widget.widget, 'onChange',
1198 function(newVal) { uEditDupeSearch('email', newVal); });
1202 case 'ident_value2':
1203 dojo.connect(widget.widget, 'onChange',
1204 function(newVal) { uEditDupeSearch('ident', newVal); });
1208 // if configured, use the last four digits of the day phone number as the password
1209 // Alt, use the first capture group of the validator regex
1210 if(uEditUsePhonePw && patron.isnew()) {
1211 dojo.connect(widget.widget, 'onChange', widget.widget, usePhonePw);
1212 if (patron.day_phone()) {
1213 usePhonePw(patron.day_phone());
1216 case 'evening_phone':
1218 dojo.connect(widget.widget, 'onChange',
1219 function(newVal) { uEditDupeSearch('phone', newVal); });
1223 widget.widget.isValid = function() {
1225 if(homeOuTypes[this.store.getValue(this.item, 'ou_type')]) {
1232 dojo.connect(widget.widget, 'onChange',
1234 checkClaimsReturnCountPerm();
1235 checkClaimsNoCheckoutCountPerm();
1236 checkCollectionsExemptPerm();
1242 dojo.connect(widget.widget, 'onChange',
1244 var pw1 = findWidget('au', 'passwd').widget;
1245 var pw2 = findWidget('au', 'passwd2').widget;
1246 var preserved_value = pw2.attr('value');
1247 // Ensure that the pw2 field match the pw1 field to validate
1248 pw2.regExp = newVal.replace(/([.\\^$*+?\(\)\[\]\{\}])/g, '\\$1');
1250 pw2.attr('value',preserved_value);
1256 if(fmclass = 'aua') {
1259 dojo.connect(widget.widget, 'onChange',
1261 fieldmapper.standardRequest(
1262 ['open-ils.search', 'open-ils.search.zip'],
1265 oncomplete : function(r) {
1266 var res = openils.Util.readResponse(r);
1268 var callback = function(w) { return w._addr == widget._addr; };
1269 if(res.city) findWidget('aua', 'city', callback).widget.attr('value', res.city);
1270 if(res.state) findWidget('aua', 'state', callback).widget.attr('value', res.state);
1271 if(res.county) findWidget('aua', 'county', callback).widget.attr('value', res.county);
1272 if(res.alert) alert(res.alert);
1283 dojo.connect(widget.widget, 'onChange',
1285 var callback = function(w) { return w._addr == widget._addr; };
1287 street1 : findWidget('aua', 'street1', callback).widget.attr('value'),
1288 street2 : findWidget('aua', 'street2', callback).widget.attr('value'),
1289 city : findWidget('aua', 'city', callback).widget.attr('value'),
1290 post_code : findWidget('aua', 'post_code', callback).widget.attr('value')
1292 if(args.street1 && args.city && args.post_code)
1293 uEditDupeSearch('address', args);
1301 function uEditDupeSearch(type, value) {
1307 openils.Util.hide('uedit-dupe-names-link');
1308 var fname = findWidget('au', 'first_given_name').widget.attr('value');
1309 var lname = findWidget('au', 'family_name').widget.attr('value');
1310 if( !(fname && lname) ) return;
1312 first_given_name : {value : fname, group : 0},
1313 family_name : {value : lname, group : 0},
1318 openils.Util.hide('uedit-dupe-email-link');
1319 search = {email : {value : value, group : 0}};
1323 openils.Util.hide('uedit-dupe-ident-link');
1324 search = {ident : {value : value, group : 2}};
1328 openils.Util.hide('uedit-dupe-phone-link');
1329 search = {phone : {value : value, group : 2}};
1333 openils.Util.hide('uedit-dupe-address-link');
1335 dojo.forEach(['street1', 'street2', 'city', 'post_code'],
1338 search[field] = {value : value[field], group: 1};
1344 // find possible duplicate patrons
1345 fieldmapper.standardRequest(
1346 ['open-ils.actor', 'open-ils.actor.patron.search.advanced'],
1348 params: [openils.User.authtoken, search],
1349 oncomplete : function(r) {
1350 var resp = openils.Util.readResponse(r);
1351 resp = resp.filter(function(id) { return (id != patron.id()); });
1353 if(resp && resp.length > 0) {
1355 openils.Util.hide('uedit-help-div');
1356 openils.Util.show('uedit-dupe-div');
1361 link = dojo.byId('uedit-dupe-names-link');
1362 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_NAME, [resp.length]);
1365 link = dojo.byId('uedit-dupe-email-link');
1366 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_EMAIL, [resp.length]);
1369 link = dojo.byId('uedit-dupe-ident-link');
1370 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_IDENT, [resp.length]);
1373 link = dojo.byId('uedit-dupe-phone-link');
1374 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_PHONE, [resp.length]);
1377 link = dojo.byId('uedit-dupe-address-link');
1378 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_ADDR, [resp.length]);
1382 openils.Util.show(link);
1383 link.onclick = function() {
1384 search.search_sort = js2JSON(["penalties", "family_name", "first_given_name"]);
1386 window.xulG.spawn_search(search);
1388 console.log("running XUL patron search " + js2JSON(search));
1396 function getByName(node, name) {
1397 return dojo.query('[name='+name+']', node)[0];
1401 function ueLoadContextHelp(fmcls, fmfield) {
1402 openils.Util.hide('uedit-dupe-div');
1403 openils.Util.show('uedit-help-div');
1404 dojo.byId('uedit-help-field').innerHTML = fieldmapper.IDL.fmclasses[fmcls].field_map[fmfield].label;
1405 dojo.byId('uedit-help-text').innerHTML = fieldDoc[fmcls][fmfield].string();
1409 /* creates a new patron object with card attached */
1410 function uEditNewPatron() {
1415 card.id(uEditCardVirtId--);
1419 patron.cards([card]);
1420 patron.net_access_level(orgSettings['ui.patron.default_inet_access_level'] || 1);
1421 patron.ident_type(orgSettings['ui.patron.default_ident_type']);
1422 patron.stat_cat_entries([]);
1423 patron.survey_responses([]);
1424 patron.addresses([]);
1425 uEditMakeRandomPw(patron);
1429 function uEditMakeRandomPw(patron) {
1430 var rand = Math.random();
1431 rand = parseInt(rand * 10000) + '';
1432 while(rand.length < 4) rand += '0';
1434 appendClear($('ue_password_plain'),text(rand));
1435 unHideMe($('ue_password_gen'));
1437 patron.passwd(rand);
1441 function uEditWidgetVal(w) {
1442 var val = (w.getFormattedValue) ? w.getFormattedValue() : w.attr('value');
1443 if(val === '') val = null;
1447 function uEditSave() { _uEditSave(); }
1448 function uEditSaveClone() { _uEditSave(true); }
1450 function _uEditSave(doClone) {
1452 if ( (! myForm.isValid()) || dupeUsrname || dupeBarcode ) {
1453 alert(localeStrings.INVALID_FORM);
1457 for(var idx in widgetPile) {
1458 var w = widgetPile[idx];
1459 var val = uEditWidgetVal(w);
1463 if(w._fmfield != 'passwd2')
1464 patron[w._fmfield](val);
1468 if(!editCard) editCard = patron.card();
1469 editCard[w._fmfield](val);
1473 var addr = patron.addresses().filter(function(i){return (i.id() == w._addr)})[0];
1475 addr = new fieldmapper.aua();
1478 addr.usr(patron.id());
1479 addr.country(orgSettings['ui.patron.default_country']);
1480 var t = patron.addresses();
1483 patron.addresses(t);
1485 if(addr[w._fmfield]() != val)
1488 addr[w._fmfield](val);
1490 if(dojo.byId('uedit-billing-address-' + addr.id()).checked)
1491 patron.billing_address(addr.id());
1493 if(dojo.byId('uedit-mailing-address-' + addr.id()).checked)
1494 patron.mailing_address(addr.id());
1499 if(val == null) break;
1500 var resp = new fieldmapper.asvr();
1502 resp.survey(w._survey)
1503 resp.usr(patron.id());
1504 resp.question(w._question)
1506 var t = patron.survey_responses();
1509 patron.survey_responses(t);
1513 var map = patron.stat_cat_entries().filter(
1515 return (m.stat_cat() == w._statcat) })[0];
1518 if(map.stat_cat_entry() == val)
1529 map = new fieldmapper.actscecm();
1533 map.stat_cat(w._statcat);
1534 map.stat_cat_entry(val);
1535 map.target_usr(patron.id());
1536 var t = patron.stat_cat_entries();
1539 patron.stat_cat_entries(t);
1544 patron.ischanged(1);
1545 fieldmapper.standardRequest(
1546 ['open-ils.actor', 'open-ils.actor.patron.update'],
1548 params: [openils.User.authtoken, patron],
1549 oncomplete: function(r) {
1551 if (xulG && typeof xulG.unlock_tab == 'function') {
1553 already_locked = false;
1555 newPatron = openils.Util.readResponse(r);
1557 uEditUpdateUserSettings(newPatron.id());
1558 if(stageUser) uEditRemoveStage();
1559 uEditFinishSave(newPatron, doClone);
1566 function uEditRemoveStage() {
1567 var resp = fieldmapper.standardRequest(
1568 ['open-ils.actor', 'open-ils.actor.user.stage.delete'],
1569 { params : [openils.User.authtoken, stageUser.row_id()] }
1573 function uEditFinishSave(newPatron, doClone) {
1575 if(doClone && cloneUser == null)
1576 cloneUser = newPatron.id();
1580 if(xulG && typeof xulG.spawn_editor == 'function' && !patron.isnew() ) {
1581 window.xulG.spawn_editor({ses:openils.User.authtoken,clone:cloneUser});
1585 location.href = location.href.replace(/\?.*/, '') + '?clone=' + cloneUser;
1593 uEditRefreshXUL(newPatron);
1596 function uEditRefresh() {
1597 var usr = cgi.param('usr');
1598 var href = location.href.replace(/\?.*/, '');
1599 href += ((usr) ? '?usr=' + usr : '');
1600 location.href = href;
1603 function uEditRefreshXUL(newuser) {
1604 if (window.xulG && typeof window.xulG.on_save == 'function')
1605 window.xulG.on_save(newuser);
1610 * Create a new address and insert it into the DOM
1611 * @param evt ignored
1612 * @param id The address id
1613 * @param mkLinks If true, set the new address as the
1614 * mailing/billing address for the user
1616 function uEditNewAddr(evt, id, mkLinks) {
1619 id = --uEditAddrVirtId; // new address
1621 var addr = patron.addresses().filter(
1622 function(i) { return (i.id() == id) })[0];
1624 dojo.forEach(addrTemplateRows,
1627 row = tbody.insertBefore(row.cloneNode(true), dojo.byId('new-addr-row'));
1628 row.setAttribute('type', '');
1629 row.setAttribute('addr', id+'');
1631 if(row.getAttribute('fmclass')) {
1632 var widget = fleshFMRow(row, 'aua', {addr:id});
1634 // make new addresses a default address type
1635 if(id < 0 && row.getAttribute('fmfield') == 'address_type')
1636 widget.widget.attr('value', localeStrings.DEFAULT_ADDRESS_TYPE);
1638 // make new addresses valid by default
1639 if(id < 0 && row.getAttribute('fmfield') == 'valid')
1640 widget.widget.attr('value', true);
1642 // make new addresses use the org setting for default country
1643 if(id < 0 && row.getAttribute('fmfield') == 'country')
1644 widget.widget.attr('value',orgSettings['ui.patron.default_country']);
1646 } else if(row.getAttribute('name') == 'uedit-addr-pending-row') {
1648 // if it's a pending address, show the 'approve' button
1649 if(addr && openils.Util.isTrue(addr.pending())) {
1650 openils.Util.show(row, 'table-row');
1651 dojo.query('[name=approve-button]', row)[0].onclick =
1652 function() { uEditApproveAddress(addr); };
1654 if(addr.replaces()) {
1655 var div = dojo.query('[name=replaced-addr]', row)[0]
1656 var replaced = patron.addresses().filter(
1657 function(i) { return (i.id() == addr.replaces()) })[0];
1659 div.innerHTML = dojo.string.substitute(localeStrings.REPLACED_ADDRESS, [
1660 replaced.address_type() || '',
1661 replaced.street1() || '',
1662 replaced.street2() || '',
1663 replaced.city() || '',
1664 replaced.state() || '',
1665 replaced.post_code() || ''
1669 openils.Util.hide(dojo.query('[name=replaced-addr-div]', row)[0]);
1673 } else if(row.getAttribute('name') == 'uedit-addr-owner-row') {
1674 // address is owned by someone else. provide option to load the
1675 // user in a different tab
1677 if(addr && addr.usr() != patron.id()) {
1678 openils.Util.show(row, 'table-row');
1679 var link = getByName(row, 'addr-owner');
1681 // fetch the linked user so we can present their name in the UI
1683 if(cloneUserObj && cloneUserObj.id() == addr.usr()) {
1685 cloneUserObj.first_given_name(),
1686 cloneUserObj.second_given_name(),
1687 cloneUserObj.family_name()
1690 addrUser = fieldmapper.standardRequest(
1691 ['open-ils.actor', 'open-ils.actor.user.retrieve.parts'],
1693 openils.User.authtoken,
1695 ['first_given_name', 'second_given_name', 'family_name']
1700 link.innerHTML = (addrUser.map(function(name) { return (name) ? name+' ' : '' })+'').replace(/,/g,''); // TODO i18n
1701 link.onclick = function() {
1702 if(openils.XUL.isXUL()) {
1703 window.xulG.spawn_editor({ses:openils.User.authtoken, usr:addr.usr()})
1705 parent.location.href = location.href.replace(/clone=\d+/, 'usr=' + addr.usr());
1710 } else if(row.getAttribute('name') == 'uedit-addr-divider') {
1711 // link up the billing/mailing address and give the inputs IDs so we can access the later
1714 var ba = getByName(row, 'billing_address');
1715 ba.id = 'uedit-billing-address-' + id;
1716 if(mkLinks || (patron.billing_address() && patron.billing_address().id() == id))
1720 var ma = getByName(row, 'mailing_address');
1721 ma.id = 'uedit-mailing-address-' + id;
1722 if(mkLinks || (patron.mailing_address() && patron.mailing_address().id() == id))
1725 var btn = dojo.query('[name=delete-button]', row)[0];
1726 if(btn) btn.onclick = function(){ uEditDeleteAddr(id) };
1732 function uEditApproveAddress(addr) {
1733 fieldmapper.standardRequest(
1734 ['open-ils.actor', 'open-ils.actor.user.pending_address.approve'],
1736 params: [openils.User.authtoken, addr],
1738 oncomplete : function(r) {
1739 var oldId = openils.Util.readResponse(r);
1741 // remove addrs from UI
1744 function(addr) { uEditDeleteAddr(addr.id(), true); }
1749 // remove the replaced address
1750 if(oldId != addr.id()) {
1752 patron.addresses().filter(
1753 function(i) { return (i.id() != oldId); }
1758 // fix the the new address
1760 addr.replaces(null);
1773 function uEditDeleteAddr(id, noAlert) {
1774 if (patron.isnew() && orgSettings['ui.patron.registration.require_address']) {
1775 if (dojo.query('tr[name=uedit-addr-divider]').length < 2) {
1776 alert(localeStrings.NEED_ADDRESS);
1781 if(!confirm(dojo.string.substitute(localeStrings.DELETE_ADDRESS, [id]))) return;
1783 var addr = patron.addresses().filter(function(i){return (i.id() == id)})[0];
1784 if (addr) { addr.isdeleted(1); }
1785 var m_a = patron.mailing_address();
1786 if (typeof m_a == 'object' && m_a != null) { m_a = m_a.id(); }
1787 if (m_a == id) { patron.mailing_address(null); }
1788 var b_a = patron.billing_address();
1789 if (typeof b_a == 'object' && b_a != null) { b_a = b_a.id(); }
1790 if (b_a == id) { patron.billing_address(null); }
1792 var rows = dojo.query('tr[addr='+id+']', tbody);
1793 for(var i = 0; i < rows.length; i++)
1794 rows[i].parentNode.removeChild(rows[i]);
1795 widgetPile = widgetPile.filter(function(w){return (w._addr != id)});
1798 function uEditToggleRequired(level) {
1799 openils.Util.removeCSSClass(tbody, 'hide-non-required');
1800 openils.Util.removeCSSClass(tbody, 'hide-non-suggested');
1801 openils.Util.show('uedit-show-required');
1802 openils.Util.show('uedit-show-required-br');
1803 openils.Util.show('uedit-show-suggested');
1804 openils.Util.show('uedit-show-suggested-br');
1805 openils.Util.show('uedit-show-all');
1808 openils.Util.hide('uedit-show-required');
1809 openils.Util.hide('uedit-show-required-br');
1810 openils.Util.addCSSClass(tbody, 'hide-non-required');
1813 openils.Util.hide('uedit-show-suggested');
1814 openils.Util.hide('uedit-show-suggested-br');
1815 openils.Util.addCSSClass(tbody, 'hide-non-suggested');
1818 openils.Util.hide('uedit-show-all');
1823 function printable_output() {
1824 var temp; var s = '=-=-=-=\r\n';
1825 for (var idx in widgetPile) {
1826 var w = widgetPile[idx];
1827 var val = uEditWidgetVal(w);
1829 if (typeof w.idlField == 'undefined') {
1831 if (w._wtype == 'statcat') {
1832 var stat = statCats.filter(
1834 return (m.id() == w._statcat) })[0];
1835 label = stat.name();
1836 } else if (w._wtype == 'survey') {
1837 var survey = surveys.filter(
1839 return (m.id() == w._survey) })[0];
1840 var question = survey.questions().filter(
1842 return (m.id() == w._question) })[0];
1843 label = survey.name() + ' : ' + question.question();
1848 label = w.idlField.label;
1850 if (temp != w._wtype) {
1854 s += label + ':\t' + (typeof val == 'object' ? '' : val) + '\r\n';
1860 openils.Util.addOnLoad(load);