2 angular.module('egCoreMod')
3 // toss tihs onto egCoreMod since the page app may vary
5 .factory('patronRegSvc', ['$q', 'egCore', 'egLovefield', function($q, egCore, egLovefield) {
8 field_doc : {}, // config.idl_field_doc
9 profiles : [], // permission groups
10 edit_profiles : [], // perm groups we can modify
12 user_settings : {}, // applied user settings
13 user_setting_types : {}, // config.usr_setting_type
14 opt_in_setting_types : {}, // config.usr_setting_type for event-def opt-in
16 survey_questions : {},
18 survey_responses : {}, // survey.responses for loaded patron in progress
20 stat_cat_entry_maps : {}, // cat.id to selected value
21 virt_id : -1, // virtual ID for new objects
22 init_done : false // have we loaded our initialization data?
25 // Launch a series of parallel data retrieval calls.
26 service.init = function(scope) {
28 // These are fetched with every instance of the page.
30 service.get_user_settings(),
31 service.get_clone_user(),
32 service.get_stage_user()
36 if (!service.init_done) {
37 // These are fetched with every instance of the app.
39 service.get_field_doc(),
40 service.get_perm_groups(),
41 service.get_ident_types(),
42 service.get_org_settings(),
43 service.get_stat_cats(),
44 service.get_surveys(),
45 service.get_net_access_levels()
47 service.init_done = true;
50 return $q.all(common_data.concat(page_data));
53 service.get_clone_user = function() {
54 if (!service.clone_id) return $q.when();
55 // we could load egUser and use its get() function, but loading
56 // user.js into the standalone register UI would mean creating a
57 // new module, since egUser is not loaded into egCoreMod. This
59 return egCore.net.request(
61 'open-ils.actor.user.fleshed.retrieve',
62 egCore.auth.token(), service.clone_id,
63 ['billing_address', 'mailing_address'])
64 .then(function(cuser) {
65 if (e = egCore.evt.parse(cuser)) {
68 service.clone_user = cuser;
73 // When editing a user with addresses linked to other users, fetch
74 // the linked user(s) so we can display their names and edit links.
75 service.get_linked_addr_users = function(addrs) {
76 angular.forEach(addrs, function(addr) {
77 if (addr.usr == service.existing_patron.id()) return;
78 egCore.pcrud.retrieve('au', addr.usr)
80 addr._linked_owner_id = usr.id();
81 addr._linked_owner = service.format_name(
83 usr.first_given_name(),
84 usr.second_given_name()
90 service.apply_secondary_groups = function(user_id, group_ids) {
91 return egCore.net.request(
93 'open-ils.actor.user.set_groups',
94 egCore.auth.token(), user_id, group_ids)
95 .then(function(resp) {
99 // debugging -- should be no events
100 alert('linked groups failure ' + egCore.evt.parse(resp));
105 service.get_stage_user = function() {
106 if (!service.stage_username) return $q.when();
108 // fetch the staged user object
109 return egCore.net.request(
111 'open-ils.actor.user.stage.retrieve.by_username',
113 service.stage_username
114 ).then(function(suser) {
115 if (e = egCore.evt.parse(suser)) {
118 service.stage_user = suser;
122 if (!service.stage_user) return;
123 var requestor = service.stage_user.user.requesting_usr();
125 if (!requestor) return;
127 // fetch the requesting user
128 return egCore.net.request(
130 'open-ils.actor.user.retrieve.parts',
133 ['family_name', 'first_given_name', 'second_given_name']
134 ).then(function(parts) {
135 service.stage_user_requestor =
136 service.format_name(parts[0], parts[1], parts[2]);
141 // See note above about not loading egUser.
143 service.format_name = function(last, first, middle) {
144 return last + ', ' + first + (middle ? ' ' + middle : '');
147 service.check_dupe_username = function(usrname) {
149 // empty usernames can't be dupes
150 if (!usrname) return $q.when(false);
152 // avoid dupe check if username matches the originally loaded usrname
153 if (service.existing_patron) {
154 if (usrname == service.existing_patron.usrname())
155 return $q.when(false);
158 return egCore.net.request(
160 'open-ils.actor.username.exists',
161 egCore.auth.token(), usrname);
164 //service.check_grp_app_perm = function(grp_id) {
166 // determine which user groups our user is not allowed to modify
167 service.set_edit_profiles = function() {
168 var all_app_perms = [];
169 var failed_perms = [];
171 // extract the application permissions
172 angular.forEach(service.profiles, function(grp) {
173 if (grp.application_perm())
174 all_app_perms.push(grp.application_perm());
177 // fill in service.edit_profiles by inspecting failed_perms
178 function traverse_grp_tree(grp, failed) {
180 failed_perms.indexOf(grp.application_perm()) > -1;
182 if (!failed) service.edit_profiles.push(grp);
185 service.profiles.filter( // children of grp
186 function(p) { return p.parent() == grp.id() }),
187 function(child) {traverse_grp_tree(child, failed)}
191 return egCore.perm.hasPermAt(all_app_perms, true).then(
192 function(perm_orgs) {
193 angular.forEach(all_app_perms, function(p) {
194 if (perm_orgs[p].length == 0)
195 failed_perms.push(p);
198 traverse_grp_tree(egCore.env.pgt.tree);
203 // resolves to a hash of perm-name => boolean value indicating
204 // wether the user has the permission at org_id.
205 service.has_perms_for_org = function(org_id) {
210 'CREATE_USER_GROUP_LINK',
211 'UPDATE_PATRON_COLLECTIONS_EXEMPT',
212 'UPDATE_PATRON_CLAIM_RETURN_COUNT',
213 'UPDATE_PATRON_CLAIM_NEVER_CHECKED_OUT_COUNT',
214 'UPDATE_PATRON_ACTIVE_CARD',
215 'UPDATE_PATRON_PRIMARY_CARD'
218 return egCore.perm.hasPermAt(perms_needed, true)
219 .then(function(perm_map) {
221 angular.forEach(perms_needed, function(perm) {
223 Boolean(perm_map[perm].indexOf(org_id) > -1);
230 service.get_surveys = function() {
231 var org_ids = egCore.org.fullPath(egCore.auth.user().ws_ou(), true);
233 return egCore.pcrud.search('asv', {
235 start_date : {'<=' : 'now'},
236 end_date : {'>=' : 'now'}
245 ).then(function(surveys) {
246 surveys = surveys.sort(function(a,b) {
247 return a.name() < b.name() ? -1 : 1 });
248 service.surveys = surveys;
249 angular.forEach(surveys, function(survey) {
250 angular.forEach(survey.questions(), function(question) {
251 service.survey_questions[question.id()] = question;
252 angular.forEach(question.answers(), function(answer) {
253 service.survey_answers[answer.id()] = answer;
258 egLovefield.setListInOfflineCache('asv', service.surveys)
259 egLovefield.setListInOfflineCache('asvq', service.survey_questions)
260 egLovefield.setListInOfflineCache('asva', service.survey_answers)
265 service.get_stat_cats = function() {
266 return egCore.net.request(
268 'open-ils.circ.stat_cat.actor.retrieve.all',
269 egCore.auth.token(), egCore.auth.user().ws_ou()
270 ).then(function(cats) {
271 cats = cats.sort(function(a, b) {
272 return a.name() < b.name() ? -1 : 1});
273 angular.forEach(cats, function(cat) {
275 cat.entries().sort(function(a,b) {
276 return a.value() < b.value() ? -1 : 1
280 service.stat_cats = cats;
281 return egLovefield.setStatCatsCache(cats);
285 service.get_org_settings = function() {
286 return egCore.org.settings([
287 'global.password_regex',
288 'global.juvenile_age_threshold',
289 'patron.password.use_phone',
290 'ui.patron.default_inet_access_level',
291 'ui.patron.default_ident_type',
292 'ui.patron.default_country',
293 'ui.patron.registration.require_address',
294 'circ.holds.behind_desk_pickup_supported',
295 'circ.patron_edit.clone.copy_address',
296 'ui.patron.edit.au.prefix.require',
297 'ui.patron.edit.au.prefix.show',
298 'ui.patron.edit.au.prefix.suggest',
299 'ui.patron.edit.ac.barcode.regex',
300 'ui.patron.edit.au.second_given_name.show',
301 'ui.patron.edit.au.second_given_name.suggest',
302 'ui.patron.edit.au.suffix.show',
303 'ui.patron.edit.au.suffix.suggest',
304 'ui.patron.edit.au.alias.show',
305 'ui.patron.edit.au.alias.suggest',
306 'ui.patron.edit.au.dob.require',
307 'ui.patron.edit.au.dob.show',
308 'ui.patron.edit.au.dob.suggest',
309 'ui.patron.edit.au.dob.calendar',
310 'ui.patron.edit.au.juvenile.show',
311 'ui.patron.edit.au.juvenile.suggest',
312 'ui.patron.edit.au.ident_value.show',
313 'ui.patron.edit.au.ident_value.suggest',
314 'ui.patron.edit.au.ident_value2.show',
315 'ui.patron.edit.au.ident_value2.suggest',
316 'ui.patron.edit.au.email.require',
317 'ui.patron.edit.au.email.show',
318 'ui.patron.edit.au.email.suggest',
319 'ui.patron.edit.au.email.regex',
320 'ui.patron.edit.au.email.example',
321 'ui.patron.edit.au.day_phone.require',
322 'ui.patron.edit.au.day_phone.show',
323 'ui.patron.edit.au.day_phone.suggest',
324 'ui.patron.edit.au.day_phone.regex',
325 'ui.patron.edit.au.day_phone.example',
326 'ui.patron.edit.au.evening_phone.require',
327 'ui.patron.edit.au.evening_phone.show',
328 'ui.patron.edit.au.evening_phone.suggest',
329 'ui.patron.edit.au.evening_phone.regex',
330 'ui.patron.edit.au.evening_phone.example',
331 'ui.patron.edit.au.other_phone.require',
332 'ui.patron.edit.au.other_phone.show',
333 'ui.patron.edit.au.other_phone.suggest',
334 'ui.patron.edit.au.other_phone.regex',
335 'ui.patron.edit.au.other_phone.example',
336 'ui.patron.edit.phone.regex',
337 'ui.patron.edit.phone.example',
338 'ui.patron.edit.au.active.show',
339 'ui.patron.edit.au.active.suggest',
340 'ui.patron.edit.au.barred.show',
341 'ui.patron.edit.au.barred.suggest',
342 'ui.patron.edit.au.master_account.show',
343 'ui.patron.edit.au.master_account.suggest',
344 'ui.patron.edit.au.claims_returned_count.show',
345 'ui.patron.edit.au.claims_returned_count.suggest',
346 'ui.patron.edit.au.claims_never_checked_out_count.show',
347 'ui.patron.edit.au.claims_never_checked_out_count.suggest',
348 'ui.patron.edit.au.alert_message.show',
349 'ui.patron.edit.au.alert_message.suggest',
350 'ui.patron.edit.aua.post_code.regex',
351 'ui.patron.edit.aua.post_code.example',
352 'ui.patron.edit.aua.county.require',
354 'ui.patron.edit.default_suggested',
355 'opac.barcode_regex',
356 'opac.username_regex',
358 'ui.patron.edit.aua.state.require',
359 'ui.patron.edit.aua.state.suggest',
360 'ui.patron.edit.aua.state.show',
361 'ui.admin.work_log.max_entries',
362 'ui.admin.patron_log.max_entries'
363 ]).then(function(settings) {
364 service.org_settings = settings;
365 if (egCore && egCore.env && !egCore.env.aous) {
366 egCore.env.aous = settings;
367 console.log('setting egCore.env.aous');
369 return service.process_org_settings(settings);
373 // some org settings require the retrieval of additional data
374 service.process_org_settings = function(settings) {
376 var promises = [egLovefield.setSettingsCache(settings)];
378 if (settings['sms.enable']) {
379 // fetch SMS carriers
381 egCore.pcrud.search('csc',
384 {'class':'csc', 'field':'name'},
385 {'class':'csc', 'field':'region'}
387 ).then(function(carriers) {
388 service.sms_carriers = carriers;
392 // if other promises are added below, this is not necessary.
393 promises.push($q.when());
396 // other post-org-settings processing goes here,
397 // adding to promises as needed.
399 return $q.all(promises);
402 service.get_ident_types = function() {
403 if (egCore.env.cit) {
404 service.ident_types = egCore.env.cit.list;
407 return egCore.pcrud.retrieveAll('cit', {}, {atomic : true})
408 .then(function(types) {
409 egCore.env.absorbList(types, 'cit')
410 service.ident_types = types
415 service.get_net_access_levels = function() {
416 if (egCore.env.cnal) {
417 service.net_access_levels = egCore.env.cnal.list;
420 return egCore.pcrud.retrieveAll('cnal', {}, {atomic : true})
421 .then(function(levels) {
422 egCore.env.absorbList(levels, 'cnal')
423 service.net_access_levels = levels
428 service.get_perm_groups = function() {
429 if (egCore.env.pgt) {
430 service.profiles = egCore.env.pgt.list;
431 return service.set_edit_profiles();
433 return egCore.pcrud.search('pgt', {parent : null},
434 {flesh : -1, flesh_fields : {pgt : ['children']}}
437 egCore.env.absorbTree(tree, 'pgt')
438 service.profiles = egCore.env.pgt.list;
439 return service.set_edit_profiles();
445 service.get_field_doc = function() {
447 return egCore.pcrud.search('fdoc', {
448 fm_class: ['au', 'ac', 'aua', 'actsc', 'asv', 'asvq', 'asva']})
451 return egLovefield.setListInOfflineCache('fdoc', to_cache)
455 if (!service.field_doc[doc.fm_class()]) {
456 service.field_doc[doc.fm_class()] = {};
458 service.field_doc[doc.fm_class()][doc.field()] = doc;
465 service.get_user_setting_types = function() {
467 // No need to re-fetch the common setting types.
468 if (Object.keys(service.user_setting_types).length)
471 var org_ids = egCore.org.ancestors(egCore.auth.user().ws_ou(), true);
474 'circ.holds_behind_desk',
475 'circ.collections.exempt',
477 'opac.default_phone',
478 'opac.default_pickup_location',
479 'opac.default_sms_carrier',
480 'opac.default_sms_notify'];
482 return egCore.pcrud.search('cust', {
484 {name : static_types}, // common user settings
485 {name : { // opt-in notification user settings
487 select : {atevdef : ['opt_in_setting']},
489 // we only care about opt-in settings for
490 // event_defs our users encounter
491 where : {'+atevdef' : {owner : org_ids}}
495 }, {}, {atomic : true}).then(function(setting_types) {
497 egCore.env.absorbList(setting_types, 'cust'); // why not...
499 angular.forEach(setting_types, function(stype) {
500 service.user_setting_types[stype.name()] = stype;
501 if (static_types.indexOf(stype.name()) == -1) {
502 service.opt_in_setting_types[stype.name()] = stype;
508 service.get_user_settings = function() {
510 return service.get_user_setting_types()
513 var setting_types = Object.values(service.user_setting_types);
515 if (service.patron_id) {
516 // retrieve applied values for the current user
517 // for the setting types we care about.
520 setting_types.map(function(obj) { return obj.name() });
522 return egCore.net.request(
524 'open-ils.actor.patron.settings.retrieve.authoritative',
528 ).then(function(settings) {
529 service.user_settings = settings;
534 // apply default user setting values
535 angular.forEach(setting_types, function(stype, index) {
536 if (stype.reg_default() != undefined) {
537 var val = stype.reg_default();
538 if (stype.datatype() == 'bool') {
539 // A boolean user setting type whose default
540 // value starts with t/T is considered 'true',
542 val = Boolean((val+'').match(/^t/i));
544 service.user_settings[stype.name()] = val;
551 service.invalidate_field = function(patron, field) {
552 console.log('Invalidating patron field ' + field);
554 return egCore.net.request(
556 'open-ils.actor.invalidate.' + field,
557 egCore.auth.token(), patron.id, null, patron.home_ou.id()
559 ).then(function(res) {
560 // clear the invalid value from the form
563 // update last_xact_id so future save operations
564 // on this patron will be allowed
565 patron.last_xact_id = res.payload.last_xact_id[patron.id];
569 service.dupe_patron_search = function(patron, type, value) {
572 console.log('Dupe search called with "'+ type +'" and value '+ value);
574 if (type.match(/phone/)) type = 'phone'; // day_phone, etc.
579 var fname = patron.first_given_name;
580 var lname = patron.family_name;
581 if (!(fname && lname)) return $q.when({count:0});
583 first_given_name : {value : fname, group : 0},
584 family_name : {value : lname, group : 0}
589 search = {email : {value : value, group : 0}};
593 search = {ident : {value : value, group : 2}};
597 search = {phone : {value : value, group : 2}};
602 angular.forEach(['street1', 'street2', 'city', 'post_code'],
605 search[field] = {value : value[field], group: 1};
611 return egCore.net.request(
613 'open-ils.actor.patron.search.advanced',
614 egCore.auth.token(), search, null, null, 1
615 ).then(function(res) {
616 res = res.filter(function(id) {return id != patron.id});
624 service.init_patron = function(current) {
627 return $q.when(service.init_new_patron());
629 service.patron = current;
630 return $q.when(service.init_existing_patron(current));
633 service.ingest_address = function(patron, addr) {
634 addr.valid = addr.valid == 't';
635 addr.within_city_limits = addr.within_city_limits == 't';
636 addr._is_mailing = (patron.mailing_address &&
637 addr.id == patron.mailing_address.id);
638 addr._is_billing = (patron.billing_address &&
639 addr.id == patron.billing_address.id);
643 * Existing patron objects reqire some data munging before insertion
646 * 1. Turn everything into a hash
647 * 2. ... Except certain fields (selectors) whose widgets require objects
648 * 3. Bools must be Boolean, not t/f.
650 service.init_existing_patron = function(current) {
652 service.existing_patron = current;
654 var patron = egCore.idl.toHash(current);
656 patron.home_ou = egCore.org.get(patron.home_ou.id);
657 patron.expire_date = new Date(Date.parse(patron.expire_date));
658 patron.dob = service.parse_dob(patron.dob);
659 patron.profile = current.profile(); // pre-hash version
660 patron.net_access_level = current.net_access_level();
661 patron.ident_type = current.ident_type();
662 patron.ident_type2 = current.ident_type2();
663 patron.groups = current.groups(); // pre-hash
666 ['juvenile', 'barred', 'active', 'master_account'],
667 function(field) { patron[field] = patron[field] == 't'; }
670 angular.forEach(patron.cards, function(card) {
671 card.active = card.active == 't';
672 if (card.id == patron.card.id) {
674 card._primary = 'on';
678 angular.forEach(patron.addresses,
679 function(addr) { service.ingest_address(patron, addr) });
681 service.get_linked_addr_users(patron.addresses);
683 // Remove stat cat entries that link to out-of-scope stat
684 // cats. With this, we avoid unnecessarily updating (or worse,
685 // modifying) stat cat values that are not ours to modify.
686 patron.stat_cat_entries = patron.stat_cat_entries.filter(
689 // service.stat_cats only contains in-scope stat cats.
690 service.stat_cats.filter(function(cat) {
691 return (cat.id() == map.stat_cat.id) })[0]
696 // toss entries for existing stat cat maps into our living
697 // stat cat entry map, which is modified within the template.
698 angular.forEach(patron.stat_cat_entries, function(map) {
699 service.stat_cat_entry_maps[map.stat_cat.id] = map.stat_cat_entry;
702 service.patron = patron;
706 service.init_new_patron = function() {
708 id : service.virt_id--,
711 address_type : egCore.strings.REG_ADDR_TYPE,
714 within_city_limits : false,
715 country : service.org_settings['ui.patron.default_country'],
719 id : service.virt_id--,
730 home_ou : egCore.org.get(egCore.auth.user().ws_ou()),
731 stat_cat_entries : [],
736 if (service.clone_user)
737 service.copy_clone_data(user);
739 if (service.stage_user)
740 service.copy_stage_data(user);
745 // dob is always YYYY-MM-DD
746 // Dates of birth do not contain timezone info, which can lead to
747 // inconcistent timezone handling, potentially representing
748 // different points in time, depending on the implementation.
749 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
750 // See "Differences in assumed time zone"
751 // TODO: move this into egDate ?
752 service.parse_dob = function(dob) {
753 if (!dob) return null;
754 var parts = dob.split('-');
755 var d = new Date(); // always local time zone, yay.
756 d.setFullYear(parts[0]);
757 d.setMonth(parts[1] - 1);
762 service.copy_stage_data = function(user) {
763 var cuser = service.stage_user;
765 // copy the data into our new user object
767 for (var key in egCore.idl.classes.stgu.field_map) {
768 if (egCore.idl.classes.au.field_map[key] &&
769 !egCore.idl.classes.stgu.field_map[key].virtual) {
770 if (cuser.user[key]() !== null)
771 user[key] = cuser.user[key]();
775 if (user.home_ou) user.home_ou = egCore.org.get(user.home_ou);
776 if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
778 user.ident_type = egCore.env.cit.map[user.ident_type];
779 if (user.ident_type2)
780 user.ident_type2 = egCore.env.cit.map[user.ident_type2];
781 user.dob = service.parse_dob(user.dob);
783 // Clear the usrname if it looks like a UUID
784 if (user.usrname.replace(/-/g,'').match(/[0-9a-f]{32}/))
787 // Don't use stub address if we have one from the staged user.
788 if (cuser.mailing_addresses.length || cuser.billing_addresses.length)
791 // is_mailing=false implies is_billing
792 function addr_from_stage(stage_addr) {
793 if (!stage_addr) return;
794 var cls = stage_addr.classname;
797 id : service.virt_id--,
801 _is_mailing : cls == 'stgma',
802 _is_billing : cls == 'stgba'
805 user.mailing_address = addr;
806 user.addresses.push(addr);
808 for (var key in egCore.idl.classes[cls].field_map) {
809 if (egCore.idl.classes.aua.field_map[key] &&
810 !egCore.idl.classes[cls].field_map[key].virtual) {
811 if (stage_addr[key]() !== null)
812 addr[key] = stage_addr[key]();
817 addr_from_stage(cuser.mailing_addresses[0]);
818 addr_from_stage(cuser.billing_addresses[0]);
820 if (user.addresses.length == 1) {
821 // If there is only one address,
822 // use it as both mailing and billing.
823 var addr = user.addresses[0];
824 addr._is_mailing = addr._is_billing = true;
825 user.mailing_address = user.billing_address = addr;
828 if (cuser.cards.length) {
830 id : service.virt_id--,
831 barcode : cuser.cards[0].barcode(),
837 user.cards.push(user.card);
838 if (user.usrname == '')
839 user.usrname = card.barcode;
842 angular.forEach(cuser.settings, function(setting) {
843 service.user_settings[setting.setting()] = Boolean(setting.value());
847 // copy select values from the cloned user to the new user.
849 service.copy_clone_data = function(user) {
850 var clone_user = service.clone_user;
852 // flesh the home org locally
853 user.home_ou = egCore.org.get(clone_user.home_ou());
854 if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
856 if (!clone_user.billing_address() &&
857 !clone_user.mailing_address())
858 return; // no addresses to copy or link
860 // if the cloned user has any addresses, we don't need
861 // the stub address created in init_new_patron.
865 service.org_settings['circ.patron_edit.clone.copy_address'];
874 angular.forEach(clone_fields, function(field) {
875 user[field] = clone_user[field]();
878 if (copy_addresses) {
879 var bill_addr, mail_addr;
881 // copy the billing and mailing addresses into new addresses
882 function clone_addr(addr) {
883 var new_addr = egCore.idl.toHash(addr);
884 new_addr.id = service.virt_id--;
885 new_addr.usr = user.id;
886 new_addr.isnew = true;
887 new_addr.valid = true;
888 user.addresses.push(new_addr);
892 if (bill_addr = clone_user.billing_address()) {
893 var addr = clone_addr(bill_addr);
894 addr._is_billing = true;
895 user.billing_address = addr;
898 if (mail_addr = clone_user.mailing_address()) {
900 if (bill_addr && bill_addr.id() == mail_addr.id()) {
901 user.mailing_address = user.billing_address;
902 user.mailing_address._is_mailing = true;
904 var addr = clone_addr(mail_addr);
905 addr._is_mailing = true;
906 user.mailing_address = addr;
910 // if there is no billing addr, use the mailing addr
911 user.billing_address = user.mailing_address;
912 user.billing_address._is_billing = true;
919 // link the billing and mailing addresses
921 if (addr = clone_user.billing_address()) {
922 user.billing_address = egCore.idl.toHash(addr);
923 user.billing_address._is_billing = true;
924 user.addresses.push(user.billing_address);
925 user.billing_address._linked_owner_id = clone_user.id();
926 user.billing_address._linked_owner = service.format_name(
927 clone_user.family_name(),
928 clone_user.first_given_name(),
929 clone_user.second_given_name()
933 if (addr = clone_user.mailing_address()) {
934 if (user.billing_address &&
935 addr.id() == user.billing_address.id) {
936 // mailing matches billing
937 user.mailing_address = user.billing_address;
938 user.mailing_address._is_mailing = true;
940 user.mailing_address = egCore.idl.toHash(addr);
941 user.mailing_address._is_mailing = true;
942 user.addresses.push(user.mailing_address);
943 user.mailing_address._linked_owner_id = clone_user.id();
944 user.mailing_address._linked_owner = service.format_name(
945 clone_user.family_name(),
946 clone_user.first_given_name(),
947 clone_user.second_given_name()
954 // translate the patron back into IDL form
955 service.save_user = function(phash) {
957 var patron = egCore.idl.fromHash('au', phash);
959 patron.home_ou(patron.home_ou().id());
960 patron.expire_date(patron.expire_date().toISOString());
961 patron.profile(patron.profile().id());
963 patron.dob(patron.dob().toISOString().replace(/T.*/,''));
964 if (patron.ident_type())
965 patron.ident_type(patron.ident_type().id());
966 if (patron.net_access_level())
967 patron.net_access_level(patron.net_access_level().id());
970 ['juvenile', 'barred', 'active', 'master_account'],
971 function(field) { patron[field](phash[field] ? 't' : 'f'); }
974 var card_hashes = patron.cards();
976 angular.forEach(card_hashes, function(chash) {
977 var card = egCore.idl.fromHash('ac', chash)
978 card.usr(patron.id());
979 card.active(chash.active ? 't' : 'f');
980 patron.cards().push(card);
981 if (chash._primary) {
986 var addr_hashes = patron.addresses();
987 patron.addresses([]);
988 angular.forEach(addr_hashes, function(addr_hash) {
989 if (!addr_hash.isnew && !addr_hash.isdeleted)
990 addr_hash.ischanged = true;
991 var addr = egCore.idl.fromHash('aua', addr_hash);
992 patron.addresses().push(addr);
993 addr.valid(addr.valid() ? 't' : 'f');
994 addr.within_city_limits(addr.within_city_limits() ? 't' : 'f');
995 if (addr_hash._is_mailing) patron.mailing_address(addr);
996 if (addr_hash._is_billing) patron.billing_address(addr);
999 patron.survey_responses([]);
1000 angular.forEach(service.survey_responses, function(answer) {
1001 var question = service.survey_questions[answer.question()];
1002 var resp = new egCore.idl.asvr();
1004 resp.survey(question.survey());
1005 resp.question(question.id());
1006 resp.answer(answer.id());
1007 resp.usr(patron.id());
1008 resp.answer_date('now');
1009 patron.survey_responses().push(resp);
1012 // re-object-ify the patron stat cat entry maps
1014 angular.forEach(patron.stat_cat_entries(), function(entry) {
1015 var e = egCore.idl.fromHash('actscecm', entry);
1016 e.stat_cat(e.stat_cat().id);
1019 patron.stat_cat_entries(maps);
1021 // service.stat_cat_entry_maps maps stats to values
1022 // patron.stat_cat_entries is an array of stat_cat_entry_usr_map's
1024 service.stat_cat_entry_maps, function(value, cat_id) {
1026 // see if we already have a mapping for this entry
1027 var existing = patron.stat_cat_entries().filter(
1028 function(e) { return e.stat_cat() == cat_id })[0];
1030 if (existing) { // we have a mapping
1031 // if the existing mapping matches the new one,
1032 // there' nothing left to do
1033 if (existing.stat_cat_entry() == value) return;
1035 // mappings differ. delete the old one and create
1037 existing.isdeleted(true);
1040 var newmap = new egCore.idl.actscecm();
1041 newmap.target_usr(patron.id());
1043 newmap.stat_cat(cat_id);
1044 newmap.stat_cat_entry(value);
1045 patron.stat_cat_entries().push(newmap);
1048 if (!patron.isnew()) patron.ischanged(true);
1050 return egCore.net.request(
1052 'open-ils.actor.patron.update',
1053 egCore.auth.token(), patron);
1056 service.remove_staged_user = function() {
1057 if (!service.stage_user) return $q.when();
1058 return egCore.net.request(
1060 'open-ils.actor.user.stage.delete',
1061 egCore.auth.token(),
1062 service.stage_user.user.row_id()
1066 service.save_user_settings = function(new_user, user_settings) {
1069 if (service.patron_id) {
1070 // Update all user editor setting values for existing
1071 // users regardless of whether a value changed.
1072 settings = user_settings;
1075 // Create settings for all non-null setting values for new patrons.
1076 angular.forEach(user_settings, function(val, key) {
1077 if (val !== null) settings[key] = val;
1081 if (Object.keys(settings).length == 0) return $q.when();
1083 return egCore.net.request(
1085 'open-ils.actor.patron.settings.update',
1086 egCore.auth.token(), new_user.id(), settings
1087 ).then(function(resp) {
1092 // Applies field-specific validation regex's from org settings
1093 // to form fields. Be careful not remove any pattern data we
1094 // are not explicitly over-writing in the provided patterns obj.
1095 service.set_field_patterns = function(patterns) {
1096 if (service.org_settings['opac.username_regex']) {
1097 patterns.au.usrname =
1098 new RegExp(service.org_settings['opac.username_regex']);
1101 if (service.org_settings['ui.patron.edit.ac.barcode.regex']) {
1102 patterns.ac.barcode =
1103 new RegExp(service.org_settings['ui.patron.edit.ac.barcode.regex']);
1106 if (service.org_settings['global.password_regex']) {
1107 patterns.au.passwd =
1108 new RegExp(service.org_settings['global.password_regex']);
1111 var phone_reg = service.org_settings['ui.patron.edit.phone.regex'];
1113 // apply generic phone regex first, replace below as needed.
1114 patterns.au.day_phone = new RegExp(phone_reg);
1115 patterns.au.evening_phone = new RegExp(phone_reg);
1116 patterns.au.other_phone = new RegExp(phone_reg);
1119 // the remaining patterns fit a well-known key name pattern
1121 angular.forEach(service.org_settings, function(val, key) {
1123 var parts = key.match(/ui.patron.edit\.(\w+)\.(\w+)\.regex/);
1126 var name = parts[2];
1127 patterns[cls][name] = new RegExp(val);
1134 .controller('PatronRegCtrl',
1135 ['$scope','$routeParams','$q','$uibModal','$window','egCore',
1136 'patronSvc','patronRegSvc','egUnloadPrompt','egAlertDialog',
1138 function($scope , $routeParams , $q , $uibModal , $window , egCore ,
1139 patronSvc , patronRegSvc , egUnloadPrompt, egAlertDialog ,
1142 $scope.page_data_loaded = false;
1143 $scope.hold_notify_type = { phone : null, email : null, sms : null };
1144 $scope.clone_id = patronRegSvc.clone_id = $routeParams.clone_id;
1145 $scope.stage_username =
1146 patronRegSvc.stage_username = $routeParams.stage_username;
1148 patronRegSvc.patron_id = $routeParams.edit_id || $routeParams.id;
1150 // for existing patrons, disable barcode input by default
1151 $scope.disable_bc = $scope.focus_usrname = Boolean($scope.patron_id);
1152 $scope.focus_bc = !Boolean($scope.patron_id);
1153 $scope.address_alerts = [];
1154 $scope.dupe_counts = {};
1156 // map of perm name to true/false for perms the logged in user
1157 // has at the currently selected patron home org unit.
1160 if (!$scope.edit_passthru) {
1161 // in edit more, scope.edit_passthru is delivered to us by
1162 // the enclosing controller. In register mode, there is
1163 // no enclosing controller, so we create our own.
1164 $scope.edit_passthru = {};
1167 // 0=all, 1=suggested, 2=all
1168 $scope.edit_passthru.vis_level = 0;
1170 // Apply default values for new patrons during initial registration
1171 // prs is shorthand for patronSvc
1172 function set_new_patron_defaults(prs) {
1173 if (!$scope.patron.passwd) {
1174 // passsword may originate from staged user.
1175 $scope.generate_password();
1177 $scope.hold_notify_type.phone = true;
1178 $scope.hold_notify_type.email = true;
1179 $scope.hold_notify_type.sms = false;
1181 // staged users may be loaded w/ a profile.
1182 $scope.set_expire_date();
1184 if (prs.org_settings['ui.patron.default_ident_type']) {
1185 // $scope.patron needs this field to be an object
1186 var id = prs.org_settings['ui.patron.default_ident_type'];
1187 var ident_type = $scope.ident_types.filter(
1188 function(type) { return type.id() == id })[0];
1189 $scope.patron.ident_type = ident_type;
1191 if (prs.org_settings['ui.patron.default_inet_access_level']) {
1192 // $scope.patron needs this field to be an object
1193 var id = prs.org_settings['ui.patron.default_inet_access_level'];
1194 var level = $scope.net_access_levels.filter(
1195 function(lvl) { return lvl.id() == id })[0];
1196 $scope.patron.net_access_level = level;
1198 if (prs.org_settings['ui.patron.default_country']) {
1199 $scope.patron.addresses[0].country =
1200 prs.org_settings['ui.patron.default_country'];
1204 // A null or undefined pattern leads to exceptions. Before the
1205 // patterns are loaded from the server, default all patterns
1206 // to an innocuous regex. To avoid re-creating numerous
1207 // RegExp objects, cache the stub RegExp after initial creation.
1208 // note: angular docs say ng-pattern accepts a regexp or string,
1209 // but as of writing, it only works with a regexp object.
1210 // (Likely an angular 1.2 vs. 1.4 issue).
1211 var field_patterns = {au : {}, ac : {}, aua : {}};
1212 $scope.field_pattern = function(cls, field) {
1213 if (!field_patterns[cls][field])
1214 field_patterns[cls][field] = new RegExp('.*');
1215 return field_patterns[cls][field];
1218 // Main page load function. Kicks off tab init and data loading.
1221 $scope.initTab ? // initTab comes from patron app
1222 $scope.initTab('edit', $routeParams.id) : $q.when(),
1224 patronRegSvc.init(),
1226 ]).then(function(){ return patronRegSvc.init_patron(patronSvc ? patronSvc.current : patronRegSvc.patron ) })
1227 .then(function(patron) {
1228 // called after initTab and patronRegSvc.init have completed
1229 // in standalone mode, we have no patronSvc
1230 var prs = patronRegSvc;
1231 $scope.patron = patron;
1232 $scope.field_doc = prs.field_doc;
1233 $scope.edit_profiles = prs.edit_profiles;
1234 $scope.ident_types = prs.ident_types;
1235 $scope.net_access_levels = prs.net_access_levels;
1236 $scope.user_setting_types = prs.user_setting_types;
1237 $scope.opt_in_setting_types = prs.opt_in_setting_types;
1238 $scope.org_settings = prs.org_settings;
1239 $scope.sms_carriers = prs.sms_carriers;
1240 $scope.stat_cats = prs.stat_cats;
1241 $scope.surveys = prs.surveys;
1242 $scope.survey_responses = prs.survey_responses;
1243 $scope.stat_cat_entry_maps = prs.stat_cat_entry_maps;
1244 $scope.stage_user = prs.stage_user;
1245 $scope.stage_user_requestor = prs.stage_user_requestor;
1247 $scope.user_settings = prs.user_settings;
1248 prs.user_settings = {};
1250 // If a default pickup lib is applied to the patron, apply it
1251 // to the UI at page load time. Otherwise, leave the value unset.
1252 if ($scope.user_settings['opac.default_pickup_location']) {
1253 $scope.patron._pickup_lib = egCore.org.get(
1254 $scope.user_settings['opac.default_pickup_location']);
1257 extract_hold_notify();
1258 if ($scope.patron.isnew)
1259 set_new_patron_defaults(prs);
1261 $scope.handle_home_org_changed();
1263 if ($scope.org_settings['ui.patron.edit.default_suggested'])
1264 $scope.edit_passthru.vis_level = 1;
1266 // Stat cats are fetched from open-ils.storage, where 't'==1
1267 $scope.hasRequiredStatCat = prs.stat_cats.filter(
1268 function(cat) {return cat.required() == 1} ).length > 0;
1270 $scope.page_data_loaded = true;
1272 prs.set_field_patterns(field_patterns);
1273 apply_username_regex();
1275 add_date_watchers();
1278 function add_date_watchers() {
1280 $scope.$watch('patron.dob', function(newVal, oldVal) {
1281 // Even though this runs after page data load, there
1282 // are still times when it fires unnecessarily.
1283 if (newVal === oldVal) return;
1285 console.debug('dob change: ' + newVal + ' : ' + oldVal);
1286 maintain_juvenile_flag();
1289 // No need to watch expire_date
1293 // update the currently displayed field documentation
1294 $scope.set_selected_field_doc = function(cls, field) {
1295 $scope.selected_field_doc = $scope.field_doc[cls][field];
1298 // returns the tree depth of the selected profile group tree node.
1299 $scope.pgt_depth = function(grp) {
1301 while (grp = egCore.env.pgt.map[grp.parent()]) d++;
1305 // IDL fields used for labels in the UI.
1306 $scope.idl_fields = {
1307 au : egCore.idl.classes.au.field_map,
1308 ac : egCore.idl.classes.ac.field_map,
1309 aua : egCore.idl.classes.aua.field_map
1312 // field visibility cache. Some fields are universally required.
1313 // 3 == value universally required
1314 // 2 == field is visible by default
1315 // 1 == field is suggested by default
1316 var field_visibility = {};
1317 var default_field_visibility = {
1321 'au.first_given_name' : 3,
1322 'au.family_name' : 3,
1323 'au.ident_type' : 3,
1324 'au.ident_type2' : 2,
1327 'au.expire_date' : 3,
1328 'au.net_access_level' : 3,
1329 'aua.address_type' : 3,
1330 'aua.post_code' : 3,
1338 'aua.within_city_limits' : 2,
1343 // Returns true if the selected field should be visible
1344 // given the current required/suggested/all setting.
1345 // The visibility flag applied to each field as a result of calling
1346 // this function also sets (via the same flag) the requiredness state.
1347 $scope.show_field = function(field_key) {
1348 // org settings have not been received yet.
1349 if (!$scope.org_settings) return false;
1351 if (field_visibility[field_key] == undefined) {
1352 // compile and cache the visibility for the selected field
1354 var req_set = 'ui.patron.edit.' + field_key + '.require';
1355 var sho_set = 'ui.patron.edit.' + field_key + '.show';
1356 var sug_set = 'ui.patron.edit.' + field_key + '.suggest';
1358 if ($scope.org_settings[req_set]) {
1359 field_visibility[field_key] = 3;
1361 } else if ($scope.org_settings[sho_set]) {
1362 field_visibility[field_key] = 2;
1364 } else if ($scope.org_settings[sug_set]) {
1365 field_visibility[field_key] = 1;
1369 if (field_visibility[field_key] == undefined) {
1370 // No org settings were applied above. Use the default
1371 // settings if present or assume the field has no
1372 // visibility flags applied.
1373 field_visibility[field_key] =
1374 default_field_visibility[field_key] || 0;
1377 return field_visibility[field_key] >= $scope.edit_passthru.vis_level;
1380 // See $scope.show_field().
1381 // A field with visbility level 3 means it's required.
1382 $scope.field_required = function(cls, field) {
1384 // Value in the password field is not required
1385 // for existing patrons.
1386 if (field == 'passwd' && $scope.patron && !$scope.patron.isnew)
1389 return (field_visibility[cls + '.' + field] == 3);
1392 // generates a random 4-digit password
1393 $scope.generate_password = function() {
1394 $scope.patron.passwd = Math.floor(Math.random()*9000) + 1000;
1397 $scope.set_expire_date = function() {
1398 if (!$scope.patron.profile) return;
1399 var seconds = egCore.date.intervalToSeconds(
1400 $scope.patron.profile.perm_interval());
1401 var now_epoch = new Date().getTime();
1402 $scope.patron.expire_date = new Date(
1403 now_epoch + (seconds * 1000 /* milliseconds */))
1406 // grp is the pgt object
1407 $scope.set_profile = function(grp) {
1408 $scope.patron.profile = grp;
1409 $scope.set_expire_date();
1410 $scope.field_modified();
1413 $scope.invalid_profile = function() {
1416 $scope.patron.profile &&
1417 $scope.patron.profile.usergroup() == 't'
1421 $scope.new_address = function() {
1422 var addr = egCore.idl.toHash(new egCore.idl.aua());
1423 patronRegSvc.ingest_address($scope.patron, addr);
1424 addr.id = patronRegSvc.virt_id--;
1427 addr.within_city_limits = true;
1428 addr.country = $scope.org_settings['ui.patron.default_country'];
1429 $scope.patron.addresses.push(addr);
1432 // keep deleted addresses out of the patron object so
1433 // they won't appear in the UI. They'll be re-inserted
1434 // when the patron is updated.
1435 deleted_addresses = [];
1436 $scope.delete_address = function(id) {
1438 if ($scope.patron.isnew &&
1439 $scope.patron.addresses.length == 1 &&
1440 $scope.org_settings['ui.patron.registration.require_address']) {
1441 egAlertDialog.open(egCore.strings.REG_ADDR_REQUIRED);
1446 angular.forEach($scope.patron.addresses, function(addr) {
1447 if (addr.id == id) {
1449 addr.isdeleted = true;
1450 deleted_addresses.push(addr);
1453 addresses.push(addr);
1456 $scope.patron.addresses = addresses;
1459 $scope.post_code_changed = function(addr) {
1461 'open-ils.search', 'open-ils.search.zip', addr.post_code)
1462 .then(function(resp) {
1464 if (resp.city) addr.city = resp.city;
1465 if (resp.state) addr.state = resp.state;
1466 if (resp.county) addr.county = resp.county;
1467 if (resp.alert) alert(resp.alert);
1471 $scope.replace_card = function() {
1472 $scope.patron.card.active = false;
1473 $scope.patron.card.ischanged = true;
1474 $scope.disable_bc = false;
1476 var new_card = egCore.idl.toHash(new egCore.idl.ac());
1477 new_card.id = patronRegSvc.virt_id--;
1478 new_card.isnew = true;
1479 new_card.active = true;
1480 new_card._primary = 'on';
1481 $scope.patron.card = new_card;
1483 // Remove any previous attempts to replace the card, since they
1484 // may be incomplete or created by accident.
1485 $scope.patron.cards =
1486 $scope.patron.cards.filter(function(c) {return !c.isnew})
1487 $scope.patron.cards.push(new_card);
1490 $scope.day_phone_changed = function(phone) {
1491 if (phone && $scope.patron.isnew &&
1492 $scope.org_settings['patron.password.use_phone']) {
1493 $scope.patron.passwd = phone.substr(-4);
1497 $scope.barcode_changed = function(bc) {
1499 $scope.dupe_barcode = false;
1502 'open-ils.actor.barcode.exists',
1503 egCore.auth.token(), bc
1504 ).then(function(resp) {
1505 if (resp == '1') { // duplicate card
1506 $scope.dupe_barcode = true;
1507 console.log('duplicate barcode detected: ' + bc);
1509 if (!$scope.patron.usrname)
1510 $scope.patron.usrname = bc;
1516 $scope.cards_dialog = function() {
1518 templateUrl: './circ/patron/t_patron_cards_dialog',
1521 ['$scope','$uibModalInstance','cards','perms',
1522 function($scope , $uibModalInstance , cards , perms) {
1523 // scope here is the modal-level scope
1524 $scope.args = {cards : cards};
1525 $scope.perms = perms;
1526 $scope.ok = function() { $uibModalInstance.close($scope.args) }
1527 $scope.cancel = function () { $uibModalInstance.dismiss() }
1530 cards : function() {
1531 // scope here is the controller-level scope
1532 return $scope.patron.cards;
1534 perms : function() {
1535 return $scope.perms;
1540 angular.forEach(args.cards, function(card) {
1541 card.ischanged = true; // assume cards need updating, OK?
1542 if (card._primary == 'on' &&
1543 card.id != $scope.patron.card.id) {
1544 $scope.patron.card = card;
1551 $scope.set_addr_type = function(addr, type) {
1552 var addrs = $scope.patron.addresses;
1553 if (addr['_is_'+type]) {
1554 angular.forEach(addrs, function(a) {
1555 if (a.id != addr.id) a['_is_'+type] = false;
1558 // unchecking mailing/billing means we have to randomly
1559 // select another address to fill that role. Select the
1560 // first address in the list (that does not match the
1562 for (var i = 0; i < addrs.length; i++) {
1563 if (addrs[i].id != addr.id) {
1564 addrs[i]['_is_' + type] = true;
1572 // Translate hold notify preferences from the form/scope back into a
1573 // single user setting value for opac.hold_notify.
1574 function compress_hold_notify() {
1575 var hold_notify_methods = [];
1576 if ($scope.hold_notify_type.phone) {
1577 hold_notify_methods.push('phone');
1579 if ($scope.hold_notify_type.email) {
1580 hold_notify_methods.push('email');
1582 if ($scope.hold_notify_type.sms) {
1583 hold_notify_methods.push('sms');
1586 $scope.user_settings['opac.hold_notify'] = hold_notify_methods.join(':');
1589 // dialog for selecting additional permission groups
1590 $scope.secondary_groups_dialog = function() {
1592 templateUrl: './circ/patron/t_patron_groups_dialog',
1595 ['$scope','$uibModalInstance','linked_groups','pgt_depth',
1596 function($scope , $uibModalInstance , linked_groups , pgt_depth) {
1598 $scope.pgt_depth = pgt_depth;
1600 linked_groups : linked_groups,
1601 edit_profiles : patronRegSvc.edit_profiles,
1602 new_profile : patronRegSvc.edit_profiles[0]
1605 // add a new group to the linked groups list
1606 $scope.link_group = function($event, grp) {
1607 var found = false; // avoid duplicates
1608 angular.forEach($scope.args.linked_groups,
1609 function(g) {if (g.id() == grp.id()) found = true});
1610 if (!found) $scope.args.linked_groups.push(grp);
1611 $event.preventDefault(); // avoid close
1614 // remove a group from the linked groups list
1615 $scope.unlink_group = function($event, grp) {
1616 $scope.args.linked_groups =
1617 $scope.args.linked_groups.filter(function(g) {
1618 return g.id() != grp.id()
1620 $event.preventDefault(); // avoid close
1623 $scope.ok = function() { $uibModalInstance.close($scope.args) }
1624 $scope.cancel = function () { $uibModalInstance.dismiss() }
1627 linked_groups : function() { return $scope.patron.groups },
1628 pgt_depth : function() { return $scope.pgt_depth }
1633 if ($scope.patron.isnew) {
1634 // groups must be linked for new patrons after the
1635 // patron is created.
1636 $scope.patron.groups = args.linked_groups;
1640 // update links groups for existing users in real time.
1641 var ids = args.linked_groups.map(function(g) {return g.id()});
1642 patronRegSvc.apply_secondary_groups($scope.patron.id, ids)
1643 .then(function(success) {
1645 $scope.patron.groups = args.linked_groups;
1651 function extract_hold_notify() {
1652 var notify = $scope.user_settings['opac.hold_notify'];
1653 if (!notify) return;
1654 $scope.hold_notify_type.phone = Boolean(notify.match(/phone/));
1655 $scope.hold_notify_type.email = Boolean(notify.match(/email/));
1656 $scope.hold_notify_type.sms = Boolean(notify.match(/sms/));
1659 $scope.invalidate_field = function(field) {
1660 patronRegSvc.invalidate_field($scope.patron, field);
1663 address_alert = function(addr) {
1665 street1: addr.street1,
1666 street2: addr.street2,
1669 county: addr.county,
1670 country: addr.country,
1671 post_code: addr.post_code,
1672 mailing_address: addr._is_mailing,
1673 billing_address: addr._is_billing
1678 'open-ils.actor.address_alert.test',
1679 egCore.auth.token(), egCore.auth.user().ws_ou(), args
1680 ).then(function(res) {
1681 $scope.address_alerts = res;
1685 $scope.dupe_value_changed = function(type, value) {
1686 if (!$scope.dupe_search_encoded)
1687 $scope.dupe_search_encoded = {};
1689 $scope.dupe_counts[type] = 0;
1691 patronRegSvc.dupe_patron_search($scope.patron, type, value)
1692 .then(function(res) {
1693 $scope.dupe_counts[type] = res.count;
1695 $scope.dupe_search_encoded[type] =
1696 encodeURIComponent(js2JSON(res.search));
1698 $scope.dupe_search_encoded[type] = '';
1703 $scope.handle_home_org_changed = function() {
1704 org_id = $scope.patron.home_ou.id();
1705 patronRegSvc.has_perms_for_org(org_id).then(function(map) {
1706 angular.forEach(map, function(v, k) { $scope.perms[k] = v });
1710 $scope.handle_pulib_changed = function(org) {
1711 if (!$scope.user_settings) return; // still rendering
1712 $scope.user_settings['opac.default_pickup_location'] = org.id();
1715 // This is called with every character typed in a form field,
1716 // since that's the only way to gaurantee something has changed.
1717 // See handle_field_changed for ng-change vs. ng-blur.
1718 $scope.field_modified = function() {
1719 // Call attach with every field change, regardless of whether
1720 // it's been called before. This will allow for re-attach after
1721 // the user clicks through the unload warning. egUnloadPrompt
1722 // will ensure we only attach once.
1723 egUnloadPrompt.attach($scope);
1726 // also monitor when form is changed *by the user*, as using
1727 // an ng-change handler doesn't work with eg-date-input
1728 $scope.$watch('reg_form.$pristine', function(newVal, oldVal) {
1729 if (!newVal) egUnloadPrompt.attach($scope);
1732 // username regex (if present) must be removed any time
1733 // the username matches the barcode to avoid firing the
1734 // invalid field handlers.
1735 function apply_username_regex() {
1736 var regex = $scope.org_settings['opac.username_regex'];
1738 if ($scope.patron.card.barcode) {
1739 // username must match the regex or the barcode
1740 field_patterns.au.usrname =
1742 regex + '|^' + $scope.patron.card.barcode + '$');
1744 // username must match the regex
1745 field_patterns.au.usrname = new RegExp(regex);
1748 // username can be any format.
1749 field_patterns.au.usrname = new RegExp('.*');
1753 // obj could be the patron, an address, etc.
1754 // This is called any time a form field achieves then loses focus.
1755 // It does not necessarily mean the field has changed.
1756 // The alternative is ng-change, but it's called with each character
1757 // typed, which would be overkill for many of the actions called here.
1758 $scope.handle_field_changed = function(obj, field_name) {
1759 var cls = obj.classname; // set by egIdl
1760 var value = obj[field_name];
1762 console.debug('changing field ' + field_name + ' to ' + value);
1764 switch (field_name) {
1766 if ($scope.patron.day_phone &&
1767 $scope.patron.isnew &&
1768 $scope.org_settings['patron.password.use_phone']) {
1769 $scope.patron.passwd = $scope.patron.day_phone.substr(-4);
1771 case 'evening_phone' :
1772 case 'other_phone' :
1773 $scope.dupe_value_changed(field_name, value);
1777 case 'ident_value2':
1778 $scope.dupe_value_changed('ident', value);
1781 case 'first_given_name':
1783 $scope.dupe_value_changed('name', value);
1787 $scope.dupe_value_changed('email', value);
1793 // dupe search on address wants the address object as the value.
1794 $scope.dupe_value_changed('address', obj);
1799 $scope.post_code_changed(obj);
1803 patronRegSvc.check_dupe_username(value)
1804 .then(function(yes) {$scope.dupe_username = Boolean(yes)});
1808 // TODO: finish barcode_changed handler.
1809 $scope.barcode_changed(value);
1810 apply_username_regex();
1815 // patron.juvenile is set to true if the user was born after
1816 function maintain_juvenile_flag() {
1817 if ( !($scope.patron && $scope.patron.dob) ) return;
1820 $scope.org_settings['global.juvenile_age_threshold']
1823 var base = new Date();
1825 base.setTime(base.getTime() -
1826 Number(egCore.date.intervalToSeconds(juv_interval) + '000'));
1828 $scope.patron.juvenile = ($scope.patron.dob > base);
1831 // returns true (disable) for orgs that cannot have users.
1832 $scope.disable_home_org = function(org_id) {
1833 if (!org_id) return;
1834 var org = egCore.org.get(org_id);
1838 org.ou_type().can_have_users() == 'f'
1842 // returns true (disable) for orgs that cannot have vols (for holds pickup)
1843 $scope.disable_pulib = function(org_id) {
1844 if (!org_id) return;
1845 return !egCore.org.CanHaveVolumes(org_id);
1848 // Returns true if the Save and Save & Clone buttons should be disabled.
1849 $scope.edit_passthru.hide_save_actions = function() {
1850 return $scope.patron.isnew ?
1851 !$scope.perms.CREATE_USER :
1852 !$scope.perms.UPDATE_USER;
1855 // Returns true if any input elements are tagged as invalid
1856 // via Angular patterns or required attributes.
1857 function form_has_invalid_fields() {
1858 return $('#patron-reg-container .ng-invalid').length > 0;
1861 function form_is_incomplete() {
1863 $scope.dupe_username ||
1864 $scope.dupe_barcode ||
1865 form_has_invalid_fields()
1870 $scope.edit_passthru.save = function(save_args) {
1871 if (!save_args) save_args = {};
1873 if (form_is_incomplete()) {
1874 // User has not provided valid values for all required fields.
1875 return egAlertDialog.open(egCore.strings.REG_INVALID_FIELDS);
1878 // remove page unload warning prompt
1879 egUnloadPrompt.clear();
1881 // toss the deleted addresses back into the patron's list of
1882 // addresses so it's included in the update
1883 $scope.patron.addresses =
1884 $scope.patron.addresses.concat(deleted_addresses);
1886 compress_hold_notify();
1890 patronRegSvc.save_user($scope.patron)
1891 .then(function(new_user) {
1892 if (new_user && new_user.classname) {
1893 updated_user = new_user;
1894 return patronRegSvc.save_user_settings(
1895 new_user, $scope.user_settings);
1897 var evt = egCore.evt.parse(new_user);
1899 if (evt && evt.textcode == 'XACT_COLLISION') {
1900 return egAlertDialog.open(
1901 egCore.strings.PATRON_EDIT_COLLISION).result;
1904 // debug only -- should not get here.
1905 alert('Patron update failed. \n\n' + js2JSON(new_user));
1908 }).then(function() {
1910 // only remove the staged user if the update succeeded.
1912 return patronRegSvc.remove_staged_user();
1916 }).then(function() {
1918 // linked groups for new users must be created after the new
1920 if ($scope.patron.isnew &&
1921 $scope.patron.groups && $scope.patron.groups.length) {
1922 var ids = $scope.patron.groups.map(function(g) {return g.id()});
1923 return patronRegSvc.apply_secondary_groups(updated_user.id(), ids)
1928 }).then(function() {
1933 ? egCore.strings.EG_WORK_LOG_REGISTERED_PATRON
1934 : egCore.strings.EG_WORK_LOG_EDITED_PATRON, {
1935 'action' : $scope.patron.isnew ? 'registered_patron' : 'edited_patron',
1936 'patron_id' : updated_user.id()
1941 // reloading the page means potentially losing some information
1942 // (e.g. last patron search), but is the only way to ensure all
1943 // components are properly updated to reflect the modified patron.
1944 if (updated_user && save_args.clone) {
1945 // open a separate tab for registering a new
1946 // patron from our cloned data.
1947 var url = 'https://'
1948 + $window.location.hostname
1949 + egCore.env.basePath
1950 + '/circ/patron/register/clone/'
1951 + updated_user.id();
1952 $window.open(url, '_blank').focus();
1955 // reload the current page
1956 $window.location.href = location.href;
1961 $scope.edit_passthru.print = function() {
1962 var print_data = {patron : $scope.patron}
1964 return egCore.print.print({
1965 context : 'default',
1966 template : 'patron_data',