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) {
128 return egCore.net.request(
130 'open-ils.actor.username.exists',
131 egCore.auth.token(), usrname);
134 //service.check_grp_app_perm = function(grp_id) {
136 // determine which user groups our user is not allowed to modify
137 service.set_edit_profiles = function() {
138 var all_app_perms = [];
139 var failed_perms = [];
141 // extract the application permissions
142 angular.forEach(service.profiles, function(grp) {
143 if (grp.application_perm())
144 all_app_perms.push(grp.application_perm());
147 // fill in service.edit_profiles by inspecting failed_perms
148 function traverse_grp_tree(grp, failed) {
150 failed_perms.indexOf(grp.application_perm()) > -1;
152 if (!failed) service.edit_profiles.push(grp);
155 service.profiles.filter( // children of grp
156 function(p) { return p.parent() == grp.id() }),
157 function(child) {traverse_grp_tree(child, failed)}
161 return egCore.perm.hasPermAt(all_app_perms, true).then(
162 function(perm_orgs) {
163 angular.forEach(all_app_perms, function(p) {
164 if (perm_orgs[p].length == 0)
165 failed_perms.push(p);
168 traverse_grp_tree(egCore.env.pgt.tree);
173 // resolves to a hash of perm-name => boolean value indicating
174 // wether the user has the permission at org_id.
175 service.has_perms_for_org = function(org_id) {
180 'CREATE_USER_GROUP_LINK',
181 'UPDATE_PATRON_COLLECTIONS_EXEMPT',
182 'UPDATE_PATRON_CLAIM_RETURN_COUNT',
183 'UPDATE_PATRON_CLAIM_NEVER_CHECKED_OUT_COUNT',
184 'UPDATE_PATRON_ACTIVE_CARD',
185 'UPDATE_PATRON_PRIMARY_CARD'
188 return egCore.perm.hasPermAt(perms_needed, true)
189 .then(function(perm_map) {
191 angular.forEach(perms_needed, function(perm) {
193 Boolean(perm_map[perm].indexOf(org_id) > -1);
200 service.get_surveys = function() {
201 var org_ids = egCore.org.fullPath(egCore.auth.user().ws_ou(), true);
203 return egCore.pcrud.search('asv', {
205 start_date : {'<=' : 'now'},
206 end_date : {'>=' : 'now'}
215 ).then(function(surveys) {
216 surveys = surveys.sort(function(a,b) {
217 return a.name() < b.name() ? -1 : 1 });
218 service.surveys = surveys;
219 angular.forEach(surveys, function(survey) {
220 angular.forEach(survey.questions(), function(question) {
221 service.survey_questions[question.id()] = question;
222 angular.forEach(question.answers(), function(answer) {
223 service.survey_answers[answer.id()] = answer;
230 service.get_stat_cats = function() {
231 return egCore.net.request(
233 'open-ils.circ.stat_cat.actor.retrieve.all',
234 egCore.auth.token(), egCore.auth.user().ws_ou()
235 ).then(function(cats) {
236 cats = cats.sort(function(a, b) {
237 return a.name() < b.name() ? -1 : 1});
238 angular.forEach(cats, function(cat) {
240 cat.entries().sort(function(a,b) {
241 return a.value() < b.value() ? -1 : 1
245 service.stat_cats = cats;
249 service.get_org_settings = function() {
250 return egCore.org.settings([
251 'global.password_regex',
252 'global.juvenile_age_threshold',
253 'patron.password.use_phone',
254 'ui.patron.default_inet_access_level',
255 'ui.patron.default_ident_type',
256 'ui.patron.default_country',
257 'ui.patron.registration.require_address',
258 'circ.holds.behind_desk_pickup_supported',
259 'circ.patron_edit.clone.copy_address',
260 'ui.patron.edit.au.prefix.require',
261 'ui.patron.edit.au.prefix.show',
262 'ui.patron.edit.au.prefix.suggest',
263 'ui.patron.edit.ac.barcode.regex',
264 'ui.patron.edit.au.second_given_name.show',
265 'ui.patron.edit.au.second_given_name.suggest',
266 'ui.patron.edit.au.suffix.show',
267 'ui.patron.edit.au.suffix.suggest',
268 'ui.patron.edit.au.alias.show',
269 'ui.patron.edit.au.alias.suggest',
270 'ui.patron.edit.au.dob.require',
271 'ui.patron.edit.au.dob.show',
272 'ui.patron.edit.au.dob.suggest',
273 'ui.patron.edit.au.dob.calendar',
274 'ui.patron.edit.au.juvenile.show',
275 'ui.patron.edit.au.juvenile.suggest',
276 'ui.patron.edit.au.ident_value.show',
277 'ui.patron.edit.au.ident_value.suggest',
278 'ui.patron.edit.au.ident_value2.show',
279 'ui.patron.edit.au.ident_value2.suggest',
280 'ui.patron.edit.au.email.require',
281 'ui.patron.edit.au.email.show',
282 'ui.patron.edit.au.email.suggest',
283 'ui.patron.edit.au.email.regex',
284 'ui.patron.edit.au.email.example',
285 'ui.patron.edit.au.day_phone.require',
286 'ui.patron.edit.au.day_phone.show',
287 'ui.patron.edit.au.day_phone.suggest',
288 'ui.patron.edit.au.day_phone.regex',
289 'ui.patron.edit.au.day_phone.example',
290 'ui.patron.edit.au.evening_phone.require',
291 'ui.patron.edit.au.evening_phone.show',
292 'ui.patron.edit.au.evening_phone.suggest',
293 'ui.patron.edit.au.evening_phone.regex',
294 'ui.patron.edit.au.evening_phone.example',
295 'ui.patron.edit.au.other_phone.require',
296 'ui.patron.edit.au.other_phone.show',
297 'ui.patron.edit.au.other_phone.suggest',
298 'ui.patron.edit.au.other_phone.regex',
299 'ui.patron.edit.au.other_phone.example',
300 'ui.patron.edit.phone.regex',
301 'ui.patron.edit.phone.example',
302 'ui.patron.edit.au.active.show',
303 'ui.patron.edit.au.active.suggest',
304 'ui.patron.edit.au.barred.show',
305 'ui.patron.edit.au.barred.suggest',
306 'ui.patron.edit.au.master_account.show',
307 'ui.patron.edit.au.master_account.suggest',
308 'ui.patron.edit.au.claims_returned_count.show',
309 'ui.patron.edit.au.claims_returned_count.suggest',
310 'ui.patron.edit.au.claims_never_checked_out_count.show',
311 'ui.patron.edit.au.claims_never_checked_out_count.suggest',
312 'ui.patron.edit.au.alert_message.show',
313 'ui.patron.edit.au.alert_message.suggest',
314 'ui.patron.edit.aua.post_code.regex',
315 'ui.patron.edit.aua.post_code.example',
316 'ui.patron.edit.aua.county.require',
318 'ui.patron.edit.default_suggested',
319 'opac.barcode_regex',
320 'opac.username_regex',
322 'ui.patron.edit.aua.state.require',
323 'ui.patron.edit.aua.state.suggest',
324 'ui.patron.edit.aua.state.show'
325 ]).then(function(settings) {
326 service.org_settings = settings;
327 return service.process_org_settings(settings);
331 // some org settings require the retrieval of additional data
332 service.process_org_settings = function(settings) {
336 if (settings['sms.enable']) {
337 // fetch SMS carriers
339 egCore.pcrud.search('csc',
342 {'class':'csc', 'field':'name'},
343 {'class':'csc', 'field':'region'}
345 ).then(function(carriers) {
346 service.sms_carriers = carriers;
350 // if other promises are added below, this is not necessary.
351 promises.push($q.when());
354 // other post-org-settings processing goes here,
355 // adding to promises as needed.
357 return $q.all(promises);
360 service.get_ident_types = function() {
361 if (egCore.env.cit) {
362 service.ident_types = egCore.env.cit.list;
365 return egCore.pcrud.retrieveAll('cit', {}, {atomic : true})
366 .then(function(types) {
367 egCore.env.absorbList(types, 'cit')
368 service.ident_types = types
373 service.get_net_access_levels = function() {
374 if (egCore.env.cnal) {
375 service.net_access_levels = egCore.env.cnal.list;
378 return egCore.pcrud.retrieveAll('cnal', {}, {atomic : true})
379 .then(function(levels) {
380 egCore.env.absorbList(levels, 'cnal')
381 service.net_access_levels = levels
386 service.get_perm_groups = function() {
387 if (egCore.env.pgt) {
388 service.profiles = egCore.env.pgt.list;
389 return service.set_edit_profiles();
391 return egCore.pcrud.search('pgt', {parent : null},
392 {flesh : -1, flesh_fields : {pgt : ['children']}}
395 egCore.env.absorbTree(tree, 'pgt')
396 service.profiles = egCore.env.pgt.list;
397 return service.set_edit_profiles();
403 service.get_field_doc = function() {
404 return egCore.pcrud.search('fdoc', {
405 fm_class: ['au', 'ac', 'aua', 'actsc', 'asv', 'asvq', 'asva']})
406 .then(null, null, function(doc) {
407 if (!service.field_doc[doc.fm_class()]) {
408 service.field_doc[doc.fm_class()] = {};
410 service.field_doc[doc.fm_class()][doc.field()] = doc;
414 service.get_user_settings = function() {
415 var org_ids = egCore.org.ancestors(egCore.auth.user().ws_ou(), true);
418 'circ.holds_behind_desk',
419 'circ.collections.exempt',
421 'opac.default_phone',
422 'opac.default_pickup_location',
423 'opac.default_sms_carrier',
424 'opac.default_sms_notify'];
426 return egCore.pcrud.search('cust', {
428 {name : static_types}, // common user settings
429 {name : { // opt-in notification user settings
431 select : {atevdef : ['opt_in_setting']},
433 // we only care about opt-in settings for
434 // event_defs our users encounter
435 where : {'+atevdef' : {owner : org_ids}}
439 }, {}, {atomic : true}).then(function(setting_types) {
441 angular.forEach(setting_types, function(stype) {
442 service.user_setting_types[stype.name()] = stype;
443 if (static_types.indexOf(stype.name()) == -1) {
444 service.opt_in_setting_types[stype.name()] = stype;
448 if (service.patron_id) {
449 // retrieve applied values for the current user
450 // for the setting types we care about.
453 setting_types.map(function(obj) { return obj.name() });
455 return egCore.net.request(
457 'open-ils.actor.patron.settings.retrieve.authoritative',
461 ).then(function(settings) {
462 service.user_settings = settings;
466 // apply default user setting values
467 angular.forEach(setting_types, function(stype, index) {
468 if (stype.reg_default() != undefined) {
469 service.user_settings[setting.name()] =
470 setting.reg_default();
477 service.invalidate_field = function(patron, field) {
478 console.log('Invalidating patron field ' + field);
480 return egCore.net.request(
482 'open-ils.actor.invalidate.' + field,
483 egCore.auth.token(), patron.id, null, patron.home_ou.id()
485 ).then(function(res) {
486 // clear the invalid value from the form
489 // update last_xact_id so future save operations
490 // on this patron will be allowed
491 patron.last_xact_id = res.payload.last_xact_id[patron.id];
495 service.dupe_patron_search = function(patron, type, value) {
498 console.log('Dupe search called with "'+ type +'" and value '+ value);
503 var fname = patron.first_given_name;
504 var lname = patron.family_name;
505 if (!(fname && lname)) return $q.when({count:0});
507 first_given_name : {value : fname, group : 0},
508 family_name : {value : lname, group : 0}
513 search = {email : {value : value, group : 0}};
517 search = {ident : {value : value, group : 2}};
521 search = {phone : {value : value, group : 2}};
526 angular.forEach(['street1', 'street2', 'city', 'post_code'],
529 search[field] = {value : value[field], group: 1};
535 return egCore.net.request(
537 'open-ils.actor.patron.search.advanced',
538 egCore.auth.token(), search, null, null, 1
539 ).then(function(res) {
540 res = res.filter(function(id) {return id != patron.id});
548 service.init_patron = function(current) {
551 return service.init_new_patron();
553 service.patron = current;
554 return service.init_existing_patron(current)
557 service.ingest_address = function(patron, addr) {
558 addr.valid = addr.valid == 't';
559 addr.within_city_limits = addr.within_city_limits == 't';
560 addr._is_mailing = (patron.mailing_address &&
561 addr.id == patron.mailing_address.id);
562 addr._is_billing = (patron.billing_address &&
563 addr.id == patron.billing_address.id);
567 * Existing patron objects reqire some data munging before insertion
570 * 1. Turn everything into a hash
571 * 2. ... Except certain fields (selectors) whose widgets require objects
572 * 3. Bools must be Boolean, not t/f.
574 service.init_existing_patron = function(current) {
576 var patron = egCore.idl.toHash(current);
578 patron.home_ou = egCore.org.get(patron.home_ou.id);
579 patron.expire_date = new Date(Date.parse(patron.expire_date));
580 patron.dob = service.parse_dob(patron.dob);
581 patron.profile = current.profile(); // pre-hash version
582 patron.net_access_level = current.net_access_level();
583 patron.ident_type = current.ident_type();
584 patron.groups = current.groups(); // pre-hash
587 ['juvenile', 'barred', 'active', 'master_account'],
588 function(field) { patron[field] = patron[field] == 't'; }
591 angular.forEach(patron.cards, function(card) {
592 card.active = card.active == 't';
593 if (card.id == patron.card.id) {
595 card._primary = 'on';
599 angular.forEach(patron.addresses,
600 function(addr) { service.ingest_address(patron, addr) });
602 // toss entries for existing stat cat maps into our living
603 // stat cat entry map, which is modified within the template.
604 angular.forEach(patron.stat_cat_entries, function(map) {
605 service.stat_cat_entry_maps[map.stat_cat.id] = map.stat_cat_entry;
611 service.init_new_patron = function() {
613 id : service.virt_id--,
616 address_type : egCore.strings.REG_ADDR_TYPE,
619 within_city_limits : false,
620 country : service.org_settings['ui.patron.default_country'],
624 id : service.virt_id--,
635 home_ou : egCore.org.get(egCore.auth.user().ws_ou()),
636 stat_cat_entries : [],
641 if (service.clone_user)
642 service.copy_clone_data(user);
644 if (service.stage_user)
645 service.copy_stage_data(user);
650 // dob is always YYYY-MM-DD
651 // Dates of birth do not contain timezone info, which can lead to
652 // inconcistent timezone handling, potentially representing
653 // different points in time, depending on the implementation.
654 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
655 // See "Differences in assumed time zone"
656 // TODO: move this into egDate ?
657 service.parse_dob = function(dob) {
658 if (!dob) return null;
659 var parts = dob.split('-');
660 var d = new Date(); // always local time zone, yay.
661 d.setFullYear(parts[0]);
662 d.setMonth(parts[1]);
667 service.copy_stage_data = function(user) {
668 var cuser = service.stage_user;
670 // copy the data into our new user object
672 for (var key in egCore.idl.classes.stgu.field_map) {
673 if (egCore.idl.classes.au.field_map[key] &&
674 !egCore.idl.classes.stgu.field_map[key].virtual) {
675 if (cuser.user[key]() !== null)
676 user[key] = cuser.user[key]();
680 if (user.home_ou) user.home_ou = egCore.org.get(user.home_ou);
681 if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
683 user.ident_type = egCore.env.cit.map[user.ident_type];
684 user.dob = service.parse_dob(user.dob);
686 // Clear the usrname if it looks like a UUID
687 if (user.usrname.replace(/-/g,'').match(/[0-9a-f]{32}/))
690 // Don't use stub address if we have one from the staged user.
691 if (cuser.mailing_addresses.length || cuser.billing_addresses.length)
694 // is_mailing=false implies is_billing
695 function addr_from_stage(stage_addr) {
696 if (!stage_addr) return;
697 var cls = stage_addr.classname;
700 id : service.virt_id--,
704 _is_mailing : cls == 'stgma',
705 _is_billing : cls == 'stgba'
708 user.mailing_address = addr;
709 user.addresses.push(addr);
711 for (var key in egCore.idl.classes[cls].field_map) {
712 if (egCore.idl.classes.aua.field_map[key] &&
713 !egCore.idl.classes[cls].field_map[key].virtual) {
714 if (stage_addr[key]() !== null)
715 addr[key] = stage_addr[key]();
720 addr_from_stage(cuser.mailing_addresses[0]);
721 addr_from_stage(cuser.billing_addresses[0]);
723 if (user.addresses.length == 1) {
724 // If there is only one address,
725 // use it as both mailing and billing.
726 var addr = user.addresses[0];
727 addr._is_mailing = addr._is_billing = true;
728 user.mailing_address = user.billing_address = addr;
731 if (cuser.cards.length) {
733 id : service.virt_id--,
734 barcode : cuser.cards[0].barcode(),
740 user.cards.push(user.card);
741 if (user.usrname == '')
742 user.usrname = card.barcode;
746 // copy select values from the cloned user to the new user.
748 service.copy_clone_data = function(user) {
749 var clone_user = service.clone_user;
751 // flesh the home org locally
752 user.home_ou = egCore.org.get(clone_user.home_ou());
753 if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
755 if (!clone_user.billing_address() &&
756 !clone_user.mailing_address())
757 return; // no addresses to copy or link
759 // if the cloned user has any addresses, we don't need
760 // the stub address created in init_new_patron.
764 service.org_settings['circ.patron_edit.clone.copy_address'];
773 angular.forEach(clone_fields, function(field) {
774 user[field] = clone_user[field]();
777 if (copy_addresses) {
778 var bill_addr, mail_addr;
780 // copy the billing and mailing addresses into new addresses
781 function clone_addr(addr) {
782 var new_addr = egCore.idl.toHash(addr);
783 new_addr.id = service.virt_id--;
784 new_addr.usr = user.id;
785 new_addr.isnew = true;
786 new_addr.valid = true;
787 user.addresses.push(new_addr);
791 if (bill_addr = clone_user.billing_address()) {
792 var addr = clone_addr(bill_addr);
793 addr._is_billing = true;
794 user.billing_address = addr;
797 if (mail_addr = clone_user.mailing_address()) {
799 if (bill_addr && bill_addr.id() == mail_addr.id()) {
800 user.mailing_address = user.billing_address;
801 user.mailing_address._is_mailing = true;
803 var addr = clone_addr(mail_addr);
804 addr._is_mailing = true;
805 user.mailing_address = addr;
809 // if there is no billing addr, use the mailing addr
810 user.billing_address = user.mailing_address;
811 user.billing_address._is_billing = true;
818 // link the billing and mailing addresses
820 if (addr = clone_user.billing_address()) {
821 user.billing_address = egCore.idl.toHash(addr);
822 user.billing_address._is_billing = true;
823 user.addresses.push(user.billing_address);
824 user.billing_address._linked_owner_id = clone_user.id();
825 user.billing_address._linked_owner = service.format_name(
826 clone_user.family_name(),
827 clone_user.first_given_name(),
828 clone_user.second_given_name()
832 if (addr = clone_user.mailing_address()) {
833 if (user.billing_address &&
834 addr.id() == user.billing_address.id) {
835 // mailing matches billing
836 user.mailing_address = user.billing_address;
837 user.mailing_address._is_mailing = true;
839 user.mailing_address = egCore.idl.toHash(addr);
840 user.mailing_address._is_mailing = true;
841 user.addresses.push(user.mailing_address);
842 user.mailing_address._linked_owner_id = clone_user.id();
843 user.mailing_address._linked_owner = service.format_name(
844 clone_user.family_name(),
845 clone_user.first_given_name(),
846 clone_user.second_given_name()
853 // translate the patron back into IDL form
854 service.save_user = function(phash) {
856 var patron = egCore.idl.fromHash('au', phash);
858 patron.home_ou(patron.home_ou().id());
859 patron.expire_date(patron.expire_date().toISOString());
860 patron.profile(patron.profile().id());
862 patron.dob(patron.dob().toISOString().replace(/T.*/,''));
863 if (patron.ident_type())
864 patron.ident_type(patron.ident_type().id());
865 if (patron.net_access_level())
866 patron.net_access_level(patron.net_access_level().id());
869 ['juvenile', 'barred', 'active', 'master_account'],
870 function(field) { patron[field](phash[field] ? 't' : 'f'); }
873 var card_hashes = patron.cards();
875 angular.forEach(card_hashes, function(chash) {
876 var card = egCore.idl.fromHash('ac', chash)
877 card.usr(patron.id());
878 card.active(chash.active ? 't' : 'f');
879 patron.cards().push(card);
880 if (chash._primary) {
885 var addr_hashes = patron.addresses();
886 patron.addresses([]);
887 angular.forEach(addr_hashes, function(addr_hash) {
888 if (!addr_hash.isnew && !addr_hash.isdeleted)
889 addr_hash.ischanged = true;
890 var addr = egCore.idl.fromHash('aua', addr_hash);
891 patron.addresses().push(addr);
892 addr.valid(addr.valid() ? 't' : 'f');
893 addr.within_city_limits(addr.within_city_limits() ? 't' : 'f');
894 if (addr_hash._is_mailing) patron.mailing_address(addr);
895 if (addr_hash._is_billing) patron.billing_address(addr);
898 patron.survey_responses([]);
899 angular.forEach(service.survey_responses, function(answer) {
900 var question = service.survey_questions[answer.question()];
901 var resp = new egCore.idl.asvr();
903 resp.survey(question.survey());
904 resp.question(question.id());
905 resp.answer(answer.id());
906 resp.usr(patron.id());
907 resp.answer_date('now');
908 patron.survey_responses().push(resp);
911 // re-object-ify the patron stat cat entry maps
913 angular.forEach(patron.stat_cat_entries(), function(entry) {
914 var e = egCore.idl.fromHash('actscecm', entry);
915 e.stat_cat(e.stat_cat().id);
918 patron.stat_cat_entries(maps);
920 // service.stat_cat_entry_maps maps stats to values
921 // patron.stat_cat_entries is an array of stat_cat_entry_usr_map's
923 service.stat_cat_entry_maps, function(value, cat_id) {
925 // see if we already have a mapping for this entry
926 var existing = patron.stat_cat_entries().filter(
927 function(e) { return e.stat_cat() == cat_id })[0];
929 if (existing) { // we have a mapping
930 // if the existing mapping matches the new one,
931 // there' nothing left to do
932 if (existing.stat_cat_entry() == value) return;
934 // mappings differ. delete the old one and create
936 existing.isdeleted(true);
939 var newmap = new egCore.idl.actscecm();
940 newmap.target_usr(patron.id());
942 newmap.stat_cat(cat_id);
943 newmap.stat_cat_entry(value);
944 patron.stat_cat_entries().push(newmap);
947 if (!patron.isnew()) patron.ischanged(true);
949 return egCore.net.request(
951 'open-ils.actor.patron.update',
952 egCore.auth.token(), patron);
955 service.remove_staged_user = function() {
956 if (!service.stage_user) return $q.when();
957 return egCore.net.request(
959 'open-ils.actor.user.stage.delete',
961 service.stage_user.row_id()
965 service.save_user_settings = function(new_user, user_settings) {
966 // user_settings contains the values from the scope/form.
967 // service.user_settings contain the values from page load time.
970 if (service.patron_id) {
971 // only update modified settings for existing patrons
972 angular.forEach(user_settings, function(val, key) {
973 if (val !== service.user_settings[key])
978 // all non-null setting values are updated for new patrons
979 angular.forEach(user_settings, function(val, key) {
980 if (val !== null) settings[key] = val;
984 if (Object.keys(settings).length == 0) return $q.when();
986 return egCore.net.request(
988 'open-ils.actor.patron.settings.update',
989 egCore.auth.token(), new_user.id(), settings
990 ).then(function(resp) {
995 // Applies field-specific validation regex's from org settings
996 // to form fields. Be careful not remove any pattern data we
997 // are not explicitly over-writing in the provided patterns obj.
998 service.set_field_patterns = function(patterns) {
999 if (service.org_settings['opac.username_regex']) {
1000 patterns.au.usrname =
1001 new RegExp(service.org_settings['opac.username_regex']);
1004 if (service.org_settings['opac.barcode_regex']) {
1005 patterns.ac.barcode =
1006 new RegExp(service.org_settings['opac.barcode_regex']);
1009 if (service.org_settings['global.password_regex']) {
1010 patterns.au.passwd =
1011 new RegExp(service.org_settings['global.password_regex']);
1014 var phone_reg = service.org_settings['ui.patron.edit.phone.regex'];
1016 // apply generic phone regex first, replace below as needed.
1017 patterns.au.day_phone = new RegExp(phone_reg);
1018 patterns.au.evening_phone = new RegExp(phone_reg);
1019 patterns.au.other_phone = new RegExp(phone_reg);
1022 // the remaining patterns fit a well-known key name pattern
1024 angular.forEach(service.org_settings, function(val, key) {
1026 var parts = key.match(/ui.patron.edit\.(\w+)\.(\w+)\.regex/);
1029 var name = parts[2];
1030 patterns[cls][name] = new RegExp(val);
1038 function PatronRegCtrl($scope, $routeParams,
1039 $q, $modal, $window, egCore, patronSvc, patronRegSvc, egUnloadPrompt) {
1041 $scope.page_data_loaded = false;
1042 $scope.clone_id = patronRegSvc.clone_id = $routeParams.clone_id;
1043 $scope.stage_username =
1044 patronRegSvc.stage_username = $routeParams.stage_username;
1046 patronRegSvc.patron_id = $routeParams.edit_id || $routeParams.id;
1048 // for existing patrons, disable barcode input by default
1049 $scope.disable_bc = $scope.focus_usrname = Boolean($scope.patron_id);
1050 $scope.focus_bc = !Boolean($scope.patron_id);
1051 $scope.dupe_counts = {};
1053 // map of perm name to true/false for perms the logged in user
1054 // has at the currently selected patron home org unit.
1057 if (!$scope.edit_passthru) {
1058 // in edit more, scope.edit_passthru is delivered to us by
1059 // the enclosing controller. In register mode, there is
1060 // no enclosing controller, so we create our own.
1061 $scope.edit_passthru = {};
1064 // 0=all, 1=suggested, 2=all
1065 $scope.edit_passthru.vis_level = 0;
1067 // Apply default values for new patrons during initial registration
1068 // prs is shorthand for patronSvc
1069 function set_new_patron_defaults(prs) {
1070 if (!$scope.patron.passwd) {
1071 // passsword may originate from staged user.
1072 $scope.generate_password();
1074 $scope.hold_notify_phone = true;
1075 $scope.hold_notify_email = true;
1077 // staged users may be loaded w/ a profile.
1078 $scope.set_expire_date();
1080 if (prs.org_settings['ui.patron.default_ident_type']) {
1081 // $scope.patron needs this field to be an object
1082 var id = prs.org_settings['ui.patron.default_ident_type'];
1083 var ident_type = $scope.ident_types.filter(
1084 function(type) { return type.id() == id })[0];
1085 $scope.patron.ident_type = ident_type;
1087 if (prs.org_settings['ui.patron.default_inet_access_level']) {
1088 // $scope.patron needs this field to be an object
1089 var id = prs.org_settings['ui.patron.default_inet_access_level'];
1090 var level = $scope.net_access_levels.filter(
1091 function(lvl) { return lvl.id() == id })[0];
1092 $scope.patron.net_access_level = level;
1094 if (prs.org_settings['ui.patron.default_country']) {
1095 $scope.patron.addresses[0].country =
1096 prs.org_settings['ui.patron.default_country'];
1100 // A null or undefined pattern leads to exceptions. Before the
1101 // patterns are loaded from the server, default all patterns
1102 // to an innocuous regex. To avoid re-creating numerous
1103 // RegExp objects, cache the stub RegExp after initial creation.
1104 // note: angular docs say ng-pattern accepts a regexp or string,
1105 // but as of writing, it only works with a regexp object.
1106 // (Likely an angular 1.2 vs. 1.4 issue).
1107 var field_patterns = {au : {}, ac : {}, aua : {}};
1108 $scope.field_pattern = function(cls, field) {
1109 if (!field_patterns[cls][field])
1110 field_patterns[cls][field] = new RegExp('.*');
1111 return field_patterns[cls][field];
1114 // Main page load function. Kicks off tab init and data loading.
1117 $scope.initTab ? // initTab comes from patron app
1118 $scope.initTab('edit', $routeParams.id) : $q.when(),
1122 ]).then(function() {
1123 // called after initTab and patronRegSvc.init have completed
1125 var prs = patronRegSvc; // brevity
1126 // in standalone mode, we have no patronSvc
1127 $scope.patron = prs.init_patron(patronSvc ? patronSvc.current : null);
1128 $scope.field_doc = prs.field_doc;
1129 $scope.edit_profiles = prs.edit_profiles;
1130 $scope.ident_types = prs.ident_types;
1131 $scope.net_access_levels = prs.net_access_levels;
1132 $scope.user_setting_types = prs.user_setting_types;
1133 $scope.opt_in_setting_types = prs.opt_in_setting_types;
1134 $scope.org_settings = prs.org_settings;
1135 $scope.sms_carriers = prs.sms_carriers;
1136 $scope.stat_cats = prs.stat_cats;
1137 $scope.surveys = prs.surveys;
1138 $scope.survey_responses = prs.survey_responses;
1139 $scope.stat_cat_entry_maps = prs.stat_cat_entry_maps;
1140 $scope.stage_user = prs.stage_user;
1141 $scope.stage_user_requestor = prs.stage_user_requestor;
1143 $scope.user_settings = prs.user_settings;
1144 // clone the user settings back into the patronRegSvc so
1145 // we have a copy of the original state of the settings.
1146 prs.user_settings = {};
1147 angular.forEach($scope.user_settings, function(val, key) {
1148 prs.user_settings[key] = val;
1151 extract_hold_notify();
1152 $scope.handle_home_org_changed();
1154 if ($scope.org_settings['ui.patron.edit.default_suggested'])
1155 $scope.edit_passthru.vis_level = 1;
1157 if ($scope.patron.isnew)
1158 set_new_patron_defaults(prs);
1160 $scope.page_data_loaded = true;
1162 prs.set_field_patterns(field_patterns);
1165 // update the currently displayed field documentation
1166 $scope.set_selected_field_doc = function(cls, field) {
1167 $scope.selected_field_doc = $scope.field_doc[cls][field];
1170 // returns the tree depth of the selected profile group tree node.
1171 $scope.pgt_depth = function(grp) {
1173 while (grp = egCore.env.pgt.map[grp.parent()]) d++;
1177 // IDL fields used for labels in the UI.
1178 $scope.idl_fields = {
1179 au : egCore.idl.classes.au.field_map,
1180 ac : egCore.idl.classes.ac.field_map,
1181 aua : egCore.idl.classes.aua.field_map
1184 // field visibility cache. Some fields are universally required.
1185 // 3 == value universally required
1186 // 2 == field is visible by default
1187 // 1 == field is suggested by default
1188 var field_visibility = {
1192 'au.first_given_name' : 3,
1193 'au.family_name' : 3,
1194 'au.ident_type' : 3,
1197 'au.expire_date' : 3,
1198 'au.net_access_level' : 3,
1199 'aua.address_type' : 3,
1200 'aua.post_code' : 3,
1208 'aua.within_city_limits' : 2,
1213 // returns true if the selected field should be visible
1214 // given the current required/suggested/all setting.
1215 $scope.show_field = function(field_key) {
1217 if (field_visibility[field_key] == undefined) {
1218 // compile and cache the visibility for the selected field
1220 // org settings have not been received yet.
1221 if (!$scope.org_settings) return false;
1223 var req_set = 'ui.patron.edit.' + field_key + '.require';
1224 var sho_set = 'ui.patron.edit.' + field_key + '.show';
1225 var sug_set = 'ui.patron.edit.' + field_key + '.suggest';
1227 if ($scope.org_settings[req_set]) {
1228 field_visibility[field_key] = 3;
1229 } else if ($scope.org_settings[sho_set]) {
1230 field_visibility[field_key] = 2;
1231 } else if ($scope.org_settings[sug_set]) {
1232 field_visibility[field_key] = 1;
1234 field_visibility[field_key] = 0;
1238 return field_visibility[field_key] >= $scope.edit_passthru.vis_level;
1241 // See $scope.show_field().
1242 // A field with visbility level 3 means it's required.
1243 $scope.field_required = function(cls, field) {
1245 // Value in the password field is not required
1246 // for existing patrons.
1247 if (field == 'passwd' && $scope.patron && !$scope.patron.isnew)
1250 return (field_visibility[cls + '.' + field] == 3);
1253 // generates a random 4-digit password
1254 $scope.generate_password = function() {
1255 $scope.patron.passwd = Math.floor(Math.random()*9000) + 1000;
1258 $scope.set_expire_date = function() {
1259 if (!$scope.patron.profile) return;
1260 var seconds = egCore.date.intervalToSeconds(
1261 $scope.patron.profile.perm_interval());
1262 var now_epoch = new Date().getTime();
1263 $scope.patron.expire_date = new Date(
1264 now_epoch + (seconds * 1000 /* milliseconds */))
1267 // grp is the pgt object
1268 $scope.set_profile = function(grp) {
1269 $scope.patron.profile = grp;
1270 $scope.set_expire_date();
1271 $scope.field_modified();
1274 $scope.invalid_profile = function() {
1277 $scope.patron.profile &&
1278 $scope.patron.profile.usergroup() == 't'
1282 $scope.new_address = function() {
1283 var addr = egCore.idl.toHash(new egCore.idl.aua());
1284 patronRegSvc.ingest_address($scope.patron, addr);
1285 addr.id = patronRegSvc.virt_id--;
1288 addr.within_city_limits = true;
1289 addr.country = $scope.org_settings['ui.patron.default_country'];
1290 $scope.patron.addresses.push(addr);
1293 // keep deleted addresses out of the patron object so
1294 // they won't appear in the UI. They'll be re-inserted
1295 // when the patron is updated.
1296 deleted_addresses = [];
1297 $scope.delete_address = function(id) {
1299 angular.forEach($scope.patron.addresses, function(addr) {
1300 if (addr.id == id) {
1302 addr.isdeleted = true;
1303 deleted_addresses.push(addr);
1306 addresses.push(addr);
1309 $scope.patron.addresses = addresses;
1312 $scope.post_code_changed = function(addr) {
1314 'open-ils.search', 'open-ils.search.zip', addr.post_code)
1315 .then(function(resp) {
1317 if (resp.city) addr.city = resp.city;
1318 if (resp.state) addr.state = resp.state;
1319 if (resp.county) addr.county = resp.county;
1320 if (resp.alert) alert(resp.alert);
1324 $scope.replace_card = function() {
1325 $scope.patron.card.active = false;
1326 $scope.patron.card.ischanged = true;
1327 $scope.disable_bc = false;
1329 var new_card = egCore.idl.toHash(new egCore.idl.ac());
1330 new_card.id = patronRegSvc.virt_id--;
1331 new_card.isnew = true;
1332 new_card.active = true;
1333 new_card._primary = 'on';
1334 $scope.patron.card = new_card;
1335 $scope.patron.cards.push(new_card);
1338 $scope.day_phone_changed = function(phone) {
1339 if (phone && $scope.patron.isnew &&
1340 $scope.org_settings['patron.password.use_phone']) {
1341 $scope.patron.passwd = phone.substr(-4);
1345 $scope.barcode_changed = function(bc) {
1347 $scope.dupe_barcode = false;
1350 'open-ils.actor.barcode.exists',
1351 egCore.auth.token(), bc
1352 ).then(function(resp) {
1354 $scope.dupe_barcode = true;
1355 console.log('duplicate barcode detected: ' + bc);
1358 if (!$scope.patron.usrname)
1359 $scope.patron.usrname = bc;
1365 $scope.cards_dialog = function() {
1367 templateUrl: './circ/patron/t_patron_cards_dialog',
1369 ['$scope','$modalInstance','cards', 'perms',
1370 function($scope , $modalInstance , cards, perms) {
1371 // scope here is the modal-level scope
1372 $scope.args = {cards : cards};
1373 $scope.perms = perms;
1374 $scope.ok = function() { $modalInstance.close($scope.args) }
1375 $scope.cancel = function () { $modalInstance.dismiss() }
1378 cards : function() {
1379 // scope here is the controller-level scope
1380 return $scope.patron.cards;
1382 perms : function() {
1383 return $scope.perms;
1388 angular.forEach(args.cards, function(card) {
1389 card.ischanged = true; // assume cards need updating, OK?
1390 if (card._primary == 'on' &&
1391 card.id != $scope.patron.card.id) {
1392 $scope.patron.card = card;
1399 $scope.set_addr_type = function(addr, type) {
1400 var addrs = $scope.patron.addresses;
1401 if (addr['_is_'+type]) {
1402 angular.forEach(addrs, function(a) {
1403 if (a.id != addr.id) a['_is_'+type] = false;
1406 // unchecking mailing/billing means we have to randomly
1407 // select another address to fill that role. Select the
1408 // first address in the list (that does not match the
1410 for (var i = 0; i < addrs.length; i++) {
1411 if (addrs[i].id != addr.id) {
1412 addrs[i]['_is_' + type] = true;
1420 // Translate hold notify preferences from the form/scope back into a
1421 // single user setting value for opac.hold_notify.
1422 function compress_hold_notify() {
1423 var hold_notify = '';
1425 if ($scope.hold_notify_phone) {
1426 hold_notify = 'phone';
1429 if ($scope.hold_notify_email) {
1430 hold_notify = splitter + 'email';
1433 if ($scope.hold_notify_sms) {
1434 hold_notify = splitter + 'sms';
1437 $scope.user_settings['opac.hold_notify'] = hold_notify;
1440 // dialog for selecting additional permission groups
1441 $scope.secondary_groups_dialog = function() {
1443 templateUrl: './circ/patron/t_patron_groups_dialog',
1445 ['$scope','$modalInstance','linked_groups','pgt_depth',
1446 function($scope , $modalInstance , linked_groups , pgt_depth) {
1448 $scope.pgt_depth = pgt_depth;
1450 linked_groups : linked_groups,
1451 edit_profiles : patronRegSvc.edit_profiles,
1452 new_profile : patronRegSvc.edit_profiles[0]
1455 // add a new group to the linked groups list
1456 $scope.link_group = function($event, grp) {
1457 var found = false; // avoid duplicates
1458 angular.forEach($scope.args.linked_groups,
1459 function(g) {if (g.id() == grp.id()) found = true});
1460 if (!found) $scope.args.linked_groups.push(grp);
1461 $event.preventDefault(); // avoid close
1464 // remove a group from the linked groups list
1465 $scope.unlink_group = function($event, grp) {
1466 $scope.args.linked_groups =
1467 $scope.args.linked_groups.filter(function(g) {
1468 return g.id() != grp.id()
1470 $event.preventDefault(); // avoid close
1473 $scope.ok = function() { $modalInstance.close($scope.args) }
1474 $scope.cancel = function () { $modalInstance.dismiss() }
1477 linked_groups : function() { return $scope.patron.groups },
1478 pgt_depth : function() { return $scope.pgt_depth }
1483 if ($scope.patron.isnew) {
1484 // groups must be linked for new patrons after the
1485 // patron is created.
1486 $scope.patron.groups = args.linked_groups;
1490 // update links groups for existing users in real time.
1491 var ids = args.linked_groups.map(function(g) {return g.id()});
1492 patronRegSvc.apply_secondary_groups($scope.patron.id, ids)
1493 .then(function(success) {
1495 $scope.patron.groups = args.linked_groups;
1501 function extract_hold_notify() {
1502 notify = $scope.user_settings['opac.hold_notify'];
1503 if (!notify) return;
1504 $scope.hold_notify_phone = Boolean(notify.match(/phone/));
1505 $scope.hold_notify_email = Boolean(notify.match(/email/));
1506 $scope.hold_notify_sms = Boolean(notify.match(/sms/));
1509 $scope.invalidate_field = function(field) {
1510 patronRegSvc.invalidate_field($scope.patron, field);
1514 $scope.dupe_value_changed = function(type, value) {
1515 $scope.dupe_counts[type] = 0;
1516 patronRegSvc.dupe_patron_search($scope.patron, type, value)
1517 .then(function(res) {
1518 $scope.dupe_counts[type] = res.count;
1520 $scope.dupe_search_encoded =
1521 encodeURIComponent(js2JSON(res.search));
1523 $scope.dupe_search_encoded = '';
1528 $scope.handle_home_org_changed = function() {
1529 org_id = $scope.patron.home_ou.id();
1530 patronRegSvc.has_perms_for_org(org_id).then(function(map) {
1531 angular.forEach(map, function(v, k) { $scope.perms[k] = v });
1535 // This is called with every character typed in a form field,
1536 // since that's the only way to gaurantee something has changed.
1537 // See handle_field_changed for ng-change vs. ng-blur.
1538 $scope.field_modified = function() {
1539 // Call attach with every field change, regardless of whether
1540 // it's been called before. This will allow for re-attach after
1541 // the user clicks through the unload warning. egUnloadPrompt
1542 // will ensure we only attach once.
1543 egUnloadPrompt.attach($scope);
1546 // obj could be the patron, an address, etc.
1547 // This is called any time a form field achieves then loses focus.
1548 // It does not necessarily mean the field has changed.
1549 // The alternative is ng-change, but it's called with each character
1550 // typed, which would be overkill for many of the actions called here.
1551 $scope.handle_field_changed = function(obj, field_name) {
1552 var cls = obj.classname; // set by egIdl
1553 var value = obj[field_name];
1555 console.log('changing field ' + field_name + ' to ' + value);
1557 switch (field_name) {
1559 if ($scope.patron.day_phone &&
1560 $scope.patron.isnew &&
1561 $scope.org_settings['patron.password.use_phone']) {
1562 $scope.patron.passwd = phone.substr(-4);
1564 case 'evening_phone' :
1565 case 'other_phone' :
1566 $scope.dupe_value_changed('phone', value);
1570 case 'ident_value2':
1571 $scope.dupe_value_changed('ident', value);
1574 case 'first_given_name':
1576 $scope.dupe_value_changed('name', value);
1580 $scope.dupe_value_changed('email', value);
1586 // dupe search on address wants the address object as the value.
1587 $scope.dupe_value_changed('address', obj);
1591 $scope.post_code_changed(obj);
1595 patronRegSvc.check_dupe_username(value)
1596 .then(function(yes) {$scope.dupe_username = Boolean(yes)});
1600 // TODO: finish barcode_changed handler.
1601 $scope.barcode_changed(value);
1605 maintain_juvenile_flag();
1610 // patron.juvenile is set to true if the user was born after
1611 function maintain_juvenile_flag() {
1612 if ( !($scope.patron && $scope.patron.dob) ) return;
1615 $scope.org_settings['global.juvenile_age_threshold']
1618 var base = new Date();
1620 base.setTime(base.getTime() -
1621 Number(egCore.date.intervalToSeconds(juv_interval) + '000'));
1623 $scope.patron.juvenile = ($scope.patron.dob > base);
1626 // returns true (disable) for orgs that cannot have users.
1627 $scope.disable_home_org = function(org_id) {
1628 if (!org_id) return;
1629 var org = egCore.org.get(org_id);
1633 org.ou_type().can_have_users() == 'f'
1637 // Returns true if any input elements are tagged as invalid
1638 $scope.edit_passthru.has_invalid_fields = function() {
1639 return $('#patron-reg-container .ng-invalid').length > 0;
1642 // Returns true if the Save and Save & Clone buttons should be disabled.
1643 $scope.edit_passthru.hide_save_actions = function() {
1644 var can_save = $scope.patron.isnew ?
1645 $scope.perms.CREATE_USER : $scope.perms.UPDATE_USER;
1649 $scope.dupe_username ||
1650 $scope.dupe_barcode ||
1651 $scope.edit_passthru.has_invalid_fields()
1655 $scope.edit_passthru.save = function(save_args) {
1656 if (!save_args) save_args = {};
1658 // remove page unload warning prompt
1659 egUnloadPrompt.clear();
1661 // toss the deleted addresses back into the patron's list of
1662 // addresses so it's included in the update
1663 $scope.patron.addresses =
1664 $scope.patron.addresses.concat(deleted_addresses);
1666 compress_hold_notify();
1670 patronRegSvc.save_user($scope.patron)
1671 .then(function(new_user) {
1672 if (new_user && new_user.classname) {
1673 updated_user = new_user;
1674 return patronRegSvc.save_user_settings(
1675 new_user, $scope.user_settings);
1677 alert('Patron update failed. \n\n' + js2JSON(new_user));
1680 }).then(function() {
1682 // only remove the staged user if the update succeeded.
1684 return patronRegSvc.remove_staged_user();
1688 }).then(function() {
1690 // linked groups for new users must be created after the new
1692 if ($scope.patron.isnew &&
1693 $scope.patron.groups && $scope.patron.groups.length) {
1694 var ids = $scope.patron.groups.map(function(g) {return g.id()});
1695 return patronRegSvc.apply_secondary_groups(updated_user.id(), ids)
1700 }).then(function() {
1702 // reloading the page means potentially losing some information
1703 // (e.g. last patron search), but is the only way to ensure all
1704 // components are properly updated to reflect the modified patron.
1705 if (updated_user && save_args.clone) {
1706 // open a separate tab for registering a new
1707 // patron from our cloned data.
1708 var url = 'https://'
1709 + $window.location.hostname
1710 + egCore.env.basePath
1711 + '/circ/patron/register/clone/'
1712 + updated_user.id();
1713 $window.open(url, '_blank').focus();
1716 // reload the current page
1717 $window.location.href = location.href;
1723 // This controller may be loaded from different modules (patron edit vs.
1724 // register new patron), so we have to inject the controller params manually.
1725 PatronRegCtrl.$inject = ['$scope', '$routeParams', '$q', '$modal',
1726 '$window', 'egCore', 'patronSvc', 'patronRegSvc', 'egUnloadPrompt'];