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 'circ.privacy_waiver',
338 'ui.patron.edit.au.prefix.require',
339 'ui.patron.edit.au.prefix.show',
340 'ui.patron.edit.au.prefix.suggest',
341 'ui.patron.edit.ac.barcode.regex',
342 'ui.patron.edit.au.second_given_name.show',
343 'ui.patron.edit.au.second_given_name.suggest',
344 'ui.patron.edit.au.suffix.show',
345 'ui.patron.edit.au.suffix.suggest',
346 'ui.patron.edit.au.alias.show',
347 'ui.patron.edit.au.alias.suggest',
348 'ui.patron.edit.au.dob.require',
349 'ui.patron.edit.au.dob.show',
350 'ui.patron.edit.au.dob.suggest',
351 'ui.patron.edit.au.dob.calendar',
352 'ui.patron.edit.au.dob.example',
353 'ui.patron.edit.au.juvenile.show',
354 'ui.patron.edit.au.juvenile.suggest',
355 'ui.patron.edit.au.ident_value.show',
356 'ui.patron.edit.au.ident_value.require',
357 'ui.patron.edit.au.ident_value.suggest',
358 'ui.patron.edit.au.ident_value2.show',
359 'ui.patron.edit.au.ident_value2.suggest',
360 'ui.patron.edit.au.email.require',
361 'ui.patron.edit.au.email.show',
362 'ui.patron.edit.au.email.suggest',
363 'ui.patron.edit.au.email.regex',
364 'ui.patron.edit.au.email.example',
365 'ui.patron.edit.au.day_phone.require',
366 'ui.patron.edit.au.day_phone.show',
367 'ui.patron.edit.au.day_phone.suggest',
368 'ui.patron.edit.au.day_phone.regex',
369 'ui.patron.edit.au.day_phone.example',
370 'ui.patron.edit.au.evening_phone.require',
371 'ui.patron.edit.au.evening_phone.show',
372 'ui.patron.edit.au.evening_phone.suggest',
373 'ui.patron.edit.au.evening_phone.regex',
374 'ui.patron.edit.au.evening_phone.example',
375 'ui.patron.edit.au.other_phone.require',
376 'ui.patron.edit.au.other_phone.show',
377 'ui.patron.edit.au.other_phone.suggest',
378 'ui.patron.edit.au.other_phone.regex',
379 'ui.patron.edit.au.other_phone.example',
380 'ui.patron.edit.phone.regex',
381 'ui.patron.edit.phone.example',
382 'ui.patron.edit.au.active.show',
383 'ui.patron.edit.au.active.suggest',
384 'ui.patron.edit.au.barred.show',
385 'ui.patron.edit.au.barred.suggest',
386 'ui.patron.edit.au.master_account.show',
387 'ui.patron.edit.au.master_account.suggest',
388 'ui.patron.edit.au.claims_returned_count.show',
389 'ui.patron.edit.au.claims_returned_count.suggest',
390 'ui.patron.edit.au.claims_never_checked_out_count.show',
391 'ui.patron.edit.au.claims_never_checked_out_count.suggest',
392 'ui.patron.edit.au.alert_message.show',
393 'ui.patron.edit.au.alert_message.suggest',
394 'ui.patron.edit.aua.post_code.regex',
395 'ui.patron.edit.aua.post_code.example',
396 'ui.patron.edit.aua.county.require',
397 'ui.patron.edit.au.guardian.show',
398 'ui.patron.edit.au.guardian.suggest',
399 'ui.patron.edit.guardian_required_for_juv',
401 'ui.patron.edit.default_suggested',
402 'opac.barcode_regex',
403 'opac.username_regex',
405 'ui.patron.edit.aua.state.require',
406 'ui.patron.edit.aua.state.suggest',
407 'ui.patron.edit.aua.state.show',
408 'ui.admin.work_log.max_entries',
409 'ui.admin.patron_log.max_entries'
410 ]).then(function(settings) {
411 service.org_settings = settings;
412 if (egCore && egCore.env && !egCore.env.aous) {
413 egCore.env.aous = settings;
414 console.log('setting egCore.env.aous');
416 return service.process_org_settings(settings);
420 // some org settings require the retrieval of additional data
421 service.process_org_settings = function(settings) {
423 var promises = [egLovefield.setSettingsCache(settings)];
425 if (settings['sms.enable']) {
426 // fetch SMS carriers
428 egCore.pcrud.search('csc',
431 {'class':'csc', 'field':'name'},
432 {'class':'csc', 'field':'region'}
434 ).then(function(carriers) {
435 service.sms_carriers = carriers;
439 // if other promises are added below, this is not necessary.
440 promises.push($q.when());
443 // other post-org-settings processing goes here,
444 // adding to promises as needed.
446 return $q.all(promises);
449 service.get_ident_types = function() {
450 if (egCore.env.cit) {
451 service.ident_types = egCore.env.cit.list;
454 return egCore.pcrud.retrieveAll('cit', {}, {atomic : true})
455 .then(function(types) {
456 egCore.env.absorbList(types, 'cit')
457 service.ident_types = types
462 service.get_net_access_levels = function() {
463 if (egCore.env.cnal) {
464 service.net_access_levels = egCore.env.cnal.list;
467 return egCore.pcrud.retrieveAll('cnal', {}, {atomic : true})
468 .then(function(levels) {
469 egCore.env.absorbList(levels, 'cnal')
470 service.net_access_levels = levels
475 service.get_perm_groups = function() {
476 if (egCore.env.pgt) {
477 service.profiles = egCore.env.pgt.list;
478 return service.set_edit_profiles();
480 return egCore.pcrud.search('pgt', {parent : null},
481 {flesh : -1, flesh_fields : {pgt : ['children']}}
484 egCore.env.absorbTree(tree, 'pgt')
485 service.profiles = egCore.env.pgt.list;
486 return service.set_edit_profiles();
492 service.searchPermGroupEntries = function(org) {
493 return egCore.pcrud.search('pgtde', {org: org, parent: null},
494 {flesh: -1, flesh_fields: {pgtde: ['grp', 'children']}}, {atomic: true}
495 ).then(function(treeArray) {
496 if (!treeArray.length && egCore.org.get(org).parent_ou()) {
497 return service.searchPermGroupEntries(egCore.org.get(org).parent_ou());
503 service.get_perm_group_entries = function() {
504 if (egCore.env.pgtde) {
505 service.profile_entries = egCore.env.pgtde.list;
506 return service.set_edit_profile_entries();
508 return service.searchPermGroupEntries(egCore.auth.user().ws_ou()).then(function(treeArray) {
509 function compare(a,b) {
510 if (a.position() > b.position())
512 if (a.position() < b.position())
518 function squash(node) {
519 node.children().sort(compare);
521 angular.forEach(node.children(), squash);
524 angular.forEach(treeArray, squash);
525 var blob = egCore.env.absorbList(list, 'pgtde');
526 blob.tree = treeArray;
528 service.profile_entries = egCore.env.pgtde.list;
529 return service.set_edit_profile_entries();
534 service.get_field_doc = function() {
536 return egCore.pcrud.search('fdoc', {
537 fm_class: ['au', 'ac', 'aua', 'actsc', 'asv', 'asvq', 'asva']})
540 return egLovefield.setListInOfflineCache('fdoc', to_cache)
544 if (!service.field_doc[doc.fm_class()]) {
545 service.field_doc[doc.fm_class()] = {};
547 service.field_doc[doc.fm_class()][doc.field()] = doc;
554 service.get_user_setting_types = function() {
556 // No need to re-fetch the common setting types.
557 if (Object.keys(service.user_setting_types).length)
560 var org_ids = egCore.org.ancestors(egCore.auth.user().ws_ou(), true);
563 'circ.holds_behind_desk',
564 'circ.collections.exempt',
566 'opac.default_phone',
567 'opac.default_pickup_location',
568 'opac.default_sms_carrier',
569 'opac.default_sms_notify'];
571 return egCore.pcrud.search('cust', {
573 {name : static_types}, // common user settings
574 {name : { // opt-in notification user settings
576 select : {atevdef : ['opt_in_setting']},
578 // we only care about opt-in settings for
579 // event_defs our users encounter
580 where : {'+atevdef' : {owner : org_ids}}
584 }, {}, {atomic : true}).then(function(setting_types) {
586 egCore.env.absorbList(setting_types, 'cust'); // why not...
588 angular.forEach(setting_types, function(stype) {
589 service.user_setting_types[stype.name()] = stype;
590 if (static_types.indexOf(stype.name()) == -1) {
591 service.opt_in_setting_types[stype.name()] = stype;
597 service.get_user_settings = function() {
599 return service.get_user_setting_types()
602 var setting_types = Object.values(service.user_setting_types);
604 if (service.patron_id) {
605 // retrieve applied values for the current user
606 // for the setting types we care about.
609 setting_types.map(function(obj) { return obj.name() });
611 return egCore.net.request(
613 'open-ils.actor.patron.settings.retrieve.authoritative',
617 ).then(function(settings) {
618 service.user_settings = settings;
623 // apply default user setting values
624 angular.forEach(setting_types, function(stype, index) {
625 if (stype.reg_default() != undefined) {
626 var val = stype.reg_default();
627 if (stype.datatype() == 'bool') {
628 // A boolean user setting type whose default
629 // value starts with t/T is considered 'true',
631 val = Boolean((val+'').match(/^t/i));
633 service.user_settings[stype.name()] = val;
640 service.invalidate_field = function(patron, field) {
641 console.log('Invalidating patron field ' + field);
643 return egCore.net.request(
645 'open-ils.actor.invalidate.' + field,
646 egCore.auth.token(), patron.id, null, patron.home_ou.id()
648 ).then(function(res) {
649 // clear the invalid value from the form
652 // update last_xact_id so future save operations
653 // on this patron will be allowed
654 patron.last_xact_id = res.payload.last_xact_id[patron.id];
658 service.dupe_patron_search = function(patron, type, value) {
661 console.log('Dupe search called with "'+ type +'" and value '+ value);
663 if (type.match(/phone/)) type = 'phone'; // day_phone, etc.
668 var fname = patron.first_given_name;
669 var lname = patron.family_name;
670 if (!(fname && lname)) return $q.when({count:0});
672 first_given_name : {value : fname, group : 0},
673 family_name : {value : lname, group : 0}
678 search = {email : {value : value, group : 0}};
682 search = {ident : {value : value, group : 2}};
686 search = {phone : {value : value, group : 2}};
691 angular.forEach(['street1', 'street2', 'city', 'post_code'],
694 search[field] = {value : value[field], group: 1};
700 return egCore.net.request(
702 'open-ils.actor.patron.search.advanced',
703 egCore.auth.token(), search, null, null, 1
704 ).then(function(res) {
705 res = res.filter(function(id) {return id != patron.id});
713 service.init_patron = function(current) {
716 return $q.when(service.init_new_patron());
718 service.patron = current;
719 return $q.when(service.init_existing_patron(current));
722 service.ingest_address = function(patron, addr) {
723 addr.valid = addr.valid == 't';
724 addr.within_city_limits = addr.within_city_limits == 't';
725 addr._is_mailing = (patron.mailing_address &&
726 addr.id == patron.mailing_address.id);
727 addr._is_billing = (patron.billing_address &&
728 addr.id == patron.billing_address.id);
729 addr.pending = addr.pending === 't';
732 service.ingest_waiver_entry = function(patron, waiver_entry) {
733 waiver_entry.place_holds = waiver_entry.place_holds == 't';
734 waiver_entry.pickup_holds = waiver_entry.pickup_holds == 't';
735 waiver_entry.view_history = waiver_entry.view_history == 't';
736 waiver_entry.checkout_items = waiver_entry.checkout_items == 't';
740 * Existing patron objects reqire some data munging before insertion
743 * 1. Turn everything into a hash
744 * 2. ... Except certain fields (selectors) whose widgets require objects
745 * 3. Bools must be Boolean, not t/f.
747 service.init_existing_patron = function(current) {
749 service.existing_patron = current;
751 var patron = egCore.idl.toHash(current);
753 patron.home_ou = egCore.org.get(patron.home_ou.id);
754 patron.expire_date = new Date(Date.parse(patron.expire_date));
755 patron.dob = service.parse_dob(patron.dob);
756 patron.profile = current.profile(); // pre-hash version
757 patron.net_access_level = current.net_access_level();
758 patron.ident_type = current.ident_type();
759 patron.ident_type2 = current.ident_type2();
760 patron.groups = current.groups(); // pre-hash
763 ['juvenile', 'barred', 'active', 'master_account'],
764 function(field) { patron[field] = patron[field] == 't'; }
767 angular.forEach(patron.cards, function(card) {
768 card.active = card.active == 't';
769 if (card.id == patron.card.id) {
771 card._primary = true;
775 angular.forEach(patron.addresses,
776 function(addr) { service.ingest_address(patron, addr) });
778 // Link replaced address to its pending address.
779 angular.forEach(patron.addresses, function(addr) {
781 addr._replaces = patron.addresses.filter(
782 function(a) {return a.id == addr.replaces})[0];
786 angular.forEach(patron.waiver_entries,
787 function(waiver_entry) { service.ingest_waiver_entry(patron, waiver_entry) });
789 service.get_linked_addr_users(patron.addresses);
791 // Remove stat cat entries that link to out-of-scope stat
792 // cats. With this, we avoid unnecessarily updating (or worse,
793 // modifying) stat cat values that are not ours to modify.
794 patron.stat_cat_entries = patron.stat_cat_entries.filter(
797 // service.stat_cats only contains in-scope stat cats.
798 service.stat_cats.filter(function(cat) {
799 return (cat.id() == map.stat_cat.id) })[0]
804 // toss entries for existing stat cat maps into our living
805 // stat cat entry map, which is modified within the template.
806 angular.forEach(patron.stat_cat_entries, function(map) {
807 service.stat_cat_entry_maps[map.stat_cat.id] = map.stat_cat_entry;
810 service.patron = patron;
814 service.init_new_patron = function() {
816 id : service.virt_id--,
819 address_type : egCore.strings.REG_ADDR_TYPE,
822 within_city_limits : false,
823 country : service.org_settings['ui.patron.default_country'],
827 id : service.virt_id--,
838 home_ou : egCore.org.get(egCore.auth.user().ws_ou()),
839 stat_cat_entries : [],
845 if (service.clone_user)
846 service.copy_clone_data(user);
848 if (service.stage_user)
849 service.copy_stage_data(user);
854 // dob is always YYYY-MM-DD
855 // Dates of birth do not contain timezone info, which can lead to
856 // inconcistent timezone handling, potentially representing
857 // different points in time, depending on the implementation.
858 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
859 // See "Differences in assumed time zone"
860 // TODO: move this into egDate ?
861 service.parse_dob = function(dob) {
862 if (!dob) return null;
863 var parts = dob.split('-');
864 return new Date(parts[0], parts[1] - 1, parts[2])
867 service.copy_stage_data = function(user) {
868 var cuser = service.stage_user;
870 // copy the data into our new user object
872 for (var key in egCore.idl.classes.stgu.field_map) {
873 if (egCore.idl.classes.au.field_map[key] &&
874 !egCore.idl.classes.stgu.field_map[key].virtual) {
875 if (cuser.user[key]() !== null)
876 user[key] = cuser.user[key]();
880 if (user.home_ou) user.home_ou = egCore.org.get(user.home_ou);
881 if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
883 user.ident_type = egCore.env.cit.map[user.ident_type];
884 if (user.ident_type2)
885 user.ident_type2 = egCore.env.cit.map[user.ident_type2];
886 user.dob = service.parse_dob(user.dob);
888 // Clear the usrname if it looks like a UUID
889 if (user.usrname.replace(/-/g,'').match(/[0-9a-f]{32}/))
892 // Don't use stub address if we have one from the staged user.
893 if (cuser.mailing_addresses.length || cuser.billing_addresses.length)
896 // is_mailing=false implies is_billing
897 function addr_from_stage(stage_addr) {
898 if (!stage_addr) return;
899 var cls = stage_addr.classname;
902 id : service.virt_id--,
906 address_type : egCore.strings.REG_ADDR_TYPE,
907 _is_mailing : cls == 'stgma',
908 _is_billing : cls == 'stgba'
911 user.mailing_address = addr;
912 user.addresses.push(addr);
914 for (var key in egCore.idl.classes[cls].field_map) {
915 if (egCore.idl.classes.aua.field_map[key] &&
916 !egCore.idl.classes[cls].field_map[key].virtual) {
917 if (stage_addr[key]() !== null)
918 addr[key] = stage_addr[key]();
923 addr_from_stage(cuser.mailing_addresses[0]);
924 addr_from_stage(cuser.billing_addresses[0]);
926 if (user.addresses.length == 1) {
927 // If there is only one address,
928 // use it as both mailing and billing.
929 var addr = user.addresses[0];
930 addr._is_mailing = addr._is_billing = true;
931 user.mailing_address = user.billing_address = addr;
934 if (cuser.cards.length) {
936 id : service.virt_id--,
937 barcode : cuser.cards[0].barcode(),
943 user.cards.push(user.card);
944 if (user.usrname == '')
945 user.usrname = card.barcode;
948 angular.forEach(cuser.settings, function(setting) {
949 service.user_settings[setting.setting()] = Boolean(setting.value());
953 // copy select values from the cloned user to the new user.
955 service.copy_clone_data = function(user) {
956 var clone_user = service.clone_user;
958 // flesh the home org locally
959 user.home_ou = egCore.org.get(clone_user.home_ou());
960 if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
962 if (!clone_user.billing_address() &&
963 !clone_user.mailing_address())
964 return; // no addresses to copy or link
966 // if the cloned user has any addresses, we don't need
967 // the stub address created in init_new_patron.
971 service.org_settings['circ.patron_edit.clone.copy_address'];
980 angular.forEach(clone_fields, function(field) {
981 user[field] = clone_user[field]();
984 if (copy_addresses) {
985 var bill_addr, mail_addr;
987 // copy the billing and mailing addresses into new addresses
988 function clone_addr(addr) {
989 var new_addr = egCore.idl.toHash(addr);
990 new_addr.id = service.virt_id--;
991 new_addr.usr = user.id;
992 new_addr.isnew = true;
993 new_addr.valid = true;
994 user.addresses.push(new_addr);
998 if (bill_addr = clone_user.billing_address()) {
999 var addr = clone_addr(bill_addr);
1000 addr._is_billing = true;
1001 user.billing_address = addr;
1004 if (mail_addr = clone_user.mailing_address()) {
1006 if (bill_addr && bill_addr.id() == mail_addr.id()) {
1007 user.mailing_address = user.billing_address;
1008 user.mailing_address._is_mailing = true;
1010 var addr = clone_addr(mail_addr);
1011 addr._is_mailing = true;
1012 user.mailing_address = addr;
1016 // if there is no billing addr, use the mailing addr
1017 user.billing_address = user.mailing_address;
1018 user.billing_address._is_billing = true;
1025 // link the billing and mailing addresses
1027 if (addr = clone_user.billing_address()) {
1028 user.billing_address = egCore.idl.toHash(addr);
1029 user.billing_address._is_billing = true;
1030 user.addresses.push(user.billing_address);
1031 user.billing_address._linked_owner_id = clone_user.id();
1032 user.billing_address._linked_owner = service.format_name(
1033 clone_user.family_name(),
1034 clone_user.first_given_name(),
1035 clone_user.second_given_name()
1039 if (addr = clone_user.mailing_address()) {
1040 if (user.billing_address &&
1041 addr.id() == user.billing_address.id) {
1042 // mailing matches billing
1043 user.mailing_address = user.billing_address;
1044 user.mailing_address._is_mailing = true;
1046 user.mailing_address = egCore.idl.toHash(addr);
1047 user.mailing_address._is_mailing = true;
1048 user.addresses.push(user.mailing_address);
1049 user.mailing_address._linked_owner_id = clone_user.id();
1050 user.mailing_address._linked_owner = service.format_name(
1051 clone_user.family_name(),
1052 clone_user.first_given_name(),
1053 clone_user.second_given_name()
1060 // translate the patron back into IDL form
1061 service.save_user = function(phash) {
1063 var patron = egCore.idl.fromHash('au', phash);
1065 patron.home_ou(patron.home_ou().id());
1066 patron.expire_date(patron.expire_date().toISOString());
1067 patron.profile(patron.profile().id());
1069 patron.dob(patron.dob().toISOString().replace(/T.*/,''));
1070 if (patron.ident_type())
1071 patron.ident_type(patron.ident_type().id());
1072 if (patron.net_access_level())
1073 patron.net_access_level(patron.net_access_level().id());
1076 ['juvenile', 'barred', 'active', 'master_account'],
1077 function(field) { patron[field](phash[field] ? 't' : 'f'); }
1080 var card_hashes = patron.cards();
1082 angular.forEach(card_hashes, function(chash) {
1083 var card = egCore.idl.fromHash('ac', chash)
1084 card.usr(patron.id());
1085 card.active(chash.active ? 't' : 'f');
1086 patron.cards().push(card);
1087 if (chash._primary) {
1092 var addr_hashes = patron.addresses();
1093 patron.addresses([]);
1094 angular.forEach(addr_hashes, function(addr_hash) {
1095 if (!addr_hash.isnew && !addr_hash.isdeleted)
1096 addr_hash.ischanged = true;
1097 var addr = egCore.idl.fromHash('aua', addr_hash);
1098 patron.addresses().push(addr);
1099 addr.valid(addr.valid() ? 't' : 'f');
1100 addr.within_city_limits(addr.within_city_limits() ? 't' : 'f');
1101 addr.pending(addr.pending() ? 't' : 'f');
1102 if (addr_hash._is_mailing) patron.mailing_address(addr);
1103 if (addr_hash._is_billing) patron.billing_address(addr);
1106 patron.survey_responses([]);
1107 angular.forEach(service.survey_responses, function(answer) {
1108 var question = service.survey_questions[answer.question()];
1109 var resp = new egCore.idl.asvr();
1111 resp.survey(question.survey());
1112 resp.question(question.id());
1113 resp.answer(answer.id());
1114 resp.usr(patron.id());
1115 resp.answer_date('now');
1116 patron.survey_responses().push(resp);
1119 // re-object-ify the patron stat cat entry maps
1121 angular.forEach(patron.stat_cat_entries(), function(entry) {
1122 var e = egCore.idl.fromHash('actscecm', entry);
1123 e.stat_cat(e.stat_cat().id);
1126 patron.stat_cat_entries(maps);
1128 // service.stat_cat_entry_maps maps stats to values
1129 // patron.stat_cat_entries is an array of stat_cat_entry_usr_map's
1131 service.stat_cat_entry_maps, function(value, cat_id) {
1133 // see if we already have a mapping for this entry
1134 var existing = patron.stat_cat_entries().filter(
1135 function(e) { return e.stat_cat() == cat_id })[0];
1137 if (existing) { // we have a mapping
1138 // if the existing mapping matches the new one,
1139 // there' nothing left to do
1140 if (existing.stat_cat_entry() == value) return;
1142 // mappings differ. delete the old one and create
1144 existing.isdeleted(true);
1147 var newmap = new egCore.idl.actscecm();
1148 newmap.target_usr(patron.id());
1150 newmap.stat_cat(cat_id);
1151 newmap.stat_cat_entry(value);
1152 patron.stat_cat_entries().push(newmap);
1155 var waiver_hashes = patron.waiver_entries();
1156 patron.waiver_entries([]);
1157 angular.forEach(waiver_hashes, function(waiver_hash) {
1158 if (!waiver_hash.isnew && !waiver_hash.isdeleted)
1159 waiver_hash.ischanged = true;
1160 var waiver_entry = egCore.idl.fromHash('aupw', waiver_hash);
1161 patron.waiver_entries().push(waiver_entry);
1164 if (!patron.isnew()) patron.ischanged(true);
1166 return egCore.net.request(
1168 'open-ils.actor.patron.update',
1169 egCore.auth.token(), patron);
1172 service.remove_staged_user = function() {
1173 if (!service.stage_user) return $q.when();
1174 return egCore.net.request(
1176 'open-ils.actor.user.stage.delete',
1177 egCore.auth.token(),
1178 service.stage_user.user.row_id()
1182 service.save_user_settings = function(new_user, user_settings) {
1185 if (service.patron_id) {
1186 // Update all user editor setting values for existing
1187 // users regardless of whether a value changed.
1188 settings = user_settings;
1191 // Create settings for all non-null setting values for new patrons.
1192 angular.forEach(user_settings, function(val, key) {
1193 if (val !== null) settings[key] = val;
1197 if (Object.keys(settings).length == 0) return $q.when();
1199 return egCore.net.request(
1201 'open-ils.actor.patron.settings.update',
1202 egCore.auth.token(), new_user.id(), settings
1203 ).then(function(resp) {
1208 // Applies field-specific validation regex's from org settings
1209 // to form fields. Be careful not remove any pattern data we
1210 // are not explicitly over-writing in the provided patterns obj.
1211 service.set_field_patterns = function(patterns) {
1212 if (service.org_settings['opac.username_regex']) {
1213 patterns.au.usrname =
1214 new RegExp(service.org_settings['opac.username_regex']);
1217 if (service.org_settings['ui.patron.edit.ac.barcode.regex']) {
1218 patterns.ac.barcode =
1219 new RegExp(service.org_settings['ui.patron.edit.ac.barcode.regex']);
1222 if (service.org_settings['global.password_regex']) {
1223 patterns.au.passwd =
1224 new RegExp(service.org_settings['global.password_regex']);
1227 var phone_reg = service.org_settings['ui.patron.edit.phone.regex'];
1229 // apply generic phone regex first, replace below as needed.
1230 patterns.au.day_phone = new RegExp(phone_reg);
1231 patterns.au.evening_phone = new RegExp(phone_reg);
1232 patterns.au.other_phone = new RegExp(phone_reg);
1235 // the remaining patterns fit a well-known key name pattern
1237 angular.forEach(service.org_settings, function(val, key) {
1239 var parts = key.match(/ui.patron.edit\.(\w+)\.(\w+)\.regex/);
1242 var name = parts[2];
1243 patterns[cls][name] = new RegExp(val);
1250 .controller('PatronRegCtrl',
1251 ['$scope','$routeParams','$q','$uibModal','$window','egCore',
1252 'patronSvc','patronRegSvc','egUnloadPrompt','egAlertDialog',
1253 'egWorkLog', '$timeout',
1254 function($scope , $routeParams , $q , $uibModal , $window , egCore ,
1255 patronSvc , patronRegSvc , egUnloadPrompt, egAlertDialog ,
1256 egWorkLog, $timeout) {
1258 $scope.page_data_loaded = false;
1259 $scope.hold_notify_type = { phone : null, email : null, sms : null };
1260 $scope.clone_id = patronRegSvc.clone_id = $routeParams.clone_id;
1261 $scope.stage_username =
1262 patronRegSvc.stage_username = $routeParams.stage_username;
1264 patronRegSvc.patron_id = $routeParams.edit_id || $routeParams.id;
1266 // for existing patrons, disable barcode input by default
1267 $scope.disable_bc = $scope.focus_usrname = Boolean($scope.patron_id);
1268 $scope.focus_bc = !Boolean($scope.patron_id);
1269 $scope.address_alerts = [];
1270 $scope.dupe_counts = {};
1272 // map of perm name to true/false for perms the logged in user
1273 // has at the currently selected patron home org unit.
1276 $scope.name_tab = 'primary';
1278 if (!$scope.edit_passthru) {
1279 // in edit more, scope.edit_passthru is delivered to us by
1280 // the enclosing controller. In register mode, there is
1281 // no enclosing controller, so we create our own.
1282 $scope.edit_passthru = {};
1285 // 0=all, 1=suggested, 2=all
1286 $scope.edit_passthru.vis_level = 0;
1288 // Apply default values for new patrons during initial registration
1289 // prs is shorthand for patronSvc
1290 function set_new_patron_defaults(prs) {
1291 if (!$scope.patron.passwd) {
1292 // passsword may originate from staged user.
1293 $scope.generate_password();
1295 $scope.hold_notify_type.phone = true;
1296 $scope.hold_notify_type.email = true;
1297 $scope.hold_notify_type.sms = false;
1299 // staged users may be loaded w/ a profile.
1300 $scope.set_expire_date();
1302 if (prs.org_settings['ui.patron.default_ident_type']) {
1303 // $scope.patron needs this field to be an object
1304 var id = prs.org_settings['ui.patron.default_ident_type'];
1305 var ident_type = $scope.ident_types.filter(
1306 function(type) { return type.id() == id })[0];
1307 $scope.patron.ident_type = ident_type;
1309 if (prs.org_settings['ui.patron.default_inet_access_level']) {
1310 // $scope.patron needs this field to be an object
1311 var id = prs.org_settings['ui.patron.default_inet_access_level'];
1312 var level = $scope.net_access_levels.filter(
1313 function(lvl) { return lvl.id() == id })[0];
1314 $scope.patron.net_access_level = level;
1316 if (prs.org_settings['ui.patron.default_country']) {
1317 $scope.patron.addresses[0].country =
1318 prs.org_settings['ui.patron.default_country'];
1322 // A null or undefined pattern leads to exceptions. Before the
1323 // patterns are loaded from the server, default all patterns
1324 // to an innocuous regex. To avoid re-creating numerous
1325 // RegExp objects, cache the stub RegExp after initial creation.
1326 // note: angular docs say ng-pattern accepts a regexp or string,
1327 // but as of writing, it only works with a regexp object.
1328 // (Likely an angular 1.2 vs. 1.4 issue).
1329 var field_patterns = {au : {}, ac : {}, aua : {}};
1330 $scope.field_pattern = function(cls, field) {
1331 if (!field_patterns[cls][field])
1332 field_patterns[cls][field] = new RegExp('.*');
1333 return field_patterns[cls][field];
1336 // Main page load function. Kicks off tab init and data loading.
1339 $scope.initTab ? // initTab comes from patron app
1340 $scope.initTab('edit', $routeParams.id) : $q.when(),
1342 patronRegSvc.init(),
1344 ]).then(function(){ return patronRegSvc.init_patron(patronSvc ? patronSvc.current : patronRegSvc.patron ) })
1345 .then(function(patron) {
1346 // called after initTab and patronRegSvc.init have completed
1347 // in standalone mode, we have no patronSvc
1348 var prs = patronRegSvc;
1349 $scope.patron = patron;
1350 $scope.field_doc = prs.field_doc;
1351 $scope.edit_profiles = prs.edit_profiles;
1352 $scope.edit_profile_entries = prs.edit_profile_entries;
1353 $scope.ident_types = prs.ident_types;
1354 $scope.net_access_levels = prs.net_access_levels;
1355 $scope.user_setting_types = prs.user_setting_types;
1356 $scope.opt_in_setting_types = prs.opt_in_setting_types;
1357 $scope.org_settings = prs.org_settings;
1358 $scope.sms_carriers = prs.sms_carriers;
1359 $scope.stat_cats = prs.stat_cats;
1360 $scope.surveys = prs.surveys;
1361 $scope.survey_responses = prs.survey_responses;
1362 $scope.stat_cat_entry_maps = prs.stat_cat_entry_maps;
1363 $scope.stage_user = prs.stage_user;
1364 $scope.stage_user_requestor = prs.stage_user_requestor;
1366 $scope.user_settings = prs.user_settings;
1367 prs.user_settings = {};
1369 // If a default pickup lib is applied to the patron, apply it
1370 // to the UI at page load time. Otherwise, leave the value unset.
1371 if ($scope.user_settings['opac.default_pickup_location']) {
1372 $scope.patron._pickup_lib = egCore.org.get(
1373 $scope.user_settings['opac.default_pickup_location']);
1376 extract_hold_notify();
1377 if ($scope.patron.isnew)
1378 set_new_patron_defaults(prs);
1380 $scope.handle_home_org_changed();
1382 if ($scope.org_settings['ui.patron.edit.default_suggested'])
1383 $scope.edit_passthru.vis_level = 1;
1385 // Stat cats are fetched from open-ils.storage, where 't'==1
1386 $scope.hasRequiredStatCat = prs.stat_cats.filter(
1387 function(cat) {return cat.required() == 1} ).length > 0;
1389 $scope.page_data_loaded = true;
1391 prs.set_field_patterns(field_patterns);
1392 apply_username_regex();
1394 add_date_watchers();
1396 if ($scope.org_settings['ui.patron.edit.guardian_required_for_juv']) {
1401 function add_date_watchers() {
1403 $scope.$watch('patron.dob', function(newVal, oldVal) {
1404 // Even though this runs after page data load, there
1405 // are still times when it fires unnecessarily.
1406 if (newVal === oldVal) return;
1408 console.debug('dob change: ' + newVal + ' : ' + oldVal);
1409 maintain_juvenile_flag();
1412 // No need to watch expire_date
1415 function add_juv_watcher() {
1416 $scope.$watch('patron.juvenile', function(newVal, oldVal) {
1417 if (newVal === oldVal) return;
1419 field_visibility['au.guardian'] = 3; // required
1421 // Value will be reassessed by show_field()
1422 delete field_visibility['au.guardian'];
1427 // update the currently displayed field documentation
1428 $scope.set_selected_field_doc = function(cls, field) {
1429 $scope.selected_field_doc = $scope.field_doc[cls][field];
1432 // returns the tree depth of the selected profile group tree node.
1433 $scope.pgt_depth = function(grp) {
1435 while (grp = egCore.env.pgt.map[grp.parent()]) d++;
1439 // returns the tree depth of the selected profile group tree node.
1440 $scope.pgtde_depth = function(entry) {
1442 while (entry = egCore.env.pgtde.map[entry.parent()]) d++;
1446 // IDL fields used for labels in the UI.
1447 $scope.idl_fields = {
1448 au : egCore.idl.classes.au.field_map,
1449 ac : egCore.idl.classes.ac.field_map,
1450 aua : egCore.idl.classes.aua.field_map
1453 // field visibility cache. Some fields are universally required.
1454 // 3 == value universally required
1455 // 2 == field is visible by default
1456 // 1 == field is suggested by default
1457 var field_visibility = {};
1458 var default_field_visibility = {
1462 'au.first_given_name' : 3,
1463 'au.family_name' : 3,
1464 'au.pref_first_given_name' : 2,
1465 'au.pref_family_name' : 2,
1466 'au.ident_type' : 3,
1467 'au.ident_type2' : 2,
1470 'au.expire_date' : 3,
1471 'au.net_access_level' : 3,
1472 'aua.address_type' : 3,
1473 'aua.post_code' : 3,
1481 'aua.within_city_limits' : 2,
1484 'au.name_keywords': 1
1487 // Returns true if the selected field should be visible
1488 // given the current required/suggested/all setting.
1489 // The visibility flag applied to each field as a result of calling
1490 // this function also sets (via the same flag) the requiredness state.
1491 $scope.show_field = function(field_key) {
1492 // org settings have not been received yet.
1493 if (!$scope.org_settings) return false;
1495 if (field_visibility[field_key] == undefined) {
1496 // compile and cache the visibility for the selected field
1498 // The preferred name fields use the primary name field settings
1499 var org_key = field_key;
1500 var alt_name = false;
1501 if (field_key.match(/^au.alt_/)) {
1503 org_key = field_key.slice(7);
1506 var req_set = 'ui.patron.edit.' + org_key + '.require';
1507 var sho_set = 'ui.patron.edit.' + org_key + '.show';
1508 var sug_set = 'ui.patron.edit.' + org_key + '.suggest';
1510 if ($scope.org_settings[req_set]) {
1512 // Avoid requiring alt name fields when primary
1513 // name fields are required.
1514 field_visibility[field_key] = 2;
1516 field_visibility[field_key] = 3;
1519 } else if ($scope.org_settings[sho_set]) {
1520 field_visibility[field_key] = 2;
1522 } else if ($scope.org_settings[sug_set]) {
1523 field_visibility[field_key] = 1;
1527 if (field_visibility[field_key] == undefined) {
1528 // No org settings were applied above. Use the default
1529 // settings if present or assume the field has no
1530 // visibility flags applied.
1531 field_visibility[field_key] =
1532 default_field_visibility[field_key] || 0;
1535 return field_visibility[field_key] >= $scope.edit_passthru.vis_level;
1538 // See $scope.show_field().
1539 // A field with visbility level 3 means it's required.
1540 $scope.field_required = function(cls, field) {
1542 // Value in the password field is not required
1543 // for existing patrons.
1544 if (field == 'passwd' && $scope.patron && !$scope.patron.isnew)
1547 return (field_visibility[cls + '.' + field] == 3);
1550 // generates a random 4-digit password
1551 $scope.generate_password = function() {
1552 $scope.patron.passwd = Math.floor(Math.random()*9000) + 1000;
1555 $scope.set_expire_date = function() {
1556 if (!$scope.patron.profile) return;
1557 var seconds = egCore.date.intervalToSeconds(
1558 $scope.patron.profile.perm_interval());
1559 var now_epoch = new Date().getTime();
1560 $scope.patron.expire_date = new Date(
1561 now_epoch + (seconds * 1000 /* milliseconds */))
1562 $scope.field_modified();
1565 // grp is the pgt object
1566 $scope.set_profile = function(grp) {
1567 $scope.patron.profile = grp;
1568 $scope.set_expire_date();
1569 $scope.field_modified();
1572 $scope.invalid_profile = function() {
1575 $scope.patron.profile &&
1576 $scope.patron.profile.usergroup() == 't'
1580 $scope.new_address = function() {
1581 var addr = egCore.idl.toHash(new egCore.idl.aua());
1582 patronRegSvc.ingest_address($scope.patron, addr);
1583 addr.id = patronRegSvc.virt_id--;
1586 addr.within_city_limits = true;
1587 addr.country = $scope.org_settings['ui.patron.default_country'];
1588 $scope.patron.addresses.push(addr);
1591 // keep deleted addresses out of the patron object so
1592 // they won't appear in the UI. They'll be re-inserted
1593 // when the patron is updated.
1594 deleted_addresses = [];
1595 $scope.delete_address = function(id) {
1597 if ($scope.patron.isnew &&
1598 $scope.patron.addresses.length == 1 &&
1599 $scope.org_settings['ui.patron.registration.require_address']) {
1600 egAlertDialog.open(egCore.strings.REG_ADDR_REQUIRED);
1605 angular.forEach($scope.patron.addresses, function(addr) {
1606 if (addr.id == id) {
1608 addr.isdeleted = true;
1609 deleted_addresses.push(addr);
1612 addresses.push(addr);
1615 $scope.patron.addresses = addresses;
1618 $scope.approve_pending_address = function(addr) {
1622 'open-ils.actor.user.pending_address.approve',
1623 egCore.auth.token(), addr.id
1624 ).then(function(replaced_id) {
1625 var evt = egCore.evt.parse(replaced_id);
1626 if (evt) { alert(evt); return; }
1628 // Remove the pending address and the replaced address
1629 // from the local list of patron addresses.
1631 angular.forEach($scope.patron.addresses, function(a) {
1632 if (a.id != addr.id && a.id != replaced_id) {
1636 $scope.patron.addresses = addresses;
1638 // Fetch a fresh copy of the modified address from the server.
1639 // and add it back to the list.
1640 egCore.pcrud.retrieve('aua', replaced_id, {}, {authoritative: true})
1641 .then(null, null, function(new_addr) {
1642 new_addr = egCore.idl.toHash(new_addr);
1643 patronRegSvc.ingest_address($scope.patron, new_addr);
1644 $scope.patron.addresses.push(new_addr);
1649 $scope.post_code_changed = function(addr) {
1651 'open-ils.search', 'open-ils.search.zip', addr.post_code)
1652 .then(function(resp) {
1654 if (resp.city) addr.city = resp.city;
1655 if (resp.state) addr.state = resp.state;
1656 if (resp.county) addr.county = resp.county;
1657 if (resp.alert) alert(resp.alert);
1661 $scope.new_waiver_entry = function() {
1662 var waiver = egCore.idl.toHash(new egCore.idl.aupw());
1663 patronRegSvc.ingest_waiver_entry($scope.patron, waiver);
1664 waiver.id = patronRegSvc.virt_id--;
1665 waiver.isnew = true;
1666 $scope.patron.waiver_entries.push(waiver);
1669 deleted_waiver_entries = [];
1670 $scope.delete_waiver_entry = function(waiver_entry) {
1671 if (waiver_entry.id > 0) {
1672 waiver_entry.isdeleted = true;
1673 deleted_waiver_entries.push(waiver_entry);
1675 var index = $scope.patron.waiver_entries.indexOf(waiver_entry);
1676 $scope.patron.waiver_entries.splice(index, 1);
1679 $scope.replace_card = function() {
1680 $scope.patron.card.active = false;
1681 $scope.patron.card.ischanged = true;
1682 $scope.disable_bc = false;
1684 var new_card = egCore.idl.toHash(new egCore.idl.ac());
1685 new_card.id = patronRegSvc.virt_id--;
1686 new_card.isnew = true;
1687 new_card.active = true;
1688 new_card._primary = 'on';
1689 $scope.patron.card = new_card;
1691 // Remove any previous attempts to replace the card, since they
1692 // may be incomplete or created by accident.
1693 $scope.patron.cards =
1694 $scope.patron.cards.filter(function(c) {return !c.isnew})
1695 $scope.patron.cards.push(new_card);
1698 $scope.day_phone_changed = function(phone) {
1699 if (phone && $scope.patron.isnew &&
1700 $scope.org_settings['patron.password.use_phone']) {
1701 $scope.patron.passwd = phone.substr(-4);
1705 $scope.barcode_changed = function(bc) {
1707 $scope.dupe_barcode = false;
1710 'open-ils.actor.barcode.exists',
1711 egCore.auth.token(), bc
1712 ).then(function(resp) {
1713 if (resp == '1') { // duplicate card
1714 $scope.dupe_barcode = true;
1715 console.log('duplicate barcode detected: ' + bc);
1717 if (!$scope.patron.usrname)
1718 $scope.patron.usrname = bc;
1724 $scope.cards_dialog = function() {
1726 templateUrl: './circ/patron/t_patron_cards_dialog',
1729 ['$scope','$uibModalInstance','cards','perms','patron',
1730 function($scope , $uibModalInstance , cards , perms , patron) {
1731 // scope here is the modal-level scope
1732 $scope.args = {cards : cards, primary_barcode : null};
1733 angular.forEach(cards, function(card) {
1734 if (card.id == patron.card.id) {
1735 $scope.args.primary_barcode = card.id;
1738 $scope.perms = perms;
1739 $scope.ok = function() { $uibModalInstance.close($scope.args) }
1740 $scope.cancel = function () { $uibModalInstance.dismiss() }
1743 cards : function() {
1744 // scope here is the controller-level scope
1745 return $scope.patron.cards;
1747 perms : function() {
1748 return $scope.perms;
1750 patron : function() {
1751 return $scope.patron;
1756 angular.forEach(args.cards, function(card) {
1757 card.ischanged = true; // assume cards need updating, OK?
1758 if (card.id == args.primary_barcode) {
1759 $scope.patron.card = card;
1760 card._primary = true;
1762 card._primary = false;
1769 $scope.set_addr_type = function(addr, type) {
1770 var addrs = $scope.patron.addresses;
1771 if (addr['_is_'+type]) {
1772 angular.forEach(addrs, function(a) {
1773 if (a.id != addr.id) a['_is_'+type] = false;
1776 // unchecking mailing/billing means we have to randomly
1777 // select another address to fill that role. Select the
1778 // first address in the list (that does not match the
1780 for (var i = 0; i < addrs.length; i++) {
1781 if (addrs[i].id != addr.id) {
1782 addrs[i]['_is_' + type] = true;
1790 // Translate hold notify preferences from the form/scope back into a
1791 // single user setting value for opac.hold_notify.
1792 function compress_hold_notify() {
1793 var hold_notify_methods = [];
1794 if ($scope.hold_notify_type.phone) {
1795 hold_notify_methods.push('phone');
1797 if ($scope.hold_notify_type.email) {
1798 hold_notify_methods.push('email');
1800 if ($scope.hold_notify_type.sms) {
1801 hold_notify_methods.push('sms');
1804 $scope.user_settings['opac.hold_notify'] = hold_notify_methods.join(':');
1807 // dialog for selecting additional permission groups
1808 $scope.secondary_groups_dialog = function() {
1810 templateUrl: './circ/patron/t_patron_groups_dialog',
1813 ['$scope','$uibModalInstance','linked_groups','pgt_depth',
1814 function($scope , $uibModalInstance , linked_groups , pgt_depth) {
1816 $scope.pgt_depth = pgt_depth;
1818 linked_groups : linked_groups,
1819 edit_profiles : patronRegSvc.edit_profiles,
1820 new_profile : patronRegSvc.edit_profiles[0]
1823 // add a new group to the linked groups list
1824 $scope.link_group = function($event, grp) {
1825 var found = false; // avoid duplicates
1826 angular.forEach($scope.args.linked_groups,
1827 function(g) {if (g.id() == grp.id()) found = true});
1828 if (!found) $scope.args.linked_groups.push(grp);
1829 $event.preventDefault(); // avoid close
1832 // remove a group from the linked groups list
1833 $scope.unlink_group = function($event, grp) {
1834 $scope.args.linked_groups =
1835 $scope.args.linked_groups.filter(function(g) {
1836 return g.id() != grp.id()
1838 $event.preventDefault(); // avoid close
1841 $scope.ok = function() { $uibModalInstance.close($scope.args) }
1842 $scope.cancel = function () { $uibModalInstance.dismiss() }
1845 linked_groups : function() { return $scope.patron.groups },
1846 pgt_depth : function() { return $scope.pgt_depth }
1851 if ($scope.patron.isnew) {
1852 // groups must be linked for new patrons after the
1853 // patron is created.
1854 $scope.patron.groups = args.linked_groups;
1858 // update links groups for existing users in real time.
1859 var ids = args.linked_groups.map(function(g) {return g.id()});
1860 patronRegSvc.apply_secondary_groups($scope.patron.id, ids)
1861 .then(function(success) {
1863 $scope.patron.groups = args.linked_groups;
1869 function extract_hold_notify() {
1870 var notify = $scope.user_settings['opac.hold_notify'];
1871 if (!notify) return;
1872 $scope.hold_notify_type.phone = Boolean(notify.match(/phone/));
1873 $scope.hold_notify_type.email = Boolean(notify.match(/email/));
1874 $scope.hold_notify_type.sms = Boolean(notify.match(/sms/));
1877 $scope.invalidate_field = function(field) {
1878 patronRegSvc.invalidate_field($scope.patron, field);
1881 address_alert = function(addr) {
1883 street1: addr.street1,
1884 street2: addr.street2,
1887 county: addr.county,
1888 country: addr.country,
1889 post_code: addr.post_code,
1890 mailing_address: addr._is_mailing,
1891 billing_address: addr._is_billing
1896 'open-ils.actor.address_alert.test',
1897 egCore.auth.token(), egCore.auth.user().ws_ou(), args
1898 ).then(function(res) {
1899 $scope.address_alerts = res;
1903 $scope.dupe_value_changed = function(type, value) {
1904 if (!$scope.dupe_search_encoded)
1905 $scope.dupe_search_encoded = {};
1907 $scope.dupe_counts[type] = 0;
1909 patronRegSvc.dupe_patron_search($scope.patron, type, value)
1910 .then(function(res) {
1911 $scope.dupe_counts[type] = res.count;
1913 $scope.dupe_search_encoded[type] =
1914 encodeURIComponent(js2JSON(res.search));
1916 $scope.dupe_search_encoded[type] = '';
1921 $scope.handle_home_org_changed = function() {
1922 org_id = $scope.patron.home_ou.id();
1923 patronRegSvc.has_perms_for_org(org_id).then(function(map) {
1924 angular.forEach(map, function(v, k) { $scope.perms[k] = v });
1928 $scope.handle_pulib_changed = function(org) {
1929 if (!$scope.user_settings) return; // still rendering
1930 $scope.user_settings['opac.default_pickup_location'] = org.id();
1933 // This is called with every character typed in a form field,
1934 // since that's the only way to gaurantee something has changed.
1935 // See handle_field_changed for ng-change vs. ng-blur.
1936 $scope.field_modified = function() {
1937 // Call attach with every field change, regardless of whether
1938 // it's been called before. This will allow for re-attach after
1939 // the user clicks through the unload warning. egUnloadPrompt
1940 // will ensure we only attach once.
1941 egUnloadPrompt.attach($scope);
1944 // also monitor when form is changed *by the user*, as using
1945 // an ng-change handler doesn't work with eg-date-input
1946 $scope.$watch('reg_form.$pristine', function(newVal, oldVal) {
1947 if (!newVal) egUnloadPrompt.attach($scope);
1950 // username regex (if present) must be removed any time
1951 // the username matches the barcode to avoid firing the
1952 // invalid field handlers.
1953 function apply_username_regex() {
1954 var regex = $scope.org_settings['opac.username_regex'];
1956 if ($scope.patron.card.barcode) {
1957 // username must match the regex or the barcode
1958 field_patterns.au.usrname =
1960 regex + '|^' + $scope.patron.card.barcode + '$');
1962 // username must match the regex
1963 field_patterns.au.usrname = new RegExp(regex);
1966 // username can be any format.
1967 field_patterns.au.usrname = new RegExp('.*');
1971 // obj could be the patron, an address, etc.
1972 // This is called any time a form field achieves then loses focus.
1973 // It does not necessarily mean the field has changed.
1974 // The alternative is ng-change, but it's called with each character
1975 // typed, which would be overkill for many of the actions called here.
1976 $scope.handle_field_changed = function(obj, field_name) {
1977 var cls = obj.classname; // set by egIdl
1978 var value = obj[field_name];
1980 console.debug('changing field ' + field_name + ' to ' + value);
1982 switch (field_name) {
1984 if ($scope.patron.day_phone &&
1985 $scope.patron.isnew &&
1986 $scope.org_settings['patron.password.use_phone']) {
1987 $scope.patron.passwd = $scope.patron.day_phone.substr(-4);
1989 case 'evening_phone' :
1990 case 'other_phone' :
1991 $scope.dupe_value_changed(field_name, value);
1995 case 'ident_value2':
1996 $scope.dupe_value_changed('ident', value);
1999 case 'first_given_name':
2001 $scope.dupe_value_changed('name', value);
2005 $scope.dupe_value_changed('email', value);
2011 // dupe search on address wants the address object as the value.
2012 $scope.dupe_value_changed('address', obj);
2017 $scope.post_code_changed(obj);
2021 patronRegSvc.check_dupe_username(value)
2022 .then(function(yes) {$scope.dupe_username = Boolean(yes)});
2026 // TODO: finish barcode_changed handler.
2027 $scope.barcode_changed(value);
2028 apply_username_regex();
2033 // patron.juvenile is set to true if the user was born after
2034 function maintain_juvenile_flag() {
2035 if ( !($scope.patron && $scope.patron.dob) ) return;
2038 $scope.org_settings['global.juvenile_age_threshold']
2041 var base = new Date();
2043 base.setTime(base.getTime() -
2044 Number(egCore.date.intervalToSeconds(juv_interval) + '000'));
2046 $scope.patron.juvenile = ($scope.patron.dob > base);
2049 // returns true (disable) for orgs that cannot have users.
2050 $scope.disable_home_org = function(org_id) {
2051 if (!org_id) return;
2052 var org = egCore.org.get(org_id);
2056 org.ou_type().can_have_users() == 'f'
2060 // returns true (disable) for orgs that cannot have vols (for holds pickup)
2061 $scope.disable_pulib = function(org_id) {
2062 if (!org_id) return;
2063 return !egCore.org.CanHaveVolumes(org_id);
2066 // Returns true if the Save and Save & Clone buttons should be disabled.
2067 $scope.edit_passthru.hide_save_actions = function() {
2068 return $scope.patron.isnew ?
2069 !$scope.perms.CREATE_USER :
2070 !$scope.perms.UPDATE_USER;
2073 // Returns true if any input elements are tagged as invalid
2074 // via Angular patterns or required attributes.
2075 function form_has_invalid_fields() {
2076 return $('#patron-reg-container .ng-invalid').length > 0;
2079 function form_is_incomplete() {
2081 $scope.dupe_username ||
2082 $scope.dupe_barcode ||
2083 form_has_invalid_fields()
2088 $scope.edit_passthru.save = function(save_args) {
2089 if (!save_args) save_args = {};
2091 if (form_is_incomplete()) {
2092 // User has not provided valid values for all required fields.
2093 return egAlertDialog.open(egCore.strings.REG_INVALID_FIELDS);
2096 // remove page unload warning prompt
2097 egUnloadPrompt.clear();
2099 // toss the deleted addresses back into the patron's list of
2100 // addresses so it's included in the update
2101 $scope.patron.addresses =
2102 $scope.patron.addresses.concat(deleted_addresses);
2104 // ditto for waiver entries
2105 $scope.patron.waiver_entries =
2106 $scope.patron.waiver_entries.concat(deleted_waiver_entries);
2108 compress_hold_notify();
2112 patronRegSvc.save_user($scope.patron)
2113 .then(function(new_user) {
2114 if (new_user && new_user.classname) {
2115 updated_user = new_user;
2116 return patronRegSvc.save_user_settings(
2117 new_user, $scope.user_settings);
2119 var evt = egCore.evt.parse(new_user);
2121 if (evt && evt.textcode == 'XACT_COLLISION') {
2122 return egAlertDialog.open(
2123 egCore.strings.PATRON_EDIT_COLLISION).result;
2126 // debug only -- should not get here.
2127 alert('Patron update failed. \n\n' + js2JSON(new_user));
2130 }).then(function() {
2132 // only remove the staged user if the update succeeded.
2134 return patronRegSvc.remove_staged_user();
2138 }).then(function() {
2140 // linked groups for new users must be created after the new
2142 if ($scope.patron.isnew &&
2143 $scope.patron.groups && $scope.patron.groups.length) {
2144 var ids = $scope.patron.groups.map(function(g) {return g.id()});
2145 return patronRegSvc.apply_secondary_groups(updated_user.id(), ids)
2150 }).then(function() {
2155 ? egCore.strings.EG_WORK_LOG_REGISTERED_PATRON
2156 : egCore.strings.EG_WORK_LOG_EDITED_PATRON, {
2157 'action' : $scope.patron.isnew ? 'registered_patron' : 'edited_patron',
2158 'patron_id' : updated_user.id()
2163 // reloading the page means potentially losing some information
2164 // (e.g. last patron search), but is the only way to ensure all
2165 // components are properly updated to reflect the modified patron.
2166 if (updated_user && save_args.clone) {
2167 // open a separate tab for registering a new
2168 // patron from our cloned data.
2169 var url = 'https://'
2170 + $window.location.hostname
2171 + egCore.env.basePath
2172 + '/circ/patron/register/clone/'
2173 + updated_user.id();
2174 $window.open(url, '_blank').focus();
2176 } else if ($window.location.href.indexOf('stage') > -1 ){
2177 // we're here after deleting a self-reg staged user.
2178 // Just close tab, since refresh won't find staged user
2179 $timeout(function(){
2180 if (typeof BroadcastChannel != 'undefined') {
2181 var bChannel = new BroadcastChannel("eg.pending_usr.update");
2182 bChannel.postMessage({
2183 usr: egCore.idl.toHash(updated_user)
2190 // reload the current page
2191 $window.location.href = location.href;
2196 $scope.edit_passthru.print = function() {
2197 var print_data = {patron : $scope.patron}
2199 return egCore.print.print({
2200 context : 'default',
2201 template : 'patron_data',