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
24 init_done : false // have we loaded our initialization data?
27 // Launch a series of parallel data retrieval calls.
28 service.init = function(scope) {
30 // These are fetched with every instance of the page.
32 service.get_user_settings(),
33 service.get_clone_user(),
34 service.get_stage_user()
38 if (!service.init_done) {
39 // These are fetched with every instance of the app.
41 service.get_field_doc(),
42 service.get_perm_groups(),
43 service.get_perm_group_entries(),
44 service.get_ident_types(),
45 service.get_org_settings(),
46 service.get_stat_cats(),
47 service.get_surveys(),
48 service.get_net_access_levels()
50 service.init_done = true;
53 return $q.all(common_data.concat(page_data));
56 service.get_clone_user = function() {
57 if (!service.clone_id) return $q.when();
58 // we could load egUser and use its get() function, but loading
59 // user.js into the standalone register UI would mean creating a
60 // new module, since egUser is not loaded into egCoreMod. This
62 return egCore.net.request(
64 'open-ils.actor.user.fleshed.retrieve',
65 egCore.auth.token(), service.clone_id,
66 ['billing_address', 'mailing_address'])
67 .then(function(cuser) {
68 if (e = egCore.evt.parse(cuser)) {
71 service.clone_user = cuser;
76 // When editing a user with addresses linked to other users, fetch
77 // the linked user(s) so we can display their names and edit links.
78 service.get_linked_addr_users = function(addrs) {
79 angular.forEach(addrs, function(addr) {
80 if (addr.usr == service.existing_patron.id()) return;
81 egCore.pcrud.retrieve('au', addr.usr)
83 addr._linked_owner_id = usr.id();
84 addr._linked_owner = service.format_name(
86 usr.first_given_name(),
87 usr.second_given_name()
93 service.apply_secondary_groups = function(user_id, group_ids) {
94 return egCore.net.request(
96 'open-ils.actor.user.set_groups',
97 egCore.auth.token(), user_id, group_ids)
98 .then(function(resp) {
102 // debugging -- should be no events
103 alert('linked groups failure ' + egCore.evt.parse(resp));
108 service.get_stage_user = function() {
109 if (!service.stage_username) return $q.when();
111 // fetch the staged user object
112 return egCore.net.request(
114 'open-ils.actor.user.stage.retrieve.by_username',
116 service.stage_username
117 ).then(function(suser) {
118 if (e = egCore.evt.parse(suser)) {
121 service.stage_user = suser;
125 if (!service.stage_user) return;
126 var requestor = service.stage_user.user.requesting_usr();
128 if (!requestor) return;
130 // fetch the requesting user
131 return egCore.net.request(
133 'open-ils.actor.user.retrieve.parts',
136 ['family_name', 'first_given_name', 'second_given_name']
137 ).then(function(parts) {
138 service.stage_user_requestor =
139 service.format_name(parts[0], parts[1], parts[2]);
144 // See note above about not loading egUser.
146 service.format_name = function(last, first, middle) {
147 return last + ', ' + first + (middle ? ' ' + middle : '');
150 service.check_dupe_username = function(usrname) {
152 // empty usernames can't be dupes
153 if (!usrname) return $q.when(false);
155 // avoid dupe check if username matches the originally loaded usrname
156 if (service.existing_patron) {
157 if (usrname == service.existing_patron.usrname())
158 return $q.when(false);
161 return egCore.net.request(
163 'open-ils.actor.username.exists',
164 egCore.auth.token(), usrname);
167 // compare string with email address of loaded user, return true if different
168 service.check_email_different = function(email) {
169 if (service.existing_patron) {
170 if (email != service.existing_patron.email()) {
176 //service.check_grp_app_perm = function(grp_id) {
178 // determine which user groups our user is not allowed to modify
179 service.set_edit_profiles = function() {
180 var all_app_perms = [];
181 var failed_perms = [];
183 // extract the application permissions
184 angular.forEach(service.profiles, function(grp) {
185 if (grp.application_perm())
186 all_app_perms.push(grp.application_perm());
189 // fill in service.edit_profiles by inspecting failed_perms
190 function traverse_grp_tree(grp, failed) {
192 failed_perms.indexOf(grp.application_perm()) > -1;
194 if (!failed) service.edit_profiles.push(grp);
197 service.profiles.filter( // children of grp
198 function(p) { return p.parent() == grp.id() }),
199 function(child) {traverse_grp_tree(child, failed)}
203 return egCore.perm.hasPermAt(all_app_perms, true).then(
204 function(perm_orgs) {
205 angular.forEach(all_app_perms, function(p) {
206 if (perm_orgs[p].length == 0)
207 failed_perms.push(p);
210 traverse_grp_tree(egCore.env.pgt.tree);
215 service.set_edit_profile_entries = function() {
216 var all_app_perms = [];
217 var failed_perms = [];
219 // extract the application permissions
220 angular.forEach(service.profile_entries, function(entry) {
221 if (entry.grp().application_perm())
222 all_app_perms.push(entry.grp().application_perm());
225 // fill in service.edit_profiles by inspecting failed_perms
226 function traverse_grp_tree(entry, failed) {
228 failed_perms.indexOf(entry.grp().application_perm()) > -1;
230 if (!failed) service.edit_profile_entries.push(entry);
233 service.profile_entries.filter( // children of grp
234 function(p) { return p.parent() == entry.id() }),
235 function(child) {traverse_grp_tree(child, failed)}
239 return egCore.perm.hasPermAt(all_app_perms, true).then(
240 function(perm_orgs) {
241 angular.forEach(all_app_perms, function(p) {
242 if (perm_orgs[p].length == 0)
243 failed_perms.push(p);
246 angular.forEach(egCore.env.pgtde.tree, function(tree) {
247 traverse_grp_tree(tree);
253 // resolves to a hash of perm-name => boolean value indicating
254 // wether the user has the permission at org_id.
255 service.has_perms_for_org = function(org_id) {
258 'EDIT_SELF_IN_CLIENT',
261 'CREATE_USER_GROUP_LINK',
262 'UPDATE_PATRON_COLLECTIONS_EXEMPT',
263 'UPDATE_PATRON_CLAIM_RETURN_COUNT',
264 'UPDATE_PATRON_CLAIM_NEVER_CHECKED_OUT_COUNT',
265 'UPDATE_PATRON_ACTIVE_CARD',
266 'UPDATE_PATRON_PRIMARY_CARD'
269 return egCore.perm.hasPermAt(perms_needed, true)
270 .then(function(perm_map) {
272 angular.forEach(perms_needed, function(perm) {
274 Boolean(perm_map[perm].indexOf(org_id) > -1);
281 service.get_surveys = function() {
282 var org_ids = egCore.org.fullPath(egCore.auth.user().ws_ou(), true);
284 return egCore.pcrud.search('asv', {
286 start_date : {'<=' : 'now'},
287 end_date : {'>=' : 'now'}
296 ).then(function(surveys) {
297 surveys = surveys.sort(function(a,b) {
298 return a.name() < b.name() ? -1 : 1 });
299 service.surveys = surveys;
300 angular.forEach(surveys, function(survey) {
301 angular.forEach(survey.questions(), function(question) {
302 service.survey_questions[question.id()] = question;
303 angular.forEach(question.answers(), function(answer) {
304 service.survey_answers[answer.id()] = answer;
309 egLovefield.setListInOfflineCache('asv', service.surveys)
310 egLovefield.setListInOfflineCache('asvq', service.survey_questions)
311 egLovefield.setListInOfflineCache('asva', service.survey_answers)
316 service.get_stat_cats = function() {
317 return egCore.net.request(
319 'open-ils.circ.stat_cat.actor.retrieve.all',
320 egCore.auth.token(), egCore.auth.user().ws_ou()
321 ).then(function(cats) {
322 cats = cats.sort(function(a, b) {
323 return a.name() < b.name() ? -1 : 1});
324 angular.forEach(cats, function(cat) {
326 cat.entries().sort(function(a,b) {
327 return a.value() < b.value() ? -1 : 1
331 service.stat_cats = cats;
332 return egLovefield.setStatCatsCache(cats);
336 service.get_org_settings = function() {
337 return egCore.org.settings([
338 'global.password_regex',
339 'global.juvenile_age_threshold',
340 'patron.password.use_phone',
341 'ui.patron.default_inet_access_level',
342 'ui.patron.default_ident_type',
343 'ui.patron.default_country',
344 'ui.patron.registration.require_address',
345 'circ.holds.behind_desk_pickup_supported',
346 'circ.patron_edit.clone.copy_address',
347 'circ.privacy_waiver',
348 'ui.patron.edit.au.prefix.require',
349 'ui.patron.edit.au.prefix.show',
350 'ui.patron.edit.au.prefix.suggest',
351 'ui.patron.edit.ac.barcode.regex',
352 'ui.patron.edit.au.second_given_name.show',
353 'ui.patron.edit.au.second_given_name.suggest',
354 'ui.patron.edit.au.suffix.show',
355 'ui.patron.edit.au.suffix.suggest',
356 'ui.patron.edit.au.alias.show',
357 'ui.patron.edit.au.alias.suggest',
358 'ui.patron.edit.au.dob.require',
359 'ui.patron.edit.au.dob.show',
360 'ui.patron.edit.au.dob.suggest',
361 'ui.patron.edit.au.dob.calendar',
362 'ui.patron.edit.au.dob.example',
363 'ui.patron.edit.au.juvenile.show',
364 'ui.patron.edit.au.juvenile.suggest',
365 'ui.patron.edit.au.ident_value.show',
366 'ui.patron.edit.au.ident_value.require',
367 'ui.patron.edit.au.ident_value.suggest',
368 'ui.patron.edit.au.ident_value2.show',
369 'ui.patron.edit.au.ident_value2.suggest',
370 'ui.patron.edit.au.photo_url.require',
371 'ui.patron.edit.au.photo_url.show',
372 'ui.patron.edit.au.photo_url.suggest',
373 'ui.patron.edit.au.email.require',
374 'ui.patron.edit.au.email.show',
375 'ui.patron.edit.au.email.suggest',
376 'ui.patron.edit.au.email.regex',
377 'ui.patron.edit.au.email.example',
378 'ui.patron.edit.au.day_phone.require',
379 'ui.patron.edit.au.day_phone.show',
380 'ui.patron.edit.au.day_phone.suggest',
381 'ui.patron.edit.au.day_phone.regex',
382 'ui.patron.edit.au.day_phone.example',
383 'ui.patron.edit.au.evening_phone.require',
384 'ui.patron.edit.au.evening_phone.show',
385 'ui.patron.edit.au.evening_phone.suggest',
386 'ui.patron.edit.au.evening_phone.regex',
387 'ui.patron.edit.au.evening_phone.example',
388 'ui.patron.edit.au.other_phone.require',
389 'ui.patron.edit.au.other_phone.show',
390 'ui.patron.edit.au.other_phone.suggest',
391 'ui.patron.edit.au.other_phone.regex',
392 'ui.patron.edit.au.other_phone.example',
393 'ui.patron.edit.phone.regex',
394 'ui.patron.edit.phone.example',
395 'ui.patron.edit.au.active.show',
396 'ui.patron.edit.au.active.suggest',
397 'ui.patron.edit.au.barred.show',
398 'ui.patron.edit.au.barred.suggest',
399 'ui.patron.edit.au.master_account.show',
400 'ui.patron.edit.au.master_account.suggest',
401 'ui.patron.edit.au.claims_returned_count.show',
402 'ui.patron.edit.au.claims_returned_count.suggest',
403 'ui.patron.edit.au.claims_never_checked_out_count.show',
404 'ui.patron.edit.au.claims_never_checked_out_count.suggest',
405 'ui.patron.edit.au.alert_message.show',
406 'ui.patron.edit.au.alert_message.suggest',
407 'ui.patron.edit.aua.post_code.regex',
408 'ui.patron.edit.aua.post_code.example',
409 'ui.patron.edit.aua.county.require',
410 'ui.patron.edit.au.guardian.show',
411 'ui.patron.edit.au.guardian.suggest',
412 'ui.patron.edit.guardian_required_for_juv',
414 'ui.patron.edit.default_suggested',
415 'opac.barcode_regex',
416 'opac.username_regex',
418 'ui.patron.edit.aua.state.require',
419 'ui.patron.edit.aua.state.suggest',
420 'ui.patron.edit.aua.state.show',
421 'ui.admin.work_log.max_entries',
422 'ui.admin.patron_log.max_entries'
423 ]).then(function(settings) {
424 service.org_settings = settings;
425 if (egCore && egCore.env && !egCore.env.aous) {
426 egCore.env.aous = settings;
427 console.log('setting egCore.env.aous');
429 return service.process_org_settings(settings);
433 // some org settings require the retrieval of additional data
434 service.process_org_settings = function(settings) {
436 var promises = [egLovefield.setSettingsCache(settings)];
438 if (settings['sms.enable']) {
439 // fetch SMS carriers
441 egCore.pcrud.search('csc',
444 {'class':'csc', 'field':'name'},
445 {'class':'csc', 'field':'region'}
447 ).then(function(carriers) {
448 service.sms_carriers = carriers;
452 // if other promises are added below, this is not necessary.
453 promises.push($q.when());
456 // other post-org-settings processing goes here,
457 // adding to promises as needed.
459 return $q.all(promises);
462 service.get_ident_types = function() {
463 if (egCore.env.cit) {
464 service.ident_types = egCore.env.cit.list;
467 return egCore.pcrud.retrieveAll('cit', {}, {atomic : true})
468 .then(function(types) {
469 egCore.env.absorbList(types, 'cit')
470 service.ident_types = types
475 service.get_net_access_levels = function() {
476 if (egCore.env.cnal) {
477 service.net_access_levels = egCore.env.cnal.list;
480 return egCore.pcrud.retrieveAll('cnal', {}, {atomic : true})
481 .then(function(levels) {
482 egCore.env.absorbList(levels, 'cnal')
483 service.net_access_levels = levels
488 service.get_perm_groups = function() {
489 if (egCore.env.pgt) {
490 service.profiles = egCore.env.pgt.list;
491 return service.set_edit_profiles();
493 return egCore.pcrud.search('pgt', {parent : null},
494 {flesh : -1, flesh_fields : {pgt : ['children']}}
497 egCore.env.absorbTree(tree, 'pgt')
498 service.profiles = egCore.env.pgt.list;
499 return service.set_edit_profiles();
505 service.searchPermGroupEntries = function(org) {
506 return egCore.pcrud.search('pgtde', {org: org, parent: null},
507 {flesh: -1, flesh_fields: {pgtde: ['grp', 'children']}}, {atomic: true}
508 ).then(function(treeArray) {
509 if (!treeArray.length && egCore.org.get(org).parent_ou()) {
510 return service.searchPermGroupEntries(egCore.org.get(org).parent_ou());
516 service.get_perm_group_entries = function() {
517 if (egCore.env.pgtde) {
518 service.profile_entries = egCore.env.pgtde.list;
519 return service.set_edit_profile_entries();
521 return service.searchPermGroupEntries(egCore.auth.user().ws_ou()).then(function(treeArray) {
522 function compare(a,b) {
523 if (a.position() > b.position())
525 if (a.position() < b.position())
531 function squash(node) {
532 node.children().sort(compare);
534 angular.forEach(node.children(), squash);
537 angular.forEach(treeArray, squash);
538 var blob = egCore.env.absorbList(list, 'pgtde');
539 blob.tree = treeArray;
541 service.profile_entries = egCore.env.pgtde.list;
542 return service.set_edit_profile_entries();
547 service.get_field_doc = function() {
549 return egCore.pcrud.search('fdoc', {
550 fm_class: ['au', 'ac', 'aua', 'actsc', 'asv', 'asvq', 'asva']})
553 return egLovefield.setListInOfflineCache('fdoc', to_cache)
557 if (!service.field_doc[doc.fm_class()]) {
558 service.field_doc[doc.fm_class()] = {};
560 service.field_doc[doc.fm_class()][doc.field()] = doc;
567 service.get_user_setting_types = function() {
569 // No need to re-fetch the common setting types.
570 if (Object.keys(service.user_setting_types).length)
573 var org_ids = egCore.org.ancestors(egCore.auth.user().ws_ou(), true);
576 'circ.holds_behind_desk',
577 'circ.collections.exempt',
579 'opac.default_phone',
580 'opac.default_pickup_location',
581 'opac.default_sms_carrier',
582 'opac.default_sms_notify'];
584 return egCore.pcrud.search('cust', {
586 {name : static_types}, // common user settings
587 {name : { // opt-in notification user settings
589 select : {atevdef : ['opt_in_setting']},
591 // we only care about opt-in settings for
592 // event_defs our users encounter
593 where : {'+atevdef' : {owner : org_ids}}
597 }, {}, {atomic : true}).then(function(setting_types) {
599 egCore.env.absorbList(setting_types, 'cust'); // why not...
601 angular.forEach(setting_types, function(stype) {
602 service.user_setting_types[stype.name()] = stype;
603 if (static_types.indexOf(stype.name()) == -1) {
604 service.opt_in_setting_types[stype.name()] = stype;
610 service.get_user_settings = function() {
612 return service.get_user_setting_types()
615 var setting_types = Object.values(service.user_setting_types);
617 if (service.patron_id) {
618 // retrieve applied values for the current user
619 // for the setting types we care about.
622 setting_types.map(function(obj) { return obj.name() });
624 return egCore.net.request(
626 'open-ils.actor.patron.settings.retrieve.authoritative',
630 ).then(function(settings) {
631 service.user_settings = settings;
636 // apply default user setting values
637 angular.forEach(setting_types, function(stype, index) {
638 if (stype.reg_default() != undefined) {
639 var val = stype.reg_default();
640 if (stype.datatype() == 'bool') {
641 // A boolean user setting type whose default
642 // value starts with t/T is considered 'true',
644 val = Boolean((val+'').match(/^t/i));
646 service.user_settings[stype.name()] = val;
653 service.invalidate_field = function(patron, field) {
654 console.log('Invalidating patron field ' + field);
656 return egCore.net.request(
658 'open-ils.actor.invalidate.' + field,
659 egCore.auth.token(), patron.id, null, patron.home_ou.id()
661 ).then(function(res) {
662 // clear the invalid value from the form
665 // update last_xact_id so future save operations
666 // on this patron will be allowed
667 patron.last_xact_id = res.payload.last_xact_id[patron.id];
671 service.send_test_message = function(user_id, hook) {
673 return egCore.net.request(
675 'open-ils.actor.event.test_notification',
676 egCore.auth.token(), {hook: hook, target: user_id}
677 ).then(function(res) {
682 service.dupe_patron_search = function(patron, type, value) {
685 console.log('Dupe search called with "'+ type +'" and value '+ value);
687 if (type.match(/phone/)) type = 'phone'; // day_phone, etc.
692 var fname = patron.first_given_name;
693 var lname = patron.family_name;
694 if (!(fname && lname)) return $q.when({count:0});
696 first_given_name : {value : fname, group : 0},
697 family_name : {value : lname, group : 0}
702 search = {email : {value : value, group : 0}};
706 search = {ident : {value : value, group : 2}};
710 search = {phone : {value : value, group : 2}};
715 angular.forEach(['street1', 'street2', 'city', 'post_code'],
718 search[field] = {value : value[field], group: 1};
724 return egCore.net.request(
726 'open-ils.actor.patron.search.advanced',
727 egCore.auth.token(), search, null, null, 1
728 ).then(function(res) {
729 res = res.filter(function(id) {return id != patron.id});
737 service.init_patron = function(current) {
740 return $q.when(service.init_new_patron());
742 service.patron = current;
743 return $q.when(service.init_existing_patron(current));
746 service.ingest_address = function(patron, addr) {
747 addr.valid = addr.valid == 't';
748 addr.within_city_limits = addr.within_city_limits == 't';
749 addr._is_mailing = (patron.mailing_address &&
750 addr.id == patron.mailing_address.id);
751 addr._is_billing = (patron.billing_address &&
752 addr.id == patron.billing_address.id);
753 addr.pending = addr.pending === 't';
756 service.ingest_waiver_entry = function(patron, waiver_entry) {
757 waiver_entry.place_holds = waiver_entry.place_holds == 't';
758 waiver_entry.pickup_holds = waiver_entry.pickup_holds == 't';
759 waiver_entry.view_history = waiver_entry.view_history == 't';
760 waiver_entry.checkout_items = waiver_entry.checkout_items == 't';
764 * Existing patron objects reqire some data munging before insertion
767 * 1. Turn everything into a hash
768 * 2. ... Except certain fields (selectors) whose widgets require objects
769 * 3. Bools must be Boolean, not t/f.
771 service.init_existing_patron = function(current) {
773 service.existing_patron = current;
775 var patron = egCore.idl.toHash(current);
777 patron.home_ou = egCore.org.get(patron.home_ou.id);
778 patron.expire_date = new Date(Date.parse(patron.expire_date));
779 patron.dob = service.parse_dob(patron.dob);
780 patron.profile = current.profile(); // pre-hash version
781 patron.net_access_level = current.net_access_level();
782 patron.ident_type = current.ident_type();
783 patron.ident_type2 = current.ident_type2();
784 patron.groups = current.groups(); // pre-hash
787 ['juvenile', 'barred', 'active', 'master_account'],
788 function(field) { patron[field] = patron[field] == 't'; }
791 angular.forEach(patron.cards, function(card) {
792 card.active = card.active == 't';
793 if (card.id == patron.card.id) {
795 card._primary = true;
799 angular.forEach(patron.addresses,
800 function(addr) { service.ingest_address(patron, addr) });
802 // Link replaced address to its pending address.
803 angular.forEach(patron.addresses, function(addr) {
805 addr._replaces = patron.addresses.filter(
806 function(a) {return a.id == addr.replaces})[0];
810 angular.forEach(patron.waiver_entries,
811 function(waiver_entry) { service.ingest_waiver_entry(patron, waiver_entry) });
813 service.get_linked_addr_users(patron.addresses);
815 // Remove stat cat entries that link to out-of-scope stat
816 // cats. With this, we avoid unnecessarily updating (or worse,
817 // modifying) stat cat values that are not ours to modify.
818 patron.stat_cat_entries = patron.stat_cat_entries.filter(
821 // service.stat_cats only contains in-scope stat cats.
822 service.stat_cats.filter(function(cat) {
823 return (cat.id() == map.stat_cat.id) })[0]
828 // toss entries for existing stat cat maps into our living
829 // stat cat entry map, which is modified within the template.
830 service.stat_cat_entry_maps = [];
831 angular.forEach(patron.stat_cat_entries, function(map) {
832 service.stat_cat_entry_maps[map.stat_cat.id] = map.stat_cat_entry;
835 service.patron = patron;
839 service.init_new_patron = function() {
841 id : service.virt_id--,
844 address_type : egCore.strings.REG_ADDR_TYPE,
847 within_city_limits : false,
848 country : service.org_settings['ui.patron.default_country'],
852 id : service.virt_id--,
863 home_ou : egCore.org.get(egCore.auth.user().ws_ou()),
864 net_access_level : service.org_settings['ui.patron.default_inet_access_level'],
865 stat_cat_entries : [],
871 if (service.clone_user)
872 service.copy_clone_data(user);
874 if (service.stage_user)
875 service.copy_stage_data(user);
880 // dob is always YYYY-MM-DD
881 // Dates of birth do not contain timezone info, which can lead to
882 // inconcistent timezone handling, potentially representing
883 // different points in time, depending on the implementation.
884 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
885 // See "Differences in assumed time zone"
886 // TODO: move this into egDate ?
887 service.parse_dob = function(dob) {
888 if (!dob) return null;
889 var parts = dob.split('-');
890 return new Date(parts[0], parts[1] - 1, parts[2])
893 service.copy_stage_data = function(user) {
894 var cuser = service.stage_user;
896 // copy the data into our new user object
898 for (var key in egCore.idl.classes.stgu.field_map) {
899 if (egCore.idl.classes.au.field_map[key] &&
900 !egCore.idl.classes.stgu.field_map[key].virtual) {
901 if (cuser.user[key]() !== null)
902 user[key] = cuser.user[key]();
906 if (user.home_ou) user.home_ou = egCore.org.get(user.home_ou);
907 if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
909 user.ident_type = egCore.env.cit.map[user.ident_type];
910 if (user.ident_type2)
911 user.ident_type2 = egCore.env.cit.map[user.ident_type2];
912 user.dob = service.parse_dob(user.dob);
914 // Clear the usrname if it looks like a UUID
915 if (user.usrname.replace(/-/g,'').match(/[0-9a-f]{32}/))
918 // Don't use stub address if we have one from the staged user.
919 if (cuser.mailing_addresses.length || cuser.billing_addresses.length)
922 // is_mailing=false implies is_billing
923 function addr_from_stage(stage_addr) {
924 if (!stage_addr) return;
925 var cls = stage_addr.classname;
928 id : service.virt_id--,
932 address_type : egCore.strings.REG_ADDR_TYPE,
933 _is_mailing : cls == 'stgma',
934 _is_billing : cls == 'stgba'
937 user.mailing_address = addr;
938 user.addresses.push(addr);
940 for (var key in egCore.idl.classes[cls].field_map) {
941 if (egCore.idl.classes.aua.field_map[key] &&
942 !egCore.idl.classes[cls].field_map[key].virtual) {
943 if (stage_addr[key]() !== null)
944 addr[key] = stage_addr[key]();
949 addr_from_stage(cuser.mailing_addresses[0]);
950 addr_from_stage(cuser.billing_addresses[0]);
952 if (user.addresses.length == 1) {
953 // If there is only one address,
954 // use it as both mailing and billing.
955 var addr = user.addresses[0];
956 addr._is_mailing = addr._is_billing = true;
957 user.mailing_address = user.billing_address = addr;
960 if (cuser.cards.length) {
962 id : service.virt_id--,
963 barcode : cuser.cards[0].barcode(),
969 user.cards.push(user.card);
970 if (user.usrname == '')
971 user.usrname = card.barcode;
974 angular.forEach(cuser.settings, function(setting) {
975 service.user_settings[setting.setting()] = Boolean(setting.value());
979 // copy select values from the cloned user to the new user.
981 service.copy_clone_data = function(user) {
982 var clone_user = service.clone_user;
984 // flesh the home org locally
985 user.home_ou = egCore.org.get(clone_user.home_ou());
986 if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
988 if (!clone_user.billing_address() &&
989 !clone_user.mailing_address())
990 return; // no addresses to copy or link
992 // if the cloned user has any addresses, we don't need
993 // the stub address created in init_new_patron.
997 service.org_settings['circ.patron_edit.clone.copy_address'];
1006 angular.forEach(clone_fields, function(field) {
1007 user[field] = clone_user[field]();
1010 if (copy_addresses) {
1011 var bill_addr, mail_addr;
1013 // copy the billing and mailing addresses into new addresses
1014 function clone_addr(addr) {
1015 var new_addr = egCore.idl.toHash(addr);
1016 new_addr.id = service.virt_id--;
1017 new_addr.usr = user.id;
1018 new_addr.isnew = true;
1019 new_addr.valid = true;
1020 user.addresses.push(new_addr);
1024 if (bill_addr = clone_user.billing_address()) {
1025 var addr = clone_addr(bill_addr);
1026 addr._is_billing = true;
1027 user.billing_address = addr;
1030 if (mail_addr = clone_user.mailing_address()) {
1032 if (bill_addr && bill_addr.id() == mail_addr.id()) {
1033 user.mailing_address = user.billing_address;
1034 user.mailing_address._is_mailing = true;
1036 var addr = clone_addr(mail_addr);
1037 addr._is_mailing = true;
1038 user.mailing_address = addr;
1042 // if there is no billing addr, use the mailing addr
1043 user.billing_address = user.mailing_address;
1044 user.billing_address._is_billing = true;
1051 // link the billing and mailing addresses
1053 if (addr = clone_user.billing_address()) {
1054 user.billing_address = egCore.idl.toHash(addr);
1055 user.billing_address._is_billing = true;
1056 user.addresses.push(user.billing_address);
1057 user.billing_address._linked_owner_id = clone_user.id();
1058 user.billing_address._linked_owner = service.format_name(
1059 clone_user.family_name(),
1060 clone_user.first_given_name(),
1061 clone_user.second_given_name()
1065 if (addr = clone_user.mailing_address()) {
1066 if (user.billing_address &&
1067 addr.id() == user.billing_address.id) {
1068 // mailing matches billing
1069 user.mailing_address = user.billing_address;
1070 user.mailing_address._is_mailing = true;
1072 user.mailing_address = egCore.idl.toHash(addr);
1073 user.mailing_address._is_mailing = true;
1074 user.addresses.push(user.mailing_address);
1075 user.mailing_address._linked_owner_id = clone_user.id();
1076 user.mailing_address._linked_owner = service.format_name(
1077 clone_user.family_name(),
1078 clone_user.first_given_name(),
1079 clone_user.second_given_name()
1086 // translate the patron back into IDL form
1087 service.save_user = function(phash) {
1089 var patron = egCore.idl.fromHash('au', phash);
1091 patron.home_ou(patron.home_ou().id());
1092 patron.expire_date(patron.expire_date().toISOString());
1093 patron.profile(patron.profile().id());
1095 patron.dob(patron.dob().toISOString().replace(/T.*/,''));
1096 if (patron.ident_type())
1097 patron.ident_type(patron.ident_type().id());
1098 if (patron.net_access_level())
1099 patron.net_access_level(patron.net_access_level().id());
1102 ['juvenile', 'barred', 'active', 'master_account'],
1103 function(field) { patron[field](phash[field] ? 't' : 'f'); }
1106 var card_hashes = patron.cards();
1108 angular.forEach(card_hashes, function(chash) {
1109 var card = egCore.idl.fromHash('ac', chash)
1110 card.usr(patron.id());
1111 card.active(chash.active ? 't' : 'f');
1112 patron.cards().push(card);
1113 if (chash._primary) {
1118 var addr_hashes = patron.addresses();
1119 patron.addresses([]);
1120 angular.forEach(addr_hashes, function(addr_hash) {
1121 if (!addr_hash.isnew && !addr_hash.isdeleted)
1122 addr_hash.ischanged = true;
1123 var addr = egCore.idl.fromHash('aua', addr_hash);
1124 patron.addresses().push(addr);
1125 addr.valid(addr.valid() ? 't' : 'f');
1126 addr.within_city_limits(addr.within_city_limits() ? 't' : 'f');
1127 addr.pending(addr.pending() ? 't' : 'f');
1128 if (addr_hash._is_mailing) patron.mailing_address(addr);
1129 if (addr_hash._is_billing) patron.billing_address(addr);
1132 patron.survey_responses([]);
1133 angular.forEach(service.survey_responses, function(answer) {
1134 var question = service.survey_questions[answer.question()];
1135 var resp = new egCore.idl.asvr();
1137 resp.survey(question.survey());
1138 resp.question(question.id());
1139 resp.answer(answer.id());
1140 resp.usr(patron.id());
1141 resp.answer_date('now');
1142 patron.survey_responses().push(resp);
1145 // re-object-ify the patron stat cat entry maps
1147 angular.forEach(patron.stat_cat_entries(), function(entry) {
1148 var e = egCore.idl.fromHash('actscecm', entry);
1149 e.stat_cat(e.stat_cat().id);
1152 patron.stat_cat_entries(maps);
1154 // service.stat_cat_entry_maps maps stats to values
1155 // patron.stat_cat_entries is an array of stat_cat_entry_usr_map's
1157 service.stat_cat_entry_maps, function(value, cat_id) {
1159 // see if we already have a mapping for this entry
1160 var existing = patron.stat_cat_entries().filter(
1161 function(e) { return e.stat_cat() == cat_id })[0];
1163 if (existing) { // we have a mapping
1164 // if the existing mapping matches the new one,
1165 // there' nothing left to do
1166 if (existing.stat_cat_entry() == value) return;
1168 // mappings differ. delete the old one and create
1170 existing.isdeleted(true);
1173 var newmap = new egCore.idl.actscecm();
1174 newmap.target_usr(patron.id());
1176 newmap.stat_cat(cat_id);
1177 newmap.stat_cat_entry(value);
1178 patron.stat_cat_entries().push(newmap);
1181 var waiver_hashes = patron.waiver_entries();
1182 patron.waiver_entries([]);
1183 angular.forEach(waiver_hashes, function(waiver_hash) {
1184 if (!waiver_hash.isnew && !waiver_hash.isdeleted)
1185 waiver_hash.ischanged = true;
1186 var waiver_entry = egCore.idl.fromHash('aupw', waiver_hash);
1187 patron.waiver_entries().push(waiver_entry);
1190 if (!patron.isnew()) patron.ischanged(true);
1192 return egCore.net.request(
1194 'open-ils.actor.patron.update',
1195 egCore.auth.token(), patron);
1198 service.remove_staged_user = function() {
1199 if (!service.stage_user) return $q.when();
1200 return egCore.net.request(
1202 'open-ils.actor.user.stage.delete',
1203 egCore.auth.token(),
1204 service.stage_user.user.row_id()
1208 service.save_user_settings = function(new_user, user_settings) {
1211 if (service.patron_id) {
1212 // Update all user editor setting values for existing
1213 // users regardless of whether a value changed.
1214 settings = user_settings;
1217 // Create settings for all non-null setting values for new patrons.
1218 angular.forEach(user_settings, function(val, key) {
1219 if (val !== null) settings[key] = val;
1223 if (Object.keys(settings).length == 0) return $q.when();
1225 return egCore.net.request(
1227 'open-ils.actor.patron.settings.update',
1228 egCore.auth.token(), new_user.id(), settings
1229 ).then(function(resp) {
1234 // Applies field-specific validation regex's from org settings
1235 // to form fields. Be careful not remove any pattern data we
1236 // are not explicitly over-writing in the provided patterns obj.
1237 service.set_field_patterns = function(patterns) {
1238 if (service.org_settings['opac.username_regex']) {
1239 patterns.au.usrname =
1240 new RegExp(service.org_settings['opac.username_regex']);
1243 if (service.org_settings['ui.patron.edit.ac.barcode.regex']) {
1244 patterns.ac.barcode =
1245 new RegExp(service.org_settings['ui.patron.edit.ac.barcode.regex']);
1248 if (service.org_settings['global.password_regex']) {
1249 patterns.au.passwd =
1250 new RegExp(service.org_settings['global.password_regex']);
1253 var phone_reg = service.org_settings['ui.patron.edit.phone.regex'];
1255 // apply generic phone regex first, replace below as needed.
1256 patterns.au.day_phone = new RegExp(phone_reg);
1257 patterns.au.evening_phone = new RegExp(phone_reg);
1258 patterns.au.other_phone = new RegExp(phone_reg);
1261 // the remaining patterns fit a well-known key name pattern
1263 angular.forEach(service.org_settings, function(val, key) {
1265 var parts = key.match(/ui.patron.edit\.(\w+)\.(\w+)\.regex/);
1268 var name = parts[2];
1269 patterns[cls][name] = new RegExp(val);
1276 .controller('PatronRegCtrl',
1277 ['$scope','$routeParams','$q','$uibModal','$window','egCore',
1278 'patronSvc','patronRegSvc','egUnloadPrompt','egAlertDialog',
1279 'egWorkLog', '$timeout', 'ngToast',
1280 function($scope , $routeParams , $q , $uibModal , $window , egCore ,
1281 patronSvc , patronRegSvc , egUnloadPrompt, egAlertDialog ,
1282 egWorkLog, $timeout, ngToast) {
1284 $scope.page_data_loaded = false;
1285 $scope.hold_notify_type = { phone : null, email : null, sms : null };
1286 $scope.hold_notify_observer = {};
1287 $scope.hold_rel_contacts = {};
1288 $scope.clone_id = patronRegSvc.clone_id = $routeParams.clone_id;
1289 $scope.stage_username =
1290 patronRegSvc.stage_username = $routeParams.stage_username;
1292 patronRegSvc.patron_id = $routeParams.edit_id || $routeParams.id;
1294 // for existing patrons, disable barcode input by default
1295 $scope.disable_bc = $scope.focus_usrname = Boolean($scope.patron_id);
1296 $scope.focus_bc = !Boolean($scope.patron_id);
1297 $scope.address_alerts = [];
1298 $scope.dupe_counts = {};
1300 // map of perm name to true/false for perms the logged in user
1301 // has at the currently selected patron home org unit.
1304 $scope.name_tab = 'primary';
1306 if (!$scope.edit_passthru) {
1307 // in edit more, scope.edit_passthru is delivered to us by
1308 // the enclosing controller. In register mode, there is
1309 // no enclosing controller, so we create our own.
1310 $scope.edit_passthru = {};
1313 // 0=all, 1=suggested, 2=all
1314 $scope.edit_passthru.vis_level = 0;
1316 // Apply default values for new patrons during initial registration
1317 // prs is shorthand for patronSvc
1318 function set_new_patron_defaults(prs) {
1319 if (!$scope.patron.passwd) {
1320 // passsword may originate from staged user.
1321 if ($scope.patron.day_phone &&
1322 $scope.org_settings['patron.password.use_phone']) {
1323 $scope.patron.passwd = $scope.patron.day_phone.substr(-4);
1325 $scope.generate_password();
1329 var notify = 'phone:email'; // hard-coded default when opac.hold_notify has no reg_default
1330 var notify_stype = $scope.user_setting_types['opac.hold_notify'];
1331 if (notify_stype && notify_stype.reg_default() !== undefined && notify_stype.reg_default() !== null) {
1332 console.log('using default opac.hold_notify');
1333 notify = notify_stype.reg_default();
1335 $scope.hold_notify_type.phone = Boolean(notify.match(/phone/));
1336 $scope.hold_notify_type.email = Boolean(notify.match(/email/));
1337 $scope.hold_notify_type.sms = Boolean(notify.match(/sms/));
1339 // staged users may be loaded w/ a profile.
1340 $scope.set_expire_date();
1342 if (prs.org_settings['ui.patron.default_ident_type']) {
1343 // $scope.patron needs this field to be an object
1344 var id = prs.org_settings['ui.patron.default_ident_type'];
1345 var ident_type = $scope.ident_types.filter(
1346 function(type) { return type.id() == id })[0];
1347 $scope.patron.ident_type = ident_type;
1349 if (prs.org_settings['ui.patron.default_inet_access_level']) {
1350 // $scope.patron needs this field to be an object
1351 var id = prs.org_settings['ui.patron.default_inet_access_level'];
1352 var level = $scope.net_access_levels.filter(
1353 function(lvl) { return lvl.id() == id })[0];
1354 $scope.patron.net_access_level = level;
1356 if (prs.org_settings['ui.patron.default_country']) {
1357 $scope.patron.addresses[0].country =
1358 prs.org_settings['ui.patron.default_country'];
1362 // A null or undefined pattern leads to exceptions. Before the
1363 // patterns are loaded from the server, default all patterns
1364 // to an innocuous regex. To avoid re-creating numerous
1365 // RegExp objects, cache the stub RegExp after initial creation.
1366 // note: angular docs say ng-pattern accepts a regexp or string,
1367 // but as of writing, it only works with a regexp object.
1368 // (Likely an angular 1.2 vs. 1.4 issue).
1369 var field_patterns = {au : {}, ac : {}, aua : {}};
1370 $scope.field_pattern = function(cls, field) {
1371 if (!field_patterns[cls][field])
1372 field_patterns[cls][field] = new RegExp('.*');
1373 return field_patterns[cls][field];
1376 // Main page load function. Kicks off tab init and data loading.
1379 $scope.initTab ? // initTab comes from patron app
1380 $scope.initTab('edit', $routeParams.id) : $q.when(),
1382 patronRegSvc.init(),
1384 ]).then(function(){ return patronRegSvc.init_patron(patronSvc ? patronSvc.current : patronRegSvc.patron ) })
1385 .then(function(patron) {
1386 // called after initTab and patronRegSvc.init have completed
1387 // in standalone mode, we have no patronSvc
1388 var prs = patronRegSvc;
1389 $scope.patron = patron;
1390 $scope.base_email = patron.email;
1391 $scope.base_default_sms = prs.user_settings['opac.default_sms_notify']
1392 $scope.field_doc = prs.field_doc;
1393 $scope.edit_profiles = prs.edit_profiles;
1394 $scope.edit_profile_entries = prs.edit_profile_entries;
1395 $scope.ident_types = prs.ident_types;
1396 $scope.net_access_levels = prs.net_access_levels;
1397 $scope.user_setting_types = prs.user_setting_types;
1398 $scope.opt_in_setting_types = prs.opt_in_setting_types;
1399 $scope.org_settings = prs.org_settings;
1400 $scope.sms_carriers = prs.sms_carriers;
1401 $scope.stat_cats = prs.stat_cats;
1402 $scope.surveys = prs.surveys;
1403 $scope.survey_responses = prs.survey_responses;
1404 $scope.stat_cat_entry_maps = prs.stat_cat_entry_maps;
1405 $scope.stage_user = prs.stage_user;
1406 $scope.stage_user_requestor = prs.stage_user_requestor;
1408 $scope.user_settings = prs.user_settings;
1409 prs.user_settings = {};
1411 // If a default pickup lib is applied to the patron, apply it
1412 // to the UI at page load time. Otherwise, leave the value unset.
1413 if ($scope.user_settings['opac.default_pickup_location']) {
1414 $scope.patron._pickup_lib = egCore.org.get(
1415 $scope.user_settings['opac.default_pickup_location']);
1418 extract_hold_notify();
1420 if ($scope.patron.isnew)
1421 set_new_patron_defaults(prs);
1423 $scope.handle_home_org_changed();
1425 if ($scope.org_settings['ui.patron.edit.default_suggested'])
1426 $scope.edit_passthru.vis_level = 1;
1428 // Stat cats are fetched from open-ils.storage, where 't'==1
1429 $scope.hasRequiredStatCat = prs.stat_cats.filter(
1430 function(cat) {return cat.required() == 1} ).length > 0;
1432 $scope.page_data_loaded = true;
1434 prs.set_field_patterns(field_patterns);
1435 apply_username_regex();
1437 add_date_watchers();
1439 if ($scope.org_settings['ui.patron.edit.guardian_required_for_juv']) {
1444 function add_date_watchers() {
1446 $scope.$watch('patron.dob', function(newVal, oldVal) {
1447 // Even though this runs after page data load, there
1448 // are still times when it fires unnecessarily.
1449 if (newVal === oldVal) return;
1451 console.debug('dob change: ' + newVal + ' : ' + oldVal);
1452 maintain_juvenile_flag();
1455 // No need to watch expire_date
1458 function add_juv_watcher() {
1459 $scope.$watch('patron.juvenile', function(newVal, oldVal) {
1460 if (newVal === oldVal) return;
1462 field_visibility['au.guardian'] = 3; // required
1464 // Value will be reassessed by show_field()
1465 delete field_visibility['au.guardian'];
1470 // add watchers for hold notify method prefs
1471 $scope.$watch('hold_notify_type.phone', function(newVal, oldVal) {
1472 var notifyOpt = $scope.hold_notify_observer['phone'];
1473 if (newVal !== null) {
1474 notifyOpt.newval = newVal;
1478 $scope.$watch('hold_notify_type.sms', function(newVal, oldVal) {
1479 var notifyOpt = $scope.hold_notify_observer['sms'];
1480 if (newVal !== null) {
1481 notifyOpt.newval = newVal;
1485 $scope.$watch('hold_notify_type.email', function(newVal, oldVal) {
1486 var notifyOpt = $scope.hold_notify_observer['email'];
1487 if (newVal !== null) {
1488 notifyOpt.newval = newVal;
1492 // update the currently displayed field documentation
1493 $scope.set_selected_field_doc = function(cls, field) {
1494 $scope.selected_field_doc = $scope.field_doc[cls][field];
1497 // returns the tree depth of the selected profile group tree node.
1498 $scope.pgt_depth = function(grp) {
1500 while (grp = egCore.env.pgt.map[grp.parent()]) d++;
1504 // returns the tree depth of the selected profile group tree node.
1505 $scope.pgtde_depth = function(entry) {
1507 while (entry = egCore.env.pgtde.map[entry.parent()]) d++;
1511 // IDL fields used for labels in the UI.
1512 $scope.idl_fields = {
1513 au : egCore.idl.classes.au.field_map,
1514 ac : egCore.idl.classes.ac.field_map,
1515 aua : egCore.idl.classes.aua.field_map
1518 // field visibility cache. Some fields are universally required.
1519 // 3 == value universally required
1520 // 2 == field is visible by default
1521 // 1 == field is suggested by default
1522 var field_visibility = {};
1523 var default_field_visibility = {
1527 'au.first_given_name' : 3,
1528 'au.family_name' : 3,
1529 'au.pref_first_given_name' : 2,
1530 'au.pref_family_name' : 2,
1531 'au.ident_type' : 3,
1532 'au.ident_type2' : 2,
1536 'au.expire_date' : 3,
1537 'au.net_access_level' : 3,
1538 'aua.address_type' : 3,
1539 'aua.post_code' : 3,
1547 'aua.within_city_limits' : 2,
1550 'au.name_keywords': 1
1553 // Returns true if the selected field should be visible
1554 // given the current required/suggested/all setting.
1555 // The visibility flag applied to each field as a result of calling
1556 // this function also sets (via the same flag) the requiredness state.
1557 $scope.show_field = function(field_key) {
1558 // org settings have not been received yet.
1559 if (!$scope.org_settings) return false;
1561 if (field_visibility[field_key] == undefined) {
1562 // compile and cache the visibility for the selected field
1564 // The preferred name fields use the primary name field settings
1565 var org_key = field_key;
1566 var alt_name = false;
1567 if (field_key.match(/^au.alt_/)) {
1569 org_key = field_key.slice(7);
1572 var req_set = 'ui.patron.edit.' + org_key + '.require';
1573 var sho_set = 'ui.patron.edit.' + org_key + '.show';
1574 var sug_set = 'ui.patron.edit.' + org_key + '.suggest';
1576 if ($scope.org_settings[req_set]) {
1578 // Avoid requiring alt name fields when primary
1579 // name fields are required.
1580 field_visibility[field_key] = 2;
1582 field_visibility[field_key] = 3;
1585 } else if ($scope.org_settings[sho_set]) {
1586 field_visibility[field_key] = 2;
1588 } else if ($scope.org_settings[sug_set]) {
1589 field_visibility[field_key] = 1;
1593 if (field_visibility[field_key] == undefined) {
1594 // No org settings were applied above. Use the default
1595 // settings if present or assume the field has no
1596 // visibility flags applied.
1597 field_visibility[field_key] =
1598 default_field_visibility[field_key] || 0;
1601 return field_visibility[field_key] >= $scope.edit_passthru.vis_level;
1604 // See $scope.show_field().
1605 // A field with visbility level 3 means it's required.
1606 $scope.field_required = function(cls, field) {
1608 // Value in the password field is not required
1609 // for existing patrons.
1610 if (field == 'passwd' && $scope.patron && !$scope.patron.isnew)
1613 return (field_visibility[cls + '.' + field] == 3);
1616 // generates a random 4-digit password
1617 $scope.generate_password = function() {
1618 $scope.patron.passwd = Math.floor(Math.random()*9000) + 1000;
1621 $scope.send_password_reset_link = function() {
1622 if (!$scope.patron.email || $scope.patron.email == '') {
1623 egAlertDialog.open(egCore.strings.REG_PASSWORD_RESET_REQUEST_NO_EMAIL);
1625 } else if (patronRegSvc.check_email_different($scope.patron.email)) {
1626 egAlertDialog.open(egCore.strings.REG_PASSWORD_RESET_REQUEST_DIFFERENT_EMAIL);
1629 // we have an email address, fire the reset request
1632 'open-ils.actor.patron.password_reset.request',
1633 'barcode', $scope.patron.card.barcode, $scope.patron.email
1634 ).then(function(resp) {
1635 if (resp == '1') { // request okay
1636 ngToast.success(egCore.strings.REG_PASSWORD_RESET_REQUEST_SUCCESSFUL);
1638 var evt = egCore.evt.parse(resp);
1639 egAlertDialog.open(evt.desc);
1644 $scope.set_expire_date = function() {
1645 if (!$scope.patron.profile) return;
1646 var seconds = egCore.date.intervalToSeconds(
1647 $scope.patron.profile.perm_interval());
1648 var now_epoch = new Date().getTime();
1649 $scope.patron.expire_date = new Date(
1650 now_epoch + (seconds * 1000 /* milliseconds */))
1651 $scope.field_modified();
1654 // grp is the pgt object
1655 $scope.set_profile = function(grp) {
1656 // If we can't save because of group perms or create/update perms
1657 if ($scope.edit_passthru.hide_save_actions()) return;
1658 $scope.patron.profile = grp;
1659 $scope.set_expire_date();
1660 $scope.field_modified();
1663 $scope.invalid_profile = function() {
1666 $scope.patron.profile &&
1667 $scope.patron.profile.usergroup() == 't'
1671 $scope.new_address = function() {
1672 var addr = egCore.idl.toHash(new egCore.idl.aua());
1673 patronRegSvc.ingest_address($scope.patron, addr);
1674 addr.id = patronRegSvc.virt_id--;
1677 addr.within_city_limits = true;
1678 addr.country = $scope.org_settings['ui.patron.default_country'];
1679 $scope.patron.addresses.push(addr);
1682 // keep deleted addresses out of the patron object so
1683 // they won't appear in the UI. They'll be re-inserted
1684 // when the patron is updated.
1685 deleted_addresses = [];
1686 $scope.delete_address = function(id) {
1688 if ($scope.patron.isnew &&
1689 $scope.patron.addresses.length == 1 &&
1690 $scope.org_settings['ui.patron.registration.require_address']) {
1691 egAlertDialog.open(egCore.strings.REG_ADDR_REQUIRED);
1696 angular.forEach($scope.patron.addresses, function(addr) {
1697 if (addr.id == id) {
1699 addr.isdeleted = true;
1700 deleted_addresses.push(addr);
1703 addresses.push(addr);
1706 $scope.patron.addresses = addresses;
1709 $scope.approve_pending_address = function(addr) {
1713 'open-ils.actor.user.pending_address.approve',
1714 egCore.auth.token(), addr.id
1715 ).then(function(replaced_id) {
1716 var evt = egCore.evt.parse(replaced_id);
1717 if (evt) { alert(evt); return; }
1719 // Remove the pending address and the replaced address
1720 // from the local list of patron addresses.
1722 angular.forEach($scope.patron.addresses, function(a) {
1723 if (a.id != addr.id && a.id != replaced_id) {
1727 $scope.patron.addresses = addresses;
1729 // Fetch a fresh copy of the modified address from the server.
1730 // and add it back to the list.
1731 egCore.pcrud.retrieve('aua', replaced_id, {}, {authoritative: true})
1732 .then(null, null, function(new_addr) {
1733 new_addr = egCore.idl.toHash(new_addr);
1734 patronRegSvc.ingest_address($scope.patron, new_addr);
1735 $scope.patron.addresses.push(new_addr);
1740 $scope.post_code_changed = function(addr) {
1742 'open-ils.search', 'open-ils.search.zip', addr.post_code)
1743 .then(function(resp) {
1745 if (resp.city) addr.city = resp.city;
1746 if (resp.state) addr.state = resp.state;
1747 if (resp.county) addr.county = resp.county;
1748 if (resp.alert) alert(resp.alert);
1752 $scope.new_waiver_entry = function() {
1753 var waiver = egCore.idl.toHash(new egCore.idl.aupw());
1754 patronRegSvc.ingest_waiver_entry($scope.patron, waiver);
1755 waiver.id = patronRegSvc.virt_id--;
1756 waiver.isnew = true;
1757 $scope.patron.waiver_entries.push(waiver);
1760 deleted_waiver_entries = [];
1761 $scope.delete_waiver_entry = function(waiver_entry) {
1762 if (waiver_entry.id > 0) {
1763 waiver_entry.isdeleted = true;
1764 deleted_waiver_entries.push(waiver_entry);
1766 var index = $scope.patron.waiver_entries.indexOf(waiver_entry);
1767 $scope.patron.waiver_entries.splice(index, 1);
1770 $scope.replace_card = function() {
1771 $scope.patron.card.active = false;
1772 $scope.patron.card.ischanged = true;
1773 $scope.disable_bc = false;
1775 var new_card = egCore.idl.toHash(new egCore.idl.ac());
1776 new_card.id = patronRegSvc.virt_id--;
1777 new_card.isnew = true;
1778 new_card.active = true;
1779 new_card._primary = 'on';
1780 $scope.patron.card = new_card;
1782 // Remove any previous attempts to replace the card, since they
1783 // may be incomplete or created by accident.
1784 $scope.patron.cards =
1785 $scope.patron.cards.filter(function(c) {return !c.isnew})
1786 $scope.patron.cards.push(new_card);
1789 $scope.day_phone_changed = function(phone) {
1790 if (phone && $scope.patron.isnew &&
1791 $scope.org_settings['patron.password.use_phone']) {
1792 $scope.patron.passwd = phone.substr(-4);
1796 $scope.barcode_changed = function(bc) {
1798 $scope.dupe_barcode = false;
1801 'open-ils.actor.barcode.exists',
1802 egCore.auth.token(), bc
1803 ).then(function(resp) {
1804 if (resp == '1') { // duplicate card
1805 $scope.dupe_barcode = true;
1806 console.log('duplicate barcode detected: ' + bc);
1808 if (!$scope.patron.usrname)
1809 $scope.patron.usrname = bc;
1815 $scope.cards_dialog = function() {
1817 templateUrl: './circ/patron/t_patron_cards_dialog',
1820 ['$scope','$uibModalInstance','cards','perms','patron',
1821 function($scope , $uibModalInstance , cards , perms , patron) {
1822 // scope here is the modal-level scope
1823 $scope.args = {cards : cards, primary_barcode : null};
1824 angular.forEach(cards, function(card) {
1825 if (card.id == patron.card.id) {
1826 $scope.args.primary_barcode = card.id;
1829 $scope.perms = perms;
1830 $scope.ok = function() { $uibModalInstance.close($scope.args) }
1831 $scope.cancel = function () { $uibModalInstance.dismiss() }
1834 cards : function() {
1835 // scope here is the controller-level scope
1836 return $scope.patron.cards;
1838 perms : function() {
1839 return $scope.perms;
1841 patron : function() {
1842 return $scope.patron;
1847 angular.forEach(args.cards, function(card) {
1848 card.ischanged = true; // assume cards need updating, OK?
1849 if (card.id == args.primary_barcode) {
1850 $scope.patron.card = card;
1851 card._primary = true;
1853 card._primary = false;
1860 $scope.set_addr_type = function(addr, type) {
1861 var addrs = $scope.patron.addresses;
1862 if (addr['_is_'+type]) {
1863 angular.forEach(addrs, function(a) {
1864 if (a.id != addr.id) a['_is_'+type] = false;
1867 // unchecking mailing/billing means we have to randomly
1868 // select another address to fill that role. Select the
1869 // first address in the list (that does not match the
1871 for (var i = 0; i < addrs.length; i++) {
1872 if (addrs[i].id != addr.id) {
1873 addrs[i]['_is_' + type] = true;
1881 // Translate hold notify preferences from the form/scope back into a
1882 // single user setting value for opac.hold_notify.
1883 function compress_hold_notify() {
1884 var hold_notify_methods = [];
1885 if ($scope.hold_notify_type.phone) {
1886 hold_notify_methods.push('phone');
1888 if ($scope.hold_notify_type.email) {
1889 hold_notify_methods.push('email');
1891 if ($scope.hold_notify_type.sms) {
1892 hold_notify_methods.push('sms');
1895 $scope.user_settings['opac.hold_notify'] = hold_notify_methods.join(':');
1898 // dialog for selecting additional permission groups
1899 $scope.secondary_groups_dialog = function() {
1901 templateUrl: './circ/patron/t_patron_groups_dialog',
1904 ['$scope','$uibModalInstance','linked_groups','pgt_depth',
1905 function($scope , $uibModalInstance , linked_groups , pgt_depth) {
1907 $scope.pgt_depth = pgt_depth;
1909 linked_groups : linked_groups,
1910 edit_profiles : patronRegSvc.edit_profiles,
1911 new_profile : patronRegSvc.edit_profiles[0]
1914 // add a new group to the linked groups list
1915 $scope.link_group = function($event, grp) {
1916 var found = false; // avoid duplicates
1917 angular.forEach($scope.args.linked_groups,
1918 function(g) {if (g.id() == grp.id()) found = true});
1919 if (!found) $scope.args.linked_groups.push(grp);
1920 $event.preventDefault(); // avoid close
1923 // remove a group from the linked groups list
1924 $scope.unlink_group = function($event, grp) {
1925 $scope.args.linked_groups =
1926 $scope.args.linked_groups.filter(function(g) {
1927 return g.id() != grp.id()
1929 $event.preventDefault(); // avoid close
1932 $scope.ok = function() { $uibModalInstance.close($scope.args) }
1933 $scope.cancel = function () { $uibModalInstance.dismiss() }
1936 linked_groups : function() { return $scope.patron.groups },
1937 pgt_depth : function() { return $scope.pgt_depth }
1942 if ($scope.patron.isnew) {
1943 // groups must be linked for new patrons after the
1944 // patron is created.
1945 $scope.patron.groups = args.linked_groups;
1949 // update links groups for existing users in real time.
1950 var ids = args.linked_groups.map(function(g) {return g.id()});
1951 patronRegSvc.apply_secondary_groups($scope.patron.id, ids)
1952 .then(function(success) {
1954 $scope.patron.groups = args.linked_groups;
1960 function extract_hold_notify() {
1961 var p = $scope.patron;
1963 // get the user's opac.hold_notify setting
1964 var notify = $scope.user_settings['opac.hold_notify'];
1966 // if it's not set, use the default opac.hold_notify value
1967 if (!notify && !(notify === '')) {
1968 var notify_stype = $scope.user_setting_types['opac.hold_notify'];
1969 if (notify_stype && notify_stype.reg_default() !== undefined && notify_stype.reg_default() !== null) {
1970 notify = notify_stype.reg_default();
1972 // no setting and no default: set phone and email to true
1973 notify = 'phone:email';
1977 $scope.hold_notify_type.phone = Boolean(notify.match(/phone/));
1978 $scope.hold_notify_type.email = Boolean(notify.match(/email/));
1979 $scope.hold_notify_type.sms = Boolean(notify.match(/sms/));
1981 // stores original loaded values for comparison later
1982 for (var k in $scope.hold_notify_type){
1983 var val = $scope.hold_notify_type[k];
1985 if ($scope.hold_notify_type.hasOwnProperty(k)){
1986 $scope.hold_notify_observer[k] = {old : val, newval: null};
1990 // actual value from user
1991 $scope.hold_rel_contacts.day_phone = { old: p.day_phone, newval : null };
1992 $scope.hold_rel_contacts.other_phone = { old: p.other_phone, newval : null };
1993 $scope.hold_rel_contacts.evening_phone = { old: p.evening_phone, newval : null };
1994 // from user_settings
1995 $scope.hold_rel_contacts.default_phone = { old: $scope.user_settings['opac.default_phone'], newval : null };
1996 $scope.hold_rel_contacts.default_sms = { old: $scope.user_settings['opac.default_sms_notify'], newval : null };
1997 $scope.hold_rel_contacts.default_sms_carrier_id = { old: $scope.user_settings['opac.default_sms_carrier'], newval : null };
2001 function normalizePhone(number){
2002 // normalize phone # for comparison, only digits
2003 if (number == null || number == undefined) return '';
2005 var regex = /[^\d]/g;
2006 return number.replace(regex, '');
2009 $scope.invalidate_field = function(field) {
2010 patronRegSvc.invalidate_field($scope.patron, field).then(function() {
2011 $scope.handle_field_changed($scope.patron, field);
2015 $scope.send_test_email = function() {
2016 patronRegSvc.send_test_message($scope.patron.id, 'au.email.test').then(function(res) {
2017 if (res && res.template_output() && res.template_output().is_error() == 'f') {
2018 ngToast.success(egCore.strings.TEST_NOTIFY_SUCCESS);
2020 ngToast.warning(egCore.strings.TEST_NOTIFY_FAIL);
2021 if (res) console.log(res);
2026 $scope.send_test_sms = function() {
2027 patronRegSvc.send_test_message($scope.patron.id, 'au.sms_text.test').then(function(res) {
2028 if (res && res.template_output() && res.template_output().is_error() == 'f') {
2029 ngToast.success(egCore.strings.TEST_NOTIFY_SUCCESS);
2031 ngToast.warning(egCore.strings.TEST_NOTIFY_FAIL);
2032 if (res) console.log(res);
2037 address_alert = function(addr) {
2039 street1: addr.street1,
2040 street2: addr.street2,
2043 county: addr.county,
2044 country: addr.country,
2045 post_code: addr.post_code,
2046 mailing_address: addr._is_mailing,
2047 billing_address: addr._is_billing
2052 'open-ils.actor.address_alert.test',
2053 egCore.auth.token(), egCore.auth.user().ws_ou(), args
2054 ).then(function(res) {
2055 $scope.address_alerts = res;
2059 $scope.dupe_value_changed = function(type, value) {
2060 if (!$scope.dupe_search_encoded)
2061 $scope.dupe_search_encoded = {};
2063 $scope.dupe_counts[type] = 0;
2065 patronRegSvc.dupe_patron_search($scope.patron, type, value)
2066 .then(function(res) {
2067 $scope.dupe_counts[type] = res.count;
2069 $scope.dupe_search_encoded[type] =
2070 encodeURIComponent(js2JSON(res.search));
2072 $scope.dupe_search_encoded[type] = '';
2077 $scope.handle_home_org_changed = function() {
2078 org_id = $scope.patron.home_ou.id();
2079 patronRegSvc.has_perms_for_org(org_id).then(function(map) {
2080 angular.forEach(map, function(v, k) { $scope.perms[k] = v });
2084 $scope.handle_pulib_changed = function(org) {
2085 if (!$scope.user_settings) return; // still rendering
2086 $scope.user_settings['opac.default_pickup_location'] = org.id();
2089 // This is called with every character typed in a form field,
2090 // since that's the only way to gaurantee something has changed.
2091 // See handle_field_changed for ng-change vs. ng-blur.
2092 $scope.field_modified = function() {
2093 // Call attach with every field change, regardless of whether
2094 // it's been called before. This will allow for re-attach after
2095 // the user clicks through the unload warning. egUnloadPrompt
2096 // will ensure we only attach once.
2097 egUnloadPrompt.attach($scope);
2100 // also monitor when form is changed *by the user*, as using
2101 // an ng-change handler doesn't work with eg-date-input
2102 $scope.$watch('reg_form.$pristine', function(newVal, oldVal) {
2103 if (!newVal) egUnloadPrompt.attach($scope);
2106 // username regex (if present) must be removed any time
2107 // the username matches the barcode to avoid firing the
2108 // invalid field handlers.
2109 function apply_username_regex() {
2110 var regex = $scope.org_settings['opac.username_regex'];
2112 if ($scope.patron.card.barcode) {
2113 // username must match the regex or the barcode
2114 field_patterns.au.usrname =
2116 regex + '|^' + $scope.patron.card.barcode + '$');
2118 // username must match the regex
2119 field_patterns.au.usrname = new RegExp(regex);
2122 // username can be any format.
2123 field_patterns.au.usrname = new RegExp('.*');
2127 // obj could be the patron, an address, etc.
2128 // This is called any time a form field achieves then loses focus.
2129 // It does not necessarily mean the field has changed.
2130 // The alternative is ng-change, but it's called with each character
2131 // typed, which would be overkill for many of the actions called here.
2132 $scope.handle_field_changed = function(obj, field_name) {
2133 var cls = obj.classname; // set by egIdl
2134 var value = obj[field_name];
2136 console.debug('changing field ' + field_name + ' to ' + value);
2138 switch (field_name) {
2140 if (normalizePhone(value) !== normalizePhone($scope.hold_rel_contacts.day_phone.old)){
2141 $scope.hold_rel_contacts.day_phone.newval = value;
2143 if ($scope.patron.day_phone &&
2144 $scope.patron.isnew &&
2145 $scope.org_settings['patron.password.use_phone']) {
2146 $scope.patron.passwd = $scope.patron.day_phone.substr(-4);
2148 $scope.dupe_value_changed(field_name, value);
2150 case 'evening_phone' :
2151 if (normalizePhone(value) !== normalizePhone($scope.hold_rel_contacts.evening_phone.old)){
2152 $scope.hold_rel_contacts.evening_phone.newval = value;
2154 $scope.dupe_value_changed(field_name, value);
2156 case 'other_phone' :
2157 if (normalizePhone(value) !== normalizePhone($scope.hold_rel_contacts.other_phone.old)){
2158 $scope.hold_rel_contacts.other_phone.newval = value;
2160 $scope.dupe_value_changed(field_name, value);
2163 case 'ident_value2':
2164 $scope.dupe_value_changed('ident', value);
2167 case 'first_given_name':
2169 $scope.dupe_value_changed('name', value);
2173 $scope.dupe_value_changed('email', value);
2179 // dupe search on address wants the address object as the value.
2180 $scope.dupe_value_changed('address', obj);
2185 $scope.post_code_changed(obj);
2189 patronRegSvc.check_dupe_username(value)
2190 .then(function(yes) {$scope.dupe_username = Boolean(yes)});
2194 // TODO: finish barcode_changed handler.
2195 $scope.barcode_changed(value);
2196 apply_username_regex();
2198 case 'opac.default_phone':
2199 if (normalizePhone(value) !== normalizePhone($scope.hold_rel_contacts.default_phone.old)){
2200 $scope.hold_rel_contacts.default_phone.newval = value;
2203 case 'opac.default_sms_notify':
2204 if (normalizePhone(value) !== normalizePhone($scope.hold_rel_contacts.default_sms.old)){
2205 $scope.hold_rel_contacts.default_sms.newval = value;
2208 case 'opac.default_sms_carrier':
2209 if (value !== $scope.hold_rel_contacts.default_sms_carrier_id.old){
2210 $scope.hold_rel_contacts.default_sms_carrier_id.newval = value;
2216 // patron.juvenile is set to true if the user was born after
2217 function maintain_juvenile_flag() {
2218 if ( !($scope.patron && $scope.patron.dob) ) return;
2221 $scope.org_settings['global.juvenile_age_threshold']
2224 var base = new Date();
2226 base.setTime(base.getTime() -
2227 Number(egCore.date.intervalToSeconds(juv_interval) + '000'));
2229 $scope.patron.juvenile = ($scope.patron.dob > base);
2232 // returns true (disable) for orgs that cannot have users.
2233 $scope.disable_home_org = function(org_id) {
2234 if (!org_id) return;
2235 var org = egCore.org.get(org_id);
2239 org.ou_type().can_have_users() == 'f'
2243 // returns true (disable) for orgs that cannot have vols (for holds pickup)
2244 $scope.disable_pulib = function(org_id) {
2245 if (!org_id) return;
2246 return !egCore.org.CanHaveVolumes(org_id);
2249 // Returns true if attempting to edit self, but perms don't allow
2250 $scope.edit_passthru.self_edit_disallowed = function() {
2251 if ($scope.patron.id
2252 && $scope.patron.id == egCore.auth.user().id()
2253 && !$scope.perms.EDIT_SELF_IN_CLIENT
2258 // Returns true if attempting to edit a user without appropriate group application perms
2259 $scope.edit_passthru.group_edit_disallowed = function() {
2260 if ( $scope.patron.profile
2263 .filter(function(p) {
2264 return $scope.patron.profile.id() == p.id();
2270 // Returns true if the Save and Save & Clone buttons should be disabled.
2271 $scope.edit_passthru.hide_save_actions = function() {
2272 if ($scope.edit_passthru.self_edit_disallowed()) return true;
2273 if ($scope.edit_passthru.group_edit_disallowed()) return true;
2275 return $scope.patron.isnew ?
2276 !$scope.perms.CREATE_USER :
2277 !$scope.perms.UPDATE_USER;
2280 // Returns true if any input elements are tagged as invalid
2281 // via Angular patterns or required attributes.
2282 function form_has_invalid_fields() {
2283 return $('#patron-reg-container .ng-invalid').length > 0;
2286 function form_is_incomplete() {
2288 $scope.dupe_username ||
2289 $scope.dupe_barcode ||
2290 form_has_invalid_fields()
2295 $scope.edit_passthru.save = function(save_args) {
2296 if (!save_args) save_args = {};
2298 if (form_is_incomplete()) {
2299 // User has not provided valid values for all required fields.
2300 return egAlertDialog.open(egCore.strings.REG_INVALID_FIELDS);
2303 // remove page unload warning prompt
2304 egUnloadPrompt.clear();
2306 // toss the deleted addresses back into the patron's list of
2307 // addresses so it's included in the update
2308 $scope.patron.addresses =
2309 $scope.patron.addresses.concat(deleted_addresses);
2311 // ditto for waiver entries
2312 $scope.patron.waiver_entries =
2313 $scope.patron.waiver_entries.concat(deleted_waiver_entries);
2315 compress_hold_notify();
2319 patronRegSvc.save_user($scope.patron)
2320 .then(function(new_user) {
2321 if (new_user && new_user.classname) {
2322 updated_user = new_user;
2323 return patronRegSvc.save_user_settings(
2324 new_user, $scope.user_settings);
2326 var evt = egCore.evt.parse(new_user);
2328 if (evt && evt.textcode == 'XACT_COLLISION') {
2329 return egAlertDialog.open(
2330 egCore.strings.PATRON_EDIT_COLLISION).result;
2333 // debug only -- should not get here.
2334 alert('Patron update failed. \n\n' + js2JSON(new_user));
2337 }).then(function() {
2339 // only remove the staged user if the update succeeded.
2341 return patronRegSvc.remove_staged_user();
2345 }).then(function() {
2347 // linked groups for new users must be created after the new
2349 if ($scope.patron.isnew &&
2350 $scope.patron.groups && $scope.patron.groups.length) {
2351 var ids = $scope.patron.groups.map(function(g) {return g.id()});
2352 return patronRegSvc.apply_secondary_groups(updated_user.id(), ids)
2356 }).then(findChangedFieldsAffectedHolds)
2357 .then(function(changed_fields_plus_holds) {
2358 var needModal = changed_fields_plus_holds[0] && changed_fields_plus_holds[0].length > 0;
2360 ? $scope.update_holds_notify_modal(changed_fields_plus_holds[0])
2361 : $q.when(); // nothing changed, continue
2362 }).then(function() {
2366 ? egCore.strings.EG_WORK_LOG_REGISTERED_PATRON
2367 : egCore.strings.EG_WORK_LOG_EDITED_PATRON, {
2368 'action' : $scope.patron.isnew ? 'registered_patron' : 'edited_patron',
2369 'patron_id' : updated_user.id()
2374 // reloading the page means potentially losing some information
2375 // (e.g. last patron search), but is the only way to ensure all
2376 // components are properly updated to reflect the modified patron.
2377 if (updated_user && save_args.clone) {
2378 // open a separate tab for registering a new
2379 // patron from our cloned data.
2380 var url = 'https://'
2381 + $window.location.hostname
2382 + egCore.env.basePath
2383 + '/circ/patron/register/clone/'
2384 + updated_user.id();
2385 $window.open(url, '_blank').focus();
2387 } else if ($window.location.href.indexOf('stage') > -1 ){
2388 // we're here after deleting a self-reg staged user.
2389 // Just close tab, since refresh won't find staged user
2390 $timeout(function(){
2391 if (typeof BroadcastChannel != 'undefined') {
2392 var bChannel = new BroadcastChannel("eg.pending_usr.update");
2393 bChannel.postMessage({
2394 usr: egCore.idl.toHash(updated_user)
2401 // reload the current page
2402 $window.location.href = location.href;
2407 var phone_inputs = ["day_phone", "evening_phone","other_phone", "default_phone"];
2408 var sms_inputs = ["default_sms", "default_sms_carrier_id"];
2409 var method_prefs = ["sms_notify", "phone_notify", "email_notify"];
2410 var groupBy = function(xs, key){
2411 return xs.reduce(function(rv, x){
2412 (rv[x[key]] = rv[x[key]] || []).push(x);
2417 function findChangedFieldsAffectedHolds(){
2419 var changed_hold_fields = [];
2421 var default_phone_changed = false;
2422 var default_sms_carrier_changed = false;
2423 var default_sms_changed = false;
2424 for (var c in $scope.hold_rel_contacts){
2425 var newinput = $scope.hold_rel_contacts[c].newval;
2426 if ($scope.hold_rel_contacts.hasOwnProperty(c)
2427 && newinput !== null // null means user has not provided a value in this session
2428 && newinput != $scope.hold_rel_contacts[c].old){
2429 var changed = $scope.hold_rel_contacts[c];
2431 changed.isChecked = false;
2432 changed_hold_fields.push(changed);
2433 if (c === 'default_phone') default_phone_changed = true;
2434 if (c === 'default_sms_carrier_id') default_sms_carrier_changed = true;
2435 if (c === 'default_sms') default_sms_changed = true;
2439 for (var c in $scope.hold_notify_observer){
2440 var newinput = $scope.hold_notify_observer[c].newval;
2441 if ($scope.hold_notify_observer.hasOwnProperty(c)
2442 && newinput !== null // null means user has not provided a value in this session
2443 && newinput != $scope.hold_notify_observer[c].old){
2444 var changed = $scope.hold_notify_observer[c];
2445 changed.name = c + "_notify";
2446 changed.isChecked = false;
2447 changed_hold_fields.push(changed);
2449 // if we're turning on phone notifications, offer to update to the
2450 // current default number
2451 if (c === 'phone' && $scope.user_settings['opac.default_phone'] && newinput && !default_phone_changed) {
2452 changed_hold_fields.push({
2453 name: 'default_phone',
2455 newval: $scope.user_settings['opac.default_phone'],
2459 // and similarly for SMS
2460 if (c === 'sms' && $scope.user_settings['opac.default_sms_carrier'] && newinput && !default_sms_carrier_changed) {
2461 changed_hold_fields.push({
2462 name: 'default_sms_carrier_id',
2464 newval: $scope.user_settings['opac.default_sms_carrier'],
2468 if (c === 'sms' && $scope.user_settings['opac.default_sms_notify'] && newinput && !default_sms_changed) {
2469 changed_hold_fields.push({
2470 name: 'default_sms',
2472 newval: $scope.user_settings['opac.default_sms_notify'],
2480 angular.forEach(changed_hold_fields, function(c){
2481 promises.push(egCore.net.request('open-ils.circ',
2482 'open-ils.circ.holds.retrieve_by_notify_staff',
2483 egCore.auth.token(),
2485 c.name.includes('notify') || c.name.includes('carrier') ? c.old : c.newval,
2487 .then(function(affected_holds){
2488 if(!affected_holds || affected_holds.length < 1){
2489 // no holds affected - remove change from list
2490 var p = changed_hold_fields.indexOf(c);
2491 changed_hold_fields.splice(p, 1);
2493 c.affects = affected_holds;
2495 //angular.forEach(c.affects, function(h){
2498 if (!c.name.includes("notify")){
2499 if (c.name === "default_sms_carrier_id") {
2500 c.groups = groupBy(c.affects,'sms_carrier');
2502 c.groups = groupBy(c.affects, c.name.includes('_phone') ? 'phone_notify':'sms_notify');
2506 return $q.when(changed_hold_fields);
2511 return $q.all(promises);
2514 $scope.update_holds_notify_modal = function(changed_hold_fields){
2515 // open modal after-save, pre-reload modal to deal with updated hold notification stuff
2516 if ($scope.patron.isnew || changed_hold_fields.length < 1){
2520 return $uibModal.open({
2521 templateUrl: './circ/patron/t_hold_notify_update',
2524 ['$scope','$uibModalInstance','changed_fields','patron','carriers','def_carrier_id','default_phone','default_sms',
2525 function($scope , $uibModalInstance , changed_fields , patron, carriers, def_carrier_id , default_phone , default_sms) {
2526 // local modal scope
2527 $scope.ch_fields = changed_fields;
2528 $scope.focusMe = true;
2529 $scope.ok = function(msg) {
2531 // Need to do this so the page will reload automatically
2532 if (msg == 'no-update') return $uibModalInstance.close();
2534 //var selectedChanges = $scope.changed_fields.filter(function(c) {
2535 // return c.isChecked;
2537 var selectedChanges = [];
2538 angular.forEach($scope.ch_fields, function(f){
2539 if (f.name == 'phone_notify' && f.newval && f.isChecked) {
2540 // convert to default_phone change
2541 f.sel_hids = f.affects.map(function(h){ return h.id});
2542 f.newval = default_phone;
2543 f.name = 'default_phone';
2544 selectedChanges.push(f);
2545 } else if (f.name == 'sms_notify' && f.newval && f.isChecked) {
2546 // convert to default_sms change
2547 f.sel_hids = f.affects.map(function(h){ return h.id});
2548 f.newval = default_sms;
2549 f.name = 'default_sms';
2550 selectedChanges.push(f);
2551 } else if (f.name.includes('notify') || f.name.includes('carrier')){
2553 f.sel_hids = f.affects.map(function(h){ return h.id});
2554 selectedChanges.push(f);
2557 // this is the sms or phone, so look in the groups obj
2559 for (var k in f.groups){
2560 if (f.groups.hasOwnProperty(k)){
2561 var sel_holds = f.groups[k].filter(function(h){
2565 var hids = sel_holds.map(function(h){ return h.id});
2566 f.sel_hids.push.apply(f.sel_hids, hids);
2570 if (f.sel_hids.length > 0) selectedChanges.push(f);
2575 // call method to update holds for each change
2576 var chain = $q.when();
2577 angular.forEach(selectedChanges, function(c){
2578 var carrierId = c.name.includes('default_sms') ? Number(def_carrier_id) : null;
2579 chain = chain.then(function() {
2580 return egCore.net.request('open-ils.circ',
2581 'open-ils.circ.holds.batch_update_holds_by_notify_staff', egCore.auth.token(),
2584 c.old, // TODO: for number changes, old val is effectively moot
2587 carrierId).then(function(okList){ console.log(okList) });
2591 // carry out the updates and close modal
2592 chain.finally(function(){ $uibModalInstance.close() });
2595 $scope.cancel = function () { $uibModalInstance.dismiss() }
2597 $scope.isNumberCh = function(c){
2598 return !(c.name.includes('notify') || c.name.includes('carrier'));
2602 $scope.groupChanged = function(ch_f, grpK){
2603 var holdArr = ch_f.groups[grpK];
2604 if (holdArr && holdArr.length > 0){
2605 angular.forEach(holdArr, function(h){
2606 if (h.isChecked) { h.isChecked = !h.isChecked; $scope.chgCt-- }
2607 else { h.isChecked = true; $scope.chgCt++ }
2612 $scope.nonGrpChanged = function(field_ch){
2613 if (field_ch.isChecked) $scope.chgCt++;
2614 else $scope.chgCt--;
2617 // use this function as a keydown handler on form
2618 // elements that should not submit the form on enter.
2619 $scope.preventSubmit = function($event) {
2620 if ($event.keyCode == 13)
2621 $event.preventDefault();
2624 $scope.prettyCarrier = function(carrierId){
2625 var sms_carrierObj = carriers.find(function(c){ return c.id == carrierId});
2626 return sms_carrierObj.name;
2628 $scope.prettyBool = function(v){
2629 return v ? 'YES' : 'NO';
2633 changed_fields : function(){ return changed_hold_fields },
2634 patron : function(){ return $scope.patron },
2635 def_carrier_id : function(){
2636 var d = $scope.hold_rel_contacts.default_sms_carrier_id;
2637 return d.newval ? d.newval : d.old;
2639 default_phone : function() {
2640 return ($scope.hold_rel_contacts.default_phone.newval) ?
2641 $scope.hold_rel_contacts.default_phone.newval :
2642 $scope.hold_rel_contacts.default_phone.old;
2644 default_sms : function() {
2645 return ($scope.hold_rel_contacts.default_sms.newval) ?
2646 $scope.hold_rel_contacts.default_sms.newval :
2647 $scope.hold_rel_contacts.default_sms.old;
2649 carriers : function(){ return $scope.sms_carriers.map(function(c){ return egCore.idl.toHash(c) }) }
2654 $scope.edit_passthru.print = function() {
2655 var print_data = {patron : $scope.patron}
2657 return egCore.print.print({
2658 context : 'default',
2659 template : 'patron_data',