1 dojo.require('dojo.data.ItemFileReadStore');
2 dojo.require('dijit.form.Form');
3 dojo.require('dijit.form.Textarea');
4 dojo.require('dijit.form.FilteringSelect');
5 dojo.require('dijit.form.ComboBox');
6 dojo.require('dijit.form.NumberSpinner');
7 dojo.require('fieldmapper.IDL');
8 dojo.require('openils.PermaCrud');
9 dojo.require('openils.widget.AutoGrid');
10 dojo.require('openils.widget.AutoFieldWidget');
11 dojo.require('dijit.form.CheckBox');
12 dojo.require('dijit.form.Button');
13 dojo.require('dojo.date');
14 dojo.require('openils.CGI');
15 dojo.require('openils.XUL');
16 dojo.require('openils.Util');
17 dojo.require('openils.Event');
19 dojo.requireLocalization('openils.actor', 'register');
20 var localeStrings = dojo.i18n.getLocalization('openils.actor', 'register');
24 var fmClasses = ['au', 'ac', 'aua', 'actsc', 'asv', 'asvq', 'asva'];
31 var uEditUsePhonePw = false;
33 var uEditCardVirtId = -1;
34 var uEditAddrVirtId = -1;
36 var userSettings = {};
37 var userSettingsToUpdate = {};
47 var uEditCloneCopyAddr; // if true, copy addrs on clone instead of link
49 var dupeUsrname = false;
50 var dupeBarcode = false;
52 if(!window.xulG) var xulG = null;
53 var lock_ready = false;
54 var already_locked = false;
57 staff = new openils.User().user;
58 pcrud = new openils.PermaCrud();
59 cgi = new openils.CGI();
60 cloneUser = cgi.param('clone');
61 var userId = cgi.param('usr');
62 var stageUname = cgi.param('stage');
65 if(xulG.ses) openils.User.authtoken = xulG.ses;
66 if(typeof xulG.clone != 'undefined') cloneUser = xulG.clone;
67 if(typeof xulG.usr != 'undefined') userId = xulG.usr
68 if(typeof xulG.params != 'undefined') {
69 var parms = xulG.params;
70 if(typeof parms.ses != 'undefined')
71 openils.User.authtoken = parms.ses;
72 if(typeof parms.clone != 'undefined')
73 cloneUser = parms.clone;
74 if(typeof parms.usr != 'undefined')
76 if(typeof parms.stage != 'undefined')
77 stageUname = parms.stage
81 orgSettings = fieldmapper.aou.fetchOrgSettingBatch(staff.ws_ou(), [
82 'global.password_regex',
83 'global.juvenile_age_threshold',
84 'patron.password.use_phone',
85 'ui.patron.default_inet_access_level',
86 'ui.patron.default_ident_type',
87 'ui.patron.default_country',
88 'ui.patron.registration.require_address',
89 'circ.holds.behind_desk_pickup_supported',
90 'circ.patron_edit.clone.copy_address'
95 orgSettings[k] = orgSettings[k].value;
97 uEditCloneCopyAddr = orgSettings['circ.patron_edit.clone.copy_address'];
98 uEditUsePhonePw = orgSettings['patron.password.use_phone'];
99 uEditFetchUserSettings(userId);
102 patron = uEditLoadUser(userId);
105 patron = uEditLoadStageUser(stageUname);
107 patron = uEditNewPatron();
109 uEditCopyCloneData(patron);
114 var list = pcrud.search('fdoc', {fm_class:fmClasses});
117 if(!fieldDoc[doc.fm_class()])
118 fieldDoc[doc.fm_class()] = {};
119 fieldDoc[doc.fm_class()][doc.field()] = doc;
122 tbody = dojo.byId('uedit-tbody');
124 addrTemplateRows = dojo.query('tr[type=addr-template]', tbody);
125 dojo.forEach(addrTemplateRows, function(row) { row.parentNode.removeChild(row); } );
126 statCatTemplate = tbody.removeChild(dojo.byId('stat-cat-row-template'));
127 surveyTemplate = tbody.removeChild(dojo.byId('survey-row-template'));
128 surveyQuestionTemplate = tbody.removeChild(dojo.byId('survey-question-row-template'));
130 checkGrpAppPerm(); // to do the initial load
132 if(patron.isnew() && patron.addresses().length == 0)
133 uEditNewAddr(null, uEditAddrVirtId, true);
137 checkClaimsReturnCountPerm();
138 checkClaimsNoCheckoutCountPerm();
140 dojo.connect(replaceBarcode, 'onClick', replaceCardHandler);
141 dojo.connect(allCards, 'onClick', drawAllCards);
142 if(patron.cards().length > 1)
143 dojo.removeClass(dojo.byId('uedit-all-barcodes'), 'hidden');
145 var input = findWidget('ac', 'barcode');
146 if (patron.isnew()) {
147 replaceBarcode.attr('disabled', true);
149 input.widget.attr('disabled', true).attr('readOnly', true);
153 if(!patron.isnew() && !checkGrpAppPerm(patron.profile()) && patron.id() != openils.User.user.id()) {
154 // we are not allowed to edit this user, so disable the save option
155 saveButton.attr('disabled', true);
156 saveCloneButton.attr('disabled', true);
163 var noPermGroups = [];
164 // Returns true if the user is allowed to edit the selected group
165 function checkGrpAppPerm(grpId) {
170 permGroups = new openils.PermaCrud().retrieveAll('pgt');
171 var permGroupPerms = []
173 // collect the group permissions
174 dojo.forEach(permGroups,
176 if(grp.application_perm())
177 permGroupPerms.push(grp.application_perm());
181 // see which of the group application perms I do not have
182 var myPerms = fieldmapper.standardRequest(
183 ['open-ils.actor', 'open-ils.actor.user.has_work_perm_at.batch'],
184 [openils.User.authtoken, permGroupPerms]
187 var failedPerms = [];
188 for(var p in myPerms) {
189 if(myPerms[p].length == 0)
193 // identify which groups I cannot edit because I do not have permisssion
195 function checkTree(grp, failed) {
196 failed = failed || failedPerms.indexOf(grp.application_perm()) > -1;
197 if(failed) noPermGroups.push(grp.id()+'');
199 permGroups.filter(function(g) { return g.parent() == grp.id() } ),
201 checkTree(child, failed);
206 checkTree(permGroups.filter(function(g) { return g.parent() == null })[0]);
209 return noPermGroups.indexOf(grpId+'') == -1;
213 function drawAllCards() {
215 var tbody = dojo.byId('uedit-all-cards-tbody');
216 if(!allCardsTemplate) {
217 allCardsTemplate = tbody.removeChild(dojo.byId('uedit-all-cards-tr-template'));
219 while(tbody.childNodes[0])
220 tbody.removeChild(tbody.childNodes[0]);
225 [patron.card()].concat(patron.cards()), // grab the main card first
228 if(card.id() == patron.card().id())
231 var row = allCardsTemplate.cloneNode(true);
232 getByName(row, 'barcode').innerHTML = card.barcode();
233 getByName(row, 'active').appendChild(
234 openils.Util.isTrue(card.active()) ?
235 dojo.byId('true').cloneNode(true) :
236 dojo.byId('false').cloneNode(true)
239 tbody.appendChild(row);
244 allCardsDialog.show();
248 * Mark the current card inactive, create a new primary card
250 function replaceCardHandler() {
251 var input = findWidget('ac', 'barcode');
252 input.widget.attr('disabled', false).attr('readOnly', false).attr('value', null).focus();
253 replaceBarcode.attr('disabled', true);
255 // pull old card off the cards list so we don't have a dupe sitting in there
256 var old = patron.cards().filter(function(c){return (c.id() == patron.card().id())})[0];
260 var newc = new fieldmapper.ac();
261 newc.id(uEditCardVirtId--);
265 var t = patron.cards();
273 * Loads a staged user and turns them into something the editor can understand
275 function uEditLoadStageUser(stageUname) {
277 var data = fieldmapper.standardRequest(
278 ['open-ils.actor', 'open-ils.actor.user.stage.retrieve.by_username'],
279 { params : [openils.User.authtoken, stageUname] }
282 stageUser = data.user;
283 patron = uEditNewPatron();
288 // copy the data into our new user object
289 for(var key in fieldmapper.IDL.fmclasses.stgu.field_map) {
290 if(fieldmapper.IDL.fmclasses.au.field_map[key] && !fieldmapper.IDL.fmclasses.stgu.field_map[key].virtual) {
291 if(data.user[key]() !== null)
292 patron[key]( data.user[key]() );
296 // copy the data into our new address objects
297 // TODO: uses the first mailing address only
298 if(data.mailing_addresses.length) {
300 var mail_addr = new fieldmapper.aua();
301 mail_addr.id(-1); // virtual ID
304 patron.mailing_address(mail_addr);
305 var t = patron.addresses();
310 for(var key in fieldmapper.IDL.fmclasses.stgma.field_map) {
311 if(fieldmapper.IDL.fmclasses.aua.field_map[key] && !fieldmapper.IDL.fmclasses.stgma.field_map[key].virtual) {
312 if(data.mailing_addresses[0][key]() !== null)
313 mail_addr[key]( data.mailing_addresses[0][key]() );
318 // copy the data into our new address objects
319 // TODO uses the first billing address only
320 if(data.billing_addresses.length) {
322 var bill_addr = new fieldmapper.aua();
323 bill_addr.id(-2); // virtual ID
326 patron.billing_address(bill_addr);
327 var t = patron.addresses();
332 for(var key in fieldmapper.IDL.fmclasses.stgba.field_map) {
333 if(fieldmapper.IDL.fmclasses.aua.field_map[key] && !fieldmapper.IDL.fmclasses.stgba.field_map[key].virtual) {
334 if(data.billing_addresses[0][key]() !== null)
335 bill_addr[key]( data.billing_addresses[0][key]() );
340 // TODO: uses the first card only
341 if(data.cards.length) {
342 var card = new fieldmapper.ac();
343 card.id(-1); // virtual ID
344 patron.card().barcode(data.cards[0].barcode());
351 * clone the home org, phone numbers, and billing/mailing address
353 function uEditCopyCloneData(patron) {
354 cloneUserObj = uEditLoadUser(cloneUser);
364 if(!uEditCloneCopyAddr)
365 cloneFields = cloneFields.concat(['mailing_address', 'billing_address']);
370 patron[field](cloneUserObj[field]());
374 if(uEditCloneCopyAddr) {
375 var billAddr, mailAddr;
377 // copy the billing and mailing addresses into new addresses
378 function cloneAddr(addr) {
379 var newAddr = addr.clone();
381 newAddr.id(uEditAddrVirtId--);
382 newAddr.usr(patron.id());
383 patron.addresses().push(newAddr);
387 if(billAddr = cloneUserObj.billing_address())
388 patron.billing_address(cloneAddr(billAddr));
390 if(mailAddr = cloneUserObj.mailing_address()) {
391 if (billAddr && billAddr.id() == mailAddr.id()) {
392 patron.mailing_address(patron.billing_address());
394 patron.mailing_address(cloneAddr(mailAddr));
398 if(!billAddr) // if there was no billing addr, use the mailing addr
399 patron.billing_address(patron.mailing_address());
403 // link the billing and mailing addresses
404 if(patron.billing_address()) {
405 var t = patron.addresses();
407 t.push(patron.billing_address());
411 if(patron.mailing_address() && (
412 patron.addresses().length == 0 ||
413 patron.mailing_address().id() != patron.billing_address().id()) ) {
414 var t = patron.addresses();
416 t.push(patron.mailing_address());
423 function uEditFetchUserSettings(userId) {
425 var baseNode = fieldmapper.aou.findOrgUnit(staff.ws_ou());
426 var orgs = fieldmapper.aou.orgNodeTrail(baseNode);
427 orgs = orgs.map(function(node) { return node.id(); });
429 /* fetch any user setting types we need + any that offer opt-in */
430 userSettingTypes = pcrud.search('cust', {
432 {name:['circ.holds_behind_desk']},
435 select : {atevdef : ['opt_in_setting']},
437 // we only care about opt-in settings for event_defs our users encounter
438 where : {'+atevdef' : {owner : orgs}}
444 var names = userSettingTypes.map(function(obj) { return obj.name() });
446 /* fetch any values set for this user */
448 userSettings = fieldmapper.standardRequest(
449 ['open-ils.actor', 'open-ils.actor.patron.settings.retrieve.authoritative'],
450 {params : [openils.User.authtoken, userId, names]});
455 function uEditLoadUser(userId) {
456 var patron = fieldmapper.standardRequest(
457 ['open-ils.actor', 'open-ils.actor.user.fleshed.retrieve.authoritative'],
458 {params : [openils.User.authtoken, userId]}
460 openils.Event.parse_and_raise(patron);
464 function loadStaticFields() {
465 for(var idx = 0; tbody.childNodes[idx]; idx++) {
466 var row = tbody.childNodes[idx];
467 if(row.nodeType != row.ELEMENT_NODE) continue;
468 var fmcls = row.getAttribute('fmclass');
470 fleshFMRow(row, fmcls);
473 if(row.id == 'uedit-settings-divider') {
475 var template = tbody.removeChild(dojo.byId('uedit-user-setting-template'));
476 dojo.forEach(userSettingTypes, function(type) { uEditDrawSettingRow(tbody, row, template, type); } );
478 if(userSettingTypes.length > 1 || orgSettings['circ.holds.behind_desk_pickup_supported']) {
479 openils.Util.show('uedit-settings-divider', 'table-row');
486 function uEditDrawSettingRow(tbody, dividerRow, template, stype) {
487 var row = template.cloneNode(true);
488 row.setAttribute('user_setting', stype.name());
489 getByName(row, 'label').innerHTML = stype.label();
490 var cb = new dijit.form.CheckBox({scrollOnFocus:false}, getByName(row, 'widget'));
491 cb.attr('value', userSettings[stype.name()]);
492 dojo.connect(cb, 'onChange', function(newVal) { userSettingsToUpdate[stype.name()] = newVal; });
493 tbody.insertBefore(row, dividerRow.nextSibling);
494 openils.Util.show(row, 'table-row');
497 function uEditUpdateUserSettings(userId) {
498 return fieldmapper.standardRequest(
499 ['open-ils.actor', 'open-ils.actor.patron.settings.update'],
500 {params : [openils.User.authtoken, userId, userSettingsToUpdate]});
503 function loadAllAddrs() {
504 dojo.forEach(patron.addresses(),
506 uEditNewAddr(null, addr.id());
511 function loadStatCats() {
513 statCats = fieldmapper.standardRequest(
514 ['open-ils.circ', 'open-ils.circ.stat_cat.actor.retrieve.all'],
515 {params : [openils.User.authtoken, staff.ws_ou()]}
519 for(var idx in statCats) {
520 var stat = statCats[idx];
521 var row = statCatTemplate.cloneNode(true);
522 row.id = 'stat-cat-row-' + idx;
523 row.setAttribute('stat_cat_owner',stat.owner());
524 row.setAttribute('stat_cat_name',stat.name());
525 row.setAttribute('stat_cat_id',stat.id());
526 tbody.appendChild(row);
527 getByName(row, 'name').innerHTML = stat.name();
528 var valtd = getByName(row, 'widget');
529 var span = valtd.appendChild(document.createElement('span'));
530 var store = new dojo.data.ItemFileReadStore(
531 {data:fieldmapper.actsc.toStoreData(stat.entries())});
532 var comboBox = new dijit.form.ComboBox({store:store,scrollOnFocus:false}, span);
533 comboBox.labelAttr = 'value';
534 comboBox.searchAttr = 'value';
536 comboBox._wtype = 'statcat';
537 comboBox._statcat = stat.id();
538 widgetPile.push(comboBox);
540 // populate existing cats
541 var map = patron.stat_cat_entries().filter(
542 function(mp) { return (mp.stat_cat() == stat.id()) })[0];
543 if(map) comboBox.attr('value', map.stat_cat_entry());
548 function loadSurveys() {
550 surveys = fieldmapper.standardRequest(
551 ['open-ils.circ', 'open-ils.circ.survey.retrieve.all'],
552 {params : [openils.User.authtoken]}
556 for(var idx in surveys) {
557 var survey = surveys[idx];
558 var srow = surveyTemplate.cloneNode(true);
559 tbody.appendChild(srow);
560 getByName(srow, 'name').innerHTML = survey.name();
562 for(var q in survey.questions()) {
563 var quest = survey.questions()[q];
564 var qrow = surveyQuestionTemplate.cloneNode(true);
565 tbody.appendChild(qrow);
566 getByName(qrow, 'question').innerHTML = quest.question();
568 var span = getByName(qrow, 'answers').appendChild(document.createElement('span'));
569 var store = new dojo.data.ItemFileReadStore(
570 {data:fieldmapper.asva.toStoreData(quest.answers())});
571 var select = new dijit.form.FilteringSelect({store:store,scrollOnFocus:false}, span);
572 if (! openils.Util.isTrue(survey.required())) {
573 select.isValid = function() { return true; };
575 select.labelAttr = 'answer';
576 select.searchAttr = 'answer';
578 select._wtype = 'survey';
579 select._survey = survey.id();
580 select._question = quest.id();
581 widgetPile.push(select);
587 function fleshFMRow(row, fmcls, args) {
588 var fmfield = row.getAttribute('fmfield');
589 var wclass = row.getAttribute('wclass');
590 var wstyle = row.getAttribute('wstyle');
591 var wconstraints = row.getAttribute('wconstraints');
592 /* use CSS to set the zindex for widgets you want to disable. */
593 var disabled = dojo.style(row, 'zIndex') == -1 ? true : false;
595 var isPasswd2 = (fmfield == 'passwd2');
596 if(isPasswd2) fmfield = 'passwd';
597 var fieldIdl = fieldmapper.IDL.fmclasses[fmcls].field_map[fmfield];
600 var existing = dojo.query('td', row);
601 var htd = existing[0] || row.appendChild(document.createElement('td'));
602 var ltd = existing[1] || row.appendChild(document.createElement('td'));
603 var wtd = existing[2] || row.appendChild(document.createElement('td'));
605 openils.Util.addCSSClass(htd, 'uedit-help');
606 if(fieldDoc[fmcls] && fieldDoc[fmcls][fmfield]) {
607 var link = dojo.byId('uedit-help-template').cloneNode(true);
609 link.onclick = function() { ueLoadContextHelp(fmcls, fmfield) };
610 openils.Util.removeCSSClass(link, 'hidden');
611 htd.appendChild(link);
614 if(!ltd.textContent) {
615 var span = document.createElement('span');
616 ltd.appendChild(document.createTextNode(fieldIdl.label));
619 span = document.createElement('span');
620 wtd.appendChild(span);
624 case 'au' : fmObject = patron; break;
625 case 'ac' : fmObject = patron.card(); break;
627 fmObject = patron.addresses().filter(
628 function(i) { return (i.id() == args.addr) })[0];
629 if(fmObject && fmObject.usr() != patron.id())
634 var required = row.getAttribute('required') == 'required';
636 // password data is not fetched/required/displayed for existing users
637 if(!patron.isnew() && 'passwd' == fmfield)
643 constraints : (wconstraints) ? eval('('+wconstraints+')') : {}, // the ()'s prevent Invalid Label errors with eval
647 if(fmcls == 'au' && fmfield == 'passwd') {
648 if (orgSettings['global.password_regex']) {
649 dijitArgs.regExp = orgSettings['global.password_regex'];
653 // TODO RSN: Add Setting!
654 if(fmcls == 'au' && fmfield == 'dob')
655 dijitArgs.popupClass = "";
657 var value = row.getAttribute('wvalue');
659 dijitArgs.value = value;
666 widgetClass : wclass,
667 dijitArgs : dijitArgs,
668 orgDefaultsToWs : true,
669 orgLimitPerms : ['UPDATE_USER'],
672 if(fmfield == 'profile') {
673 // fetch profile groups non-async so existing expire_date is
674 // not overwritten when the profile groups arrive and update
675 wargs.forceSync = true;
676 wargs.disableQuery = {usergroup : 'f'};
677 if(!patron.isnew() && !checkGrpAppPerm(patron.profile()))
678 wargs.readOnly = true;
680 wargs.forceSync = false;
683 var widget = new openils.widget.AutoFieldWidget(wargs);
686 if(fmfield == 'profile') { trimGrpTree(ww); }
690 // now put it back before we register the widget
691 if(isPasswd2) fmfield = 'passwd2';
693 widget._wtype = fmcls;
694 widget._fmfield = fmfield;
695 widget._addr = args.addr;
696 widgetPile.push(widget);
697 attachWidgetEvents(fmcls, fmfield, widget);
701 function trimGrpTree(autoWidget) {
702 var store = autoWidget.widget.store;
704 // remove all groups that this user are not allowed to edit,
705 // except the profile group of an existing user
706 store.fetch({onItem :
708 if(!checkGrpAppPerm(item.id[0]) && patron.profile() != item.id[0])
709 store.deleteItem(item);
714 function findWidget(wtype, fmfield, callback) {
715 return widgetPile.filter(
717 if(i._wtype == wtype && i._fmfield == fmfield) {
718 if(callback) return callback(i);
726 * if the user does not have the UPDATE_PATRON_CLAIM_RETURN_COUNT,
727 * they are not allowed to directly alter the claim return count.
728 * This function checks the perm and disable/enables the widget.
730 function checkClaimsReturnCountPerm() {
731 new openils.User().getPermOrgList(
732 'UPDATE_PATRON_CLAIM_RETURN_COUNT',
734 var cr = findWidget('au', 'claims_returned_count');
735 if(orgList.indexOf(patron.home_ou()) == -1)
736 cr.widget.attr('disabled', true);
738 cr.widget.attr('disabled', false);
746 function checkClaimsNoCheckoutCountPerm() {
747 new openils.User().getPermOrgList(
748 'UPDATE_PATRON_CLAIM_NEVER_CHECKED_OUT_COUNT',
750 var cr = findWidget('au', 'claims_never_checked_out_count');
751 if(orgList.indexOf(patron.home_ou()) == -1)
752 cr.widget.attr('disabled', true);
754 cr.widget.attr('disabled', false);
762 function attachWidgetEvents(fmcls, fmfield, widget) {
768 netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
769 if (!(ev.altKey || ev.ctrlKey || ev.metaKey)) {
770 if (lock_ready && xulG && typeof xulG.lock_tab == 'function') {
771 if (! already_locked) {
773 already_locked = true;
783 if (lock_ready && xulG && typeof xulG.lock_tab == 'function') {
784 if (! already_locked) {
786 already_locked = true;
794 if(fmfield == 'barcode') {
795 dojo.connect(widget.widget, 'onChange',
797 var barcode = this.attr('value');
799 dojo.addClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
800 fieldmapper.standardRequest(
801 ['open-ils.actor', 'open-ils.actor.barcode.exists'],
803 params: [openils.User.authtoken, barcode],
804 oncomplete : function(r) {
805 var res = openils.Util.readResponse(r);
808 dojo.removeClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
811 dojo.addClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
812 var un = findWidget('au', 'usrname');
813 if(!un.widget.attr('value'))
814 un.widget.attr('value', barcode);
829 dojo.connect(widget.widget, 'onChange',
831 var input = findWidget('au', 'usrname');
832 var usrname = input.widget.attr('value');
836 dojo.addClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
840 fieldmapper.standardRequest(
841 ['open-ils.actor', 'open-ils.actor.username.exists'],
843 params: [openils.User.authtoken, usrname],
844 oncomplete : function(r) {
845 var res = openils.Util.readResponse(r);
848 dojo.removeClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
851 dojo.addClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
861 case 'profile': // when the profile changes, update the expire date
862 dojo.connect(widget.widget, 'onChange',
865 var expireWidget = findWidget('au', 'expire_date');
866 function found(items) {
867 if(items.length == 0) return;
869 var interval = self.store.getValue(item, 'perm_interval');
870 expireWidget.widget.attr('value', dojo.date.add(new Date(),
871 'second', openils.Util.intervalToSeconds(interval)));
873 this.store.fetch({onComplete:found, query:{id:this.attr('value')}});
879 dojo.connect(widget.widget, 'onChange',
882 var oldDob = patron.dob();
883 if(dojo.date.stamp.fromISOString(oldDob) == newDob) return;
885 var juvInterval = orgSettings['global.juvenile_age_threshold'] || '18 years';
886 var juvWidget = findWidget('au', 'juvenile');
887 var base = new Date();
888 base.setTime(base.getTime() - Number(openils.Util.intervalToSeconds(juvInterval) + '000'));
890 if(newDob <= base) // older than global.juvenile_age_threshold
891 juvWidget.widget.attr('value', false);
893 juvWidget.widget.attr('value', true);
898 case 'first_given_name':
900 dojo.connect(widget.widget, 'onChange',
901 function(newVal) { uEditDupeSearch('name', newVal); });
905 dojo.connect(widget.widget, 'onChange',
906 function(newVal) { uEditDupeSearch('email', newVal); });
911 dojo.connect(widget.widget, 'onChange',
912 function(newVal) { uEditDupeSearch('ident', newVal); });
916 // if configured, use the last for digits of the day phone number as the password
917 if(uEditUsePhonePw && patron.isnew()) {
918 dojo.connect(widget.widget, 'onChange',
920 if(newVal && newVal.length >= 4) {
921 var pw1 = findWidget('au', 'passwd').widget;
922 var pw2 = findWidget('au', 'passwd2').widget;
923 pw1.attr('value', newVal.substring(newVal.length - 4));
924 pw2.attr('value', newVal.substring(newVal.length - 4));
929 case 'evening_phone':
931 dojo.connect(widget.widget, 'onChange',
932 function(newVal) { uEditDupeSearch('phone', newVal); });
936 dojo.connect(widget.widget, 'onChange',
938 checkClaimsReturnCountPerm();
939 checkClaimsNoCheckoutCountPerm();
945 dojo.connect(widget.widget, 'onChange',
947 var pw1 = findWidget('au', 'passwd').widget;
948 var pw2 = findWidget('au', 'passwd2').widget;
949 var preserved_value = pw2.attr('value');
950 // Ensure that the pw2 field match the pw1 field to validate
951 pw2.regExp = newVal.replace(/([.\\^$*+?\(\)\[\]\{\}])/g, '\\$1');
953 pw2.attr('value',preserved_value);
959 if(fmclass = 'aua') {
962 dojo.connect(widget.widget, 'onChange',
964 fieldmapper.standardRequest(
965 ['open-ils.search', 'open-ils.search.zip'],
968 oncomplete : function(r) {
969 var res = openils.Util.readResponse(r);
971 var callback = function(w) { return w._addr == widget._addr; };
972 if(res.city) findWidget('aua', 'city', callback).widget.attr('value', res.city);
973 if(res.state) findWidget('aua', 'state', callback).widget.attr('value', res.state);
974 if(res.county) findWidget('aua', 'county', callback).widget.attr('value', res.county);
975 if(res.alert) alert(res.alert);
986 dojo.connect(widget.widget, 'onChange',
988 var callback = function(w) { return w._addr == widget._addr; };
990 street1 : findWidget('aua', 'street1', callback).widget.attr('value'),
991 street2 : findWidget('aua', 'street2', callback).widget.attr('value'),
992 city : findWidget('aua', 'city', callback).widget.attr('value'),
993 post_code : findWidget('aua', 'post_code', callback).widget.attr('value')
995 if(args.street1 && args.city && args.post_code)
996 uEditDupeSearch('address', args);
1004 function uEditDupeSearch(type, value) {
1010 openils.Util.hide('uedit-dupe-names-link');
1011 var fname = findWidget('au', 'first_given_name').widget.attr('value');
1012 var lname = findWidget('au', 'family_name').widget.attr('value');
1013 if( !(fname && lname) ) return;
1015 first_given_name : {value : fname, group : 0},
1016 family_name : {value : lname, group : 0},
1021 openils.Util.hide('uedit-dupe-email-link');
1022 search = {email : {value : value, group : 0}};
1026 openils.Util.hide('uedit-dupe-ident-link');
1027 search = {ident : {value : value, group : 2}};
1031 openils.Util.hide('uedit-dupe-phone-link');
1032 search = {phone : {value : value, group : 2}};
1036 openils.Util.hide('uedit-dupe-address-link');
1038 dojo.forEach(['street1', 'street2', 'city', 'post_code'],
1041 search[field] = {value : value[field], group: 1};
1047 // find possible duplicate patrons
1048 fieldmapper.standardRequest(
1049 ['open-ils.actor', 'open-ils.actor.patron.search.advanced'],
1051 params: [openils.User.authtoken, search],
1052 oncomplete : function(r) {
1053 var resp = openils.Util.readResponse(r);
1054 resp = resp.filter(function(id) { return (id != patron.id()); });
1056 if(resp && resp.length > 0) {
1058 openils.Util.hide('uedit-help-div');
1059 openils.Util.show('uedit-dupe-div');
1064 link = dojo.byId('uedit-dupe-names-link');
1065 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_NAME, [resp.length]);
1068 link = dojo.byId('uedit-dupe-email-link');
1069 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_EMAIL, [resp.length]);
1072 link = dojo.byId('uedit-dupe-ident-link');
1073 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_IDENT, [resp.length]);
1076 link = dojo.byId('uedit-dupe-phone-link');
1077 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_PHONE, [resp.length]);
1080 link = dojo.byId('uedit-dupe-address-link');
1081 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_ADDR, [resp.length]);
1085 openils.Util.show(link);
1086 link.onclick = function() {
1087 search.search_sort = js2JSON(["penalties", "family_name", "first_given_name"]);
1089 window.xulG.spawn_search(search);
1091 console.log("running XUL patron search " + js2JSON(search));
1099 function getByName(node, name) {
1100 return dojo.query('[name='+name+']', node)[0];
1104 function ueLoadContextHelp(fmcls, fmfield) {
1105 openils.Util.hide('uedit-dupe-div');
1106 openils.Util.show('uedit-help-div');
1107 dojo.byId('uedit-help-field').innerHTML = fieldmapper.IDL.fmclasses[fmcls].field_map[fmfield].label;
1108 dojo.byId('uedit-help-text').innerHTML = fieldDoc[fmcls][fmfield].string();
1112 /* creates a new patron object with card attached */
1113 function uEditNewPatron() {
1118 card.id(uEditCardVirtId--);
1122 patron.cards([card]);
1123 patron.net_access_level(orgSettings['ui.patron.default_inet_access_level'] || 1);
1124 patron.ident_type(orgSettings['ui.patron.default_ident_type']);
1125 patron.stat_cat_entries([]);
1126 patron.survey_responses([]);
1127 patron.addresses([]);
1128 uEditMakeRandomPw(patron);
1132 function uEditMakeRandomPw(patron) {
1133 if(uEditUsePhonePw) return;
1134 var rand = Math.random();
1135 rand = parseInt(rand * 10000) + '';
1136 while(rand.length < 4) rand += '0';
1138 appendClear($('ue_password_plain'),text(rand));
1139 unHideMe($('ue_password_gen'));
1141 patron.passwd(rand);
1145 function uEditWidgetVal(w) {
1146 var val = (w.getFormattedValue) ? w.getFormattedValue() : w.attr('value');
1147 if(val === '') val = null;
1151 function uEditSave() { _uEditSave(); }
1152 function uEditSaveClone() { _uEditSave(true); }
1154 function _uEditSave(doClone) {
1156 if ( (! myForm.isValid()) || dupeUsrname || dupeBarcode ) {
1157 alert(localeStrings.INVALID_FORM);
1161 for(var idx in widgetPile) {
1162 var w = widgetPile[idx];
1163 var val = uEditWidgetVal(w);
1167 if(w._fmfield != 'passwd2')
1168 patron[w._fmfield](val);
1172 patron.card()[w._fmfield](val);
1176 var addr = patron.addresses().filter(function(i){return (i.id() == w._addr)})[0];
1178 addr = new fieldmapper.aua();
1181 addr.usr(patron.id());
1182 addr.country(orgSettings['ui.patron.default_country']);
1183 var t = patron.addresses();
1186 patron.addresses(t);
1188 if(addr[w._fmfield]() != val)
1191 addr[w._fmfield](val);
1193 if(dojo.byId('uedit-billing-address-' + addr.id()).checked)
1194 patron.billing_address(addr.id());
1196 if(dojo.byId('uedit-mailing-address-' + addr.id()).checked)
1197 patron.mailing_address(addr.id());
1202 if(val == null) break;
1203 var resp = new fieldmapper.asvr();
1205 resp.survey(w._survey)
1206 resp.usr(patron.id());
1207 resp.question(w._question)
1209 var t = patron.survey_responses();
1212 patron.survey_responses(t);
1216 var map = patron.stat_cat_entries().filter(
1218 return (m.stat_cat() == w._statcat) })[0];
1221 if(map.stat_cat_entry() == val)
1232 map = new fieldmapper.actscecm();
1236 map.stat_cat(w._statcat);
1237 map.stat_cat_entry(val);
1238 map.target_usr(patron.id());
1239 var t = patron.stat_cat_entries();
1242 patron.stat_cat_entries(t);
1247 patron.ischanged(1);
1248 fieldmapper.standardRequest(
1249 ['open-ils.actor', 'open-ils.actor.patron.update'],
1251 params: [openils.User.authtoken, patron],
1252 oncomplete: function(r) {
1254 if (xulG && typeof xulG.unlock_tab == 'function') {
1256 already_locked = false;
1258 newPatron = openils.Util.readResponse(r);
1260 uEditUpdateUserSettings(newPatron.id());
1261 if(stageUser) uEditRemoveStage();
1262 uEditFinishSave(newPatron, doClone);
1269 function uEditRemoveStage() {
1270 var resp = fieldmapper.standardRequest(
1271 ['open-ils.actor', 'open-ils.actor.user.stage.delete'],
1272 { params : [openils.User.authtoken, stageUser.row_id()] }
1276 function uEditFinishSave(newPatron, doClone) {
1278 if(doClone && cloneUser == null)
1279 cloneUser = newPatron.id();
1283 if(xulG && typeof xulG.spawn_editor == 'function' && !patron.isnew() ) {
1284 window.xulG.spawn_editor({ses:openils.User.authtoken,clone:cloneUser});
1288 location.href = location.href.replace(/\?.*/, '') + '?clone=' + cloneUser;
1296 uEditRefreshXUL(newPatron);
1299 function uEditRefresh() {
1300 var usr = cgi.param('usr');
1301 var href = location.href.replace(/\?.*/, '');
1302 href += ((usr) ? '?usr=' + usr : '');
1303 location.href = href;
1306 function uEditRefreshXUL(newuser) {
1307 if (window.xulG && typeof window.xulG.on_save == 'function')
1308 window.xulG.on_save(newuser);
1313 * Create a new address and insert it into the DOM
1314 * @param evt ignored
1315 * @param id The address id
1316 * @param mkLinks If true, set the new address as the
1317 * mailing/billing address for the user
1319 function uEditNewAddr(evt, id, mkLinks) {
1322 id = --uEditAddrVirtId; // new address
1324 var addr = patron.addresses().filter(
1325 function(i) { return (i.id() == id) })[0];
1327 dojo.forEach(addrTemplateRows,
1330 row = tbody.insertBefore(row.cloneNode(true), dojo.byId('new-addr-row'));
1331 row.setAttribute('type', '');
1332 row.setAttribute('addr', id+'');
1334 if(row.getAttribute('fmclass')) {
1335 var widget = fleshFMRow(row, 'aua', {addr:id});
1337 // make new addresses a default address type
1338 if(id < 0 && row.getAttribute('fmfield') == 'address_type')
1339 widget.widget.attr('value', localeStrings.DEFAULT_ADDRESS_TYPE);
1341 // make new addresses valid by default
1342 if(id < 0 && row.getAttribute('fmfield') == 'valid')
1343 widget.widget.attr('value', true);
1345 // make new addresses use the org setting for default country
1346 if(id < 0 && row.getAttribute('fmfield') == 'country')
1347 widget.widget.attr('value',orgSettings['ui.patron.default_country']);
1349 } else if(row.getAttribute('name') == 'uedit-addr-pending-row') {
1351 // if it's a pending address, show the 'approve' button
1352 if(addr && openils.Util.isTrue(addr.pending())) {
1353 openils.Util.show(row, 'table-row');
1354 dojo.query('[name=approve-button]', row)[0].onclick =
1355 function() { uEditApproveAddress(addr); };
1357 if(addr.replaces()) {
1358 var div = dojo.query('[name=replaced-addr]', row)[0]
1359 var replaced = patron.addresses().filter(
1360 function(i) { return (i.id() == addr.replaces()) })[0];
1362 div.innerHTML = dojo.string.substitute(localeStrings.REPLACED_ADDRESS, [
1363 replaced.address_type() || '',
1364 replaced.street1() || '',
1365 replaced.street2() || '',
1366 replaced.city() || '',
1367 replaced.state() || '',
1368 replaced.post_code() || ''
1372 openils.Util.hide(dojo.query('[name=replaced-addr-div]', row)[0]);
1376 } else if(row.getAttribute('name') == 'uedit-addr-owner-row') {
1377 // address is owned by someone else. provide option to load the
1378 // user in a different tab
1380 if(addr && addr.usr() != patron.id()) {
1381 openils.Util.show(row, 'table-row');
1382 var link = getByName(row, 'addr-owner');
1384 // fetch the linked user so we can present their name in the UI
1386 if(cloneUserObj && cloneUserObj.id() == addr.usr()) {
1388 cloneUserObj.first_given_name(),
1389 cloneUserObj.second_given_name(),
1390 cloneUserObj.family_name()
1393 addrUser = fieldmapper.standardRequest(
1394 ['open-ils.actor', 'open-ils.actor.user.retrieve.parts'],
1396 openils.User.authtoken,
1398 ['first_given_name', 'second_given_name', 'family_name']
1403 link.innerHTML = (addrUser.map(function(name) { return (name) ? name+' ' : '' })+'').replace(/,/g,''); // TODO i18n
1404 link.onclick = function() {
1405 if(openils.XUL.isXUL()) {
1406 window.xulG.spawn_editor({ses:openils.User.authtoken, usr:addr.usr()})
1408 parent.location.href = location.href.replace(/clone=\d+/, 'usr=' + addr.usr());
1413 } else if(row.getAttribute('name') == 'uedit-addr-divider') {
1414 // link up the billing/mailing address and give the inputs IDs so we can acces the later
1417 var ba = getByName(row, 'billing_address');
1418 ba.id = 'uedit-billing-address-' + id;
1419 if(mkLinks || (patron.billing_address() && patron.billing_address().id() == id))
1423 var ma = getByName(row, 'mailing_address');
1424 ma.id = 'uedit-mailing-address-' + id;
1425 if(mkLinks || (patron.mailing_address() && patron.mailing_address().id() == id))
1428 var btn = dojo.query('[name=delete-button]', row)[0];
1429 if(btn) btn.onclick = function(){ uEditDeleteAddr(id) };
1435 function uEditApproveAddress(addr) {
1436 fieldmapper.standardRequest(
1437 ['open-ils.actor', 'open-ils.actor.user.pending_address.approve'],
1439 params: [openils.User.authtoken, addr],
1441 oncomplete : function(r) {
1442 var oldId = openils.Util.readResponse(r);
1444 // remove addrs from UI
1447 function(addr) { uEditDeleteAddr(addr.id(), true); }
1452 // remove the replaced address
1453 if(oldId != addr.id()) {
1455 patron.addresses().filter(
1456 function(i) { return (i.id() != oldId); }
1461 // fix the the new address
1463 addr.replaces(null);
1476 function uEditDeleteAddr(id, noAlert) {
1477 if (patron.isnew() && orgSettings['ui.patron.registration.require_address']) {
1478 if (dojo.query('tr[name=uedit-addr-divider]').length < 2) {
1479 alert(localeStrings.NEED_ADDRESS);
1484 if(!confirm(dojo.string.substitute(localeStrings.DELETE_ADDRESS, [id]))) return;
1486 var addr = patron.addresses().filter(function(i){return (i.id() == id)})[0];
1487 if (addr) { addr.isdeleted(1); }
1488 var m_a = patron.mailing_address();
1489 if (typeof m_a == 'object' && m_a != null) { m_a = m_a.id(); }
1490 if (m_a == id) { patron.mailing_address(null); }
1491 var b_a = patron.billing_address();
1492 if (typeof b_a == 'object' && b_a != null) { b_a = b_a.id(); }
1493 if (b_a == id) { patron.billing_address(null); }
1495 var rows = dojo.query('tr[addr='+id+']', tbody);
1496 for(var i = 0; i < rows.length; i++)
1497 rows[i].parentNode.removeChild(rows[i]);
1498 widgetPile = widgetPile.filter(function(w){return (w._addr != id)});
1501 function uEditToggleRequired() {
1502 if((tbody.className +'').match(/hide-non-required/))
1503 openils.Util.removeCSSClass(tbody, 'hide-non-required');
1505 openils.Util.addCSSClass(tbody, 'hide-non-required');
1506 openils.Util.toggle('uedit-show-required');
1507 openils.Util.toggle('uedit-show-all');
1510 function printable_output() {
1511 var temp; var s = '=-=-=-=\r\n';
1512 for (var idx in widgetPile) {
1513 var w = widgetPile[idx];
1514 var val = uEditWidgetVal(w);
1516 if (typeof w.idlField == 'undefined') {
1518 if (w._wtype == 'statcat') {
1519 var stat = statCats.filter(
1521 return (m.id() == w._statcat) })[0];
1522 label = stat.name();
1523 } else if (w._wtype == 'survey') {
1524 var survey = surveys.filter(
1526 return (m.id() == w._survey) })[0];
1527 var question = survey.questions().filter(
1529 return (m.id() == w._question) })[0];
1530 label = survey.name() + ' : ' + question.question();
1535 label = w.idlField.label;
1537 if (temp != w._wtype) {
1541 s += label + ':\t' + (typeof val == 'object' ? '' : val) + '\r\n';
1547 openils.Util.addOnLoad(load);