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;
56 staff = new openils.User().user;
57 pcrud = new openils.PermaCrud();
58 cgi = new openils.CGI();
59 cloneUser = cgi.param('clone');
60 var userId = cgi.param('usr');
61 var stageUname = cgi.param('stage');
64 if(xulG.ses) openils.User.authtoken = xulG.ses;
65 if(typeof xulG.clone != 'undefined') cloneUser = xulG.clone;
66 if(typeof xulG.usr != 'undefined') userId = xulG.usr
67 if(typeof xulG.params != 'undefined') {
68 var parms = xulG.params;
69 if(typeof parms.ses != 'undefined')
70 openils.User.authtoken = parms.ses;
71 if(typeof parms.clone != 'undefined')
72 cloneUser = parms.clone;
73 if(typeof parms.usr != 'undefined')
75 if(typeof parms.stage != 'undefined')
76 stageUname = parms.stage
80 orgSettings = fieldmapper.aou.fetchOrgSettingBatch(staff.ws_ou(), [
81 'global.password_regex',
82 'global.juvenile_age_threshold',
83 'patron.password.use_phone',
84 'ui.patron.default_inet_access_level',
85 'ui.patron.default_ident_type',
86 'ui.patron.default_country',
87 'circ.holds.behind_desk_pickup_supported',
88 'circ.patron_edit.clone.copy_address'
93 orgSettings[k] = orgSettings[k].value;
95 uEditCloneCopyAddr = orgSettings['circ.patron_edit.clone.copy_address'];
96 uEditUsePhonePw = orgSettings['patron.password.use_phone'];
97 uEditFetchUserSettings(userId);
100 patron = uEditLoadUser(userId);
103 patron = uEditLoadStageUser(stageUname);
105 patron = uEditNewPatron();
107 uEditCopyCloneData(patron);
112 var list = pcrud.search('fdoc', {fm_class:fmClasses});
115 if(!fieldDoc[doc.fm_class()])
116 fieldDoc[doc.fm_class()] = {};
117 fieldDoc[doc.fm_class()][doc.field()] = doc;
120 tbody = dojo.byId('uedit-tbody');
122 addrTemplateRows = dojo.query('tr[type=addr-template]', tbody);
123 dojo.forEach(addrTemplateRows, function(row) { row.parentNode.removeChild(row); } );
124 statCatTemplate = tbody.removeChild(dojo.byId('stat-cat-row-template'));
125 surveyTemplate = tbody.removeChild(dojo.byId('survey-row-template'));
126 surveyQuestionTemplate = tbody.removeChild(dojo.byId('survey-question-row-template'));
129 if(patron.isnew() && patron.addresses().length == 0)
130 uEditNewAddr(null, uEditAddrVirtId, true);
134 checkClaimsReturnCountPerm();
135 checkClaimsNoCheckoutCountPerm();
137 dojo.connect(replaceBarcode, 'onClick', replaceCardHandler);
138 dojo.connect(allCards, 'onClick', drawAllCards);
139 if(patron.cards().length > 1)
140 dojo.removeClass(dojo.byId('uedit-all-barcodes'), 'hidden');
142 var input = findWidget('ac', 'barcode');
143 if (patron.isnew()) {
144 replaceBarcode.attr('disabled', true);
146 input.widget.attr('disabled', true).attr('readOnly', true);
151 function drawAllCards() {
153 var tbody = dojo.byId('uedit-all-cards-tbody');
154 if(!allCardsTemplate) {
155 allCardsTemplate = tbody.removeChild(dojo.byId('uedit-all-cards-tr-template'));
157 while(tbody.childNodes[0])
158 tbody.removeChild(tbody.childNodes[0]);
163 [patron.card()].concat(patron.cards()), // grab the main card first
166 if(card.id() == patron.card().id())
169 var row = allCardsTemplate.cloneNode(true);
170 getByName(row, 'barcode').innerHTML = card.barcode();
171 getByName(row, 'active').appendChild(
172 openils.Util.isTrue(card.active()) ?
173 dojo.byId('true').cloneNode(true) :
174 dojo.byId('false').cloneNode(true)
177 tbody.appendChild(row);
182 allCardsDialog.show();
186 * Mark the current card inactive, create a new primary card
188 function replaceCardHandler() {
189 var input = findWidget('ac', 'barcode');
190 input.widget.attr('disabled', false).attr('readOnly', false).attr('value', null).focus();
191 replaceBarcode.attr('disabled', true);
193 // pull old card off the cards list so we don't have a dupe sitting in there
194 var old = patron.cards().filter(function(c){return (c.id() == patron.card().id())})[0];
198 var newc = new fieldmapper.ac();
199 newc.id(uEditCardVirtId--);
203 var t = patron.cards();
211 * Loads a staged user and turns them into something the editor can understand
213 function uEditLoadStageUser(stageUname) {
215 var data = fieldmapper.standardRequest(
216 ['open-ils.actor', 'open-ils.actor.user.stage.retrieve.by_username'],
217 { params : [openils.User.authtoken, stageUname] }
220 stageUser = data.user;
221 patron = uEditNewPatron();
226 // copy the data into our new user object
227 for(var key in fieldmapper.IDL.fmclasses.stgu.field_map) {
228 if(fieldmapper.IDL.fmclasses.au.field_map[key] && !fieldmapper.IDL.fmclasses.stgu.field_map[key].virtual) {
229 if(data.user[key]() !== null)
230 patron[key]( data.user[key]() );
234 // copy the data into our new address objects
235 // TODO: uses the first mailing address only
236 if(data.mailing_addresses.length) {
238 var mail_addr = new fieldmapper.aua();
239 mail_addr.id(-1); // virtual ID
242 patron.mailing_address(mail_addr);
243 var t = patron.addresses();
248 for(var key in fieldmapper.IDL.fmclasses.stgma.field_map) {
249 if(fieldmapper.IDL.fmclasses.aua.field_map[key] && !fieldmapper.IDL.fmclasses.stgma.field_map[key].virtual) {
250 if(data.mailing_addresses[0][key]() !== null)
251 mail_addr[key]( data.mailing_addresses[0][key]() );
256 // copy the data into our new address objects
257 // TODO uses the first billing address only
258 if(data.billing_addresses.length) {
260 var bill_addr = new fieldmapper.aua();
261 bill_addr.id(-2); // virtual ID
264 patron.billing_address(bill_addr);
265 var t = patron.addresses();
270 for(var key in fieldmapper.IDL.fmclasses.stgba.field_map) {
271 if(fieldmapper.IDL.fmclasses.aua.field_map[key] && !fieldmapper.IDL.fmclasses.stgba.field_map[key].virtual) {
272 if(data.billing_addresses[0][key]() !== null)
273 bill_addr[key]( data.billing_addresses[0][key]() );
278 // TODO: uses the first card only
279 if(data.cards.length) {
280 var card = new fieldmapper.ac();
281 card.id(-1); // virtual ID
282 patron.card().barcode(data.cards[0].barcode());
289 * clone the home org, phone numbers, and billing/mailing address
291 function uEditCopyCloneData(patron) {
292 cloneUserObj = uEditLoadUser(cloneUser);
302 if(!uEditCloneCopyAddr)
303 cloneFields = cloneFields.concat(['mailing_address', 'billing_address']);
308 patron[field](cloneUserObj[field]());
312 if(uEditCloneCopyAddr) {
313 var billAddr, mailAddr;
315 // copy the billing and mailing addresses into new addresses
316 function cloneAddr(addr) {
317 var newAddr = addr.clone();
319 newAddr.id(uEditAddrVirtId--);
320 newAddr.usr(patron.id());
321 patron.addresses().push(newAddr);
325 if(billAddr = cloneUserObj.billing_address())
326 patron.billing_address(cloneAddr(billAddr));
328 if(mailAddr = cloneUserObj.mailing_address()) {
329 if (billAddr && billAddr.id() == mailAddr.id()) {
330 patron.mailing_address(patron.billing_address());
332 patron.mailing_address(cloneAddr(mailAddr));
336 if(!billAddr) // if there was no billing addr, use the mailing addr
337 patron.billing_address(patron.mailing_address());
341 // link the billing and mailing addresses
342 if(patron.billing_address()) {
343 var t = patron.addresses();
345 t.push(patron.billing_address());
349 if(patron.mailing_address() && (
350 patron.addresses().length == 0 ||
351 patron.mailing_address().id() != patron.billing_address().id()) ) {
352 var t = patron.addresses();
354 t.push(patron.mailing_address());
361 function uEditFetchUserSettings(userId) {
363 var baseNode = fieldmapper.aou.findOrgUnit(staff.ws_ou());
364 var orgs = fieldmapper.aou.orgNodeTrail(baseNode);
365 orgs = orgs.map(function(node) { return node.id(); });
367 /* fetch any user setting types we need + any that offer opt-in */
368 userSettingTypes = pcrud.search('cust', {
370 {name:['circ.holds_behind_desk']},
373 select : {atevdef : ['opt_in_setting']},
375 // we only care about opt-in settings for event_defs our users encounter
376 where : {'+atevdef' : {owner : orgs}}
382 var names = userSettingTypes.map(function(obj) { return obj.name() });
384 /* fetch any values set for this user */
385 userSettings = fieldmapper.standardRequest(
386 ['open-ils.actor', 'open-ils.actor.patron.settings.retrieve'],
387 {params : [openils.User.authtoken, userId, names]});
391 function uEditLoadUser(userId) {
392 var patron = fieldmapper.standardRequest(
393 ['open-ils.actor', 'open-ils.actor.user.fleshed.retrieve'],
394 {params : [openils.User.authtoken, userId]}
396 openils.Event.parse_and_raise(patron);
400 function loadStaticFields() {
401 for(var idx = 0; tbody.childNodes[idx]; idx++) {
402 var row = tbody.childNodes[idx];
403 if(row.nodeType != row.ELEMENT_NODE) continue;
404 var fmcls = row.getAttribute('fmclass');
406 fleshFMRow(row, fmcls);
409 if(row.id == 'uedit-settings-divider') {
411 var template = tbody.removeChild(dojo.byId('uedit-user-setting-template'));
412 dojo.forEach(userSettingTypes, function(type) { uEditDrawSettingRow(tbody, row, template, type); } );
414 if(userSettingTypes.length > 1 || orgSettings['circ.holds.behind_desk_pickup_supported']) {
415 openils.Util.show('uedit-settings-divider', 'table-row');
422 function uEditDrawSettingRow(tbody, dividerRow, template, stype) {
423 var row = template.cloneNode(true);
424 row.setAttribute('user_setting', stype.name());
425 getByName(row, 'label').innerHTML = stype.label();
426 var cb = new dijit.form.CheckBox({scrollOnFocus:false}, getByName(row, 'widget'));
427 cb.attr('value', userSettings[stype.name()]);
428 dojo.connect(cb, 'onChange', function(newVal) { userSettingsToUpdate[stype.name()] = newVal; });
429 tbody.insertBefore(row, dividerRow.nextSibling);
430 openils.Util.show(row, 'table-row');
433 function uEditUpdateUserSettings(userId) {
434 return fieldmapper.standardRequest(
435 ['open-ils.actor', 'open-ils.actor.patron.settings.update'],
436 {params : [openils.User.authtoken, userId, userSettingsToUpdate]});
439 function loadAllAddrs() {
440 dojo.forEach(patron.addresses(),
442 uEditNewAddr(null, addr.id());
447 function loadStatCats() {
449 statCats = fieldmapper.standardRequest(
450 ['open-ils.circ', 'open-ils.circ.stat_cat.actor.retrieve.all'],
451 {params : [openils.User.authtoken, staff.ws_ou()]}
455 for(var idx in statCats) {
456 var stat = statCats[idx];
457 var row = statCatTemplate.cloneNode(true);
458 row.id = 'stat-cat-row-' + idx;
459 row.setAttribute('stat_cat_owner',stat.owner());
460 row.setAttribute('stat_cat_name',stat.name());
461 row.setAttribute('stat_cat_id',stat.id());
462 tbody.appendChild(row);
463 getByName(row, 'name').innerHTML = stat.name();
464 var valtd = getByName(row, 'widget');
465 var span = valtd.appendChild(document.createElement('span'));
466 var store = new dojo.data.ItemFileReadStore(
467 {data:fieldmapper.actsc.toStoreData(stat.entries())});
468 var comboBox = new dijit.form.ComboBox({store:store,scrollOnFocus:false}, span);
469 comboBox.labelAttr = 'value';
470 comboBox.searchAttr = 'value';
472 comboBox._wtype = 'statcat';
473 comboBox._statcat = stat.id();
474 widgetPile.push(comboBox);
476 // populate existing cats
477 var map = patron.stat_cat_entries().filter(
478 function(mp) { return (mp.stat_cat() == stat.id()) })[0];
479 if(map) comboBox.attr('value', map.stat_cat_entry());
484 function loadSurveys() {
486 surveys = fieldmapper.standardRequest(
487 ['open-ils.circ', 'open-ils.circ.survey.retrieve.all'],
488 {params : [openils.User.authtoken]}
492 for(var idx in surveys) {
493 var survey = surveys[idx];
494 var srow = surveyTemplate.cloneNode(true);
495 tbody.appendChild(srow);
496 getByName(srow, 'name').innerHTML = survey.name();
498 for(var q in survey.questions()) {
499 var quest = survey.questions()[q];
500 var qrow = surveyQuestionTemplate.cloneNode(true);
501 tbody.appendChild(qrow);
502 getByName(qrow, 'question').innerHTML = quest.question();
504 var span = getByName(qrow, 'answers').appendChild(document.createElement('span'));
505 var store = new dojo.data.ItemFileReadStore(
506 {data:fieldmapper.asva.toStoreData(quest.answers())});
507 var select = new dijit.form.FilteringSelect({store:store,scrollOnFocus:false}, span);
508 if (! openils.Util.isTrue(survey.required())) {
509 select.isValid = function() { return true; };
511 select.labelAttr = 'answer';
512 select.searchAttr = 'answer';
514 select._wtype = 'survey';
515 select._survey = survey.id();
516 select._question = quest.id();
517 widgetPile.push(select);
523 function fleshFMRow(row, fmcls, args) {
524 var fmfield = row.getAttribute('fmfield');
525 var wclass = row.getAttribute('wclass');
526 var wstyle = row.getAttribute('wstyle');
527 var wconstraints = row.getAttribute('wconstraints');
528 /* use CSS to set the zindex for widgets you want to disable. */
529 var disabled = dojo.style(row, 'zIndex') == -1 ? true : false;
531 var isPasswd2 = (fmfield == 'passwd2');
532 if(isPasswd2) fmfield = 'passwd';
533 var fieldIdl = fieldmapper.IDL.fmclasses[fmcls].field_map[fmfield];
536 var existing = dojo.query('td', row);
537 var htd = existing[0] || row.appendChild(document.createElement('td'));
538 var ltd = existing[1] || row.appendChild(document.createElement('td'));
539 var wtd = existing[2] || row.appendChild(document.createElement('td'));
541 openils.Util.addCSSClass(htd, 'uedit-help');
542 if(fieldDoc[fmcls] && fieldDoc[fmcls][fmfield]) {
543 var link = dojo.byId('uedit-help-template').cloneNode(true);
545 link.onclick = function() { ueLoadContextHelp(fmcls, fmfield) };
546 openils.Util.removeCSSClass(link, 'hidden');
547 htd.appendChild(link);
550 if(!ltd.textContent) {
551 var span = document.createElement('span');
552 ltd.appendChild(document.createTextNode(fieldIdl.label));
555 span = document.createElement('span');
556 wtd.appendChild(span);
560 case 'au' : fmObject = patron; break;
561 case 'ac' : fmObject = patron.card(); break;
563 fmObject = patron.addresses().filter(
564 function(i) { return (i.id() == args.addr) })[0];
565 if(fmObject && fmObject.usr() != patron.id())
570 var required = row.getAttribute('required') == 'required';
572 // password data is not fetched/required/displayed for existing users
573 if(!patron.isnew() && 'passwd' == fmfield)
579 constraints : (wconstraints) ? eval('('+wconstraints+')') : {}, // the ()'s prevent Invalid Label errors with eval
583 if(fmcls == 'au' && fmfield == 'passwd') {
584 if (orgSettings['global.password_regex']) {
585 dijitArgs.regExp = orgSettings['global.password_regex'];
589 // TODO RSN: Add Setting!
590 if(fmcls == 'au' && fmfield == 'dob')
591 dijitArgs.popupClass = "";
593 var value = row.getAttribute('wvalue');
595 dijitArgs.value = value;
602 widgetClass : wclass,
603 dijitArgs : dijitArgs,
604 orgDefaultsToWs : true,
605 orgLimitPerms : ['UPDATE_USER'],
608 if(fmfield == 'profile') {
609 // fetch profile groups non-async so existing expire_date is
610 // not overwritten when the profile groups arrive and update
611 wargs.forceSync = true;
612 wargs.disableQuery = {usergroup : 'f'};
614 wargs.forceSync = false;
617 var widget = new openils.widget.AutoFieldWidget(wargs);
620 // now put it back before we register the widget
621 if(isPasswd2) fmfield = 'passwd2';
623 widget._wtype = fmcls;
624 widget._fmfield = fmfield;
625 widget._addr = args.addr;
626 widgetPile.push(widget);
627 attachWidgetEvents(fmcls, fmfield, widget);
631 function findWidget(wtype, fmfield, callback) {
632 return widgetPile.filter(
634 if(i._wtype == wtype && i._fmfield == fmfield) {
635 if(callback) return callback(i);
643 * if the user does not have the UPDATE_PATRON_CLAIM_RETURN_COUNT,
644 * they are not allowed to directly alter the claim return count.
645 * This function checks the perm and disable/enables the widget.
647 function checkClaimsReturnCountPerm() {
648 new openils.User().getPermOrgList(
649 'UPDATE_PATRON_CLAIM_RETURN_COUNT',
651 var cr = findWidget('au', 'claims_returned_count');
652 if(orgList.indexOf(patron.home_ou()) == -1)
653 cr.widget.attr('disabled', true);
655 cr.widget.attr('disabled', false);
663 function checkClaimsNoCheckoutCountPerm() {
664 new openils.User().getPermOrgList(
665 'UPDATE_PATRON_CLAIM_NEVER_CHECKED_OUT_COUNT',
667 var cr = findWidget('au', 'claims_never_checked_out_count');
668 if(orgList.indexOf(patron.home_ou()) == -1)
669 cr.widget.attr('disabled', true);
671 cr.widget.attr('disabled', false);
679 function attachWidgetEvents(fmcls, fmfield, widget) {
682 if(fmfield == 'barcode') {
683 dojo.connect(widget.widget, 'onChange',
685 var barcode = this.attr('value');
687 dojo.addClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
688 fieldmapper.standardRequest(
689 ['open-ils.actor', 'open-ils.actor.barcode.exists'],
691 params: [openils.User.authtoken, barcode],
692 oncomplete : function(r) {
693 var res = openils.Util.readResponse(r);
696 dojo.removeClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
699 dojo.addClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
700 var un = findWidget('au', 'usrname');
701 if(!un.widget.attr('value'))
702 un.widget.attr('value', barcode);
717 dojo.connect(widget.widget, 'onChange',
719 var input = findWidget('au', 'usrname');
720 var usrname = input.widget.attr('value');
724 dojo.addClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
728 fieldmapper.standardRequest(
729 ['open-ils.actor', 'open-ils.actor.username.exists'],
731 params: [openils.User.authtoken, usrname],
732 oncomplete : function(r) {
733 var res = openils.Util.readResponse(r);
736 dojo.removeClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
739 dojo.addClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
749 case 'profile': // when the profile changes, update the expire date
750 dojo.connect(widget.widget, 'onChange',
753 var expireWidget = findWidget('au', 'expire_date');
754 function found(items) {
755 if(items.length == 0) return;
757 var interval = self.store.getValue(item, 'perm_interval');
758 expireWidget.widget.attr('value', dojo.date.add(new Date(),
759 'second', openils.Util.intervalToSeconds(interval)));
761 this.store.fetch({onComplete:found, query:{id:this.attr('value')}});
767 dojo.connect(widget.widget, 'onChange',
770 var oldDob = patron.dob();
771 if(dojo.date.stamp.fromISOString(oldDob) == newDob) return;
773 var juvInterval = orgSettings['global.juvenile_age_threshold'] || '18 years';
774 var juvWidget = findWidget('au', 'juvenile');
775 var base = new Date();
776 base.setTime(base.getTime() - Number(openils.Util.intervalToSeconds(juvInterval) + '000'));
778 if(newDob <= base) // older than global.juvenile_age_threshold
779 juvWidget.widget.attr('value', false);
781 juvWidget.widget.attr('value', true);
786 case 'first_given_name':
788 dojo.connect(widget.widget, 'onChange',
789 function(newVal) { uEditDupeSearch('name', newVal); });
793 dojo.connect(widget.widget, 'onChange',
794 function(newVal) { uEditDupeSearch('email', newVal); });
799 dojo.connect(widget.widget, 'onChange',
800 function(newVal) { uEditDupeSearch('ident', newVal); });
804 // if configured, use the last for digits of the day phone number as the password
805 if(uEditUsePhonePw && patron.isnew()) {
806 dojo.connect(widget.widget, 'onChange',
808 if(newVal && newVal.length >= 4) {
809 var pw1 = findWidget('au', 'passwd').widget;
810 var pw2 = findWidget('au', 'passwd2').widget;
811 pw1.attr('value', newVal.substring(newVal.length - 4));
812 pw2.attr('value', newVal.substring(newVal.length - 4));
817 case 'evening_phone':
819 dojo.connect(widget.widget, 'onChange',
820 function(newVal) { uEditDupeSearch('phone', newVal); });
824 dojo.connect(widget.widget, 'onChange',
826 checkClaimsReturnCountPerm();
827 checkClaimsNoCheckoutCountPerm();
833 dojo.connect(widget.widget, 'onChange',
835 var pw1 = findWidget('au', 'passwd').widget;
836 var pw2 = findWidget('au', 'passwd2').widget;
837 var preserved_value = pw2.attr('value');
838 // Ensure that the pw2 field match the pw1 field to validate
839 pw2.regExp = newVal.replace(/([.\\^$*+?\(\)\[\]\{\}])/g, '\\$1');
841 pw2.attr('value',preserved_value);
847 if(fmclass = 'aua') {
850 dojo.connect(widget.widget, 'onChange',
852 fieldmapper.standardRequest(
853 ['open-ils.search', 'open-ils.search.zip'],
856 oncomplete : function(r) {
857 var res = openils.Util.readResponse(r);
859 var callback = function(w) { return w._addr == widget._addr; };
860 if(res.city) findWidget('aua', 'city', callback).widget.attr('value', res.city);
861 if(res.state) findWidget('aua', 'state', callback).widget.attr('value', res.state);
862 if(res.county) findWidget('aua', 'county', callback).widget.attr('value', res.county);
863 if(res.alert) alert(res.alert);
874 dojo.connect(widget.widget, 'onChange',
876 var callback = function(w) { return w._addr == widget._addr; };
878 street1 : findWidget('aua', 'street1', callback).widget.attr('value'),
879 street2 : findWidget('aua', 'street2', callback).widget.attr('value'),
880 city : findWidget('aua', 'city', callback).widget.attr('value'),
881 post_code : findWidget('aua', 'post_code', callback).widget.attr('value')
883 if(args.street1 && args.city && args.post_code)
884 uEditDupeSearch('address', args);
892 function uEditDupeSearch(type, value) {
898 openils.Util.hide('uedit-dupe-names-link');
899 var fname = findWidget('au', 'first_given_name').widget.attr('value');
900 var lname = findWidget('au', 'family_name').widget.attr('value');
901 if( !(fname && lname) ) return;
903 first_given_name : {value : fname, group : 0},
904 family_name : {value : lname, group : 0},
909 openils.Util.hide('uedit-dupe-email-link');
910 search = {email : {value : value, group : 0}};
914 openils.Util.hide('uedit-dupe-ident-link');
915 search = {ident : {value : value, group : 2}};
919 openils.Util.hide('uedit-dupe-phone-link');
920 search = {phone : {value : value, group : 2}};
924 openils.Util.hide('uedit-dupe-address-link');
926 dojo.forEach(['street1', 'street2', 'city', 'post_code'],
929 search[field] = {value : value[field], group: 1};
935 // find possible duplicate patrons
936 fieldmapper.standardRequest(
937 ['open-ils.actor', 'open-ils.actor.patron.search.advanced'],
939 params: [openils.User.authtoken, search],
940 oncomplete : function(r) {
941 var resp = openils.Util.readResponse(r);
942 resp = resp.filter(function(id) { return (id != patron.id()); });
944 if(resp && resp.length > 0) {
946 openils.Util.hide('uedit-help-div');
947 openils.Util.show('uedit-dupe-div');
952 link = dojo.byId('uedit-dupe-names-link');
953 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_NAME, [resp.length]);
956 link = dojo.byId('uedit-dupe-email-link');
957 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_EMAIL, [resp.length]);
960 link = dojo.byId('uedit-dupe-ident-link');
961 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_IDENT, [resp.length]);
964 link = dojo.byId('uedit-dupe-phone-link');
965 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_PHONE, [resp.length]);
968 link = dojo.byId('uedit-dupe-address-link');
969 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_ADDR, [resp.length]);
973 openils.Util.show(link);
974 link.onclick = function() {
975 search.search_sort = js2JSON(["penalties", "family_name", "first_given_name"]);
977 window.xulG.spawn_search(search);
979 console.log("running XUL patron search " + js2JSON(search));
987 function getByName(node, name) {
988 return dojo.query('[name='+name+']', node)[0];
992 function ueLoadContextHelp(fmcls, fmfield) {
993 openils.Util.hide('uedit-dupe-div');
994 openils.Util.show('uedit-help-div');
995 dojo.byId('uedit-help-field').innerHTML = fieldmapper.IDL.fmclasses[fmcls].field_map[fmfield].label;
996 dojo.byId('uedit-help-text').innerHTML = fieldDoc[fmcls][fmfield].string();
1000 /* creates a new patron object with card attached */
1001 function uEditNewPatron() {
1006 card.id(uEditCardVirtId--);
1010 patron.cards([card]);
1011 patron.net_access_level(orgSettings['ui.patron.default_inet_access_level'] || 1);
1012 patron.ident_type(orgSettings['ui.patron.default_ident_type']);
1013 patron.stat_cat_entries([]);
1014 patron.survey_responses([]);
1015 patron.addresses([]);
1016 uEditMakeRandomPw(patron);
1020 function uEditMakeRandomPw(patron) {
1021 if(uEditUsePhonePw) return;
1022 var rand = Math.random();
1023 rand = parseInt(rand * 10000) + '';
1024 while(rand.length < 4) rand += '0';
1026 appendClear($('ue_password_plain'),text(rand));
1027 unHideMe($('ue_password_gen'));
1029 patron.passwd(rand);
1033 function uEditWidgetVal(w) {
1034 var val = (w.getFormattedValue) ? w.getFormattedValue() : w.attr('value');
1035 if(val === '') val = null;
1039 function uEditSave() { _uEditSave(); }
1040 function uEditSaveClone() { _uEditSave(true); }
1042 function _uEditSave(doClone) {
1044 if ( (! myForm.isValid()) || dupeUsrname || dupeBarcode ) {
1045 alert(localeStrings.INVALID_FORM);
1049 for(var idx in widgetPile) {
1050 var w = widgetPile[idx];
1051 var val = uEditWidgetVal(w);
1055 if(w._fmfield != 'passwd2')
1056 patron[w._fmfield](val);
1060 patron.card()[w._fmfield](val);
1064 var addr = patron.addresses().filter(function(i){return (i.id() == w._addr)})[0];
1066 addr = new fieldmapper.aua();
1069 addr.usr(patron.id());
1070 addr.country(orgSettings['ui.patron.default_country']);
1071 var t = patron.addresses();
1074 patron.addresses(t);
1076 if(addr[w._fmfield]() != val)
1079 addr[w._fmfield](val);
1081 if(dojo.byId('uedit-billing-address-' + addr.id()).checked)
1082 patron.billing_address(addr.id());
1084 if(dojo.byId('uedit-mailing-address-' + addr.id()).checked)
1085 patron.mailing_address(addr.id());
1090 if(val == null) break;
1091 var resp = new fieldmapper.asvr();
1093 resp.survey(w._survey)
1094 resp.usr(patron.id());
1095 resp.question(w._question)
1097 var t = patron.survey_responses();
1100 patron.survey_responses(t);
1104 if(val == null) break;
1106 var map = patron.stat_cat_entries().filter(
1108 return (m.stat_cat() == w._statcat) })[0];
1111 if(map.stat_cat_entry() == val)
1115 map = new fieldmapper.actscecm();
1119 map.stat_cat(w._statcat);
1120 map.stat_cat_entry(val);
1121 map.target_usr(patron.id());
1122 var t = patron.stat_cat_entries();
1125 patron.stat_cat_entries(t);
1130 patron.ischanged(1);
1131 fieldmapper.standardRequest(
1132 ['open-ils.actor', 'open-ils.actor.patron.update'],
1134 params: [openils.User.authtoken, patron],
1135 oncomplete: function(r) {
1136 newPatron = openils.Util.readResponse(r);
1138 uEditUpdateUserSettings(newPatron.id());
1139 if(stageUser) uEditRemoveStage();
1140 uEditFinishSave(newPatron, doClone);
1147 function uEditRemoveStage() {
1148 var resp = fieldmapper.standardRequest(
1149 ['open-ils.actor', 'open-ils.actor.user.stage.delete'],
1150 { params : [openils.User.authtoken, stageUser.row_id()] }
1154 function uEditFinishSave(newPatron, doClone) {
1156 if(doClone && cloneUser == null)
1157 cloneUser = newPatron.id();
1161 if(xulG && typeof xulG.spawn_editor == 'function' && !patron.isnew() ) {
1162 window.xulG.spawn_editor({ses:openils.User.authtoken,clone:cloneUser});
1166 location.href = location.href.replace(/\?.*/, '') + '?clone=' + cloneUser;
1174 uEditRefreshXUL(newPatron);
1177 function uEditRefresh() {
1178 var usr = cgi.param('usr');
1179 var href = location.href.replace(/\?.*/, '');
1180 href += ((usr) ? '?usr=' + usr : '');
1181 location.href = href;
1184 function uEditRefreshXUL(newuser) {
1185 if (window.xulG && typeof window.xulG.on_save == 'function')
1186 window.xulG.on_save(newuser);
1191 * Create a new address and insert it into the DOM
1192 * @param evt ignored
1193 * @param id The address id
1194 * @param mkLinks If true, set the new address as the
1195 * mailing/billing address for the user
1197 function uEditNewAddr(evt, id, mkLinks) {
1200 id = --uEditAddrVirtId; // new address
1202 var addr = patron.addresses().filter(
1203 function(i) { return (i.id() == id) })[0];
1205 dojo.forEach(addrTemplateRows,
1208 row = tbody.insertBefore(row.cloneNode(true), dojo.byId('new-addr-row'));
1209 row.setAttribute('type', '');
1210 row.setAttribute('addr', id+'');
1212 if(row.getAttribute('fmclass')) {
1213 var widget = fleshFMRow(row, 'aua', {addr:id});
1215 // make new addresses valid by default
1216 if(id < 0 && row.getAttribute('fmfield') == 'valid')
1217 widget.widget.attr('value', true);
1219 // make new addresses use the org setting for default country
1220 if(id < 0 && row.getAttribute('fmfield') == 'country')
1221 widget.widget.attr('value',orgSettings['ui.patron.default_country']);
1223 } else if(row.getAttribute('name') == 'uedit-addr-pending-row') {
1225 // if it's a pending address, show the 'approve' button
1226 if(addr && openils.Util.isTrue(addr.pending())) {
1227 openils.Util.show(row, 'table-row');
1228 dojo.query('[name=approve-button]', row)[0].onclick =
1229 function() { uEditApproveAddress(addr); };
1231 if(addr.replaces()) {
1232 var div = dojo.query('[name=replaced-addr]', row)[0]
1233 var replaced = patron.addresses().filter(
1234 function(i) { return (i.id() == addr.replaces()) })[0];
1236 div.innerHTML = dojo.string.substitute(localeStrings.REPLACED_ADDRESS, [
1237 replaced.address_type() || '',
1238 replaced.street1() || '',
1239 replaced.street2() || '',
1240 replaced.city() || '',
1241 replaced.state() || '',
1242 replaced.post_code() || ''
1246 openils.Util.hide(dojo.query('[name=replaced-addr-div]', row)[0]);
1250 } else if(row.getAttribute('name') == 'uedit-addr-owner-row') {
1251 // address is owned by someone else. provide option to load the
1252 // user in a different tab
1254 if(addr && addr.usr() != patron.id()) {
1255 openils.Util.show(row, 'table-row');
1256 var link = getByName(row, 'addr-owner');
1258 // fetch the linked user so we can present their name in the UI
1260 if(cloneUserObj && cloneUserObj.id() == addr.usr()) {
1262 cloneUserObj.first_given_name(),
1263 cloneUserObj.second_given_name(),
1264 cloneUserObj.family_name()
1267 addrUser = fieldmapper.standardRequest(
1268 ['open-ils.actor', 'open-ils.actor.user.retrieve.parts'],
1270 openils.User.authtoken,
1272 ['first_given_name', 'second_given_name', 'family_name']
1277 link.innerHTML = (addrUser.map(function(name) { return (name) ? name+' ' : '' })+'').replace(/,/g,''); // TODO i18n
1278 link.onclick = function() {
1279 if(openils.XUL.isXUL()) {
1280 window.xulG.spawn_editor({ses:openils.User.authtoken, usr:addr.usr()})
1282 parent.location.href = location.href.replace(/clone=\d+/, 'usr=' + addr.usr());
1287 } else if(row.getAttribute('name') == 'uedit-addr-divider') {
1288 // link up the billing/mailing address and give the inputs IDs so we can acces the later
1291 var ba = getByName(row, 'billing_address');
1292 ba.id = 'uedit-billing-address-' + id;
1293 if(mkLinks || (patron.billing_address() && patron.billing_address().id() == id))
1297 var ma = getByName(row, 'mailing_address');
1298 ma.id = 'uedit-mailing-address-' + id;
1299 if(mkLinks || (patron.mailing_address() && patron.mailing_address().id() == id))
1302 var btn = dojo.query('[name=delete-button]', row)[0];
1303 if(btn) btn.onclick = function(){ uEditDeleteAddr(id) };
1309 function uEditApproveAddress(addr) {
1310 fieldmapper.standardRequest(
1311 ['open-ils.actor', 'open-ils.actor.user.pending_address.approve'],
1313 params: [openils.User.authtoken, addr],
1315 oncomplete : function(r) {
1316 var oldId = openils.Util.readResponse(r);
1318 // remove addrs from UI
1321 function(addr) { uEditDeleteAddr(addr.id(), true); }
1326 // remove the replaced address
1327 if(oldId != addr.id()) {
1329 patron.addresses().filter(
1330 function(i) { return (i.id() != oldId); }
1335 // fix the the new address
1337 addr.replaces(null);
1350 function uEditDeleteAddr(id, noAlert) {
1352 if(!confirm('Delete address ' + id)) return; /* XXX i18n */
1354 var addr = patron.addresses().filter(function(i){return (i.id() == id)})[0];
1355 if (addr) { addr.isdeleted(1); }
1356 var m_a = patron.mailing_address();
1357 if (typeof m_a == 'object' && m_a != null) { m_a = m_a.id(); }
1358 if (m_a == id) { patron.mailing_address(null); }
1359 var b_a = patron.billing_address();
1360 if (typeof b_a == 'object' && b_a != null) { b_a = b_a.id(); }
1361 if (b_a == id) { patron.billing_address(null); }
1363 var rows = dojo.query('tr[addr='+id+']', tbody);
1364 for(var i = 0; i < rows.length; i++)
1365 rows[i].parentNode.removeChild(rows[i]);
1366 widgetPile = widgetPile.filter(function(w){return (w._addr != id)});
1369 function uEditToggleRequired() {
1370 if((tbody.className +'').match(/hide-non-required/))
1371 openils.Util.removeCSSClass(tbody, 'hide-non-required');
1373 openils.Util.addCSSClass(tbody, 'hide-non-required');
1374 openils.Util.toggle('uedit-show-required');
1375 openils.Util.toggle('uedit-show-all');
1378 function printable_output() {
1379 var temp; var s = '=-=-=-=\r\n';
1380 for (var idx in widgetPile) {
1381 var w = widgetPile[idx];
1382 var val = uEditWidgetVal(w);
1384 if (typeof w.idlField == 'undefined') {
1386 if (w._wtype == 'statcat') {
1387 var stat = statCats.filter(
1389 return (m.id() == w._statcat) })[0];
1390 label = stat.name();
1391 } else if (w._wtype == 'survey') {
1392 var survey = surveys.filter(
1394 return (m.id() == w._survey) })[0];
1395 var question = survey.questions().filter(
1397 return (m.id() == w._question) })[0];
1398 label = survey.name() + ' : ' + question.question();
1403 label = w.idlField.label;
1405 if (temp != w._wtype) {
1409 s += label + ':\t' + (typeof val == 'object' ? '' : val) + '\r\n';
1415 openils.Util.addOnLoad(load);