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;
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 'ui.patron.registration.require_address',
88 'circ.holds.behind_desk_pickup_supported',
89 'circ.patron_edit.clone.copy_address'
94 orgSettings[k] = orgSettings[k].value;
96 uEditCloneCopyAddr = orgSettings['circ.patron_edit.clone.copy_address'];
97 uEditUsePhonePw = orgSettings['patron.password.use_phone'];
98 uEditFetchUserSettings(userId);
101 patron = uEditLoadUser(userId);
104 patron = uEditLoadStageUser(stageUname);
106 patron = uEditNewPatron();
108 uEditCopyCloneData(patron);
113 var list = pcrud.search('fdoc', {fm_class:fmClasses});
116 if(!fieldDoc[doc.fm_class()])
117 fieldDoc[doc.fm_class()] = {};
118 fieldDoc[doc.fm_class()][doc.field()] = doc;
121 tbody = dojo.byId('uedit-tbody');
123 addrTemplateRows = dojo.query('tr[type=addr-template]', tbody);
124 dojo.forEach(addrTemplateRows, function(row) { row.parentNode.removeChild(row); } );
125 statCatTemplate = tbody.removeChild(dojo.byId('stat-cat-row-template'));
126 surveyTemplate = tbody.removeChild(dojo.byId('survey-row-template'));
127 surveyQuestionTemplate = tbody.removeChild(dojo.byId('survey-question-row-template'));
130 if(patron.isnew() && patron.addresses().length == 0)
131 uEditNewAddr(null, uEditAddrVirtId, true);
135 checkClaimsReturnCountPerm();
136 checkClaimsNoCheckoutCountPerm();
138 dojo.connect(replaceBarcode, 'onClick', replaceCardHandler);
139 dojo.connect(allCards, 'onClick', drawAllCards);
140 if(patron.cards().length > 1)
141 dojo.removeClass(dojo.byId('uedit-all-barcodes'), 'hidden');
143 var input = findWidget('ac', 'barcode');
144 if (patron.isnew()) {
145 replaceBarcode.attr('disabled', true);
147 input.widget.attr('disabled', true).attr('readOnly', true);
154 function drawAllCards() {
156 var tbody = dojo.byId('uedit-all-cards-tbody');
157 if(!allCardsTemplate) {
158 allCardsTemplate = tbody.removeChild(dojo.byId('uedit-all-cards-tr-template'));
160 while(tbody.childNodes[0])
161 tbody.removeChild(tbody.childNodes[0]);
166 [patron.card()].concat(patron.cards()), // grab the main card first
169 if(card.id() == patron.card().id())
172 var row = allCardsTemplate.cloneNode(true);
173 getByName(row, 'barcode').innerHTML = card.barcode();
174 getByName(row, 'active').appendChild(
175 openils.Util.isTrue(card.active()) ?
176 dojo.byId('true').cloneNode(true) :
177 dojo.byId('false').cloneNode(true)
180 tbody.appendChild(row);
185 allCardsDialog.show();
189 * Mark the current card inactive, create a new primary card
191 function replaceCardHandler() {
192 var input = findWidget('ac', 'barcode');
193 input.widget.attr('disabled', false).attr('readOnly', false).attr('value', null).focus();
194 replaceBarcode.attr('disabled', true);
196 // pull old card off the cards list so we don't have a dupe sitting in there
197 var old = patron.cards().filter(function(c){return (c.id() == patron.card().id())})[0];
201 var newc = new fieldmapper.ac();
202 newc.id(uEditCardVirtId--);
206 var t = patron.cards();
214 * Loads a staged user and turns them into something the editor can understand
216 function uEditLoadStageUser(stageUname) {
218 var data = fieldmapper.standardRequest(
219 ['open-ils.actor', 'open-ils.actor.user.stage.retrieve.by_username'],
220 { params : [openils.User.authtoken, stageUname] }
223 stageUser = data.user;
224 patron = uEditNewPatron();
229 // copy the data into our new user object
230 for(var key in fieldmapper.IDL.fmclasses.stgu.field_map) {
231 if(fieldmapper.IDL.fmclasses.au.field_map[key] && !fieldmapper.IDL.fmclasses.stgu.field_map[key].virtual) {
232 if(data.user[key]() !== null)
233 patron[key]( data.user[key]() );
237 // copy the data into our new address objects
238 // TODO: uses the first mailing address only
239 if(data.mailing_addresses.length) {
241 var mail_addr = new fieldmapper.aua();
242 mail_addr.id(-1); // virtual ID
245 patron.mailing_address(mail_addr);
246 var t = patron.addresses();
251 for(var key in fieldmapper.IDL.fmclasses.stgma.field_map) {
252 if(fieldmapper.IDL.fmclasses.aua.field_map[key] && !fieldmapper.IDL.fmclasses.stgma.field_map[key].virtual) {
253 if(data.mailing_addresses[0][key]() !== null)
254 mail_addr[key]( data.mailing_addresses[0][key]() );
259 // copy the data into our new address objects
260 // TODO uses the first billing address only
261 if(data.billing_addresses.length) {
263 var bill_addr = new fieldmapper.aua();
264 bill_addr.id(-2); // virtual ID
267 patron.billing_address(bill_addr);
268 var t = patron.addresses();
273 for(var key in fieldmapper.IDL.fmclasses.stgba.field_map) {
274 if(fieldmapper.IDL.fmclasses.aua.field_map[key] && !fieldmapper.IDL.fmclasses.stgba.field_map[key].virtual) {
275 if(data.billing_addresses[0][key]() !== null)
276 bill_addr[key]( data.billing_addresses[0][key]() );
281 // TODO: uses the first card only
282 if(data.cards.length) {
283 var card = new fieldmapper.ac();
284 card.id(-1); // virtual ID
285 patron.card().barcode(data.cards[0].barcode());
292 * clone the home org, phone numbers, and billing/mailing address
294 function uEditCopyCloneData(patron) {
295 cloneUserObj = uEditLoadUser(cloneUser);
305 if(!uEditCloneCopyAddr)
306 cloneFields = cloneFields.concat(['mailing_address', 'billing_address']);
311 patron[field](cloneUserObj[field]());
315 if(uEditCloneCopyAddr) {
316 var billAddr, mailAddr;
318 // copy the billing and mailing addresses into new addresses
319 function cloneAddr(addr) {
320 var newAddr = addr.clone();
322 newAddr.id(uEditAddrVirtId--);
323 newAddr.usr(patron.id());
324 patron.addresses().push(newAddr);
328 if(billAddr = cloneUserObj.billing_address())
329 patron.billing_address(cloneAddr(billAddr));
331 if(mailAddr = cloneUserObj.mailing_address()) {
332 if (billAddr && billAddr.id() == mailAddr.id()) {
333 patron.mailing_address(patron.billing_address());
335 patron.mailing_address(cloneAddr(mailAddr));
339 if(!billAddr) // if there was no billing addr, use the mailing addr
340 patron.billing_address(patron.mailing_address());
344 // link the billing and mailing addresses
345 if(patron.billing_address()) {
346 var t = patron.addresses();
348 t.push(patron.billing_address());
352 if(patron.mailing_address() && (
353 patron.addresses().length == 0 ||
354 patron.mailing_address().id() != patron.billing_address().id()) ) {
355 var t = patron.addresses();
357 t.push(patron.mailing_address());
364 function uEditFetchUserSettings(userId) {
366 var baseNode = fieldmapper.aou.findOrgUnit(staff.ws_ou());
367 var orgs = fieldmapper.aou.orgNodeTrail(baseNode);
368 orgs = orgs.map(function(node) { return node.id(); });
370 /* fetch any user setting types we need + any that offer opt-in */
371 userSettingTypes = pcrud.search('cust', {
373 {name:['circ.holds_behind_desk']},
376 select : {atevdef : ['opt_in_setting']},
378 // we only care about opt-in settings for event_defs our users encounter
379 where : {'+atevdef' : {owner : orgs}}
385 var names = userSettingTypes.map(function(obj) { return obj.name() });
387 /* fetch any values set for this user */
389 userSettings = fieldmapper.standardRequest(
390 ['open-ils.actor', 'open-ils.actor.patron.settings.retrieve.authoritative'],
391 {params : [openils.User.authtoken, userId, names]});
396 function uEditLoadUser(userId) {
397 var patron = fieldmapper.standardRequest(
398 ['open-ils.actor', 'open-ils.actor.user.fleshed.retrieve.authoritative'],
399 {params : [openils.User.authtoken, userId]}
401 openils.Event.parse_and_raise(patron);
405 function loadStaticFields() {
406 for(var idx = 0; tbody.childNodes[idx]; idx++) {
407 var row = tbody.childNodes[idx];
408 if(row.nodeType != row.ELEMENT_NODE) continue;
409 var fmcls = row.getAttribute('fmclass');
411 fleshFMRow(row, fmcls);
414 if(row.id == 'uedit-settings-divider') {
416 var template = tbody.removeChild(dojo.byId('uedit-user-setting-template'));
417 dojo.forEach(userSettingTypes, function(type) { uEditDrawSettingRow(tbody, row, template, type); } );
419 if(userSettingTypes.length > 1 || orgSettings['circ.holds.behind_desk_pickup_supported']) {
420 openils.Util.show('uedit-settings-divider', 'table-row');
427 function uEditDrawSettingRow(tbody, dividerRow, template, stype) {
428 var row = template.cloneNode(true);
429 row.setAttribute('user_setting', stype.name());
430 getByName(row, 'label').innerHTML = stype.label();
431 var cb = new dijit.form.CheckBox({scrollOnFocus:false}, getByName(row, 'widget'));
432 cb.attr('value', userSettings[stype.name()]);
433 dojo.connect(cb, 'onChange', function(newVal) { userSettingsToUpdate[stype.name()] = newVal; });
434 tbody.insertBefore(row, dividerRow.nextSibling);
435 openils.Util.show(row, 'table-row');
438 function uEditUpdateUserSettings(userId) {
439 return fieldmapper.standardRequest(
440 ['open-ils.actor', 'open-ils.actor.patron.settings.update'],
441 {params : [openils.User.authtoken, userId, userSettingsToUpdate]});
444 function loadAllAddrs() {
445 dojo.forEach(patron.addresses(),
447 uEditNewAddr(null, addr.id());
452 function loadStatCats() {
454 statCats = fieldmapper.standardRequest(
455 ['open-ils.circ', 'open-ils.circ.stat_cat.actor.retrieve.all'],
456 {params : [openils.User.authtoken, staff.ws_ou()]}
460 for(var idx in statCats) {
461 var stat = statCats[idx];
462 var row = statCatTemplate.cloneNode(true);
463 row.id = 'stat-cat-row-' + idx;
464 row.setAttribute('stat_cat_owner',stat.owner());
465 row.setAttribute('stat_cat_name',stat.name());
466 row.setAttribute('stat_cat_id',stat.id());
467 tbody.appendChild(row);
468 getByName(row, 'name').innerHTML = stat.name();
469 var valtd = getByName(row, 'widget');
470 var span = valtd.appendChild(document.createElement('span'));
471 var store = new dojo.data.ItemFileReadStore(
472 {data:fieldmapper.actsc.toStoreData(stat.entries())});
473 var comboBox = new dijit.form.ComboBox({store:store,scrollOnFocus:false}, span);
474 comboBox.labelAttr = 'value';
475 comboBox.searchAttr = 'value';
477 comboBox._wtype = 'statcat';
478 comboBox._statcat = stat.id();
479 widgetPile.push(comboBox);
481 // populate existing cats
482 var map = patron.stat_cat_entries().filter(
483 function(mp) { return (mp.stat_cat() == stat.id()) })[0];
484 if(map) comboBox.attr('value', map.stat_cat_entry());
489 function loadSurveys() {
491 surveys = fieldmapper.standardRequest(
492 ['open-ils.circ', 'open-ils.circ.survey.retrieve.all'],
493 {params : [openils.User.authtoken]}
497 for(var idx in surveys) {
498 var survey = surveys[idx];
499 var srow = surveyTemplate.cloneNode(true);
500 tbody.appendChild(srow);
501 getByName(srow, 'name').innerHTML = survey.name();
503 for(var q in survey.questions()) {
504 var quest = survey.questions()[q];
505 var qrow = surveyQuestionTemplate.cloneNode(true);
506 tbody.appendChild(qrow);
507 getByName(qrow, 'question').innerHTML = quest.question();
509 var span = getByName(qrow, 'answers').appendChild(document.createElement('span'));
510 var store = new dojo.data.ItemFileReadStore(
511 {data:fieldmapper.asva.toStoreData(quest.answers())});
512 var select = new dijit.form.FilteringSelect({store:store,scrollOnFocus:false}, span);
513 if (! openils.Util.isTrue(survey.required())) {
514 select.isValid = function() { return true; };
516 select.labelAttr = 'answer';
517 select.searchAttr = 'answer';
519 select._wtype = 'survey';
520 select._survey = survey.id();
521 select._question = quest.id();
522 widgetPile.push(select);
528 function fleshFMRow(row, fmcls, args) {
529 var fmfield = row.getAttribute('fmfield');
530 var wclass = row.getAttribute('wclass');
531 var wstyle = row.getAttribute('wstyle');
532 var wconstraints = row.getAttribute('wconstraints');
533 /* use CSS to set the zindex for widgets you want to disable. */
534 var disabled = dojo.style(row, 'zIndex') == -1 ? true : false;
536 var isPasswd2 = (fmfield == 'passwd2');
537 if(isPasswd2) fmfield = 'passwd';
538 var fieldIdl = fieldmapper.IDL.fmclasses[fmcls].field_map[fmfield];
541 var existing = dojo.query('td', row);
542 var htd = existing[0] || row.appendChild(document.createElement('td'));
543 var ltd = existing[1] || row.appendChild(document.createElement('td'));
544 var wtd = existing[2] || row.appendChild(document.createElement('td'));
546 openils.Util.addCSSClass(htd, 'uedit-help');
547 if(fieldDoc[fmcls] && fieldDoc[fmcls][fmfield]) {
548 var link = dojo.byId('uedit-help-template').cloneNode(true);
550 link.onclick = function() { ueLoadContextHelp(fmcls, fmfield) };
551 openils.Util.removeCSSClass(link, 'hidden');
552 htd.appendChild(link);
555 if(!ltd.textContent) {
556 var span = document.createElement('span');
557 ltd.appendChild(document.createTextNode(fieldIdl.label));
560 span = document.createElement('span');
561 wtd.appendChild(span);
565 case 'au' : fmObject = patron; break;
566 case 'ac' : fmObject = patron.card(); break;
568 fmObject = patron.addresses().filter(
569 function(i) { return (i.id() == args.addr) })[0];
570 if(fmObject && fmObject.usr() != patron.id())
575 var required = row.getAttribute('required') == 'required';
577 // password data is not fetched/required/displayed for existing users
578 if(!patron.isnew() && 'passwd' == fmfield)
584 constraints : (wconstraints) ? eval('('+wconstraints+')') : {}, // the ()'s prevent Invalid Label errors with eval
588 if(fmcls == 'au' && fmfield == 'passwd') {
589 if (orgSettings['global.password_regex']) {
590 dijitArgs.regExp = orgSettings['global.password_regex'];
594 // TODO RSN: Add Setting!
595 if(fmcls == 'au' && fmfield == 'dob')
596 dijitArgs.popupClass = "";
598 var value = row.getAttribute('wvalue');
600 dijitArgs.value = value;
607 widgetClass : wclass,
608 dijitArgs : dijitArgs,
609 orgDefaultsToWs : true,
610 orgLimitPerms : ['UPDATE_USER'],
613 if(fmfield == 'profile') {
614 // fetch profile groups non-async so existing expire_date is
615 // not overwritten when the profile groups arrive and update
616 wargs.forceSync = true;
617 wargs.disableQuery = {usergroup : 'f'};
619 wargs.forceSync = false;
622 var widget = new openils.widget.AutoFieldWidget(wargs);
625 // now put it back before we register the widget
626 if(isPasswd2) fmfield = 'passwd2';
628 widget._wtype = fmcls;
629 widget._fmfield = fmfield;
630 widget._addr = args.addr;
631 widgetPile.push(widget);
632 attachWidgetEvents(fmcls, fmfield, widget);
636 function findWidget(wtype, fmfield, callback) {
637 return widgetPile.filter(
639 if(i._wtype == wtype && i._fmfield == fmfield) {
640 if(callback) return callback(i);
648 * if the user does not have the UPDATE_PATRON_CLAIM_RETURN_COUNT,
649 * they are not allowed to directly alter the claim return count.
650 * This function checks the perm and disable/enables the widget.
652 function checkClaimsReturnCountPerm() {
653 new openils.User().getPermOrgList(
654 'UPDATE_PATRON_CLAIM_RETURN_COUNT',
656 var cr = findWidget('au', 'claims_returned_count');
657 if(orgList.indexOf(patron.home_ou()) == -1)
658 cr.widget.attr('disabled', true);
660 cr.widget.attr('disabled', false);
668 function checkClaimsNoCheckoutCountPerm() {
669 new openils.User().getPermOrgList(
670 'UPDATE_PATRON_CLAIM_NEVER_CHECKED_OUT_COUNT',
672 var cr = findWidget('au', 'claims_never_checked_out_count');
673 if(orgList.indexOf(patron.home_ou()) == -1)
674 cr.widget.attr('disabled', true);
676 cr.widget.attr('disabled', false);
684 function attachWidgetEvents(fmcls, fmfield, widget) {
690 if (lock_ready && xulG && typeof xulG.lock_tab == 'function') {
699 if (lock_ready && xulG && typeof xulG.lock_tab == 'function') {
707 if(fmfield == 'barcode') {
708 dojo.connect(widget.widget, 'onChange',
710 var barcode = this.attr('value');
712 dojo.addClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
713 fieldmapper.standardRequest(
714 ['open-ils.actor', 'open-ils.actor.barcode.exists'],
716 params: [openils.User.authtoken, barcode],
717 oncomplete : function(r) {
718 var res = openils.Util.readResponse(r);
721 dojo.removeClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
724 dojo.addClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
725 var un = findWidget('au', 'usrname');
726 if(!un.widget.attr('value'))
727 un.widget.attr('value', barcode);
742 dojo.connect(widget.widget, 'onChange',
744 var input = findWidget('au', 'usrname');
745 var usrname = input.widget.attr('value');
749 dojo.addClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
753 fieldmapper.standardRequest(
754 ['open-ils.actor', 'open-ils.actor.username.exists'],
756 params: [openils.User.authtoken, usrname],
757 oncomplete : function(r) {
758 var res = openils.Util.readResponse(r);
761 dojo.removeClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
764 dojo.addClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
774 case 'profile': // when the profile changes, update the expire date
775 dojo.connect(widget.widget, 'onChange',
778 var expireWidget = findWidget('au', 'expire_date');
779 function found(items) {
780 if(items.length == 0) return;
782 var interval = self.store.getValue(item, 'perm_interval');
783 expireWidget.widget.attr('value', dojo.date.add(new Date(),
784 'second', openils.Util.intervalToSeconds(interval)));
786 this.store.fetch({onComplete:found, query:{id:this.attr('value')}});
792 dojo.connect(widget.widget, 'onChange',
795 var oldDob = patron.dob();
796 if(dojo.date.stamp.fromISOString(oldDob) == newDob) return;
798 var juvInterval = orgSettings['global.juvenile_age_threshold'] || '18 years';
799 var juvWidget = findWidget('au', 'juvenile');
800 var base = new Date();
801 base.setTime(base.getTime() - Number(openils.Util.intervalToSeconds(juvInterval) + '000'));
803 if(newDob <= base) // older than global.juvenile_age_threshold
804 juvWidget.widget.attr('value', false);
806 juvWidget.widget.attr('value', true);
811 case 'first_given_name':
813 dojo.connect(widget.widget, 'onChange',
814 function(newVal) { uEditDupeSearch('name', newVal); });
818 dojo.connect(widget.widget, 'onChange',
819 function(newVal) { uEditDupeSearch('email', newVal); });
824 dojo.connect(widget.widget, 'onChange',
825 function(newVal) { uEditDupeSearch('ident', newVal); });
829 // if configured, use the last for digits of the day phone number as the password
830 if(uEditUsePhonePw && patron.isnew()) {
831 dojo.connect(widget.widget, 'onChange',
833 if(newVal && newVal.length >= 4) {
834 var pw1 = findWidget('au', 'passwd').widget;
835 var pw2 = findWidget('au', 'passwd2').widget;
836 pw1.attr('value', newVal.substring(newVal.length - 4));
837 pw2.attr('value', newVal.substring(newVal.length - 4));
842 case 'evening_phone':
844 dojo.connect(widget.widget, 'onChange',
845 function(newVal) { uEditDupeSearch('phone', newVal); });
849 dojo.connect(widget.widget, 'onChange',
851 checkClaimsReturnCountPerm();
852 checkClaimsNoCheckoutCountPerm();
858 dojo.connect(widget.widget, 'onChange',
860 var pw1 = findWidget('au', 'passwd').widget;
861 var pw2 = findWidget('au', 'passwd2').widget;
862 var preserved_value = pw2.attr('value');
863 // Ensure that the pw2 field match the pw1 field to validate
864 pw2.regExp = newVal.replace(/([.\\^$*+?\(\)\[\]\{\}])/g, '\\$1');
866 pw2.attr('value',preserved_value);
872 if(fmclass = 'aua') {
875 dojo.connect(widget.widget, 'onChange',
877 fieldmapper.standardRequest(
878 ['open-ils.search', 'open-ils.search.zip'],
881 oncomplete : function(r) {
882 var res = openils.Util.readResponse(r);
884 var callback = function(w) { return w._addr == widget._addr; };
885 if(res.city) findWidget('aua', 'city', callback).widget.attr('value', res.city);
886 if(res.state) findWidget('aua', 'state', callback).widget.attr('value', res.state);
887 if(res.county) findWidget('aua', 'county', callback).widget.attr('value', res.county);
888 if(res.alert) alert(res.alert);
899 dojo.connect(widget.widget, 'onChange',
901 var callback = function(w) { return w._addr == widget._addr; };
903 street1 : findWidget('aua', 'street1', callback).widget.attr('value'),
904 street2 : findWidget('aua', 'street2', callback).widget.attr('value'),
905 city : findWidget('aua', 'city', callback).widget.attr('value'),
906 post_code : findWidget('aua', 'post_code', callback).widget.attr('value')
908 if(args.street1 && args.city && args.post_code)
909 uEditDupeSearch('address', args);
917 function uEditDupeSearch(type, value) {
923 openils.Util.hide('uedit-dupe-names-link');
924 var fname = findWidget('au', 'first_given_name').widget.attr('value');
925 var lname = findWidget('au', 'family_name').widget.attr('value');
926 if( !(fname && lname) ) return;
928 first_given_name : {value : fname, group : 0},
929 family_name : {value : lname, group : 0},
934 openils.Util.hide('uedit-dupe-email-link');
935 search = {email : {value : value, group : 0}};
939 openils.Util.hide('uedit-dupe-ident-link');
940 search = {ident : {value : value, group : 2}};
944 openils.Util.hide('uedit-dupe-phone-link');
945 search = {phone : {value : value, group : 2}};
949 openils.Util.hide('uedit-dupe-address-link');
951 dojo.forEach(['street1', 'street2', 'city', 'post_code'],
954 search[field] = {value : value[field], group: 1};
960 // find possible duplicate patrons
961 fieldmapper.standardRequest(
962 ['open-ils.actor', 'open-ils.actor.patron.search.advanced'],
964 params: [openils.User.authtoken, search],
965 oncomplete : function(r) {
966 var resp = openils.Util.readResponse(r);
967 resp = resp.filter(function(id) { return (id != patron.id()); });
969 if(resp && resp.length > 0) {
971 openils.Util.hide('uedit-help-div');
972 openils.Util.show('uedit-dupe-div');
977 link = dojo.byId('uedit-dupe-names-link');
978 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_NAME, [resp.length]);
981 link = dojo.byId('uedit-dupe-email-link');
982 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_EMAIL, [resp.length]);
985 link = dojo.byId('uedit-dupe-ident-link');
986 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_IDENT, [resp.length]);
989 link = dojo.byId('uedit-dupe-phone-link');
990 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_PHONE, [resp.length]);
993 link = dojo.byId('uedit-dupe-address-link');
994 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_ADDR, [resp.length]);
998 openils.Util.show(link);
999 link.onclick = function() {
1000 search.search_sort = js2JSON(["penalties", "family_name", "first_given_name"]);
1002 window.xulG.spawn_search(search);
1004 console.log("running XUL patron search " + js2JSON(search));
1012 function getByName(node, name) {
1013 return dojo.query('[name='+name+']', node)[0];
1017 function ueLoadContextHelp(fmcls, fmfield) {
1018 openils.Util.hide('uedit-dupe-div');
1019 openils.Util.show('uedit-help-div');
1020 dojo.byId('uedit-help-field').innerHTML = fieldmapper.IDL.fmclasses[fmcls].field_map[fmfield].label;
1021 dojo.byId('uedit-help-text').innerHTML = fieldDoc[fmcls][fmfield].string();
1025 /* creates a new patron object with card attached */
1026 function uEditNewPatron() {
1031 card.id(uEditCardVirtId--);
1035 patron.cards([card]);
1036 patron.net_access_level(orgSettings['ui.patron.default_inet_access_level'] || 1);
1037 patron.ident_type(orgSettings['ui.patron.default_ident_type']);
1038 patron.stat_cat_entries([]);
1039 patron.survey_responses([]);
1040 patron.addresses([]);
1041 uEditMakeRandomPw(patron);
1045 function uEditMakeRandomPw(patron) {
1046 if(uEditUsePhonePw) return;
1047 var rand = Math.random();
1048 rand = parseInt(rand * 10000) + '';
1049 while(rand.length < 4) rand += '0';
1051 appendClear($('ue_password_plain'),text(rand));
1052 unHideMe($('ue_password_gen'));
1054 patron.passwd(rand);
1058 function uEditWidgetVal(w) {
1059 var val = (w.getFormattedValue) ? w.getFormattedValue() : w.attr('value');
1060 if(val === '') val = null;
1064 function uEditSave() { _uEditSave(); }
1065 function uEditSaveClone() { _uEditSave(true); }
1067 function _uEditSave(doClone) {
1069 if ( (! myForm.isValid()) || dupeUsrname || dupeBarcode ) {
1070 alert(localeStrings.INVALID_FORM);
1074 for(var idx in widgetPile) {
1075 var w = widgetPile[idx];
1076 var val = uEditWidgetVal(w);
1080 if(w._fmfield != 'passwd2')
1081 patron[w._fmfield](val);
1085 patron.card()[w._fmfield](val);
1089 var addr = patron.addresses().filter(function(i){return (i.id() == w._addr)})[0];
1091 addr = new fieldmapper.aua();
1094 addr.usr(patron.id());
1095 addr.country(orgSettings['ui.patron.default_country']);
1096 var t = patron.addresses();
1099 patron.addresses(t);
1101 if(addr[w._fmfield]() != val)
1104 addr[w._fmfield](val);
1106 if(dojo.byId('uedit-billing-address-' + addr.id()).checked)
1107 patron.billing_address(addr.id());
1109 if(dojo.byId('uedit-mailing-address-' + addr.id()).checked)
1110 patron.mailing_address(addr.id());
1115 if(val == null) break;
1116 var resp = new fieldmapper.asvr();
1118 resp.survey(w._survey)
1119 resp.usr(patron.id());
1120 resp.question(w._question)
1122 var t = patron.survey_responses();
1125 patron.survey_responses(t);
1129 if(val == null) break;
1131 var map = patron.stat_cat_entries().filter(
1133 return (m.stat_cat() == w._statcat) })[0];
1136 if(map.stat_cat_entry() == val)
1140 map = new fieldmapper.actscecm();
1144 map.stat_cat(w._statcat);
1145 map.stat_cat_entry(val);
1146 map.target_usr(patron.id());
1147 var t = patron.stat_cat_entries();
1150 patron.stat_cat_entries(t);
1155 patron.ischanged(1);
1156 fieldmapper.standardRequest(
1157 ['open-ils.actor', 'open-ils.actor.patron.update'],
1159 params: [openils.User.authtoken, patron],
1160 oncomplete: function(r) {
1162 if (xulG && typeof xulG.unlock_tab == 'function') { xulG.unlock_tab(); }
1163 newPatron = openils.Util.readResponse(r);
1165 uEditUpdateUserSettings(newPatron.id());
1166 if(stageUser) uEditRemoveStage();
1167 uEditFinishSave(newPatron, doClone);
1174 function uEditRemoveStage() {
1175 var resp = fieldmapper.standardRequest(
1176 ['open-ils.actor', 'open-ils.actor.user.stage.delete'],
1177 { params : [openils.User.authtoken, stageUser.row_id()] }
1181 function uEditFinishSave(newPatron, doClone) {
1183 if(doClone && cloneUser == null)
1184 cloneUser = newPatron.id();
1188 if(xulG && typeof xulG.spawn_editor == 'function' && !patron.isnew() ) {
1189 window.xulG.spawn_editor({ses:openils.User.authtoken,clone:cloneUser});
1193 location.href = location.href.replace(/\?.*/, '') + '?clone=' + cloneUser;
1201 uEditRefreshXUL(newPatron);
1204 function uEditRefresh() {
1205 var usr = cgi.param('usr');
1206 var href = location.href.replace(/\?.*/, '');
1207 href += ((usr) ? '?usr=' + usr : '');
1208 location.href = href;
1211 function uEditRefreshXUL(newuser) {
1212 if (window.xulG && typeof window.xulG.on_save == 'function')
1213 window.xulG.on_save(newuser);
1218 * Create a new address and insert it into the DOM
1219 * @param evt ignored
1220 * @param id The address id
1221 * @param mkLinks If true, set the new address as the
1222 * mailing/billing address for the user
1224 function uEditNewAddr(evt, id, mkLinks) {
1227 id = --uEditAddrVirtId; // new address
1229 var addr = patron.addresses().filter(
1230 function(i) { return (i.id() == id) })[0];
1232 dojo.forEach(addrTemplateRows,
1235 row = tbody.insertBefore(row.cloneNode(true), dojo.byId('new-addr-row'));
1236 row.setAttribute('type', '');
1237 row.setAttribute('addr', id+'');
1239 if(row.getAttribute('fmclass')) {
1240 var widget = fleshFMRow(row, 'aua', {addr:id});
1242 // make new addresses a default address type
1243 if(id < 0 && row.getAttribute('fmfield') == 'address_type')
1244 widget.widget.attr('value', localeStrings.DEFAULT_ADDRESS_TYPE);
1246 // make new addresses valid by default
1247 if(id < 0 && row.getAttribute('fmfield') == 'valid')
1248 widget.widget.attr('value', true);
1250 // make new addresses use the org setting for default country
1251 if(id < 0 && row.getAttribute('fmfield') == 'country')
1252 widget.widget.attr('value',orgSettings['ui.patron.default_country']);
1254 } else if(row.getAttribute('name') == 'uedit-addr-pending-row') {
1256 // if it's a pending address, show the 'approve' button
1257 if(addr && openils.Util.isTrue(addr.pending())) {
1258 openils.Util.show(row, 'table-row');
1259 dojo.query('[name=approve-button]', row)[0].onclick =
1260 function() { uEditApproveAddress(addr); };
1262 if(addr.replaces()) {
1263 var div = dojo.query('[name=replaced-addr]', row)[0]
1264 var replaced = patron.addresses().filter(
1265 function(i) { return (i.id() == addr.replaces()) })[0];
1267 div.innerHTML = dojo.string.substitute(localeStrings.REPLACED_ADDRESS, [
1268 replaced.address_type() || '',
1269 replaced.street1() || '',
1270 replaced.street2() || '',
1271 replaced.city() || '',
1272 replaced.state() || '',
1273 replaced.post_code() || ''
1277 openils.Util.hide(dojo.query('[name=replaced-addr-div]', row)[0]);
1281 } else if(row.getAttribute('name') == 'uedit-addr-owner-row') {
1282 // address is owned by someone else. provide option to load the
1283 // user in a different tab
1285 if(addr && addr.usr() != patron.id()) {
1286 openils.Util.show(row, 'table-row');
1287 var link = getByName(row, 'addr-owner');
1289 // fetch the linked user so we can present their name in the UI
1291 if(cloneUserObj && cloneUserObj.id() == addr.usr()) {
1293 cloneUserObj.first_given_name(),
1294 cloneUserObj.second_given_name(),
1295 cloneUserObj.family_name()
1298 addrUser = fieldmapper.standardRequest(
1299 ['open-ils.actor', 'open-ils.actor.user.retrieve.parts'],
1301 openils.User.authtoken,
1303 ['first_given_name', 'second_given_name', 'family_name']
1308 link.innerHTML = (addrUser.map(function(name) { return (name) ? name+' ' : '' })+'').replace(/,/g,''); // TODO i18n
1309 link.onclick = function() {
1310 if(openils.XUL.isXUL()) {
1311 window.xulG.spawn_editor({ses:openils.User.authtoken, usr:addr.usr()})
1313 parent.location.href = location.href.replace(/clone=\d+/, 'usr=' + addr.usr());
1318 } else if(row.getAttribute('name') == 'uedit-addr-divider') {
1319 // link up the billing/mailing address and give the inputs IDs so we can acces the later
1322 var ba = getByName(row, 'billing_address');
1323 ba.id = 'uedit-billing-address-' + id;
1324 if(mkLinks || (patron.billing_address() && patron.billing_address().id() == id))
1328 var ma = getByName(row, 'mailing_address');
1329 ma.id = 'uedit-mailing-address-' + id;
1330 if(mkLinks || (patron.mailing_address() && patron.mailing_address().id() == id))
1333 var btn = dojo.query('[name=delete-button]', row)[0];
1334 if(btn) btn.onclick = function(){ uEditDeleteAddr(id) };
1340 function uEditApproveAddress(addr) {
1341 fieldmapper.standardRequest(
1342 ['open-ils.actor', 'open-ils.actor.user.pending_address.approve'],
1344 params: [openils.User.authtoken, addr],
1346 oncomplete : function(r) {
1347 var oldId = openils.Util.readResponse(r);
1349 // remove addrs from UI
1352 function(addr) { uEditDeleteAddr(addr.id(), true); }
1357 // remove the replaced address
1358 if(oldId != addr.id()) {
1360 patron.addresses().filter(
1361 function(i) { return (i.id() != oldId); }
1366 // fix the the new address
1368 addr.replaces(null);
1381 function uEditDeleteAddr(id, noAlert) {
1382 if (patron.isnew() && orgSettings['ui.patron.registration.require_address']) {
1383 if (dojo.query('tr[name=uedit-addr-divider]').length < 2) {
1384 alert(localeStrings.NEED_ADDRESS);
1389 if(!confirm(dojo.string.substitute(localeStrings.DELETE_ADDRESS, [id]))) return;
1391 var addr = patron.addresses().filter(function(i){return (i.id() == id)})[0];
1392 if (addr) { addr.isdeleted(1); }
1393 var m_a = patron.mailing_address();
1394 if (typeof m_a == 'object' && m_a != null) { m_a = m_a.id(); }
1395 if (m_a == id) { patron.mailing_address(null); }
1396 var b_a = patron.billing_address();
1397 if (typeof b_a == 'object' && b_a != null) { b_a = b_a.id(); }
1398 if (b_a == id) { patron.billing_address(null); }
1400 var rows = dojo.query('tr[addr='+id+']', tbody);
1401 for(var i = 0; i < rows.length; i++)
1402 rows[i].parentNode.removeChild(rows[i]);
1403 widgetPile = widgetPile.filter(function(w){return (w._addr != id)});
1406 function uEditToggleRequired() {
1407 if((tbody.className +'').match(/hide-non-required/))
1408 openils.Util.removeCSSClass(tbody, 'hide-non-required');
1410 openils.Util.addCSSClass(tbody, 'hide-non-required');
1411 openils.Util.toggle('uedit-show-required');
1412 openils.Util.toggle('uedit-show-all');
1415 function printable_output() {
1416 var temp; var s = '=-=-=-=\r\n';
1417 for (var idx in widgetPile) {
1418 var w = widgetPile[idx];
1419 var val = uEditWidgetVal(w);
1421 if (typeof w.idlField == 'undefined') {
1423 if (w._wtype == 'statcat') {
1424 var stat = statCats.filter(
1426 return (m.id() == w._statcat) })[0];
1427 label = stat.name();
1428 } else if (w._wtype == 'survey') {
1429 var survey = surveys.filter(
1431 return (m.id() == w._survey) })[0];
1432 var question = survey.questions().filter(
1434 return (m.id() == w._question) })[0];
1435 label = survey.name() + ' : ' + question.question();
1440 label = w.idlField.label;
1442 if (temp != w._wtype) {
1446 s += label + ':\t' + (typeof val == 'object' ? '' : val) + '\r\n';
1452 openils.Util.addOnLoad(load);