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('openils.widget.ProgressDialog');
12 dojo.require('dijit.form.CheckBox');
13 dojo.require('dijit.form.Button');
14 dojo.require('dojo.date');
15 dojo.require('openils.CGI');
16 dojo.require('openils.XUL');
17 dojo.require('openils.Util');
18 dojo.require('openils.Event');
20 dojo.requireLocalization('openils.actor', 'register');
21 var localeStrings = dojo.i18n.getLocalization('openils.actor', 'register');
25 var fmClasses = ['au', 'ac', 'aua', 'actsc', 'asv', 'asvq', 'asva'];
32 var uEditUsePhonePw = false;
34 var uEditCardVirtId = -1;
35 var uEditAddrVirtId = -1;
37 var userSettings = {};
38 var userSettingsToUpdate = {};
48 var uEditCloneCopyAddr; // if true, copy addrs on clone instead of link
52 var prevBillingAddress;
53 var prevMailingAddress;
55 var dupeUsrname = false;
56 var dupeBarcode = false;
58 // allow for a pause after typing before sending address alert queries
59 var addressAlertTimeout = 2000;
60 var addressAlertFields =
61 ['street1', 'street2', 'city', 'state', 'county', 'country', 'post_code'];
63 if(!window.xulG) var xulG = null;
64 var lock_ready = false;
65 var already_locked = false;
68 staff = new openils.User().user;
69 pcrud = new openils.PermaCrud();
70 cgi = new openils.CGI();
71 cloneUser = cgi.param('clone');
72 var userId = cgi.param('usr');
73 var stageUname = cgi.param('stage');
75 saveButton.attr("label", localeStrings.SAVE);
76 saveCloneButton.attr("label", localeStrings.SAVE_CLONE);
77 replaceBarcode.attr("label", localeStrings.REPLACE_BARCODE);
78 dojo.byId('uedit-show-required').innerHTML = localeStrings.SHOW_REQUIRED;
79 dojo.byId('uedit-show-suggested').innerHTML = localeStrings.SHOW_SUGGESTED;
80 dojo.byId('uedit-show-all').innerHTML = localeStrings.SHOW_ALL;
81 dojo.byId('uedit-dupe-barcode-warning').innerHTML = localeStrings.BARCODE_IN_USE;
82 allCards.attr("label", localeStrings.SEE_ALL);
83 dojo.byId('uedit-dupe-username-warning').innerHTML = localeStrings.DUPE_USERNAME;
84 generatePassword.attr("label", localeStrings.RESET_PASSWORD);
85 dojo.byId('verifyPassword').innerHTML = localeStrings.VERIFY_PASSWORD;
86 dojo.byId('parentGuardian').innerHTML = localeStrings.PARENT_OR_GUARDIAN;
87 dojo.byId('userSettings').innerHTML = localeStrings.USER_SETTINGS;
88 dojo.byId('statCats').innerHTML = localeStrings.STAT_CATS;
89 dojo.byId('uedit-all-cards-barcode').innerHTML = localeStrings.ALL_CARDS_BARCODE;
90 dojo.byId('uedit-all-cards-active').innerHTML = localeStrings.ALL_CARDS_ACTIVE;
91 dojo.byId('uedit-all-cards-primary').innerHTML = localeStrings.ALL_CARDS_PRIMARY;
92 allCardsClose.attr("label", localeStrings.ALL_CARDS_CLOSE);
93 allCardsApply.attr("label", localeStrings.ALL_CARDS_APPLY);
95 dojo.query("td[name='addressHeader']").forEach( function(item) { item.innerHTML = localeStrings.ADDRESS_HEADER; });
96 dojo.query("span[name='mailingAddress']").forEach( function(item) { item.innerHTML = localeStrings.ADDRESS_MAILING; });
97 dojo.query("span[name='billingAddress']").forEach( function(item) { item.innerHTML = localeStrings.ADDRESS_BILLING; });
98 dojo.query("span[name='addressPending']").forEach( function(item) { item.innerHTML = localeStrings.ADDRESS_PENDING; });
99 dojo.query("button[name='approve-button']").forEach( function(item) { item.innerHTML = localeStrings.ADDRESS_APPROVE; });
100 dojo.query("span[name='address-already-owned']").forEach( function(item) { item.innerHTML = localeStrings.ADDRESS_OWNED; });
101 dojo.query("button[name='addressNew']").forEach( function(item) { item.innerHTML = localeStrings.ADDRESS_NEW; });
104 if(xulG.ses) openils.User.authtoken = xulG.ses;
105 if(typeof xulG.clone != 'undefined') cloneUser = xulG.clone;
106 if(typeof xulG.usr != 'undefined') userId = xulG.usr
107 if(typeof xulG.params != 'undefined') {
108 var parms = xulG.params;
109 if(typeof parms.ses != 'undefined')
110 openils.User.authtoken = parms.ses;
111 if(typeof parms.clone != 'undefined')
112 cloneUser = parms.clone;
113 if(typeof parms.usr != 'undefined')
115 if(typeof parms.stage != 'undefined')
116 stageUname = parms.stage
120 orgSettings = fieldmapper.aou.fetchOrgSettingBatch(staff.ws_ou(), [
121 'global.password_regex',
122 'global.juvenile_age_threshold',
123 'patron.password.use_phone',
124 'ui.patron.default_inet_access_level',
125 'ui.patron.default_ident_type',
126 'ui.patron.default_country',
127 'ui.patron.registration.require_address',
128 'circ.holds.behind_desk_pickup_supported',
129 'circ.patron_edit.clone.copy_address',
130 'ui.patron.edit.au.second_given_name.show',
131 'ui.patron.edit.au.second_given_name.suggest',
132 'ui.patron.edit.au.suffix.show',
133 'ui.patron.edit.au.suffix.suggest',
134 'ui.patron.edit.au.alias.show',
135 'ui.patron.edit.au.alias.suggest',
136 'ui.patron.edit.au.dob.require',
137 'ui.patron.edit.au.dob.show',
138 'ui.patron.edit.au.dob.suggest',
139 'ui.patron.edit.au.dob.calendar',
140 'ui.patron.edit.au.juvenile.show',
141 'ui.patron.edit.au.juvenile.suggest',
142 'ui.patron.edit.au.ident_value.show',
143 'ui.patron.edit.au.ident_value.suggest',
144 'ui.patron.edit.au.ident_value2.show',
145 'ui.patron.edit.au.ident_value2.suggest',
146 'ui.patron.edit.au.email.require',
147 'ui.patron.edit.au.email.show',
148 'ui.patron.edit.au.email.suggest',
149 'ui.patron.edit.au.email.regex',
150 'ui.patron.edit.au.email.example',
151 'ui.patron.edit.au.day_phone.require',
152 'ui.patron.edit.au.day_phone.show',
153 'ui.patron.edit.au.day_phone.suggest',
154 'ui.patron.edit.au.day_phone.regex',
155 'ui.patron.edit.au.day_phone.example',
156 'ui.patron.edit.au.evening_phone.require',
157 'ui.patron.edit.au.evening_phone.show',
158 'ui.patron.edit.au.evening_phone.suggest',
159 'ui.patron.edit.au.evening_phone.regex',
160 'ui.patron.edit.au.evening_phone.example',
161 'ui.patron.edit.au.other_phone.require',
162 'ui.patron.edit.au.other_phone.show',
163 'ui.patron.edit.au.other_phone.suggest',
164 'ui.patron.edit.au.other_phone.regex',
165 'ui.patron.edit.au.other_phone.example',
166 'ui.patron.edit.phone.regex',
167 'ui.patron.edit.phone.example',
168 'ui.patron.edit.au.active.show',
169 'ui.patron.edit.au.active.suggest',
170 'ui.patron.edit.au.barred.show',
171 'ui.patron.edit.au.barred.suggest',
172 'ui.patron.edit.au.master_account.show',
173 'ui.patron.edit.au.master_account.suggest',
174 'ui.patron.edit.au.claims_returned_count.show',
175 'ui.patron.edit.au.claims_returned_count.suggest',
176 'ui.patron.edit.au.claims_never_checked_out_count.show',
177 'ui.patron.edit.au.claims_never_checked_out_count.suggest',
178 'ui.patron.edit.au.alert_message.show',
179 'ui.patron.edit.au.alert_message.suggest',
180 'ui.patron.edit.aua.post_code.regex',
181 'ui.patron.edit.aua.post_code.example',
182 'ui.patron.edit.aua.county.require',
184 'ui.patron.edit.default_suggested',
185 'opac.barcode_regex',
186 'opac.username_regex'
189 for(k in orgSettings)
191 orgSettings[k] = orgSettings[k].value;
193 uEditCloneCopyAddr = orgSettings['circ.patron_edit.clone.copy_address'];
194 uEditUsePhonePw = orgSettings['patron.password.use_phone'];
195 uEditFetchUserSettings(userId);
198 patron = uEditLoadUser(userId);
201 patron = uEditLoadStageUser(stageUname);
203 patron = uEditNewPatron();
205 uEditCopyCloneData(patron);
210 var list = pcrud.search('fdoc', {fm_class:fmClasses});
213 if(!fieldDoc[doc.fm_class()])
214 fieldDoc[doc.fm_class()] = {};
215 fieldDoc[doc.fm_class()][doc.field()] = doc;
218 list = pcrud.search('aout', {can_have_users: 'true'});
221 homeOuTypes[type.id()] = true;
224 tbody = dojo.byId('uedit-tbody');
226 if(orgSettings['ui.patron.edit.default_suggested'])
227 uEditToggleRequired(2);
229 addrTemplateRows = dojo.query('tr[type=addr-template]', tbody);
230 dojo.forEach(addrTemplateRows, function(row) { row.parentNode.removeChild(row); } );
231 statCatTemplate = tbody.removeChild(dojo.byId('stat-cat-row-template'));
232 surveyTemplate = tbody.removeChild(dojo.byId('survey-row-template'));
233 surveyQuestionTemplate = tbody.removeChild(dojo.byId('survey-question-row-template'));
235 checkGrpAppPerm(); // to do the initial load
239 if(patron.isnew() && patron.addresses().length == 0)
240 uEditNewAddr(null, uEditAddrVirtId, true);
244 checkClaimsReturnCountPerm();
245 checkClaimsNoCheckoutCountPerm();
247 dojo.connect(replaceBarcode, 'onClick', replaceCardHandler);
248 dojo.connect(allCards, 'onClick', drawAllCards);
250 dojo.addClass(dojo.byId('uedit-all-barcodes'), 'hidden');
251 } else if(checkGrpAppPerm(patron.profile())) {
252 new openils.User().getPermOrgList(
253 'UPDATE_PATRON_ACTIVE_CARD',
255 if(orgList.indexOf(patron.home_ou()) != -1)
256 cardPerms['UPDATE_PATRON_ACTIVE_CARD'] = true;
261 new openils.User().getPermOrgList(
262 'UPDATE_PATRON_PRIMARY_CARD',
264 if(orgList.indexOf(patron.home_ou()) != -1)
265 cardPerms['UPDATE_PATRON_PRIMARY_CARD'] = true;
272 var input = findWidget('ac', 'barcode');
273 if (patron.isnew()) {
274 replaceBarcode.attr('disabled', true);
276 input.widget.attr('disabled', true).attr('readOnly', true);
279 dojo.connect(generatePassword, 'onClick', generatePasswordHandler);
281 if(!patron.isnew() && !checkGrpAppPerm(patron.profile()) && patron.id() != openils.User.user.id()) {
282 // we are not allowed to edit this user, so disable the save option
283 saveButton.attr('disabled', true);
284 saveCloneButton.attr('disabled', true);
287 uUpdateContactInvalidators();
292 var noPermGroups = [];
293 // Returns true if the user is allowed to edit the selected group
294 function checkGrpAppPerm(grpId) {
299 permGroups = new openils.PermaCrud().retrieveAll('pgt');
300 var permGroupPerms = []
302 // collect the group permissions
303 dojo.forEach(permGroups,
305 if(grp.application_perm())
306 permGroupPerms.push(grp.application_perm());
310 // see which of the group application perms I do not have
311 var myPerms = fieldmapper.standardRequest(
312 ['open-ils.actor', 'open-ils.actor.user.has_work_perm_at.batch'],
313 [openils.User.authtoken, permGroupPerms]
316 var failedPerms = [];
317 for(var p in myPerms) {
318 if(myPerms[p].length == 0)
322 // identify which groups I cannot edit because I do not have permisssion
324 function checkTree(grp, failed) {
325 failed = failed || failedPerms.indexOf(grp.application_perm()) > -1;
326 if(failed) noPermGroups.push(grp.id()+'');
328 permGroups.filter(function(g) { return g.parent() == grp.id() } ),
330 checkTree(child, failed);
335 checkTree(permGroups.filter(function(g) { return g.parent() == null })[0]);
338 return noPermGroups.indexOf(grpId+'') == -1;
342 function drawAllCards() {
344 var tbody = dojo.byId('uedit-all-cards-tbody');
345 if(!allCardsTemplate) {
346 allCardsTemplate = tbody.removeChild(dojo.byId('uedit-all-cards-tr-template'));
348 while(tbody.childNodes[0])
349 tbody.removeChild(tbody.childNodes[0]);
352 if(cardPerms['UPDATE_PATRON_ACTIVE_CARD'] || cardPerms['UPDATE_PATRON_PRIMARY_CARD']) {
353 dojo.removeClass(dojo.byId('uedit-apply-card-changes'), 'hidden');
355 dojo.addClass(dojo.byId('uedit-apply-card-changes'), 'hidden');
360 patron.cards().filter(function(c) { return c.id() == patron.card().id(); }).concat(patron.cards()), // grab the main card first
363 if(card.id() == patron.card().id())
366 var row = allCardsTemplate.cloneNode(true);
367 row.setAttribute("cardid", card.id());
369 getByName(row, 'barcode').innerHTML = card.barcode();
370 if(cardPerms['UPDATE_PATRON_ACTIVE_CARD']) {
371 row.active_checkbox = new dijit.form.CheckBox({
373 checked: openils.Util.isTrue(card.active())
374 }, getByName(row, 'active'));
376 getByName(row, 'active').appendChild(
377 openils.Util.isTrue(card.active()) ?
378 dojo.byId('true').cloneNode(true) :
379 dojo.byId('false').cloneNode(true)
382 if(cardPerms['UPDATE_PATRON_PRIMARY_CARD']) {
383 row.primary_radiobutton = new dijit.form.RadioButton({
385 checked: card.id() == patron.card().id(),
388 }, getByName(row, 'primary'));
390 getByName(row, 'primary').appendChild(
391 openils.Util.isTrue(card.id() == patron.card().id()) ?
392 dojo.byId('true').cloneNode(true) :
393 dojo.byId('false').cloneNode(true)
396 tbody.appendChild(row);
401 allCardsDialog.show();
404 function applyCardChanges() {
405 var cardrows = dojo.query('[cardid]', allCardsDialog.domNode);
407 dojo.forEach(cardrows,
409 if(cardPerms['UPDATE_PATRON_ACTIVE_CARD']) {
410 var active = row.active_checkbox.checked ? 't' : 'f'
411 if(row.card.active() != active) {
412 row.card.active(active);
413 row.card.ischanged(1);
417 if(cardPerms['UPDATE_PATRON_PRIMARY_CARD']) {
418 if(row.primary_radiobutton.checked && row.card.id() != patron.card().id()) {
419 patron.card(row.card);
425 if(changed && lock_ready && xulG && typeof xulG.lock_tab == 'function' && !already_locked) {
427 already_locked = true;
429 allCardsDialog.hide();
433 * Mark the current card inactive, create a new primary card
435 function replaceCardHandler() {
436 var input = findWidget('ac', 'barcode');
437 input.widget.attr('disabled', false).attr('readOnly', false).attr('value', null).focus();
438 replaceBarcode.attr('disabled', true);
440 // pull old card off the cards list so we don't have a dupe sitting in there
441 if (patron.cards().length > 0) {
442 var old = patron.cards().filter(function(c){return (c.id() == patron.card().id())})[0];
447 var newc = new fieldmapper.ac();
448 newc.id(uEditCardVirtId--);
453 var t = patron.cards();
460 * Generate a random password for the patron.
462 function generatePasswordHandler() {
463 uEditMakeRandomPw(patron);
464 var f = findWidget('au', 'passwd');
465 f.widget.attr('value', patron.passwd());
466 f = findWidget('au', 'passwd2');
467 f.widget.attr('value', patron.passwd());
471 * Loads a staged user and turns them into something the editor can understand
473 function uEditLoadStageUser(stageUname) {
475 var data = fieldmapper.standardRequest(
476 ['open-ils.actor', 'open-ils.actor.user.stage.retrieve.by_username'],
477 { params : [openils.User.authtoken, stageUname] }
480 stageUser = data.user;
481 patron = uEditNewPatron();
486 // copy the data into our new user object
487 for(var key in fieldmapper.IDL.fmclasses.stgu.field_map) {
488 if(fieldmapper.IDL.fmclasses.au.field_map[key] && !fieldmapper.IDL.fmclasses.stgu.field_map[key].virtual) {
489 if(data.user[key]() !== null)
490 patron[key]( data.user[key]() );
494 // copy the data into our new address objects
495 // TODO: uses the first mailing address only
496 if(data.mailing_addresses.length) {
498 var mail_addr = new fieldmapper.aua();
499 mail_addr.id(-1); // virtual ID
502 patron.mailing_address(mail_addr);
503 var t = patron.addresses();
508 for(var key in fieldmapper.IDL.fmclasses.stgma.field_map) {
509 if(fieldmapper.IDL.fmclasses.aua.field_map[key] && !fieldmapper.IDL.fmclasses.stgma.field_map[key].virtual) {
510 if(data.mailing_addresses[0][key]() !== null)
511 mail_addr[key]( data.mailing_addresses[0][key]() );
516 // copy the data into our new address objects
517 // TODO uses the first billing address only
518 if(data.billing_addresses.length) {
520 var bill_addr = new fieldmapper.aua();
521 bill_addr.id(-2); // virtual ID
524 patron.billing_address(bill_addr);
525 var t = patron.addresses();
530 for(var key in fieldmapper.IDL.fmclasses.stgba.field_map) {
531 if(fieldmapper.IDL.fmclasses.aua.field_map[key] && !fieldmapper.IDL.fmclasses.stgba.field_map[key].virtual) {
532 if(data.billing_addresses[0][key]() !== null)
533 bill_addr[key]( data.billing_addresses[0][key]() );
538 // TODO: uses the first card only
539 if(data.cards.length) {
540 var card = new fieldmapper.ac();
541 card.id(-1); // virtual ID
542 patron.card().barcode(data.cards[0].barcode());
549 * clone the home org, phone numbers, and billing/mailing address
551 function uEditCopyCloneData(patron) {
552 cloneUserObj = uEditLoadUser(cloneUser);
562 if(!uEditCloneCopyAddr)
563 cloneFields = cloneFields.concat(['mailing_address', 'billing_address']);
568 patron[field](cloneUserObj[field]());
572 if(uEditCloneCopyAddr) {
573 var billAddr, mailAddr;
575 // copy the billing and mailing addresses into new addresses
576 function cloneAddr(addr) {
577 var newAddr = addr.clone();
579 newAddr.id(uEditAddrVirtId--);
580 newAddr.usr(patron.id());
581 patron.addresses().push(newAddr);
585 if(billAddr = cloneUserObj.billing_address())
586 patron.billing_address(cloneAddr(billAddr));
588 if(mailAddr = cloneUserObj.mailing_address()) {
589 if (billAddr && billAddr.id() == mailAddr.id()) {
590 patron.mailing_address(patron.billing_address());
592 patron.mailing_address(cloneAddr(mailAddr));
596 if(!billAddr) // if there was no billing addr, use the mailing addr
597 patron.billing_address(patron.mailing_address());
601 // link the billing and mailing addresses
602 if(patron.billing_address()) {
603 var t = patron.addresses();
605 t.push(patron.billing_address());
609 if(patron.mailing_address() && (
610 patron.addresses().length == 0 ||
611 patron.mailing_address().id() != patron.billing_address().id()) ) {
612 var t = patron.addresses();
614 t.push(patron.mailing_address());
621 function uEditFetchUserSettings(userId) {
623 var baseNode = fieldmapper.aou.findOrgUnit(staff.ws_ou());
624 var orgs = fieldmapper.aou.orgNodeTrail(baseNode);
625 orgs = orgs.map(function(node) { return node.id(); });
627 /* fetch any user setting types we need + any that offer opt-in */
628 userSettingTypes = pcrud.search('cust', {
630 {name:['circ.holds_behind_desk', 'circ.collections.exempt']},
633 select : {atevdef : ['opt_in_setting']},
635 // we only care about opt-in settings for event_defs our users encounter
636 where : {'+atevdef' : {owner : orgs}}
642 var names = userSettingTypes.map(function(obj) { return obj.name() });
644 /* fetch any values set for this user */
646 userSettings = fieldmapper.standardRequest(
647 ['open-ils.actor', 'open-ils.actor.patron.settings.retrieve.authoritative'],
648 {params : [openils.User.authtoken, userId, names]});
653 function uEditLoadUser(userId) {
654 var patron = fieldmapper.standardRequest(
655 ['open-ils.actor', 'open-ils.actor.user.fleshed.retrieve.authoritative'],
656 {params : [openils.User.authtoken, userId]}
658 openils.Event.parse_and_raise(patron);
662 function loadStaticFields() {
663 for(var idx = 0; tbody.childNodes[idx]; idx++) {
664 var row = tbody.childNodes[idx];
665 if(row.nodeType != row.ELEMENT_NODE) continue;
666 var fmcls = row.getAttribute('fmclass');
668 fleshFMRow(row, fmcls);
671 if(row.id == 'uedit-settings-divider') {
673 var template = tbody.removeChild(dojo.byId('uedit-user-setting-template'));
674 dojo.forEach(userSettingTypes, function(type) { uEditDrawSettingRow(tbody, row, template, type); } );
676 if(userSettingTypes.length > 1 || orgSettings['circ.holds.behind_desk_pickup_supported']) {
677 openils.Util.show('uedit-settings-divider', 'table-row');
684 function uEditDrawSettingRow(tbody, dividerRow, template, stype) {
685 var row = template.cloneNode(true);
686 row.setAttribute('user_setting', stype.name());
687 getByName(row, 'label').innerHTML = stype.label();
688 var cb = new dijit.form.CheckBox({scrollOnFocus:false}, getByName(row, 'widget'));
689 cb.attr('value', userSettings[stype.name()]);
690 dojo.connect(cb, 'onChange', function(newVal) { userSettingsToUpdate[stype.name()] = newVal; });
691 tbody.insertBefore(row, dividerRow.nextSibling);
692 openils.Util.show(row, 'table-row');
694 if(stype.name() == 'circ.collections.exempt') {
695 checkCollectionsExemptPerm(cb);
699 function uEditUpdateUserSettings(userId) {
700 return fieldmapper.standardRequest(
701 ['open-ils.actor', 'open-ils.actor.patron.settings.update'],
702 {params : [openils.User.authtoken, userId, userSettingsToUpdate]});
705 function loadAllAddrs() {
706 dojo.forEach(patron.addresses(),
708 uEditNewAddr(null, addr.id());
713 function loadStatCats() {
715 statCats = fieldmapper.standardRequest(
716 ['open-ils.circ', 'open-ils.circ.stat_cat.actor.retrieve.all'],
717 {params : [openils.User.authtoken, staff.ws_ou()]}
721 for(var idx in statCats) {
722 var stat = statCats[idx];
723 var row = statCatTemplate.cloneNode(true);
724 row.id = 'stat-cat-row-' + idx;
725 row.setAttribute('stat_cat_owner',stat.owner());
726 row.setAttribute('stat_cat_name',stat.name());
727 row.setAttribute('stat_cat_id',stat.id());
728 tbody.appendChild(row);
729 getByName(row, 'name').innerHTML = stat.name();
730 var valtd = getByName(row, 'widget');
731 var span = valtd.appendChild(document.createElement('span'));
732 var store = new dojo.data.ItemFileReadStore(
733 {data:fieldmapper.actsc.toStoreData(stat.entries())});
734 var comboBox = new dijit.form.ComboBox({store:store,scrollOnFocus:false,fetchProperties:{sort:[{attribute: 'value'}]}}, span);
735 comboBox.labelAttr = 'value';
736 comboBox.searchAttr = 'value';
738 comboBox._wtype = 'statcat';
739 comboBox._statcat = stat.id();
740 widgetPile.push(comboBox);
742 // populate existing cats
743 var map = patron.stat_cat_entries().filter(
744 function(mp) { return (mp.stat_cat() == stat.id()) })[0];
745 if(map) comboBox.attr('value', map.stat_cat_entry());
750 function loadSurveys() {
752 surveys = fieldmapper.standardRequest(
753 ['open-ils.circ', 'open-ils.circ.survey.retrieve.all'],
754 {params : [openils.User.authtoken]}
758 for(var idx in surveys) {
759 var survey = surveys[idx];
760 var required = openils.Util.isTrue(survey.required());
761 var srow = surveyTemplate.cloneNode(true);
762 if(required) srow.setAttribute('required','required');
763 tbody.appendChild(srow);
764 getByName(srow, 'name').innerHTML = survey.name();
766 for(var q in survey.questions()) {
767 var quest = survey.questions()[q];
768 var qrow = surveyQuestionTemplate.cloneNode(true);
769 if(required) qrow.setAttribute('required','required');
770 tbody.appendChild(qrow);
771 getByName(qrow, 'question').innerHTML = quest.question();
773 var span = getByName(qrow, 'answers').appendChild(document.createElement('span'));
774 var store = new dojo.data.ItemFileReadStore(
775 {data:fieldmapper.asva.toStoreData(quest.answers())});
776 var select = new dijit.form.FilteringSelect({store:store,scrollOnFocus:false}, span);
778 select.isValid = function() { return true; };
780 select.labelAttr = 'answer';
781 select.searchAttr = 'answer';
783 select._wtype = 'survey';
784 select._survey = survey.id();
785 select._question = quest.id();
786 widgetPile.push(select);
792 function fleshFMRow(row, fmcls, args) {
793 var fmfield = row.getAttribute('fmfield');
794 var wclass = row.getAttribute('wclass');
795 var wstyle = row.getAttribute('wstyle');
796 var wconstraints = row.getAttribute('wconstraints');
797 /* use CSS to set the zindex for widgets you want to disable. */
798 var disabled = dojo.style(row, 'zIndex') == -1 ? true : false;
799 var isphone = (fmcls == 'au') && (fmfield.search('_phone') != -1);
801 var isPasswd2 = (fmfield == 'passwd2');
802 if(isPasswd2) fmfield = 'passwd';
803 var fieldIdl = fieldmapper.IDL.fmclasses[fmcls].field_map[fmfield];
806 var existing = dojo.query('td', row);
807 var htd = existing[0] || row.appendChild(document.createElement('td'));
808 var ltd = existing[1] || row.appendChild(document.createElement('td'));
809 var wtd = existing[2] || row.appendChild(document.createElement('td'));
810 var ftd = existing[3] || row.appendChild(document.createElement('td'));
812 openils.Util.addCSSClass(htd, 'uedit-help');
813 if(fieldDoc[fmcls] && fieldDoc[fmcls][fmfield]) {
814 var link = dojo.byId('uedit-help-template').cloneNode(true);
816 link.onclick = function() { ueLoadContextHelp(fmcls, fmfield) };
817 openils.Util.removeCSSClass(link, 'hidden');
818 htd.appendChild(link);
821 if(!ltd.textContent) {
822 ltd.appendChild(document.createTextNode(fieldIdl.label));
825 if(!ftd.textContent) {
826 if(orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.example']) {
827 ftd.appendChild(document.createTextNode(localeStrings.EXAMPLE + orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.example']));
829 else if(isphone && orgSettings['ui.patron.edit.phone.example']) {
830 ftd.appendChild(document.createTextNode(localeStrings.EXAMPLE + orgSettings['ui.patron.edit.phone.example']));
832 else if(fieldIdl.datatype == 'timestamp') {
833 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)})));
836 if (fmcls == "au" && (isphone || fmfield == "email")) {
837 var span = dojo.create(
839 "className": "hidden",
840 "id": "wrap_invalidate_" + fmfield
843 uGenerateInvalidatorWidget(span, fmfield);
844 ftd.appendChild(span);
848 var span = document.createElement('span');
849 wtd.appendChild(span);
855 if(fmfield == 'barred') {
856 // Are we allowed to touch the barred state?
857 var permission = 'BAR_PATRON';
858 if(fmObject.barred() == 't') {
859 permission = 'UNBAR_PATRON';
861 var ou = staff.ws_ou();
862 if(fmObject.home_ou() != null) {
863 ou = fmObject.home_ou();
865 var resp = fieldmapper.standardRequest(
866 ['open-ils.actor', 'open-ils.actor.user.perm.check'],
867 { params : [openils.User.authtoken, staff.id(), ou, [permission] ] }
869 if(resp[0]) { // No permission to adjust barred state from current
874 case 'ac' : if(!editCard) editCard = patron.card(); fmObject = editCard; break;
876 fmObject = patron.addresses().filter(
877 function(i) { return (i.id() == args.addr) })[0];
878 if(fmObject && fmObject.usr() != patron.id())
883 // Adjust required value by org settings
884 var curRequired = row.getAttribute('required');
885 var required = curRequired == 'required';
886 if(orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.require']) {
887 row.setAttribute('required', 'required');
890 else if (curRequired != 'required' && orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.show']) {
891 row.setAttribute('required', 'show');
893 else if (curRequired != 'required' && curRequired != 'show' && orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.suggest']) {
894 row.setAttribute('required', 'suggested');
897 // password data is not fetched/required/displayed for existing users
898 if(!patron.isnew() && 'passwd' == fmfield)
904 constraints : (wconstraints) ? eval('('+wconstraints+')') : {}, // the ()'s prevent Invalid Label errors with eval
908 // Org settings provided regex?
909 if(orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.regex']) {
910 dijitArgs.regExp = orgSettings['ui.patron.edit.' + fmcls + '.' + fmfield + '.regex'];
912 else if(isphone && orgSettings['ui.patron.edit.phone.regex']) {
913 dijitArgs.regExp = orgSettings['ui.patron.edit.phone.regex'];
916 if(fmcls == 'au' && fmfield == 'passwd') {
917 if (orgSettings['global.password_regex']) {
918 dijitArgs.regExp = orgSettings['global.password_regex'];
922 if(fmcls == 'au' && fmfield == 'dob' && !orgSettings['ui.patron.edit.au.dob.calendar'])
923 dijitArgs.popupClass = "";
925 var value = row.getAttribute('wvalue');
927 dijitArgs.value = value;
934 widgetClass : wclass,
935 dijitArgs : dijitArgs,
936 orgDefaultsToWs : true,
937 orgLimitPerms : ['UPDATE_USER'],
940 if(fmfield == 'profile') {
941 // fetch profile groups non-async so existing expire_date is
942 // not overwritten when the profile groups arrive and update
943 wargs.forceSync = true;
944 wargs.disableQuery = {usergroup : 'f'};
946 wargs.forceSync = false;
949 if(fmcls == 'au' && fmfield == 'home_ou'){
950 wargs.labelAttr = 'name';
951 wargs.searchAttr = 'name';
954 var widget = new openils.widget.AutoFieldWidget(wargs);
957 if(fmfield == 'profile') {
959 if(!patron.isnew() && !checkGrpAppPerm(patron.profile())){
960 w.attr('disabled', true);
966 // now put it back before we register the widget
967 if(isPasswd2) fmfield = 'passwd2';
969 widget._wtype = fmcls;
970 widget._fmfield = fmfield;
971 widget._addr = args.addr;
972 widgetPile.push(widget);
973 attachWidgetEvents(fmcls, fmfield, widget);
977 function trimGrpTree(autoWidget) {
978 var store = autoWidget.widget.store;
980 // remove all groups that this user are not allowed to edit,
981 // except the profile group of an existing user
982 store.fetch({onItem :
984 if(!checkGrpAppPerm(item.id[0]) && patron.profile() != item.id[0])
985 store.deleteItem(item);
990 function findWidget(wtype, fmfield, callback) {
991 return widgetPile.filter(
993 if(i._wtype == wtype && i._fmfield == fmfield) {
994 if(callback) return callback(i);
1002 * if the user does not have the UPDATE_PATRON_CLAIM_RETURN_COUNT,
1003 * they are not allowed to directly alter the claim return count.
1004 * This function checks the perm and disable/enables the widget.
1006 function checkClaimsReturnCountPerm() {
1007 new openils.User().getPermOrgList(
1008 'UPDATE_PATRON_CLAIM_RETURN_COUNT',
1010 var cr = findWidget('au', 'claims_returned_count');
1011 if(orgList.indexOf(patron.home_ou()) == -1)
1012 cr.widget.attr('disabled', true);
1014 cr.widget.attr('disabled', false);
1022 function checkClaimsNoCheckoutCountPerm() {
1023 new openils.User().getPermOrgList(
1024 'UPDATE_PATRON_CLAIM_NEVER_CHECKED_OUT_COUNT',
1026 var cr = findWidget('au', 'claims_never_checked_out_count');
1027 if(orgList.indexOf(patron.home_ou()) == -1)
1028 cr.widget.attr('disabled', true);
1030 cr.widget.attr('disabled', false);
1037 var collectExemptCBox;
1038 function checkCollectionsExemptPerm(cbox) {
1039 if(cbox) collectExemptCBox = cbox;
1040 new openils.User().getPermOrgList(
1041 'UPDATE_PATRON_COLLECTIONS_EXEMPT',
1043 if(orgList.indexOf(patron.home_ou()) == -1)
1044 collectExemptCBox.attr('disabled', true);
1046 collectExemptCBox.attr('disabled', false);
1053 function usePhonePw(newVal) {
1056 matches = RegExp(this.regExp).exec(newVal);
1057 if(matches.length > 1) newPw = matches[1];
1059 if(!newPw && newVal && newVal.length >= 4) {
1060 newPw = newVal.substring(newVal.length - 4);
1063 var p1 = findWidget('au', 'passwd');
1064 var p2 = findWidget('au', 'passwd2');
1066 p1.widget.attr('value', newPw);
1067 p2.widget.attr('value', newPw);
1075 function attachWidgetEvents(fmcls, fmfield, widget) {
1081 netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
1082 if (!(ev.altKey || ev.ctrlKey || ev.metaKey)) {
1083 if (lock_ready && xulG && typeof xulG.lock_tab == 'function') {
1084 if (! already_locked) {
1086 already_locked = true;
1096 if (lock_ready && xulG && typeof xulG.lock_tab == 'function') {
1097 if (! already_locked) {
1099 already_locked = true;
1107 if(fmfield == 'barcode') {
1108 dojo.connect(widget.widget, 'onChange',
1110 var barcode = this.attr('value');
1111 dupeBarcode = false;
1112 dojo.addClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
1113 fieldmapper.standardRequest(
1114 ['open-ils.actor', 'open-ils.actor.barcode.exists'],
1116 params: [openils.User.authtoken, barcode],
1117 oncomplete : function(r) {
1118 var res = openils.Util.readResponse(r);
1121 dojo.removeClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
1123 dupeBarcode = false;
1124 dojo.addClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
1125 editCard.barcode(barcode); // Keep the "All" interface up to date
1126 var un = findWidget('au', 'usrname');
1127 if(!un.widget.attr('value'))
1128 un.widget.attr('value', barcode);
1143 widget.widget.isValid = function() {
1145 if(this.attr("value").match(/\s/)) {
1148 // Can look like a barcode (for initial value)
1149 if(orgSettings['opac.barcode_regex']) {
1150 var test_regexp = new RegExp(orgSettings['opac.barcode_regex']);
1151 if(test_regexp.test(this.attr("value"))) {
1155 // Can look like a username
1156 if(orgSettings['opac.username_regex']) {
1157 var test_regexp = new RegExp(orgSettings['opac.username_regex']);
1158 if(test_regexp.test(this.attr("value"))) {
1162 // If we know what a barcode and username look like and we got here, reject
1163 if(orgSettings['opac.barcode_regex'] && orgSettings['opac.username_regex'])
1165 // Otherwise we don't have enough info to say either way, let it through.
1168 dojo.connect(widget.widget, 'onChange',
1170 var input = findWidget('au', 'usrname');
1171 var usrname = input.widget.attr('value');
1174 dupeUsrname = false;
1175 dojo.addClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
1179 fieldmapper.standardRequest(
1180 ['open-ils.actor', 'open-ils.actor.username.exists'],
1182 params: [openils.User.authtoken, usrname],
1183 oncomplete : function(r) {
1184 var res = openils.Util.readResponse(r);
1187 dojo.removeClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
1189 dupeUsrname = false;
1190 dojo.addClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
1200 case 'profile': // when the profile changes, update the expire date
1201 dojo.connect(widget.widget, 'onChange',
1204 var expireWidget = findWidget('au', 'expire_date');
1205 function found(items) {
1206 if(items.length == 0) return;
1207 var item = items[0];
1208 var interval = self.store.getValue(item, 'perm_interval');
1209 expireWidget.widget.attr('value', dojo.date.add(new Date(),
1210 'second', openils.Util.intervalToSeconds(interval)));
1212 this.store.fetch({onComplete:found, query:{id:this.attr('value')}});
1218 widget.widget.isValid = function() {
1219 return this.attr("value") < new Date();
1221 dojo.connect(widget.widget, 'onChange',
1224 var oldDob = patron.dob();
1225 if(dojo.date.stamp.fromISOString(oldDob) == newDob) return;
1227 var juvInterval = orgSettings['global.juvenile_age_threshold'] || '18 years';
1228 var juvWidget = findWidget('au', 'juvenile');
1229 var base = new Date();
1230 base.setTime(base.getTime() - Number(openils.Util.intervalToSeconds(juvInterval) + '000'));
1232 if(newDob <= base) // older than global.juvenile_age_threshold
1233 juvWidget.widget.attr('value', false);
1235 juvWidget.widget.attr('value', true);
1240 case 'first_given_name':
1242 dojo.connect(widget.widget, 'onChange',
1243 function(newVal) { uEditDupeSearch('name', newVal); });
1247 dojo.connect(widget.widget, 'onChange',
1248 function(newVal) { uEditDupeSearch('email', newVal); });
1252 case 'ident_value2':
1253 dojo.connect(widget.widget, 'onChange',
1254 function(newVal) { uEditDupeSearch('ident', newVal); });
1258 // if configured, use the last four digits of the day phone number as the password
1259 // Alt, use the first capture group of the validator regex
1260 if(uEditUsePhonePw && patron.isnew()) {
1261 dojo.connect(widget.widget, 'onChange', widget.widget, usePhonePw);
1262 if (patron.day_phone()) {
1263 usePhonePw(patron.day_phone());
1266 case 'evening_phone':
1268 dojo.connect(widget.widget, 'onChange',
1269 function(newVal) { uEditDupeSearch('phone', newVal); });
1273 widget.widget.isValid = function() {
1275 if(homeOuTypes[this.store.getValue(this.item, 'ou_type')]) {
1282 dojo.connect(widget.widget, 'onChange',
1284 checkClaimsReturnCountPerm();
1285 checkClaimsNoCheckoutCountPerm();
1286 checkCollectionsExemptPerm();
1292 dojo.connect(widget.widget, 'onChange',
1294 var pw1 = findWidget('au', 'passwd').widget;
1295 var pw2 = findWidget('au', 'passwd2').widget;
1296 var preserved_value = pw2.attr('value');
1297 // Ensure that the pw2 field match the pw1 field to validate
1298 pw2.regExp = newVal.replace(/([.\\^$*+?\(\)\[\]\{\}])/g, '\\$1');
1300 pw2.attr('value',preserved_value);
1306 if(fmclass = 'aua') {
1308 // map post code to city, state, and county
1309 if (fmfield == 'post_code') {
1310 dojo.connect(widget.widget, 'onChange',
1312 fieldmapper.standardRequest(
1313 ['open-ils.search', 'open-ils.search.zip'],
1316 oncomplete : function(r) {
1317 var res = openils.Util.readResponse(r);
1319 var callback = function(w) { return w._addr == widget._addr; };
1320 if(res.city) findWidget('aua', 'city', callback).widget.attr('value', res.city);
1321 if(res.state) findWidget('aua', 'state', callback).widget.attr('value', res.state);
1322 if(res.county) findWidget('aua', 'county', callback).widget.attr('value', res.county);
1323 if(res.alert) alert(res.alert);
1331 // duplicate address search
1332 if (['street1', 'street2', 'city'].indexOf(fmfield) > -1) {
1333 dojo.connect(widget.widget, 'onChange',
1335 var callback = function(w) { return w._addr == widget._addr; };
1337 street1 : findWidget('aua', 'street1', callback).widget.attr('value'),
1338 street2 : findWidget('aua', 'street2', callback).widget.attr('value'),
1339 city : findWidget('aua', 'city', callback).widget.attr('value'),
1340 post_code : findWidget('aua', 'post_code', callback).widget.attr('value')
1342 if(args.street1 && args.city && args.post_code)
1343 uEditDupeSearch('address', args);
1348 if (addressAlertFields.indexOf(fmfield) > -1) {
1350 widget.widget, 'onChange',
1351 function() { uEditAddressAlertMarshal(widget._addr) }
1357 function uEditAddressAlertMarshal(addrId, changeBilling, changeMailing) {
1359 if (changeBilling) {
1360 uEditAddressAlertMarshal(prevBillingAddress);
1361 prevBillingAddress = addrId;
1364 if (changeMailing) {
1365 uEditAddressAlertMarshal(prevMailingAddress);
1366 prevMailingAddress = addrId;
1369 var callback = function(w) { return w._addr == addrId; };
1371 dojo.forEach(addressAlertFields,
1373 args[field] = findWidget('aua', field, callback).widget.attr('value')
1376 args.mailing_address = dojo.byId('uedit-mailing-address-' + addrId).checked;
1377 args.billing_address = dojo.byId('uedit-billing-address-' + addrId).checked;
1378 uEditAddressAlertSearch(args, addrId);
1381 var _addrAlertTimeout = {};
1382 function uEditAddressAlertSearch(args, addrId) {
1384 _addrAlertTimeout[addrId] = setTimeout(
1386 if (_addrAlertTimeout[addrId])
1387 clearTimeout(_addrAlertTimeout[addrId]);
1389 console.log('creating addr alert search for ' + addrId);
1391 fieldmapper.standardRequest(
1392 ['open-ils.actor', 'open-ils.actor.address_alert.test'],
1394 params: [openils.User.authtoken, staff.ws_ou(), args],
1395 oncomplete : function(r) {
1396 var alerts = openils.Util.readResponse(r);
1397 var msgNode = dojo.byId('uedit-address-alert-message');
1398 var headerRow = dojo.filter(
1399 dojo.query('[name=uedit-addr-divider]'),
1400 function(row) { return row.getAttribute('addr') == addrId })[0]
1402 msgNode.innerHTML = '';
1404 if (alerts.length) {
1406 // show the alert box
1407 openils.Util.hide('uedit-help-div');
1408 openils.Util.hide('uedit-dupe-div');
1409 openils.Util.show('uedit-address-alert');
1411 // style the address header row
1412 openils.Util.addCSSClass(headerRow, 'uedit-address-alert-divider');
1414 dojo.forEach(alerts,
1416 msgNode.innerHTML += addr.alert_message() + '<br/>';
1421 openils.Util.hide('uedit-address-alert');
1422 openils.Util.removeCSSClass(headerRow, 'uedit-address-alert-divider');
1432 function uEditDupeSearch(type, value) {
1438 openils.Util.hide('uedit-dupe-names-link');
1439 var fname = findWidget('au', 'first_given_name').widget.attr('value');
1440 var lname = findWidget('au', 'family_name').widget.attr('value');
1441 if( !(fname && lname) ) return;
1443 first_given_name : {value : fname, group : 0},
1444 family_name : {value : lname, group : 0},
1449 openils.Util.hide('uedit-dupe-email-link');
1450 search = {email : {value : value, group : 0}};
1454 openils.Util.hide('uedit-dupe-ident-link');
1455 search = {ident : {value : value, group : 2}};
1459 openils.Util.hide('uedit-dupe-phone-link');
1460 search = {phone : {value : value, group : 2}};
1464 openils.Util.hide('uedit-dupe-address-link');
1466 dojo.forEach(['street1', 'street2', 'city', 'post_code'],
1469 search[field] = {value : value[field], group: 1};
1475 // find possible duplicate patrons
1476 fieldmapper.standardRequest(
1477 ['open-ils.actor', 'open-ils.actor.patron.search.advanced'],
1479 params: [openils.User.authtoken, search],
1480 oncomplete : function(r) {
1481 var resp = openils.Util.readResponse(r);
1482 resp = resp.filter(function(id) { return (id != patron.id()); });
1484 if(resp && resp.length > 0) {
1486 openils.Util.hide('uedit-help-div');
1487 openils.Util.hide('uedit-address-alert');
1488 openils.Util.show('uedit-dupe-div');
1493 link = dojo.byId('uedit-dupe-names-link');
1494 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_NAME, [resp.length]);
1497 link = dojo.byId('uedit-dupe-email-link');
1498 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_EMAIL, [resp.length]);
1501 link = dojo.byId('uedit-dupe-ident-link');
1502 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_IDENT, [resp.length]);
1505 link = dojo.byId('uedit-dupe-phone-link');
1506 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_PHONE, [resp.length]);
1509 link = dojo.byId('uedit-dupe-address-link');
1510 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_ADDR, [resp.length]);
1514 openils.Util.show(link);
1515 link.onclick = function() {
1516 search.search_sort = js2JSON(["penalties", "family_name", "first_given_name"]);
1518 window.xulG.spawn_search(search);
1520 console.log("running XUL patron search " + js2JSON(search));
1528 function getByName(node, name) {
1529 return dojo.query('[name='+name+']', node)[0];
1533 function ueLoadContextHelp(fmcls, fmfield) {
1534 openils.Util.hide('uedit-dupe-div');
1535 openils.Util.hide('uedit-dupe-div');
1536 openils.Util.show('uedit-help-div');
1537 dojo.byId('uedit-help-field').innerHTML = fieldmapper.IDL.fmclasses[fmcls].field_map[fmfield].label;
1538 dojo.byId('uedit-help-text').innerHTML = fieldDoc[fmcls][fmfield].string();
1542 /* creates a new patron object with card attached */
1543 function uEditNewPatron() {
1548 card.id(uEditCardVirtId--);
1552 patron.cards([card]);
1553 patron.net_access_level(orgSettings['ui.patron.default_inet_access_level'] || 1);
1554 patron.ident_type(orgSettings['ui.patron.default_ident_type']);
1555 patron.stat_cat_entries([]);
1556 patron.survey_responses([]);
1557 patron.addresses([]);
1558 uEditMakeRandomPw(patron);
1562 function uEditMakeRandomPw(patron) {
1563 var rand = Math.random();
1564 rand = parseInt(rand * 10000) + '';
1565 while(rand.length < 4) rand += '0';
1567 appendClear($('ue_password_plain'),text(rand));
1568 unHideMe($('ue_password_gen'));
1570 patron.passwd(rand);
1574 function uEditWidgetVal(w) {
1575 var val = (w.getFormattedValue) ? w.getFormattedValue() : w.attr('value');
1576 if(val === '') val = null;
1580 function uEditSave() { _uEditSave(); }
1581 function uEditSaveClone() { _uEditSave(true); }
1583 function _uEditSave(doClone) {
1585 if ( (! myForm.isValid()) || dupeUsrname || dupeBarcode ) {
1586 alert(localeStrings.INVALID_FORM);
1590 for(var idx in widgetPile) {
1591 var w = widgetPile[idx];
1592 var val = uEditWidgetVal(w);
1596 if(w._fmfield != 'passwd2')
1597 patron[w._fmfield](val);
1601 if(!editCard) editCard = patron.card();
1602 editCard[w._fmfield](val);
1606 var addr = patron.addresses().filter(function(i){return (i.id() == w._addr)})[0];
1608 addr = new fieldmapper.aua();
1611 addr.usr(patron.id());
1612 addr.country(orgSettings['ui.patron.default_country']);
1613 var t = patron.addresses();
1616 patron.addresses(t);
1618 if(addr[w._fmfield]() != val)
1621 addr[w._fmfield](val);
1623 if(dojo.byId('uedit-billing-address-' + addr.id()).checked)
1624 patron.billing_address(addr.id());
1626 if(dojo.byId('uedit-mailing-address-' + addr.id()).checked)
1627 patron.mailing_address(addr.id());
1632 if(val == null) break;
1633 var resp = new fieldmapper.asvr();
1635 resp.survey(w._survey)
1636 resp.usr(patron.id());
1637 resp.question(w._question)
1639 var t = patron.survey_responses();
1642 patron.survey_responses(t);
1646 var map = patron.stat_cat_entries().filter(
1648 return (m.stat_cat() == w._statcat) })[0];
1651 if(map.stat_cat_entry() == val)
1662 map = new fieldmapper.actscecm();
1666 map.stat_cat(w._statcat);
1667 map.stat_cat_entry(val);
1668 map.target_usr(patron.id());
1669 var t = patron.stat_cat_entries();
1672 patron.stat_cat_entries(t);
1677 patron.ischanged(1);
1678 fieldmapper.standardRequest(
1679 ['open-ils.actor', 'open-ils.actor.patron.update'],
1681 params: [openils.User.authtoken, patron],
1682 oncomplete: function(r) {
1684 if (xulG && typeof xulG.unlock_tab == 'function') {
1686 already_locked = false;
1688 /* There's something that seems to just make the form reload
1689 * on all saves, so this uUpdate... isn't needed here after
1691 //uUpdateContactInvalidators();
1693 newPatron = openils.Util.readResponse(r);
1695 uEditUpdateUserSettings(newPatron.id());
1696 if(stageUser) uEditRemoveStage();
1697 uEditFinishSave(newPatron, doClone);
1704 function uUpdateContactInvalidators() {
1705 /* show invalidator buttons for fields that having anything in them */
1706 ["email", "day_phone", "evening_phone", "other_phone"].forEach(
1708 openils.Util[patron[f]() ? "show" : "hide"]("wrap_invalidate_" + f);
1713 function uGenerateInvalidatorWidget(container_node, field) {
1714 new dijit.form.Button(
1716 "label": localeStrings.INVALIDATE,
1717 "scrollOnFocus": false,
1718 "onClick": function() {
1719 progressDialog.show(true);
1720 fieldmapper.standardRequest(
1721 ["open-ils.actor", "open-ils.actor.invalidate." + field], {
1723 "params": [openils.User.authtoken, patron.id(), null, patron.home_ou()],
1724 "oncomplete": function(r) {
1725 progressDialog.hide();
1726 // alerts on non-success event
1727 var res = openils.Util.readResponse(r);
1729 if (res.payload.last_xact_id) {
1730 for (var id in res.payload.last_xact_id) {
1731 if (patron.id() == id)
1732 patron.last_xact_id(
1733 res.payload.last_xact_id[id]
1737 findWidget("au",field).widget.attr("value","");
1738 openils.Util.hide(container_node);
1744 }, dojo.create("span", null, container_node, "only")
1748 function uEditRemoveStage() {
1749 var resp = fieldmapper.standardRequest(
1750 ['open-ils.actor', 'open-ils.actor.user.stage.delete'],
1751 { params : [openils.User.authtoken, stageUser.row_id()] }
1755 function uEditFinishSave(newPatron, doClone) {
1757 if(doClone && cloneUser == null)
1758 cloneUser = newPatron.id();
1762 if(xulG && typeof xulG.spawn_editor == 'function' && !patron.isnew() ) {
1763 window.xulG.spawn_editor({ses:openils.User.authtoken,clone:cloneUser});
1767 location.href = location.href.replace(/\?.*/, '') + '?clone=' + cloneUser;
1775 uEditRefreshXUL(newPatron);
1778 function uEditRefresh() {
1779 var usr = cgi.param('usr');
1780 var href = location.href.replace(/\?.*/, '');
1781 href += ((usr) ? '?usr=' + usr : '');
1782 location.href = href;
1785 function uEditRefreshXUL(newuser) {
1786 if (window.xulG && typeof window.xulG.on_save == 'function')
1787 window.xulG.on_save(newuser);
1792 * Create a new address and insert it into the DOM
1793 * @param evt ignored
1794 * @param id The address id
1795 * @param mkLinks If true, set the new address as the
1796 * mailing/billing address for the user
1798 function uEditNewAddr(evt, id, mkLinks) {
1801 id = --uEditAddrVirtId; // new address
1803 var addr = patron.addresses().filter(
1804 function(i) { return (i.id() == id) })[0];
1806 dojo.forEach(addrTemplateRows,
1809 row = tbody.insertBefore(row.cloneNode(true), dojo.byId('new-addr-row'));
1810 row.setAttribute('type', '');
1811 row.setAttribute('addr', id+'');
1813 if(row.getAttribute('fmclass')) {
1814 var widget = fleshFMRow(row, 'aua', {addr:id});
1816 // make new addresses a default address type
1817 if(id < 0 && row.getAttribute('fmfield') == 'address_type')
1818 widget.widget.attr('value', localeStrings.DEFAULT_ADDRESS_TYPE);
1820 // make new addresses valid by default
1821 if(id < 0 && row.getAttribute('fmfield') == 'valid')
1822 widget.widget.attr('value', true);
1824 // make new addresses use the org setting for default country
1825 if(id < 0 && row.getAttribute('fmfield') == 'country')
1826 widget.widget.attr('value',orgSettings['ui.patron.default_country']);
1828 } else if(row.getAttribute('name') == 'uedit-addr-pending-row') {
1830 // if it's a pending address, show the 'approve' button
1831 if(addr && openils.Util.isTrue(addr.pending())) {
1832 openils.Util.show(row, 'table-row');
1833 dojo.query('[name=approve-button]', row)[0].onclick =
1834 function() { uEditApproveAddress(addr); };
1836 if(addr.replaces()) {
1837 var div = dojo.query('[name=replaced-addr]', row)[0]
1838 var replaced = patron.addresses().filter(
1839 function(i) { return (i.id() == addr.replaces()) })[0];
1841 div.innerHTML = dojo.string.substitute(localeStrings.REPLACED_ADDRESS, [
1842 replaced.address_type() || '',
1843 replaced.street1() || '',
1844 replaced.street2() || '',
1845 replaced.city() || '',
1846 replaced.state() || '',
1847 replaced.post_code() || ''
1851 openils.Util.hide(dojo.query('[name=replaced-addr-div]', row)[0]);
1855 } else if(row.getAttribute('name') == 'uedit-addr-owner-row') {
1856 // address is owned by someone else. provide option to load the
1857 // user in a different tab
1859 if(addr && addr.usr() != patron.id()) {
1860 openils.Util.show(row, 'table-row');
1861 var link = getByName(row, 'addr-owner');
1863 // fetch the linked user so we can present their name in the UI
1865 if(cloneUserObj && cloneUserObj.id() == addr.usr()) {
1867 cloneUserObj.first_given_name(),
1868 cloneUserObj.second_given_name(),
1869 cloneUserObj.family_name()
1872 addrUser = fieldmapper.standardRequest(
1873 ['open-ils.actor', 'open-ils.actor.user.retrieve.parts'],
1875 openils.User.authtoken,
1877 ['first_given_name', 'second_given_name', 'family_name']
1882 link.innerHTML = (addrUser.map(function(name) { return (name) ? name+' ' : '' })+'').replace(/,/g,''); // TODO i18n
1883 link.onclick = function() {
1884 if(openils.XUL.isXUL()) {
1885 window.xulG.spawn_editor({ses:openils.User.authtoken, usr:addr.usr()})
1887 parent.location.href = location.href.replace(/clone=\d+/, 'usr=' + addr.usr());
1892 } else if(row.getAttribute('name') == 'uedit-addr-divider') {
1893 // link up the billing/mailing address and give the inputs IDs so we can access the later
1896 var ba = getByName(row, 'billing_address');
1897 ba.id = 'uedit-billing-address-' + id;
1898 if(mkLinks || (patron.billing_address() && patron.billing_address().id() == id)) {
1900 prevBillingAddress = id;
1904 var ma = getByName(row, 'mailing_address');
1905 ma.id = 'uedit-mailing-address-' + id;
1906 if(mkLinks || (patron.mailing_address() && patron.mailing_address().id() == id)) {
1908 prevMailingAddress = id;
1911 ba.onclick = function() { console.log('ba.onchange ' + id); uEditAddressAlertMarshal(id, true) };
1912 ma.onclick = function() { uEditAddressAlertMarshal(id, false, true) };
1914 var btn = dojo.query('[name=delete-button]', row)[0];
1915 if(btn) btn.onclick = function(){ uEditDeleteAddr(id) };
1921 function uEditApproveAddress(addr) {
1922 fieldmapper.standardRequest(
1923 ['open-ils.actor', 'open-ils.actor.user.pending_address.approve'],
1925 params: [openils.User.authtoken, addr],
1927 oncomplete : function(r) {
1928 var oldId = openils.Util.readResponse(r);
1930 // remove addrs from UI
1933 function(addr) { uEditDeleteAddr(addr.id(), true); }
1938 // remove the replaced address
1939 if(oldId != addr.id()) {
1941 patron.addresses().filter(
1942 function(i) { return (i.id() != oldId); }
1947 // fix the the new address
1949 addr.replaces(null);
1962 function uEditDeleteAddr(id, noAlert) {
1963 if (patron.isnew() && orgSettings['ui.patron.registration.require_address']) {
1964 if (dojo.query('tr[name=uedit-addr-divider]').length < 2) {
1965 alert(localeStrings.NEED_ADDRESS);
1970 if(!confirm(dojo.string.substitute(localeStrings.DELETE_ADDRESS, [id]))) return;
1972 var addr = patron.addresses().filter(function(i){return (i.id() == id)})[0];
1973 if (addr) { addr.isdeleted(1); }
1974 var m_a = patron.mailing_address();
1975 if (typeof m_a == 'object' && m_a != null) { m_a = m_a.id(); }
1976 if (m_a == id) { patron.mailing_address(null); }
1977 var b_a = patron.billing_address();
1978 if (typeof b_a == 'object' && b_a != null) { b_a = b_a.id(); }
1979 if (b_a == id) { patron.billing_address(null); }
1981 var rows = dojo.query('tr[addr='+id+']', tbody);
1982 for(var i = 0; i < rows.length; i++)
1983 rows[i].parentNode.removeChild(rows[i]);
1984 widgetPile = widgetPile.filter(function(w){return (w._addr != id)});
1987 function uEditToggleRequired(level) {
1988 openils.Util.removeCSSClass(tbody, 'hide-non-required');
1989 openils.Util.removeCSSClass(tbody, 'hide-non-suggested');
1990 openils.Util.show('uedit-show-required');
1991 openils.Util.show('uedit-show-required-br');
1992 openils.Util.show('uedit-show-suggested');
1993 openils.Util.show('uedit-show-suggested-br');
1994 openils.Util.show('uedit-show-all');
1997 openils.Util.hide('uedit-show-required');
1998 openils.Util.hide('uedit-show-required-br');
1999 openils.Util.addCSSClass(tbody, 'hide-non-required');
2002 openils.Util.hide('uedit-show-suggested');
2003 openils.Util.hide('uedit-show-suggested-br');
2004 openils.Util.addCSSClass(tbody, 'hide-non-suggested');
2007 openils.Util.hide('uedit-show-all');
2012 function printable_output() {
2013 var temp; var s = '=-=-=-=\r\n';
2014 for (var idx in widgetPile) {
2015 var w = widgetPile[idx];
2016 var val = uEditWidgetVal(w);
2018 if (typeof w.idlField == 'undefined') {
2020 if (w._wtype == 'statcat') {
2021 var stat = statCats.filter(
2023 return (m.id() == w._statcat) })[0];
2024 label = stat.name();
2025 } else if (w._wtype == 'survey') {
2026 var survey = surveys.filter(
2028 return (m.id() == w._survey) })[0];
2029 var question = survey.questions().filter(
2031 return (m.id() == w._question) })[0];
2032 label = survey.name() + ' : ' + question.question();
2037 label = w.idlField.label;
2039 if (temp != w._wtype) {
2043 s += label + ':\t' + (typeof val == 'object' ? '' : val) + '\r\n';
2049 openils.Util.addOnLoad(load);