2 angular.module('egCoreMod')
3 // toss tihs onto egCoreMod since the page app may vary
5 .factory('patronRegSvc', ['$q', '$filter', 'egCore', 'egLovefield', function($q, $filter, egCore, egLovefield) {
8 field_doc : {}, // config.idl_field_doc
9 profiles : [], // permission groups
10 profile_entries : [], // permission gorup display entries
11 edit_profiles : [], // perm groups we can modify
12 edit_profile_entries : [], // perm group display entries we can modify
14 user_settings : {}, // applied user settings
15 user_setting_types : {}, // config.usr_setting_type
16 opt_in_setting_types : {}, // config.usr_setting_type for event-def opt-in
18 survey_questions : {},
20 survey_responses : {}, // survey.responses for loaded patron in progress
22 stat_cat_entry_maps : {}, // cat.id to selected value
23 virt_id : -1, // virtual ID for new objects
25 init_done : false // have we loaded our initialization data?
28 // Launch a series of parallel data retrieval calls.
29 service.init = function(scope) {
31 // These are fetched with every instance of the page.
33 service.get_user_settings(),
34 service.get_clone_user(),
35 service.get_stage_user()
39 if (!service.init_done) {
40 // These are fetched with every instance of the app.
42 service.get_field_doc(),
43 service.get_perm_groups(),
44 service.get_perm_group_entries(),
45 service.get_ident_types(),
46 service.get_locales(),
47 service.get_org_settings(),
48 service.get_stat_cats(),
49 service.get_surveys(),
50 service.get_net_access_levels()
52 service.init_done = true;
54 return $q.all(common_data.concat(page_data));
57 service.get_clone_user = function() {
58 if (!service.clone_id) return $q.when();
59 // we could load egUser and use its get() function, but loading
60 // user.js into the standalone register UI would mean creating a
61 // new module, since egUser is not loaded into egCoreMod. This
63 return egCore.net.request(
65 'open-ils.actor.user.fleshed.retrieve',
66 egCore.auth.token(), service.clone_id,
67 ['billing_address', 'mailing_address'])
68 .then(function(cuser) {
69 if (e = egCore.evt.parse(cuser)) {
72 service.clone_user = cuser;
77 // When editing a user with addresses linked to other users, fetch
78 // the linked user(s) so we can display their names and edit links.
79 service.get_linked_addr_users = function(addrs) {
80 angular.forEach(addrs, function(addr) {
81 if (addr.usr == service.existing_patron.id()) return;
82 egCore.pcrud.retrieve('au', addr.usr)
84 addr._linked_owner_id = usr.id();
85 addr._linked_owner = service.format_name(
87 usr.first_given_name(),
88 usr.second_given_name()
94 service.apply_secondary_groups = function(user_id, group_ids) {
95 return egCore.net.request(
97 'open-ils.actor.user.set_groups',
98 egCore.auth.token(), user_id, group_ids)
99 .then(function(resp) {
103 // debugging -- should be no events
104 alert('linked groups failure ' + egCore.evt.parse(resp));
109 service.get_stage_user = function() {
110 if (!service.stage_username) return $q.when();
112 // fetch the staged user object
113 return egCore.net.request(
115 'open-ils.actor.user.stage.retrieve.by_username',
117 service.stage_username
118 ).then(function(suser) {
119 if (e = egCore.evt.parse(suser)) {
122 service.stage_user = suser;
126 if (!service.stage_user) return;
127 var requestor = service.stage_user.user.requesting_usr();
129 if (!requestor) return;
131 // fetch the requesting user
132 return egCore.net.request(
134 'open-ils.actor.user.retrieve.parts',
137 ['family_name', 'first_given_name', 'second_given_name']
138 ).then(function(parts) {
139 service.stage_user_requestor =
140 service.format_name(parts[0], parts[1], parts[2]);
145 // See note above about not loading egUser.
147 service.format_name = function(last, first, middle) {
148 return last + ', ' + first + (middle ? ' ' + middle : '');
151 service.check_dupe_username = function(usrname) {
153 // empty usernames can't be dupes
154 if (!usrname) return $q.when(false);
156 // avoid dupe check if username matches the originally loaded usrname
157 if (service.existing_patron) {
158 if (usrname == service.existing_patron.usrname())
159 return $q.when(false);
162 return egCore.net.request(
164 'open-ils.actor.username.exists',
165 egCore.auth.token(), usrname);
168 // compare string with email address of loaded user, return true if different
169 service.check_email_different = function(email) {
170 if (service.existing_patron) {
171 if (email != service.existing_patron.email()) {
177 //service.check_grp_app_perm = function(grp_id) {
179 // determine which user groups our user is not allowed to modify
180 service.set_edit_profiles = function() {
181 var all_app_perms = [];
182 var failed_perms = [];
184 // extract the application permissions
185 angular.forEach(service.profiles, function(grp) {
186 if (grp.application_perm())
187 all_app_perms.push(grp.application_perm());
190 // fill in service.edit_profiles by inspecting failed_perms
191 function traverse_grp_tree(grp, failed) {
193 failed_perms.indexOf(grp.application_perm()) > -1;
195 if (!failed) service.edit_profiles.push(grp);
198 service.profiles.filter( // children of grp
199 function(p) { return p.parent() == grp.id() }),
200 function(child) {traverse_grp_tree(child, failed)}
204 return egCore.perm.hasPermAt(all_app_perms, true).then(
205 function(perm_orgs) {
206 angular.forEach(all_app_perms, function(p) {
207 if (perm_orgs[p].length == 0)
208 failed_perms.push(p);
211 traverse_grp_tree(egCore.env.pgt.tree);
216 service.set_edit_profile_entries = function() {
217 var all_app_perms = [];
218 var failed_perms = [];
220 // extract the application permissions
221 angular.forEach(service.profile_entries, function(entry) {
222 if (entry.grp().application_perm())
223 all_app_perms.push(entry.grp().application_perm());
226 // fill in service.edit_profiles by inspecting failed_perms
227 function traverse_grp_tree(entry, failed) {
229 failed_perms.indexOf(entry.grp().application_perm()) > -1;
231 if (!failed) service.edit_profile_entries.push(entry);
234 service.profile_entries.filter( // children of grp
235 function(p) { return p.parent() == entry.id() }),
236 function(child) {traverse_grp_tree(child, failed)}
240 return egCore.perm.hasPermAt(all_app_perms, true).then(
241 function(perm_orgs) {
242 angular.forEach(all_app_perms, function(p) {
243 if (perm_orgs[p].length == 0)
244 failed_perms.push(p);
247 angular.forEach(egCore.env.pgtde.tree, function(tree) {
248 traverse_grp_tree(tree);
254 // resolves to a hash of perm-name => boolean value indicating
255 // wether the user has the permission at org_id.
256 service.has_perms_for_org = function(org_id) {
259 'EDIT_SELF_IN_CLIENT',
262 'CREATE_USER_GROUP_LINK',
263 'UPDATE_PATRON_COLLECTIONS_EXEMPT',
264 'UPDATE_PATRON_CLAIM_RETURN_COUNT',
265 'UPDATE_PATRON_CLAIM_NEVER_CHECKED_OUT_COUNT',
266 'UPDATE_PATRON_ACTIVE_CARD',
267 'UPDATE_PATRON_PRIMARY_CARD'
270 return egCore.perm.hasPermAt(perms_needed, true)
271 .then(function(perm_map) {
273 angular.forEach(perms_needed, function(perm) {
275 Boolean(perm_map[perm].indexOf(org_id) > -1);
282 service.get_surveys = function() {
283 var org_ids = egCore.org.fullPath(egCore.auth.user().ws_ou(), true);
285 return egCore.pcrud.search('asv', {
287 start_date : {'<=' : 'now'},
288 end_date : {'>=' : 'now'}
297 ).then(function(surveys) {
298 surveys = surveys.sort(function(a,b) {
299 return a.name() < b.name() ? -1 : 1 });
300 service.surveys = surveys;
301 angular.forEach(surveys, function(survey) {
302 angular.forEach(survey.questions(), function(question) {
303 service.survey_questions[question.id()] = question;
304 angular.forEach(question.answers(), function(answer) {
305 service.survey_answers[answer.id()] = answer;
310 egLovefield.setListInOfflineCache('asv', service.surveys)
311 egLovefield.setListInOfflineCache('asvq', service.survey_questions)
312 egLovefield.setListInOfflineCache('asva', service.survey_answers)
317 service.get_stat_cats = function() {
318 return egCore.net.request(
320 'open-ils.circ.stat_cat.actor.retrieve.all',
321 egCore.auth.token(), egCore.auth.user().ws_ou()
322 ).then(function(cats) {
323 cats = cats.sort(function(a, b) {
324 return a.name() < b.name() ? -1 : 1});
325 angular.forEach(cats, function(cat) {
327 cat.entries().sort(function(a,b) {
328 return a.value() < b.value() ? -1 : 1
332 service.stat_cats = cats;
333 return egLovefield.setStatCatsCache(cats);
337 service.get_org_settings = function() {
338 return egCore.org.settings([
339 'global.password_regex',
340 'global.juvenile_age_threshold',
341 'patron.password.use_phone',
342 'ui.patron.default_inet_access_level',
343 'ui.patron.default_ident_type',
344 'ui.patron.default_country',
345 'ui.patron.registration.require_address',
346 'circ.holds.behind_desk_pickup_supported',
347 'circ.patron_edit.clone.copy_address',
348 'circ.privacy_waiver',
349 'ui.patron.edit.au.prefix.require',
350 'ui.patron.edit.au.prefix.show',
351 'ui.patron.edit.au.prefix.suggest',
352 'ui.patron.edit.ac.barcode.regex',
353 'ui.patron.edit.au.second_given_name.show',
354 'ui.patron.edit.au.second_given_name.suggest',
355 'ui.patron.edit.au.suffix.show',
356 'ui.patron.edit.au.suffix.suggest',
357 'ui.patron.edit.au.alias.show',
358 'ui.patron.edit.au.alias.suggest',
359 'ui.patron.edit.au.dob.require',
360 'ui.patron.edit.au.dob.show',
361 'ui.patron.edit.au.dob.suggest',
362 'ui.patron.edit.au.dob.calendar',
363 'ui.patron.edit.au.dob.example',
364 'ui.patron.edit.au.juvenile.show',
365 'ui.patron.edit.au.juvenile.suggest',
366 'ui.patron.edit.au.ident_value.show',
367 'ui.patron.edit.au.ident_value.require',
368 'ui.patron.edit.au.ident_value.suggest',
369 'ui.patron.edit.au.ident_value2.show',
370 'ui.patron.edit.au.ident_value2.suggest',
371 'ui.patron.edit.au.photo_url.require',
372 'ui.patron.edit.au.photo_url.show',
373 'ui.patron.edit.au.photo_url.suggest',
374 'ui.patron.edit.au.email.require',
375 'ui.patron.edit.au.email.show',
376 'ui.patron.edit.au.email.suggest',
377 'ui.patron.edit.au.email.regex',
378 'ui.patron.edit.au.email.example',
379 'ui.patron.edit.au.day_phone.require',
380 'ui.patron.edit.au.day_phone.show',
381 'ui.patron.edit.au.day_phone.suggest',
382 'ui.patron.edit.au.day_phone.regex',
383 'ui.patron.edit.au.day_phone.example',
384 'ui.patron.edit.au.evening_phone.require',
385 'ui.patron.edit.au.evening_phone.show',
386 'ui.patron.edit.au.evening_phone.suggest',
387 'ui.patron.edit.au.evening_phone.regex',
388 'ui.patron.edit.au.evening_phone.example',
389 'ui.patron.edit.au.other_phone.require',
390 'ui.patron.edit.au.other_phone.show',
391 'ui.patron.edit.au.other_phone.suggest',
392 'ui.patron.edit.au.other_phone.regex',
393 'ui.patron.edit.au.other_phone.example',
394 'ui.patron.edit.phone.regex',
395 'ui.patron.edit.phone.example',
396 'ui.patron.edit.au.active.show',
397 'ui.patron.edit.au.active.suggest',
398 'ui.patron.edit.au.barred.show',
399 'ui.patron.edit.au.barred.suggest',
400 'ui.patron.edit.au.master_account.show',
401 'ui.patron.edit.au.master_account.suggest',
402 'ui.patron.edit.au.claims_returned_count.show',
403 'ui.patron.edit.au.claims_returned_count.suggest',
404 'ui.patron.edit.au.claims_never_checked_out_count.show',
405 'ui.patron.edit.au.claims_never_checked_out_count.suggest',
406 'ui.patron.edit.aua.post_code.regex',
407 'ui.patron.edit.aua.post_code.example',
408 'ui.patron.edit.aua.county.require',
409 'ui.patron.edit.au.guardian.show',
410 'ui.patron.edit.au.guardian.suggest',
411 'ui.patron.edit.guardian_required_for_juv',
413 'ui.patron.edit.default_suggested',
414 'opac.barcode_regex',
415 'opac.username_regex',
417 'ui.patron.edit.aua.state.require',
418 'ui.patron.edit.aua.state.suggest',
419 'ui.patron.edit.aua.state.show',
420 'ui.admin.work_log.max_entries',
421 'ui.admin.patron_log.max_entries'
422 ]).then(function(settings) {
423 service.org_settings = settings;
424 if (egCore && egCore.env && !egCore.env.aous) {
425 egCore.env.aous = settings;
426 console.log('setting egCore.env.aous');
428 return service.process_org_settings(settings);
432 // some org settings require the retrieval of additional data
433 service.process_org_settings = function(settings) {
435 var promises = [egLovefield.setSettingsCache(settings)];
437 if (settings['sms.enable']) {
438 // fetch SMS carriers
440 egCore.pcrud.search('csc',
443 {'class':'csc', 'field':'name'},
444 {'class':'csc', 'field':'region'}
446 ).then(function(carriers) {
447 service.sms_carriers = carriers;
451 // if other promises are added below, this is not necessary.
452 promises.push($q.when());
455 // other post-org-settings processing goes here,
456 // adding to promises as needed.
458 return $q.all(promises);
461 service.get_ident_types = function() {
462 if (egCore.env.cit) {
463 service.ident_types = egCore.env.cit.list;
466 return egCore.pcrud.retrieveAll('cit', {}, {atomic : true})
467 .then(function(types) {
468 egCore.env.absorbList(types, 'cit')
469 service.ident_types = types
474 service.get_locales = function() {
475 if (egCore.env.i18n_l) {
476 service.locales = egCore.env.i18n_l.list;
479 return egCore.pcrud.retrieveAll('i18n_l', {}, {atomic : true})
480 .then(function(locales) {
481 egCore.env.absorbList(locales, 'i18n_l')
482 service.locales = locales
487 service.get_net_access_levels = function() {
488 if (egCore.env.cnal) {
489 service.net_access_levels = egCore.env.cnal.list;
492 return egCore.pcrud.retrieveAll('cnal', {}, {atomic : true})
493 .then(function(levels) {
494 egCore.env.absorbList(levels, 'cnal')
495 service.net_access_levels = levels
500 service.get_perm_groups = function() {
501 if (egCore.env.pgt) {
502 service.profiles = egCore.env.pgt.list;
503 return service.set_edit_profiles();
505 return egCore.pcrud.search('pgt', {parent : null},
506 {flesh : -1, flesh_fields : {pgt : ['children']}}
509 egCore.env.absorbTree(tree, 'pgt')
510 service.profiles = egCore.env.pgt.list;
511 return service.set_edit_profiles();
517 service.searchPermGroupEntries = function(org) {
518 return egCore.pcrud.search('pgtde', {org: org, parent: null},
519 {flesh: -1, flesh_fields: {pgtde: ['grp', 'children']}, 'order_by':{'pgtde':'position desc'}}, {atomic: true}
520 ).then(function(treeArray) {
521 if (!treeArray.length && egCore.org.get(org).parent_ou()) {
522 return service.searchPermGroupEntries(egCore.org.get(org).parent_ou());
528 service.get_perm_group_entries = function() {
529 if (egCore.env.pgtde) {
530 service.profile_entries = egCore.env.pgtde.list;
531 return service.set_edit_profile_entries();
533 return service.searchPermGroupEntries(egCore.auth.user().ws_ou()).then(function(treeArray) {
534 function compare(a,b) {
535 if (a.position() > b.position())
537 if (a.position() < b.position())
543 function squash(node) {
544 node.children().sort(compare);
546 angular.forEach(node.children(), squash);
549 angular.forEach(treeArray, squash);
550 var blob = egCore.env.absorbList(list, 'pgtde');
551 blob.tree = treeArray;
553 service.profile_entries = egCore.env.pgtde.list;
554 return service.set_edit_profile_entries();
559 service.get_field_doc = function() {
561 return egCore.pcrud.search('fdoc', {
562 fm_class: ['au', 'ac', 'aua', 'actsc', 'asv', 'asvq', 'asva']})
565 return egLovefield.setListInOfflineCache('fdoc', to_cache)
569 if (!service.field_doc[doc.fm_class()]) {
570 service.field_doc[doc.fm_class()] = {};
572 service.field_doc[doc.fm_class()][doc.field()] = doc;
579 service.get_user_setting_types = function() {
581 // No need to re-fetch the common setting types.
582 if (Object.keys(service.user_setting_types).length)
585 var org_ids = egCore.org.ancestors(egCore.auth.user().ws_ou(), true);
588 'circ.holds_behind_desk',
589 'circ.collections.exempt',
591 'opac.default_phone',
592 'opac.default_pickup_location',
593 'opac.default_sms_carrier',
594 'opac.default_sms_notify'];
596 return egCore.pcrud.search('cust', {
598 {name : static_types}, // common user settings
599 {name : { // opt-in notification user settings
601 select : {atevdef : ['opt_in_setting']},
603 // we only care about opt-in settings for
604 // event_defs our users encounter
605 where : {'+atevdef' : {owner : org_ids}}
609 }, {}, {atomic : true}).then(function(setting_types) {
611 egCore.env.absorbList(setting_types, 'cust'); // why not...
613 angular.forEach(setting_types, function(stype) {
614 service.user_setting_types[stype.name()] = stype;
615 if (static_types.indexOf(stype.name()) == -1) {
616 service.opt_in_setting_types[stype.name()] = stype;
622 service.get_user_settings = function() {
624 return service.get_user_setting_types()
627 var setting_types = Object.values(service.user_setting_types);
629 if (service.patron_id) {
630 // retrieve applied values for the current user
631 // for the setting types we care about.
634 setting_types.map(function(obj) { return obj.name() });
636 return egCore.net.request(
638 'open-ils.actor.patron.settings.retrieve.authoritative',
642 ).then(function(settings) {
643 service.user_settings = settings;
648 // apply default user setting values
649 angular.forEach(setting_types, function(stype, index) {
650 if (stype.reg_default() != undefined) {
651 var val = stype.reg_default();
652 if (stype.datatype() == 'bool') {
653 // A boolean user setting type whose default
654 // value starts with t/T is considered 'true',
656 val = Boolean((val+'').match(/^t/i));
658 service.user_settings[stype.name()] = val;
665 service.invalidate_field = function(patron, field) {
666 console.log('Invalidating patron field ' + field);
668 return egCore.net.request(
670 'open-ils.actor.invalidate.' + field,
671 egCore.auth.token(), patron.id, null, patron.home_ou.id()
673 ).then(function(res) {
674 // clear the invalid value from the form
677 // update last_xact_id so future save operations
678 // on this patron will be allowed
679 patron.last_xact_id = res.payload.last_xact_id[patron.id];
683 service.send_test_message = function(user_id, hook) {
685 return egCore.net.request(
687 'open-ils.actor.event.test_notification',
688 egCore.auth.token(), {hook: hook, target: user_id}
689 ).then(function(res) {
694 service.dupe_patron_search = function(patron, type, value) {
697 console.log('Dupe search called with "'+ type +'" and value '+ value);
699 if (type.match(/phone/)) type = 'phone'; // day_phone, etc.
704 var fname = patron.first_given_name;
705 var lname = patron.family_name;
706 if (!(fname && lname)) return $q.when({count:0});
708 first_given_name : {value : fname, group : 0},
709 family_name : {value : lname, group : 0}
714 search = {email : {value : value, group : 0}};
718 search = {ident : {value : value, group : 2}};
722 search = {phone : {value : value, group : 2}};
727 angular.forEach(['street1', 'street2', 'city', 'post_code'],
730 search[field] = {value : value[field], group: 1};
736 return egCore.net.request(
738 'open-ils.actor.patron.search.advanced',
739 egCore.auth.token(), search, null, null, 1
740 ).then(function(res) {
741 res = res.filter(function(id) {return id != patron.id});
749 service.init_patron = function(current) {
752 return $q.when(service.init_new_patron());
754 service.patron = current;
755 return $q.when(service.init_existing_patron(current));
758 service.ingest_address = function(patron, addr) {
759 addr.valid = addr.valid == 't';
760 addr.within_city_limits = addr.within_city_limits == 't';
761 addr._is_mailing = (patron.mailing_address &&
762 addr.id == patron.mailing_address.id);
763 addr._is_billing = (patron.billing_address &&
764 addr.id == patron.billing_address.id);
765 addr.pending = addr.pending === 't';
768 service.ingest_waiver_entry = function(patron, waiver_entry) {
769 waiver_entry.place_holds = waiver_entry.place_holds == 't';
770 waiver_entry.pickup_holds = waiver_entry.pickup_holds == 't';
771 waiver_entry.view_history = waiver_entry.view_history == 't';
772 waiver_entry.checkout_items = waiver_entry.checkout_items == 't';
776 * Existing patron objects reqire some data munging before insertion
779 * 1. Turn everything into a hash
780 * 2. ... Except certain fields (selectors) whose widgets require objects
781 * 3. Bools must be Boolean, not t/f.
783 service.init_existing_patron = function(current) {
785 service.existing_patron = current;
787 var patron = egCore.idl.toHash(current);
788 patron.home_ou = egCore.org.get(patron.home_ou.id);
789 patron.expire_date = new Date(Date.parse(patron.expire_date));
790 patron.dob = service.parse_dob(patron.dob);
791 patron.profile = current.profile(); // pre-hash version
792 patron.net_access_level = current.net_access_level();
793 patron.ident_type = current.ident_type();
794 patron.ident_type2 = current.ident_type2();
795 patron.locale = current.locale();
796 patron.groups = current.groups(); // pre-hash
799 ['juvenile', 'barred', 'active', 'master_account'],
800 function(field) { patron[field] = patron[field] == 't'; }
803 angular.forEach(patron.cards, function(card) {
804 card.active = card.active == 't';
805 if (card.id == patron.card.id) {
807 card._primary = true;
811 angular.forEach(patron.addresses,
812 function(addr) { service.ingest_address(patron, addr) });
814 // Link replaced address to its pending address.
815 angular.forEach(patron.addresses, function(addr) {
817 addr._replaces = patron.addresses.filter(
818 function(a) {return a.id == addr.replaces})[0];
822 angular.forEach(patron.waiver_entries,
823 function(waiver_entry) { service.ingest_waiver_entry(patron, waiver_entry) });
825 service.get_linked_addr_users(patron.addresses);
827 // Remove stat cat entries that link to out-of-scope stat
828 // cats. With this, we avoid unnecessarily updating (or worse,
829 // modifying) stat cat values that are not ours to modify.
830 patron.stat_cat_entries = patron.stat_cat_entries.filter(
833 // service.stat_cats only contains in-scope stat cats.
834 service.stat_cats.filter(function(cat) {
835 return (cat.id() == map.stat_cat.id) })[0]
840 // toss entries for existing stat cat maps into our living
841 // stat cat entry map, which is modified within the template.
842 service.stat_cat_entry_maps = [];
843 angular.forEach(patron.stat_cat_entries, function(map) {
844 service.stat_cat_entry_maps[map.stat_cat.id] = map.stat_cat_entry;
847 // fetch survey responses for this user
848 var org_ids = egCore.org.fullPath(egCore.auth.user().ws_ou(), true);
849 var svr_responses = {};
852 egCore.pcrud.search('asvr',
854 {flesh : 2, flesh_fields : {asvr : ['survey','question','answer']}}
857 // All responses collected and deduplicated.
858 // Create one collection of responses per survey.
859 angular.forEach(svr_responses, function(questions, survey_id) {
860 var collection = {responses : []};
861 angular.forEach(questions, function(response) {
862 collection.survey = response.survey();
863 collection.responses.push(response);
865 patron.surveys.push(collection);
870 // Discard responses for out-of-scope surveys.
871 if (org_ids.indexOf(response.survey().owner()) < 0)
874 // survey_id => question_id => response
875 var svr_id = response.survey().id();
876 var qst_id = response.question().id();
878 if (!svr_responses[svr_id])
879 svr_responses[svr_id] = [];
881 if (!svr_responses[svr_id][qst_id]) {
882 svr_responses[svr_id][qst_id] = response;
884 // We may have multiple responses for the same question.
885 // For this UI we only care about the most recent response.
886 if (response.effective_date() >
887 svr_responses[svr_id][qst_id].effective_date())
888 svr_responses[svr_id][qst_id] = response;
893 service.patron = patron;
897 service.init_new_patron = function() {
899 id : service.virt_id--,
902 address_type : egCore.strings.REG_ADDR_TYPE,
905 within_city_limits : false,
906 country : service.org_settings['ui.patron.default_country'],
910 id : service.virt_id--,
921 home_ou : egCore.org.get(egCore.auth.user().ws_ou()),
922 net_access_level : service.org_settings['ui.patron.default_inet_access_level'],
923 stat_cat_entries : [],
929 if (service.clone_user)
930 service.copy_clone_data(user);
932 if (service.stage_user)
933 service.copy_stage_data(user);
938 // dob is always YYYY-MM-DD
939 // Dates of birth do not contain timezone info, which can lead to
940 // inconcistent timezone handling, potentially representing
941 // different points in time, depending on the implementation.
942 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
943 // See "Differences in assumed time zone"
944 // TODO: move this into egDate ?
945 service.parse_dob = function(dob) {
946 if (!dob) return null;
947 var parts = dob.split('-');
948 return new Date(parts[0], parts[1] - 1, parts[2])
951 service.copy_stage_data = function(user) {
952 var cuser = service.stage_user;
954 // copy the data into our new user object
956 for (var key in egCore.idl.classes.stgu.field_map) {
957 if (egCore.idl.classes.au.field_map[key] &&
958 !egCore.idl.classes.stgu.field_map[key].virtual) {
959 if (cuser.user[key]() !== null)
960 user[key] = cuser.user[key]();
964 if (user.home_ou) user.home_ou = egCore.org.get(user.home_ou);
965 if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
967 user.ident_type = egCore.env.cit.map[user.ident_type];
968 if (user.ident_type2)
969 user.ident_type2 = egCore.env.cit.map[user.ident_type2];
971 user.locale = egCore.env.i18n_l.map[user.locale];
972 user.dob = service.parse_dob(user.dob);
974 // Clear the usrname if it looks like a UUID
975 if (user.usrname.replace(/-/g,'').match(/[0-9a-f]{32}/))
978 // Don't use stub address if we have one from the staged user.
979 if (cuser.mailing_addresses.length || cuser.billing_addresses.length)
982 // is_mailing=false implies is_billing
983 function addr_from_stage(stage_addr) {
984 if (!stage_addr) return;
985 var cls = stage_addr.classname;
988 id : service.virt_id--,
992 address_type : egCore.strings.REG_ADDR_TYPE,
993 _is_mailing : cls == 'stgma',
994 _is_billing : cls == 'stgba'
997 user.mailing_address = addr;
998 user.addresses.push(addr);
1000 for (var key in egCore.idl.classes[cls].field_map) {
1001 if (egCore.idl.classes.aua.field_map[key] &&
1002 !egCore.idl.classes[cls].field_map[key].virtual) {
1003 if (stage_addr[key]() !== null)
1004 addr[key] = stage_addr[key]();
1009 addr_from_stage(cuser.mailing_addresses[0]);
1010 addr_from_stage(cuser.billing_addresses[0]);
1012 if (user.addresses.length == 1) {
1013 // If there is only one address,
1014 // use it as both mailing and billing.
1015 var addr = user.addresses[0];
1016 addr._is_mailing = addr._is_billing = true;
1017 user.mailing_address = user.billing_address = addr;
1020 if (cuser.cards.length) {
1022 id : service.virt_id--,
1023 barcode : cuser.cards[0].barcode(),
1029 user.cards.push(user.card);
1030 if (user.usrname == '')
1031 user.usrname = card.barcode;
1034 angular.forEach(cuser.settings, function(setting) {
1035 service.user_settings[setting.setting()] = Boolean(setting.value());
1039 // copy select values from the cloned user to the new user.
1041 service.copy_clone_data = function(user) {
1042 var clone_user = service.clone_user;
1044 // flesh the home org locally
1045 user.home_ou = egCore.org.get(clone_user.home_ou());
1046 if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
1048 if (!clone_user.billing_address() &&
1049 !clone_user.mailing_address())
1050 return; // no addresses to copy or link
1052 // if the cloned user has any addresses, we don't need
1053 // the stub address created in init_new_patron.
1054 user.addresses = [];
1056 var copy_addresses =
1057 service.org_settings['circ.patron_edit.clone.copy_address'];
1059 var clone_fields = [
1066 angular.forEach(clone_fields, function(field) {
1067 user[field] = clone_user[field]();
1070 if (copy_addresses) {
1071 var bill_addr, mail_addr;
1073 // copy the billing and mailing addresses into new addresses
1074 function clone_addr(addr) {
1075 var new_addr = egCore.idl.toHash(addr);
1076 new_addr.id = service.virt_id--;
1077 new_addr.usr = user.id;
1078 new_addr.isnew = true;
1079 new_addr.valid = true;
1080 new_addr.pending = new_addr.pending === 't';
1081 new_addr.within_city_limits = new_addr.within_city_limits == 't';
1082 user.addresses.push(new_addr);
1086 if (bill_addr = clone_user.billing_address()) {
1087 var addr = clone_addr(bill_addr);
1088 addr._is_billing = true;
1089 user.billing_address = addr;
1092 if (mail_addr = clone_user.mailing_address()) {
1094 if (bill_addr && bill_addr.id() == mail_addr.id()) {
1095 user.mailing_address = user.billing_address;
1096 user.mailing_address._is_mailing = true;
1098 var addr = clone_addr(mail_addr);
1099 addr._is_mailing = true;
1100 user.mailing_address = addr;
1104 // if there is no billing addr, use the mailing addr
1105 user.billing_address = user.mailing_address;
1106 user.billing_address._is_billing = true;
1113 // link the billing and mailing addresses
1115 if (addr = clone_user.billing_address()) {
1116 user.billing_address = egCore.idl.toHash(addr);
1117 user.billing_address._is_billing = true;
1118 user.addresses.push(user.billing_address);
1119 user.billing_address._linked_owner_id = clone_user.id();
1120 user.billing_address._linked_owner = service.format_name(
1121 clone_user.family_name(),
1122 clone_user.first_given_name(),
1123 clone_user.second_given_name()
1127 if (addr = clone_user.mailing_address()) {
1128 if (user.billing_address &&
1129 addr.id() == user.billing_address.id) {
1130 // mailing matches billing
1131 user.mailing_address = user.billing_address;
1132 user.mailing_address._is_mailing = true;
1134 user.mailing_address = egCore.idl.toHash(addr);
1135 user.mailing_address._is_mailing = true;
1136 user.addresses.push(user.mailing_address);
1137 user.mailing_address._linked_owner_id = clone_user.id();
1138 user.mailing_address._linked_owner = service.format_name(
1139 clone_user.family_name(),
1140 clone_user.first_given_name(),
1141 clone_user.second_given_name()
1148 // translate the patron back into IDL form
1149 service.save_user = function(phash) {
1151 var patron = egCore.idl.fromHash('au', phash);
1153 patron.home_ou(patron.home_ou().id());
1154 patron.expire_date(patron.expire_date().toISOString());
1155 patron.profile(patron.profile().id());
1157 patron.dob(patron.dob().toISOString().replace(/T.*/,''));
1158 if (patron.ident_type())
1159 patron.ident_type(patron.ident_type().id());
1160 if (patron.locale())
1161 patron.locale(patron.locale().code());
1162 if (patron.net_access_level())
1163 patron.net_access_level(patron.net_access_level().id());
1166 ['juvenile', 'barred', 'active', 'master_account'],
1167 function(field) { patron[field](phash[field] ? 't' : 'f'); }
1170 var card_hashes = patron.cards();
1172 angular.forEach(card_hashes, function(chash) {
1173 var card = egCore.idl.fromHash('ac', chash)
1174 card.usr(patron.id());
1175 card.active(chash.active ? 't' : 'f');
1176 patron.cards().push(card);
1177 if (chash._primary) {
1182 var addr_hashes = patron.addresses();
1183 patron.addresses([]);
1184 angular.forEach(addr_hashes, function(addr_hash) {
1185 if (!addr_hash.isnew && !addr_hash.isdeleted)
1186 addr_hash.ischanged = true;
1187 var addr = egCore.idl.fromHash('aua', addr_hash);
1188 patron.addresses().push(addr);
1189 addr.valid(addr.valid() ? 't' : 'f');
1190 addr.within_city_limits(addr.within_city_limits() ? 't' : 'f');
1191 addr.pending(addr.pending() ? 't' : 'f');
1192 if (addr_hash._is_mailing) patron.mailing_address(addr);
1193 if (addr_hash._is_billing) patron.billing_address(addr);
1196 patron.survey_responses([]);
1197 angular.forEach(service.survey_responses, function(answer) {
1198 var question = service.survey_questions[answer.question()];
1199 var resp = new egCore.idl.asvr();
1201 resp.survey(question.survey());
1202 resp.question(question.id());
1203 resp.answer(answer.id());
1204 resp.usr(patron.id());
1205 resp.answer_date('now');
1206 patron.survey_responses().push(resp);
1209 // re-object-ify the patron stat cat entry maps
1211 angular.forEach(patron.stat_cat_entries(), function(entry) {
1212 var e = egCore.idl.fromHash('actscecm', entry);
1213 e.stat_cat(e.stat_cat().id);
1216 patron.stat_cat_entries(maps);
1218 // service.stat_cat_entry_maps maps stats to values
1219 // patron.stat_cat_entries is an array of stat_cat_entry_usr_map's
1221 service.stat_cat_entry_maps, function(value, cat_id) {
1223 // see if we already have a mapping for this entry
1224 var existing = patron.stat_cat_entries().filter(
1225 function(e) { return e.stat_cat() == cat_id })[0];
1227 if (existing) { // we have a mapping
1228 // if the existing mapping matches the new one,
1229 // there' nothing left to do
1230 if (existing.stat_cat_entry() == value) return;
1232 // mappings differ. delete the old one and create
1234 existing.isdeleted(true);
1237 var newmap = new egCore.idl.actscecm();
1238 newmap.target_usr(patron.id());
1240 newmap.stat_cat(cat_id);
1241 newmap.stat_cat_entry(value);
1242 patron.stat_cat_entries().push(newmap);
1245 var waiver_hashes = patron.waiver_entries();
1246 patron.waiver_entries([]);
1247 angular.forEach(waiver_hashes, function(waiver_hash) {
1248 if (!waiver_hash.isnew && !waiver_hash.isdeleted)
1249 waiver_hash.ischanged = true;
1250 var waiver_entry = egCore.idl.fromHash('aupw', waiver_hash);
1251 patron.waiver_entries().push(waiver_entry);
1254 if (!patron.isnew()) patron.ischanged(true);
1256 // Make sure these are empty, we don't update them this way
1258 patron.usr_activity([]);
1259 patron.standing_penalties([]);
1261 return egCore.net.request(
1263 'open-ils.actor.patron.update',
1264 egCore.auth.token(), patron);
1267 service.remove_staged_user = function() {
1268 if (!service.stage_user) return $q.when();
1269 return egCore.net.request(
1271 'open-ils.actor.user.stage.delete',
1272 egCore.auth.token(),
1273 service.stage_user.user.row_id()
1277 service.save_user_settings = function(new_user, user_settings) {
1280 if (service.patron_id) {
1281 // Update all user editor setting values for existing
1282 // users regardless of whether a value changed.
1283 settings = user_settings;
1286 // Create settings for all non-null setting values for new patrons.
1287 angular.forEach(user_settings, function(val, key) {
1288 if (val !== null) settings[key] = val;
1292 if (Object.keys(settings).length == 0) return $q.when();
1294 return egCore.net.request(
1296 'open-ils.actor.patron.settings.update',
1297 egCore.auth.token(), new_user.id(), settings
1298 ).then(function(resp) {
1303 // Applies field-specific validation regex's from org settings
1304 // to form fields. Be careful not remove any pattern data we
1305 // are not explicitly over-writing in the provided patterns obj.
1306 service.set_field_patterns = function(patterns) {
1307 if (service.org_settings['opac.username_regex']) {
1308 patterns.au.usrname =
1309 new RegExp(service.org_settings['opac.username_regex']);
1312 if (service.org_settings['ui.patron.edit.ac.barcode.regex']) {
1313 patterns.ac.barcode =
1314 new RegExp(service.org_settings['ui.patron.edit.ac.barcode.regex']);
1317 if (service.org_settings['global.password_regex']) {
1318 patterns.au.passwd =
1319 new RegExp(service.org_settings['global.password_regex']);
1322 var phone_reg = service.org_settings['ui.patron.edit.phone.regex'];
1324 // apply generic phone regex first, replace below as needed.
1325 patterns.au.day_phone = new RegExp(phone_reg);
1326 patterns.au.evening_phone = new RegExp(phone_reg);
1327 patterns.au.other_phone = new RegExp(phone_reg);
1330 // the remaining patterns fit a well-known key name pattern
1332 angular.forEach(service.org_settings, function(val, key) {
1334 var parts = key.match(/ui.patron.edit\.(\w+)\.(\w+)\.regex/);
1337 var name = parts[2];
1338 patterns[cls][name] = new RegExp(val);
1345 .controller('PatronRegCtrl',
1346 ['$scope','$routeParams','$q','$uibModal','$window','egCore',
1347 'patronSvc','patronRegSvc','egUnloadPrompt','egAlertDialog',
1348 'egWorkLog', '$timeout', 'ngToast',
1349 function($scope , $routeParams , $q , $uibModal , $window , egCore ,
1350 patronSvc , patronRegSvc , egUnloadPrompt, egAlertDialog ,
1351 egWorkLog, $timeout, ngToast) {
1353 $scope.page_data_loaded = false;
1354 $scope.hold_notify_type = { phone : null, email : null, sms : null };
1355 $scope.hold_notify_observer = {};
1356 $scope.hold_rel_contacts = {};
1357 $scope.clone_id = patronRegSvc.clone_id = $routeParams.clone_id;
1358 $scope.stage_username =
1359 patronRegSvc.stage_username = $routeParams.stage_username;
1361 patronRegSvc.patron_id = $routeParams.edit_id || $routeParams.id;
1363 // for existing patrons, disable barcode input by default
1364 $scope.disable_bc = $scope.focus_usrname = Boolean($scope.patron_id);
1365 $scope.focus_bc = !Boolean($scope.patron_id);
1366 $scope.address_alerts = [];
1367 $scope.dupe_counts = {};
1369 // map of perm name to true/false for perms the logged in user
1370 // has at the currently selected patron home org unit.
1373 $scope.name_tab = 'primary';
1375 if (!$scope.edit_passthru) {
1376 // in edit more, scope.edit_passthru is delivered to us by
1377 // the enclosing controller. In register mode, there is
1378 // no enclosing controller, so we create our own.
1379 $scope.edit_passthru = {};
1382 // 0=all, 1=suggested, 2=all
1383 $scope.edit_passthru.vis_level = 0;
1385 // Apply default values for new patrons during initial registration
1386 // prs is shorthand for patronSvc
1387 function set_new_patron_defaults(prs) {
1388 if (!$scope.patron.passwd) {
1389 // passsword may originate from staged user.
1390 if ($scope.patron.day_phone &&
1391 $scope.org_settings['patron.password.use_phone']) {
1392 $scope.patron.passwd = $scope.patron.day_phone.substr(-4);
1394 $scope.generate_password();
1398 var notify = 'phone:email'; // hard-coded default when opac.hold_notify has no reg_default
1399 var notify_stype = $scope.user_setting_types['opac.hold_notify'];
1400 if (notify_stype && notify_stype.reg_default() !== undefined && notify_stype.reg_default() !== null) {
1401 console.log('using default opac.hold_notify');
1402 notify = notify_stype.reg_default();
1404 $scope.hold_notify_type.phone = Boolean(notify.match(/phone/));
1405 $scope.hold_notify_type.email = Boolean(notify.match(/email/));
1406 $scope.hold_notify_type.sms = Boolean(notify.match(/sms/));
1408 // staged users may be loaded w/ a profile.
1409 $scope.set_expire_date();
1411 if (prs.org_settings['ui.patron.default_ident_type']) {
1412 // $scope.patron needs this field to be an object
1413 var id = prs.org_settings['ui.patron.default_ident_type'];
1414 var ident_type = $scope.ident_types.filter(
1415 function(type) { return type.id() == id })[0];
1416 $scope.patron.ident_type = ident_type;
1418 if (prs.org_settings['ui.patron.default_inet_access_level']) {
1419 // $scope.patron needs this field to be an object
1420 var id = prs.org_settings['ui.patron.default_inet_access_level'];
1421 var level = $scope.net_access_levels.filter(
1422 function(lvl) { return lvl.id() == id })[0];
1423 $scope.patron.net_access_level = level;
1425 if (prs.org_settings['ui.patron.default_country']) {
1426 $scope.patron.addresses[0].country =
1427 prs.org_settings['ui.patron.default_country'];
1431 // A null or undefined pattern leads to exceptions. Before the
1432 // patterns are loaded from the server, default all patterns
1433 // to an innocuous regex. To avoid re-creating numerous
1434 // RegExp objects, cache the stub RegExp after initial creation.
1435 // note: angular docs say ng-pattern accepts a regexp or string,
1436 // but as of writing, it only works with a regexp object.
1437 // (Likely an angular 1.2 vs. 1.4 issue).
1438 var field_patterns = {au : {}, ac : {}, aua : {}};
1439 $scope.field_pattern = function(cls, field) {
1440 if (!field_patterns[cls][field])
1441 field_patterns[cls][field] = new RegExp('.*');
1442 return field_patterns[cls][field];
1445 // Main page load function. Kicks off tab init and data loading.
1448 $scope.initTab ? // initTab comes from patron app
1449 $scope.initTab('edit', $routeParams.id) : $q.when(),
1451 patronRegSvc.init(),
1453 ]).then(function(){ return patronRegSvc.init_patron(patronSvc ? patronSvc.current : patronRegSvc.patron ) })
1454 .then(function(patron) {
1455 // called after initTab and patronRegSvc.init have completed
1456 // in standalone mode, we have no patronSvc
1457 var prs = patronRegSvc;
1458 $scope.patron = patron;
1459 $scope.base_email = patron.email;
1460 $scope.base_default_sms = prs.user_settings['opac.default_sms_notify']
1461 $scope.field_doc = prs.field_doc;
1462 $scope.edit_profiles = prs.edit_profiles;
1463 $scope.edit_profile_entries = prs.edit_profile_entries;
1464 $scope.ident_types = prs.ident_types;
1465 $scope.locales = prs.locales;
1466 $scope.net_access_levels = prs.net_access_levels;
1467 $scope.user_setting_types = prs.user_setting_types;
1468 $scope.opt_in_setting_types = prs.opt_in_setting_types;
1469 $scope.org_settings = prs.org_settings;
1470 $scope.sms_carriers = prs.sms_carriers;
1471 $scope.stat_cats = prs.stat_cats;
1472 $scope.surveys = prs.surveys;
1473 $scope.survey_responses = prs.survey_responses;
1474 $scope.stat_cat_entry_maps = prs.stat_cat_entry_maps;
1475 $scope.stage_user = prs.stage_user;
1476 $scope.stage_user_requestor = prs.stage_user_requestor;
1478 $scope.user_settings = prs.user_settings;
1479 prs.user_settings = {};
1481 // If a default pickup lib is applied to the patron, apply it
1482 // to the UI at page load time. Otherwise, leave the value unset.
1483 if ($scope.user_settings['opac.default_pickup_location']) {
1484 $scope.patron._pickup_lib = egCore.org.get(
1485 $scope.user_settings['opac.default_pickup_location']);
1488 extract_hold_notify();
1490 if ($scope.patron.isnew)
1491 set_new_patron_defaults(prs);
1493 $scope.handle_home_org_changed();
1495 if ($scope.org_settings['ui.patron.edit.default_suggested'])
1496 $scope.edit_passthru.vis_level = 1;
1498 // Stat cats are fetched from open-ils.storage, where 't'==1
1499 $scope.hasRequiredStatCat = prs.stat_cats.filter(
1500 function(cat) {return cat.required() == 1} ).length > 0;
1502 $scope.page_data_loaded = true;
1504 prs.set_field_patterns(field_patterns);
1505 apply_username_regex();
1507 add_date_watchers();
1509 if ($scope.org_settings['ui.patron.edit.guardian_required_for_juv']) {
1514 function add_date_watchers() {
1516 $scope.$watch('patron.dob', function(newVal, oldVal) {
1517 // Even though this runs after page data load, there
1518 // are still times when it fires unnecessarily.
1519 if (newVal === oldVal) return;
1521 console.debug('dob change: ' + newVal + ' : ' + oldVal);
1522 maintain_juvenile_flag();
1525 // No need to watch expire_date
1528 function add_juv_watcher() {
1529 $scope.$watch('patron.juvenile', function(newVal, oldVal) {
1530 if (newVal === oldVal) return;
1532 field_visibility['au.guardian'] = 3; // required
1534 // Value will be reassessed by show_field()
1535 delete field_visibility['au.guardian'];
1540 // add watchers for hold notify method prefs
1541 $scope.$watch('hold_notify_type.phone', function(newVal, oldVal) {
1542 var notifyOpt = $scope.hold_notify_observer['phone'];
1543 if (newVal !== null) {
1544 notifyOpt.newval = newVal;
1548 $scope.$watch('hold_notify_type.sms', function(newVal, oldVal) {
1549 var notifyOpt = $scope.hold_notify_observer['sms'];
1550 if (newVal !== null) {
1551 notifyOpt.newval = newVal;
1555 $scope.$watch('hold_notify_type.email', function(newVal, oldVal) {
1556 var notifyOpt = $scope.hold_notify_observer['email'];
1557 if (newVal !== null) {
1558 notifyOpt.newval = newVal;
1562 // update the currently displayed field documentation
1563 $scope.set_selected_field_doc = function(cls, field) {
1564 $scope.selected_field_doc = $scope.field_doc[cls][field];
1567 // returns the tree depth of the selected profile group tree node.
1568 $scope.pgt_depth = function(grp) {
1570 while (grp = egCore.env.pgt.map[grp.parent()]) d++;
1574 // returns the tree depth of the selected profile group tree node.
1575 $scope.pgtde_depth = function(entry) {
1577 while (entry = egCore.env.pgtde.map[entry.parent()]) d++;
1581 // IDL fields used for labels in the UI.
1582 $scope.idl_fields = {
1583 au : egCore.idl.classes.au.field_map,
1584 ac : egCore.idl.classes.ac.field_map,
1585 aua : egCore.idl.classes.aua.field_map
1588 // field visibility cache. Some fields are universally required.
1589 // 3 == value universally required
1590 // 2 == field is visible by default
1591 // 1 == field is suggested by default
1592 var field_visibility = {};
1593 var default_field_visibility = {
1597 'au.first_given_name' : 3,
1598 'au.family_name' : 3,
1599 'au.pref_first_given_name' : 2,
1600 'au.pref_family_name' : 2,
1601 'au.ident_type' : 3,
1602 'au.ident_type2' : 2,
1607 'au.expire_date' : 3,
1608 'au.net_access_level' : 3,
1609 'aua.address_type' : 3,
1610 'aua.post_code' : 3,
1618 'aua.within_city_limits' : 2,
1621 'au.name_keywords': 1
1624 // Returns true if the selected field should be visible
1625 // given the current required/suggested/all setting.
1626 // The visibility flag applied to each field as a result of calling
1627 // this function also sets (via the same flag) the requiredness state.
1628 $scope.show_field = function(field_key) {
1629 // org settings have not been received yet.
1630 if (!$scope.org_settings) return false;
1632 if (field_visibility[field_key] == undefined) {
1633 // compile and cache the visibility for the selected field
1635 // The preferred name fields use the primary name field settings
1636 var org_key = field_key;
1637 var alt_name = false;
1638 if (field_key.match(/^au.alt_/)) {
1640 org_key = field_key.slice(7);
1643 var req_set = 'ui.patron.edit.' + org_key + '.require';
1644 var sho_set = 'ui.patron.edit.' + org_key + '.show';
1645 var sug_set = 'ui.patron.edit.' + org_key + '.suggest';
1647 if ($scope.org_settings[req_set]) {
1649 // Avoid requiring alt name fields when primary
1650 // name fields are required.
1651 field_visibility[field_key] = 2;
1653 field_visibility[field_key] = 3;
1656 } else if ($scope.org_settings[sho_set]) {
1657 field_visibility[field_key] = 2;
1659 } else if ($scope.org_settings[sug_set]) {
1660 field_visibility[field_key] = 1;
1664 if (field_visibility[field_key] == undefined) {
1665 // No org settings were applied above. Use the default
1666 // settings if present or assume the field has no
1667 // visibility flags applied.
1668 field_visibility[field_key] =
1669 default_field_visibility[field_key] || 0;
1672 return field_visibility[field_key] >= $scope.edit_passthru.vis_level;
1675 // See $scope.show_field().
1676 // A field with visbility level 3 means it's required.
1677 $scope.field_required = function(cls, field) {
1679 // Value in the password field is not required
1680 // for existing patrons.
1681 if (field == 'passwd' && $scope.patron && !$scope.patron.isnew)
1684 return (field_visibility[cls + '.' + field] == 3);
1687 // generates a random 4-digit password
1688 $scope.generate_password = function() {
1689 $scope.patron.passwd = Math.floor(Math.random()*9000) + 1000;
1692 $scope.send_password_reset_link = function() {
1693 if (!$scope.patron.email || $scope.patron.email == '') {
1694 egAlertDialog.open(egCore.strings.REG_PASSWORD_RESET_REQUEST_NO_EMAIL);
1696 } else if (patronRegSvc.check_email_different($scope.patron.email)) {
1697 egAlertDialog.open(egCore.strings.REG_PASSWORD_RESET_REQUEST_DIFFERENT_EMAIL);
1700 // we have an email address, fire the reset request
1703 'open-ils.actor.patron.password_reset.request',
1704 'barcode', $scope.patron.card.barcode, $scope.patron.email
1705 ).then(function(resp) {
1706 if (resp == '1') { // request okay
1707 ngToast.success(egCore.strings.REG_PASSWORD_RESET_REQUEST_SUCCESSFUL);
1709 var evt = egCore.evt.parse(resp);
1710 egAlertDialog.open(evt.desc);
1715 $scope.set_expire_date = function() {
1716 if (!$scope.patron.profile) return;
1717 var seconds = egCore.date.intervalToSeconds(
1718 $scope.patron.profile.perm_interval());
1719 var now_epoch = new Date().getTime();
1720 $scope.patron.expire_date = new Date(
1721 now_epoch + (seconds * 1000 /* milliseconds */))
1722 $scope.field_modified();
1725 // grp is the pgt object
1726 $scope.set_profile = function(grp) {
1727 // If we can't save because of group perms or create/update perms
1728 if ($scope.edit_passthru.hide_save_actions()) return;
1729 $scope.patron.profile = grp;
1730 $scope.set_expire_date();
1731 $scope.field_modified();
1734 $scope.invalid_profile = function() {
1737 $scope.patron.profile &&
1738 $scope.patron.profile.usergroup() == 't'
1742 $scope.new_address = function() {
1743 var addr = egCore.idl.toHash(new egCore.idl.aua());
1744 patronRegSvc.ingest_address($scope.patron, addr);
1745 addr.id = patronRegSvc.virt_id--;
1748 addr.within_city_limits = true;
1749 addr.country = $scope.org_settings['ui.patron.default_country'];
1750 $scope.patron.addresses.push(addr);
1753 // keep deleted addresses out of the patron object so
1754 // they won't appear in the UI. They'll be re-inserted
1755 // when the patron is updated.
1756 deleted_addresses = [];
1757 $scope.delete_address = function(id) {
1759 if ($scope.patron.isnew &&
1760 $scope.patron.addresses.length == 1 &&
1761 $scope.org_settings['ui.patron.registration.require_address']) {
1762 egAlertDialog.open(egCore.strings.REG_ADDR_REQUIRED);
1767 angular.forEach($scope.patron.addresses, function(addr) {
1768 if (addr.id == id) {
1770 addr.isdeleted = true;
1771 deleted_addresses.push(addr);
1774 addresses.push(addr);
1777 $scope.patron.addresses = addresses;
1780 $scope.approve_pending_address = function(addr) {
1784 'open-ils.actor.user.pending_address.approve',
1785 egCore.auth.token(), addr.id
1786 ).then(function(replaced_id) {
1787 var evt = egCore.evt.parse(replaced_id);
1788 if (evt) { alert(evt); return; }
1790 // Remove the pending address and the replaced address
1791 // from the local list of patron addresses.
1793 angular.forEach($scope.patron.addresses, function(a) {
1794 if (a.id != addr.id && a.id != replaced_id) {
1798 $scope.patron.addresses = addresses;
1800 // Fetch a fresh copy of the modified address from the server.
1801 // and add it back to the list.
1802 egCore.pcrud.retrieve('aua', replaced_id, {}, {authoritative: true})
1803 .then(null, null, function(new_addr) {
1804 new_addr = egCore.idl.toHash(new_addr);
1805 patronRegSvc.ingest_address($scope.patron, new_addr);
1806 $scope.patron.addresses.push(new_addr);
1811 $scope.post_code_changed = function(addr) {
1813 'open-ils.search', 'open-ils.search.zip', addr.post_code)
1814 .then(function(resp) {
1816 if (resp.city) addr.city = resp.city;
1817 if (resp.state) addr.state = resp.state;
1818 if (resp.county) addr.county = resp.county;
1819 if (resp.alert) alert(resp.alert);
1823 $scope.new_waiver_entry = function() {
1824 var waiver = egCore.idl.toHash(new egCore.idl.aupw());
1825 patronRegSvc.ingest_waiver_entry($scope.patron, waiver);
1826 waiver.id = patronRegSvc.virt_id--;
1827 waiver.isnew = true;
1828 $scope.patron.waiver_entries.push(waiver);
1831 deleted_waiver_entries = [];
1832 $scope.delete_waiver_entry = function(waiver_entry) {
1833 if (waiver_entry.id > 0) {
1834 waiver_entry.isdeleted = true;
1835 deleted_waiver_entries.push(waiver_entry);
1837 var index = $scope.patron.waiver_entries.indexOf(waiver_entry);
1838 $scope.patron.waiver_entries.splice(index, 1);
1841 $scope.replace_card = function() {
1842 $scope.patron.card.active = false;
1843 $scope.patron.card.ischanged = true;
1844 $scope.disable_bc = false;
1846 var new_card = egCore.idl.toHash(new egCore.idl.ac());
1847 new_card.id = patronRegSvc.virt_id--;
1848 new_card.isnew = true;
1849 new_card.active = true;
1850 new_card._primary = 'on';
1851 $scope.patron.card = new_card;
1853 // Remove any previous attempts to replace the card, since they
1854 // may be incomplete or created by accident.
1855 $scope.patron.cards =
1856 $scope.patron.cards.filter(function(c) {return !c.isnew})
1857 $scope.patron.cards.push(new_card);
1860 $scope.day_phone_changed = function(phone) {
1861 if (phone && $scope.patron.isnew &&
1862 $scope.org_settings['patron.password.use_phone']) {
1863 $scope.patron.passwd = phone.substr(-4);
1867 $scope.barcode_changed = function(bc) {
1869 $scope.dupe_barcode = false;
1872 'open-ils.actor.barcode.exists',
1873 egCore.auth.token(), bc
1874 ).then(function(resp) {
1875 if (resp == '1') { // duplicate card
1876 $scope.dupe_barcode = true;
1877 console.log('duplicate barcode detected: ' + bc);
1879 if (!$scope.patron.usrname)
1880 $scope.patron.usrname = bc;
1886 $scope.cards_dialog = function() {
1888 templateUrl: './circ/patron/t_patron_cards_dialog',
1891 ['$scope','$uibModalInstance','cards','perms','patron',
1892 function($scope , $uibModalInstance , cards , perms , patron) {
1893 // scope here is the modal-level scope
1894 $scope.args = {cards : cards, primary_barcode : null};
1895 angular.forEach(cards, function(card) {
1896 if (card.id == patron.card.id) {
1897 $scope.args.primary_barcode = card.id;
1900 $scope.perms = perms;
1901 $scope.ok = function() { $uibModalInstance.close($scope.args) }
1902 $scope.cancel = function () { $uibModalInstance.dismiss() }
1905 cards : function() {
1906 // scope here is the controller-level scope
1907 return $scope.patron.cards;
1909 perms : function() {
1910 return $scope.perms;
1912 patron : function() {
1913 return $scope.patron;
1918 angular.forEach(args.cards, function(card) {
1919 card.ischanged = true; // assume cards need updating, OK?
1920 if (card.id == args.primary_barcode) {
1921 $scope.patron.card = card;
1922 card._primary = true;
1924 card._primary = false;
1931 $scope.set_addr_type = function(addr, type) {
1932 var addrs = $scope.patron.addresses;
1933 if (addr['_is_'+type]) {
1934 angular.forEach(addrs, function(a) {
1935 if (a.id != addr.id) a['_is_'+type] = false;
1938 // unchecking mailing/billing means we have to randomly
1939 // select another address to fill that role. Select the
1940 // first address in the list (that does not match the
1942 for (var i = 0; i < addrs.length; i++) {
1943 if (addrs[i].id != addr.id) {
1944 addrs[i]['_is_' + type] = true;
1952 // Translate hold notify preferences from the form/scope back into a
1953 // single user setting value for opac.hold_notify.
1954 function compress_hold_notify() {
1955 var hold_notify_methods = [];
1956 if ($scope.hold_notify_type.phone) {
1957 hold_notify_methods.push('phone');
1959 if ($scope.hold_notify_type.email) {
1960 hold_notify_methods.push('email');
1962 if ($scope.hold_notify_type.sms) {
1963 hold_notify_methods.push('sms');
1966 $scope.user_settings['opac.hold_notify'] = hold_notify_methods.join(':');
1969 // dialog for selecting additional permission groups
1970 $scope.secondary_groups_dialog = function() {
1972 templateUrl: './circ/patron/t_patron_groups_dialog',
1975 ['$scope','$uibModalInstance','linked_groups','pgt_depth',
1976 function($scope , $uibModalInstance , linked_groups , pgt_depth) {
1978 $scope.pgt_depth = pgt_depth;
1980 linked_groups : linked_groups,
1981 edit_profiles : patronRegSvc.edit_profiles,
1982 new_profile : patronRegSvc.edit_profiles[0]
1985 // add a new group to the linked groups list
1986 $scope.link_group = function($event, grp) {
1987 var found = false; // avoid duplicates
1988 angular.forEach($scope.args.linked_groups,
1989 function(g) {if (g.id() == grp.id()) found = true});
1990 if (!found) $scope.args.linked_groups.push(grp);
1991 $event.preventDefault(); // avoid close
1994 // remove a group from the linked groups list
1995 $scope.unlink_group = function($event, grp) {
1996 $scope.args.linked_groups =
1997 $scope.args.linked_groups.filter(function(g) {
1998 return g.id() != grp.id()
2000 $event.preventDefault(); // avoid close
2003 $scope.ok = function() { $uibModalInstance.close($scope.args) }
2004 $scope.cancel = function () { $uibModalInstance.dismiss() }
2007 linked_groups : function() { return $scope.patron.groups },
2008 pgt_depth : function() { return $scope.pgt_depth }
2013 if ($scope.patron.isnew) {
2014 // groups must be linked for new patrons after the
2015 // patron is created.
2016 $scope.patron.groups = args.linked_groups;
2020 // update links groups for existing users in real time.
2021 var ids = args.linked_groups.map(function(g) {return g.id()});
2022 patronRegSvc.apply_secondary_groups($scope.patron.id, ids)
2023 .then(function(success) {
2025 $scope.patron.groups = args.linked_groups;
2031 function extract_hold_notify() {
2032 var p = $scope.patron;
2034 // get the user's opac.hold_notify setting
2035 var notify = $scope.user_settings['opac.hold_notify'];
2037 // if it's not set, use the default opac.hold_notify value
2038 if (!notify && !(notify === '')) {
2039 var notify_stype = $scope.user_setting_types['opac.hold_notify'];
2040 if (notify_stype && notify_stype.reg_default() !== undefined && notify_stype.reg_default() !== null) {
2041 notify = notify_stype.reg_default();
2043 // no setting and no default: set phone and email to true
2044 notify = 'phone:email';
2048 $scope.hold_notify_type.phone = Boolean(notify.match(/phone/));
2049 $scope.hold_notify_type.email = Boolean(notify.match(/email/));
2050 $scope.hold_notify_type.sms = Boolean(notify.match(/sms/));
2052 // stores original loaded values for comparison later
2053 for (var k in $scope.hold_notify_type){
2054 var val = $scope.hold_notify_type[k];
2056 if ($scope.hold_notify_type.hasOwnProperty(k)){
2057 $scope.hold_notify_observer[k] = {old : val, newval: null};
2061 // actual value from user
2062 $scope.hold_rel_contacts.day_phone = { old: p.day_phone, newval : null };
2063 $scope.hold_rel_contacts.other_phone = { old: p.other_phone, newval : null };
2064 $scope.hold_rel_contacts.evening_phone = { old: p.evening_phone, newval : null };
2065 // from user_settings
2066 $scope.hold_rel_contacts.default_phone = { old: $scope.user_settings['opac.default_phone'], newval : null };
2067 $scope.hold_rel_contacts.default_sms = { old: $scope.user_settings['opac.default_sms_notify'], newval : null };
2068 $scope.hold_rel_contacts.default_sms_carrier_id = { old: $scope.user_settings['opac.default_sms_carrier'], newval : null };
2072 function normalizePhone(number){
2073 // normalize phone # for comparison, only digits
2074 if (number == null || number == undefined) return '';
2076 var regex = /[^\d]/g;
2077 return number.replace(regex, '');
2080 $scope.invalidate_field = function(field) {
2081 patronRegSvc.invalidate_field($scope.patron, field).then(function() {
2082 $scope.handle_field_changed($scope.patron, field);
2086 $scope.send_test_email = function() {
2087 patronRegSvc.send_test_message($scope.patron.id, 'au.email.test').then(function(res) {
2088 if (res && res.template_output() && res.template_output().is_error() == 'f') {
2089 ngToast.success(egCore.strings.TEST_NOTIFY_SUCCESS);
2091 ngToast.warning(egCore.strings.TEST_NOTIFY_FAIL);
2092 if (res) console.log(res);
2097 $scope.send_test_sms = function() {
2098 patronRegSvc.send_test_message($scope.patron.id, 'au.sms_text.test').then(function(res) {
2099 if (res && res.template_output() && res.template_output().is_error() == 'f') {
2100 ngToast.success(egCore.strings.TEST_NOTIFY_SUCCESS);
2102 ngToast.warning(egCore.strings.TEST_NOTIFY_FAIL);
2103 if (res) console.log(res);
2108 address_alert = function(addr) {
2110 street1: addr.street1,
2111 street2: addr.street2,
2114 county: addr.county,
2115 country: addr.country,
2116 post_code: addr.post_code,
2117 mailing_address: addr._is_mailing,
2118 billing_address: addr._is_billing
2123 'open-ils.actor.address_alert.test',
2124 egCore.auth.token(), egCore.auth.user().ws_ou(), args
2125 ).then(function(res) {
2126 $scope.address_alerts = res;
2130 $scope.dupe_value_changed = function(type, value) {
2131 if (!$scope.dupe_search_encoded)
2132 $scope.dupe_search_encoded = {};
2134 $scope.dupe_counts[type] = 0;
2136 patronRegSvc.dupe_patron_search($scope.patron, type, value)
2137 .then(function(res) {
2138 $scope.dupe_counts[type] = res.count;
2140 $scope.dupe_search_encoded[type] =
2141 encodeURIComponent(js2JSON(res.search));
2143 $scope.dupe_search_encoded[type] = '';
2148 $scope.handle_home_org_changed = function() {
2149 org_id = $scope.patron.home_ou.id();
2150 patronRegSvc.has_perms_for_org(org_id).then(function(map) {
2151 angular.forEach(map, function(v, k) { $scope.perms[k] = v });
2155 $scope.clear_pulib = function() {
2156 if (!$scope.user_settings) return; // still rendering
2157 $scope.patron._pickup_lib = null;
2158 $scope.user_settings['opac.default_pickup_location'] = null;
2161 $scope.handle_pulib_changed = function(org) {
2162 if (!$scope.user_settings) return; // still rendering
2163 $scope.user_settings['opac.default_pickup_location'] = org.id();
2166 // This is called with every character typed in a form field,
2167 // since that's the only way to gaurantee something has changed.
2168 // See handle_field_changed for ng-change vs. ng-blur.
2169 $scope.field_modified = function() {
2170 // Call attach with every field change, regardless of whether
2171 // it's been called before. This will allow for re-attach after
2172 // the user clicks through the unload warning. egUnloadPrompt
2173 // will ensure we only attach once.
2174 egUnloadPrompt.attach($scope);
2177 // also monitor when form is changed *by the user*, as using
2178 // an ng-change handler doesn't work with eg-date-input
2179 $scope.$watch('reg_form.$pristine', function(newVal, oldVal) {
2180 if (!newVal) egUnloadPrompt.attach($scope);
2183 // username regex (if present) must be removed any time
2184 // the username matches the barcode to avoid firing the
2185 // invalid field handlers.
2186 function apply_username_regex() {
2187 var regex = $scope.org_settings['opac.username_regex'];
2189 if ($scope.patron.card.barcode) {
2190 // username must match the regex or the barcode
2191 field_patterns.au.usrname =
2193 regex + '|^' + $scope.patron.card.barcode + '$');
2195 // username must match the regex
2196 field_patterns.au.usrname = new RegExp(regex);
2199 // username can be any format.
2200 field_patterns.au.usrname = new RegExp('.*');
2204 // obj could be the patron, an address, etc.
2205 // This is called any time a form field achieves then loses focus.
2206 // It does not necessarily mean the field has changed.
2207 // The alternative is ng-change, but it's called with each character
2208 // typed, which would be overkill for many of the actions called here.
2209 $scope.handle_field_changed = function(obj, field_name) {
2210 var cls = obj.classname; // set by egIdl
2211 var value = obj[field_name];
2213 console.debug('changing field ' + field_name + ' to ' + value);
2215 switch (field_name) {
2217 if (normalizePhone(value) !== normalizePhone($scope.hold_rel_contacts.day_phone.old)){
2218 $scope.hold_rel_contacts.day_phone.newval = value;
2220 if ($scope.patron.day_phone &&
2221 $scope.patron.isnew &&
2222 $scope.org_settings['patron.password.use_phone']) {
2223 $scope.patron.passwd = $scope.patron.day_phone.substr(-4);
2225 $scope.dupe_value_changed(field_name, value);
2227 case 'evening_phone' :
2228 if (normalizePhone(value) !== normalizePhone($scope.hold_rel_contacts.evening_phone.old)){
2229 $scope.hold_rel_contacts.evening_phone.newval = value;
2231 $scope.dupe_value_changed(field_name, value);
2233 case 'other_phone' :
2234 if (normalizePhone(value) !== normalizePhone($scope.hold_rel_contacts.other_phone.old)){
2235 $scope.hold_rel_contacts.other_phone.newval = value;
2237 $scope.dupe_value_changed(field_name, value);
2240 case 'ident_value2':
2241 $scope.dupe_value_changed('ident', value);
2244 case 'first_given_name':
2246 $scope.dupe_value_changed('name', value);
2250 $scope.dupe_value_changed('email', value);
2256 // dupe search on address wants the address object as the value.
2257 $scope.dupe_value_changed('address', obj);
2262 $scope.post_code_changed(obj);
2266 patronRegSvc.check_dupe_username(value)
2267 .then(function(yes) {$scope.dupe_username = Boolean(yes)});
2271 // TODO: finish barcode_changed handler.
2272 $scope.barcode_changed(value);
2273 apply_username_regex();
2275 case 'opac.default_phone':
2276 if (normalizePhone(value) !== normalizePhone($scope.hold_rel_contacts.default_phone.old)){
2277 $scope.hold_rel_contacts.default_phone.newval = value;
2280 case 'opac.default_sms_notify':
2281 if (normalizePhone(value) !== normalizePhone($scope.hold_rel_contacts.default_sms.old)){
2282 $scope.hold_rel_contacts.default_sms.newval = value;
2285 case 'opac.default_sms_carrier':
2286 if (value !== $scope.hold_rel_contacts.default_sms_carrier_id.old){
2287 $scope.hold_rel_contacts.default_sms_carrier_id.newval = value;
2293 // patron.juvenile is set to true if the user was born after
2294 function maintain_juvenile_flag() {
2295 if ( !($scope.patron && $scope.patron.dob) ) return;
2298 $scope.org_settings['global.juvenile_age_threshold']
2301 var base = new Date();
2303 base.setTime(base.getTime() -
2304 Number(egCore.date.intervalToSeconds(juv_interval) + '000'));
2306 $scope.patron.juvenile = ($scope.patron.dob > base);
2309 // returns true (disable) for orgs that cannot have users.
2310 $scope.disable_home_org = function(org_id) {
2311 if (!org_id) return;
2312 var org = egCore.org.get(org_id);
2316 org.ou_type().can_have_users() == 'f'
2320 // returns true (disable) for orgs that cannot have vols (for holds pickup)
2321 $scope.disable_pulib = function(org_id) {
2322 if (!org_id) return;
2323 return !egCore.org.CanHaveVolumes(org_id);
2326 // Returns true if attempting to edit self, but perms don't allow
2327 $scope.edit_passthru.self_edit_disallowed = function() {
2328 if ($scope.patron.id
2329 && $scope.patron.id == egCore.auth.user().id()
2330 && !$scope.perms.EDIT_SELF_IN_CLIENT
2335 // Returns true if attempting to edit a user without appropriate group application perms
2336 $scope.edit_passthru.group_edit_disallowed = function() {
2337 if ( $scope.patron.profile
2340 .filter(function(p) {
2341 return $scope.patron.profile.id() == p.id();
2347 // Returns true if the Save and Save & Clone buttons should be disabled.
2348 $scope.edit_passthru.hide_save_actions = function() {
2349 if ($scope.edit_passthru.self_edit_disallowed()) return true;
2350 if ($scope.edit_passthru.group_edit_disallowed()) return true;
2352 return $scope.patron.isnew ?
2353 !$scope.perms.CREATE_USER :
2354 !$scope.perms.UPDATE_USER;
2357 // Returns true if any input elements are tagged as invalid
2358 // via Angular patterns or required attributes.
2359 function form_has_invalid_fields() {
2360 return $('#patron-reg-container .ng-invalid').length > 0;
2363 function form_is_incomplete() {
2365 $scope.dupe_username ||
2366 $scope.dupe_barcode ||
2367 form_has_invalid_fields()
2372 $scope.edit_passthru.save = function(save_args) {
2373 if (!save_args) save_args = {};
2375 if (form_is_incomplete()) {
2376 // User has not provided valid values for all required fields.
2377 return egAlertDialog.open(egCore.strings.REG_INVALID_FIELDS);
2380 // remove page unload warning prompt
2381 egUnloadPrompt.clear();
2383 // toss the deleted addresses back into the patron's list of
2384 // addresses so it's included in the update
2385 $scope.patron.addresses =
2386 $scope.patron.addresses.concat(deleted_addresses);
2388 // ditto for waiver entries
2389 $scope.patron.waiver_entries =
2390 $scope.patron.waiver_entries.concat(deleted_waiver_entries);
2392 compress_hold_notify();
2396 patronRegSvc.save_user($scope.patron)
2397 .then(function(new_user) {
2398 if (new_user && new_user.classname) {
2399 updated_user = new_user;
2400 return patronRegSvc.save_user_settings(
2401 new_user, $scope.user_settings);
2403 var evt = egCore.evt.parse(new_user);
2405 if (evt && evt.textcode == 'XACT_COLLISION') {
2406 return egAlertDialog.open(
2407 egCore.strings.PATRON_EDIT_COLLISION).result;
2410 // debug only -- should not get here.
2411 alert('Patron update failed. \n\n' + js2JSON(new_user));
2414 }).then(function() {
2416 // only remove the staged user if the update succeeded.
2418 return patronRegSvc.remove_staged_user();
2422 }).then(function() {
2424 // linked groups for new users must be created after the new
2426 if ($scope.patron.isnew &&
2427 $scope.patron.groups && $scope.patron.groups.length) {
2428 var ids = $scope.patron.groups.map(function(g) {return g.id()});
2429 return patronRegSvc.apply_secondary_groups(updated_user.id(), ids)
2433 }).then(findChangedFieldsAffectedHolds)
2434 .then(function(changed_fields_plus_holds) {
2435 var needModal = changed_fields_plus_holds[0] && changed_fields_plus_holds[0].length > 0;
2437 ? $scope.update_holds_notify_modal(changed_fields_plus_holds[0])
2438 : $q.when(); // nothing changed, continue
2439 }).then(function() {
2443 ? egCore.strings.EG_WORK_LOG_REGISTERED_PATRON
2444 : egCore.strings.EG_WORK_LOG_EDITED_PATRON, {
2445 'action' : $scope.patron.isnew ? 'registered_patron' : 'edited_patron',
2446 'patron_id' : updated_user.id()
2451 // reloading the page means potentially losing some information
2452 // (e.g. last patron search), but is the only way to ensure all
2453 // components are properly updated to reflect the modified patron.
2454 if (updated_user && save_args.clone) {
2455 // open a separate tab for registering a new
2456 // patron from our cloned data.
2457 var url = 'https://'
2458 + $window.location.hostname
2459 + egCore.env.basePath
2460 + '/circ/patron/register/clone/'
2461 + updated_user.id();
2462 $window.open(url, '_blank').focus();
2464 } else if ($window.location.href.indexOf('stage') > -1 ){
2465 // we're here after deleting a self-reg staged user.
2466 // Just close tab, since refresh won't find staged user
2467 $timeout(function(){
2468 if (typeof BroadcastChannel != 'undefined') {
2469 var bChannel = new BroadcastChannel("eg.pending_usr.update");
2470 bChannel.postMessage({
2471 usr: egCore.idl.toHash(updated_user)
2478 // reload the current page
2479 $window.location.href = location.href;
2484 var phone_inputs = ["day_phone", "evening_phone","other_phone", "default_phone"];
2485 var sms_inputs = ["default_sms", "default_sms_carrier_id"];
2486 var method_prefs = ["sms_notify", "phone_notify", "email_notify"];
2487 var groupBy = function(xs, key){
2488 return xs.reduce(function(rv, x){
2489 (rv[x[key]] = rv[x[key]] || []).push(x);
2494 function findChangedFieldsAffectedHolds(){
2496 var changed_hold_fields = [];
2498 var default_phone_changed = false;
2499 var default_sms_carrier_changed = false;
2500 var default_sms_changed = false;
2501 for (var c in $scope.hold_rel_contacts){
2502 var newinput = $scope.hold_rel_contacts[c].newval;
2503 if ($scope.hold_rel_contacts.hasOwnProperty(c)
2504 && newinput !== null // null means user has not provided a value in this session
2505 && newinput != $scope.hold_rel_contacts[c].old){
2506 var changed = $scope.hold_rel_contacts[c];
2508 changed.isChecked = false;
2509 changed_hold_fields.push(changed);
2510 if (c === 'default_phone') default_phone_changed = true;
2511 if (c === 'default_sms_carrier_id') default_sms_carrier_changed = true;
2512 if (c === 'default_sms') default_sms_changed = true;
2516 for (var c in $scope.hold_notify_observer){
2517 var newinput = $scope.hold_notify_observer[c].newval;
2518 if ($scope.hold_notify_observer.hasOwnProperty(c)
2519 && newinput !== null // null means user has not provided a value in this session
2520 && newinput != $scope.hold_notify_observer[c].old){
2521 var changed = $scope.hold_notify_observer[c];
2522 changed.name = c + "_notify";
2523 changed.isChecked = false;
2524 changed_hold_fields.push(changed);
2526 // if we're turning on phone notifications, offer to update to the
2527 // current default number
2528 if (c === 'phone' && $scope.user_settings['opac.default_phone'] && newinput && !default_phone_changed) {
2529 changed_hold_fields.push({
2530 name: 'default_phone',
2532 newval: $scope.user_settings['opac.default_phone'],
2536 // and similarly for SMS
2537 if (c === 'sms' && $scope.user_settings['opac.default_sms_carrier'] && newinput && !default_sms_carrier_changed) {
2538 changed_hold_fields.push({
2539 name: 'default_sms_carrier_id',
2541 newval: $scope.user_settings['opac.default_sms_carrier'],
2545 if (c === 'sms' && $scope.user_settings['opac.default_sms_notify'] && newinput && !default_sms_changed) {
2546 changed_hold_fields.push({
2547 name: 'default_sms',
2549 newval: $scope.user_settings['opac.default_sms_notify'],
2557 angular.forEach(changed_hold_fields, function(c){
2558 promises.push(egCore.net.request('open-ils.circ',
2559 'open-ils.circ.holds.retrieve_by_notify_staff',
2560 egCore.auth.token(),
2562 c.name.includes('notify') || c.name.includes('carrier') ? c.old : c.newval,
2564 .then(function(affected_holds){
2565 if(!affected_holds || affected_holds.length < 1){
2566 // no holds affected - remove change from list
2567 var p = changed_hold_fields.indexOf(c);
2568 changed_hold_fields.splice(p, 1);
2570 c.affects = affected_holds;
2572 //angular.forEach(c.affects, function(h){
2575 if (!c.name.includes("notify")){
2576 if (c.name === "default_sms_carrier_id") {
2577 c.groups = groupBy(c.affects,'sms_carrier');
2579 c.groups = groupBy(c.affects, c.name.includes('_phone') ? 'phone_notify':'sms_notify');
2583 return $q.when(changed_hold_fields);
2588 return $q.all(promises);
2591 $scope.update_holds_notify_modal = function(changed_hold_fields){
2592 // open modal after-save, pre-reload modal to deal with updated hold notification stuff
2593 if ($scope.patron.isnew || changed_hold_fields.length < 1){
2597 return $uibModal.open({
2598 templateUrl: './circ/patron/t_hold_notify_update',
2601 ['$scope','$uibModalInstance','changed_fields','patron','carriers','def_carrier_id','default_phone','default_sms',
2602 function($scope , $uibModalInstance , changed_fields , patron, carriers, def_carrier_id , default_phone , default_sms) {
2603 // local modal scope
2604 $scope.ch_fields = changed_fields;
2605 $scope.focusMe = true;
2606 $scope.ok = function(msg) {
2608 // Need to do this so the page will reload automatically
2609 if (msg == 'no-update') return $uibModalInstance.close();
2611 //var selectedChanges = $scope.changed_fields.filter(function(c) {
2612 // return c.isChecked;
2614 var selectedChanges = [];
2615 angular.forEach($scope.ch_fields, function(f){
2616 if (f.name == 'phone_notify' && f.newval && f.isChecked) {
2617 // convert to default_phone change
2618 f.sel_hids = f.affects.map(function(h){ return h.id});
2619 f.newval = default_phone;
2620 f.name = 'default_phone';
2621 selectedChanges.push(f);
2622 } else if (f.name == 'sms_notify' && f.newval && f.isChecked) {
2623 // convert to default_sms change
2624 f.sel_hids = f.affects.map(function(h){ return h.id});
2625 f.newval = default_sms;
2626 f.name = 'default_sms';
2627 selectedChanges.push(f);
2628 } else if (f.name.includes('notify') || f.name.includes('carrier')){
2630 f.sel_hids = f.affects.map(function(h){ return h.id});
2631 selectedChanges.push(f);
2634 // this is the sms or phone, so look in the groups obj
2636 for (var k in f.groups){
2637 if (f.groups.hasOwnProperty(k)){
2638 var sel_holds = f.groups[k].filter(function(h){
2642 var hids = sel_holds.map(function(h){ return h.id});
2643 f.sel_hids.push.apply(f.sel_hids, hids);
2647 if (f.sel_hids.length > 0) selectedChanges.push(f);
2652 // call method to update holds for each change
2653 var chain = $q.when();
2654 angular.forEach(selectedChanges, function(c){
2655 var carrierId = c.name.includes('default_sms') ? Number(def_carrier_id) : null;
2656 chain = chain.then(function() {
2657 return egCore.net.request('open-ils.circ',
2658 'open-ils.circ.holds.batch_update_holds_by_notify_staff', egCore.auth.token(),
2661 c.old, // TODO: for number changes, old val is effectively moot
2664 carrierId).then(function(okList){ console.log(okList) });
2668 // carry out the updates and close modal
2669 chain.finally(function(){ $uibModalInstance.close() });
2672 $scope.cancel = function () { $uibModalInstance.dismiss() }
2674 $scope.isNumberCh = function(c){
2675 return !(c.name.includes('notify') || c.name.includes('carrier'));
2679 $scope.groupChanged = function(ch_f, grpK){
2680 var holdArr = ch_f.groups[grpK];
2681 if (holdArr && holdArr.length > 0){
2682 angular.forEach(holdArr, function(h){
2683 if (h.isChecked) { h.isChecked = !h.isChecked; $scope.chgCt-- }
2684 else { h.isChecked = true; $scope.chgCt++ }
2689 $scope.nonGrpChanged = function(field_ch){
2690 if (field_ch.isChecked) $scope.chgCt++;
2691 else $scope.chgCt--;
2694 // use this function as a keydown handler on form
2695 // elements that should not submit the form on enter.
2696 $scope.preventSubmit = function($event) {
2697 if ($event.keyCode == 13)
2698 $event.preventDefault();
2701 $scope.prettyCarrier = function(carrierId){
2702 var sms_carrierObj = carriers.find(function(c){ return c.id == carrierId});
2703 return sms_carrierObj.name;
2705 $scope.prettyBool = function(v){
2706 return v ? 'YES' : 'NO';
2710 changed_fields : function(){ return changed_hold_fields },
2711 patron : function(){ return $scope.patron },
2712 def_carrier_id : function(){
2713 var d = $scope.hold_rel_contacts.default_sms_carrier_id;
2714 return d.newval ? d.newval : d.old;
2716 default_phone : function() {
2717 return ($scope.hold_rel_contacts.default_phone.newval) ?
2718 $scope.hold_rel_contacts.default_phone.newval :
2719 $scope.hold_rel_contacts.default_phone.old;
2721 default_sms : function() {
2722 return ($scope.hold_rel_contacts.default_sms.newval) ?
2723 $scope.hold_rel_contacts.default_sms.newval :
2724 $scope.hold_rel_contacts.default_sms.old;
2726 carriers : function(){ return $scope.sms_carriers.map(function(c){ return egCore.idl.toHash(c) }) }
2731 $scope.edit_passthru.print = function() {
2732 var print_data = {patron : $scope.patron}
2734 return egCore.print.print({
2735 context : 'default',
2736 template : 'patron_data',