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) {
251 'CREATE_USER_GROUP_LINK',
252 'UPDATE_PATRON_COLLECTIONS_EXEMPT',
253 'UPDATE_PATRON_CLAIM_RETURN_COUNT',
254 'UPDATE_PATRON_CLAIM_NEVER_CHECKED_OUT_COUNT',
255 'UPDATE_PATRON_ACTIVE_CARD',
256 'UPDATE_PATRON_PRIMARY_CARD'
259 return egCore.perm.hasPermAt(perms_needed, true)
260 .then(function(perm_map) {
262 angular.forEach(perms_needed, function(perm) {
264 Boolean(perm_map[perm].indexOf(org_id) > -1);
271 service.get_surveys = function() {
272 var org_ids = egCore.org.fullPath(egCore.auth.user().ws_ou(), true);
274 return egCore.pcrud.search('asv', {
276 start_date : {'<=' : 'now'},
277 end_date : {'>=' : 'now'}
286 ).then(function(surveys) {
287 surveys = surveys.sort(function(a,b) {
288 return a.name() < b.name() ? -1 : 1 });
289 service.surveys = surveys;
290 angular.forEach(surveys, function(survey) {
291 angular.forEach(survey.questions(), function(question) {
292 service.survey_questions[question.id()] = question;
293 angular.forEach(question.answers(), function(answer) {
294 service.survey_answers[answer.id()] = answer;
299 egLovefield.setListInOfflineCache('asv', service.surveys)
300 egLovefield.setListInOfflineCache('asvq', service.survey_questions)
301 egLovefield.setListInOfflineCache('asva', service.survey_answers)
306 service.get_stat_cats = function() {
307 return egCore.net.request(
309 'open-ils.circ.stat_cat.actor.retrieve.all',
310 egCore.auth.token(), egCore.auth.user().ws_ou()
311 ).then(function(cats) {
312 cats = cats.sort(function(a, b) {
313 return a.name() < b.name() ? -1 : 1});
314 angular.forEach(cats, function(cat) {
316 cat.entries().sort(function(a,b) {
317 return a.value() < b.value() ? -1 : 1
321 service.stat_cats = cats;
322 return egLovefield.setStatCatsCache(cats);
326 service.get_org_settings = function() {
327 return egCore.org.settings([
328 'global.password_regex',
329 'global.juvenile_age_threshold',
330 'patron.password.use_phone',
331 'ui.patron.default_inet_access_level',
332 'ui.patron.default_ident_type',
333 'ui.patron.default_country',
334 'ui.patron.registration.require_address',
335 'circ.holds.behind_desk_pickup_supported',
336 'circ.patron_edit.clone.copy_address',
337 'ui.patron.edit.au.prefix.require',
338 'ui.patron.edit.au.prefix.show',
339 'ui.patron.edit.au.prefix.suggest',
340 'ui.patron.edit.ac.barcode.regex',
341 'ui.patron.edit.au.second_given_name.show',
342 'ui.patron.edit.au.second_given_name.suggest',
343 'ui.patron.edit.au.suffix.show',
344 'ui.patron.edit.au.suffix.suggest',
345 'ui.patron.edit.au.alias.show',
346 'ui.patron.edit.au.alias.suggest',
347 'ui.patron.edit.au.dob.require',
348 'ui.patron.edit.au.dob.show',
349 'ui.patron.edit.au.dob.suggest',
350 'ui.patron.edit.au.dob.calendar',
351 'ui.patron.edit.au.juvenile.show',
352 'ui.patron.edit.au.juvenile.suggest',
353 'ui.patron.edit.au.ident_value.show',
354 'ui.patron.edit.au.ident_value.suggest',
355 'ui.patron.edit.au.ident_value2.show',
356 'ui.patron.edit.au.ident_value2.suggest',
357 'ui.patron.edit.au.email.require',
358 'ui.patron.edit.au.email.show',
359 'ui.patron.edit.au.email.suggest',
360 'ui.patron.edit.au.email.regex',
361 'ui.patron.edit.au.email.example',
362 'ui.patron.edit.au.day_phone.require',
363 'ui.patron.edit.au.day_phone.show',
364 'ui.patron.edit.au.day_phone.suggest',
365 'ui.patron.edit.au.day_phone.regex',
366 'ui.patron.edit.au.day_phone.example',
367 'ui.patron.edit.au.evening_phone.require',
368 'ui.patron.edit.au.evening_phone.show',
369 'ui.patron.edit.au.evening_phone.suggest',
370 'ui.patron.edit.au.evening_phone.regex',
371 'ui.patron.edit.au.evening_phone.example',
372 'ui.patron.edit.au.other_phone.require',
373 'ui.patron.edit.au.other_phone.show',
374 'ui.patron.edit.au.other_phone.suggest',
375 'ui.patron.edit.au.other_phone.regex',
376 'ui.patron.edit.au.other_phone.example',
377 'ui.patron.edit.phone.regex',
378 'ui.patron.edit.phone.example',
379 'ui.patron.edit.au.active.show',
380 'ui.patron.edit.au.active.suggest',
381 'ui.patron.edit.au.barred.show',
382 'ui.patron.edit.au.barred.suggest',
383 'ui.patron.edit.au.master_account.show',
384 'ui.patron.edit.au.master_account.suggest',
385 'ui.patron.edit.au.claims_returned_count.show',
386 'ui.patron.edit.au.claims_returned_count.suggest',
387 'ui.patron.edit.au.claims_never_checked_out_count.show',
388 'ui.patron.edit.au.claims_never_checked_out_count.suggest',
389 'ui.patron.edit.au.alert_message.show',
390 'ui.patron.edit.au.alert_message.suggest',
391 'ui.patron.edit.aua.post_code.regex',
392 'ui.patron.edit.aua.post_code.example',
393 'ui.patron.edit.aua.county.require',
395 'ui.patron.edit.default_suggested',
396 'opac.barcode_regex',
397 'opac.username_regex',
399 'ui.patron.edit.aua.state.require',
400 'ui.patron.edit.aua.state.suggest',
401 'ui.patron.edit.aua.state.show',
402 'ui.admin.work_log.max_entries',
403 'ui.admin.patron_log.max_entries'
404 ]).then(function(settings) {
405 service.org_settings = settings;
406 if (egCore && egCore.env && !egCore.env.aous) {
407 egCore.env.aous = settings;
408 console.log('setting egCore.env.aous');
410 return service.process_org_settings(settings);
414 // some org settings require the retrieval of additional data
415 service.process_org_settings = function(settings) {
417 var promises = [egLovefield.setSettingsCache(settings)];
419 if (settings['sms.enable']) {
420 // fetch SMS carriers
422 egCore.pcrud.search('csc',
425 {'class':'csc', 'field':'name'},
426 {'class':'csc', 'field':'region'}
428 ).then(function(carriers) {
429 service.sms_carriers = carriers;
433 // if other promises are added below, this is not necessary.
434 promises.push($q.when());
437 // other post-org-settings processing goes here,
438 // adding to promises as needed.
440 return $q.all(promises);
443 service.get_ident_types = function() {
444 if (egCore.env.cit) {
445 service.ident_types = egCore.env.cit.list;
448 return egCore.pcrud.retrieveAll('cit', {}, {atomic : true})
449 .then(function(types) {
450 egCore.env.absorbList(types, 'cit')
451 service.ident_types = types
456 service.get_net_access_levels = function() {
457 if (egCore.env.cnal) {
458 service.net_access_levels = egCore.env.cnal.list;
461 return egCore.pcrud.retrieveAll('cnal', {}, {atomic : true})
462 .then(function(levels) {
463 egCore.env.absorbList(levels, 'cnal')
464 service.net_access_levels = levels
469 service.get_perm_groups = function() {
470 if (egCore.env.pgt) {
471 service.profiles = egCore.env.pgt.list;
472 return service.set_edit_profiles();
474 return egCore.pcrud.search('pgt', {parent : null},
475 {flesh : -1, flesh_fields : {pgt : ['children']}}
478 egCore.env.absorbTree(tree, 'pgt')
479 service.profiles = egCore.env.pgt.list;
480 return service.set_edit_profiles();
486 service.get_perm_group_entries = function() {
487 if (egCore.env.pgtde) {
488 service.profile_entries = egCore.env.pgtde.list;
489 return service.set_edit_profile_entries();
491 return egCore.pcrud.search('pgtde', {org: egCore.auth.user().ws_ou(), parent: null},
492 {flesh : -1, flesh_fields : {pgtde : ['grp', 'children']}}, {atomic : true}
493 ).then(function(treeArray) {
494 function compare(a,b) {
495 if (a.position() > b.position())
497 if (a.position() < b.position())
503 function squash(node) {
504 node.children().sort(compare);
506 angular.forEach(node.children(), squash);
509 angular.forEach(treeArray, squash);
510 var blob = egCore.env.absorbList(list, 'pgtde');
511 blob.tree = treeArray;
513 service.profile_entries = egCore.env.pgtde.list;
514 return service.set_edit_profile_entries();
519 service.get_field_doc = function() {
521 return egCore.pcrud.search('fdoc', {
522 fm_class: ['au', 'ac', 'aua', 'actsc', 'asv', 'asvq', 'asva']})
525 return egLovefield.setListInOfflineCache('fdoc', to_cache)
529 if (!service.field_doc[doc.fm_class()]) {
530 service.field_doc[doc.fm_class()] = {};
532 service.field_doc[doc.fm_class()][doc.field()] = doc;
539 service.get_user_setting_types = function() {
541 // No need to re-fetch the common setting types.
542 if (Object.keys(service.user_setting_types).length)
545 var org_ids = egCore.org.ancestors(egCore.auth.user().ws_ou(), true);
548 'circ.holds_behind_desk',
549 'circ.collections.exempt',
551 'opac.default_phone',
552 'opac.default_pickup_location',
553 'opac.default_sms_carrier',
554 'opac.default_sms_notify'];
556 return egCore.pcrud.search('cust', {
558 {name : static_types}, // common user settings
559 {name : { // opt-in notification user settings
561 select : {atevdef : ['opt_in_setting']},
563 // we only care about opt-in settings for
564 // event_defs our users encounter
565 where : {'+atevdef' : {owner : org_ids}}
569 }, {}, {atomic : true}).then(function(setting_types) {
571 egCore.env.absorbList(setting_types, 'cust'); // why not...
573 angular.forEach(setting_types, function(stype) {
574 service.user_setting_types[stype.name()] = stype;
575 if (static_types.indexOf(stype.name()) == -1) {
576 service.opt_in_setting_types[stype.name()] = stype;
582 service.get_user_settings = function() {
584 return service.get_user_setting_types()
587 var setting_types = Object.values(service.user_setting_types);
589 if (service.patron_id) {
590 // retrieve applied values for the current user
591 // for the setting types we care about.
594 setting_types.map(function(obj) { return obj.name() });
596 return egCore.net.request(
598 'open-ils.actor.patron.settings.retrieve.authoritative',
602 ).then(function(settings) {
603 service.user_settings = settings;
608 // apply default user setting values
609 angular.forEach(setting_types, function(stype, index) {
610 if (stype.reg_default() != undefined) {
611 var val = stype.reg_default();
612 if (stype.datatype() == 'bool') {
613 // A boolean user setting type whose default
614 // value starts with t/T is considered 'true',
616 val = Boolean((val+'').match(/^t/i));
618 service.user_settings[stype.name()] = val;
625 service.invalidate_field = function(patron, field) {
626 console.log('Invalidating patron field ' + field);
628 return egCore.net.request(
630 'open-ils.actor.invalidate.' + field,
631 egCore.auth.token(), patron.id, null, patron.home_ou.id()
633 ).then(function(res) {
634 // clear the invalid value from the form
637 // update last_xact_id so future save operations
638 // on this patron will be allowed
639 patron.last_xact_id = res.payload.last_xact_id[patron.id];
643 service.dupe_patron_search = function(patron, type, value) {
646 console.log('Dupe search called with "'+ type +'" and value '+ value);
648 if (type.match(/phone/)) type = 'phone'; // day_phone, etc.
653 var fname = patron.first_given_name;
654 var lname = patron.family_name;
655 if (!(fname && lname)) return $q.when({count:0});
657 first_given_name : {value : fname, group : 0},
658 family_name : {value : lname, group : 0}
663 search = {email : {value : value, group : 0}};
667 search = {ident : {value : value, group : 2}};
671 search = {phone : {value : value, group : 2}};
676 angular.forEach(['street1', 'street2', 'city', 'post_code'],
679 search[field] = {value : value[field], group: 1};
685 return egCore.net.request(
687 'open-ils.actor.patron.search.advanced',
688 egCore.auth.token(), search, null, null, 1
689 ).then(function(res) {
690 res = res.filter(function(id) {return id != patron.id});
698 service.init_patron = function(current) {
701 return $q.when(service.init_new_patron());
703 service.patron = current;
704 return $q.when(service.init_existing_patron(current));
707 service.ingest_address = function(patron, addr) {
708 addr.valid = addr.valid == 't';
709 addr.within_city_limits = addr.within_city_limits == 't';
710 addr._is_mailing = (patron.mailing_address &&
711 addr.id == patron.mailing_address.id);
712 addr._is_billing = (patron.billing_address &&
713 addr.id == patron.billing_address.id);
717 * Existing patron objects reqire some data munging before insertion
720 * 1. Turn everything into a hash
721 * 2. ... Except certain fields (selectors) whose widgets require objects
722 * 3. Bools must be Boolean, not t/f.
724 service.init_existing_patron = function(current) {
726 service.existing_patron = current;
728 var patron = egCore.idl.toHash(current);
730 patron.home_ou = egCore.org.get(patron.home_ou.id);
731 patron.expire_date = new Date(Date.parse(patron.expire_date));
732 patron.dob = service.parse_dob(patron.dob);
733 patron.profile = current.profile(); // pre-hash version
734 patron.net_access_level = current.net_access_level();
735 patron.ident_type = current.ident_type();
736 patron.ident_type2 = current.ident_type2();
737 patron.groups = current.groups(); // pre-hash
740 ['juvenile', 'barred', 'active', 'master_account'],
741 function(field) { patron[field] = patron[field] == 't'; }
744 angular.forEach(patron.cards, function(card) {
745 card.active = card.active == 't';
746 if (card.id == patron.card.id) {
748 card._primary = 'on';
752 angular.forEach(patron.addresses,
753 function(addr) { service.ingest_address(patron, addr) });
755 service.get_linked_addr_users(patron.addresses);
757 // Remove stat cat entries that link to out-of-scope stat
758 // cats. With this, we avoid unnecessarily updating (or worse,
759 // modifying) stat cat values that are not ours to modify.
760 patron.stat_cat_entries = patron.stat_cat_entries.filter(
763 // service.stat_cats only contains in-scope stat cats.
764 service.stat_cats.filter(function(cat) {
765 return (cat.id() == map.stat_cat.id) })[0]
770 // toss entries for existing stat cat maps into our living
771 // stat cat entry map, which is modified within the template.
772 angular.forEach(patron.stat_cat_entries, function(map) {
773 service.stat_cat_entry_maps[map.stat_cat.id] = map.stat_cat_entry;
776 service.patron = patron;
780 service.init_new_patron = function() {
782 id : service.virt_id--,
785 address_type : egCore.strings.REG_ADDR_TYPE,
788 within_city_limits : false,
789 country : service.org_settings['ui.patron.default_country'],
793 id : service.virt_id--,
804 home_ou : egCore.org.get(egCore.auth.user().ws_ou()),
805 stat_cat_entries : [],
810 if (service.clone_user)
811 service.copy_clone_data(user);
813 if (service.stage_user)
814 service.copy_stage_data(user);
819 // dob is always YYYY-MM-DD
820 // Dates of birth do not contain timezone info, which can lead to
821 // inconcistent timezone handling, potentially representing
822 // different points in time, depending on the implementation.
823 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
824 // See "Differences in assumed time zone"
825 // TODO: move this into egDate ?
826 service.parse_dob = function(dob) {
827 if (!dob) return null;
828 var parts = dob.split('-');
829 return new Date(parts[0], parts[1] - 1, parts[2])
832 service.copy_stage_data = function(user) {
833 var cuser = service.stage_user;
835 // copy the data into our new user object
837 for (var key in egCore.idl.classes.stgu.field_map) {
838 if (egCore.idl.classes.au.field_map[key] &&
839 !egCore.idl.classes.stgu.field_map[key].virtual) {
840 if (cuser.user[key]() !== null)
841 user[key] = cuser.user[key]();
845 if (user.home_ou) user.home_ou = egCore.org.get(user.home_ou);
846 if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
848 user.ident_type = egCore.env.cit.map[user.ident_type];
849 if (user.ident_type2)
850 user.ident_type2 = egCore.env.cit.map[user.ident_type2];
851 user.dob = service.parse_dob(user.dob);
853 // Clear the usrname if it looks like a UUID
854 if (user.usrname.replace(/-/g,'').match(/[0-9a-f]{32}/))
857 // Don't use stub address if we have one from the staged user.
858 if (cuser.mailing_addresses.length || cuser.billing_addresses.length)
861 // is_mailing=false implies is_billing
862 function addr_from_stage(stage_addr) {
863 if (!stage_addr) return;
864 var cls = stage_addr.classname;
867 id : service.virt_id--,
871 _is_mailing : cls == 'stgma',
872 _is_billing : cls == 'stgba'
875 user.mailing_address = addr;
876 user.addresses.push(addr);
878 for (var key in egCore.idl.classes[cls].field_map) {
879 if (egCore.idl.classes.aua.field_map[key] &&
880 !egCore.idl.classes[cls].field_map[key].virtual) {
881 if (stage_addr[key]() !== null)
882 addr[key] = stage_addr[key]();
887 addr_from_stage(cuser.mailing_addresses[0]);
888 addr_from_stage(cuser.billing_addresses[0]);
890 if (user.addresses.length == 1) {
891 // If there is only one address,
892 // use it as both mailing and billing.
893 var addr = user.addresses[0];
894 addr._is_mailing = addr._is_billing = true;
895 user.mailing_address = user.billing_address = addr;
898 if (cuser.cards.length) {
900 id : service.virt_id--,
901 barcode : cuser.cards[0].barcode(),
907 user.cards.push(user.card);
908 if (user.usrname == '')
909 user.usrname = card.barcode;
912 angular.forEach(cuser.settings, function(setting) {
913 service.user_settings[setting.setting()] = Boolean(setting.value());
917 // copy select values from the cloned user to the new user.
919 service.copy_clone_data = function(user) {
920 var clone_user = service.clone_user;
922 // flesh the home org locally
923 user.home_ou = egCore.org.get(clone_user.home_ou());
924 if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
926 if (!clone_user.billing_address() &&
927 !clone_user.mailing_address())
928 return; // no addresses to copy or link
930 // if the cloned user has any addresses, we don't need
931 // the stub address created in init_new_patron.
935 service.org_settings['circ.patron_edit.clone.copy_address'];
944 angular.forEach(clone_fields, function(field) {
945 user[field] = clone_user[field]();
948 if (copy_addresses) {
949 var bill_addr, mail_addr;
951 // copy the billing and mailing addresses into new addresses
952 function clone_addr(addr) {
953 var new_addr = egCore.idl.toHash(addr);
954 new_addr.id = service.virt_id--;
955 new_addr.usr = user.id;
956 new_addr.isnew = true;
957 new_addr.valid = true;
958 user.addresses.push(new_addr);
962 if (bill_addr = clone_user.billing_address()) {
963 var addr = clone_addr(bill_addr);
964 addr._is_billing = true;
965 user.billing_address = addr;
968 if (mail_addr = clone_user.mailing_address()) {
970 if (bill_addr && bill_addr.id() == mail_addr.id()) {
971 user.mailing_address = user.billing_address;
972 user.mailing_address._is_mailing = true;
974 var addr = clone_addr(mail_addr);
975 addr._is_mailing = true;
976 user.mailing_address = addr;
980 // if there is no billing addr, use the mailing addr
981 user.billing_address = user.mailing_address;
982 user.billing_address._is_billing = true;
989 // link the billing and mailing addresses
991 if (addr = clone_user.billing_address()) {
992 user.billing_address = egCore.idl.toHash(addr);
993 user.billing_address._is_billing = true;
994 user.addresses.push(user.billing_address);
995 user.billing_address._linked_owner_id = clone_user.id();
996 user.billing_address._linked_owner = service.format_name(
997 clone_user.family_name(),
998 clone_user.first_given_name(),
999 clone_user.second_given_name()
1003 if (addr = clone_user.mailing_address()) {
1004 if (user.billing_address &&
1005 addr.id() == user.billing_address.id) {
1006 // mailing matches billing
1007 user.mailing_address = user.billing_address;
1008 user.mailing_address._is_mailing = true;
1010 user.mailing_address = egCore.idl.toHash(addr);
1011 user.mailing_address._is_mailing = true;
1012 user.addresses.push(user.mailing_address);
1013 user.mailing_address._linked_owner_id = clone_user.id();
1014 user.mailing_address._linked_owner = service.format_name(
1015 clone_user.family_name(),
1016 clone_user.first_given_name(),
1017 clone_user.second_given_name()
1024 // translate the patron back into IDL form
1025 service.save_user = function(phash) {
1027 var patron = egCore.idl.fromHash('au', phash);
1029 patron.home_ou(patron.home_ou().id());
1030 patron.expire_date(patron.expire_date().toISOString());
1031 patron.profile(patron.profile().id());
1033 patron.dob(patron.dob().toISOString().replace(/T.*/,''));
1034 if (patron.ident_type())
1035 patron.ident_type(patron.ident_type().id());
1036 if (patron.net_access_level())
1037 patron.net_access_level(patron.net_access_level().id());
1040 ['juvenile', 'barred', 'active', 'master_account'],
1041 function(field) { patron[field](phash[field] ? 't' : 'f'); }
1044 var card_hashes = patron.cards();
1046 angular.forEach(card_hashes, function(chash) {
1047 var card = egCore.idl.fromHash('ac', chash)
1048 card.usr(patron.id());
1049 card.active(chash.active ? 't' : 'f');
1050 patron.cards().push(card);
1051 if (chash._primary) {
1056 var addr_hashes = patron.addresses();
1057 patron.addresses([]);
1058 angular.forEach(addr_hashes, function(addr_hash) {
1059 if (!addr_hash.isnew && !addr_hash.isdeleted)
1060 addr_hash.ischanged = true;
1061 var addr = egCore.idl.fromHash('aua', addr_hash);
1062 patron.addresses().push(addr);
1063 addr.valid(addr.valid() ? 't' : 'f');
1064 addr.within_city_limits(addr.within_city_limits() ? 't' : 'f');
1065 if (addr_hash._is_mailing) patron.mailing_address(addr);
1066 if (addr_hash._is_billing) patron.billing_address(addr);
1069 patron.survey_responses([]);
1070 angular.forEach(service.survey_responses, function(answer) {
1071 var question = service.survey_questions[answer.question()];
1072 var resp = new egCore.idl.asvr();
1074 resp.survey(question.survey());
1075 resp.question(question.id());
1076 resp.answer(answer.id());
1077 resp.usr(patron.id());
1078 resp.answer_date('now');
1079 patron.survey_responses().push(resp);
1082 // re-object-ify the patron stat cat entry maps
1084 angular.forEach(patron.stat_cat_entries(), function(entry) {
1085 var e = egCore.idl.fromHash('actscecm', entry);
1086 e.stat_cat(e.stat_cat().id);
1089 patron.stat_cat_entries(maps);
1091 // service.stat_cat_entry_maps maps stats to values
1092 // patron.stat_cat_entries is an array of stat_cat_entry_usr_map's
1094 service.stat_cat_entry_maps, function(value, cat_id) {
1096 // see if we already have a mapping for this entry
1097 var existing = patron.stat_cat_entries().filter(
1098 function(e) { return e.stat_cat() == cat_id })[0];
1100 if (existing) { // we have a mapping
1101 // if the existing mapping matches the new one,
1102 // there' nothing left to do
1103 if (existing.stat_cat_entry() == value) return;
1105 // mappings differ. delete the old one and create
1107 existing.isdeleted(true);
1110 var newmap = new egCore.idl.actscecm();
1111 newmap.target_usr(patron.id());
1113 newmap.stat_cat(cat_id);
1114 newmap.stat_cat_entry(value);
1115 patron.stat_cat_entries().push(newmap);
1118 if (!patron.isnew()) patron.ischanged(true);
1120 return egCore.net.request(
1122 'open-ils.actor.patron.update',
1123 egCore.auth.token(), patron);
1126 service.remove_staged_user = function() {
1127 if (!service.stage_user) return $q.when();
1128 return egCore.net.request(
1130 'open-ils.actor.user.stage.delete',
1131 egCore.auth.token(),
1132 service.stage_user.user.row_id()
1136 service.save_user_settings = function(new_user, user_settings) {
1139 if (service.patron_id) {
1140 // Update all user editor setting values for existing
1141 // users regardless of whether a value changed.
1142 settings = user_settings;
1145 // Create settings for all non-null setting values for new patrons.
1146 angular.forEach(user_settings, function(val, key) {
1147 if (val !== null) settings[key] = val;
1151 if (Object.keys(settings).length == 0) return $q.when();
1153 return egCore.net.request(
1155 'open-ils.actor.patron.settings.update',
1156 egCore.auth.token(), new_user.id(), settings
1157 ).then(function(resp) {
1162 // Applies field-specific validation regex's from org settings
1163 // to form fields. Be careful not remove any pattern data we
1164 // are not explicitly over-writing in the provided patterns obj.
1165 service.set_field_patterns = function(patterns) {
1166 if (service.org_settings['opac.username_regex']) {
1167 patterns.au.usrname =
1168 new RegExp(service.org_settings['opac.username_regex']);
1171 if (service.org_settings['ui.patron.edit.ac.barcode.regex']) {
1172 patterns.ac.barcode =
1173 new RegExp(service.org_settings['ui.patron.edit.ac.barcode.regex']);
1176 if (service.org_settings['global.password_regex']) {
1177 patterns.au.passwd =
1178 new RegExp(service.org_settings['global.password_regex']);
1181 var phone_reg = service.org_settings['ui.patron.edit.phone.regex'];
1183 // apply generic phone regex first, replace below as needed.
1184 patterns.au.day_phone = new RegExp(phone_reg);
1185 patterns.au.evening_phone = new RegExp(phone_reg);
1186 patterns.au.other_phone = new RegExp(phone_reg);
1189 // the remaining patterns fit a well-known key name pattern
1191 angular.forEach(service.org_settings, function(val, key) {
1193 var parts = key.match(/ui.patron.edit\.(\w+)\.(\w+)\.regex/);
1196 var name = parts[2];
1197 patterns[cls][name] = new RegExp(val);
1204 .controller('PatronRegCtrl',
1205 ['$scope','$routeParams','$q','$uibModal','$window','egCore',
1206 'patronSvc','patronRegSvc','egUnloadPrompt','egAlertDialog',
1208 function($scope , $routeParams , $q , $uibModal , $window , egCore ,
1209 patronSvc , patronRegSvc , egUnloadPrompt, egAlertDialog ,
1212 $scope.page_data_loaded = false;
1213 $scope.hold_notify_type = { phone : null, email : null, sms : null };
1214 $scope.clone_id = patronRegSvc.clone_id = $routeParams.clone_id;
1215 $scope.stage_username =
1216 patronRegSvc.stage_username = $routeParams.stage_username;
1218 patronRegSvc.patron_id = $routeParams.edit_id || $routeParams.id;
1220 // for existing patrons, disable barcode input by default
1221 $scope.disable_bc = $scope.focus_usrname = Boolean($scope.patron_id);
1222 $scope.focus_bc = !Boolean($scope.patron_id);
1223 $scope.address_alerts = [];
1224 $scope.dupe_counts = {};
1226 // map of perm name to true/false for perms the logged in user
1227 // has at the currently selected patron home org unit.
1230 if (!$scope.edit_passthru) {
1231 // in edit more, scope.edit_passthru is delivered to us by
1232 // the enclosing controller. In register mode, there is
1233 // no enclosing controller, so we create our own.
1234 $scope.edit_passthru = {};
1237 // 0=all, 1=suggested, 2=all
1238 $scope.edit_passthru.vis_level = 0;
1240 // Apply default values for new patrons during initial registration
1241 // prs is shorthand for patronSvc
1242 function set_new_patron_defaults(prs) {
1243 if (!$scope.patron.passwd) {
1244 // passsword may originate from staged user.
1245 $scope.generate_password();
1247 $scope.hold_notify_type.phone = true;
1248 $scope.hold_notify_type.email = true;
1249 $scope.hold_notify_type.sms = false;
1251 // staged users may be loaded w/ a profile.
1252 $scope.set_expire_date();
1254 if (prs.org_settings['ui.patron.default_ident_type']) {
1255 // $scope.patron needs this field to be an object
1256 var id = prs.org_settings['ui.patron.default_ident_type'];
1257 var ident_type = $scope.ident_types.filter(
1258 function(type) { return type.id() == id })[0];
1259 $scope.patron.ident_type = ident_type;
1261 if (prs.org_settings['ui.patron.default_inet_access_level']) {
1262 // $scope.patron needs this field to be an object
1263 var id = prs.org_settings['ui.patron.default_inet_access_level'];
1264 var level = $scope.net_access_levels.filter(
1265 function(lvl) { return lvl.id() == id })[0];
1266 $scope.patron.net_access_level = level;
1268 if (prs.org_settings['ui.patron.default_country']) {
1269 $scope.patron.addresses[0].country =
1270 prs.org_settings['ui.patron.default_country'];
1274 // A null or undefined pattern leads to exceptions. Before the
1275 // patterns are loaded from the server, default all patterns
1276 // to an innocuous regex. To avoid re-creating numerous
1277 // RegExp objects, cache the stub RegExp after initial creation.
1278 // note: angular docs say ng-pattern accepts a regexp or string,
1279 // but as of writing, it only works with a regexp object.
1280 // (Likely an angular 1.2 vs. 1.4 issue).
1281 var field_patterns = {au : {}, ac : {}, aua : {}};
1282 $scope.field_pattern = function(cls, field) {
1283 if (!field_patterns[cls][field])
1284 field_patterns[cls][field] = new RegExp('.*');
1285 return field_patterns[cls][field];
1288 // Main page load function. Kicks off tab init and data loading.
1291 $scope.initTab ? // initTab comes from patron app
1292 $scope.initTab('edit', $routeParams.id) : $q.when(),
1294 patronRegSvc.init(),
1296 ]).then(function(){ return patronRegSvc.init_patron(patronSvc ? patronSvc.current : patronRegSvc.patron ) })
1297 .then(function(patron) {
1298 // called after initTab and patronRegSvc.init have completed
1299 // in standalone mode, we have no patronSvc
1300 var prs = patronRegSvc;
1301 $scope.patron = patron;
1302 $scope.field_doc = prs.field_doc;
1303 $scope.edit_profiles = prs.edit_profiles;
1304 $scope.edit_profile_entries = prs.edit_profile_entries;
1305 $scope.ident_types = prs.ident_types;
1306 $scope.net_access_levels = prs.net_access_levels;
1307 $scope.user_setting_types = prs.user_setting_types;
1308 $scope.opt_in_setting_types = prs.opt_in_setting_types;
1309 $scope.org_settings = prs.org_settings;
1310 $scope.sms_carriers = prs.sms_carriers;
1311 $scope.stat_cats = prs.stat_cats;
1312 $scope.surveys = prs.surveys;
1313 $scope.survey_responses = prs.survey_responses;
1314 $scope.stat_cat_entry_maps = prs.stat_cat_entry_maps;
1315 $scope.stage_user = prs.stage_user;
1316 $scope.stage_user_requestor = prs.stage_user_requestor;
1318 $scope.user_settings = prs.user_settings;
1319 prs.user_settings = {};
1321 // If a default pickup lib is applied to the patron, apply it
1322 // to the UI at page load time. Otherwise, leave the value unset.
1323 if ($scope.user_settings['opac.default_pickup_location']) {
1324 $scope.patron._pickup_lib = egCore.org.get(
1325 $scope.user_settings['opac.default_pickup_location']);
1328 extract_hold_notify();
1329 if ($scope.patron.isnew)
1330 set_new_patron_defaults(prs);
1332 $scope.handle_home_org_changed();
1334 if ($scope.org_settings['ui.patron.edit.default_suggested'])
1335 $scope.edit_passthru.vis_level = 1;
1337 // Stat cats are fetched from open-ils.storage, where 't'==1
1338 $scope.hasRequiredStatCat = prs.stat_cats.filter(
1339 function(cat) {return cat.required() == 1} ).length > 0;
1341 $scope.page_data_loaded = true;
1343 prs.set_field_patterns(field_patterns);
1344 apply_username_regex();
1346 add_date_watchers();
1349 function add_date_watchers() {
1351 $scope.$watch('patron.dob', function(newVal, oldVal) {
1352 // Even though this runs after page data load, there
1353 // are still times when it fires unnecessarily.
1354 if (newVal === oldVal) return;
1356 console.debug('dob change: ' + newVal + ' : ' + oldVal);
1357 maintain_juvenile_flag();
1360 // No need to watch expire_date
1364 // update the currently displayed field documentation
1365 $scope.set_selected_field_doc = function(cls, field) {
1366 $scope.selected_field_doc = $scope.field_doc[cls][field];
1369 // returns the tree depth of the selected profile group tree node.
1370 $scope.pgt_depth = function(grp) {
1372 while (grp = egCore.env.pgt.map[grp.parent()]) d++;
1376 // returns the tree depth of the selected profile group tree node.
1377 $scope.pgtde_depth = function(entry) {
1379 while (entry = egCore.env.pgtde.map[entry.parent()]) d++;
1383 // IDL fields used for labels in the UI.
1384 $scope.idl_fields = {
1385 au : egCore.idl.classes.au.field_map,
1386 ac : egCore.idl.classes.ac.field_map,
1387 aua : egCore.idl.classes.aua.field_map
1390 // field visibility cache. Some fields are universally required.
1391 // 3 == value universally required
1392 // 2 == field is visible by default
1393 // 1 == field is suggested by default
1394 var field_visibility = {};
1395 var default_field_visibility = {
1399 'au.first_given_name' : 3,
1400 'au.family_name' : 3,
1401 'au.ident_type' : 3,
1402 'au.ident_type2' : 2,
1405 'au.expire_date' : 3,
1406 'au.net_access_level' : 3,
1407 'aua.address_type' : 3,
1408 'aua.post_code' : 3,
1416 'aua.within_city_limits' : 2,
1421 // Returns true if the selected field should be visible
1422 // given the current required/suggested/all setting.
1423 // The visibility flag applied to each field as a result of calling
1424 // this function also sets (via the same flag) the requiredness state.
1425 $scope.show_field = function(field_key) {
1426 // org settings have not been received yet.
1427 if (!$scope.org_settings) return false;
1429 if (field_visibility[field_key] == undefined) {
1430 // compile and cache the visibility for the selected field
1432 var req_set = 'ui.patron.edit.' + field_key + '.require';
1433 var sho_set = 'ui.patron.edit.' + field_key + '.show';
1434 var sug_set = 'ui.patron.edit.' + field_key + '.suggest';
1436 if ($scope.org_settings[req_set]) {
1437 field_visibility[field_key] = 3;
1439 } else if ($scope.org_settings[sho_set]) {
1440 field_visibility[field_key] = 2;
1442 } else if ($scope.org_settings[sug_set]) {
1443 field_visibility[field_key] = 1;
1447 if (field_visibility[field_key] == undefined) {
1448 // No org settings were applied above. Use the default
1449 // settings if present or assume the field has no
1450 // visibility flags applied.
1451 field_visibility[field_key] =
1452 default_field_visibility[field_key] || 0;
1455 return field_visibility[field_key] >= $scope.edit_passthru.vis_level;
1458 // See $scope.show_field().
1459 // A field with visbility level 3 means it's required.
1460 $scope.field_required = function(cls, field) {
1462 // Value in the password field is not required
1463 // for existing patrons.
1464 if (field == 'passwd' && $scope.patron && !$scope.patron.isnew)
1467 return (field_visibility[cls + '.' + field] == 3);
1470 // generates a random 4-digit password
1471 $scope.generate_password = function() {
1472 $scope.patron.passwd = Math.floor(Math.random()*9000) + 1000;
1475 $scope.set_expire_date = function() {
1476 if (!$scope.patron.profile) return;
1477 var seconds = egCore.date.intervalToSeconds(
1478 $scope.patron.profile.perm_interval());
1479 var now_epoch = new Date().getTime();
1480 $scope.patron.expire_date = new Date(
1481 now_epoch + (seconds * 1000 /* milliseconds */))
1482 $scope.field_modified();
1485 // grp is the pgt object
1486 $scope.set_profile = function(grp) {
1487 $scope.patron.profile = grp;
1488 $scope.set_expire_date();
1489 $scope.field_modified();
1492 $scope.invalid_profile = function() {
1495 $scope.patron.profile &&
1496 $scope.patron.profile.usergroup() == 't'
1500 $scope.new_address = function() {
1501 var addr = egCore.idl.toHash(new egCore.idl.aua());
1502 patronRegSvc.ingest_address($scope.patron, addr);
1503 addr.id = patronRegSvc.virt_id--;
1506 addr.within_city_limits = true;
1507 addr.country = $scope.org_settings['ui.patron.default_country'];
1508 $scope.patron.addresses.push(addr);
1511 // keep deleted addresses out of the patron object so
1512 // they won't appear in the UI. They'll be re-inserted
1513 // when the patron is updated.
1514 deleted_addresses = [];
1515 $scope.delete_address = function(id) {
1517 if ($scope.patron.isnew &&
1518 $scope.patron.addresses.length == 1 &&
1519 $scope.org_settings['ui.patron.registration.require_address']) {
1520 egAlertDialog.open(egCore.strings.REG_ADDR_REQUIRED);
1525 angular.forEach($scope.patron.addresses, function(addr) {
1526 if (addr.id == id) {
1528 addr.isdeleted = true;
1529 deleted_addresses.push(addr);
1532 addresses.push(addr);
1535 $scope.patron.addresses = addresses;
1538 $scope.post_code_changed = function(addr) {
1540 'open-ils.search', 'open-ils.search.zip', addr.post_code)
1541 .then(function(resp) {
1543 if (resp.city) addr.city = resp.city;
1544 if (resp.state) addr.state = resp.state;
1545 if (resp.county) addr.county = resp.county;
1546 if (resp.alert) alert(resp.alert);
1550 $scope.replace_card = function() {
1551 $scope.patron.card.active = false;
1552 $scope.patron.card.ischanged = true;
1553 $scope.disable_bc = false;
1555 var new_card = egCore.idl.toHash(new egCore.idl.ac());
1556 new_card.id = patronRegSvc.virt_id--;
1557 new_card.isnew = true;
1558 new_card.active = true;
1559 new_card._primary = 'on';
1560 $scope.patron.card = new_card;
1562 // Remove any previous attempts to replace the card, since they
1563 // may be incomplete or created by accident.
1564 $scope.patron.cards =
1565 $scope.patron.cards.filter(function(c) {return !c.isnew})
1566 $scope.patron.cards.push(new_card);
1569 $scope.day_phone_changed = function(phone) {
1570 if (phone && $scope.patron.isnew &&
1571 $scope.org_settings['patron.password.use_phone']) {
1572 $scope.patron.passwd = phone.substr(-4);
1576 $scope.barcode_changed = function(bc) {
1578 $scope.dupe_barcode = false;
1581 'open-ils.actor.barcode.exists',
1582 egCore.auth.token(), bc
1583 ).then(function(resp) {
1584 if (resp == '1') { // duplicate card
1585 $scope.dupe_barcode = true;
1586 console.log('duplicate barcode detected: ' + bc);
1588 if (!$scope.patron.usrname)
1589 $scope.patron.usrname = bc;
1595 $scope.cards_dialog = function() {
1597 templateUrl: './circ/patron/t_patron_cards_dialog',
1600 ['$scope','$uibModalInstance','cards','perms',
1601 function($scope , $uibModalInstance , cards , perms) {
1602 // scope here is the modal-level scope
1603 $scope.args = {cards : cards};
1604 $scope.perms = perms;
1605 $scope.ok = function() { $uibModalInstance.close($scope.args) }
1606 $scope.cancel = function () { $uibModalInstance.dismiss() }
1609 cards : function() {
1610 // scope here is the controller-level scope
1611 return $scope.patron.cards;
1613 perms : function() {
1614 return $scope.perms;
1619 angular.forEach(args.cards, function(card) {
1620 card.ischanged = true; // assume cards need updating, OK?
1621 if (card._primary == 'on' &&
1622 card.id != $scope.patron.card.id) {
1623 $scope.patron.card = card;
1630 $scope.set_addr_type = function(addr, type) {
1631 var addrs = $scope.patron.addresses;
1632 if (addr['_is_'+type]) {
1633 angular.forEach(addrs, function(a) {
1634 if (a.id != addr.id) a['_is_'+type] = false;
1637 // unchecking mailing/billing means we have to randomly
1638 // select another address to fill that role. Select the
1639 // first address in the list (that does not match the
1641 for (var i = 0; i < addrs.length; i++) {
1642 if (addrs[i].id != addr.id) {
1643 addrs[i]['_is_' + type] = true;
1651 // Translate hold notify preferences from the form/scope back into a
1652 // single user setting value for opac.hold_notify.
1653 function compress_hold_notify() {
1654 var hold_notify_methods = [];
1655 if ($scope.hold_notify_type.phone) {
1656 hold_notify_methods.push('phone');
1658 if ($scope.hold_notify_type.email) {
1659 hold_notify_methods.push('email');
1661 if ($scope.hold_notify_type.sms) {
1662 hold_notify_methods.push('sms');
1665 $scope.user_settings['opac.hold_notify'] = hold_notify_methods.join(':');
1668 // dialog for selecting additional permission groups
1669 $scope.secondary_groups_dialog = function() {
1671 templateUrl: './circ/patron/t_patron_groups_dialog',
1674 ['$scope','$uibModalInstance','linked_groups','pgt_depth',
1675 function($scope , $uibModalInstance , linked_groups , pgt_depth) {
1677 $scope.pgt_depth = pgt_depth;
1679 linked_groups : linked_groups,
1680 edit_profiles : patronRegSvc.edit_profiles,
1681 new_profile : patronRegSvc.edit_profiles[0]
1684 // add a new group to the linked groups list
1685 $scope.link_group = function($event, grp) {
1686 var found = false; // avoid duplicates
1687 angular.forEach($scope.args.linked_groups,
1688 function(g) {if (g.id() == grp.id()) found = true});
1689 if (!found) $scope.args.linked_groups.push(grp);
1690 $event.preventDefault(); // avoid close
1693 // remove a group from the linked groups list
1694 $scope.unlink_group = function($event, grp) {
1695 $scope.args.linked_groups =
1696 $scope.args.linked_groups.filter(function(g) {
1697 return g.id() != grp.id()
1699 $event.preventDefault(); // avoid close
1702 $scope.ok = function() { $uibModalInstance.close($scope.args) }
1703 $scope.cancel = function () { $uibModalInstance.dismiss() }
1706 linked_groups : function() { return $scope.patron.groups },
1707 pgt_depth : function() { return $scope.pgt_depth }
1712 if ($scope.patron.isnew) {
1713 // groups must be linked for new patrons after the
1714 // patron is created.
1715 $scope.patron.groups = args.linked_groups;
1719 // update links groups for existing users in real time.
1720 var ids = args.linked_groups.map(function(g) {return g.id()});
1721 patronRegSvc.apply_secondary_groups($scope.patron.id, ids)
1722 .then(function(success) {
1724 $scope.patron.groups = args.linked_groups;
1730 function extract_hold_notify() {
1731 var notify = $scope.user_settings['opac.hold_notify'];
1732 if (!notify) return;
1733 $scope.hold_notify_type.phone = Boolean(notify.match(/phone/));
1734 $scope.hold_notify_type.email = Boolean(notify.match(/email/));
1735 $scope.hold_notify_type.sms = Boolean(notify.match(/sms/));
1738 $scope.invalidate_field = function(field) {
1739 patronRegSvc.invalidate_field($scope.patron, field);
1742 address_alert = function(addr) {
1744 street1: addr.street1,
1745 street2: addr.street2,
1748 county: addr.county,
1749 country: addr.country,
1750 post_code: addr.post_code,
1751 mailing_address: addr._is_mailing,
1752 billing_address: addr._is_billing
1757 'open-ils.actor.address_alert.test',
1758 egCore.auth.token(), egCore.auth.user().ws_ou(), args
1759 ).then(function(res) {
1760 $scope.address_alerts = res;
1764 $scope.dupe_value_changed = function(type, value) {
1765 if (!$scope.dupe_search_encoded)
1766 $scope.dupe_search_encoded = {};
1768 $scope.dupe_counts[type] = 0;
1770 patronRegSvc.dupe_patron_search($scope.patron, type, value)
1771 .then(function(res) {
1772 $scope.dupe_counts[type] = res.count;
1774 $scope.dupe_search_encoded[type] =
1775 encodeURIComponent(js2JSON(res.search));
1777 $scope.dupe_search_encoded[type] = '';
1782 $scope.handle_home_org_changed = function() {
1783 org_id = $scope.patron.home_ou.id();
1784 patronRegSvc.has_perms_for_org(org_id).then(function(map) {
1785 angular.forEach(map, function(v, k) { $scope.perms[k] = v });
1789 $scope.handle_pulib_changed = function(org) {
1790 if (!$scope.user_settings) return; // still rendering
1791 $scope.user_settings['opac.default_pickup_location'] = org.id();
1794 // This is called with every character typed in a form field,
1795 // since that's the only way to gaurantee something has changed.
1796 // See handle_field_changed for ng-change vs. ng-blur.
1797 $scope.field_modified = function() {
1798 // Call attach with every field change, regardless of whether
1799 // it's been called before. This will allow for re-attach after
1800 // the user clicks through the unload warning. egUnloadPrompt
1801 // will ensure we only attach once.
1802 egUnloadPrompt.attach($scope);
1805 // also monitor when form is changed *by the user*, as using
1806 // an ng-change handler doesn't work with eg-date-input
1807 $scope.$watch('reg_form.$pristine', function(newVal, oldVal) {
1808 if (!newVal) egUnloadPrompt.attach($scope);
1811 // username regex (if present) must be removed any time
1812 // the username matches the barcode to avoid firing the
1813 // invalid field handlers.
1814 function apply_username_regex() {
1815 var regex = $scope.org_settings['opac.username_regex'];
1817 if ($scope.patron.card.barcode) {
1818 // username must match the regex or the barcode
1819 field_patterns.au.usrname =
1821 regex + '|^' + $scope.patron.card.barcode + '$');
1823 // username must match the regex
1824 field_patterns.au.usrname = new RegExp(regex);
1827 // username can be any format.
1828 field_patterns.au.usrname = new RegExp('.*');
1832 // obj could be the patron, an address, etc.
1833 // This is called any time a form field achieves then loses focus.
1834 // It does not necessarily mean the field has changed.
1835 // The alternative is ng-change, but it's called with each character
1836 // typed, which would be overkill for many of the actions called here.
1837 $scope.handle_field_changed = function(obj, field_name) {
1838 var cls = obj.classname; // set by egIdl
1839 var value = obj[field_name];
1841 console.debug('changing field ' + field_name + ' to ' + value);
1843 switch (field_name) {
1845 if ($scope.patron.day_phone &&
1846 $scope.patron.isnew &&
1847 $scope.org_settings['patron.password.use_phone']) {
1848 $scope.patron.passwd = $scope.patron.day_phone.substr(-4);
1850 case 'evening_phone' :
1851 case 'other_phone' :
1852 $scope.dupe_value_changed(field_name, value);
1856 case 'ident_value2':
1857 $scope.dupe_value_changed('ident', value);
1860 case 'first_given_name':
1862 $scope.dupe_value_changed('name', value);
1866 $scope.dupe_value_changed('email', value);
1872 // dupe search on address wants the address object as the value.
1873 $scope.dupe_value_changed('address', obj);
1878 $scope.post_code_changed(obj);
1882 patronRegSvc.check_dupe_username(value)
1883 .then(function(yes) {$scope.dupe_username = Boolean(yes)});
1887 // TODO: finish barcode_changed handler.
1888 $scope.barcode_changed(value);
1889 apply_username_regex();
1894 // patron.juvenile is set to true if the user was born after
1895 function maintain_juvenile_flag() {
1896 if ( !($scope.patron && $scope.patron.dob) ) return;
1899 $scope.org_settings['global.juvenile_age_threshold']
1902 var base = new Date();
1904 base.setTime(base.getTime() -
1905 Number(egCore.date.intervalToSeconds(juv_interval) + '000'));
1907 $scope.patron.juvenile = ($scope.patron.dob > base);
1910 // returns true (disable) for orgs that cannot have users.
1911 $scope.disable_home_org = function(org_id) {
1912 if (!org_id) return;
1913 var org = egCore.org.get(org_id);
1917 org.ou_type().can_have_users() == 'f'
1921 // returns true (disable) for orgs that cannot have vols (for holds pickup)
1922 $scope.disable_pulib = function(org_id) {
1923 if (!org_id) return;
1924 return !egCore.org.CanHaveVolumes(org_id);
1927 // Returns true if the Save and Save & Clone buttons should be disabled.
1928 $scope.edit_passthru.hide_save_actions = function() {
1929 return $scope.patron.isnew ?
1930 !$scope.perms.CREATE_USER :
1931 !$scope.perms.UPDATE_USER;
1934 // Returns true if any input elements are tagged as invalid
1935 // via Angular patterns or required attributes.
1936 function form_has_invalid_fields() {
1937 return $('#patron-reg-container .ng-invalid').length > 0;
1940 function form_is_incomplete() {
1942 $scope.dupe_username ||
1943 $scope.dupe_barcode ||
1944 form_has_invalid_fields()
1949 $scope.edit_passthru.save = function(save_args) {
1950 if (!save_args) save_args = {};
1952 if (form_is_incomplete()) {
1953 // User has not provided valid values for all required fields.
1954 return egAlertDialog.open(egCore.strings.REG_INVALID_FIELDS);
1957 // remove page unload warning prompt
1958 egUnloadPrompt.clear();
1960 // toss the deleted addresses back into the patron's list of
1961 // addresses so it's included in the update
1962 $scope.patron.addresses =
1963 $scope.patron.addresses.concat(deleted_addresses);
1965 compress_hold_notify();
1969 patronRegSvc.save_user($scope.patron)
1970 .then(function(new_user) {
1971 if (new_user && new_user.classname) {
1972 updated_user = new_user;
1973 return patronRegSvc.save_user_settings(
1974 new_user, $scope.user_settings);
1976 var evt = egCore.evt.parse(new_user);
1978 if (evt && evt.textcode == 'XACT_COLLISION') {
1979 return egAlertDialog.open(
1980 egCore.strings.PATRON_EDIT_COLLISION).result;
1983 // debug only -- should not get here.
1984 alert('Patron update failed. \n\n' + js2JSON(new_user));
1987 }).then(function() {
1989 // only remove the staged user if the update succeeded.
1991 return patronRegSvc.remove_staged_user();
1995 }).then(function() {
1997 // linked groups for new users must be created after the new
1999 if ($scope.patron.isnew &&
2000 $scope.patron.groups && $scope.patron.groups.length) {
2001 var ids = $scope.patron.groups.map(function(g) {return g.id()});
2002 return patronRegSvc.apply_secondary_groups(updated_user.id(), ids)
2007 }).then(function() {
2012 ? egCore.strings.EG_WORK_LOG_REGISTERED_PATRON
2013 : egCore.strings.EG_WORK_LOG_EDITED_PATRON, {
2014 'action' : $scope.patron.isnew ? 'registered_patron' : 'edited_patron',
2015 'patron_id' : updated_user.id()
2020 // reloading the page means potentially losing some information
2021 // (e.g. last patron search), but is the only way to ensure all
2022 // components are properly updated to reflect the modified patron.
2023 if (updated_user && save_args.clone) {
2024 // open a separate tab for registering a new
2025 // patron from our cloned data.
2026 var url = 'https://'
2027 + $window.location.hostname
2028 + egCore.env.basePath
2029 + '/circ/patron/register/clone/'
2030 + updated_user.id();
2031 $window.open(url, '_blank').focus();
2034 // reload the current page
2035 $window.location.href = location.href;
2040 $scope.edit_passthru.print = function() {
2041 var print_data = {patron : $scope.patron}
2043 return egCore.print.print({
2044 context : 'default',
2045 template : 'patron_data',