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 */
388 userSettings = fieldmapper.standardRequest(
389 ['open-ils.actor', 'open-ils.actor.patron.settings.retrieve.authoritative'],
390 {params : [openils.User.authtoken, userId, names]});
394 function uEditLoadUser(userId) {
395 var patron = fieldmapper.standardRequest(
396 ['open-ils.actor', 'open-ils.actor.user.fleshed.retrieve.authoritative'],
397 {params : [openils.User.authtoken, userId]}
399 openils.Event.parse_and_raise(patron);
403 function loadStaticFields() {
404 for(var idx = 0; tbody.childNodes[idx]; idx++) {
405 var row = tbody.childNodes[idx];
406 if(row.nodeType != row.ELEMENT_NODE) continue;
407 var fmcls = row.getAttribute('fmclass');
409 fleshFMRow(row, fmcls);
412 if(row.id == 'uedit-settings-divider') {
414 var template = tbody.removeChild(dojo.byId('uedit-user-setting-template'));
415 dojo.forEach(userSettingTypes, function(type) { uEditDrawSettingRow(tbody, row, template, type); } );
417 if(userSettingTypes.length > 1 || orgSettings['circ.holds.behind_desk_pickup_supported']) {
418 openils.Util.show('uedit-settings-divider', 'table-row');
425 function uEditDrawSettingRow(tbody, dividerRow, template, stype) {
426 var row = template.cloneNode(true);
427 row.setAttribute('user_setting', stype.name());
428 getByName(row, 'label').innerHTML = stype.label();
429 var cb = new dijit.form.CheckBox({scrollOnFocus:false}, getByName(row, 'widget'));
430 cb.attr('value', userSettings[stype.name()]);
431 dojo.connect(cb, 'onChange', function(newVal) { userSettingsToUpdate[stype.name()] = newVal; });
432 tbody.insertBefore(row, dividerRow.nextSibling);
433 openils.Util.show(row, 'table-row');
436 function uEditUpdateUserSettings(userId) {
437 return fieldmapper.standardRequest(
438 ['open-ils.actor', 'open-ils.actor.patron.settings.update'],
439 {params : [openils.User.authtoken, userId, userSettingsToUpdate]});
442 function loadAllAddrs() {
443 dojo.forEach(patron.addresses(),
445 uEditNewAddr(null, addr.id());
450 function loadStatCats() {
452 statCats = fieldmapper.standardRequest(
453 ['open-ils.circ', 'open-ils.circ.stat_cat.actor.retrieve.all'],
454 {params : [openils.User.authtoken, staff.ws_ou()]}
458 for(var idx in statCats) {
459 var stat = statCats[idx];
460 var row = statCatTemplate.cloneNode(true);
461 row.id = 'stat-cat-row-' + idx;
462 row.setAttribute('stat_cat_owner',stat.owner());
463 row.setAttribute('stat_cat_name',stat.name());
464 row.setAttribute('stat_cat_id',stat.id());
465 tbody.appendChild(row);
466 getByName(row, 'name').innerHTML = stat.name();
467 var valtd = getByName(row, 'widget');
468 var span = valtd.appendChild(document.createElement('span'));
469 var store = new dojo.data.ItemFileReadStore(
470 {data:fieldmapper.actsc.toStoreData(stat.entries())});
471 var comboBox = new dijit.form.ComboBox({store:store,scrollOnFocus:false}, span);
472 comboBox.labelAttr = 'value';
473 comboBox.searchAttr = 'value';
475 comboBox._wtype = 'statcat';
476 comboBox._statcat = stat.id();
477 widgetPile.push(comboBox);
479 // populate existing cats
480 var map = patron.stat_cat_entries().filter(
481 function(mp) { return (mp.stat_cat() == stat.id()) })[0];
482 if(map) comboBox.attr('value', map.stat_cat_entry());
487 function loadSurveys() {
489 surveys = fieldmapper.standardRequest(
490 ['open-ils.circ', 'open-ils.circ.survey.retrieve.all'],
491 {params : [openils.User.authtoken]}
495 for(var idx in surveys) {
496 var survey = surveys[idx];
497 var srow = surveyTemplate.cloneNode(true);
498 tbody.appendChild(srow);
499 getByName(srow, 'name').innerHTML = survey.name();
501 for(var q in survey.questions()) {
502 var quest = survey.questions()[q];
503 var qrow = surveyQuestionTemplate.cloneNode(true);
504 tbody.appendChild(qrow);
505 getByName(qrow, 'question').innerHTML = quest.question();
507 var span = getByName(qrow, 'answers').appendChild(document.createElement('span'));
508 var store = new dojo.data.ItemFileReadStore(
509 {data:fieldmapper.asva.toStoreData(quest.answers())});
510 var select = new dijit.form.FilteringSelect({store:store,scrollOnFocus:false}, span);
511 if (! openils.Util.isTrue(survey.required())) {
512 select.isValid = function() { return true; };
514 select.labelAttr = 'answer';
515 select.searchAttr = 'answer';
517 select._wtype = 'survey';
518 select._survey = survey.id();
519 select._question = quest.id();
520 widgetPile.push(select);
526 function fleshFMRow(row, fmcls, args) {
527 var fmfield = row.getAttribute('fmfield');
528 var wclass = row.getAttribute('wclass');
529 var wstyle = row.getAttribute('wstyle');
530 var wconstraints = row.getAttribute('wconstraints');
531 /* use CSS to set the zindex for widgets you want to disable. */
532 var disabled = dojo.style(row, 'zIndex') == -1 ? true : false;
534 var isPasswd2 = (fmfield == 'passwd2');
535 if(isPasswd2) fmfield = 'passwd';
536 var fieldIdl = fieldmapper.IDL.fmclasses[fmcls].field_map[fmfield];
539 var existing = dojo.query('td', row);
540 var htd = existing[0] || row.appendChild(document.createElement('td'));
541 var ltd = existing[1] || row.appendChild(document.createElement('td'));
542 var wtd = existing[2] || row.appendChild(document.createElement('td'));
544 openils.Util.addCSSClass(htd, 'uedit-help');
545 if(fieldDoc[fmcls] && fieldDoc[fmcls][fmfield]) {
546 var link = dojo.byId('uedit-help-template').cloneNode(true);
548 link.onclick = function() { ueLoadContextHelp(fmcls, fmfield) };
549 openils.Util.removeCSSClass(link, 'hidden');
550 htd.appendChild(link);
553 if(!ltd.textContent) {
554 var span = document.createElement('span');
555 ltd.appendChild(document.createTextNode(fieldIdl.label));
558 span = document.createElement('span');
559 wtd.appendChild(span);
563 case 'au' : fmObject = patron; break;
564 case 'ac' : fmObject = patron.card(); break;
566 fmObject = patron.addresses().filter(
567 function(i) { return (i.id() == args.addr) })[0];
568 if(fmObject && fmObject.usr() != patron.id())
573 var required = row.getAttribute('required') == 'required';
575 // password data is not fetched/required/displayed for existing users
576 if(!patron.isnew() && 'passwd' == fmfield)
582 constraints : (wconstraints) ? eval('('+wconstraints+')') : {}, // the ()'s prevent Invalid Label errors with eval
586 if(fmcls == 'au' && fmfield == 'passwd') {
587 if (orgSettings['global.password_regex']) {
588 dijitArgs.regExp = orgSettings['global.password_regex'];
592 // TODO RSN: Add Setting!
593 if(fmcls == 'au' && fmfield == 'dob')
594 dijitArgs.popupClass = "";
596 var value = row.getAttribute('wvalue');
598 dijitArgs.value = value;
605 widgetClass : wclass,
606 dijitArgs : dijitArgs,
607 orgDefaultsToWs : true,
608 orgLimitPerms : ['UPDATE_USER'],
611 if(fmfield == 'profile') {
612 // fetch profile groups non-async so existing expire_date is
613 // not overwritten when the profile groups arrive and update
614 wargs.forceSync = true;
615 wargs.disableQuery = {usergroup : 'f'};
617 wargs.forceSync = false;
620 var widget = new openils.widget.AutoFieldWidget(wargs);
623 // now put it back before we register the widget
624 if(isPasswd2) fmfield = 'passwd2';
626 widget._wtype = fmcls;
627 widget._fmfield = fmfield;
628 widget._addr = args.addr;
629 widgetPile.push(widget);
630 attachWidgetEvents(fmcls, fmfield, widget);
634 function findWidget(wtype, fmfield, callback) {
635 return widgetPile.filter(
637 if(i._wtype == wtype && i._fmfield == fmfield) {
638 if(callback) return callback(i);
646 * if the user does not have the UPDATE_PATRON_CLAIM_RETURN_COUNT,
647 * they are not allowed to directly alter the claim return count.
648 * This function checks the perm and disable/enables the widget.
650 function checkClaimsReturnCountPerm() {
651 new openils.User().getPermOrgList(
652 'UPDATE_PATRON_CLAIM_RETURN_COUNT',
654 var cr = findWidget('au', 'claims_returned_count');
655 if(orgList.indexOf(patron.home_ou()) == -1)
656 cr.widget.attr('disabled', true);
658 cr.widget.attr('disabled', false);
666 function checkClaimsNoCheckoutCountPerm() {
667 new openils.User().getPermOrgList(
668 'UPDATE_PATRON_CLAIM_NEVER_CHECKED_OUT_COUNT',
670 var cr = findWidget('au', 'claims_never_checked_out_count');
671 if(orgList.indexOf(patron.home_ou()) == -1)
672 cr.widget.attr('disabled', true);
674 cr.widget.attr('disabled', false);
682 function attachWidgetEvents(fmcls, fmfield, widget) {
688 if (lock_ready && xulG && typeof xulG.lock_tab == 'function') {
695 if(fmfield == 'barcode') {
696 dojo.connect(widget.widget, 'onChange',
698 var barcode = this.attr('value');
700 dojo.addClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
701 fieldmapper.standardRequest(
702 ['open-ils.actor', 'open-ils.actor.barcode.exists'],
704 params: [openils.User.authtoken, barcode],
705 oncomplete : function(r) {
706 var res = openils.Util.readResponse(r);
709 dojo.removeClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
712 dojo.addClass(dojo.byId('uedit-dupe-barcode-warning'), 'hidden');
713 var un = findWidget('au', 'usrname');
714 if(!un.widget.attr('value'))
715 un.widget.attr('value', barcode);
730 dojo.connect(widget.widget, 'onChange',
732 var input = findWidget('au', 'usrname');
733 var usrname = input.widget.attr('value');
737 dojo.addClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
741 fieldmapper.standardRequest(
742 ['open-ils.actor', 'open-ils.actor.username.exists'],
744 params: [openils.User.authtoken, usrname],
745 oncomplete : function(r) {
746 var res = openils.Util.readResponse(r);
749 dojo.removeClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
752 dojo.addClass(dojo.byId('uedit-dupe-username-warning'), 'hidden');
762 case 'profile': // when the profile changes, update the expire date
763 dojo.connect(widget.widget, 'onChange',
766 var expireWidget = findWidget('au', 'expire_date');
767 function found(items) {
768 if(items.length == 0) return;
770 var interval = self.store.getValue(item, 'perm_interval');
771 expireWidget.widget.attr('value', dojo.date.add(new Date(),
772 'second', openils.Util.intervalToSeconds(interval)));
774 this.store.fetch({onComplete:found, query:{id:this.attr('value')}});
780 dojo.connect(widget.widget, 'onChange',
783 var oldDob = patron.dob();
784 if(dojo.date.stamp.fromISOString(oldDob) == newDob) return;
786 var juvInterval = orgSettings['global.juvenile_age_threshold'] || '18 years';
787 var juvWidget = findWidget('au', 'juvenile');
788 var base = new Date();
789 base.setTime(base.getTime() - Number(openils.Util.intervalToSeconds(juvInterval) + '000'));
791 if(newDob <= base) // older than global.juvenile_age_threshold
792 juvWidget.widget.attr('value', false);
794 juvWidget.widget.attr('value', true);
799 case 'first_given_name':
801 dojo.connect(widget.widget, 'onChange',
802 function(newVal) { uEditDupeSearch('name', newVal); });
806 dojo.connect(widget.widget, 'onChange',
807 function(newVal) { uEditDupeSearch('email', newVal); });
812 dojo.connect(widget.widget, 'onChange',
813 function(newVal) { uEditDupeSearch('ident', newVal); });
817 // if configured, use the last for digits of the day phone number as the password
818 if(uEditUsePhonePw && patron.isnew()) {
819 dojo.connect(widget.widget, 'onChange',
821 if(newVal && newVal.length >= 4) {
822 var pw1 = findWidget('au', 'passwd').widget;
823 var pw2 = findWidget('au', 'passwd2').widget;
824 pw1.attr('value', newVal.substring(newVal.length - 4));
825 pw2.attr('value', newVal.substring(newVal.length - 4));
830 case 'evening_phone':
832 dojo.connect(widget.widget, 'onChange',
833 function(newVal) { uEditDupeSearch('phone', newVal); });
837 dojo.connect(widget.widget, 'onChange',
839 checkClaimsReturnCountPerm();
840 checkClaimsNoCheckoutCountPerm();
846 dojo.connect(widget.widget, 'onChange',
848 var pw1 = findWidget('au', 'passwd').widget;
849 var pw2 = findWidget('au', 'passwd2').widget;
850 var preserved_value = pw2.attr('value');
851 // Ensure that the pw2 field match the pw1 field to validate
852 pw2.regExp = newVal.replace(/([.\\^$*+?\(\)\[\]\{\}])/g, '\\$1');
854 pw2.attr('value',preserved_value);
860 if(fmclass = 'aua') {
863 dojo.connect(widget.widget, 'onChange',
865 fieldmapper.standardRequest(
866 ['open-ils.search', 'open-ils.search.zip'],
869 oncomplete : function(r) {
870 var res = openils.Util.readResponse(r);
872 var callback = function(w) { return w._addr == widget._addr; };
873 if(res.city) findWidget('aua', 'city', callback).widget.attr('value', res.city);
874 if(res.state) findWidget('aua', 'state', callback).widget.attr('value', res.state);
875 if(res.county) findWidget('aua', 'county', callback).widget.attr('value', res.county);
876 if(res.alert) alert(res.alert);
887 dojo.connect(widget.widget, 'onChange',
889 var callback = function(w) { return w._addr == widget._addr; };
891 street1 : findWidget('aua', 'street1', callback).widget.attr('value'),
892 street2 : findWidget('aua', 'street2', callback).widget.attr('value'),
893 city : findWidget('aua', 'city', callback).widget.attr('value'),
894 post_code : findWidget('aua', 'post_code', callback).widget.attr('value')
896 if(args.street1 && args.city && args.post_code)
897 uEditDupeSearch('address', args);
905 function uEditDupeSearch(type, value) {
911 openils.Util.hide('uedit-dupe-names-link');
912 var fname = findWidget('au', 'first_given_name').widget.attr('value');
913 var lname = findWidget('au', 'family_name').widget.attr('value');
914 if( !(fname && lname) ) return;
916 first_given_name : {value : fname, group : 0},
917 family_name : {value : lname, group : 0},
922 openils.Util.hide('uedit-dupe-email-link');
923 search = {email : {value : value, group : 0}};
927 openils.Util.hide('uedit-dupe-ident-link');
928 search = {ident : {value : value, group : 2}};
932 openils.Util.hide('uedit-dupe-phone-link');
933 search = {phone : {value : value, group : 2}};
937 openils.Util.hide('uedit-dupe-address-link');
939 dojo.forEach(['street1', 'street2', 'city', 'post_code'],
942 search[field] = {value : value[field], group: 1};
948 // find possible duplicate patrons
949 fieldmapper.standardRequest(
950 ['open-ils.actor', 'open-ils.actor.patron.search.advanced'],
952 params: [openils.User.authtoken, search],
953 oncomplete : function(r) {
954 var resp = openils.Util.readResponse(r);
955 resp = resp.filter(function(id) { return (id != patron.id()); });
957 if(resp && resp.length > 0) {
959 openils.Util.hide('uedit-help-div');
960 openils.Util.show('uedit-dupe-div');
965 link = dojo.byId('uedit-dupe-names-link');
966 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_NAME, [resp.length]);
969 link = dojo.byId('uedit-dupe-email-link');
970 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_EMAIL, [resp.length]);
973 link = dojo.byId('uedit-dupe-ident-link');
974 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_IDENT, [resp.length]);
977 link = dojo.byId('uedit-dupe-phone-link');
978 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_PHONE, [resp.length]);
981 link = dojo.byId('uedit-dupe-address-link');
982 link.innerHTML = dojo.string.substitute(localeStrings.DUPE_PATRON_ADDR, [resp.length]);
986 openils.Util.show(link);
987 link.onclick = function() {
988 search.search_sort = js2JSON(["penalties", "family_name", "first_given_name"]);
990 window.xulG.spawn_search(search);
992 console.log("running XUL patron search " + js2JSON(search));
1000 function getByName(node, name) {
1001 return dojo.query('[name='+name+']', node)[0];
1005 function ueLoadContextHelp(fmcls, fmfield) {
1006 openils.Util.hide('uedit-dupe-div');
1007 openils.Util.show('uedit-help-div');
1008 dojo.byId('uedit-help-field').innerHTML = fieldmapper.IDL.fmclasses[fmcls].field_map[fmfield].label;
1009 dojo.byId('uedit-help-text').innerHTML = fieldDoc[fmcls][fmfield].string();
1013 /* creates a new patron object with card attached */
1014 function uEditNewPatron() {
1019 card.id(uEditCardVirtId--);
1023 patron.cards([card]);
1024 patron.net_access_level(orgSettings['ui.patron.default_inet_access_level'] || 1);
1025 patron.ident_type(orgSettings['ui.patron.default_ident_type']);
1026 patron.stat_cat_entries([]);
1027 patron.survey_responses([]);
1028 patron.addresses([]);
1029 uEditMakeRandomPw(patron);
1033 function uEditMakeRandomPw(patron) {
1034 if(uEditUsePhonePw) return;
1035 var rand = Math.random();
1036 rand = parseInt(rand * 10000) + '';
1037 while(rand.length < 4) rand += '0';
1039 appendClear($('ue_password_plain'),text(rand));
1040 unHideMe($('ue_password_gen'));
1042 patron.passwd(rand);
1046 function uEditWidgetVal(w) {
1047 var val = (w.getFormattedValue) ? w.getFormattedValue() : w.attr('value');
1048 if(val === '') val = null;
1052 function uEditSave() { _uEditSave(); }
1053 function uEditSaveClone() { _uEditSave(true); }
1055 function _uEditSave(doClone) {
1057 if ( (! myForm.isValid()) || dupeUsrname || dupeBarcode ) {
1058 alert(localeStrings.INVALID_FORM);
1062 for(var idx in widgetPile) {
1063 var w = widgetPile[idx];
1064 var val = uEditWidgetVal(w);
1068 if(w._fmfield != 'passwd2')
1069 patron[w._fmfield](val);
1073 patron.card()[w._fmfield](val);
1077 var addr = patron.addresses().filter(function(i){return (i.id() == w._addr)})[0];
1079 addr = new fieldmapper.aua();
1082 addr.usr(patron.id());
1083 addr.country(orgSettings['ui.patron.default_country']);
1084 var t = patron.addresses();
1087 patron.addresses(t);
1089 if(addr[w._fmfield]() != val)
1092 addr[w._fmfield](val);
1094 if(dojo.byId('uedit-billing-address-' + addr.id()).checked)
1095 patron.billing_address(addr.id());
1097 if(dojo.byId('uedit-mailing-address-' + addr.id()).checked)
1098 patron.mailing_address(addr.id());
1103 if(val == null) break;
1104 var resp = new fieldmapper.asvr();
1106 resp.survey(w._survey)
1107 resp.usr(patron.id());
1108 resp.question(w._question)
1110 var t = patron.survey_responses();
1113 patron.survey_responses(t);
1117 if(val == null) break;
1119 var map = patron.stat_cat_entries().filter(
1121 return (m.stat_cat() == w._statcat) })[0];
1124 if(map.stat_cat_entry() == val)
1128 map = new fieldmapper.actscecm();
1132 map.stat_cat(w._statcat);
1133 map.stat_cat_entry(val);
1134 map.target_usr(patron.id());
1135 var t = patron.stat_cat_entries();
1138 patron.stat_cat_entries(t);
1143 patron.ischanged(1);
1144 fieldmapper.standardRequest(
1145 ['open-ils.actor', 'open-ils.actor.patron.update'],
1147 params: [openils.User.authtoken, patron],
1148 oncomplete: function(r) {
1150 if (xulG && typeof xulG.unlock_tab == 'function') { xulG.unlock_tab(); }
1151 newPatron = openils.Util.readResponse(r);
1153 uEditUpdateUserSettings(newPatron.id());
1154 if(stageUser) uEditRemoveStage();
1155 uEditFinishSave(newPatron, doClone);
1162 function uEditRemoveStage() {
1163 var resp = fieldmapper.standardRequest(
1164 ['open-ils.actor', 'open-ils.actor.user.stage.delete'],
1165 { params : [openils.User.authtoken, stageUser.row_id()] }
1169 function uEditFinishSave(newPatron, doClone) {
1171 if(doClone && cloneUser == null)
1172 cloneUser = newPatron.id();
1176 if(xulG && typeof xulG.spawn_editor == 'function' && !patron.isnew() ) {
1177 window.xulG.spawn_editor({ses:openils.User.authtoken,clone:cloneUser});
1181 location.href = location.href.replace(/\?.*/, '') + '?clone=' + cloneUser;
1189 uEditRefreshXUL(newPatron);
1192 function uEditRefresh() {
1193 var usr = cgi.param('usr');
1194 var href = location.href.replace(/\?.*/, '');
1195 href += ((usr) ? '?usr=' + usr : '');
1196 location.href = href;
1199 function uEditRefreshXUL(newuser) {
1200 if (window.xulG && typeof window.xulG.on_save == 'function')
1201 window.xulG.on_save(newuser);
1206 * Create a new address and insert it into the DOM
1207 * @param evt ignored
1208 * @param id The address id
1209 * @param mkLinks If true, set the new address as the
1210 * mailing/billing address for the user
1212 function uEditNewAddr(evt, id, mkLinks) {
1215 id = --uEditAddrVirtId; // new address
1217 var addr = patron.addresses().filter(
1218 function(i) { return (i.id() == id) })[0];
1220 dojo.forEach(addrTemplateRows,
1223 row = tbody.insertBefore(row.cloneNode(true), dojo.byId('new-addr-row'));
1224 row.setAttribute('type', '');
1225 row.setAttribute('addr', id+'');
1227 if(row.getAttribute('fmclass')) {
1228 var widget = fleshFMRow(row, 'aua', {addr:id});
1230 // make new addresses a default address type
1231 if(id < 0 && row.getAttribute('fmfield') == 'address_type')
1232 widget.widget.attr('value', localeStrings.DEFAULT_ADDRESS_TYPE);
1234 // make new addresses valid by default
1235 if(id < 0 && row.getAttribute('fmfield') == 'valid')
1236 widget.widget.attr('value', true);
1238 // make new addresses use the org setting for default country
1239 if(id < 0 && row.getAttribute('fmfield') == 'country')
1240 widget.widget.attr('value',orgSettings['ui.patron.default_country']);
1242 } else if(row.getAttribute('name') == 'uedit-addr-pending-row') {
1244 // if it's a pending address, show the 'approve' button
1245 if(addr && openils.Util.isTrue(addr.pending())) {
1246 openils.Util.show(row, 'table-row');
1247 dojo.query('[name=approve-button]', row)[0].onclick =
1248 function() { uEditApproveAddress(addr); };
1250 if(addr.replaces()) {
1251 var div = dojo.query('[name=replaced-addr]', row)[0]
1252 var replaced = patron.addresses().filter(
1253 function(i) { return (i.id() == addr.replaces()) })[0];
1255 div.innerHTML = dojo.string.substitute(localeStrings.REPLACED_ADDRESS, [
1256 replaced.address_type() || '',
1257 replaced.street1() || '',
1258 replaced.street2() || '',
1259 replaced.city() || '',
1260 replaced.state() || '',
1261 replaced.post_code() || ''
1265 openils.Util.hide(dojo.query('[name=replaced-addr-div]', row)[0]);
1269 } else if(row.getAttribute('name') == 'uedit-addr-owner-row') {
1270 // address is owned by someone else. provide option to load the
1271 // user in a different tab
1273 if(addr && addr.usr() != patron.id()) {
1274 openils.Util.show(row, 'table-row');
1275 var link = getByName(row, 'addr-owner');
1277 // fetch the linked user so we can present their name in the UI
1279 if(cloneUserObj && cloneUserObj.id() == addr.usr()) {
1281 cloneUserObj.first_given_name(),
1282 cloneUserObj.second_given_name(),
1283 cloneUserObj.family_name()
1286 addrUser = fieldmapper.standardRequest(
1287 ['open-ils.actor', 'open-ils.actor.user.retrieve.parts'],
1289 openils.User.authtoken,
1291 ['first_given_name', 'second_given_name', 'family_name']
1296 link.innerHTML = (addrUser.map(function(name) { return (name) ? name+' ' : '' })+'').replace(/,/g,''); // TODO i18n
1297 link.onclick = function() {
1298 if(openils.XUL.isXUL()) {
1299 window.xulG.spawn_editor({ses:openils.User.authtoken, usr:addr.usr()})
1301 parent.location.href = location.href.replace(/clone=\d+/, 'usr=' + addr.usr());
1306 } else if(row.getAttribute('name') == 'uedit-addr-divider') {
1307 // link up the billing/mailing address and give the inputs IDs so we can acces the later
1310 var ba = getByName(row, 'billing_address');
1311 ba.id = 'uedit-billing-address-' + id;
1312 if(mkLinks || (patron.billing_address() && patron.billing_address().id() == id))
1316 var ma = getByName(row, 'mailing_address');
1317 ma.id = 'uedit-mailing-address-' + id;
1318 if(mkLinks || (patron.mailing_address() && patron.mailing_address().id() == id))
1321 var btn = dojo.query('[name=delete-button]', row)[0];
1322 if(btn) btn.onclick = function(){ uEditDeleteAddr(id) };
1328 function uEditApproveAddress(addr) {
1329 fieldmapper.standardRequest(
1330 ['open-ils.actor', 'open-ils.actor.user.pending_address.approve'],
1332 params: [openils.User.authtoken, addr],
1334 oncomplete : function(r) {
1335 var oldId = openils.Util.readResponse(r);
1337 // remove addrs from UI
1340 function(addr) { uEditDeleteAddr(addr.id(), true); }
1345 // remove the replaced address
1346 if(oldId != addr.id()) {
1348 patron.addresses().filter(
1349 function(i) { return (i.id() != oldId); }
1354 // fix the the new address
1356 addr.replaces(null);
1369 function uEditDeleteAddr(id, noAlert) {
1370 if (patron.isnew() && orgSettings['ui.patron.registration.require_address']) {
1371 if (dojo.query('tr[name=uedit-addr-divider]').length < 2) {
1372 alert(localeStrings.NEED_ADDRESS);
1377 if(!confirm(dojo.string.substitute(localeStrings.DELETE_ADDRESS, [id]))) return;
1379 var addr = patron.addresses().filter(function(i){return (i.id() == id)})[0];
1380 if (addr) { addr.isdeleted(1); }
1381 var m_a = patron.mailing_address();
1382 if (typeof m_a == 'object' && m_a != null) { m_a = m_a.id(); }
1383 if (m_a == id) { patron.mailing_address(null); }
1384 var b_a = patron.billing_address();
1385 if (typeof b_a == 'object' && b_a != null) { b_a = b_a.id(); }
1386 if (b_a == id) { patron.billing_address(null); }
1388 var rows = dojo.query('tr[addr='+id+']', tbody);
1389 for(var i = 0; i < rows.length; i++)
1390 rows[i].parentNode.removeChild(rows[i]);
1391 widgetPile = widgetPile.filter(function(w){return (w._addr != id)});
1394 function uEditToggleRequired() {
1395 if((tbody.className +'').match(/hide-non-required/))
1396 openils.Util.removeCSSClass(tbody, 'hide-non-required');
1398 openils.Util.addCSSClass(tbody, 'hide-non-required');
1399 openils.Util.toggle('uedit-show-required');
1400 openils.Util.toggle('uedit-show-all');
1403 function printable_output() {
1404 var temp; var s = '=-=-=-=\r\n';
1405 for (var idx in widgetPile) {
1406 var w = widgetPile[idx];
1407 var val = uEditWidgetVal(w);
1409 if (typeof w.idlField == 'undefined') {
1411 if (w._wtype == 'statcat') {
1412 var stat = statCats.filter(
1414 return (m.id() == w._statcat) })[0];
1415 label = stat.name();
1416 } else if (w._wtype == 'survey') {
1417 var survey = surveys.filter(
1419 return (m.id() == w._survey) })[0];
1420 var question = survey.questions().filter(
1422 return (m.id() == w._question) })[0];
1423 label = survey.name() + ' : ' + question.question();
1428 label = w.idlField.label;
1430 if (temp != w._wtype) {
1434 s += label + ':\t' + (typeof val == 'object' ? '' : val) + '\r\n';
1440 openils.Util.addOnLoad(load);