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 //service.check_grp_app_perm = function(grp_id) {
169 // determine which user groups our user is not allowed to modify
170 service.set_edit_profiles = function() {
171 var all_app_perms = [];
172 var failed_perms = [];
174 // extract the application permissions
175 angular.forEach(service.profiles, function(grp) {
176 if (grp.application_perm())
177 all_app_perms.push(grp.application_perm());
180 // fill in service.edit_profiles by inspecting failed_perms
181 function traverse_grp_tree(grp, failed) {
183 failed_perms.indexOf(grp.application_perm()) > -1;
185 if (!failed) service.edit_profiles.push(grp);
188 service.profiles.filter( // children of grp
189 function(p) { return p.parent() == grp.id() }),
190 function(child) {traverse_grp_tree(child, failed)}
194 return egCore.perm.hasPermAt(all_app_perms, true).then(
195 function(perm_orgs) {
196 angular.forEach(all_app_perms, function(p) {
197 if (perm_orgs[p].length == 0)
198 failed_perms.push(p);
201 traverse_grp_tree(egCore.env.pgt.tree);
206 service.set_edit_profile_entries = function() {
207 var all_app_perms = [];
208 var failed_perms = [];
210 // extract the application permissions
211 angular.forEach(service.profile_entries, function(entry) {
212 if (entry.grp().application_perm())
213 all_app_perms.push(entry.grp().application_perm());
216 // fill in service.edit_profiles by inspecting failed_perms
217 function traverse_grp_tree(entry, failed) {
219 failed_perms.indexOf(entry.grp().application_perm()) > -1;
221 if (!failed) service.edit_profile_entries.push(entry);
224 service.profile_entries.filter( // children of grp
225 function(p) { return p.parent() == entry.id() }),
226 function(child) {traverse_grp_tree(child, failed)}
230 return egCore.perm.hasPermAt(all_app_perms, true).then(
231 function(perm_orgs) {
232 angular.forEach(all_app_perms, function(p) {
233 if (perm_orgs[p].length == 0)
234 failed_perms.push(p);
237 angular.forEach(egCore.env.pgtde.tree, function(tree) {
238 traverse_grp_tree(tree);
244 // resolves to a hash of perm-name => boolean value indicating
245 // wether the user has the permission at org_id.
246 service.has_perms_for_org = function(org_id) {
249 'EDIT_SELF_IN_CLIENT',
252 'CREATE_USER_GROUP_LINK',
253 'UPDATE_PATRON_COLLECTIONS_EXEMPT',
254 'UPDATE_PATRON_CLAIM_RETURN_COUNT',
255 'UPDATE_PATRON_CLAIM_NEVER_CHECKED_OUT_COUNT',
256 'UPDATE_PATRON_ACTIVE_CARD',
257 'UPDATE_PATRON_PRIMARY_CARD'
260 return egCore.perm.hasPermAt(perms_needed, true)
261 .then(function(perm_map) {
263 angular.forEach(perms_needed, function(perm) {
265 Boolean(perm_map[perm].indexOf(org_id) > -1);
272 service.get_surveys = function() {
273 var org_ids = egCore.org.fullPath(egCore.auth.user().ws_ou(), true);
275 return egCore.pcrud.search('asv', {
277 start_date : {'<=' : 'now'},
278 end_date : {'>=' : 'now'}
287 ).then(function(surveys) {
288 surveys = surveys.sort(function(a,b) {
289 return a.name() < b.name() ? -1 : 1 });
290 service.surveys = surveys;
291 angular.forEach(surveys, function(survey) {
292 angular.forEach(survey.questions(), function(question) {
293 service.survey_questions[question.id()] = question;
294 angular.forEach(question.answers(), function(answer) {
295 service.survey_answers[answer.id()] = answer;
300 egLovefield.setListInOfflineCache('asv', service.surveys)
301 egLovefield.setListInOfflineCache('asvq', service.survey_questions)
302 egLovefield.setListInOfflineCache('asva', service.survey_answers)
307 service.get_stat_cats = function() {
308 return egCore.net.request(
310 'open-ils.circ.stat_cat.actor.retrieve.all',
311 egCore.auth.token(), egCore.auth.user().ws_ou()
312 ).then(function(cats) {
313 cats = cats.sort(function(a, b) {
314 return a.name() < b.name() ? -1 : 1});
315 angular.forEach(cats, function(cat) {
317 cat.entries().sort(function(a,b) {
318 return a.value() < b.value() ? -1 : 1
322 service.stat_cats = cats;
323 return egLovefield.setStatCatsCache(cats);
327 service.get_org_settings = function() {
328 return egCore.org.settings([
329 'global.password_regex',
330 'global.juvenile_age_threshold',
331 'patron.password.use_phone',
332 'ui.patron.default_inet_access_level',
333 'ui.patron.default_ident_type',
334 'ui.patron.default_country',
335 'ui.patron.registration.require_address',
336 'circ.holds.behind_desk_pickup_supported',
337 'circ.patron_edit.clone.copy_address',
338 'circ.privacy_waiver',
339 'ui.patron.edit.au.prefix.require',
340 'ui.patron.edit.au.prefix.show',
341 'ui.patron.edit.au.prefix.suggest',
342 'ui.patron.edit.ac.barcode.regex',
343 'ui.patron.edit.au.second_given_name.show',
344 'ui.patron.edit.au.second_given_name.suggest',
345 'ui.patron.edit.au.suffix.show',
346 'ui.patron.edit.au.suffix.suggest',
347 'ui.patron.edit.au.alias.show',
348 'ui.patron.edit.au.alias.suggest',
349 'ui.patron.edit.au.dob.require',
350 'ui.patron.edit.au.dob.show',
351 'ui.patron.edit.au.dob.suggest',
352 'ui.patron.edit.au.dob.calendar',
353 'ui.patron.edit.au.dob.example',
354 'ui.patron.edit.au.juvenile.show',
355 'ui.patron.edit.au.juvenile.suggest',
356 'ui.patron.edit.au.ident_value.show',
357 'ui.patron.edit.au.ident_value.require',
358 'ui.patron.edit.au.ident_value.suggest',
359 'ui.patron.edit.au.ident_value2.show',
360 'ui.patron.edit.au.ident_value2.suggest',
361 'ui.patron.edit.au.email.require',
362 'ui.patron.edit.au.email.show',
363 'ui.patron.edit.au.email.suggest',
364 'ui.patron.edit.au.email.regex',
365 'ui.patron.edit.au.email.example',
366 'ui.patron.edit.au.day_phone.require',
367 'ui.patron.edit.au.day_phone.show',
368 'ui.patron.edit.au.day_phone.suggest',
369 'ui.patron.edit.au.day_phone.regex',
370 'ui.patron.edit.au.day_phone.example',
371 'ui.patron.edit.au.evening_phone.require',
372 'ui.patron.edit.au.evening_phone.show',
373 'ui.patron.edit.au.evening_phone.suggest',
374 'ui.patron.edit.au.evening_phone.regex',
375 'ui.patron.edit.au.evening_phone.example',
376 'ui.patron.edit.au.other_phone.require',
377 'ui.patron.edit.au.other_phone.show',
378 'ui.patron.edit.au.other_phone.suggest',
379 'ui.patron.edit.au.other_phone.regex',
380 'ui.patron.edit.au.other_phone.example',
381 'ui.patron.edit.phone.regex',
382 'ui.patron.edit.phone.example',
383 'ui.patron.edit.au.active.show',
384 'ui.patron.edit.au.active.suggest',
385 'ui.patron.edit.au.barred.show',
386 'ui.patron.edit.au.barred.suggest',
387 'ui.patron.edit.au.master_account.show',
388 'ui.patron.edit.au.master_account.suggest',
389 'ui.patron.edit.au.claims_returned_count.show',
390 'ui.patron.edit.au.claims_returned_count.suggest',
391 'ui.patron.edit.au.claims_never_checked_out_count.show',
392 'ui.patron.edit.au.claims_never_checked_out_count.suggest',
393 'ui.patron.edit.au.alert_message.show',
394 'ui.patron.edit.au.alert_message.suggest',
395 'ui.patron.edit.aua.post_code.regex',
396 'ui.patron.edit.aua.post_code.example',
397 'ui.patron.edit.aua.county.require',
398 'ui.patron.edit.au.guardian.show',
399 'ui.patron.edit.au.guardian.suggest',
400 'ui.patron.edit.guardian_required_for_juv',
402 'ui.patron.edit.default_suggested',
403 'opac.barcode_regex',
404 'opac.username_regex',
406 'ui.patron.edit.aua.state.require',
407 'ui.patron.edit.aua.state.suggest',
408 'ui.patron.edit.aua.state.show',
409 'ui.admin.work_log.max_entries',
410 'ui.admin.patron_log.max_entries'
411 ]).then(function(settings) {
412 service.org_settings = settings;
413 if (egCore && egCore.env && !egCore.env.aous) {
414 egCore.env.aous = settings;
415 console.log('setting egCore.env.aous');
417 return service.process_org_settings(settings);
421 // some org settings require the retrieval of additional data
422 service.process_org_settings = function(settings) {
424 var promises = [egLovefield.setSettingsCache(settings)];
426 if (settings['sms.enable']) {
427 // fetch SMS carriers
429 egCore.pcrud.search('csc',
432 {'class':'csc', 'field':'name'},
433 {'class':'csc', 'field':'region'}
435 ).then(function(carriers) {
436 service.sms_carriers = carriers;
440 // if other promises are added below, this is not necessary.
441 promises.push($q.when());
444 // other post-org-settings processing goes here,
445 // adding to promises as needed.
447 return $q.all(promises);
450 service.get_ident_types = function() {
451 if (egCore.env.cit) {
452 service.ident_types = egCore.env.cit.list;
455 return egCore.pcrud.retrieveAll('cit', {}, {atomic : true})
456 .then(function(types) {
457 egCore.env.absorbList(types, 'cit')
458 service.ident_types = types
463 service.get_net_access_levels = function() {
464 if (egCore.env.cnal) {
465 service.net_access_levels = egCore.env.cnal.list;
468 return egCore.pcrud.retrieveAll('cnal', {}, {atomic : true})
469 .then(function(levels) {
470 egCore.env.absorbList(levels, 'cnal')
471 service.net_access_levels = levels
476 service.get_perm_groups = function() {
477 if (egCore.env.pgt) {
478 service.profiles = egCore.env.pgt.list;
479 return service.set_edit_profiles();
481 return egCore.pcrud.search('pgt', {parent : null},
482 {flesh : -1, flesh_fields : {pgt : ['children']}}
485 egCore.env.absorbTree(tree, 'pgt')
486 service.profiles = egCore.env.pgt.list;
487 return service.set_edit_profiles();
493 service.searchPermGroupEntries = function(org) {
494 return egCore.pcrud.search('pgtde', {org: org, parent: null},
495 {flesh: -1, flesh_fields: {pgtde: ['grp', 'children']}}, {atomic: true}
496 ).then(function(treeArray) {
497 if (!treeArray.length && egCore.org.get(org).parent_ou()) {
498 return service.searchPermGroupEntries(egCore.org.get(org).parent_ou());
504 service.get_perm_group_entries = function() {
505 if (egCore.env.pgtde) {
506 service.profile_entries = egCore.env.pgtde.list;
507 return service.set_edit_profile_entries();
509 return service.searchPermGroupEntries(egCore.auth.user().ws_ou()).then(function(treeArray) {
510 function compare(a,b) {
511 if (a.position() > b.position())
513 if (a.position() < b.position())
519 function squash(node) {
520 node.children().sort(compare);
522 angular.forEach(node.children(), squash);
525 angular.forEach(treeArray, squash);
526 var blob = egCore.env.absorbList(list, 'pgtde');
527 blob.tree = treeArray;
529 service.profile_entries = egCore.env.pgtde.list;
530 return service.set_edit_profile_entries();
535 service.get_field_doc = function() {
537 return egCore.pcrud.search('fdoc', {
538 fm_class: ['au', 'ac', 'aua', 'actsc', 'asv', 'asvq', 'asva']})
541 return egLovefield.setListInOfflineCache('fdoc', to_cache)
545 if (!service.field_doc[doc.fm_class()]) {
546 service.field_doc[doc.fm_class()] = {};
548 service.field_doc[doc.fm_class()][doc.field()] = doc;
555 service.get_user_setting_types = function() {
557 // No need to re-fetch the common setting types.
558 if (Object.keys(service.user_setting_types).length)
561 var org_ids = egCore.org.ancestors(egCore.auth.user().ws_ou(), true);
564 'circ.holds_behind_desk',
565 'circ.collections.exempt',
567 'opac.default_phone',
568 'opac.default_pickup_location',
569 'opac.default_sms_carrier',
570 'opac.default_sms_notify'];
572 return egCore.pcrud.search('cust', {
574 {name : static_types}, // common user settings
575 {name : { // opt-in notification user settings
577 select : {atevdef : ['opt_in_setting']},
579 // we only care about opt-in settings for
580 // event_defs our users encounter
581 where : {'+atevdef' : {owner : org_ids}}
585 }, {}, {atomic : true}).then(function(setting_types) {
587 egCore.env.absorbList(setting_types, 'cust'); // why not...
589 angular.forEach(setting_types, function(stype) {
590 service.user_setting_types[stype.name()] = stype;
591 if (static_types.indexOf(stype.name()) == -1) {
592 service.opt_in_setting_types[stype.name()] = stype;
598 service.get_user_settings = function() {
600 return service.get_user_setting_types()
603 var setting_types = Object.values(service.user_setting_types);
605 if (service.patron_id) {
606 // retrieve applied values for the current user
607 // for the setting types we care about.
610 setting_types.map(function(obj) { return obj.name() });
612 return egCore.net.request(
614 'open-ils.actor.patron.settings.retrieve.authoritative',
618 ).then(function(settings) {
619 service.user_settings = settings;
624 // apply default user setting values
625 angular.forEach(setting_types, function(stype, index) {
626 if (stype.reg_default() != undefined) {
627 var val = stype.reg_default();
628 if (stype.datatype() == 'bool') {
629 // A boolean user setting type whose default
630 // value starts with t/T is considered 'true',
632 val = Boolean((val+'').match(/^t/i));
634 service.user_settings[stype.name()] = val;
641 service.invalidate_field = function(patron, field) {
642 console.log('Invalidating patron field ' + field);
644 return egCore.net.request(
646 'open-ils.actor.invalidate.' + field,
647 egCore.auth.token(), patron.id, null, patron.home_ou.id()
649 ).then(function(res) {
650 // clear the invalid value from the form
653 // update last_xact_id so future save operations
654 // on this patron will be allowed
655 patron.last_xact_id = res.payload.last_xact_id[patron.id];
659 service.send_test_message = function(user_id, hook) {
661 return egCore.net.request(
663 'open-ils.actor.event.test_notification',
664 egCore.auth.token(), {hook: hook, target: user_id}
665 ).then(function(res) {
670 service.dupe_patron_search = function(patron, type, value) {
673 console.log('Dupe search called with "'+ type +'" and value '+ value);
675 if (type.match(/phone/)) type = 'phone'; // day_phone, etc.
680 var fname = patron.first_given_name;
681 var lname = patron.family_name;
682 if (!(fname && lname)) return $q.when({count:0});
684 first_given_name : {value : fname, group : 0},
685 family_name : {value : lname, group : 0}
690 search = {email : {value : value, group : 0}};
694 search = {ident : {value : value, group : 2}};
698 search = {phone : {value : value, group : 2}};
703 angular.forEach(['street1', 'street2', 'city', 'post_code'],
706 search[field] = {value : value[field], group: 1};
712 return egCore.net.request(
714 'open-ils.actor.patron.search.advanced',
715 egCore.auth.token(), search, null, null, 1
716 ).then(function(res) {
717 res = res.filter(function(id) {return id != patron.id});
725 service.init_patron = function(current) {
728 return $q.when(service.init_new_patron());
730 service.patron = current;
731 return $q.when(service.init_existing_patron(current));
734 service.ingest_address = function(patron, addr) {
735 addr.valid = addr.valid == 't';
736 addr.within_city_limits = addr.within_city_limits == 't';
737 addr._is_mailing = (patron.mailing_address &&
738 addr.id == patron.mailing_address.id);
739 addr._is_billing = (patron.billing_address &&
740 addr.id == patron.billing_address.id);
741 addr.pending = addr.pending === 't';
744 service.ingest_waiver_entry = function(patron, waiver_entry) {
745 waiver_entry.place_holds = waiver_entry.place_holds == 't';
746 waiver_entry.pickup_holds = waiver_entry.pickup_holds == 't';
747 waiver_entry.view_history = waiver_entry.view_history == 't';
748 waiver_entry.checkout_items = waiver_entry.checkout_items == 't';
752 * Existing patron objects reqire some data munging before insertion
755 * 1. Turn everything into a hash
756 * 2. ... Except certain fields (selectors) whose widgets require objects
757 * 3. Bools must be Boolean, not t/f.
759 service.init_existing_patron = function(current) {
761 service.existing_patron = current;
763 var patron = egCore.idl.toHash(current);
765 patron.home_ou = egCore.org.get(patron.home_ou.id);
766 patron.expire_date = new Date(Date.parse(patron.expire_date));
767 patron.dob = service.parse_dob(patron.dob);
768 patron.profile = current.profile(); // pre-hash version
769 patron.net_access_level = current.net_access_level();
770 patron.ident_type = current.ident_type();
771 patron.ident_type2 = current.ident_type2();
772 patron.groups = current.groups(); // pre-hash
775 ['juvenile', 'barred', 'active', 'master_account'],
776 function(field) { patron[field] = patron[field] == 't'; }
779 angular.forEach(patron.cards, function(card) {
780 card.active = card.active == 't';
781 if (card.id == patron.card.id) {
783 card._primary = true;
787 angular.forEach(patron.addresses,
788 function(addr) { service.ingest_address(patron, addr) });
790 // Link replaced address to its pending address.
791 angular.forEach(patron.addresses, function(addr) {
793 addr._replaces = patron.addresses.filter(
794 function(a) {return a.id == addr.replaces})[0];
798 angular.forEach(patron.waiver_entries,
799 function(waiver_entry) { service.ingest_waiver_entry(patron, waiver_entry) });
801 service.get_linked_addr_users(patron.addresses);
803 // Remove stat cat entries that link to out-of-scope stat
804 // cats. With this, we avoid unnecessarily updating (or worse,
805 // modifying) stat cat values that are not ours to modify.
806 patron.stat_cat_entries = patron.stat_cat_entries.filter(
809 // service.stat_cats only contains in-scope stat cats.
810 service.stat_cats.filter(function(cat) {
811 return (cat.id() == map.stat_cat.id) })[0]
816 // toss entries for existing stat cat maps into our living
817 // stat cat entry map, which is modified within the template.
818 service.stat_cat_entry_maps = [];
819 angular.forEach(patron.stat_cat_entries, function(map) {
820 service.stat_cat_entry_maps[map.stat_cat.id] = map.stat_cat_entry;
823 service.patron = patron;
827 service.init_new_patron = function() {
829 id : service.virt_id--,
832 address_type : egCore.strings.REG_ADDR_TYPE,
835 within_city_limits : false,
836 country : service.org_settings['ui.patron.default_country'],
840 id : service.virt_id--,
851 home_ou : egCore.org.get(egCore.auth.user().ws_ou()),
852 stat_cat_entries : [],
858 if (service.clone_user)
859 service.copy_clone_data(user);
861 if (service.stage_user)
862 service.copy_stage_data(user);
867 // dob is always YYYY-MM-DD
868 // Dates of birth do not contain timezone info, which can lead to
869 // inconcistent timezone handling, potentially representing
870 // different points in time, depending on the implementation.
871 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
872 // See "Differences in assumed time zone"
873 // TODO: move this into egDate ?
874 service.parse_dob = function(dob) {
875 if (!dob) return null;
876 var parts = dob.split('-');
877 return new Date(parts[0], parts[1] - 1, parts[2])
880 service.copy_stage_data = function(user) {
881 var cuser = service.stage_user;
883 // copy the data into our new user object
885 for (var key in egCore.idl.classes.stgu.field_map) {
886 if (egCore.idl.classes.au.field_map[key] &&
887 !egCore.idl.classes.stgu.field_map[key].virtual) {
888 if (cuser.user[key]() !== null)
889 user[key] = cuser.user[key]();
893 if (user.home_ou) user.home_ou = egCore.org.get(user.home_ou);
894 if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
896 user.ident_type = egCore.env.cit.map[user.ident_type];
897 if (user.ident_type2)
898 user.ident_type2 = egCore.env.cit.map[user.ident_type2];
899 user.dob = service.parse_dob(user.dob);
901 // Clear the usrname if it looks like a UUID
902 if (user.usrname.replace(/-/g,'').match(/[0-9a-f]{32}/))
905 // Don't use stub address if we have one from the staged user.
906 if (cuser.mailing_addresses.length || cuser.billing_addresses.length)
909 // is_mailing=false implies is_billing
910 function addr_from_stage(stage_addr) {
911 if (!stage_addr) return;
912 var cls = stage_addr.classname;
915 id : service.virt_id--,
919 address_type : egCore.strings.REG_ADDR_TYPE,
920 _is_mailing : cls == 'stgma',
921 _is_billing : cls == 'stgba'
924 user.mailing_address = addr;
925 user.addresses.push(addr);
927 for (var key in egCore.idl.classes[cls].field_map) {
928 if (egCore.idl.classes.aua.field_map[key] &&
929 !egCore.idl.classes[cls].field_map[key].virtual) {
930 if (stage_addr[key]() !== null)
931 addr[key] = stage_addr[key]();
936 addr_from_stage(cuser.mailing_addresses[0]);
937 addr_from_stage(cuser.billing_addresses[0]);
939 if (user.addresses.length == 1) {
940 // If there is only one address,
941 // use it as both mailing and billing.
942 var addr = user.addresses[0];
943 addr._is_mailing = addr._is_billing = true;
944 user.mailing_address = user.billing_address = addr;
947 if (cuser.cards.length) {
949 id : service.virt_id--,
950 barcode : cuser.cards[0].barcode(),
956 user.cards.push(user.card);
957 if (user.usrname == '')
958 user.usrname = card.barcode;
961 angular.forEach(cuser.settings, function(setting) {
962 service.user_settings[setting.setting()] = Boolean(setting.value());
966 // copy select values from the cloned user to the new user.
968 service.copy_clone_data = function(user) {
969 var clone_user = service.clone_user;
971 // flesh the home org locally
972 user.home_ou = egCore.org.get(clone_user.home_ou());
973 if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
975 if (!clone_user.billing_address() &&
976 !clone_user.mailing_address())
977 return; // no addresses to copy or link
979 // if the cloned user has any addresses, we don't need
980 // the stub address created in init_new_patron.
984 service.org_settings['circ.patron_edit.clone.copy_address'];
993 angular.forEach(clone_fields, function(field) {
994 user[field] = clone_user[field]();
997 if (copy_addresses) {
998 var bill_addr, mail_addr;
1000 // copy the billing and mailing addresses into new addresses
1001 function clone_addr(addr) {
1002 var new_addr = egCore.idl.toHash(addr);
1003 new_addr.id = service.virt_id--;
1004 new_addr.usr = user.id;
1005 new_addr.isnew = true;
1006 new_addr.valid = true;
1007 user.addresses.push(new_addr);
1011 if (bill_addr = clone_user.billing_address()) {
1012 var addr = clone_addr(bill_addr);
1013 addr._is_billing = true;
1014 user.billing_address = addr;
1017 if (mail_addr = clone_user.mailing_address()) {
1019 if (bill_addr && bill_addr.id() == mail_addr.id()) {
1020 user.mailing_address = user.billing_address;
1021 user.mailing_address._is_mailing = true;
1023 var addr = clone_addr(mail_addr);
1024 addr._is_mailing = true;
1025 user.mailing_address = addr;
1029 // if there is no billing addr, use the mailing addr
1030 user.billing_address = user.mailing_address;
1031 user.billing_address._is_billing = true;
1038 // link the billing and mailing addresses
1040 if (addr = clone_user.billing_address()) {
1041 user.billing_address = egCore.idl.toHash(addr);
1042 user.billing_address._is_billing = true;
1043 user.addresses.push(user.billing_address);
1044 user.billing_address._linked_owner_id = clone_user.id();
1045 user.billing_address._linked_owner = service.format_name(
1046 clone_user.family_name(),
1047 clone_user.first_given_name(),
1048 clone_user.second_given_name()
1052 if (addr = clone_user.mailing_address()) {
1053 if (user.billing_address &&
1054 addr.id() == user.billing_address.id) {
1055 // mailing matches billing
1056 user.mailing_address = user.billing_address;
1057 user.mailing_address._is_mailing = true;
1059 user.mailing_address = egCore.idl.toHash(addr);
1060 user.mailing_address._is_mailing = true;
1061 user.addresses.push(user.mailing_address);
1062 user.mailing_address._linked_owner_id = clone_user.id();
1063 user.mailing_address._linked_owner = service.format_name(
1064 clone_user.family_name(),
1065 clone_user.first_given_name(),
1066 clone_user.second_given_name()
1073 // translate the patron back into IDL form
1074 service.save_user = function(phash) {
1076 var patron = egCore.idl.fromHash('au', phash);
1078 patron.home_ou(patron.home_ou().id());
1079 patron.expire_date(patron.expire_date().toISOString());
1080 patron.profile(patron.profile().id());
1082 patron.dob(patron.dob().toISOString().replace(/T.*/,''));
1083 if (patron.ident_type())
1084 patron.ident_type(patron.ident_type().id());
1085 if (patron.net_access_level())
1086 patron.net_access_level(patron.net_access_level().id());
1089 ['juvenile', 'barred', 'active', 'master_account'],
1090 function(field) { patron[field](phash[field] ? 't' : 'f'); }
1093 var card_hashes = patron.cards();
1095 angular.forEach(card_hashes, function(chash) {
1096 var card = egCore.idl.fromHash('ac', chash)
1097 card.usr(patron.id());
1098 card.active(chash.active ? 't' : 'f');
1099 patron.cards().push(card);
1100 if (chash._primary) {
1105 var addr_hashes = patron.addresses();
1106 patron.addresses([]);
1107 angular.forEach(addr_hashes, function(addr_hash) {
1108 if (!addr_hash.isnew && !addr_hash.isdeleted)
1109 addr_hash.ischanged = true;
1110 var addr = egCore.idl.fromHash('aua', addr_hash);
1111 patron.addresses().push(addr);
1112 addr.valid(addr.valid() ? 't' : 'f');
1113 addr.within_city_limits(addr.within_city_limits() ? 't' : 'f');
1114 addr.pending(addr.pending() ? 't' : 'f');
1115 if (addr_hash._is_mailing) patron.mailing_address(addr);
1116 if (addr_hash._is_billing) patron.billing_address(addr);
1119 patron.survey_responses([]);
1120 angular.forEach(service.survey_responses, function(answer) {
1121 var question = service.survey_questions[answer.question()];
1122 var resp = new egCore.idl.asvr();
1124 resp.survey(question.survey());
1125 resp.question(question.id());
1126 resp.answer(answer.id());
1127 resp.usr(patron.id());
1128 resp.answer_date('now');
1129 patron.survey_responses().push(resp);
1132 // re-object-ify the patron stat cat entry maps
1134 angular.forEach(patron.stat_cat_entries(), function(entry) {
1135 var e = egCore.idl.fromHash('actscecm', entry);
1136 e.stat_cat(e.stat_cat().id);
1139 patron.stat_cat_entries(maps);
1141 // service.stat_cat_entry_maps maps stats to values
1142 // patron.stat_cat_entries is an array of stat_cat_entry_usr_map's
1144 service.stat_cat_entry_maps, function(value, cat_id) {
1146 // see if we already have a mapping for this entry
1147 var existing = patron.stat_cat_entries().filter(
1148 function(e) { return e.stat_cat() == cat_id })[0];
1150 if (existing) { // we have a mapping
1151 // if the existing mapping matches the new one,
1152 // there' nothing left to do
1153 if (existing.stat_cat_entry() == value) return;
1155 // mappings differ. delete the old one and create
1157 existing.isdeleted(true);
1160 var newmap = new egCore.idl.actscecm();
1161 newmap.target_usr(patron.id());
1163 newmap.stat_cat(cat_id);
1164 newmap.stat_cat_entry(value);
1165 patron.stat_cat_entries().push(newmap);
1168 var waiver_hashes = patron.waiver_entries();
1169 patron.waiver_entries([]);
1170 angular.forEach(waiver_hashes, function(waiver_hash) {
1171 if (!waiver_hash.isnew && !waiver_hash.isdeleted)
1172 waiver_hash.ischanged = true;
1173 var waiver_entry = egCore.idl.fromHash('aupw', waiver_hash);
1174 patron.waiver_entries().push(waiver_entry);
1177 if (!patron.isnew()) patron.ischanged(true);
1179 return egCore.net.request(
1181 'open-ils.actor.patron.update',
1182 egCore.auth.token(), patron);
1185 service.remove_staged_user = function() {
1186 if (!service.stage_user) return $q.when();
1187 return egCore.net.request(
1189 'open-ils.actor.user.stage.delete',
1190 egCore.auth.token(),
1191 service.stage_user.user.row_id()
1195 service.save_user_settings = function(new_user, user_settings) {
1198 if (service.patron_id) {
1199 // Update all user editor setting values for existing
1200 // users regardless of whether a value changed.
1201 settings = user_settings;
1204 // Create settings for all non-null setting values for new patrons.
1205 angular.forEach(user_settings, function(val, key) {
1206 if (val !== null) settings[key] = val;
1210 if (Object.keys(settings).length == 0) return $q.when();
1212 return egCore.net.request(
1214 'open-ils.actor.patron.settings.update',
1215 egCore.auth.token(), new_user.id(), settings
1216 ).then(function(resp) {
1221 // Applies field-specific validation regex's from org settings
1222 // to form fields. Be careful not remove any pattern data we
1223 // are not explicitly over-writing in the provided patterns obj.
1224 service.set_field_patterns = function(patterns) {
1225 if (service.org_settings['opac.username_regex']) {
1226 patterns.au.usrname =
1227 new RegExp(service.org_settings['opac.username_regex']);
1230 if (service.org_settings['ui.patron.edit.ac.barcode.regex']) {
1231 patterns.ac.barcode =
1232 new RegExp(service.org_settings['ui.patron.edit.ac.barcode.regex']);
1235 if (service.org_settings['global.password_regex']) {
1236 patterns.au.passwd =
1237 new RegExp(service.org_settings['global.password_regex']);
1240 var phone_reg = service.org_settings['ui.patron.edit.phone.regex'];
1242 // apply generic phone regex first, replace below as needed.
1243 patterns.au.day_phone = new RegExp(phone_reg);
1244 patterns.au.evening_phone = new RegExp(phone_reg);
1245 patterns.au.other_phone = new RegExp(phone_reg);
1248 // the remaining patterns fit a well-known key name pattern
1250 angular.forEach(service.org_settings, function(val, key) {
1252 var parts = key.match(/ui.patron.edit\.(\w+)\.(\w+)\.regex/);
1255 var name = parts[2];
1256 patterns[cls][name] = new RegExp(val);
1263 .controller('PatronRegCtrl',
1264 ['$scope','$routeParams','$q','$uibModal','$window','egCore',
1265 'patronSvc','patronRegSvc','egUnloadPrompt','egAlertDialog',
1266 'egWorkLog', '$timeout','ngToast',
1267 function($scope , $routeParams , $q , $uibModal , $window , egCore ,
1268 patronSvc , patronRegSvc , egUnloadPrompt, egAlertDialog ,
1269 egWorkLog, $timeout, ngToast) {
1271 $scope.page_data_loaded = false;
1272 $scope.hold_notify_type = { phone : null, email : null, sms : null };
1273 $scope.hold_notify_observer = {};
1274 $scope.hold_rel_contacts = {};
1275 $scope.clone_id = patronRegSvc.clone_id = $routeParams.clone_id;
1276 $scope.stage_username =
1277 patronRegSvc.stage_username = $routeParams.stage_username;
1279 patronRegSvc.patron_id = $routeParams.edit_id || $routeParams.id;
1281 // for existing patrons, disable barcode input by default
1282 $scope.disable_bc = $scope.focus_usrname = Boolean($scope.patron_id);
1283 $scope.focus_bc = !Boolean($scope.patron_id);
1284 $scope.address_alerts = [];
1285 $scope.dupe_counts = {};
1287 // map of perm name to true/false for perms the logged in user
1288 // has at the currently selected patron home org unit.
1291 $scope.name_tab = 'primary';
1293 if (!$scope.edit_passthru) {
1294 // in edit more, scope.edit_passthru is delivered to us by
1295 // the enclosing controller. In register mode, there is
1296 // no enclosing controller, so we create our own.
1297 $scope.edit_passthru = {};
1300 // 0=all, 1=suggested, 2=all
1301 $scope.edit_passthru.vis_level = 0;
1303 // Apply default values for new patrons during initial registration
1304 // prs is shorthand for patronSvc
1305 function set_new_patron_defaults(prs) {
1306 if (!$scope.patron.passwd) {
1307 // passsword may originate from staged user.
1308 if ($scope.patron.day_phone &&
1309 $scope.org_settings['patron.password.use_phone']) {
1310 $scope.patron.passwd = $scope.patron.day_phone.substr(-4);
1312 $scope.generate_password();
1316 var notify = 'phone:email'; // hard-coded default when opac.hold_notify has no reg_default
1317 var notify_stype = $scope.user_setting_types['opac.hold_notify'];
1318 if (notify_stype && notify_stype.reg_default() !== undefined && notify_stype.reg_default() !== null) {
1319 console.log('using default opac.hold_notify');
1320 notify = notify_stype.reg_default();
1322 $scope.hold_notify_type.phone = Boolean(notify.match(/phone/));
1323 $scope.hold_notify_type.email = Boolean(notify.match(/email/));
1324 $scope.hold_notify_type.sms = Boolean(notify.match(/sms/));
1326 // staged users may be loaded w/ a profile.
1327 $scope.set_expire_date();
1329 if (prs.org_settings['ui.patron.default_ident_type']) {
1330 // $scope.patron needs this field to be an object
1331 var id = prs.org_settings['ui.patron.default_ident_type'];
1332 var ident_type = $scope.ident_types.filter(
1333 function(type) { return type.id() == id })[0];
1334 $scope.patron.ident_type = ident_type;
1336 if (prs.org_settings['ui.patron.default_inet_access_level']) {
1337 // $scope.patron needs this field to be an object
1338 var id = prs.org_settings['ui.patron.default_inet_access_level'];
1339 var level = $scope.net_access_levels.filter(
1340 function(lvl) { return lvl.id() == id })[0];
1341 $scope.patron.net_access_level = level;
1343 if (prs.org_settings['ui.patron.default_country']) {
1344 $scope.patron.addresses[0].country =
1345 prs.org_settings['ui.patron.default_country'];
1349 // A null or undefined pattern leads to exceptions. Before the
1350 // patterns are loaded from the server, default all patterns
1351 // to an innocuous regex. To avoid re-creating numerous
1352 // RegExp objects, cache the stub RegExp after initial creation.
1353 // note: angular docs say ng-pattern accepts a regexp or string,
1354 // but as of writing, it only works with a regexp object.
1355 // (Likely an angular 1.2 vs. 1.4 issue).
1356 var field_patterns = {au : {}, ac : {}, aua : {}};
1357 $scope.field_pattern = function(cls, field) {
1358 if (!field_patterns[cls][field])
1359 field_patterns[cls][field] = new RegExp('.*');
1360 return field_patterns[cls][field];
1363 // Main page load function. Kicks off tab init and data loading.
1366 $scope.initTab ? // initTab comes from patron app
1367 $scope.initTab('edit', $routeParams.id) : $q.when(),
1369 patronRegSvc.init(),
1371 ]).then(function(){ return patronRegSvc.init_patron(patronSvc ? patronSvc.current : patronRegSvc.patron ) })
1372 .then(function(patron) {
1373 // called after initTab and patronRegSvc.init have completed
1374 // in standalone mode, we have no patronSvc
1375 var prs = patronRegSvc;
1376 $scope.patron = patron;
1377 $scope.base_email = patron.email;
1378 $scope.base_default_sms = prs.user_settings['opac.default_sms_notify']
1379 $scope.field_doc = prs.field_doc;
1380 $scope.edit_profiles = prs.edit_profiles;
1381 $scope.edit_profile_entries = prs.edit_profile_entries;
1382 $scope.ident_types = prs.ident_types;
1383 $scope.net_access_levels = prs.net_access_levels;
1384 $scope.user_setting_types = prs.user_setting_types;
1385 $scope.opt_in_setting_types = prs.opt_in_setting_types;
1386 $scope.org_settings = prs.org_settings;
1387 $scope.sms_carriers = prs.sms_carriers;
1388 $scope.stat_cats = prs.stat_cats;
1389 $scope.surveys = prs.surveys;
1390 $scope.survey_responses = prs.survey_responses;
1391 $scope.stat_cat_entry_maps = prs.stat_cat_entry_maps;
1392 $scope.stage_user = prs.stage_user;
1393 $scope.stage_user_requestor = prs.stage_user_requestor;
1395 $scope.user_settings = prs.user_settings;
1396 prs.user_settings = {};
1398 // If a default pickup lib is applied to the patron, apply it
1399 // to the UI at page load time. Otherwise, leave the value unset.
1400 if ($scope.user_settings['opac.default_pickup_location']) {
1401 $scope.patron._pickup_lib = egCore.org.get(
1402 $scope.user_settings['opac.default_pickup_location']);
1405 extract_hold_notify();
1407 if ($scope.patron.isnew)
1408 set_new_patron_defaults(prs);
1410 $scope.handle_home_org_changed();
1412 if ($scope.org_settings['ui.patron.edit.default_suggested'])
1413 $scope.edit_passthru.vis_level = 1;
1415 // Stat cats are fetched from open-ils.storage, where 't'==1
1416 $scope.hasRequiredStatCat = prs.stat_cats.filter(
1417 function(cat) {return cat.required() == 1} ).length > 0;
1419 $scope.page_data_loaded = true;
1421 prs.set_field_patterns(field_patterns);
1422 apply_username_regex();
1424 add_date_watchers();
1426 if ($scope.org_settings['ui.patron.edit.guardian_required_for_juv']) {
1431 function add_date_watchers() {
1433 $scope.$watch('patron.dob', function(newVal, oldVal) {
1434 // Even though this runs after page data load, there
1435 // are still times when it fires unnecessarily.
1436 if (newVal === oldVal) return;
1438 console.debug('dob change: ' + newVal + ' : ' + oldVal);
1439 maintain_juvenile_flag();
1442 // No need to watch expire_date
1445 function add_juv_watcher() {
1446 $scope.$watch('patron.juvenile', function(newVal, oldVal) {
1447 if (newVal === oldVal) return;
1449 field_visibility['au.guardian'] = 3; // required
1451 // Value will be reassessed by show_field()
1452 delete field_visibility['au.guardian'];
1457 // add watchers for hold notify method prefs
1458 $scope.$watch('hold_notify_type.phone', function(newVal, oldVal) {
1459 var notifyOpt = $scope.hold_notify_observer['phone'];
1460 if (newVal !== null) {
1461 notifyOpt.newval = newVal;
1465 $scope.$watch('hold_notify_type.sms', function(newVal, oldVal) {
1466 var notifyOpt = $scope.hold_notify_observer['sms'];
1467 if (newVal !== null) {
1468 notifyOpt.newval = newVal;
1472 $scope.$watch('hold_notify_type.email', function(newVal, oldVal) {
1473 var notifyOpt = $scope.hold_notify_observer['email'];
1474 if (newVal !== null) {
1475 notifyOpt.newval = newVal;
1479 // update the currently displayed field documentation
1480 $scope.set_selected_field_doc = function(cls, field) {
1481 $scope.selected_field_doc = $scope.field_doc[cls][field];
1484 // returns the tree depth of the selected profile group tree node.
1485 $scope.pgt_depth = function(grp) {
1487 while (grp = egCore.env.pgt.map[grp.parent()]) d++;
1491 // returns the tree depth of the selected profile group tree node.
1492 $scope.pgtde_depth = function(entry) {
1494 while (entry = egCore.env.pgtde.map[entry.parent()]) d++;
1498 // IDL fields used for labels in the UI.
1499 $scope.idl_fields = {
1500 au : egCore.idl.classes.au.field_map,
1501 ac : egCore.idl.classes.ac.field_map,
1502 aua : egCore.idl.classes.aua.field_map
1505 // field visibility cache. Some fields are universally required.
1506 // 3 == value universally required
1507 // 2 == field is visible by default
1508 // 1 == field is suggested by default
1509 var field_visibility = {};
1510 var default_field_visibility = {
1514 'au.first_given_name' : 3,
1515 'au.family_name' : 3,
1516 'au.pref_first_given_name' : 2,
1517 'au.pref_family_name' : 2,
1518 'au.ident_type' : 3,
1519 'au.ident_type2' : 2,
1522 'au.expire_date' : 3,
1523 'au.net_access_level' : 3,
1524 'aua.address_type' : 3,
1525 'aua.post_code' : 3,
1533 'aua.within_city_limits' : 2,
1536 'au.name_keywords': 1
1539 // Returns true if the selected field should be visible
1540 // given the current required/suggested/all setting.
1541 // The visibility flag applied to each field as a result of calling
1542 // this function also sets (via the same flag) the requiredness state.
1543 $scope.show_field = function(field_key) {
1544 // org settings have not been received yet.
1545 if (!$scope.org_settings) return false;
1547 if (field_visibility[field_key] == undefined) {
1548 // compile and cache the visibility for the selected field
1550 // The preferred name fields use the primary name field settings
1551 var org_key = field_key;
1552 var alt_name = false;
1553 if (field_key.match(/^au.alt_/)) {
1555 org_key = field_key.slice(7);
1558 var req_set = 'ui.patron.edit.' + org_key + '.require';
1559 var sho_set = 'ui.patron.edit.' + org_key + '.show';
1560 var sug_set = 'ui.patron.edit.' + org_key + '.suggest';
1562 if ($scope.org_settings[req_set]) {
1564 // Avoid requiring alt name fields when primary
1565 // name fields are required.
1566 field_visibility[field_key] = 2;
1568 field_visibility[field_key] = 3;
1571 } else if ($scope.org_settings[sho_set]) {
1572 field_visibility[field_key] = 2;
1574 } else if ($scope.org_settings[sug_set]) {
1575 field_visibility[field_key] = 1;
1579 if (field_visibility[field_key] == undefined) {
1580 // No org settings were applied above. Use the default
1581 // settings if present or assume the field has no
1582 // visibility flags applied.
1583 field_visibility[field_key] =
1584 default_field_visibility[field_key] || 0;
1587 return field_visibility[field_key] >= $scope.edit_passthru.vis_level;
1590 // See $scope.show_field().
1591 // A field with visbility level 3 means it's required.
1592 $scope.field_required = function(cls, field) {
1594 // Value in the password field is not required
1595 // for existing patrons.
1596 if (field == 'passwd' && $scope.patron && !$scope.patron.isnew)
1599 return (field_visibility[cls + '.' + field] == 3);
1602 // generates a random 4-digit password
1603 $scope.generate_password = function() {
1604 $scope.patron.passwd = Math.floor(Math.random()*9000) + 1000;
1607 $scope.set_expire_date = function() {
1608 if (!$scope.patron.profile) return;
1609 var seconds = egCore.date.intervalToSeconds(
1610 $scope.patron.profile.perm_interval());
1611 var now_epoch = new Date().getTime();
1612 $scope.patron.expire_date = new Date(
1613 now_epoch + (seconds * 1000 /* milliseconds */))
1614 $scope.field_modified();
1617 // grp is the pgt object
1618 $scope.set_profile = function(grp) {
1619 // If we can't save because of group perms or create/update perms
1620 if ($scope.edit_passthru.hide_save_actions()) return;
1621 $scope.patron.profile = grp;
1622 $scope.set_expire_date();
1623 $scope.field_modified();
1626 $scope.invalid_profile = function() {
1629 $scope.patron.profile &&
1630 $scope.patron.profile.usergroup() == 't'
1634 $scope.new_address = function() {
1635 var addr = egCore.idl.toHash(new egCore.idl.aua());
1636 patronRegSvc.ingest_address($scope.patron, addr);
1637 addr.id = patronRegSvc.virt_id--;
1640 addr.within_city_limits = true;
1641 addr.country = $scope.org_settings['ui.patron.default_country'];
1642 $scope.patron.addresses.push(addr);
1645 // keep deleted addresses out of the patron object so
1646 // they won't appear in the UI. They'll be re-inserted
1647 // when the patron is updated.
1648 deleted_addresses = [];
1649 $scope.delete_address = function(id) {
1651 if ($scope.patron.isnew &&
1652 $scope.patron.addresses.length == 1 &&
1653 $scope.org_settings['ui.patron.registration.require_address']) {
1654 egAlertDialog.open(egCore.strings.REG_ADDR_REQUIRED);
1659 angular.forEach($scope.patron.addresses, function(addr) {
1660 if (addr.id == id) {
1662 addr.isdeleted = true;
1663 deleted_addresses.push(addr);
1666 addresses.push(addr);
1669 $scope.patron.addresses = addresses;
1672 $scope.approve_pending_address = function(addr) {
1676 'open-ils.actor.user.pending_address.approve',
1677 egCore.auth.token(), addr.id
1678 ).then(function(replaced_id) {
1679 var evt = egCore.evt.parse(replaced_id);
1680 if (evt) { alert(evt); return; }
1682 // Remove the pending address and the replaced address
1683 // from the local list of patron addresses.
1685 angular.forEach($scope.patron.addresses, function(a) {
1686 if (a.id != addr.id && a.id != replaced_id) {
1690 $scope.patron.addresses = addresses;
1692 // Fetch a fresh copy of the modified address from the server.
1693 // and add it back to the list.
1694 egCore.pcrud.retrieve('aua', replaced_id, {}, {authoritative: true})
1695 .then(null, null, function(new_addr) {
1696 new_addr = egCore.idl.toHash(new_addr);
1697 patronRegSvc.ingest_address($scope.patron, new_addr);
1698 $scope.patron.addresses.push(new_addr);
1703 $scope.post_code_changed = function(addr) {
1705 'open-ils.search', 'open-ils.search.zip', addr.post_code)
1706 .then(function(resp) {
1708 if (resp.city) addr.city = resp.city;
1709 if (resp.state) addr.state = resp.state;
1710 if (resp.county) addr.county = resp.county;
1711 if (resp.alert) alert(resp.alert);
1715 $scope.new_waiver_entry = function() {
1716 var waiver = egCore.idl.toHash(new egCore.idl.aupw());
1717 patronRegSvc.ingest_waiver_entry($scope.patron, waiver);
1718 waiver.id = patronRegSvc.virt_id--;
1719 waiver.isnew = true;
1720 $scope.patron.waiver_entries.push(waiver);
1723 deleted_waiver_entries = [];
1724 $scope.delete_waiver_entry = function(waiver_entry) {
1725 if (waiver_entry.id > 0) {
1726 waiver_entry.isdeleted = true;
1727 deleted_waiver_entries.push(waiver_entry);
1729 var index = $scope.patron.waiver_entries.indexOf(waiver_entry);
1730 $scope.patron.waiver_entries.splice(index, 1);
1733 $scope.replace_card = function() {
1734 $scope.patron.card.active = false;
1735 $scope.patron.card.ischanged = true;
1736 $scope.disable_bc = false;
1738 var new_card = egCore.idl.toHash(new egCore.idl.ac());
1739 new_card.id = patronRegSvc.virt_id--;
1740 new_card.isnew = true;
1741 new_card.active = true;
1742 new_card._primary = 'on';
1743 $scope.patron.card = new_card;
1745 // Remove any previous attempts to replace the card, since they
1746 // may be incomplete or created by accident.
1747 $scope.patron.cards =
1748 $scope.patron.cards.filter(function(c) {return !c.isnew})
1749 $scope.patron.cards.push(new_card);
1752 $scope.day_phone_changed = function(phone) {
1753 if (phone && $scope.patron.isnew &&
1754 $scope.org_settings['patron.password.use_phone']) {
1755 $scope.patron.passwd = phone.substr(-4);
1759 $scope.barcode_changed = function(bc) {
1761 $scope.dupe_barcode = false;
1764 'open-ils.actor.barcode.exists',
1765 egCore.auth.token(), bc
1766 ).then(function(resp) {
1767 if (resp == '1') { // duplicate card
1768 $scope.dupe_barcode = true;
1769 console.log('duplicate barcode detected: ' + bc);
1771 if (!$scope.patron.usrname)
1772 $scope.patron.usrname = bc;
1778 $scope.cards_dialog = function() {
1780 templateUrl: './circ/patron/t_patron_cards_dialog',
1783 ['$scope','$uibModalInstance','cards','perms','patron',
1784 function($scope , $uibModalInstance , cards , perms , patron) {
1785 // scope here is the modal-level scope
1786 $scope.args = {cards : cards, primary_barcode : null};
1787 angular.forEach(cards, function(card) {
1788 if (card.id == patron.card.id) {
1789 $scope.args.primary_barcode = card.id;
1792 $scope.perms = perms;
1793 $scope.ok = function() { $uibModalInstance.close($scope.args) }
1794 $scope.cancel = function () { $uibModalInstance.dismiss() }
1797 cards : function() {
1798 // scope here is the controller-level scope
1799 return $scope.patron.cards;
1801 perms : function() {
1802 return $scope.perms;
1804 patron : function() {
1805 return $scope.patron;
1810 angular.forEach(args.cards, function(card) {
1811 card.ischanged = true; // assume cards need updating, OK?
1812 if (card.id == args.primary_barcode) {
1813 $scope.patron.card = card;
1814 card._primary = true;
1816 card._primary = false;
1823 $scope.set_addr_type = function(addr, type) {
1824 var addrs = $scope.patron.addresses;
1825 if (addr['_is_'+type]) {
1826 angular.forEach(addrs, function(a) {
1827 if (a.id != addr.id) a['_is_'+type] = false;
1830 // unchecking mailing/billing means we have to randomly
1831 // select another address to fill that role. Select the
1832 // first address in the list (that does not match the
1834 for (var i = 0; i < addrs.length; i++) {
1835 if (addrs[i].id != addr.id) {
1836 addrs[i]['_is_' + type] = true;
1844 // Translate hold notify preferences from the form/scope back into a
1845 // single user setting value for opac.hold_notify.
1846 function compress_hold_notify() {
1847 var hold_notify_methods = [];
1848 if ($scope.hold_notify_type.phone) {
1849 hold_notify_methods.push('phone');
1851 if ($scope.hold_notify_type.email) {
1852 hold_notify_methods.push('email');
1854 if ($scope.hold_notify_type.sms) {
1855 hold_notify_methods.push('sms');
1858 $scope.user_settings['opac.hold_notify'] = hold_notify_methods.join(':');
1861 // dialog for selecting additional permission groups
1862 $scope.secondary_groups_dialog = function() {
1864 templateUrl: './circ/patron/t_patron_groups_dialog',
1867 ['$scope','$uibModalInstance','linked_groups','pgt_depth',
1868 function($scope , $uibModalInstance , linked_groups , pgt_depth) {
1870 $scope.pgt_depth = pgt_depth;
1872 linked_groups : linked_groups,
1873 edit_profiles : patronRegSvc.edit_profiles,
1874 new_profile : patronRegSvc.edit_profiles[0]
1877 // add a new group to the linked groups list
1878 $scope.link_group = function($event, grp) {
1879 var found = false; // avoid duplicates
1880 angular.forEach($scope.args.linked_groups,
1881 function(g) {if (g.id() == grp.id()) found = true});
1882 if (!found) $scope.args.linked_groups.push(grp);
1883 $event.preventDefault(); // avoid close
1886 // remove a group from the linked groups list
1887 $scope.unlink_group = function($event, grp) {
1888 $scope.args.linked_groups =
1889 $scope.args.linked_groups.filter(function(g) {
1890 return g.id() != grp.id()
1892 $event.preventDefault(); // avoid close
1895 $scope.ok = function() { $uibModalInstance.close($scope.args) }
1896 $scope.cancel = function () { $uibModalInstance.dismiss() }
1899 linked_groups : function() { return $scope.patron.groups },
1900 pgt_depth : function() { return $scope.pgt_depth }
1905 if ($scope.patron.isnew) {
1906 // groups must be linked for new patrons after the
1907 // patron is created.
1908 $scope.patron.groups = args.linked_groups;
1912 // update links groups for existing users in real time.
1913 var ids = args.linked_groups.map(function(g) {return g.id()});
1914 patronRegSvc.apply_secondary_groups($scope.patron.id, ids)
1915 .then(function(success) {
1917 $scope.patron.groups = args.linked_groups;
1923 function extract_hold_notify() {
1924 var p = $scope.patron;
1926 // get the user's opac.hold_notify setting
1927 var notify = $scope.user_settings['opac.hold_notify'];
1929 // if it's not set, use the default opac.hold_notify value
1930 if (!notify && !(notify === '')) {
1931 var notify_stype = $scope.user_setting_types['opac.hold_notify'];
1932 if (notify_stype && notify_stype.reg_default() !== undefined && notify_stype.reg_default() !== null) {
1933 notify = notify_stype.reg_default();
1935 // no setting and no default: set phone and email to true
1936 notify = 'phone:email';
1940 $scope.hold_notify_type.phone = Boolean(notify.match(/phone/));
1941 $scope.hold_notify_type.email = Boolean(notify.match(/email/));
1942 $scope.hold_notify_type.sms = Boolean(notify.match(/sms/));
1944 // stores original loaded values for comparison later
1945 for (var k in $scope.hold_notify_type){
1946 var val = $scope.hold_notify_type[k];
1948 if ($scope.hold_notify_type.hasOwnProperty(k)){
1949 $scope.hold_notify_observer[k] = {old : val, newval: null};
1953 // actual value from user
1954 $scope.hold_rel_contacts.day_phone = { old: p.day_phone, newval : null };
1955 $scope.hold_rel_contacts.other_phone = { old: p.other_phone, newval : null };
1956 $scope.hold_rel_contacts.evening_phone = { old: p.evening_phone, newval : null };
1957 // from user_settings
1958 $scope.hold_rel_contacts.default_phone = { old: $scope.user_settings['opac.default_phone'], newval : null };
1959 $scope.hold_rel_contacts.default_sms = { old: $scope.user_settings['opac.default_sms_notify'], newval : null };
1960 $scope.hold_rel_contacts.default_sms_carrier_id = { old: $scope.user_settings['opac.default_sms_carrier'], newval : null };
1964 function normalizePhone(number){
1965 // normalize phone # for comparison, only digits
1966 if (number == null || number == undefined) return '';
1968 var regex = /[^\d]/g;
1969 return number.replace(regex, '');
1972 $scope.invalidate_field = function(field) {
1973 patronRegSvc.invalidate_field($scope.patron, field).then(function() {
1974 $scope.handle_field_changed($scope.patron, field);
1978 $scope.send_test_email = function() {
1979 patronRegSvc.send_test_message($scope.patron.id, 'au.email.test').then(function(res) {
1980 if (res && res.template_output() && res.template_output().is_error() == 'f') {
1981 ngToast.success(egCore.strings.TEST_NOTIFY_SUCCESS);
1983 ngToast.warning(egCore.strings.TEST_NOTIFY_FAIL);
1984 if (res) console.log(res);
1989 $scope.send_test_sms = function() {
1990 patronRegSvc.send_test_message($scope.patron.id, 'au.sms_text.test').then(function(res) {
1991 if (res && res.template_output() && res.template_output().is_error() == 'f') {
1992 ngToast.success(egCore.strings.TEST_NOTIFY_SUCCESS);
1994 ngToast.warning(egCore.strings.TEST_NOTIFY_FAIL);
1995 if (res) console.log(res);
2000 address_alert = function(addr) {
2002 street1: addr.street1,
2003 street2: addr.street2,
2006 county: addr.county,
2007 country: addr.country,
2008 post_code: addr.post_code,
2009 mailing_address: addr._is_mailing,
2010 billing_address: addr._is_billing
2015 'open-ils.actor.address_alert.test',
2016 egCore.auth.token(), egCore.auth.user().ws_ou(), args
2017 ).then(function(res) {
2018 $scope.address_alerts = res;
2022 $scope.dupe_value_changed = function(type, value) {
2023 if (!$scope.dupe_search_encoded)
2024 $scope.dupe_search_encoded = {};
2026 $scope.dupe_counts[type] = 0;
2028 patronRegSvc.dupe_patron_search($scope.patron, type, value)
2029 .then(function(res) {
2030 $scope.dupe_counts[type] = res.count;
2032 $scope.dupe_search_encoded[type] =
2033 encodeURIComponent(js2JSON(res.search));
2035 $scope.dupe_search_encoded[type] = '';
2040 $scope.handle_home_org_changed = function() {
2041 org_id = $scope.patron.home_ou.id();
2042 patronRegSvc.has_perms_for_org(org_id).then(function(map) {
2043 angular.forEach(map, function(v, k) { $scope.perms[k] = v });
2047 $scope.handle_pulib_changed = function(org) {
2048 if (!$scope.user_settings) return; // still rendering
2049 $scope.user_settings['opac.default_pickup_location'] = org.id();
2052 // This is called with every character typed in a form field,
2053 // since that's the only way to gaurantee something has changed.
2054 // See handle_field_changed for ng-change vs. ng-blur.
2055 $scope.field_modified = function() {
2056 // Call attach with every field change, regardless of whether
2057 // it's been called before. This will allow for re-attach after
2058 // the user clicks through the unload warning. egUnloadPrompt
2059 // will ensure we only attach once.
2060 egUnloadPrompt.attach($scope);
2063 // also monitor when form is changed *by the user*, as using
2064 // an ng-change handler doesn't work with eg-date-input
2065 $scope.$watch('reg_form.$pristine', function(newVal, oldVal) {
2066 if (!newVal) egUnloadPrompt.attach($scope);
2069 // username regex (if present) must be removed any time
2070 // the username matches the barcode to avoid firing the
2071 // invalid field handlers.
2072 function apply_username_regex() {
2073 var regex = $scope.org_settings['opac.username_regex'];
2075 if ($scope.patron.card.barcode) {
2076 // username must match the regex or the barcode
2077 field_patterns.au.usrname =
2079 regex + '|^' + $scope.patron.card.barcode + '$');
2081 // username must match the regex
2082 field_patterns.au.usrname = new RegExp(regex);
2085 // username can be any format.
2086 field_patterns.au.usrname = new RegExp('.*');
2090 // obj could be the patron, an address, etc.
2091 // This is called any time a form field achieves then loses focus.
2092 // It does not necessarily mean the field has changed.
2093 // The alternative is ng-change, but it's called with each character
2094 // typed, which would be overkill for many of the actions called here.
2095 $scope.handle_field_changed = function(obj, field_name) {
2096 var cls = obj.classname; // set by egIdl
2097 var value = obj[field_name];
2099 console.debug('changing field ' + field_name + ' to ' + value);
2101 switch (field_name) {
2103 if (normalizePhone(value) !== normalizePhone($scope.hold_rel_contacts.day_phone.old)){
2104 $scope.hold_rel_contacts.day_phone.newval = value;
2106 if ($scope.patron.day_phone &&
2107 $scope.patron.isnew &&
2108 $scope.org_settings['patron.password.use_phone']) {
2109 $scope.patron.passwd = $scope.patron.day_phone.substr(-4);
2111 $scope.dupe_value_changed(field_name, value);
2113 case 'evening_phone' :
2114 if (normalizePhone(value) !== normalizePhone($scope.hold_rel_contacts.evening_phone.old)){
2115 $scope.hold_rel_contacts.evening_phone.newval = value;
2117 $scope.dupe_value_changed(field_name, value);
2119 case 'other_phone' :
2120 if (normalizePhone(value) !== normalizePhone($scope.hold_rel_contacts.other_phone.old)){
2121 $scope.hold_rel_contacts.other_phone.newval = value;
2123 $scope.dupe_value_changed(field_name, value);
2126 case 'ident_value2':
2127 $scope.dupe_value_changed('ident', value);
2130 case 'first_given_name':
2132 $scope.dupe_value_changed('name', value);
2136 $scope.dupe_value_changed('email', value);
2142 // dupe search on address wants the address object as the value.
2143 $scope.dupe_value_changed('address', obj);
2148 $scope.post_code_changed(obj);
2152 patronRegSvc.check_dupe_username(value)
2153 .then(function(yes) {$scope.dupe_username = Boolean(yes)});
2157 // TODO: finish barcode_changed handler.
2158 $scope.barcode_changed(value);
2159 apply_username_regex();
2161 case 'opac.default_phone':
2162 if (normalizePhone(value) !== normalizePhone($scope.hold_rel_contacts.default_phone.old)){
2163 $scope.hold_rel_contacts.default_phone.newval = value;
2166 case 'opac.default_sms_notify':
2167 if (normalizePhone(value) !== normalizePhone($scope.hold_rel_contacts.default_sms.old)){
2168 $scope.hold_rel_contacts.default_sms.newval = value;
2171 case 'opac.default_sms_carrier':
2172 if (value !== $scope.hold_rel_contacts.default_sms_carrier_id.old){
2173 $scope.hold_rel_contacts.default_sms_carrier_id.newval = value;
2179 // patron.juvenile is set to true if the user was born after
2180 function maintain_juvenile_flag() {
2181 if ( !($scope.patron && $scope.patron.dob) ) return;
2184 $scope.org_settings['global.juvenile_age_threshold']
2187 var base = new Date();
2189 base.setTime(base.getTime() -
2190 Number(egCore.date.intervalToSeconds(juv_interval) + '000'));
2192 $scope.patron.juvenile = ($scope.patron.dob > base);
2195 // returns true (disable) for orgs that cannot have users.
2196 $scope.disable_home_org = function(org_id) {
2197 if (!org_id) return;
2198 var org = egCore.org.get(org_id);
2202 org.ou_type().can_have_users() == 'f'
2206 // returns true (disable) for orgs that cannot have vols (for holds pickup)
2207 $scope.disable_pulib = function(org_id) {
2208 if (!org_id) return;
2209 return !egCore.org.CanHaveVolumes(org_id);
2212 // Returns true if attempting to edit self, but perms don't allow
2213 $scope.edit_passthru.self_edit_disallowed = function() {
2214 if ($scope.patron.id
2215 && $scope.patron.id == egCore.auth.user().id()
2216 && !$scope.perms.EDIT_SELF_IN_CLIENT
2221 // Returns true if attempting to edit a user without appropriate group application perms
2222 $scope.edit_passthru.group_edit_disallowed = function() {
2223 if ( $scope.patron.profile
2226 .filter(function(p) {
2227 return $scope.patron.profile.id() == p.id();
2233 // Returns true if the Save and Save & Clone buttons should be disabled.
2234 $scope.edit_passthru.hide_save_actions = function() {
2235 if ($scope.edit_passthru.self_edit_disallowed()) return true;
2236 if ($scope.edit_passthru.group_edit_disallowed()) return true;
2238 return $scope.patron.isnew ?
2239 !$scope.perms.CREATE_USER :
2240 !$scope.perms.UPDATE_USER;
2243 // Returns true if any input elements are tagged as invalid
2244 // via Angular patterns or required attributes.
2245 function form_has_invalid_fields() {
2246 return $('#patron-reg-container .ng-invalid').length > 0;
2249 function form_is_incomplete() {
2251 $scope.dupe_username ||
2252 $scope.dupe_barcode ||
2253 form_has_invalid_fields()
2258 $scope.edit_passthru.save = function(save_args) {
2259 if (!save_args) save_args = {};
2261 if (form_is_incomplete()) {
2262 // User has not provided valid values for all required fields.
2263 return egAlertDialog.open(egCore.strings.REG_INVALID_FIELDS);
2266 // remove page unload warning prompt
2267 egUnloadPrompt.clear();
2269 // toss the deleted addresses back into the patron's list of
2270 // addresses so it's included in the update
2271 $scope.patron.addresses =
2272 $scope.patron.addresses.concat(deleted_addresses);
2274 // ditto for waiver entries
2275 $scope.patron.waiver_entries =
2276 $scope.patron.waiver_entries.concat(deleted_waiver_entries);
2278 compress_hold_notify();
2282 patronRegSvc.save_user($scope.patron)
2283 .then(function(new_user) {
2284 if (new_user && new_user.classname) {
2285 updated_user = new_user;
2286 return patronRegSvc.save_user_settings(
2287 new_user, $scope.user_settings);
2289 var evt = egCore.evt.parse(new_user);
2291 if (evt && evt.textcode == 'XACT_COLLISION') {
2292 return egAlertDialog.open(
2293 egCore.strings.PATRON_EDIT_COLLISION).result;
2296 // debug only -- should not get here.
2297 alert('Patron update failed. \n\n' + js2JSON(new_user));
2300 }).then(function() {
2302 // only remove the staged user if the update succeeded.
2304 return patronRegSvc.remove_staged_user();
2308 }).then(function() {
2310 // linked groups for new users must be created after the new
2312 if ($scope.patron.isnew &&
2313 $scope.patron.groups && $scope.patron.groups.length) {
2314 var ids = $scope.patron.groups.map(function(g) {return g.id()});
2315 return patronRegSvc.apply_secondary_groups(updated_user.id(), ids)
2319 }).then(findChangedFieldsAffectedHolds)
2320 .then(function(changed_fields_plus_holds) {
2321 var needModal = changed_fields_plus_holds[0] && changed_fields_plus_holds[0].length > 0;
2323 ? $scope.update_holds_notify_modal(changed_fields_plus_holds[0])
2324 : $q.when(); // nothing changed, continue
2325 }).then(function() {
2329 ? egCore.strings.EG_WORK_LOG_REGISTERED_PATRON
2330 : egCore.strings.EG_WORK_LOG_EDITED_PATRON, {
2331 'action' : $scope.patron.isnew ? 'registered_patron' : 'edited_patron',
2332 'patron_id' : updated_user.id()
2337 // reloading the page means potentially losing some information
2338 // (e.g. last patron search), but is the only way to ensure all
2339 // components are properly updated to reflect the modified patron.
2340 if (updated_user && save_args.clone) {
2341 // open a separate tab for registering a new
2342 // patron from our cloned data.
2343 var url = 'https://'
2344 + $window.location.hostname
2345 + egCore.env.basePath
2346 + '/circ/patron/register/clone/'
2347 + updated_user.id();
2348 $window.open(url, '_blank').focus();
2350 } else if ($window.location.href.indexOf('stage') > -1 ){
2351 // we're here after deleting a self-reg staged user.
2352 // Just close tab, since refresh won't find staged user
2353 $timeout(function(){
2354 if (typeof BroadcastChannel != 'undefined') {
2355 var bChannel = new BroadcastChannel("eg.pending_usr.update");
2356 bChannel.postMessage({
2357 usr: egCore.idl.toHash(updated_user)
2364 // reload the current page
2365 $window.location.href = location.href;
2370 var phone_inputs = ["day_phone", "evening_phone","other_phone", "default_phone"];
2371 var sms_inputs = ["default_sms", "default_sms_carrier_id"];
2372 var method_prefs = ["sms_notify", "phone_notify", "email_notify"];
2373 var groupBy = function(xs, key){
2374 return xs.reduce(function(rv, x){
2375 (rv[x[key]] = rv[x[key]] || []).push(x);
2380 function findChangedFieldsAffectedHolds(){
2382 var changed_hold_fields = [];
2384 var default_phone_changed = false;
2385 var default_sms_carrier_changed = false;
2386 var default_sms_changed = false;
2387 for (var c in $scope.hold_rel_contacts){
2388 var newinput = $scope.hold_rel_contacts[c].newval;
2389 if ($scope.hold_rel_contacts.hasOwnProperty(c)
2390 && newinput !== null // null means user has not provided a value in this session
2391 && newinput != $scope.hold_rel_contacts[c].old){
2392 var changed = $scope.hold_rel_contacts[c];
2394 changed.isChecked = false;
2395 changed_hold_fields.push(changed);
2396 if (c === 'default_phone') default_phone_changed = true;
2397 if (c === 'default_sms_carrier_id') default_sms_carrier_changed = true;
2398 if (c === 'default_sms') default_sms_changed = true;
2402 for (var c in $scope.hold_notify_observer){
2403 var newinput = $scope.hold_notify_observer[c].newval;
2404 if ($scope.hold_notify_observer.hasOwnProperty(c)
2405 && newinput !== null // null means user has not provided a value in this session
2406 && newinput != $scope.hold_notify_observer[c].old){
2407 var changed = $scope.hold_notify_observer[c];
2408 changed.name = c + "_notify";
2409 changed.isChecked = false;
2410 changed_hold_fields.push(changed);
2412 // if we're turning on phone notifications, offer to update to the
2413 // current default number
2414 if (c === 'phone' && $scope.user_settings['opac.default_phone'] && newinput && !default_phone_changed) {
2415 changed_hold_fields.push({
2416 name: 'default_phone',
2418 newval: $scope.user_settings['opac.default_phone'],
2422 // and similarly for SMS
2423 if (c === 'sms' && $scope.user_settings['opac.default_sms_carrier'] && newinput && !default_sms_carrier_changed) {
2424 changed_hold_fields.push({
2425 name: 'default_sms_carrier_id',
2427 newval: $scope.user_settings['opac.default_sms_carrier'],
2431 if (c === 'sms' && $scope.user_settings['opac.default_sms_notify'] && newinput && !default_sms_changed) {
2432 changed_hold_fields.push({
2433 name: 'default_sms',
2435 newval: $scope.user_settings['opac.default_sms_notify'],
2443 angular.forEach(changed_hold_fields, function(c){
2444 promises.push(egCore.net.request('open-ils.circ',
2445 'open-ils.circ.holds.retrieve_by_notify_staff',
2446 egCore.auth.token(),
2448 c.name.includes('notify') || c.name.includes('carrier') ? c.old : c.newval,
2450 .then(function(affected_holds){
2451 if(!affected_holds || affected_holds.length < 1){
2452 // no holds affected - remove change from list
2453 var p = changed_hold_fields.indexOf(c);
2454 changed_hold_fields.splice(p, 1);
2456 c.affects = affected_holds;
2458 //angular.forEach(c.affects, function(h){
2461 if (!c.name.includes("notify")){
2462 if (c.name === "default_sms_carrier_id") {
2463 c.groups = groupBy(c.affects,'sms_carrier');
2465 c.groups = groupBy(c.affects, c.name.includes('_phone') ? 'phone_notify':'sms_notify');
2469 return $q.when(changed_hold_fields);
2474 return $q.all(promises);
2477 $scope.update_holds_notify_modal = function(changed_hold_fields){
2478 // open modal after-save, pre-reload modal to deal with updated hold notification stuff
2479 if ($scope.patron.isnew || changed_hold_fields.length < 1){
2483 return $uibModal.open({
2484 templateUrl: './circ/patron/t_hold_notify_update',
2487 ['$scope','$uibModalInstance','changed_fields','patron','carriers','def_carrier_id','default_phone','default_sms',
2488 function($scope , $uibModalInstance , changed_fields , patron, carriers, def_carrier_id , default_phone , default_sms) {
2489 // local modal scope
2490 $scope.ch_fields = changed_fields;
2491 $scope.focusMe = true;
2492 $scope.ok = function(msg) {
2494 // Need to do this so the page will reload automatically
2495 if (msg == 'no-update') return $uibModalInstance.close();
2497 //var selectedChanges = $scope.changed_fields.filter(function(c) {
2498 // return c.isChecked;
2500 var selectedChanges = [];
2501 angular.forEach($scope.ch_fields, function(f){
2502 if (f.name == 'phone_notify' && f.newval && f.isChecked) {
2503 // convert to default_phone change
2504 f.sel_hids = f.affects.map(function(h){ return h.id});
2505 f.newval = default_phone;
2506 f.name = 'default_phone';
2507 selectedChanges.push(f);
2508 } else if (f.name == 'sms_notify' && f.newval && f.isChecked) {
2509 // convert to default_sms change
2510 f.sel_hids = f.affects.map(function(h){ return h.id});
2511 f.newval = default_sms;
2512 f.name = 'default_sms';
2513 selectedChanges.push(f);
2514 } else if (f.name.includes('notify') || f.name.includes('carrier')){
2516 f.sel_hids = f.affects.map(function(h){ return h.id});
2517 selectedChanges.push(f);
2520 // this is the sms or phone, so look in the groups obj
2522 for (var k in f.groups){
2523 if (f.groups.hasOwnProperty(k)){
2524 var sel_holds = f.groups[k].filter(function(h){
2528 var hids = sel_holds.map(function(h){ return h.id});
2529 f.sel_hids.push.apply(f.sel_hids, hids);
2533 if (f.sel_hids.length > 0) selectedChanges.push(f);
2538 // call method to update holds for each change
2539 var chain = $q.when();
2540 angular.forEach(selectedChanges, function(c){
2541 var carrierId = c.name.includes('default_sms') ? Number(def_carrier_id) : null;
2542 chain = chain.then(function() {
2543 return egCore.net.request('open-ils.circ',
2544 'open-ils.circ.holds.batch_update_holds_by_notify_staff', egCore.auth.token(),
2547 c.old, // TODO: for number changes, old val is effectively moot
2550 carrierId).then(function(okList){ console.log(okList) });
2554 // carry out the updates and close modal
2555 chain.finally(function(){ $uibModalInstance.close() });
2558 $scope.cancel = function () { $uibModalInstance.dismiss() }
2560 $scope.isNumberCh = function(c){
2561 return !(c.name.includes('notify') || c.name.includes('carrier'));
2565 $scope.groupChanged = function(ch_f, grpK){
2566 var holdArr = ch_f.groups[grpK];
2567 if (holdArr && holdArr.length > 0){
2568 angular.forEach(holdArr, function(h){
2569 if (h.isChecked) { h.isChecked = !h.isChecked; $scope.chgCt-- }
2570 else { h.isChecked = true; $scope.chgCt++ }
2575 $scope.nonGrpChanged = function(field_ch){
2576 if (field_ch.isChecked) $scope.chgCt++;
2577 else $scope.chgCt--;
2580 // use this function as a keydown handler on form
2581 // elements that should not submit the form on enter.
2582 $scope.preventSubmit = function($event) {
2583 if ($event.keyCode == 13)
2584 $event.preventDefault();
2587 $scope.prettyCarrier = function(carrierId){
2588 var sms_carrierObj = carriers.find(function(c){ return c.id == carrierId});
2589 return sms_carrierObj.name;
2591 $scope.prettyBool = function(v){
2592 return v ? 'YES' : 'NO';
2596 changed_fields : function(){ return changed_hold_fields },
2597 patron : function(){ return $scope.patron },
2598 def_carrier_id : function(){
2599 var d = $scope.hold_rel_contacts.default_sms_carrier_id;
2600 return d.newval ? d.newval : d.old;
2602 default_phone : function() {
2603 return ($scope.hold_rel_contacts.default_phone.newval) ?
2604 $scope.hold_rel_contacts.default_phone.newval :
2605 $scope.hold_rel_contacts.default_phone.old;
2607 default_sms : function() {
2608 return ($scope.hold_rel_contacts.default_sms.newval) ?
2609 $scope.hold_rel_contacts.default_sms.newval :
2610 $scope.hold_rel_contacts.default_sms.old;
2612 carriers : function(){ return $scope.sms_carriers.map(function(c){ return egCore.idl.toHash(c) }) }
2617 $scope.edit_passthru.print = function() {
2618 var print_data = {patron : $scope.patron}
2620 return egCore.print.print({
2621 context : 'default',
2622 template : 'patron_data',