2 angular.module('egCoreMod')
3 // toss tihs onto egCoreMod since the page app may vary
5 .factory('patronRegSvc', ['$q', '$filter', 'egCore', 'egLovefield', function($q, $filter, egCore, egLovefield) {
8 field_doc : {}, // config.idl_field_doc
9 profiles : [], // permission groups
10 profile_entries : [], // permission gorup display entries
11 edit_profiles : [], // perm groups we can modify
12 edit_profile_entries : [], // perm group display entries we can modify
14 user_settings : {}, // applied user settings
15 user_setting_types : {}, // config.usr_setting_type
16 opt_in_setting_types : {}, // config.usr_setting_type for event-def opt-in
18 survey_questions : {},
20 survey_responses : {}, // survey.responses for loaded patron in progress
22 stat_cat_entry_maps : {}, // cat.id to selected value
23 virt_id : -1, // virtual ID for new objects
25 init_done : false // have we loaded our initialization data?
28 // Launch a series of parallel data retrieval calls.
29 service.init = function(scope) {
31 // These are fetched with every instance of the page.
33 service.get_user_settings(),
34 service.get_clone_user(),
35 service.get_stage_user()
39 if (!service.init_done) {
40 // These are fetched with every instance of the app.
42 service.get_field_doc(),
43 service.get_perm_groups(),
44 service.get_perm_group_entries(),
45 service.get_ident_types(),
46 service.get_locales(),
47 service.get_org_settings(),
48 service.get_stat_cats(),
49 service.get_surveys(),
50 service.get_net_access_levels()
52 service.init_done = true;
54 return $q.all(common_data.concat(page_data));
57 service.get_clone_user = function() {
58 if (!service.clone_id) return $q.when();
59 // we could load egUser and use its get() function, but loading
60 // user.js into the standalone register UI would mean creating a
61 // new module, since egUser is not loaded into egCoreMod. This
63 return egCore.net.request(
65 'open-ils.actor.user.fleshed.retrieve',
66 egCore.auth.token(), service.clone_id,
67 ['billing_address', 'mailing_address'])
68 .then(function(cuser) {
69 if (e = egCore.evt.parse(cuser)) {
72 service.clone_user = cuser;
77 // When editing a user with addresses linked to other users, fetch
78 // the linked user(s) so we can display their names and edit links.
79 service.get_linked_addr_users = function(addrs) {
80 angular.forEach(addrs, function(addr) {
81 if (addr.usr == service.existing_patron.id()) return;
82 egCore.pcrud.retrieve('au', addr.usr)
84 addr._linked_owner_id = usr.id();
85 addr._linked_owner = service.format_name(
87 usr.first_given_name(),
88 usr.second_given_name()
94 service.apply_secondary_groups = function(user_id, group_ids) {
95 return egCore.net.request(
97 'open-ils.actor.user.set_groups',
98 egCore.auth.token(), user_id, group_ids)
99 .then(function(resp) {
103 // debugging -- should be no events
104 alert('linked groups failure ' + egCore.evt.parse(resp));
109 service.get_stage_user = function() {
110 if (!service.stage_username) return $q.when();
112 // fetch the staged user object
113 return egCore.net.request(
115 'open-ils.actor.user.stage.retrieve.by_username',
117 service.stage_username
118 ).then(function(suser) {
119 if (e = egCore.evt.parse(suser)) {
122 service.stage_user = suser;
126 if (!service.stage_user) return;
127 var requestor = service.stage_user.user.requesting_usr();
129 if (!requestor) return;
131 // fetch the requesting user
132 return egCore.net.request(
134 'open-ils.actor.user.retrieve.parts',
137 ['family_name', 'first_given_name', 'second_given_name']
138 ).then(function(parts) {
139 service.stage_user_requestor =
140 service.format_name(parts[0], parts[1], parts[2]);
145 // See note above about not loading egUser.
147 service.format_name = function(last, first, middle) {
148 return last + ', ' + first + (middle ? ' ' + middle : '');
151 service.check_dupe_username = function(usrname) {
153 // empty usernames can't be dupes
154 if (!usrname) return $q.when(false);
156 // avoid dupe check if username matches the originally loaded usrname
157 if (service.existing_patron) {
158 if (usrname == service.existing_patron.usrname())
159 return $q.when(false);
162 return egCore.net.request(
164 'open-ils.actor.username.exists',
165 egCore.auth.token(), usrname);
168 // compare string with email address of loaded user, return true if different
169 service.check_email_different = function(email) {
170 if (service.existing_patron) {
171 if (email != service.existing_patron.email()) {
177 //service.check_grp_app_perm = function(grp_id) {
179 // determine which user groups our user is not allowed to modify
180 service.set_edit_profiles = function() {
181 var all_app_perms = [];
182 var failed_perms = [];
184 // extract the application permissions
185 angular.forEach(service.profiles, function(grp) {
186 if (grp.application_perm())
187 all_app_perms.push(grp.application_perm());
190 // fill in service.edit_profiles by inspecting failed_perms
191 function traverse_grp_tree(grp, failed) {
193 failed_perms.indexOf(grp.application_perm()) > -1;
195 if (!failed) service.edit_profiles.push(grp);
198 service.profiles.filter( // children of grp
199 function(p) { return p.parent() == grp.id() }),
200 function(child) {traverse_grp_tree(child, failed)}
204 return egCore.perm.hasPermAt(all_app_perms, true).then(
205 function(perm_orgs) {
206 angular.forEach(all_app_perms, function(p) {
207 if (perm_orgs[p].length == 0)
208 failed_perms.push(p);
211 traverse_grp_tree(egCore.env.pgt.tree);
216 service.set_edit_profile_entries = function() {
217 var all_app_perms = [];
218 var failed_perms = [];
220 // extract the application permissions
221 angular.forEach(service.profile_entries, function(entry) {
222 if (entry.grp().application_perm())
223 all_app_perms.push(entry.grp().application_perm());
226 // fill in service.edit_profiles by inspecting failed_perms
227 function traverse_grp_tree(entry, failed) {
229 failed_perms.indexOf(entry.grp().application_perm()) > -1;
231 if (!failed) service.edit_profile_entries.push(entry);
234 service.profile_entries.filter( // children of grp
235 function(p) { return p.parent() == entry.id() }),
236 function(child) {traverse_grp_tree(child, failed)}
240 return egCore.perm.hasPermAt(all_app_perms, true).then(
241 function(perm_orgs) {
242 angular.forEach(all_app_perms, function(p) {
243 if (perm_orgs[p].length == 0)
244 failed_perms.push(p);
247 angular.forEach(egCore.env.pgtde.tree, function(tree) {
248 traverse_grp_tree(tree);
254 // resolves to a hash of perm-name => boolean value indicating
255 // wether the user has the permission at org_id.
256 service.has_perms_for_org = function(org_id) {
259 'EDIT_SELF_IN_CLIENT',
262 'CREATE_USER_GROUP_LINK',
263 'UPDATE_PATRON_COLLECTIONS_EXEMPT',
264 'UPDATE_PATRON_CLAIM_RETURN_COUNT',
265 'UPDATE_PATRON_CLAIM_NEVER_CHECKED_OUT_COUNT',
266 'UPDATE_PATRON_ACTIVE_CARD',
267 'UPDATE_PATRON_PRIMARY_CARD'
270 return egCore.perm.hasPermAt(perms_needed, true)
271 .then(function(perm_map) {
273 angular.forEach(perms_needed, function(perm) {
275 Boolean(perm_map[perm].indexOf(org_id) > -1);
282 service.get_surveys = function() {
283 var org_ids = egCore.org.fullPath(egCore.auth.user().ws_ou(), true);
285 return egCore.pcrud.search('asv', {
287 start_date : {'<=' : 'now'},
288 end_date : {'>=' : 'now'}
297 ).then(function(surveys) {
298 surveys = surveys.sort(function(a,b) {
299 return a.name() < b.name() ? -1 : 1 });
300 service.surveys = surveys;
301 angular.forEach(surveys, function(survey) {
302 angular.forEach(survey.questions(), function(question) {
303 service.survey_questions[question.id()] = question;
304 angular.forEach(question.answers(), function(answer) {
305 service.survey_answers[answer.id()] = answer;
310 egLovefield.setListInOfflineCache('asv', service.surveys)
311 egLovefield.setListInOfflineCache('asvq', service.survey_questions)
312 egLovefield.setListInOfflineCache('asva', service.survey_answers)
317 service.get_stat_cats = function() {
318 return egCore.net.request(
320 'open-ils.circ.stat_cat.actor.retrieve.all',
321 egCore.auth.token(), egCore.auth.user().ws_ou()
322 ).then(function(cats) {
323 cats = cats.sort(function(a, b) {
324 return a.name() < b.name() ? -1 : 1});
325 angular.forEach(cats, function(cat) {
327 cat.entries().sort(function(a,b) {
328 return a.value() < b.value() ? -1 : 1
332 service.stat_cats = cats;
333 return egLovefield.setStatCatsCache(cats);
337 service.get_org_settings = function() {
338 return egCore.org.settings([
339 'global.password_regex',
340 'global.juvenile_age_threshold',
341 'patron.password.use_phone',
342 'ui.patron.default_inet_access_level',
343 'ui.patron.default_ident_type',
344 'ui.patron.default_country',
345 'ui.patron.registration.require_address',
346 'circ.holds.behind_desk_pickup_supported',
347 'circ.patron_edit.clone.copy_address',
348 'circ.privacy_waiver',
349 'ui.patron.edit.au.prefix.require',
350 'ui.patron.edit.au.prefix.show',
351 'ui.patron.edit.au.prefix.suggest',
352 'ui.patron.edit.ac.barcode.regex',
353 'ui.patron.edit.au.second_given_name.show',
354 'ui.patron.edit.au.second_given_name.suggest',
355 'ui.patron.edit.au.suffix.show',
356 'ui.patron.edit.au.suffix.suggest',
357 'ui.patron.edit.au.alias.show',
358 'ui.patron.edit.au.alias.suggest',
359 'ui.patron.edit.au.dob.require',
360 'ui.patron.edit.au.dob.show',
361 'ui.patron.edit.au.dob.suggest',
362 'ui.patron.edit.au.dob.calendar',
363 'ui.patron.edit.au.dob.example',
364 'ui.patron.edit.au.juvenile.show',
365 'ui.patron.edit.au.juvenile.suggest',
366 'ui.patron.edit.au.ident_value.show',
367 'ui.patron.edit.au.ident_value.require',
368 'ui.patron.edit.au.ident_value.suggest',
369 'ui.patron.edit.au.ident_value2.show',
370 'ui.patron.edit.au.ident_value2.suggest',
371 'ui.patron.edit.au.photo_url.require',
372 'ui.patron.edit.au.photo_url.show',
373 'ui.patron.edit.au.photo_url.suggest',
374 'ui.patron.edit.au.email.require',
375 'ui.patron.edit.au.email.show',
376 'ui.patron.edit.au.email.suggest',
377 'ui.patron.edit.au.email.regex',
378 'ui.patron.edit.au.email.example',
379 'ui.patron.edit.au.day_phone.require',
380 'ui.patron.edit.au.day_phone.show',
381 'ui.patron.edit.au.day_phone.suggest',
382 'ui.patron.edit.au.day_phone.regex',
383 'ui.patron.edit.au.day_phone.example',
384 'ui.patron.edit.au.evening_phone.require',
385 'ui.patron.edit.au.evening_phone.show',
386 'ui.patron.edit.au.evening_phone.suggest',
387 'ui.patron.edit.au.evening_phone.regex',
388 'ui.patron.edit.au.evening_phone.example',
389 'ui.patron.edit.au.other_phone.require',
390 'ui.patron.edit.au.other_phone.show',
391 'ui.patron.edit.au.other_phone.suggest',
392 'ui.patron.edit.au.other_phone.regex',
393 'ui.patron.edit.au.other_phone.example',
394 'ui.patron.edit.phone.regex',
395 'ui.patron.edit.phone.example',
396 'ui.patron.edit.au.active.show',
397 'ui.patron.edit.au.active.suggest',
398 'ui.patron.edit.au.barred.show',
399 'ui.patron.edit.au.barred.suggest',
400 'ui.patron.edit.au.master_account.show',
401 'ui.patron.edit.au.master_account.suggest',
402 'ui.patron.edit.au.claims_returned_count.show',
403 'ui.patron.edit.au.claims_returned_count.suggest',
404 'ui.patron.edit.au.claims_never_checked_out_count.show',
405 'ui.patron.edit.au.claims_never_checked_out_count.suggest',
406 'ui.patron.edit.aua.post_code.regex',
407 'ui.patron.edit.aua.post_code.example',
408 'ui.patron.edit.aua.county.require',
409 'ui.patron.edit.au.guardian.show',
410 'ui.patron.edit.au.guardian.suggest',
411 'ui.patron.edit.guardian_required_for_juv',
413 'ui.patron.edit.default_suggested',
414 'opac.barcode_regex',
415 'opac.username_regex',
417 'ui.patron.edit.aua.state.require',
418 'ui.patron.edit.aua.state.suggest',
419 'ui.patron.edit.aua.state.show',
420 'ui.admin.work_log.max_entries',
421 'ui.admin.patron_log.max_entries'
422 ]).then(function(settings) {
423 service.org_settings = settings;
424 if (egCore && egCore.env && !egCore.env.aous) {
425 egCore.env.aous = settings;
426 console.log('setting egCore.env.aous');
428 return service.process_org_settings(settings);
432 // some org settings require the retrieval of additional data
433 service.process_org_settings = function(settings) {
435 var promises = [egLovefield.setSettingsCache(settings)];
437 if (settings['sms.enable']) {
438 // fetch SMS carriers
440 egCore.pcrud.search('csc',
443 {'class':'csc', 'field':'name'},
444 {'class':'csc', 'field':'region'}
446 ).then(function(carriers) {
447 service.sms_carriers = carriers;
451 // if other promises are added below, this is not necessary.
452 promises.push($q.when());
455 // other post-org-settings processing goes here,
456 // adding to promises as needed.
458 return $q.all(promises);
461 service.get_ident_types = function() {
462 if (egCore.env.cit) {
463 service.ident_types = egCore.env.cit.list;
466 return egCore.pcrud.retrieveAll('cit', {}, {atomic : true})
467 .then(function(types) {
468 egCore.env.absorbList(types, 'cit')
469 service.ident_types = types
474 service.get_locales = function() {
475 if (egCore.env.i18n_l) {
476 service.locales = egCore.env.i18n_l.list;
479 return egCore.pcrud.retrieveAll('i18n_l', {}, {atomic : true})
480 .then(function(locales) {
481 egCore.env.absorbList(locales, 'i18n_l')
482 service.locales = locales
487 service.get_net_access_levels = function() {
488 if (egCore.env.cnal) {
489 service.net_access_levels = egCore.env.cnal.list;
492 return egCore.pcrud.retrieveAll('cnal', {}, {atomic : true})
493 .then(function(levels) {
494 egCore.env.absorbList(levels, 'cnal')
495 service.net_access_levels = levels
500 service.get_perm_groups = function() {
501 if (egCore.env.pgt) {
502 service.profiles = egCore.env.pgt.list;
503 return service.set_edit_profiles();
505 return egCore.pcrud.search('pgt', {parent : null},
506 {flesh : -1, flesh_fields : {pgt : ['children']}}
509 egCore.env.absorbTree(tree, 'pgt')
510 service.profiles = egCore.env.pgt.list;
511 return service.set_edit_profiles();
517 service.searchPermGroupEntries = function(org) {
518 return egCore.pcrud.search('pgtde', {org: org, parent: null},
519 {flesh: -1, flesh_fields: {pgtde: ['grp', 'children']}}, {atomic: true}
520 ).then(function(treeArray) {
521 if (!treeArray.length && egCore.org.get(org).parent_ou()) {
522 return service.searchPermGroupEntries(egCore.org.get(org).parent_ou());
528 service.get_perm_group_entries = function() {
529 if (egCore.env.pgtde) {
530 service.profile_entries = egCore.env.pgtde.list;
531 return service.set_edit_profile_entries();
533 return service.searchPermGroupEntries(egCore.auth.user().ws_ou()).then(function(treeArray) {
534 function compare(a,b) {
535 if (a.position() > b.position())
537 if (a.position() < b.position())
543 function squash(node) {
544 node.children().sort(compare);
546 angular.forEach(node.children(), squash);
549 angular.forEach(treeArray, squash);
550 var blob = egCore.env.absorbList(list, 'pgtde');
551 blob.tree = treeArray;
553 service.profile_entries = egCore.env.pgtde.list;
554 return service.set_edit_profile_entries();
559 service.get_field_doc = function() {
561 return egCore.pcrud.search('fdoc', {
562 fm_class: ['au', 'ac', 'aua', 'actsc', 'asv', 'asvq', 'asva']})
565 return egLovefield.setListInOfflineCache('fdoc', to_cache)
569 if (!service.field_doc[doc.fm_class()]) {
570 service.field_doc[doc.fm_class()] = {};
572 service.field_doc[doc.fm_class()][doc.field()] = doc;
579 service.get_user_setting_types = function() {
581 // No need to re-fetch the common setting types.
582 if (Object.keys(service.user_setting_types).length)
585 var org_ids = egCore.org.ancestors(egCore.auth.user().ws_ou(), true);
588 'circ.holds_behind_desk',
589 'circ.collections.exempt',
591 'opac.default_phone',
592 'opac.default_pickup_location',
593 'opac.default_sms_carrier',
594 'opac.default_sms_notify'];
596 return egCore.pcrud.search('cust', {
598 {name : static_types}, // common user settings
599 {name : { // opt-in notification user settings
601 select : {atevdef : ['opt_in_setting']},
603 // we only care about opt-in settings for
604 // event_defs our users encounter
605 where : {'+atevdef' : {owner : org_ids}}
609 }, {}, {atomic : true}).then(function(setting_types) {
611 egCore.env.absorbList(setting_types, 'cust'); // why not...
613 angular.forEach(setting_types, function(stype) {
614 service.user_setting_types[stype.name()] = stype;
615 if (static_types.indexOf(stype.name()) == -1) {
616 service.opt_in_setting_types[stype.name()] = stype;
622 service.get_user_settings = function() {
624 return service.get_user_setting_types()
627 var setting_types = Object.values(service.user_setting_types);
629 if (service.patron_id) {
630 // retrieve applied values for the current user
631 // for the setting types we care about.
634 setting_types.map(function(obj) { return obj.name() });
636 return egCore.net.request(
638 'open-ils.actor.patron.settings.retrieve.authoritative',
642 ).then(function(settings) {
643 service.user_settings = settings;
648 // apply default user setting values
649 angular.forEach(setting_types, function(stype, index) {
650 if (stype.reg_default() != undefined) {
651 var val = stype.reg_default();
652 if (stype.datatype() == 'bool') {
653 // A boolean user setting type whose default
654 // value starts with t/T is considered 'true',
656 val = Boolean((val+'').match(/^t/i));
658 service.user_settings[stype.name()] = val;
665 service.invalidate_field = function(patron, field) {
666 console.log('Invalidating patron field ' + field);
668 return egCore.net.request(
670 'open-ils.actor.invalidate.' + field,
671 egCore.auth.token(), patron.id, null, patron.home_ou.id()
673 ).then(function(res) {
674 // clear the invalid value from the form
677 // update last_xact_id so future save operations
678 // on this patron will be allowed
679 patron.last_xact_id = res.payload.last_xact_id[patron.id];
683 service.send_test_message = function(user_id, hook) {
685 return egCore.net.request(
687 'open-ils.actor.event.test_notification',
688 egCore.auth.token(), {hook: hook, target: user_id}
689 ).then(function(res) {
694 service.dupe_patron_search = function(patron, type, value) {
697 console.log('Dupe search called with "'+ type +'" and value '+ value);
699 if (type.match(/phone/)) type = 'phone'; // day_phone, etc.
704 var fname = patron.first_given_name;
705 var lname = patron.family_name;
706 if (!(fname && lname)) return $q.when({count:0});
708 first_given_name : {value : fname, group : 0},
709 family_name : {value : lname, group : 0}
714 search = {email : {value : value, group : 0}};
718 search = {ident : {value : value, group : 2}};
722 search = {phone : {value : value, group : 2}};
727 angular.forEach(['street1', 'street2', 'city', 'post_code'],
730 search[field] = {value : value[field], group: 1};
736 return egCore.net.request(
738 'open-ils.actor.patron.search.advanced',
739 egCore.auth.token(), search, null, null, 1
740 ).then(function(res) {
741 res = res.filter(function(id) {return id != patron.id});
749 service.init_patron = function(current) {
752 return $q.when(service.init_new_patron());
754 service.patron = current;
755 return $q.when(service.init_existing_patron(current));
758 service.ingest_address = function(patron, addr) {
759 addr.valid = addr.valid == 't';
760 addr.within_city_limits = addr.within_city_limits == 't';
761 addr._is_mailing = (patron.mailing_address &&
762 addr.id == patron.mailing_address.id);
763 addr._is_billing = (patron.billing_address &&
764 addr.id == patron.billing_address.id);
765 addr.pending = addr.pending === 't';
768 service.ingest_waiver_entry = function(patron, waiver_entry) {
769 waiver_entry.place_holds = waiver_entry.place_holds == 't';
770 waiver_entry.pickup_holds = waiver_entry.pickup_holds == 't';
771 waiver_entry.view_history = waiver_entry.view_history == 't';
772 waiver_entry.checkout_items = waiver_entry.checkout_items == 't';
776 * Existing patron objects reqire some data munging before insertion
779 * 1. Turn everything into a hash
780 * 2. ... Except certain fields (selectors) whose widgets require objects
781 * 3. Bools must be Boolean, not t/f.
783 service.init_existing_patron = function(current) {
785 service.existing_patron = current;
787 var patron = egCore.idl.toHash(current);
788 patron.home_ou = egCore.org.get(patron.home_ou.id);
789 patron.expire_date = new Date(Date.parse(patron.expire_date));
790 patron.dob = service.parse_dob(patron.dob);
791 patron.profile = current.profile(); // pre-hash version
792 patron.net_access_level = current.net_access_level();
793 patron.ident_type = current.ident_type();
794 patron.ident_type2 = current.ident_type2();
795 patron.locale = current.locale();
796 patron.groups = current.groups(); // pre-hash
799 ['juvenile', 'barred', 'active', 'master_account'],
800 function(field) { patron[field] = patron[field] == 't'; }
803 angular.forEach(patron.cards, function(card) {
804 card.active = card.active == 't';
805 if (card.id == patron.card.id) {
807 card._primary = true;
811 angular.forEach(patron.addresses,
812 function(addr) { service.ingest_address(patron, addr) });
814 // Link replaced address to its pending address.
815 angular.forEach(patron.addresses, function(addr) {
817 addr._replaces = patron.addresses.filter(
818 function(a) {return a.id == addr.replaces})[0];
822 angular.forEach(patron.waiver_entries,
823 function(waiver_entry) { service.ingest_waiver_entry(patron, waiver_entry) });
825 service.get_linked_addr_users(patron.addresses);
827 // Remove stat cat entries that link to out-of-scope stat
828 // cats. With this, we avoid unnecessarily updating (or worse,
829 // modifying) stat cat values that are not ours to modify.
830 patron.stat_cat_entries = patron.stat_cat_entries.filter(
833 // service.stat_cats only contains in-scope stat cats.
834 service.stat_cats.filter(function(cat) {
835 return (cat.id() == map.stat_cat.id) })[0]
840 // toss entries for existing stat cat maps into our living
841 // stat cat entry map, which is modified within the template.
842 service.stat_cat_entry_maps = [];
843 angular.forEach(patron.stat_cat_entries, function(map) {
844 service.stat_cat_entry_maps[map.stat_cat.id] = map.stat_cat_entry;
847 service.patron = patron;
851 service.init_new_patron = function() {
853 id : service.virt_id--,
856 address_type : egCore.strings.REG_ADDR_TYPE,
859 within_city_limits : false,
860 country : service.org_settings['ui.patron.default_country'],
864 id : service.virt_id--,
875 home_ou : egCore.org.get(egCore.auth.user().ws_ou()),
876 net_access_level : service.org_settings['ui.patron.default_inet_access_level'],
877 stat_cat_entries : [],
883 if (service.clone_user)
884 service.copy_clone_data(user);
886 if (service.stage_user)
887 service.copy_stage_data(user);
892 // dob is always YYYY-MM-DD
893 // Dates of birth do not contain timezone info, which can lead to
894 // inconcistent timezone handling, potentially representing
895 // different points in time, depending on the implementation.
896 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
897 // See "Differences in assumed time zone"
898 // TODO: move this into egDate ?
899 service.parse_dob = function(dob) {
900 if (!dob) return null;
901 var parts = dob.split('-');
902 return new Date(parts[0], parts[1] - 1, parts[2])
905 service.copy_stage_data = function(user) {
906 var cuser = service.stage_user;
908 // copy the data into our new user object
910 for (var key in egCore.idl.classes.stgu.field_map) {
911 if (egCore.idl.classes.au.field_map[key] &&
912 !egCore.idl.classes.stgu.field_map[key].virtual) {
913 if (cuser.user[key]() !== null)
914 user[key] = cuser.user[key]();
918 if (user.home_ou) user.home_ou = egCore.org.get(user.home_ou);
919 if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
921 user.ident_type = egCore.env.cit.map[user.ident_type];
922 if (user.ident_type2)
923 user.ident_type2 = egCore.env.cit.map[user.ident_type2];
925 user.locale = egCore.env.i18n_l.map[user.locale];
926 user.dob = service.parse_dob(user.dob);
928 // Clear the usrname if it looks like a UUID
929 if (user.usrname.replace(/-/g,'').match(/[0-9a-f]{32}/))
932 // Don't use stub address if we have one from the staged user.
933 if (cuser.mailing_addresses.length || cuser.billing_addresses.length)
936 // is_mailing=false implies is_billing
937 function addr_from_stage(stage_addr) {
938 if (!stage_addr) return;
939 var cls = stage_addr.classname;
942 id : service.virt_id--,
946 address_type : egCore.strings.REG_ADDR_TYPE,
947 _is_mailing : cls == 'stgma',
948 _is_billing : cls == 'stgba'
951 user.mailing_address = addr;
952 user.addresses.push(addr);
954 for (var key in egCore.idl.classes[cls].field_map) {
955 if (egCore.idl.classes.aua.field_map[key] &&
956 !egCore.idl.classes[cls].field_map[key].virtual) {
957 if (stage_addr[key]() !== null)
958 addr[key] = stage_addr[key]();
963 addr_from_stage(cuser.mailing_addresses[0]);
964 addr_from_stage(cuser.billing_addresses[0]);
966 if (user.addresses.length == 1) {
967 // If there is only one address,
968 // use it as both mailing and billing.
969 var addr = user.addresses[0];
970 addr._is_mailing = addr._is_billing = true;
971 user.mailing_address = user.billing_address = addr;
974 if (cuser.cards.length) {
976 id : service.virt_id--,
977 barcode : cuser.cards[0].barcode(),
983 user.cards.push(user.card);
984 if (user.usrname == '')
985 user.usrname = card.barcode;
988 angular.forEach(cuser.settings, function(setting) {
989 service.user_settings[setting.setting()] = Boolean(setting.value());
993 // copy select values from the cloned user to the new user.
995 service.copy_clone_data = function(user) {
996 var clone_user = service.clone_user;
998 // flesh the home org locally
999 user.home_ou = egCore.org.get(clone_user.home_ou());
1000 if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
1002 if (!clone_user.billing_address() &&
1003 !clone_user.mailing_address())
1004 return; // no addresses to copy or link
1006 // if the cloned user has any addresses, we don't need
1007 // the stub address created in init_new_patron.
1008 user.addresses = [];
1010 var copy_addresses =
1011 service.org_settings['circ.patron_edit.clone.copy_address'];
1013 var clone_fields = [
1020 angular.forEach(clone_fields, function(field) {
1021 user[field] = clone_user[field]();
1024 if (copy_addresses) {
1025 var bill_addr, mail_addr;
1027 // copy the billing and mailing addresses into new addresses
1028 function clone_addr(addr) {
1029 var new_addr = egCore.idl.toHash(addr);
1030 new_addr.id = service.virt_id--;
1031 new_addr.usr = user.id;
1032 new_addr.isnew = true;
1033 new_addr.valid = true;
1034 new_addr.pending = new_addr.pending === 't';
1035 new_addr.within_city_limits = new_addr.within_city_limits == 't';
1036 user.addresses.push(new_addr);
1040 if (bill_addr = clone_user.billing_address()) {
1041 var addr = clone_addr(bill_addr);
1042 addr._is_billing = true;
1043 user.billing_address = addr;
1046 if (mail_addr = clone_user.mailing_address()) {
1048 if (bill_addr && bill_addr.id() == mail_addr.id()) {
1049 user.mailing_address = user.billing_address;
1050 user.mailing_address._is_mailing = true;
1052 var addr = clone_addr(mail_addr);
1053 addr._is_mailing = true;
1054 user.mailing_address = addr;
1058 // if there is no billing addr, use the mailing addr
1059 user.billing_address = user.mailing_address;
1060 user.billing_address._is_billing = true;
1067 // link the billing and mailing addresses
1069 if (addr = clone_user.billing_address()) {
1070 user.billing_address = egCore.idl.toHash(addr);
1071 user.billing_address._is_billing = true;
1072 user.addresses.push(user.billing_address);
1073 user.billing_address._linked_owner_id = clone_user.id();
1074 user.billing_address._linked_owner = service.format_name(
1075 clone_user.family_name(),
1076 clone_user.first_given_name(),
1077 clone_user.second_given_name()
1081 if (addr = clone_user.mailing_address()) {
1082 if (user.billing_address &&
1083 addr.id() == user.billing_address.id) {
1084 // mailing matches billing
1085 user.mailing_address = user.billing_address;
1086 user.mailing_address._is_mailing = true;
1088 user.mailing_address = egCore.idl.toHash(addr);
1089 user.mailing_address._is_mailing = true;
1090 user.addresses.push(user.mailing_address);
1091 user.mailing_address._linked_owner_id = clone_user.id();
1092 user.mailing_address._linked_owner = service.format_name(
1093 clone_user.family_name(),
1094 clone_user.first_given_name(),
1095 clone_user.second_given_name()
1102 // translate the patron back into IDL form
1103 service.save_user = function(phash) {
1105 var patron = egCore.idl.fromHash('au', phash);
1107 patron.home_ou(patron.home_ou().id());
1108 patron.expire_date(patron.expire_date().toISOString());
1109 patron.profile(patron.profile().id());
1111 patron.dob(patron.dob().toISOString().replace(/T.*/,''));
1112 if (patron.ident_type())
1113 patron.ident_type(patron.ident_type().id());
1114 if (patron.locale())
1115 patron.locale(patron.locale().code());
1116 if (patron.net_access_level())
1117 patron.net_access_level(patron.net_access_level().id());
1120 ['juvenile', 'barred', 'active', 'master_account'],
1121 function(field) { patron[field](phash[field] ? 't' : 'f'); }
1124 var card_hashes = patron.cards();
1126 angular.forEach(card_hashes, function(chash) {
1127 var card = egCore.idl.fromHash('ac', chash)
1128 card.usr(patron.id());
1129 card.active(chash.active ? 't' : 'f');
1130 patron.cards().push(card);
1131 if (chash._primary) {
1136 var addr_hashes = patron.addresses();
1137 patron.addresses([]);
1138 angular.forEach(addr_hashes, function(addr_hash) {
1139 if (!addr_hash.isnew && !addr_hash.isdeleted)
1140 addr_hash.ischanged = true;
1141 var addr = egCore.idl.fromHash('aua', addr_hash);
1142 patron.addresses().push(addr);
1143 addr.valid(addr.valid() ? 't' : 'f');
1144 addr.within_city_limits(addr.within_city_limits() ? 't' : 'f');
1145 addr.pending(addr.pending() ? 't' : 'f');
1146 if (addr_hash._is_mailing) patron.mailing_address(addr);
1147 if (addr_hash._is_billing) patron.billing_address(addr);
1150 patron.survey_responses([]);
1151 angular.forEach(service.survey_responses, function(answer) {
1152 var question = service.survey_questions[answer.question()];
1153 var resp = new egCore.idl.asvr();
1155 resp.survey(question.survey());
1156 resp.question(question.id());
1157 resp.answer(answer.id());
1158 resp.usr(patron.id());
1159 resp.answer_date('now');
1160 patron.survey_responses().push(resp);
1163 // re-object-ify the patron stat cat entry maps
1165 angular.forEach(patron.stat_cat_entries(), function(entry) {
1166 var e = egCore.idl.fromHash('actscecm', entry);
1167 e.stat_cat(e.stat_cat().id);
1170 patron.stat_cat_entries(maps);
1172 // service.stat_cat_entry_maps maps stats to values
1173 // patron.stat_cat_entries is an array of stat_cat_entry_usr_map's
1175 service.stat_cat_entry_maps, function(value, cat_id) {
1177 // see if we already have a mapping for this entry
1178 var existing = patron.stat_cat_entries().filter(
1179 function(e) { return e.stat_cat() == cat_id })[0];
1181 if (existing) { // we have a mapping
1182 // if the existing mapping matches the new one,
1183 // there' nothing left to do
1184 if (existing.stat_cat_entry() == value) return;
1186 // mappings differ. delete the old one and create
1188 existing.isdeleted(true);
1191 var newmap = new egCore.idl.actscecm();
1192 newmap.target_usr(patron.id());
1194 newmap.stat_cat(cat_id);
1195 newmap.stat_cat_entry(value);
1196 patron.stat_cat_entries().push(newmap);
1199 var waiver_hashes = patron.waiver_entries();
1200 patron.waiver_entries([]);
1201 angular.forEach(waiver_hashes, function(waiver_hash) {
1202 if (!waiver_hash.isnew && !waiver_hash.isdeleted)
1203 waiver_hash.ischanged = true;
1204 var waiver_entry = egCore.idl.fromHash('aupw', waiver_hash);
1205 patron.waiver_entries().push(waiver_entry);
1208 if (!patron.isnew()) patron.ischanged(true);
1210 // Make sure these are empty, we don't update them this way
1212 patron.usr_activity([]);
1213 patron.standing_penalties([]);
1215 return egCore.net.request(
1217 'open-ils.actor.patron.update',
1218 egCore.auth.token(), patron);
1221 service.remove_staged_user = function() {
1222 if (!service.stage_user) return $q.when();
1223 return egCore.net.request(
1225 'open-ils.actor.user.stage.delete',
1226 egCore.auth.token(),
1227 service.stage_user.user.row_id()
1231 service.save_user_settings = function(new_user, user_settings) {
1234 if (service.patron_id) {
1235 // Update all user editor setting values for existing
1236 // users regardless of whether a value changed.
1237 settings = user_settings;
1240 // Create settings for all non-null setting values for new patrons.
1241 angular.forEach(user_settings, function(val, key) {
1242 if (val !== null) settings[key] = val;
1246 if (Object.keys(settings).length == 0) return $q.when();
1248 return egCore.net.request(
1250 'open-ils.actor.patron.settings.update',
1251 egCore.auth.token(), new_user.id(), settings
1252 ).then(function(resp) {
1257 // Applies field-specific validation regex's from org settings
1258 // to form fields. Be careful not remove any pattern data we
1259 // are not explicitly over-writing in the provided patterns obj.
1260 service.set_field_patterns = function(patterns) {
1261 if (service.org_settings['opac.username_regex']) {
1262 patterns.au.usrname =
1263 new RegExp(service.org_settings['opac.username_regex']);
1266 if (service.org_settings['ui.patron.edit.ac.barcode.regex']) {
1267 patterns.ac.barcode =
1268 new RegExp(service.org_settings['ui.patron.edit.ac.barcode.regex']);
1271 if (service.org_settings['global.password_regex']) {
1272 patterns.au.passwd =
1273 new RegExp(service.org_settings['global.password_regex']);
1276 var phone_reg = service.org_settings['ui.patron.edit.phone.regex'];
1278 // apply generic phone regex first, replace below as needed.
1279 patterns.au.day_phone = new RegExp(phone_reg);
1280 patterns.au.evening_phone = new RegExp(phone_reg);
1281 patterns.au.other_phone = new RegExp(phone_reg);
1284 // the remaining patterns fit a well-known key name pattern
1286 angular.forEach(service.org_settings, function(val, key) {
1288 var parts = key.match(/ui.patron.edit\.(\w+)\.(\w+)\.regex/);
1291 var name = parts[2];
1292 patterns[cls][name] = new RegExp(val);
1299 .controller('PatronRegCtrl',
1300 ['$scope','$routeParams','$q','$uibModal','$window','egCore',
1301 'patronSvc','patronRegSvc','egUnloadPrompt','egAlertDialog',
1302 'egWorkLog', '$timeout', 'ngToast',
1303 function($scope , $routeParams , $q , $uibModal , $window , egCore ,
1304 patronSvc , patronRegSvc , egUnloadPrompt, egAlertDialog ,
1305 egWorkLog, $timeout, ngToast) {
1307 $scope.page_data_loaded = false;
1308 $scope.hold_notify_type = { phone : null, email : null, sms : null };
1309 $scope.hold_notify_observer = {};
1310 $scope.hold_rel_contacts = {};
1311 $scope.clone_id = patronRegSvc.clone_id = $routeParams.clone_id;
1312 $scope.stage_username =
1313 patronRegSvc.stage_username = $routeParams.stage_username;
1315 patronRegSvc.patron_id = $routeParams.edit_id || $routeParams.id;
1317 // for existing patrons, disable barcode input by default
1318 $scope.disable_bc = $scope.focus_usrname = Boolean($scope.patron_id);
1319 $scope.focus_bc = !Boolean($scope.patron_id);
1320 $scope.address_alerts = [];
1321 $scope.dupe_counts = {};
1323 // map of perm name to true/false for perms the logged in user
1324 // has at the currently selected patron home org unit.
1327 $scope.name_tab = 'primary';
1329 if (!$scope.edit_passthru) {
1330 // in edit more, scope.edit_passthru is delivered to us by
1331 // the enclosing controller. In register mode, there is
1332 // no enclosing controller, so we create our own.
1333 $scope.edit_passthru = {};
1336 // 0=all, 1=suggested, 2=all
1337 $scope.edit_passthru.vis_level = 0;
1339 // Apply default values for new patrons during initial registration
1340 // prs is shorthand for patronSvc
1341 function set_new_patron_defaults(prs) {
1342 if (!$scope.patron.passwd) {
1343 // passsword may originate from staged user.
1344 if ($scope.patron.day_phone &&
1345 $scope.org_settings['patron.password.use_phone']) {
1346 $scope.patron.passwd = $scope.patron.day_phone.substr(-4);
1348 $scope.generate_password();
1352 var notify = 'phone:email'; // hard-coded default when opac.hold_notify has no reg_default
1353 var notify_stype = $scope.user_setting_types['opac.hold_notify'];
1354 if (notify_stype && notify_stype.reg_default() !== undefined && notify_stype.reg_default() !== null) {
1355 console.log('using default opac.hold_notify');
1356 notify = notify_stype.reg_default();
1358 $scope.hold_notify_type.phone = Boolean(notify.match(/phone/));
1359 $scope.hold_notify_type.email = Boolean(notify.match(/email/));
1360 $scope.hold_notify_type.sms = Boolean(notify.match(/sms/));
1362 // staged users may be loaded w/ a profile.
1363 $scope.set_expire_date();
1365 if (prs.org_settings['ui.patron.default_ident_type']) {
1366 // $scope.patron needs this field to be an object
1367 var id = prs.org_settings['ui.patron.default_ident_type'];
1368 var ident_type = $scope.ident_types.filter(
1369 function(type) { return type.id() == id })[0];
1370 $scope.patron.ident_type = ident_type;
1372 if (prs.org_settings['ui.patron.default_inet_access_level']) {
1373 // $scope.patron needs this field to be an object
1374 var id = prs.org_settings['ui.patron.default_inet_access_level'];
1375 var level = $scope.net_access_levels.filter(
1376 function(lvl) { return lvl.id() == id })[0];
1377 $scope.patron.net_access_level = level;
1379 if (prs.org_settings['ui.patron.default_country']) {
1380 $scope.patron.addresses[0].country =
1381 prs.org_settings['ui.patron.default_country'];
1385 // A null or undefined pattern leads to exceptions. Before the
1386 // patterns are loaded from the server, default all patterns
1387 // to an innocuous regex. To avoid re-creating numerous
1388 // RegExp objects, cache the stub RegExp after initial creation.
1389 // note: angular docs say ng-pattern accepts a regexp or string,
1390 // but as of writing, it only works with a regexp object.
1391 // (Likely an angular 1.2 vs. 1.4 issue).
1392 var field_patterns = {au : {}, ac : {}, aua : {}};
1393 $scope.field_pattern = function(cls, field) {
1394 if (!field_patterns[cls][field])
1395 field_patterns[cls][field] = new RegExp('.*');
1396 return field_patterns[cls][field];
1399 // Main page load function. Kicks off tab init and data loading.
1402 $scope.initTab ? // initTab comes from patron app
1403 $scope.initTab('edit', $routeParams.id) : $q.when(),
1405 patronRegSvc.init(),
1407 ]).then(function(){ return patronRegSvc.init_patron(patronSvc ? patronSvc.current : patronRegSvc.patron ) })
1408 .then(function(patron) {
1409 // called after initTab and patronRegSvc.init have completed
1410 // in standalone mode, we have no patronSvc
1411 var prs = patronRegSvc;
1412 $scope.patron = patron;
1413 $scope.base_email = patron.email;
1414 $scope.base_default_sms = prs.user_settings['opac.default_sms_notify']
1415 $scope.field_doc = prs.field_doc;
1416 $scope.edit_profiles = prs.edit_profiles;
1417 $scope.edit_profile_entries = prs.edit_profile_entries;
1418 $scope.ident_types = prs.ident_types;
1419 $scope.locales = prs.locales;
1420 $scope.net_access_levels = prs.net_access_levels;
1421 $scope.user_setting_types = prs.user_setting_types;
1422 $scope.opt_in_setting_types = prs.opt_in_setting_types;
1423 $scope.org_settings = prs.org_settings;
1424 $scope.sms_carriers = prs.sms_carriers;
1425 $scope.stat_cats = prs.stat_cats;
1426 $scope.surveys = prs.surveys;
1427 $scope.survey_responses = prs.survey_responses;
1428 $scope.stat_cat_entry_maps = prs.stat_cat_entry_maps;
1429 $scope.stage_user = prs.stage_user;
1430 $scope.stage_user_requestor = prs.stage_user_requestor;
1432 $scope.user_settings = prs.user_settings;
1433 prs.user_settings = {};
1435 // If a default pickup lib is applied to the patron, apply it
1436 // to the UI at page load time. Otherwise, leave the value unset.
1437 if ($scope.user_settings['opac.default_pickup_location']) {
1438 $scope.patron._pickup_lib = egCore.org.get(
1439 $scope.user_settings['opac.default_pickup_location']);
1442 extract_hold_notify();
1444 if ($scope.patron.isnew)
1445 set_new_patron_defaults(prs);
1447 $scope.handle_home_org_changed();
1449 if ($scope.org_settings['ui.patron.edit.default_suggested'])
1450 $scope.edit_passthru.vis_level = 1;
1452 // Stat cats are fetched from open-ils.storage, where 't'==1
1453 $scope.hasRequiredStatCat = prs.stat_cats.filter(
1454 function(cat) {return cat.required() == 1} ).length > 0;
1456 $scope.page_data_loaded = true;
1458 prs.set_field_patterns(field_patterns);
1459 apply_username_regex();
1461 add_date_watchers();
1463 if ($scope.org_settings['ui.patron.edit.guardian_required_for_juv']) {
1468 function add_date_watchers() {
1470 $scope.$watch('patron.dob', function(newVal, oldVal) {
1471 // Even though this runs after page data load, there
1472 // are still times when it fires unnecessarily.
1473 if (newVal === oldVal) return;
1475 console.debug('dob change: ' + newVal + ' : ' + oldVal);
1476 maintain_juvenile_flag();
1479 // No need to watch expire_date
1482 function add_juv_watcher() {
1483 $scope.$watch('patron.juvenile', function(newVal, oldVal) {
1484 if (newVal === oldVal) return;
1486 field_visibility['au.guardian'] = 3; // required
1488 // Value will be reassessed by show_field()
1489 delete field_visibility['au.guardian'];
1494 // add watchers for hold notify method prefs
1495 $scope.$watch('hold_notify_type.phone', function(newVal, oldVal) {
1496 var notifyOpt = $scope.hold_notify_observer['phone'];
1497 if (newVal !== null) {
1498 notifyOpt.newval = newVal;
1502 $scope.$watch('hold_notify_type.sms', function(newVal, oldVal) {
1503 var notifyOpt = $scope.hold_notify_observer['sms'];
1504 if (newVal !== null) {
1505 notifyOpt.newval = newVal;
1509 $scope.$watch('hold_notify_type.email', function(newVal, oldVal) {
1510 var notifyOpt = $scope.hold_notify_observer['email'];
1511 if (newVal !== null) {
1512 notifyOpt.newval = newVal;
1516 // update the currently displayed field documentation
1517 $scope.set_selected_field_doc = function(cls, field) {
1518 $scope.selected_field_doc = $scope.field_doc[cls][field];
1521 // returns the tree depth of the selected profile group tree node.
1522 $scope.pgt_depth = function(grp) {
1524 while (grp = egCore.env.pgt.map[grp.parent()]) d++;
1528 // returns the tree depth of the selected profile group tree node.
1529 $scope.pgtde_depth = function(entry) {
1531 while (entry = egCore.env.pgtde.map[entry.parent()]) d++;
1535 // IDL fields used for labels in the UI.
1536 $scope.idl_fields = {
1537 au : egCore.idl.classes.au.field_map,
1538 ac : egCore.idl.classes.ac.field_map,
1539 aua : egCore.idl.classes.aua.field_map
1542 // field visibility cache. Some fields are universally required.
1543 // 3 == value universally required
1544 // 2 == field is visible by default
1545 // 1 == field is suggested by default
1546 var field_visibility = {};
1547 var default_field_visibility = {
1551 'au.first_given_name' : 3,
1552 'au.family_name' : 3,
1553 'au.pref_first_given_name' : 2,
1554 'au.pref_family_name' : 2,
1555 'au.ident_type' : 3,
1556 'au.ident_type2' : 2,
1561 'au.expire_date' : 3,
1562 'au.net_access_level' : 3,
1563 'aua.address_type' : 3,
1564 'aua.post_code' : 3,
1572 'aua.within_city_limits' : 2,
1575 'au.name_keywords': 1
1578 // Returns true if the selected field should be visible
1579 // given the current required/suggested/all setting.
1580 // The visibility flag applied to each field as a result of calling
1581 // this function also sets (via the same flag) the requiredness state.
1582 $scope.show_field = function(field_key) {
1583 // org settings have not been received yet.
1584 if (!$scope.org_settings) return false;
1586 if (field_visibility[field_key] == undefined) {
1587 // compile and cache the visibility for the selected field
1589 // The preferred name fields use the primary name field settings
1590 var org_key = field_key;
1591 var alt_name = false;
1592 if (field_key.match(/^au.alt_/)) {
1594 org_key = field_key.slice(7);
1597 var req_set = 'ui.patron.edit.' + org_key + '.require';
1598 var sho_set = 'ui.patron.edit.' + org_key + '.show';
1599 var sug_set = 'ui.patron.edit.' + org_key + '.suggest';
1601 if ($scope.org_settings[req_set]) {
1603 // Avoid requiring alt name fields when primary
1604 // name fields are required.
1605 field_visibility[field_key] = 2;
1607 field_visibility[field_key] = 3;
1610 } else if ($scope.org_settings[sho_set]) {
1611 field_visibility[field_key] = 2;
1613 } else if ($scope.org_settings[sug_set]) {
1614 field_visibility[field_key] = 1;
1618 if (field_visibility[field_key] == undefined) {
1619 // No org settings were applied above. Use the default
1620 // settings if present or assume the field has no
1621 // visibility flags applied.
1622 field_visibility[field_key] =
1623 default_field_visibility[field_key] || 0;
1626 return field_visibility[field_key] >= $scope.edit_passthru.vis_level;
1629 // See $scope.show_field().
1630 // A field with visbility level 3 means it's required.
1631 $scope.field_required = function(cls, field) {
1633 // Value in the password field is not required
1634 // for existing patrons.
1635 if (field == 'passwd' && $scope.patron && !$scope.patron.isnew)
1638 return (field_visibility[cls + '.' + field] == 3);
1641 // generates a random 4-digit password
1642 $scope.generate_password = function() {
1643 $scope.patron.passwd = Math.floor(Math.random()*9000) + 1000;
1646 $scope.send_password_reset_link = function() {
1647 if (!$scope.patron.email || $scope.patron.email == '') {
1648 egAlertDialog.open(egCore.strings.REG_PASSWORD_RESET_REQUEST_NO_EMAIL);
1650 } else if (patronRegSvc.check_email_different($scope.patron.email)) {
1651 egAlertDialog.open(egCore.strings.REG_PASSWORD_RESET_REQUEST_DIFFERENT_EMAIL);
1654 // we have an email address, fire the reset request
1657 'open-ils.actor.patron.password_reset.request',
1658 'barcode', $scope.patron.card.barcode, $scope.patron.email
1659 ).then(function(resp) {
1660 if (resp == '1') { // request okay
1661 ngToast.success(egCore.strings.REG_PASSWORD_RESET_REQUEST_SUCCESSFUL);
1663 var evt = egCore.evt.parse(resp);
1664 egAlertDialog.open(evt.desc);
1669 $scope.set_expire_date = function() {
1670 if (!$scope.patron.profile) return;
1671 var seconds = egCore.date.intervalToSeconds(
1672 $scope.patron.profile.perm_interval());
1673 var now_epoch = new Date().getTime();
1674 $scope.patron.expire_date = new Date(
1675 now_epoch + (seconds * 1000 /* milliseconds */))
1676 $scope.field_modified();
1679 // grp is the pgt object
1680 $scope.set_profile = function(grp) {
1681 // If we can't save because of group perms or create/update perms
1682 if ($scope.edit_passthru.hide_save_actions()) return;
1683 $scope.patron.profile = grp;
1684 $scope.set_expire_date();
1685 $scope.field_modified();
1688 $scope.invalid_profile = function() {
1691 $scope.patron.profile &&
1692 $scope.patron.profile.usergroup() == 't'
1696 $scope.new_address = function() {
1697 var addr = egCore.idl.toHash(new egCore.idl.aua());
1698 patronRegSvc.ingest_address($scope.patron, addr);
1699 addr.id = patronRegSvc.virt_id--;
1702 addr.within_city_limits = true;
1703 addr.country = $scope.org_settings['ui.patron.default_country'];
1704 $scope.patron.addresses.push(addr);
1707 // keep deleted addresses out of the patron object so
1708 // they won't appear in the UI. They'll be re-inserted
1709 // when the patron is updated.
1710 deleted_addresses = [];
1711 $scope.delete_address = function(id) {
1713 if ($scope.patron.isnew &&
1714 $scope.patron.addresses.length == 1 &&
1715 $scope.org_settings['ui.patron.registration.require_address']) {
1716 egAlertDialog.open(egCore.strings.REG_ADDR_REQUIRED);
1721 angular.forEach($scope.patron.addresses, function(addr) {
1722 if (addr.id == id) {
1724 addr.isdeleted = true;
1725 deleted_addresses.push(addr);
1728 addresses.push(addr);
1731 $scope.patron.addresses = addresses;
1734 $scope.approve_pending_address = function(addr) {
1738 'open-ils.actor.user.pending_address.approve',
1739 egCore.auth.token(), addr.id
1740 ).then(function(replaced_id) {
1741 var evt = egCore.evt.parse(replaced_id);
1742 if (evt) { alert(evt); return; }
1744 // Remove the pending address and the replaced address
1745 // from the local list of patron addresses.
1747 angular.forEach($scope.patron.addresses, function(a) {
1748 if (a.id != addr.id && a.id != replaced_id) {
1752 $scope.patron.addresses = addresses;
1754 // Fetch a fresh copy of the modified address from the server.
1755 // and add it back to the list.
1756 egCore.pcrud.retrieve('aua', replaced_id, {}, {authoritative: true})
1757 .then(null, null, function(new_addr) {
1758 new_addr = egCore.idl.toHash(new_addr);
1759 patronRegSvc.ingest_address($scope.patron, new_addr);
1760 $scope.patron.addresses.push(new_addr);
1765 $scope.post_code_changed = function(addr) {
1767 'open-ils.search', 'open-ils.search.zip', addr.post_code)
1768 .then(function(resp) {
1770 if (resp.city) addr.city = resp.city;
1771 if (resp.state) addr.state = resp.state;
1772 if (resp.county) addr.county = resp.county;
1773 if (resp.alert) alert(resp.alert);
1777 $scope.new_waiver_entry = function() {
1778 var waiver = egCore.idl.toHash(new egCore.idl.aupw());
1779 patronRegSvc.ingest_waiver_entry($scope.patron, waiver);
1780 waiver.id = patronRegSvc.virt_id--;
1781 waiver.isnew = true;
1782 $scope.patron.waiver_entries.push(waiver);
1785 deleted_waiver_entries = [];
1786 $scope.delete_waiver_entry = function(waiver_entry) {
1787 if (waiver_entry.id > 0) {
1788 waiver_entry.isdeleted = true;
1789 deleted_waiver_entries.push(waiver_entry);
1791 var index = $scope.patron.waiver_entries.indexOf(waiver_entry);
1792 $scope.patron.waiver_entries.splice(index, 1);
1795 $scope.replace_card = function() {
1796 $scope.patron.card.active = false;
1797 $scope.patron.card.ischanged = true;
1798 $scope.disable_bc = false;
1800 var new_card = egCore.idl.toHash(new egCore.idl.ac());
1801 new_card.id = patronRegSvc.virt_id--;
1802 new_card.isnew = true;
1803 new_card.active = true;
1804 new_card._primary = 'on';
1805 $scope.patron.card = new_card;
1807 // Remove any previous attempts to replace the card, since they
1808 // may be incomplete or created by accident.
1809 $scope.patron.cards =
1810 $scope.patron.cards.filter(function(c) {return !c.isnew})
1811 $scope.patron.cards.push(new_card);
1814 $scope.day_phone_changed = function(phone) {
1815 if (phone && $scope.patron.isnew &&
1816 $scope.org_settings['patron.password.use_phone']) {
1817 $scope.patron.passwd = phone.substr(-4);
1821 $scope.barcode_changed = function(bc) {
1823 $scope.dupe_barcode = false;
1826 'open-ils.actor.barcode.exists',
1827 egCore.auth.token(), bc
1828 ).then(function(resp) {
1829 if (resp == '1') { // duplicate card
1830 $scope.dupe_barcode = true;
1831 console.log('duplicate barcode detected: ' + bc);
1833 if (!$scope.patron.usrname)
1834 $scope.patron.usrname = bc;
1840 $scope.cards_dialog = function() {
1842 templateUrl: './circ/patron/t_patron_cards_dialog',
1845 ['$scope','$uibModalInstance','cards','perms','patron',
1846 function($scope , $uibModalInstance , cards , perms , patron) {
1847 // scope here is the modal-level scope
1848 $scope.args = {cards : cards, primary_barcode : null};
1849 angular.forEach(cards, function(card) {
1850 if (card.id == patron.card.id) {
1851 $scope.args.primary_barcode = card.id;
1854 $scope.perms = perms;
1855 $scope.ok = function() { $uibModalInstance.close($scope.args) }
1856 $scope.cancel = function () { $uibModalInstance.dismiss() }
1859 cards : function() {
1860 // scope here is the controller-level scope
1861 return $scope.patron.cards;
1863 perms : function() {
1864 return $scope.perms;
1866 patron : function() {
1867 return $scope.patron;
1872 angular.forEach(args.cards, function(card) {
1873 card.ischanged = true; // assume cards need updating, OK?
1874 if (card.id == args.primary_barcode) {
1875 $scope.patron.card = card;
1876 card._primary = true;
1878 card._primary = false;
1885 $scope.set_addr_type = function(addr, type) {
1886 var addrs = $scope.patron.addresses;
1887 if (addr['_is_'+type]) {
1888 angular.forEach(addrs, function(a) {
1889 if (a.id != addr.id) a['_is_'+type] = false;
1892 // unchecking mailing/billing means we have to randomly
1893 // select another address to fill that role. Select the
1894 // first address in the list (that does not match the
1896 for (var i = 0; i < addrs.length; i++) {
1897 if (addrs[i].id != addr.id) {
1898 addrs[i]['_is_' + type] = true;
1906 // Translate hold notify preferences from the form/scope back into a
1907 // single user setting value for opac.hold_notify.
1908 function compress_hold_notify() {
1909 var hold_notify_methods = [];
1910 if ($scope.hold_notify_type.phone) {
1911 hold_notify_methods.push('phone');
1913 if ($scope.hold_notify_type.email) {
1914 hold_notify_methods.push('email');
1916 if ($scope.hold_notify_type.sms) {
1917 hold_notify_methods.push('sms');
1920 $scope.user_settings['opac.hold_notify'] = hold_notify_methods.join(':');
1923 // dialog for selecting additional permission groups
1924 $scope.secondary_groups_dialog = function() {
1926 templateUrl: './circ/patron/t_patron_groups_dialog',
1929 ['$scope','$uibModalInstance','linked_groups','pgt_depth',
1930 function($scope , $uibModalInstance , linked_groups , pgt_depth) {
1932 $scope.pgt_depth = pgt_depth;
1934 linked_groups : linked_groups,
1935 edit_profiles : patronRegSvc.edit_profiles,
1936 new_profile : patronRegSvc.edit_profiles[0]
1939 // add a new group to the linked groups list
1940 $scope.link_group = function($event, grp) {
1941 var found = false; // avoid duplicates
1942 angular.forEach($scope.args.linked_groups,
1943 function(g) {if (g.id() == grp.id()) found = true});
1944 if (!found) $scope.args.linked_groups.push(grp);
1945 $event.preventDefault(); // avoid close
1948 // remove a group from the linked groups list
1949 $scope.unlink_group = function($event, grp) {
1950 $scope.args.linked_groups =
1951 $scope.args.linked_groups.filter(function(g) {
1952 return g.id() != grp.id()
1954 $event.preventDefault(); // avoid close
1957 $scope.ok = function() { $uibModalInstance.close($scope.args) }
1958 $scope.cancel = function () { $uibModalInstance.dismiss() }
1961 linked_groups : function() { return $scope.patron.groups },
1962 pgt_depth : function() { return $scope.pgt_depth }
1967 if ($scope.patron.isnew) {
1968 // groups must be linked for new patrons after the
1969 // patron is created.
1970 $scope.patron.groups = args.linked_groups;
1974 // update links groups for existing users in real time.
1975 var ids = args.linked_groups.map(function(g) {return g.id()});
1976 patronRegSvc.apply_secondary_groups($scope.patron.id, ids)
1977 .then(function(success) {
1979 $scope.patron.groups = args.linked_groups;
1985 function extract_hold_notify() {
1986 var p = $scope.patron;
1988 // get the user's opac.hold_notify setting
1989 var notify = $scope.user_settings['opac.hold_notify'];
1991 // if it's not set, use the default opac.hold_notify value
1992 if (!notify && !(notify === '')) {
1993 var notify_stype = $scope.user_setting_types['opac.hold_notify'];
1994 if (notify_stype && notify_stype.reg_default() !== undefined && notify_stype.reg_default() !== null) {
1995 notify = notify_stype.reg_default();
1997 // no setting and no default: set phone and email to true
1998 notify = 'phone:email';
2002 $scope.hold_notify_type.phone = Boolean(notify.match(/phone/));
2003 $scope.hold_notify_type.email = Boolean(notify.match(/email/));
2004 $scope.hold_notify_type.sms = Boolean(notify.match(/sms/));
2006 // stores original loaded values for comparison later
2007 for (var k in $scope.hold_notify_type){
2008 var val = $scope.hold_notify_type[k];
2010 if ($scope.hold_notify_type.hasOwnProperty(k)){
2011 $scope.hold_notify_observer[k] = {old : val, newval: null};
2015 // actual value from user
2016 $scope.hold_rel_contacts.day_phone = { old: p.day_phone, newval : null };
2017 $scope.hold_rel_contacts.other_phone = { old: p.other_phone, newval : null };
2018 $scope.hold_rel_contacts.evening_phone = { old: p.evening_phone, newval : null };
2019 // from user_settings
2020 $scope.hold_rel_contacts.default_phone = { old: $scope.user_settings['opac.default_phone'], newval : null };
2021 $scope.hold_rel_contacts.default_sms = { old: $scope.user_settings['opac.default_sms_notify'], newval : null };
2022 $scope.hold_rel_contacts.default_sms_carrier_id = { old: $scope.user_settings['opac.default_sms_carrier'], newval : null };
2026 function normalizePhone(number){
2027 // normalize phone # for comparison, only digits
2028 if (number == null || number == undefined) return '';
2030 var regex = /[^\d]/g;
2031 return number.replace(regex, '');
2034 $scope.invalidate_field = function(field) {
2035 patronRegSvc.invalidate_field($scope.patron, field).then(function() {
2036 $scope.handle_field_changed($scope.patron, field);
2040 $scope.send_test_email = function() {
2041 patronRegSvc.send_test_message($scope.patron.id, 'au.email.test').then(function(res) {
2042 if (res && res.template_output() && res.template_output().is_error() == 'f') {
2043 ngToast.success(egCore.strings.TEST_NOTIFY_SUCCESS);
2045 ngToast.warning(egCore.strings.TEST_NOTIFY_FAIL);
2046 if (res) console.log(res);
2051 $scope.send_test_sms = function() {
2052 patronRegSvc.send_test_message($scope.patron.id, 'au.sms_text.test').then(function(res) {
2053 if (res && res.template_output() && res.template_output().is_error() == 'f') {
2054 ngToast.success(egCore.strings.TEST_NOTIFY_SUCCESS);
2056 ngToast.warning(egCore.strings.TEST_NOTIFY_FAIL);
2057 if (res) console.log(res);
2062 address_alert = function(addr) {
2064 street1: addr.street1,
2065 street2: addr.street2,
2068 county: addr.county,
2069 country: addr.country,
2070 post_code: addr.post_code,
2071 mailing_address: addr._is_mailing,
2072 billing_address: addr._is_billing
2077 'open-ils.actor.address_alert.test',
2078 egCore.auth.token(), egCore.auth.user().ws_ou(), args
2079 ).then(function(res) {
2080 $scope.address_alerts = res;
2084 $scope.dupe_value_changed = function(type, value) {
2085 if (!$scope.dupe_search_encoded)
2086 $scope.dupe_search_encoded = {};
2088 $scope.dupe_counts[type] = 0;
2090 patronRegSvc.dupe_patron_search($scope.patron, type, value)
2091 .then(function(res) {
2092 $scope.dupe_counts[type] = res.count;
2094 $scope.dupe_search_encoded[type] =
2095 encodeURIComponent(js2JSON(res.search));
2097 $scope.dupe_search_encoded[type] = '';
2102 $scope.handle_home_org_changed = function() {
2103 org_id = $scope.patron.home_ou.id();
2104 patronRegSvc.has_perms_for_org(org_id).then(function(map) {
2105 angular.forEach(map, function(v, k) { $scope.perms[k] = v });
2109 $scope.handle_pulib_changed = function(org) {
2110 if (!$scope.user_settings) return; // still rendering
2111 $scope.user_settings['opac.default_pickup_location'] = org.id();
2114 // This is called with every character typed in a form field,
2115 // since that's the only way to gaurantee something has changed.
2116 // See handle_field_changed for ng-change vs. ng-blur.
2117 $scope.field_modified = function() {
2118 // Call attach with every field change, regardless of whether
2119 // it's been called before. This will allow for re-attach after
2120 // the user clicks through the unload warning. egUnloadPrompt
2121 // will ensure we only attach once.
2122 egUnloadPrompt.attach($scope);
2125 // also monitor when form is changed *by the user*, as using
2126 // an ng-change handler doesn't work with eg-date-input
2127 $scope.$watch('reg_form.$pristine', function(newVal, oldVal) {
2128 if (!newVal) egUnloadPrompt.attach($scope);
2131 // username regex (if present) must be removed any time
2132 // the username matches the barcode to avoid firing the
2133 // invalid field handlers.
2134 function apply_username_regex() {
2135 var regex = $scope.org_settings['opac.username_regex'];
2137 if ($scope.patron.card.barcode) {
2138 // username must match the regex or the barcode
2139 field_patterns.au.usrname =
2141 regex + '|^' + $scope.patron.card.barcode + '$');
2143 // username must match the regex
2144 field_patterns.au.usrname = new RegExp(regex);
2147 // username can be any format.
2148 field_patterns.au.usrname = new RegExp('.*');
2152 // obj could be the patron, an address, etc.
2153 // This is called any time a form field achieves then loses focus.
2154 // It does not necessarily mean the field has changed.
2155 // The alternative is ng-change, but it's called with each character
2156 // typed, which would be overkill for many of the actions called here.
2157 $scope.handle_field_changed = function(obj, field_name) {
2158 var cls = obj.classname; // set by egIdl
2159 var value = obj[field_name];
2161 console.debug('changing field ' + field_name + ' to ' + value);
2163 switch (field_name) {
2165 if (normalizePhone(value) !== normalizePhone($scope.hold_rel_contacts.day_phone.old)){
2166 $scope.hold_rel_contacts.day_phone.newval = value;
2168 if ($scope.patron.day_phone &&
2169 $scope.patron.isnew &&
2170 $scope.org_settings['patron.password.use_phone']) {
2171 $scope.patron.passwd = $scope.patron.day_phone.substr(-4);
2173 $scope.dupe_value_changed(field_name, value);
2175 case 'evening_phone' :
2176 if (normalizePhone(value) !== normalizePhone($scope.hold_rel_contacts.evening_phone.old)){
2177 $scope.hold_rel_contacts.evening_phone.newval = value;
2179 $scope.dupe_value_changed(field_name, value);
2181 case 'other_phone' :
2182 if (normalizePhone(value) !== normalizePhone($scope.hold_rel_contacts.other_phone.old)){
2183 $scope.hold_rel_contacts.other_phone.newval = value;
2185 $scope.dupe_value_changed(field_name, value);
2188 case 'ident_value2':
2189 $scope.dupe_value_changed('ident', value);
2192 case 'first_given_name':
2194 $scope.dupe_value_changed('name', value);
2198 $scope.dupe_value_changed('email', value);
2204 // dupe search on address wants the address object as the value.
2205 $scope.dupe_value_changed('address', obj);
2210 $scope.post_code_changed(obj);
2214 patronRegSvc.check_dupe_username(value)
2215 .then(function(yes) {$scope.dupe_username = Boolean(yes)});
2219 // TODO: finish barcode_changed handler.
2220 $scope.barcode_changed(value);
2221 apply_username_regex();
2223 case 'opac.default_phone':
2224 if (normalizePhone(value) !== normalizePhone($scope.hold_rel_contacts.default_phone.old)){
2225 $scope.hold_rel_contacts.default_phone.newval = value;
2228 case 'opac.default_sms_notify':
2229 if (normalizePhone(value) !== normalizePhone($scope.hold_rel_contacts.default_sms.old)){
2230 $scope.hold_rel_contacts.default_sms.newval = value;
2233 case 'opac.default_sms_carrier':
2234 if (value !== $scope.hold_rel_contacts.default_sms_carrier_id.old){
2235 $scope.hold_rel_contacts.default_sms_carrier_id.newval = value;
2241 // patron.juvenile is set to true if the user was born after
2242 function maintain_juvenile_flag() {
2243 if ( !($scope.patron && $scope.patron.dob) ) return;
2246 $scope.org_settings['global.juvenile_age_threshold']
2249 var base = new Date();
2251 base.setTime(base.getTime() -
2252 Number(egCore.date.intervalToSeconds(juv_interval) + '000'));
2254 $scope.patron.juvenile = ($scope.patron.dob > base);
2257 // returns true (disable) for orgs that cannot have users.
2258 $scope.disable_home_org = function(org_id) {
2259 if (!org_id) return;
2260 var org = egCore.org.get(org_id);
2264 org.ou_type().can_have_users() == 'f'
2268 // returns true (disable) for orgs that cannot have vols (for holds pickup)
2269 $scope.disable_pulib = function(org_id) {
2270 if (!org_id) return;
2271 return !egCore.org.CanHaveVolumes(org_id);
2274 // Returns true if attempting to edit self, but perms don't allow
2275 $scope.edit_passthru.self_edit_disallowed = function() {
2276 if ($scope.patron.id
2277 && $scope.patron.id == egCore.auth.user().id()
2278 && !$scope.perms.EDIT_SELF_IN_CLIENT
2283 // Returns true if attempting to edit a user without appropriate group application perms
2284 $scope.edit_passthru.group_edit_disallowed = function() {
2285 if ( $scope.patron.profile
2288 .filter(function(p) {
2289 return $scope.patron.profile.id() == p.id();
2295 // Returns true if the Save and Save & Clone buttons should be disabled.
2296 $scope.edit_passthru.hide_save_actions = function() {
2297 if ($scope.edit_passthru.self_edit_disallowed()) return true;
2298 if ($scope.edit_passthru.group_edit_disallowed()) return true;
2300 return $scope.patron.isnew ?
2301 !$scope.perms.CREATE_USER :
2302 !$scope.perms.UPDATE_USER;
2305 // Returns true if any input elements are tagged as invalid
2306 // via Angular patterns or required attributes.
2307 function form_has_invalid_fields() {
2308 return $('#patron-reg-container .ng-invalid').length > 0;
2311 function form_is_incomplete() {
2313 $scope.dupe_username ||
2314 $scope.dupe_barcode ||
2315 form_has_invalid_fields()
2320 $scope.edit_passthru.save = function(save_args) {
2321 if (!save_args) save_args = {};
2323 if (form_is_incomplete()) {
2324 // User has not provided valid values for all required fields.
2325 return egAlertDialog.open(egCore.strings.REG_INVALID_FIELDS);
2328 // remove page unload warning prompt
2329 egUnloadPrompt.clear();
2331 // toss the deleted addresses back into the patron's list of
2332 // addresses so it's included in the update
2333 $scope.patron.addresses =
2334 $scope.patron.addresses.concat(deleted_addresses);
2336 // ditto for waiver entries
2337 $scope.patron.waiver_entries =
2338 $scope.patron.waiver_entries.concat(deleted_waiver_entries);
2340 compress_hold_notify();
2344 patronRegSvc.save_user($scope.patron)
2345 .then(function(new_user) {
2346 if (new_user && new_user.classname) {
2347 updated_user = new_user;
2348 return patronRegSvc.save_user_settings(
2349 new_user, $scope.user_settings);
2351 var evt = egCore.evt.parse(new_user);
2353 if (evt && evt.textcode == 'XACT_COLLISION') {
2354 return egAlertDialog.open(
2355 egCore.strings.PATRON_EDIT_COLLISION).result;
2358 // debug only -- should not get here.
2359 alert('Patron update failed. \n\n' + js2JSON(new_user));
2362 }).then(function() {
2364 // only remove the staged user if the update succeeded.
2366 return patronRegSvc.remove_staged_user();
2370 }).then(function() {
2372 // linked groups for new users must be created after the new
2374 if ($scope.patron.isnew &&
2375 $scope.patron.groups && $scope.patron.groups.length) {
2376 var ids = $scope.patron.groups.map(function(g) {return g.id()});
2377 return patronRegSvc.apply_secondary_groups(updated_user.id(), ids)
2381 }).then(findChangedFieldsAffectedHolds)
2382 .then(function(changed_fields_plus_holds) {
2383 var needModal = changed_fields_plus_holds[0] && changed_fields_plus_holds[0].length > 0;
2385 ? $scope.update_holds_notify_modal(changed_fields_plus_holds[0])
2386 : $q.when(); // nothing changed, continue
2387 }).then(function() {
2391 ? egCore.strings.EG_WORK_LOG_REGISTERED_PATRON
2392 : egCore.strings.EG_WORK_LOG_EDITED_PATRON, {
2393 'action' : $scope.patron.isnew ? 'registered_patron' : 'edited_patron',
2394 'patron_id' : updated_user.id()
2399 // reloading the page means potentially losing some information
2400 // (e.g. last patron search), but is the only way to ensure all
2401 // components are properly updated to reflect the modified patron.
2402 if (updated_user && save_args.clone) {
2403 // open a separate tab for registering a new
2404 // patron from our cloned data.
2405 var url = 'https://'
2406 + $window.location.hostname
2407 + egCore.env.basePath
2408 + '/circ/patron/register/clone/'
2409 + updated_user.id();
2410 $window.open(url, '_blank').focus();
2412 } else if ($window.location.href.indexOf('stage') > -1 ){
2413 // we're here after deleting a self-reg staged user.
2414 // Just close tab, since refresh won't find staged user
2415 $timeout(function(){
2416 if (typeof BroadcastChannel != 'undefined') {
2417 var bChannel = new BroadcastChannel("eg.pending_usr.update");
2418 bChannel.postMessage({
2419 usr: egCore.idl.toHash(updated_user)
2426 // reload the current page
2427 $window.location.href = location.href;
2432 var phone_inputs = ["day_phone", "evening_phone","other_phone", "default_phone"];
2433 var sms_inputs = ["default_sms", "default_sms_carrier_id"];
2434 var method_prefs = ["sms_notify", "phone_notify", "email_notify"];
2435 var groupBy = function(xs, key){
2436 return xs.reduce(function(rv, x){
2437 (rv[x[key]] = rv[x[key]] || []).push(x);
2442 function findChangedFieldsAffectedHolds(){
2444 var changed_hold_fields = [];
2446 var default_phone_changed = false;
2447 var default_sms_carrier_changed = false;
2448 var default_sms_changed = false;
2449 for (var c in $scope.hold_rel_contacts){
2450 var newinput = $scope.hold_rel_contacts[c].newval;
2451 if ($scope.hold_rel_contacts.hasOwnProperty(c)
2452 && newinput !== null // null means user has not provided a value in this session
2453 && newinput != $scope.hold_rel_contacts[c].old){
2454 var changed = $scope.hold_rel_contacts[c];
2456 changed.isChecked = false;
2457 changed_hold_fields.push(changed);
2458 if (c === 'default_phone') default_phone_changed = true;
2459 if (c === 'default_sms_carrier_id') default_sms_carrier_changed = true;
2460 if (c === 'default_sms') default_sms_changed = true;
2464 for (var c in $scope.hold_notify_observer){
2465 var newinput = $scope.hold_notify_observer[c].newval;
2466 if ($scope.hold_notify_observer.hasOwnProperty(c)
2467 && newinput !== null // null means user has not provided a value in this session
2468 && newinput != $scope.hold_notify_observer[c].old){
2469 var changed = $scope.hold_notify_observer[c];
2470 changed.name = c + "_notify";
2471 changed.isChecked = false;
2472 changed_hold_fields.push(changed);
2474 // if we're turning on phone notifications, offer to update to the
2475 // current default number
2476 if (c === 'phone' && $scope.user_settings['opac.default_phone'] && newinput && !default_phone_changed) {
2477 changed_hold_fields.push({
2478 name: 'default_phone',
2480 newval: $scope.user_settings['opac.default_phone'],
2484 // and similarly for SMS
2485 if (c === 'sms' && $scope.user_settings['opac.default_sms_carrier'] && newinput && !default_sms_carrier_changed) {
2486 changed_hold_fields.push({
2487 name: 'default_sms_carrier_id',
2489 newval: $scope.user_settings['opac.default_sms_carrier'],
2493 if (c === 'sms' && $scope.user_settings['opac.default_sms_notify'] && newinput && !default_sms_changed) {
2494 changed_hold_fields.push({
2495 name: 'default_sms',
2497 newval: $scope.user_settings['opac.default_sms_notify'],
2505 angular.forEach(changed_hold_fields, function(c){
2506 promises.push(egCore.net.request('open-ils.circ',
2507 'open-ils.circ.holds.retrieve_by_notify_staff',
2508 egCore.auth.token(),
2510 c.name.includes('notify') || c.name.includes('carrier') ? c.old : c.newval,
2512 .then(function(affected_holds){
2513 if(!affected_holds || affected_holds.length < 1){
2514 // no holds affected - remove change from list
2515 var p = changed_hold_fields.indexOf(c);
2516 changed_hold_fields.splice(p, 1);
2518 c.affects = affected_holds;
2520 //angular.forEach(c.affects, function(h){
2523 if (!c.name.includes("notify")){
2524 if (c.name === "default_sms_carrier_id") {
2525 c.groups = groupBy(c.affects,'sms_carrier');
2527 c.groups = groupBy(c.affects, c.name.includes('_phone') ? 'phone_notify':'sms_notify');
2531 return $q.when(changed_hold_fields);
2536 return $q.all(promises);
2539 $scope.update_holds_notify_modal = function(changed_hold_fields){
2540 // open modal after-save, pre-reload modal to deal with updated hold notification stuff
2541 if ($scope.patron.isnew || changed_hold_fields.length < 1){
2545 return $uibModal.open({
2546 templateUrl: './circ/patron/t_hold_notify_update',
2549 ['$scope','$uibModalInstance','changed_fields','patron','carriers','def_carrier_id','default_phone','default_sms',
2550 function($scope , $uibModalInstance , changed_fields , patron, carriers, def_carrier_id , default_phone , default_sms) {
2551 // local modal scope
2552 $scope.ch_fields = changed_fields;
2553 $scope.focusMe = true;
2554 $scope.ok = function(msg) {
2556 // Need to do this so the page will reload automatically
2557 if (msg == 'no-update') return $uibModalInstance.close();
2559 //var selectedChanges = $scope.changed_fields.filter(function(c) {
2560 // return c.isChecked;
2562 var selectedChanges = [];
2563 angular.forEach($scope.ch_fields, function(f){
2564 if (f.name == 'phone_notify' && f.newval && f.isChecked) {
2565 // convert to default_phone change
2566 f.sel_hids = f.affects.map(function(h){ return h.id});
2567 f.newval = default_phone;
2568 f.name = 'default_phone';
2569 selectedChanges.push(f);
2570 } else if (f.name == 'sms_notify' && f.newval && f.isChecked) {
2571 // convert to default_sms change
2572 f.sel_hids = f.affects.map(function(h){ return h.id});
2573 f.newval = default_sms;
2574 f.name = 'default_sms';
2575 selectedChanges.push(f);
2576 } else if (f.name.includes('notify') || f.name.includes('carrier')){
2578 f.sel_hids = f.affects.map(function(h){ return h.id});
2579 selectedChanges.push(f);
2582 // this is the sms or phone, so look in the groups obj
2584 for (var k in f.groups){
2585 if (f.groups.hasOwnProperty(k)){
2586 var sel_holds = f.groups[k].filter(function(h){
2590 var hids = sel_holds.map(function(h){ return h.id});
2591 f.sel_hids.push.apply(f.sel_hids, hids);
2595 if (f.sel_hids.length > 0) selectedChanges.push(f);
2600 // call method to update holds for each change
2601 var chain = $q.when();
2602 angular.forEach(selectedChanges, function(c){
2603 var carrierId = c.name.includes('default_sms') ? Number(def_carrier_id) : null;
2604 chain = chain.then(function() {
2605 return egCore.net.request('open-ils.circ',
2606 'open-ils.circ.holds.batch_update_holds_by_notify_staff', egCore.auth.token(),
2609 c.old, // TODO: for number changes, old val is effectively moot
2612 carrierId).then(function(okList){ console.log(okList) });
2616 // carry out the updates and close modal
2617 chain.finally(function(){ $uibModalInstance.close() });
2620 $scope.cancel = function () { $uibModalInstance.dismiss() }
2622 $scope.isNumberCh = function(c){
2623 return !(c.name.includes('notify') || c.name.includes('carrier'));
2627 $scope.groupChanged = function(ch_f, grpK){
2628 var holdArr = ch_f.groups[grpK];
2629 if (holdArr && holdArr.length > 0){
2630 angular.forEach(holdArr, function(h){
2631 if (h.isChecked) { h.isChecked = !h.isChecked; $scope.chgCt-- }
2632 else { h.isChecked = true; $scope.chgCt++ }
2637 $scope.nonGrpChanged = function(field_ch){
2638 if (field_ch.isChecked) $scope.chgCt++;
2639 else $scope.chgCt--;
2642 // use this function as a keydown handler on form
2643 // elements that should not submit the form on enter.
2644 $scope.preventSubmit = function($event) {
2645 if ($event.keyCode == 13)
2646 $event.preventDefault();
2649 $scope.prettyCarrier = function(carrierId){
2650 var sms_carrierObj = carriers.find(function(c){ return c.id == carrierId});
2651 return sms_carrierObj.name;
2653 $scope.prettyBool = function(v){
2654 return v ? 'YES' : 'NO';
2658 changed_fields : function(){ return changed_hold_fields },
2659 patron : function(){ return $scope.patron },
2660 def_carrier_id : function(){
2661 var d = $scope.hold_rel_contacts.default_sms_carrier_id;
2662 return d.newval ? d.newval : d.old;
2664 default_phone : function() {
2665 return ($scope.hold_rel_contacts.default_phone.newval) ?
2666 $scope.hold_rel_contacts.default_phone.newval :
2667 $scope.hold_rel_contacts.default_phone.old;
2669 default_sms : function() {
2670 return ($scope.hold_rel_contacts.default_sms.newval) ?
2671 $scope.hold_rel_contacts.default_sms.newval :
2672 $scope.hold_rel_contacts.default_sms.old;
2674 carriers : function(){ return $scope.sms_carriers.map(function(c){ return egCore.idl.toHash(c) }) }
2679 $scope.edit_passthru.print = function() {
2680 var print_data = {patron : $scope.patron}
2682 return egCore.print.print({
2683 context : 'default',
2684 template : 'patron_data',