2 angular.module('egCoreMod')
3 // toss tihs onto egCoreMod since the page app may vary
5 .factory('patronRegSvc', ['$q', 'egCore', function($q, egCore) {
8 field_doc : {}, // config.idl_field_doc
9 profiles : [], // permission groups
10 edit_profiles : [], // perm groups we can modify
12 user_settings : {}, // applied user settings
13 user_setting_types : {}, // config.usr_setting_type
14 opt_in_setting_types : {}, // config.usr_setting_type for event-def opt-in
16 survey_questions : {},
18 survey_responses : {}, // survey.responses for loaded patron in progress
20 stat_cat_entry_maps : {}, // cat.id to selected value
21 virt_id : -1, // virtual ID for new objects
22 init_done : false // have we loaded our initialization data?
25 // launch a series of parallel data retrieval calls
26 service.init = function(scope) {
28 // Data loaded here only needs to be retrieved the first time this
29 // tab becomes active within the current instance of the patron app.
30 // In other words, navigating between patron tabs will not cause
31 // all of this data to be reloaded. Navigating to a separate app
32 // and returning will cause the data to be reloaded.
33 if (service.init_done) return $q.when();
34 service.init_done = true;
37 service.get_field_doc(),
38 service.get_perm_groups(),
39 service.get_ident_types(),
40 service.get_user_settings(),
41 service.get_org_settings(),
42 service.get_stat_cats(),
43 service.get_surveys(),
44 service.get_clone_user(),
45 service.get_stage_user(),
46 service.get_net_access_levels()
50 service.get_clone_user = function() {
51 if (!service.clone_id) return $q.when();
52 // we could load egUser and use its get() function, but loading
53 // user.js into the standalone register UI would mean creating a
54 // new module, since egUser is not loaded into egCoreMod. This
56 return egCore.net.request(
58 'open-ils.actor.user.fleshed.retrieve',
59 egCore.auth.token(), service.clone_id,
60 ['billing_address', 'mailing_address'])
61 .then(function(cuser) {
62 if (e = egCore.evt.parse(cuser)) {
65 service.clone_user = cuser;
70 service.apply_secondary_groups = function(user_id, group_ids) {
71 return egCore.net.request(
73 'open-ils.actor.user.set_groups',
74 egCore.auth.token(), user_id, group_ids)
75 .then(function(resp) {
79 // debugging -- should be no events
80 alert('linked groups failure ' + egCore.evt.parse(resp));
85 service.get_stage_user = function() {
86 if (!service.stage_username) return $q.when();
88 // fetch the staged user object
89 return egCore.net.request(
91 'open-ils.actor.user.stage.retrieve.by_username',
93 service.stage_username
94 ).then(function(suser) {
95 if (e = egCore.evt.parse(suser)) {
98 service.stage_user = suser;
102 if (!service.stage_user) return;
103 var requestor = service.stage_user.user.requesting_usr();
105 if (!requestor) return;
107 // fetch the requesting user
108 return egCore.net.request(
110 'open-ils.actor.user.retrieve.parts',
113 ['family_name', 'first_given_name', 'second_given_name']
114 ).then(function(parts) {
115 service.stage_user_requestor =
116 service.format_name(parts[0], parts[1], parts[2]);
121 // See note above about not loading egUser.
123 service.format_name = function(last, first, middle) {
124 return last + ', ' + first + (middle ? ' ' + middle : '');
127 service.check_dupe_username = function(usrname) {
129 // empty usernames can't be dupes
130 if (!usrname) return $q.when(false);
132 // avoid dupe check if username matches the originally loaded usrname
133 if (service.existing_patron) {
134 if (usrname == service.existing_patron.usrname())
135 return $q.when(false);
138 return egCore.net.request(
140 'open-ils.actor.username.exists',
141 egCore.auth.token(), usrname);
144 //service.check_grp_app_perm = function(grp_id) {
146 // determine which user groups our user is not allowed to modify
147 service.set_edit_profiles = function() {
148 var all_app_perms = [];
149 var failed_perms = [];
151 // extract the application permissions
152 angular.forEach(service.profiles, function(grp) {
153 if (grp.application_perm())
154 all_app_perms.push(grp.application_perm());
157 // fill in service.edit_profiles by inspecting failed_perms
158 function traverse_grp_tree(grp, failed) {
160 failed_perms.indexOf(grp.application_perm()) > -1;
162 if (!failed) service.edit_profiles.push(grp);
165 service.profiles.filter( // children of grp
166 function(p) { return p.parent() == grp.id() }),
167 function(child) {traverse_grp_tree(child, failed)}
171 return egCore.perm.hasPermAt(all_app_perms, true).then(
172 function(perm_orgs) {
173 angular.forEach(all_app_perms, function(p) {
174 if (perm_orgs[p].length == 0)
175 failed_perms.push(p);
178 traverse_grp_tree(egCore.env.pgt.tree);
183 // resolves to a hash of perm-name => boolean value indicating
184 // wether the user has the permission at org_id.
185 service.has_perms_for_org = function(org_id) {
190 'CREATE_USER_GROUP_LINK',
191 'UPDATE_PATRON_COLLECTIONS_EXEMPT',
192 'UPDATE_PATRON_CLAIM_RETURN_COUNT',
193 'UPDATE_PATRON_CLAIM_NEVER_CHECKED_OUT_COUNT',
194 'UPDATE_PATRON_ACTIVE_CARD',
195 'UPDATE_PATRON_PRIMARY_CARD'
198 return egCore.perm.hasPermAt(perms_needed, true)
199 .then(function(perm_map) {
201 angular.forEach(perms_needed, function(perm) {
203 Boolean(perm_map[perm].indexOf(org_id) > -1);
210 service.get_surveys = function() {
211 var org_ids = egCore.org.fullPath(egCore.auth.user().ws_ou(), true);
213 return egCore.pcrud.search('asv', {
215 start_date : {'<=' : 'now'},
216 end_date : {'>=' : 'now'}
225 ).then(function(surveys) {
226 surveys = surveys.sort(function(a,b) {
227 return a.name() < b.name() ? -1 : 1 });
228 service.surveys = surveys;
229 angular.forEach(surveys, function(survey) {
230 angular.forEach(survey.questions(), function(question) {
231 service.survey_questions[question.id()] = question;
232 angular.forEach(question.answers(), function(answer) {
233 service.survey_answers[answer.id()] = answer;
240 service.get_stat_cats = function() {
241 return egCore.net.request(
243 'open-ils.circ.stat_cat.actor.retrieve.all',
244 egCore.auth.token(), egCore.auth.user().ws_ou()
245 ).then(function(cats) {
246 cats = cats.sort(function(a, b) {
247 return a.name() < b.name() ? -1 : 1});
248 angular.forEach(cats, function(cat) {
250 cat.entries().sort(function(a,b) {
251 return a.value() < b.value() ? -1 : 1
255 service.stat_cats = cats;
259 service.get_org_settings = function() {
260 return egCore.org.settings([
261 'global.password_regex',
262 'global.juvenile_age_threshold',
263 'patron.password.use_phone',
264 'ui.patron.default_inet_access_level',
265 'ui.patron.default_ident_type',
266 'ui.patron.default_country',
267 'ui.patron.registration.require_address',
268 'circ.holds.behind_desk_pickup_supported',
269 'circ.patron_edit.clone.copy_address',
270 'ui.patron.edit.au.prefix.require',
271 'ui.patron.edit.au.prefix.show',
272 'ui.patron.edit.au.prefix.suggest',
273 'ui.patron.edit.ac.barcode.regex',
274 'ui.patron.edit.au.second_given_name.show',
275 'ui.patron.edit.au.second_given_name.suggest',
276 'ui.patron.edit.au.suffix.show',
277 'ui.patron.edit.au.suffix.suggest',
278 'ui.patron.edit.au.alias.show',
279 'ui.patron.edit.au.alias.suggest',
280 'ui.patron.edit.au.dob.require',
281 'ui.patron.edit.au.dob.show',
282 'ui.patron.edit.au.dob.suggest',
283 'ui.patron.edit.au.dob.calendar',
284 'ui.patron.edit.au.juvenile.show',
285 'ui.patron.edit.au.juvenile.suggest',
286 'ui.patron.edit.au.ident_value.show',
287 'ui.patron.edit.au.ident_value.suggest',
288 'ui.patron.edit.au.ident_value2.show',
289 'ui.patron.edit.au.ident_value2.suggest',
290 'ui.patron.edit.au.email.require',
291 'ui.patron.edit.au.email.show',
292 'ui.patron.edit.au.email.suggest',
293 'ui.patron.edit.au.email.regex',
294 'ui.patron.edit.au.email.example',
295 'ui.patron.edit.au.day_phone.require',
296 'ui.patron.edit.au.day_phone.show',
297 'ui.patron.edit.au.day_phone.suggest',
298 'ui.patron.edit.au.day_phone.regex',
299 'ui.patron.edit.au.day_phone.example',
300 'ui.patron.edit.au.evening_phone.require',
301 'ui.patron.edit.au.evening_phone.show',
302 'ui.patron.edit.au.evening_phone.suggest',
303 'ui.patron.edit.au.evening_phone.regex',
304 'ui.patron.edit.au.evening_phone.example',
305 'ui.patron.edit.au.other_phone.require',
306 'ui.patron.edit.au.other_phone.show',
307 'ui.patron.edit.au.other_phone.suggest',
308 'ui.patron.edit.au.other_phone.regex',
309 'ui.patron.edit.au.other_phone.example',
310 'ui.patron.edit.phone.regex',
311 'ui.patron.edit.phone.example',
312 'ui.patron.edit.au.active.show',
313 'ui.patron.edit.au.active.suggest',
314 'ui.patron.edit.au.barred.show',
315 'ui.patron.edit.au.barred.suggest',
316 'ui.patron.edit.au.master_account.show',
317 'ui.patron.edit.au.master_account.suggest',
318 'ui.patron.edit.au.claims_returned_count.show',
319 'ui.patron.edit.au.claims_returned_count.suggest',
320 'ui.patron.edit.au.claims_never_checked_out_count.show',
321 'ui.patron.edit.au.claims_never_checked_out_count.suggest',
322 'ui.patron.edit.au.alert_message.show',
323 'ui.patron.edit.au.alert_message.suggest',
324 'ui.patron.edit.aua.post_code.regex',
325 'ui.patron.edit.aua.post_code.example',
326 'ui.patron.edit.aua.county.require',
328 'ui.patron.edit.default_suggested',
329 'opac.barcode_regex',
330 'opac.username_regex',
332 'ui.patron.edit.aua.state.require',
333 'ui.patron.edit.aua.state.suggest',
334 'ui.patron.edit.aua.state.show'
335 ]).then(function(settings) {
336 service.org_settings = settings;
337 return service.process_org_settings(settings);
341 // some org settings require the retrieval of additional data
342 service.process_org_settings = function(settings) {
346 if (settings['sms.enable']) {
347 // fetch SMS carriers
349 egCore.pcrud.search('csc',
352 {'class':'csc', 'field':'name'},
353 {'class':'csc', 'field':'region'}
355 ).then(function(carriers) {
356 service.sms_carriers = carriers;
360 // if other promises are added below, this is not necessary.
361 promises.push($q.when());
364 // other post-org-settings processing goes here,
365 // adding to promises as needed.
367 return $q.all(promises);
370 service.get_ident_types = function() {
371 if (egCore.env.cit) {
372 service.ident_types = egCore.env.cit.list;
375 return egCore.pcrud.retrieveAll('cit', {}, {atomic : true})
376 .then(function(types) {
377 egCore.env.absorbList(types, 'cit')
378 service.ident_types = types
383 service.get_net_access_levels = function() {
384 if (egCore.env.cnal) {
385 service.net_access_levels = egCore.env.cnal.list;
388 return egCore.pcrud.retrieveAll('cnal', {}, {atomic : true})
389 .then(function(levels) {
390 egCore.env.absorbList(levels, 'cnal')
391 service.net_access_levels = levels
396 service.get_perm_groups = function() {
397 if (egCore.env.pgt) {
398 service.profiles = egCore.env.pgt.list;
399 return service.set_edit_profiles();
401 return egCore.pcrud.search('pgt', {parent : null},
402 {flesh : -1, flesh_fields : {pgt : ['children']}}
405 egCore.env.absorbTree(tree, 'pgt')
406 service.profiles = egCore.env.pgt.list;
407 return service.set_edit_profiles();
413 service.get_field_doc = function() {
414 return egCore.pcrud.search('fdoc', {
415 fm_class: ['au', 'ac', 'aua', 'actsc', 'asv', 'asvq', 'asva']})
416 .then(null, null, function(doc) {
417 if (!service.field_doc[doc.fm_class()]) {
418 service.field_doc[doc.fm_class()] = {};
420 service.field_doc[doc.fm_class()][doc.field()] = doc;
424 service.get_user_settings = function() {
425 var org_ids = egCore.org.ancestors(egCore.auth.user().ws_ou(), true);
428 'circ.holds_behind_desk',
429 'circ.collections.exempt',
431 'opac.default_phone',
432 'opac.default_pickup_location',
433 'opac.default_sms_carrier',
434 'opac.default_sms_notify'];
436 return egCore.pcrud.search('cust', {
438 {name : static_types}, // common user settings
439 {name : { // opt-in notification user settings
441 select : {atevdef : ['opt_in_setting']},
443 // we only care about opt-in settings for
444 // event_defs our users encounter
445 where : {'+atevdef' : {owner : org_ids}}
449 }, {}, {atomic : true}).then(function(setting_types) {
451 angular.forEach(setting_types, function(stype) {
452 service.user_setting_types[stype.name()] = stype;
453 if (static_types.indexOf(stype.name()) == -1) {
454 service.opt_in_setting_types[stype.name()] = stype;
458 if (service.patron_id) {
459 // retrieve applied values for the current user
460 // for the setting types we care about.
463 setting_types.map(function(obj) { return obj.name() });
465 return egCore.net.request(
467 'open-ils.actor.patron.settings.retrieve.authoritative',
471 ).then(function(settings) {
472 service.user_settings = settings;
476 // apply default user setting values
477 angular.forEach(setting_types, function(stype, index) {
478 if (stype.reg_default() != undefined) {
479 service.user_settings[setting.name()] =
480 setting.reg_default();
487 service.invalidate_field = function(patron, field) {
488 console.log('Invalidating patron field ' + field);
490 return egCore.net.request(
492 'open-ils.actor.invalidate.' + field,
493 egCore.auth.token(), patron.id, null, patron.home_ou.id()
495 ).then(function(res) {
496 // clear the invalid value from the form
499 // update last_xact_id so future save operations
500 // on this patron will be allowed
501 patron.last_xact_id = res.payload.last_xact_id[patron.id];
505 service.dupe_patron_search = function(patron, type, value) {
508 console.log('Dupe search called with "'+ type +'" and value '+ value);
513 var fname = patron.first_given_name;
514 var lname = patron.family_name;
515 if (!(fname && lname)) return $q.when({count:0});
517 first_given_name : {value : fname, group : 0},
518 family_name : {value : lname, group : 0}
523 search = {email : {value : value, group : 0}};
527 search = {ident : {value : value, group : 2}};
531 search = {phone : {value : value, group : 2}};
536 angular.forEach(['street1', 'street2', 'city', 'post_code'],
539 search[field] = {value : value[field], group: 1};
545 return egCore.net.request(
547 'open-ils.actor.patron.search.advanced',
548 egCore.auth.token(), search, null, null, 1
549 ).then(function(res) {
550 res = res.filter(function(id) {return id != patron.id});
558 service.init_patron = function(current) {
561 return service.init_new_patron();
563 service.patron = current;
564 return service.init_existing_patron(current)
567 service.ingest_address = function(patron, addr) {
568 addr.valid = addr.valid == 't';
569 addr.within_city_limits = addr.within_city_limits == 't';
570 addr._is_mailing = (patron.mailing_address &&
571 addr.id == patron.mailing_address.id);
572 addr._is_billing = (patron.billing_address &&
573 addr.id == patron.billing_address.id);
577 * Existing patron objects reqire some data munging before insertion
580 * 1. Turn everything into a hash
581 * 2. ... Except certain fields (selectors) whose widgets require objects
582 * 3. Bools must be Boolean, not t/f.
584 service.init_existing_patron = function(current) {
586 service.existing_patron = current;
588 var patron = egCore.idl.toHash(current);
590 patron.home_ou = egCore.org.get(patron.home_ou.id);
591 patron.expire_date = new Date(Date.parse(patron.expire_date));
592 patron.dob = service.parse_dob(patron.dob);
593 patron.profile = current.profile(); // pre-hash version
594 patron.net_access_level = current.net_access_level();
595 patron.ident_type = current.ident_type();
596 patron.groups = current.groups(); // pre-hash
599 ['juvenile', 'barred', 'active', 'master_account'],
600 function(field) { patron[field] = patron[field] == 't'; }
603 angular.forEach(patron.cards, function(card) {
604 card.active = card.active == 't';
605 if (card.id == patron.card.id) {
607 card._primary = 'on';
611 angular.forEach(patron.addresses,
612 function(addr) { service.ingest_address(patron, addr) });
614 // toss entries for existing stat cat maps into our living
615 // stat cat entry map, which is modified within the template.
616 angular.forEach(patron.stat_cat_entries, function(map) {
617 service.stat_cat_entry_maps[map.stat_cat.id] = map.stat_cat_entry;
623 service.init_new_patron = function() {
625 id : service.virt_id--,
628 address_type : egCore.strings.REG_ADDR_TYPE,
631 within_city_limits : false,
632 country : service.org_settings['ui.patron.default_country'],
636 id : service.virt_id--,
647 home_ou : egCore.org.get(egCore.auth.user().ws_ou()),
648 stat_cat_entries : [],
653 if (service.clone_user)
654 service.copy_clone_data(user);
656 if (service.stage_user)
657 service.copy_stage_data(user);
662 // dob is always YYYY-MM-DD
663 // Dates of birth do not contain timezone info, which can lead to
664 // inconcistent timezone handling, potentially representing
665 // different points in time, depending on the implementation.
666 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
667 // See "Differences in assumed time zone"
668 // TODO: move this into egDate ?
669 service.parse_dob = function(dob) {
670 if (!dob) return null;
671 var parts = dob.split('-');
672 var d = new Date(); // always local time zone, yay.
673 d.setFullYear(parts[0]);
674 d.setMonth(parts[1]);
679 service.copy_stage_data = function(user) {
680 var cuser = service.stage_user;
682 // copy the data into our new user object
684 for (var key in egCore.idl.classes.stgu.field_map) {
685 if (egCore.idl.classes.au.field_map[key] &&
686 !egCore.idl.classes.stgu.field_map[key].virtual) {
687 if (cuser.user[key]() !== null)
688 user[key] = cuser.user[key]();
692 if (user.home_ou) user.home_ou = egCore.org.get(user.home_ou);
693 if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
695 user.ident_type = egCore.env.cit.map[user.ident_type];
696 user.dob = service.parse_dob(user.dob);
698 // Clear the usrname if it looks like a UUID
699 if (user.usrname.replace(/-/g,'').match(/[0-9a-f]{32}/))
702 // Don't use stub address if we have one from the staged user.
703 if (cuser.mailing_addresses.length || cuser.billing_addresses.length)
706 // is_mailing=false implies is_billing
707 function addr_from_stage(stage_addr) {
708 if (!stage_addr) return;
709 var cls = stage_addr.classname;
712 id : service.virt_id--,
716 _is_mailing : cls == 'stgma',
717 _is_billing : cls == 'stgba'
720 user.mailing_address = addr;
721 user.addresses.push(addr);
723 for (var key in egCore.idl.classes[cls].field_map) {
724 if (egCore.idl.classes.aua.field_map[key] &&
725 !egCore.idl.classes[cls].field_map[key].virtual) {
726 if (stage_addr[key]() !== null)
727 addr[key] = stage_addr[key]();
732 addr_from_stage(cuser.mailing_addresses[0]);
733 addr_from_stage(cuser.billing_addresses[0]);
735 if (user.addresses.length == 1) {
736 // If there is only one address,
737 // use it as both mailing and billing.
738 var addr = user.addresses[0];
739 addr._is_mailing = addr._is_billing = true;
740 user.mailing_address = user.billing_address = addr;
743 if (cuser.cards.length) {
745 id : service.virt_id--,
746 barcode : cuser.cards[0].barcode(),
752 user.cards.push(user.card);
753 if (user.usrname == '')
754 user.usrname = card.barcode;
758 // copy select values from the cloned user to the new user.
760 service.copy_clone_data = function(user) {
761 var clone_user = service.clone_user;
763 // flesh the home org locally
764 user.home_ou = egCore.org.get(clone_user.home_ou());
765 if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
767 if (!clone_user.billing_address() &&
768 !clone_user.mailing_address())
769 return; // no addresses to copy or link
771 // if the cloned user has any addresses, we don't need
772 // the stub address created in init_new_patron.
776 service.org_settings['circ.patron_edit.clone.copy_address'];
785 angular.forEach(clone_fields, function(field) {
786 user[field] = clone_user[field]();
789 if (copy_addresses) {
790 var bill_addr, mail_addr;
792 // copy the billing and mailing addresses into new addresses
793 function clone_addr(addr) {
794 var new_addr = egCore.idl.toHash(addr);
795 new_addr.id = service.virt_id--;
796 new_addr.usr = user.id;
797 new_addr.isnew = true;
798 new_addr.valid = true;
799 user.addresses.push(new_addr);
803 if (bill_addr = clone_user.billing_address()) {
804 var addr = clone_addr(bill_addr);
805 addr._is_billing = true;
806 user.billing_address = addr;
809 if (mail_addr = clone_user.mailing_address()) {
811 if (bill_addr && bill_addr.id() == mail_addr.id()) {
812 user.mailing_address = user.billing_address;
813 user.mailing_address._is_mailing = true;
815 var addr = clone_addr(mail_addr);
816 addr._is_mailing = true;
817 user.mailing_address = addr;
821 // if there is no billing addr, use the mailing addr
822 user.billing_address = user.mailing_address;
823 user.billing_address._is_billing = true;
830 // link the billing and mailing addresses
832 if (addr = clone_user.billing_address()) {
833 user.billing_address = egCore.idl.toHash(addr);
834 user.billing_address._is_billing = true;
835 user.addresses.push(user.billing_address);
836 user.billing_address._linked_owner_id = clone_user.id();
837 user.billing_address._linked_owner = service.format_name(
838 clone_user.family_name(),
839 clone_user.first_given_name(),
840 clone_user.second_given_name()
844 if (addr = clone_user.mailing_address()) {
845 if (user.billing_address &&
846 addr.id() == user.billing_address.id) {
847 // mailing matches billing
848 user.mailing_address = user.billing_address;
849 user.mailing_address._is_mailing = true;
851 user.mailing_address = egCore.idl.toHash(addr);
852 user.mailing_address._is_mailing = true;
853 user.addresses.push(user.mailing_address);
854 user.mailing_address._linked_owner_id = clone_user.id();
855 user.mailing_address._linked_owner = service.format_name(
856 clone_user.family_name(),
857 clone_user.first_given_name(),
858 clone_user.second_given_name()
865 // translate the patron back into IDL form
866 service.save_user = function(phash) {
868 var patron = egCore.idl.fromHash('au', phash);
870 patron.home_ou(patron.home_ou().id());
871 patron.expire_date(patron.expire_date().toISOString());
872 patron.profile(patron.profile().id());
874 patron.dob(patron.dob().toISOString().replace(/T.*/,''));
875 if (patron.ident_type())
876 patron.ident_type(patron.ident_type().id());
877 if (patron.net_access_level())
878 patron.net_access_level(patron.net_access_level().id());
881 ['juvenile', 'barred', 'active', 'master_account'],
882 function(field) { patron[field](phash[field] ? 't' : 'f'); }
885 var card_hashes = patron.cards();
887 angular.forEach(card_hashes, function(chash) {
888 var card = egCore.idl.fromHash('ac', chash)
889 card.usr(patron.id());
890 card.active(chash.active ? 't' : 'f');
891 patron.cards().push(card);
892 if (chash._primary) {
897 var addr_hashes = patron.addresses();
898 patron.addresses([]);
899 angular.forEach(addr_hashes, function(addr_hash) {
900 if (!addr_hash.isnew && !addr_hash.isdeleted)
901 addr_hash.ischanged = true;
902 var addr = egCore.idl.fromHash('aua', addr_hash);
903 patron.addresses().push(addr);
904 addr.valid(addr.valid() ? 't' : 'f');
905 addr.within_city_limits(addr.within_city_limits() ? 't' : 'f');
906 if (addr_hash._is_mailing) patron.mailing_address(addr);
907 if (addr_hash._is_billing) patron.billing_address(addr);
910 patron.survey_responses([]);
911 angular.forEach(service.survey_responses, function(answer) {
912 var question = service.survey_questions[answer.question()];
913 var resp = new egCore.idl.asvr();
915 resp.survey(question.survey());
916 resp.question(question.id());
917 resp.answer(answer.id());
918 resp.usr(patron.id());
919 resp.answer_date('now');
920 patron.survey_responses().push(resp);
923 // re-object-ify the patron stat cat entry maps
925 angular.forEach(patron.stat_cat_entries(), function(entry) {
926 var e = egCore.idl.fromHash('actscecm', entry);
927 e.stat_cat(e.stat_cat().id);
930 patron.stat_cat_entries(maps);
932 // service.stat_cat_entry_maps maps stats to values
933 // patron.stat_cat_entries is an array of stat_cat_entry_usr_map's
935 service.stat_cat_entry_maps, function(value, cat_id) {
937 // see if we already have a mapping for this entry
938 var existing = patron.stat_cat_entries().filter(
939 function(e) { return e.stat_cat() == cat_id })[0];
941 if (existing) { // we have a mapping
942 // if the existing mapping matches the new one,
943 // there' nothing left to do
944 if (existing.stat_cat_entry() == value) return;
946 // mappings differ. delete the old one and create
948 existing.isdeleted(true);
951 var newmap = new egCore.idl.actscecm();
952 newmap.target_usr(patron.id());
954 newmap.stat_cat(cat_id);
955 newmap.stat_cat_entry(value);
956 patron.stat_cat_entries().push(newmap);
959 if (!patron.isnew()) patron.ischanged(true);
961 return egCore.net.request(
963 'open-ils.actor.patron.update',
964 egCore.auth.token(), patron);
967 service.remove_staged_user = function() {
968 if (!service.stage_user) return $q.when();
969 return egCore.net.request(
971 'open-ils.actor.user.stage.delete',
973 service.stage_user.row_id()
977 service.save_user_settings = function(new_user, user_settings) {
978 // user_settings contains the values from the scope/form.
979 // service.user_settings contain the values from page load time.
982 if (service.patron_id) {
983 // only update modified settings for existing patrons
984 angular.forEach(user_settings, function(val, key) {
985 if (val !== service.user_settings[key])
990 // all non-null setting values are updated for new patrons
991 angular.forEach(user_settings, function(val, key) {
992 if (val !== null) settings[key] = val;
996 if (Object.keys(settings).length == 0) return $q.when();
998 return egCore.net.request(
1000 'open-ils.actor.patron.settings.update',
1001 egCore.auth.token(), new_user.id(), settings
1002 ).then(function(resp) {
1007 // Applies field-specific validation regex's from org settings
1008 // to form fields. Be careful not remove any pattern data we
1009 // are not explicitly over-writing in the provided patterns obj.
1010 service.set_field_patterns = function(patterns) {
1011 if (service.org_settings['opac.username_regex']) {
1012 patterns.au.usrname =
1013 new RegExp(service.org_settings['opac.username_regex']);
1016 if (service.org_settings['opac.barcode_regex']) {
1017 patterns.ac.barcode =
1018 new RegExp(service.org_settings['opac.barcode_regex']);
1021 if (service.org_settings['global.password_regex']) {
1022 patterns.au.passwd =
1023 new RegExp(service.org_settings['global.password_regex']);
1026 var phone_reg = service.org_settings['ui.patron.edit.phone.regex'];
1028 // apply generic phone regex first, replace below as needed.
1029 patterns.au.day_phone = new RegExp(phone_reg);
1030 patterns.au.evening_phone = new RegExp(phone_reg);
1031 patterns.au.other_phone = new RegExp(phone_reg);
1034 // the remaining patterns fit a well-known key name pattern
1036 angular.forEach(service.org_settings, function(val, key) {
1038 var parts = key.match(/ui.patron.edit\.(\w+)\.(\w+)\.regex/);
1041 var name = parts[2];
1042 patterns[cls][name] = new RegExp(val);
1050 function PatronRegCtrl($scope, $routeParams,
1051 $q, $modal, $window, egCore, patronSvc, patronRegSvc, egUnloadPrompt) {
1053 $scope.page_data_loaded = false;
1054 $scope.clone_id = patronRegSvc.clone_id = $routeParams.clone_id;
1055 $scope.stage_username =
1056 patronRegSvc.stage_username = $routeParams.stage_username;
1058 patronRegSvc.patron_id = $routeParams.edit_id || $routeParams.id;
1060 // for existing patrons, disable barcode input by default
1061 $scope.disable_bc = $scope.focus_usrname = Boolean($scope.patron_id);
1062 $scope.focus_bc = !Boolean($scope.patron_id);
1063 $scope.dupe_counts = {};
1065 // map of perm name to true/false for perms the logged in user
1066 // has at the currently selected patron home org unit.
1069 if (!$scope.edit_passthru) {
1070 // in edit more, scope.edit_passthru is delivered to us by
1071 // the enclosing controller. In register mode, there is
1072 // no enclosing controller, so we create our own.
1073 $scope.edit_passthru = {};
1076 // 0=all, 1=suggested, 2=all
1077 $scope.edit_passthru.vis_level = 0;
1079 // Apply default values for new patrons during initial registration
1080 // prs is shorthand for patronSvc
1081 function set_new_patron_defaults(prs) {
1082 if (!$scope.patron.passwd) {
1083 // passsword may originate from staged user.
1084 $scope.generate_password();
1086 $scope.hold_notify_phone = true;
1087 $scope.hold_notify_email = true;
1089 // staged users may be loaded w/ a profile.
1090 $scope.set_expire_date();
1092 if (prs.org_settings['ui.patron.default_ident_type']) {
1093 // $scope.patron needs this field to be an object
1094 var id = prs.org_settings['ui.patron.default_ident_type'];
1095 var ident_type = $scope.ident_types.filter(
1096 function(type) { return type.id() == id })[0];
1097 $scope.patron.ident_type = ident_type;
1099 if (prs.org_settings['ui.patron.default_inet_access_level']) {
1100 // $scope.patron needs this field to be an object
1101 var id = prs.org_settings['ui.patron.default_inet_access_level'];
1102 var level = $scope.net_access_levels.filter(
1103 function(lvl) { return lvl.id() == id })[0];
1104 $scope.patron.net_access_level = level;
1106 if (prs.org_settings['ui.patron.default_country']) {
1107 $scope.patron.addresses[0].country =
1108 prs.org_settings['ui.patron.default_country'];
1112 // A null or undefined pattern leads to exceptions. Before the
1113 // patterns are loaded from the server, default all patterns
1114 // to an innocuous regex. To avoid re-creating numerous
1115 // RegExp objects, cache the stub RegExp after initial creation.
1116 // note: angular docs say ng-pattern accepts a regexp or string,
1117 // but as of writing, it only works with a regexp object.
1118 // (Likely an angular 1.2 vs. 1.4 issue).
1119 var field_patterns = {au : {}, ac : {}, aua : {}};
1120 $scope.field_pattern = function(cls, field) {
1121 if (!field_patterns[cls][field])
1122 field_patterns[cls][field] = new RegExp('.*');
1123 return field_patterns[cls][field];
1126 // Main page load function. Kicks off tab init and data loading.
1129 $scope.initTab ? // initTab comes from patron app
1130 $scope.initTab('edit', $routeParams.id) : $q.when(),
1134 ]).then(function() {
1135 // called after initTab and patronRegSvc.init have completed
1137 var prs = patronRegSvc; // brevity
1138 // in standalone mode, we have no patronSvc
1139 $scope.patron = prs.init_patron(patronSvc ? patronSvc.current : null);
1140 $scope.field_doc = prs.field_doc;
1141 $scope.edit_profiles = prs.edit_profiles;
1142 $scope.ident_types = prs.ident_types;
1143 $scope.net_access_levels = prs.net_access_levels;
1144 $scope.user_setting_types = prs.user_setting_types;
1145 $scope.opt_in_setting_types = prs.opt_in_setting_types;
1146 $scope.org_settings = prs.org_settings;
1147 $scope.sms_carriers = prs.sms_carriers;
1148 $scope.stat_cats = prs.stat_cats;
1149 $scope.surveys = prs.surveys;
1150 $scope.survey_responses = prs.survey_responses;
1151 $scope.stat_cat_entry_maps = prs.stat_cat_entry_maps;
1152 $scope.stage_user = prs.stage_user;
1153 $scope.stage_user_requestor = prs.stage_user_requestor;
1155 $scope.user_settings = prs.user_settings;
1156 // clone the user settings back into the patronRegSvc so
1157 // we have a copy of the original state of the settings.
1158 prs.user_settings = {};
1159 angular.forEach($scope.user_settings, function(val, key) {
1160 prs.user_settings[key] = val;
1163 extract_hold_notify();
1164 $scope.handle_home_org_changed();
1166 if ($scope.org_settings['ui.patron.edit.default_suggested'])
1167 $scope.edit_passthru.vis_level = 1;
1169 if ($scope.patron.isnew)
1170 set_new_patron_defaults(prs);
1172 $scope.page_data_loaded = true;
1174 prs.set_field_patterns(field_patterns);
1177 // update the currently displayed field documentation
1178 $scope.set_selected_field_doc = function(cls, field) {
1179 $scope.selected_field_doc = $scope.field_doc[cls][field];
1182 // returns the tree depth of the selected profile group tree node.
1183 $scope.pgt_depth = function(grp) {
1185 while (grp = egCore.env.pgt.map[grp.parent()]) d++;
1189 // IDL fields used for labels in the UI.
1190 $scope.idl_fields = {
1191 au : egCore.idl.classes.au.field_map,
1192 ac : egCore.idl.classes.ac.field_map,
1193 aua : egCore.idl.classes.aua.field_map
1196 // field visibility cache. Some fields are universally required.
1197 // 3 == value universally required
1198 // 2 == field is visible by default
1199 // 1 == field is suggested by default
1200 var field_visibility = {
1204 'au.first_given_name' : 3,
1205 'au.family_name' : 3,
1206 'au.ident_type' : 3,
1209 'au.expire_date' : 3,
1210 'au.net_access_level' : 3,
1211 'aua.address_type' : 3,
1212 'aua.post_code' : 3,
1220 'aua.within_city_limits' : 2,
1225 // returns true if the selected field should be visible
1226 // given the current required/suggested/all setting.
1227 $scope.show_field = function(field_key) {
1229 if (field_visibility[field_key] == undefined) {
1230 // compile and cache the visibility for the selected field
1232 // org settings have not been received yet.
1233 if (!$scope.org_settings) return false;
1235 var req_set = 'ui.patron.edit.' + field_key + '.require';
1236 var sho_set = 'ui.patron.edit.' + field_key + '.show';
1237 var sug_set = 'ui.patron.edit.' + field_key + '.suggest';
1239 if ($scope.org_settings[req_set]) {
1240 field_visibility[field_key] = 3;
1241 } else if ($scope.org_settings[sho_set]) {
1242 field_visibility[field_key] = 2;
1243 } else if ($scope.org_settings[sug_set]) {
1244 field_visibility[field_key] = 1;
1246 field_visibility[field_key] = 0;
1250 return field_visibility[field_key] >= $scope.edit_passthru.vis_level;
1253 // See $scope.show_field().
1254 // A field with visbility level 3 means it's required.
1255 $scope.field_required = function(cls, field) {
1257 // Value in the password field is not required
1258 // for existing patrons.
1259 if (field == 'passwd' && $scope.patron && !$scope.patron.isnew)
1262 return (field_visibility[cls + '.' + field] == 3);
1265 // generates a random 4-digit password
1266 $scope.generate_password = function() {
1267 $scope.patron.passwd = Math.floor(Math.random()*9000) + 1000;
1270 $scope.set_expire_date = function() {
1271 if (!$scope.patron.profile) return;
1272 var seconds = egCore.date.intervalToSeconds(
1273 $scope.patron.profile.perm_interval());
1274 var now_epoch = new Date().getTime();
1275 $scope.patron.expire_date = new Date(
1276 now_epoch + (seconds * 1000 /* milliseconds */))
1279 // grp is the pgt object
1280 $scope.set_profile = function(grp) {
1281 $scope.patron.profile = grp;
1282 $scope.set_expire_date();
1283 $scope.field_modified();
1286 $scope.invalid_profile = function() {
1289 $scope.patron.profile &&
1290 $scope.patron.profile.usergroup() == 't'
1294 $scope.new_address = function() {
1295 var addr = egCore.idl.toHash(new egCore.idl.aua());
1296 patronRegSvc.ingest_address($scope.patron, addr);
1297 addr.id = patronRegSvc.virt_id--;
1300 addr.within_city_limits = true;
1301 addr.country = $scope.org_settings['ui.patron.default_country'];
1302 $scope.patron.addresses.push(addr);
1305 // keep deleted addresses out of the patron object so
1306 // they won't appear in the UI. They'll be re-inserted
1307 // when the patron is updated.
1308 deleted_addresses = [];
1309 $scope.delete_address = function(id) {
1311 angular.forEach($scope.patron.addresses, function(addr) {
1312 if (addr.id == id) {
1314 addr.isdeleted = true;
1315 deleted_addresses.push(addr);
1318 addresses.push(addr);
1321 $scope.patron.addresses = addresses;
1324 $scope.post_code_changed = function(addr) {
1326 'open-ils.search', 'open-ils.search.zip', addr.post_code)
1327 .then(function(resp) {
1329 if (resp.city) addr.city = resp.city;
1330 if (resp.state) addr.state = resp.state;
1331 if (resp.county) addr.county = resp.county;
1332 if (resp.alert) alert(resp.alert);
1336 $scope.replace_card = function() {
1337 $scope.patron.card.active = false;
1338 $scope.patron.card.ischanged = true;
1339 $scope.disable_bc = false;
1341 var new_card = egCore.idl.toHash(new egCore.idl.ac());
1342 new_card.id = patronRegSvc.virt_id--;
1343 new_card.isnew = true;
1344 new_card.active = true;
1345 new_card._primary = 'on';
1346 $scope.patron.card = new_card;
1347 $scope.patron.cards.push(new_card);
1350 $scope.day_phone_changed = function(phone) {
1351 if (phone && $scope.patron.isnew &&
1352 $scope.org_settings['patron.password.use_phone']) {
1353 $scope.patron.passwd = phone.substr(-4);
1357 $scope.barcode_changed = function(bc) {
1359 $scope.dupe_barcode = false;
1362 'open-ils.actor.barcode.exists',
1363 egCore.auth.token(), bc
1364 ).then(function(resp) {
1366 $scope.dupe_barcode = true;
1367 console.log('duplicate barcode detected: ' + bc);
1370 if (!$scope.patron.usrname)
1371 $scope.patron.usrname = bc;
1377 $scope.cards_dialog = function() {
1379 templateUrl: './circ/patron/t_patron_cards_dialog',
1381 ['$scope','$modalInstance','cards', 'perms',
1382 function($scope , $modalInstance , cards, perms) {
1383 // scope here is the modal-level scope
1384 $scope.args = {cards : cards};
1385 $scope.perms = perms;
1386 $scope.ok = function() { $modalInstance.close($scope.args) }
1387 $scope.cancel = function () { $modalInstance.dismiss() }
1390 cards : function() {
1391 // scope here is the controller-level scope
1392 return $scope.patron.cards;
1394 perms : function() {
1395 return $scope.perms;
1400 angular.forEach(args.cards, function(card) {
1401 card.ischanged = true; // assume cards need updating, OK?
1402 if (card._primary == 'on' &&
1403 card.id != $scope.patron.card.id) {
1404 $scope.patron.card = card;
1411 $scope.set_addr_type = function(addr, type) {
1412 var addrs = $scope.patron.addresses;
1413 if (addr['_is_'+type]) {
1414 angular.forEach(addrs, function(a) {
1415 if (a.id != addr.id) a['_is_'+type] = false;
1418 // unchecking mailing/billing means we have to randomly
1419 // select another address to fill that role. Select the
1420 // first address in the list (that does not match the
1422 for (var i = 0; i < addrs.length; i++) {
1423 if (addrs[i].id != addr.id) {
1424 addrs[i]['_is_' + type] = true;
1432 // Translate hold notify preferences from the form/scope back into a
1433 // single user setting value for opac.hold_notify.
1434 function compress_hold_notify() {
1435 var hold_notify = '';
1437 if ($scope.hold_notify_phone) {
1438 hold_notify = 'phone';
1441 if ($scope.hold_notify_email) {
1442 hold_notify = splitter + 'email';
1445 if ($scope.hold_notify_sms) {
1446 hold_notify = splitter + 'sms';
1449 $scope.user_settings['opac.hold_notify'] = hold_notify;
1452 // dialog for selecting additional permission groups
1453 $scope.secondary_groups_dialog = function() {
1455 templateUrl: './circ/patron/t_patron_groups_dialog',
1457 ['$scope','$modalInstance','linked_groups','pgt_depth',
1458 function($scope , $modalInstance , linked_groups , pgt_depth) {
1460 $scope.pgt_depth = pgt_depth;
1462 linked_groups : linked_groups,
1463 edit_profiles : patronRegSvc.edit_profiles,
1464 new_profile : patronRegSvc.edit_profiles[0]
1467 // add a new group to the linked groups list
1468 $scope.link_group = function($event, grp) {
1469 var found = false; // avoid duplicates
1470 angular.forEach($scope.args.linked_groups,
1471 function(g) {if (g.id() == grp.id()) found = true});
1472 if (!found) $scope.args.linked_groups.push(grp);
1473 $event.preventDefault(); // avoid close
1476 // remove a group from the linked groups list
1477 $scope.unlink_group = function($event, grp) {
1478 $scope.args.linked_groups =
1479 $scope.args.linked_groups.filter(function(g) {
1480 return g.id() != grp.id()
1482 $event.preventDefault(); // avoid close
1485 $scope.ok = function() { $modalInstance.close($scope.args) }
1486 $scope.cancel = function () { $modalInstance.dismiss() }
1489 linked_groups : function() { return $scope.patron.groups },
1490 pgt_depth : function() { return $scope.pgt_depth }
1495 if ($scope.patron.isnew) {
1496 // groups must be linked for new patrons after the
1497 // patron is created.
1498 $scope.patron.groups = args.linked_groups;
1502 // update links groups for existing users in real time.
1503 var ids = args.linked_groups.map(function(g) {return g.id()});
1504 patronRegSvc.apply_secondary_groups($scope.patron.id, ids)
1505 .then(function(success) {
1507 $scope.patron.groups = args.linked_groups;
1513 function extract_hold_notify() {
1514 notify = $scope.user_settings['opac.hold_notify'];
1515 if (!notify) return;
1516 $scope.hold_notify_phone = Boolean(notify.match(/phone/));
1517 $scope.hold_notify_email = Boolean(notify.match(/email/));
1518 $scope.hold_notify_sms = Boolean(notify.match(/sms/));
1521 $scope.invalidate_field = function(field) {
1522 patronRegSvc.invalidate_field($scope.patron, field);
1526 $scope.dupe_value_changed = function(type, value) {
1527 $scope.dupe_counts[type] = 0;
1528 patronRegSvc.dupe_patron_search($scope.patron, type, value)
1529 .then(function(res) {
1530 $scope.dupe_counts[type] = res.count;
1532 $scope.dupe_search_encoded =
1533 encodeURIComponent(js2JSON(res.search));
1535 $scope.dupe_search_encoded = '';
1540 $scope.handle_home_org_changed = function() {
1541 org_id = $scope.patron.home_ou.id();
1542 patronRegSvc.has_perms_for_org(org_id).then(function(map) {
1543 angular.forEach(map, function(v, k) { $scope.perms[k] = v });
1547 // This is called with every character typed in a form field,
1548 // since that's the only way to gaurantee something has changed.
1549 // See handle_field_changed for ng-change vs. ng-blur.
1550 $scope.field_modified = function() {
1551 // Call attach with every field change, regardless of whether
1552 // it's been called before. This will allow for re-attach after
1553 // the user clicks through the unload warning. egUnloadPrompt
1554 // will ensure we only attach once.
1555 egUnloadPrompt.attach($scope);
1558 // obj could be the patron, an address, etc.
1559 // This is called any time a form field achieves then loses focus.
1560 // It does not necessarily mean the field has changed.
1561 // The alternative is ng-change, but it's called with each character
1562 // typed, which would be overkill for many of the actions called here.
1563 $scope.handle_field_changed = function(obj, field_name) {
1564 var cls = obj.classname; // set by egIdl
1565 var value = obj[field_name];
1567 console.log('changing field ' + field_name + ' to ' + value);
1569 switch (field_name) {
1571 if ($scope.patron.day_phone &&
1572 $scope.patron.isnew &&
1573 $scope.org_settings['patron.password.use_phone']) {
1574 $scope.patron.passwd = phone.substr(-4);
1576 case 'evening_phone' :
1577 case 'other_phone' :
1578 $scope.dupe_value_changed('phone', value);
1582 case 'ident_value2':
1583 $scope.dupe_value_changed('ident', value);
1586 case 'first_given_name':
1588 $scope.dupe_value_changed('name', value);
1592 $scope.dupe_value_changed('email', value);
1598 // dupe search on address wants the address object as the value.
1599 $scope.dupe_value_changed('address', obj);
1603 $scope.post_code_changed(obj);
1607 patronRegSvc.check_dupe_username(value)
1608 .then(function(yes) {$scope.dupe_username = Boolean(yes)});
1612 // TODO: finish barcode_changed handler.
1613 $scope.barcode_changed(value);
1617 maintain_juvenile_flag();
1622 // patron.juvenile is set to true if the user was born after
1623 function maintain_juvenile_flag() {
1624 if ( !($scope.patron && $scope.patron.dob) ) return;
1627 $scope.org_settings['global.juvenile_age_threshold']
1630 var base = new Date();
1632 base.setTime(base.getTime() -
1633 Number(egCore.date.intervalToSeconds(juv_interval) + '000'));
1635 $scope.patron.juvenile = ($scope.patron.dob > base);
1638 // returns true (disable) for orgs that cannot have users.
1639 $scope.disable_home_org = function(org_id) {
1640 if (!org_id) return;
1641 var org = egCore.org.get(org_id);
1645 org.ou_type().can_have_users() == 'f'
1649 // Returns true if any input elements are tagged as invalid
1650 $scope.edit_passthru.has_invalid_fields = function() {
1651 return $('#patron-reg-container .ng-invalid').length > 0;
1654 // Returns true if the Save and Save & Clone buttons should be disabled.
1655 $scope.edit_passthru.hide_save_actions = function() {
1656 var can_save = $scope.patron.isnew ?
1657 $scope.perms.CREATE_USER : $scope.perms.UPDATE_USER;
1661 $scope.dupe_username ||
1662 $scope.dupe_barcode ||
1663 $scope.edit_passthru.has_invalid_fields()
1667 $scope.edit_passthru.save = function(save_args) {
1668 if (!save_args) save_args = {};
1670 // remove page unload warning prompt
1671 egUnloadPrompt.clear();
1673 // toss the deleted addresses back into the patron's list of
1674 // addresses so it's included in the update
1675 $scope.patron.addresses =
1676 $scope.patron.addresses.concat(deleted_addresses);
1678 compress_hold_notify();
1682 patronRegSvc.save_user($scope.patron)
1683 .then(function(new_user) {
1684 if (new_user && new_user.classname) {
1685 updated_user = new_user;
1686 return patronRegSvc.save_user_settings(
1687 new_user, $scope.user_settings);
1689 alert('Patron update failed. \n\n' + js2JSON(new_user));
1692 }).then(function() {
1694 // only remove the staged user if the update succeeded.
1696 return patronRegSvc.remove_staged_user();
1700 }).then(function() {
1702 // linked groups for new users must be created after the new
1704 if ($scope.patron.isnew &&
1705 $scope.patron.groups && $scope.patron.groups.length) {
1706 var ids = $scope.patron.groups.map(function(g) {return g.id()});
1707 return patronRegSvc.apply_secondary_groups(updated_user.id(), ids)
1712 }).then(function() {
1714 // reloading the page means potentially losing some information
1715 // (e.g. last patron search), but is the only way to ensure all
1716 // components are properly updated to reflect the modified patron.
1717 if (updated_user && save_args.clone) {
1718 // open a separate tab for registering a new
1719 // patron from our cloned data.
1720 var url = 'https://'
1721 + $window.location.hostname
1722 + egCore.env.basePath
1723 + '/circ/patron/register/clone/'
1724 + updated_user.id();
1725 $window.open(url, '_blank').focus();
1728 // reload the current page
1729 $window.location.href = location.href;
1735 // This controller may be loaded from different modules (patron edit vs.
1736 // register new patron), so we have to inject the controller params manually.
1737 PatronRegCtrl.$inject = ['$scope', '$routeParams', '$q', '$modal',
1738 '$window', 'egCore', 'patronSvc', 'patronRegSvc', 'egUnloadPrompt'];