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.get_stage_user = function() {
71 if (!service.stage_username) return $q.when();
73 // fetch the staged user object
74 return egCore.net.request(
76 'open-ils.actor.user.stage.retrieve.by_username',
78 service.stage_username
79 ).then(function(suser) {
80 if (e = egCore.evt.parse(suser)) {
83 service.stage_user = suser;
87 if (!service.stage_user) return;
88 var requestor = service.stage_user.user.requesting_usr();
90 if (!requestor) return;
92 // fetch the requesting user
93 return egCore.net.request(
95 'open-ils.actor.user.retrieve.parts',
98 ['family_name', 'first_given_name', 'second_given_name']
99 ).then(function(parts) {
100 service.stage_user_requestor =
101 service.format_name(parts[0], parts[1], parts[2]);
106 // See note above about not loading egUser.
108 service.format_name = function(last, first, middle) {
109 return last + ', ' + first + (middle ? ' ' + middle : '');
112 service.check_dupe_username = function(usrname) {
113 return egCore.net.request(
115 'open-ils.actor.username.exists',
116 egCore.auth.token(), usrname);
119 //service.check_grp_app_perm = function(grp_id) {
121 // determine which user groups our user is not allowed to modify
122 service.set_edit_profiles = function() {
123 var all_app_perms = [];
124 var failed_perms = [];
126 // extract the application permissions
127 angular.forEach(service.profiles, function(grp) {
128 if (grp.application_perm())
129 all_app_perms.push(grp.application_perm());
132 // fill in service.edit_profiles by inspecting failed_perms
133 function traverse_grp_tree(grp, failed) {
135 failed_perms.indexOf(grp.application_perm()) > -1;
137 if (!failed) service.edit_profiles.push(grp);
140 service.profiles.filter( // children of grp
141 function(p) { return p.parent() == grp.id() }),
142 function(child) {traverse_grp_tree(child, failed)}
146 return egCore.perm.hasPermAt(all_app_perms, true).then(
147 function(perm_orgs) {
148 angular.forEach(all_app_perms, function(p) {
149 if (perm_orgs[p].length == 0)
150 failed_perms.push(p);
153 traverse_grp_tree(egCore.env.pgt.tree);
158 // resolves to a hash of perm-name => boolean value indicating
159 // wether the user has the permission at org_id.
160 service.has_perms_for_org = function(org_id) {
165 'CREATE_USER_GROUP_LINK',
166 'UPDATE_PATRON_COLLECTIONS_EXEMPT',
167 'UPDATE_PATRON_CLAIM_RETURN_COUNT',
168 'UPDATE_PATRON_CLAIM_NEVER_CHECKED_OUT_COUNT',
169 'UPDATE_PATRON_ACTIVE_CARD',
170 'UPDATE_PATRON_PRIMARY_CARD'
173 return egCore.perm.hasPermAt(perms_needed, true)
174 .then(function(perm_map) {
176 angular.forEach(perms_needed, function(perm) {
178 Boolean(perm_map[perm].indexOf(org_id) > -1);
185 service.get_surveys = function() {
186 var org_ids = egCore.org.fullPath(egCore.auth.user().ws_ou(), true);
188 return egCore.pcrud.search('asv', {
190 start_date : {'<=' : 'now'},
191 end_date : {'>=' : 'now'}
200 ).then(function(surveys) {
201 surveys = surveys.sort(function(a,b) {
202 return a.name() < b.name() ? -1 : 1 });
203 service.surveys = surveys;
204 angular.forEach(surveys, function(survey) {
205 angular.forEach(survey.questions(), function(question) {
206 service.survey_questions[question.id()] = question;
207 angular.forEach(question.answers(), function(answer) {
208 service.survey_answers[answer.id()] = answer;
215 service.get_stat_cats = function() {
216 return egCore.net.request(
218 'open-ils.circ.stat_cat.actor.retrieve.all',
219 egCore.auth.token(), egCore.auth.user().ws_ou()
220 ).then(function(cats) {
221 cats = cats.sort(function(a, b) {
222 return a.name() < b.name() ? -1 : 1});
223 angular.forEach(cats, function(cat) {
225 cat.entries().sort(function(a,b) {
226 return a.value() < b.value() ? -1 : 1
230 service.stat_cats = cats;
234 service.get_org_settings = function() {
235 return egCore.org.settings([
236 'global.password_regex',
237 'global.juvenile_age_threshold',
238 'patron.password.use_phone',
239 'ui.patron.default_inet_access_level',
240 'ui.patron.default_ident_type',
241 'ui.patron.default_country',
242 'ui.patron.registration.require_address',
243 'circ.holds.behind_desk_pickup_supported',
244 'circ.patron_edit.clone.copy_address',
245 'ui.patron.edit.au.prefix.require',
246 'ui.patron.edit.au.prefix.show',
247 'ui.patron.edit.au.prefix.suggest',
248 'ui.patron.edit.ac.barcode.regex',
249 'ui.patron.edit.au.second_given_name.show',
250 'ui.patron.edit.au.second_given_name.suggest',
251 'ui.patron.edit.au.suffix.show',
252 'ui.patron.edit.au.suffix.suggest',
253 'ui.patron.edit.au.alias.show',
254 'ui.patron.edit.au.alias.suggest',
255 'ui.patron.edit.au.dob.require',
256 'ui.patron.edit.au.dob.show',
257 'ui.patron.edit.au.dob.suggest',
258 'ui.patron.edit.au.dob.calendar',
259 'ui.patron.edit.au.juvenile.show',
260 'ui.patron.edit.au.juvenile.suggest',
261 'ui.patron.edit.au.ident_value.show',
262 'ui.patron.edit.au.ident_value.suggest',
263 'ui.patron.edit.au.ident_value2.show',
264 'ui.patron.edit.au.ident_value2.suggest',
265 'ui.patron.edit.au.email.require',
266 'ui.patron.edit.au.email.show',
267 'ui.patron.edit.au.email.suggest',
268 'ui.patron.edit.au.email.regex',
269 'ui.patron.edit.au.email.example',
270 'ui.patron.edit.au.day_phone.require',
271 'ui.patron.edit.au.day_phone.show',
272 'ui.patron.edit.au.day_phone.suggest',
273 'ui.patron.edit.au.day_phone.regex',
274 'ui.patron.edit.au.day_phone.example',
275 'ui.patron.edit.au.evening_phone.require',
276 'ui.patron.edit.au.evening_phone.show',
277 'ui.patron.edit.au.evening_phone.suggest',
278 'ui.patron.edit.au.evening_phone.regex',
279 'ui.patron.edit.au.evening_phone.example',
280 'ui.patron.edit.au.other_phone.require',
281 'ui.patron.edit.au.other_phone.show',
282 'ui.patron.edit.au.other_phone.suggest',
283 'ui.patron.edit.au.other_phone.regex',
284 'ui.patron.edit.au.other_phone.example',
285 'ui.patron.edit.phone.regex',
286 'ui.patron.edit.phone.example',
287 'ui.patron.edit.au.active.show',
288 'ui.patron.edit.au.active.suggest',
289 'ui.patron.edit.au.barred.show',
290 'ui.patron.edit.au.barred.suggest',
291 'ui.patron.edit.au.master_account.show',
292 'ui.patron.edit.au.master_account.suggest',
293 'ui.patron.edit.au.claims_returned_count.show',
294 'ui.patron.edit.au.claims_returned_count.suggest',
295 'ui.patron.edit.au.claims_never_checked_out_count.show',
296 'ui.patron.edit.au.claims_never_checked_out_count.suggest',
297 'ui.patron.edit.au.alert_message.show',
298 'ui.patron.edit.au.alert_message.suggest',
299 'ui.patron.edit.aua.post_code.regex',
300 'ui.patron.edit.aua.post_code.example',
301 'ui.patron.edit.aua.county.require',
303 'ui.patron.edit.default_suggested',
304 'opac.barcode_regex',
305 'opac.username_regex',
307 'ui.patron.edit.aua.state.require',
308 'ui.patron.edit.aua.state.suggest',
309 'ui.patron.edit.aua.state.show'
310 ]).then(function(settings) {
311 service.org_settings = settings;
312 return service.process_org_settings(settings);
316 // some org settings require the retrieval of additional data
317 service.process_org_settings = function(settings) {
321 if (settings['sms.enable']) {
322 // fetch SMS carriers
324 egCore.pcrud.search('csc',
327 {'class':'csc', 'field':'name'},
328 {'class':'csc', 'field':'region'}
330 ).then(function(carriers) {
331 service.sms_carriers = carriers;
335 // if other promises are added below, this is not necessary.
336 promises.push($q.when());
339 // other post-org-settings processing goes here,
340 // adding to promises as needed.
342 return $q.all(promises);
345 service.get_ident_types = function() {
346 if (egCore.env.cit) {
347 service.ident_types = egCore.env.cit.list;
350 return egCore.pcrud.retrieveAll('cit', {}, {atomic : true})
351 .then(function(types) {
352 egCore.env.absorbList(types, 'cit')
353 service.ident_types = types
358 service.get_net_access_levels = function() {
359 if (egCore.env.cnal) {
360 service.net_access_levels = egCore.env.cnal.list;
363 return egCore.pcrud.retrieveAll('cnal', {}, {atomic : true})
364 .then(function(levels) {
365 egCore.env.absorbList(levels, 'cnal')
366 service.net_access_levels = levels
371 service.get_perm_groups = function() {
372 if (egCore.env.pgt) {
373 service.profiles = egCore.env.pgt.list;
374 return service.set_edit_profiles();
376 return egCore.pcrud.search('pgt', {parent : null},
377 {flesh : -1, flesh_fields : {pgt : ['children']}}
380 egCore.env.absorbTree(tree, 'pgt')
381 service.profiles = egCore.env.pgt.list;
382 return service.set_edit_profiles();
388 service.get_field_doc = function() {
389 return egCore.pcrud.search('fdoc', {
390 fm_class: ['au', 'ac', 'aua', 'actsc', 'asv', 'asvq', 'asva']})
391 .then(null, null, function(doc) {
392 if (!service.field_doc[doc.fm_class()]) {
393 service.field_doc[doc.fm_class()] = {};
395 service.field_doc[doc.fm_class()][doc.field()] = doc;
399 service.get_user_settings = function() {
400 var org_ids = egCore.org.ancestors(egCore.auth.user().ws_ou(), true);
403 'circ.holds_behind_desk',
404 'circ.collections.exempt',
406 'opac.default_phone',
407 'opac.default_pickup_location',
408 'opac.default_sms_carrier',
409 'opac.default_sms_notify'];
411 return egCore.pcrud.search('cust', {
413 {name : static_types}, // common user settings
414 {name : { // opt-in notification user settings
416 select : {atevdef : ['opt_in_setting']},
418 // we only care about opt-in settings for
419 // event_defs our users encounter
420 where : {'+atevdef' : {owner : org_ids}}
424 }, {}, {atomic : true}).then(function(setting_types) {
426 angular.forEach(setting_types, function(stype) {
427 service.user_setting_types[stype.name()] = stype;
428 if (static_types.indexOf(stype.name()) == -1) {
429 service.opt_in_setting_types[stype.name()] = stype;
433 if (service.patron_id) {
434 // retrieve applied values for the current user
435 // for the setting types we care about.
438 setting_types.map(function(obj) { return obj.name() });
440 return egCore.net.request(
442 'open-ils.actor.patron.settings.retrieve.authoritative',
446 ).then(function(settings) {
447 service.user_settings = settings;
451 // apply default user setting values
452 angular.forEach(setting_types, function(stype, index) {
453 if (stype.reg_default() != undefined) {
454 service.user_settings[setting.name()] =
455 setting.reg_default();
462 service.invalidate_field = function(patron, field) {
463 console.log('Invalidating patron field ' + field);
465 return egCore.net.request(
467 'open-ils.actor.invalidate.' + field,
468 egCore.auth.token(), patron.id, null, patron.home_ou.id()
470 ).then(function(res) {
471 // clear the invalid value from the form
474 // update last_xact_id so future save operations
475 // on this patron will be allowed
476 patron.last_xact_id = res.payload.last_xact_id[patron.id];
480 service.dupe_patron_search = function(patron, type, value) {
483 console.log('Dupe search called with "'+ type +'" and value '+ value);
488 var fname = patron.first_given_name;
489 var lname = patron.family_name;
490 if (!(fname && lname)) return $q.when({count:0});
492 first_given_name : {value : fname, group : 0},
493 family_name : {value : lname, group : 0}
498 search = {email : {value : value, group : 0}};
502 search = {ident : {value : value, group : 2}};
506 search = {phone : {value : value, group : 2}};
511 angular.forEach(['street1', 'street2', 'city', 'post_code'],
514 search[field] = {value : value[field], group: 1};
520 return egCore.net.request(
522 'open-ils.actor.patron.search.advanced',
523 egCore.auth.token(), search, null, null, 1
524 ).then(function(res) {
525 res = res.filter(function(id) {return id != patron.id});
533 service.init_patron = function(current) {
536 return service.init_new_patron();
538 service.patron = current;
539 return service.init_existing_patron(current)
542 service.ingest_address = function(patron, addr) {
543 addr.valid = addr.valid == 't';
544 addr.within_city_limits = addr.within_city_limits == 't';
545 addr._is_mailing = (patron.mailing_address &&
546 addr.id == patron.mailing_address.id);
547 addr._is_billing = (patron.billing_address &&
548 addr.id == patron.billing_address.id);
552 * Existing patron objects reqire some data munging before insertion
555 * 1. Turn everything into a hash
556 * 2. ... Except certain fields (selectors) whose widgets require objects
557 * 3. Bools must be Boolean, not t/f.
559 service.init_existing_patron = function(current) {
561 var patron = egCore.idl.toHash(current);
563 patron.home_ou = egCore.org.get(patron.home_ou.id);
564 patron.expire_date = new Date(Date.parse(patron.expire_date));
565 patron.dob = service.parse_dob(patron.dob);
566 patron.profile = current.profile(); // pre-hash version
567 patron.net_access_level = current.net_access_level();
568 patron.ident_type = current.ident_type();
569 patron.groups = current.groups(); // pre-hash
572 ['juvenile', 'barred', 'active', 'master_account'],
573 function(field) { patron[field] = patron[field] == 't'; }
576 angular.forEach(patron.cards, function(card) {
577 card.active = card.active == 't';
578 if (card.id == patron.card.id) {
580 card._primary = 'on';
584 angular.forEach(patron.addresses,
585 function(addr) { service.ingest_address(patron, addr) });
587 // toss entries for existing stat cat maps into our living
588 // stat cat entry map, which is modified within the template.
589 angular.forEach(patron.stat_cat_entries, function(map) {
590 service.stat_cat_entry_maps[map.stat_cat.id] = map.stat_cat_entry;
596 service.init_new_patron = function() {
598 id : service.virt_id--,
601 address_type : egCore.strings.REG_ADDR_TYPE,
604 within_city_limits : false,
605 country : service.org_settings['ui.patron.default_country'],
609 id : service.virt_id--,
620 home_ou : egCore.org.get(egCore.auth.user().ws_ou()),
621 stat_cat_entries : [],
625 if (service.clone_user)
626 service.copy_clone_data(user);
628 if (service.stage_user)
629 service.copy_stage_data(user);
634 // dob is always YYYY-MM-DD
635 // Dates of birth do not contain timezone info, which can lead to
636 // inconcistent timezone handling, potentially representing
637 // different points in time, depending on the implementation.
638 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
639 // See "Differences in assumed time zone"
640 // TODO: move this into egDate ?
641 service.parse_dob = function(dob) {
642 if (!dob) return null;
643 var parts = dob.split('-');
644 var d = new Date(); // always local time zone, yay.
645 d.setFullYear(parts[0]);
646 d.setMonth(parts[1]);
651 service.copy_stage_data = function(user) {
652 var cuser = service.stage_user;
654 // copy the data into our new user object
656 for (var key in egCore.idl.classes.stgu.field_map) {
657 if (egCore.idl.classes.au.field_map[key] &&
658 !egCore.idl.classes.stgu.field_map[key].virtual) {
659 if (cuser.user[key]() !== null)
660 user[key] = cuser.user[key]();
664 if (user.home_ou) user.home_ou = egCore.org.get(user.home_ou);
665 if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
667 user.ident_type = egCore.env.cit.map[user.ident_type];
668 user.dob = service.parse_dob(user.dob);
670 // Clear the usrname if it looks like a UUID
671 if (user.usrname.replace(/-/g,'').match(/[0-9a-f]{32}/))
674 // Don't use stub address if we have one from the staged user.
675 if (cuser.mailing_addresses.length || cuser.billing_addresses.length)
678 // is_mailing=false implies is_billing
679 function addr_from_stage(stage_addr) {
680 if (!stage_addr) return;
681 var cls = stage_addr.classname;
684 id : service.virt_id--,
688 _is_mailing : cls == 'stgma',
689 _is_billing : cls == 'stgba'
692 user.mailing_address = addr;
693 user.addresses.push(addr);
695 for (var key in egCore.idl.classes[cls].field_map) {
696 if (egCore.idl.classes.aua.field_map[key] &&
697 !egCore.idl.classes[cls].field_map[key].virtual) {
698 if (stage_addr[key]() !== null)
699 addr[key] = stage_addr[key]();
704 addr_from_stage(cuser.mailing_addresses[0]);
705 addr_from_stage(cuser.billing_addresses[0]);
707 if (user.addresses.length == 1) {
708 // If there is only one address,
709 // use it as both mailing and billing.
710 var addr = user.addresses[0];
711 addr._is_mailing = addr._is_billing = true;
712 user.mailing_address = user.billing_address = addr;
715 if (cuser.cards.length) {
717 id : service.virt_id--,
718 barcode : cuser.cards[0].barcode(),
724 user.cards.push(user.card);
725 if (user.usrname == '')
726 user.usrname = card.barcode;
730 // copy select values from the cloned user to the new user.
732 service.copy_clone_data = function(user) {
733 var clone_user = service.clone_user;
735 // flesh the home org locally
736 user.home_ou = egCore.org.get(clone_user.home_ou());
737 if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
739 if (!clone_user.billing_address() &&
740 !clone_user.mailing_address())
741 return; // no addresses to copy or link
743 // if the cloned user has any addresses, we don't need
744 // the stub address created in init_new_patron.
748 service.org_settings['circ.patron_edit.clone.copy_address'];
757 angular.forEach(clone_fields, function(field) {
758 user[field] = clone_user[field]();
761 if (copy_addresses) {
762 var bill_addr, mail_addr;
764 // copy the billing and mailing addresses into new addresses
765 function clone_addr(addr) {
766 var new_addr = egCore.idl.toHash(addr);
767 new_addr.id = service.virt_id--;
768 new_addr.usr = user.id;
769 new_addr.isnew = true;
770 new_addr.valid = true;
771 user.addresses.push(new_addr);
775 if (bill_addr = clone_user.billing_address()) {
776 var addr = clone_addr(bill_addr);
777 addr._is_billing = true;
778 user.billing_address = addr;
781 if (mail_addr = clone_user.mailing_address()) {
783 if (bill_addr && bill_addr.id() == mail_addr.id()) {
784 user.mailing_address = user.billing_address;
785 user.mailing_address._is_mailing = true;
787 var addr = clone_addr(mail_addr);
788 addr._is_mailing = true;
789 user.mailing_address = addr;
793 // if there is no billing addr, use the mailing addr
794 user.billing_address = user.mailing_address;
795 user.billing_address._is_billing = true;
802 // link the billing and mailing addresses
804 if (addr = clone_user.billing_address()) {
805 user.billing_address = egCore.idl.toHash(addr);
806 user.billing_address._is_billing = true;
807 user.addresses.push(user.billing_address);
808 user.billing_address._linked_owner_id = clone_user.id();
809 user.billing_address._linked_owner = service.format_name(
810 clone_user.family_name(),
811 clone_user.first_given_name(),
812 clone_user.second_given_name()
816 if (addr = clone_user.mailing_address()) {
817 if (user.billing_address &&
818 addr.id() == user.billing_address.id) {
819 // mailing matches billing
820 user.mailing_address = user.billing_address;
821 user.mailing_address._is_mailing = true;
823 user.mailing_address = egCore.idl.toHash(addr);
824 user.mailing_address._is_mailing = true;
825 user.addresses.push(user.mailing_address);
826 user.mailing_address._linked_owner_id = clone_user.id();
827 user.mailing_address._linked_owner = service.format_name(
828 clone_user.family_name(),
829 clone_user.first_given_name(),
830 clone_user.second_given_name()
837 // translate the patron back into IDL form
838 service.save_user = function(phash) {
840 var patron = egCore.idl.fromHash('au', phash);
842 patron.home_ou(patron.home_ou().id());
843 patron.expire_date(patron.expire_date().toISOString());
844 patron.profile(patron.profile().id());
846 patron.dob(patron.dob().toISOString().replace(/T.*/,''));
847 if (patron.ident_type())
848 patron.ident_type(patron.ident_type().id());
849 if (patron.net_access_level())
850 patron.net_access_level(patron.net_access_level().id());
853 ['juvenile', 'barred', 'active', 'master_account'],
854 function(field) { patron[field](phash[field] ? 't' : 'f'); }
857 var card_hashes = patron.cards();
859 angular.forEach(card_hashes, function(chash) {
860 var card = egCore.idl.fromHash('ac', chash)
861 card.usr(patron.id());
862 card.active(chash.active ? 't' : 'f');
863 patron.cards().push(card);
864 if (chash._primary) {
869 var addr_hashes = patron.addresses();
870 patron.addresses([]);
871 angular.forEach(addr_hashes, function(addr_hash) {
872 if (!addr_hash.isnew && !addr_hash.isdeleted)
873 addr_hash.ischanged = true;
874 var addr = egCore.idl.fromHash('aua', addr_hash);
875 patron.addresses().push(addr);
876 addr.valid(addr.valid() ? 't' : 'f');
877 addr.within_city_limits(addr.within_city_limits() ? 't' : 'f');
878 if (addr_hash._is_mailing) patron.mailing_address(addr);
879 if (addr_hash._is_billing) patron.billing_address(addr);
882 patron.survey_responses([]);
883 angular.forEach(service.survey_responses, function(answer) {
884 var question = service.survey_questions[answer.question()];
885 var resp = new egCore.idl.asvr();
887 resp.survey(question.survey());
888 resp.question(question.id());
889 resp.answer(answer.id());
890 resp.usr(patron.id());
891 resp.answer_date('now');
892 patron.survey_responses().push(resp);
895 // re-object-ify the patron stat cat entry maps
897 angular.forEach(patron.stat_cat_entries(), function(entry) {
898 var e = egCore.idl.fromHash('actscecm', entry);
899 e.stat_cat(e.stat_cat().id);
902 patron.stat_cat_entries(maps);
904 // service.stat_cat_entry_maps maps stats to values
905 // patron.stat_cat_entries is an array of stat_cat_entry_usr_map's
907 service.stat_cat_entry_maps, function(value, cat_id) {
909 // see if we already have a mapping for this entry
910 var existing = patron.stat_cat_entries().filter(
911 function(e) { return e.stat_cat() == cat_id })[0];
913 if (existing) { // we have a mapping
914 // if the existing mapping matches the new one,
915 // there' nothing left to do
916 if (existing.stat_cat_entry() == value) return;
918 // mappings differ. delete the old one and create
920 existing.isdeleted(true);
923 var newmap = new egCore.idl.actscecm();
924 newmap.target_usr(patron.id());
926 newmap.stat_cat(cat_id);
927 newmap.stat_cat_entry(value);
928 patron.stat_cat_entries().push(newmap);
931 if (!patron.isnew()) patron.ischanged(true);
933 return egCore.net.request(
935 'open-ils.actor.patron.update',
936 egCore.auth.token(), patron);
939 service.remove_staged_user = function() {
940 if (!service.stage_user) return $q.when();
941 return egCore.net.request(
943 'open-ils.actor.user.stage.delete',
945 service.stage_user.row_id()
949 service.save_user_settings = function(new_user, user_settings) {
950 // user_settings contains the values from the scope/form.
951 // service.user_settings contain the values from page load time.
954 if (service.patron_id) {
955 // only update modified settings for existing patrons
956 angular.forEach(user_settings, function(val, key) {
957 if (val !== service.user_settings[key])
962 // all non-null setting values are updated for new patrons
963 angular.forEach(user_settings, function(val, key) {
964 if (val !== null) settings[key] = val;
968 if (Object.keys(settings).length == 0) return $q.when();
970 return egCore.net.request(
972 'open-ils.actor.patron.settings.update',
973 egCore.auth.token(), new_user.id(), settings
974 ).then(function(resp) {
979 // Applies field-specific validation regex's from org settings
980 // to form fields. Be careful not remove any pattern data we
981 // are not explicitly over-writing in the provided patterns obj.
982 service.set_field_patterns = function(patterns) {
983 if (service.org_settings['opac.username_regex']) {
984 patterns.au.usrname =
985 new RegExp(service.org_settings['opac.username_regex']);
988 if (service.org_settings['opac.barcode_regex']) {
989 patterns.ac.barcode =
990 new RegExp(service.org_settings['opac.barcode_regex']);
993 if (service.org_settings['global.password_regex']) {
995 new RegExp(service.org_settings['global.password_regex']);
998 var phone_reg = service.org_settings['ui.patron.edit.phone.regex'];
1000 // apply generic phone regex first, replace below as needed.
1001 patterns.au.day_phone = new RegExp(phone_reg);
1002 patterns.au.evening_phone = new RegExp(phone_reg);
1003 patterns.au.other_phone = new RegExp(phone_reg);
1006 // the remaining patterns fit a well-known key name pattern
1008 angular.forEach(service.org_settings, function(val, key) {
1010 var parts = key.match(/ui.patron.edit\.(\w+)\.(\w+)\.regex/);
1013 var name = parts[2];
1014 patterns[cls][name] = new RegExp(val);
1022 function PatronRegCtrl($scope, $routeParams,
1023 $q, $modal, $window, egCore, patronSvc, patronRegSvc, egUnloadPrompt) {
1025 $scope.page_data_loaded = false;
1026 $scope.clone_id = patronRegSvc.clone_id = $routeParams.clone_id;
1027 $scope.stage_username =
1028 patronRegSvc.stage_username = $routeParams.stage_username;
1030 patronRegSvc.patron_id = $routeParams.edit_id || $routeParams.id;
1032 // for existing patrons, disable barcode input by default
1033 $scope.disable_bc = $scope.focus_usrname = Boolean($scope.patron_id);
1034 $scope.focus_bc = !Boolean($scope.patron_id);
1035 $scope.dupe_counts = {};
1037 // map of perm name to true/false for perms the logged in user
1038 // has at the currently selected patron home org unit.
1041 if (!$scope.edit_passthru) {
1042 // in edit more, scope.edit_passthru is delivered to us by
1043 // the enclosing controller. In register mode, there is
1044 // no enclosing controller, so we create our own.
1045 $scope.edit_passthru = {};
1048 // 0=all, 1=suggested, 2=all
1049 $scope.edit_passthru.vis_level = 0;
1051 // Apply default values for new patrons during initial registration
1052 // prs is shorthand for patronSvc
1053 function set_new_patron_defaults(prs) {
1054 if (!$scope.patron.passwd) {
1055 // passsword may originate from staged user.
1056 $scope.generate_password();
1058 $scope.hold_notify_phone = true;
1059 $scope.hold_notify_email = true;
1061 // staged users may be loaded w/ a profile.
1062 $scope.set_expire_date();
1064 if (prs.org_settings['ui.patron.default_ident_type']) {
1065 // $scope.patron needs this field to be an object
1066 var id = prs.org_settings['ui.patron.default_ident_type'];
1067 var ident_type = $scope.ident_types.filter(
1068 function(type) { return type.id() == id })[0];
1069 $scope.patron.ident_type = ident_type;
1071 if (prs.org_settings['ui.patron.default_inet_access_level']) {
1072 // $scope.patron needs this field to be an object
1073 var id = prs.org_settings['ui.patron.default_inet_access_level'];
1074 var level = $scope.net_access_levels.filter(
1075 function(lvl) { return lvl.id() == id })[0];
1076 $scope.patron.net_access_level = level;
1078 if (prs.org_settings['ui.patron.default_country']) {
1079 $scope.patron.addresses[0].country =
1080 prs.org_settings['ui.patron.default_country'];
1084 // A null or undefined pattern leads to exceptions. Before the
1085 // patterns are loaded from the server, default all patterns
1086 // to an innocuous regex. To avoid re-creating numerous
1087 // RegExp objects, cache the stub RegExp after initial creation.
1088 // note: angular docs say ng-pattern accepts a regexp or string,
1089 // but as of writing, it only works with a regexp object.
1090 // (Likely an angular 1.2 vs. 1.4 issue).
1091 var field_patterns = {au : {}, ac : {}, aua : {}};
1092 $scope.field_pattern = function(cls, field) {
1093 if (!field_patterns[cls][field])
1094 field_patterns[cls][field] = new RegExp('.*');
1095 return field_patterns[cls][field];
1098 // Main page load function. Kicks off tab init and data loading.
1101 $scope.initTab ? // initTab comes from patron app
1102 $scope.initTab('edit', $routeParams.id) : $q.when(),
1106 ]).then(function() {
1107 // called after initTab and patronRegSvc.init have completed
1109 var prs = patronRegSvc; // brevity
1110 // in standalone mode, we have no patronSvc
1111 $scope.patron = prs.init_patron(patronSvc ? patronSvc.current : null);
1112 $scope.field_doc = prs.field_doc;
1113 $scope.edit_profiles = prs.edit_profiles;
1114 $scope.ident_types = prs.ident_types;
1115 $scope.net_access_levels = prs.net_access_levels;
1116 $scope.user_setting_types = prs.user_setting_types;
1117 $scope.opt_in_setting_types = prs.opt_in_setting_types;
1118 $scope.org_settings = prs.org_settings;
1119 $scope.sms_carriers = prs.sms_carriers;
1120 $scope.stat_cats = prs.stat_cats;
1121 $scope.surveys = prs.surveys;
1122 $scope.survey_responses = prs.survey_responses;
1123 $scope.stat_cat_entry_maps = prs.stat_cat_entry_maps;
1124 $scope.stage_user = prs.stage_user;
1125 $scope.stage_user_requestor = prs.stage_user_requestor;
1127 $scope.user_settings = prs.user_settings;
1128 // clone the user settings back into the patronRegSvc so
1129 // we have a copy of the original state of the settings.
1130 prs.user_settings = {};
1131 angular.forEach($scope.user_settings, function(val, key) {
1132 prs.user_settings[key] = val;
1135 extract_hold_notify();
1136 $scope.handle_home_org_changed();
1138 if ($scope.org_settings['ui.patron.edit.default_suggested'])
1139 $scope.edit_passthru.vis_level = 1;
1141 if ($scope.patron.isnew)
1142 set_new_patron_defaults(prs);
1144 $scope.page_data_loaded = true;
1146 prs.set_field_patterns(field_patterns);
1149 // update the currently displayed field documentation
1150 $scope.set_selected_field_doc = function(cls, field) {
1151 $scope.selected_field_doc = $scope.field_doc[cls][field];
1154 // returns the tree depth of the selected profile group tree node.
1155 $scope.pgt_depth = function(grp) {
1157 while (grp = egCore.env.pgt.map[grp.parent()]) d++;
1161 // IDL fields used for labels in the UI.
1162 $scope.idl_fields = {
1163 au : egCore.idl.classes.au.field_map,
1164 ac : egCore.idl.classes.ac.field_map,
1165 aua : egCore.idl.classes.aua.field_map
1168 // field visibility cache. Some fields are universally required.
1169 // 3 == value universally required
1170 // 2 == field is visible by default
1171 // 1 == field is suggested by default
1172 var field_visibility = {
1176 'au.first_given_name' : 3,
1177 'au.family_name' : 3,
1178 'au.ident_type' : 3,
1181 'au.expire_date' : 3,
1182 'au.net_access_level' : 3,
1183 'aua.address_type' : 3,
1184 'aua.post_code' : 3,
1192 'aua.within_city_limits' : 2,
1197 // returns true if the selected field should be visible
1198 // given the current required/suggested/all setting.
1199 $scope.show_field = function(field_key) {
1201 if (field_visibility[field_key] == undefined) {
1202 // compile and cache the visibility for the selected field
1204 // org settings have not been received yet.
1205 if (!$scope.org_settings) return false;
1207 var req_set = 'ui.patron.edit.' + field_key + '.require';
1208 var sho_set = 'ui.patron.edit.' + field_key + '.show';
1209 var sug_set = 'ui.patron.edit.' + field_key + '.suggest';
1211 if ($scope.org_settings[req_set]) {
1212 field_visibility[field_key] = 3;
1213 } else if ($scope.org_settings[sho_set]) {
1214 field_visibility[field_key] = 2;
1215 } else if ($scope.org_settings[sug_set]) {
1216 field_visibility[field_key] = 1;
1218 field_visibility[field_key] = 0;
1222 return field_visibility[field_key] >= $scope.edit_passthru.vis_level;
1225 // See $scope.show_field().
1226 // A field with visbility level 3 means it's required.
1227 $scope.field_required = function(cls, field) {
1229 // Value in the password field is not required
1230 // for existing patrons.
1231 if (field == 'passwd' && $scope.patron && !$scope.patron.isnew)
1234 return (field_visibility[cls + '.' + field] == 3);
1237 // generates a random 4-digit password
1238 $scope.generate_password = function() {
1239 $scope.patron.passwd = Math.floor(Math.random()*9000) + 1000;
1242 $scope.set_expire_date = function() {
1243 if (!$scope.patron.profile) return;
1244 var seconds = egCore.date.intervalToSeconds(
1245 $scope.patron.profile.perm_interval());
1246 var now_epoch = new Date().getTime();
1247 $scope.patron.expire_date = new Date(
1248 now_epoch + (seconds * 1000 /* milliseconds */))
1251 // grp is the pgt object
1252 $scope.set_profile = function(grp) {
1253 $scope.patron.profile = grp;
1254 $scope.set_expire_date();
1255 $scope.field_modified();
1258 $scope.invalid_profile = function() {
1261 $scope.patron.profile &&
1262 $scope.patron.profile.usergroup() == 't'
1266 $scope.new_address = function() {
1267 var addr = egCore.idl.toHash(new egCore.idl.aua());
1268 patronRegSvc.ingest_address($scope.patron, addr);
1269 addr.id = patronRegSvc.virt_id--;
1272 addr.within_city_limits = true;
1273 addr.country = $scope.org_settings['ui.patron.default_country'];
1274 $scope.patron.addresses.push(addr);
1277 // keep deleted addresses out of the patron object so
1278 // they won't appear in the UI. They'll be re-inserted
1279 // when the patron is updated.
1280 deleted_addresses = [];
1281 $scope.delete_address = function(id) {
1283 angular.forEach($scope.patron.addresses, function(addr) {
1284 if (addr.id == id) {
1286 addr.isdeleted = true;
1287 deleted_addresses.push(addr);
1290 addresses.push(addr);
1293 $scope.patron.addresses = addresses;
1296 $scope.post_code_changed = function(addr) {
1298 'open-ils.search', 'open-ils.search.zip', addr.post_code)
1299 .then(function(resp) {
1301 if (resp.city) addr.city = resp.city;
1302 if (resp.state) addr.state = resp.state;
1303 if (resp.county) addr.county = resp.county;
1304 if (resp.alert) alert(resp.alert);
1308 $scope.replace_card = function() {
1309 $scope.patron.card.active = false;
1310 $scope.patron.card.ischanged = true;
1311 $scope.disable_bc = false;
1313 var new_card = egCore.idl.toHash(new egCore.idl.ac());
1314 new_card.id = patronRegSvc.virt_id--;
1315 new_card.isnew = true;
1316 new_card.active = true;
1317 new_card._primary = 'on';
1318 $scope.patron.card = new_card;
1319 $scope.patron.cards.push(new_card);
1322 $scope.day_phone_changed = function(phone) {
1323 if (phone && $scope.patron.isnew &&
1324 $scope.org_settings['patron.password.use_phone']) {
1325 $scope.patron.passwd = phone.substr(-4);
1329 $scope.barcode_changed = function(bc) {
1331 $scope.dupe_barcode = false;
1334 'open-ils.actor.barcode.exists',
1335 egCore.auth.token(), bc
1336 ).then(function(resp) {
1338 $scope.dupe_barcode = true;
1339 console.log('duplicate barcode detected: ' + bc);
1342 if (!$scope.patron.usrname)
1343 $scope.patron.usrname = bc;
1349 $scope.cards_dialog = function() {
1351 templateUrl: './circ/patron/t_patron_cards_dialog',
1353 ['$scope','$modalInstance','cards', 'perms',
1354 function($scope , $modalInstance , cards, perms) {
1355 // scope here is the modal-level scope
1356 $scope.args = {cards : cards};
1357 $scope.perms = perms;
1358 $scope.ok = function() { $modalInstance.close($scope.args) }
1359 $scope.cancel = function () { $modalInstance.dismiss() }
1362 cards : function() {
1363 // scope here is the controller-level scope
1364 return $scope.patron.cards;
1366 perms : function() {
1367 return $scope.perms;
1372 angular.forEach(args.cards, function(card) {
1373 card.ischanged = true; // assume cards need updating, OK?
1374 if (card._primary == 'on' &&
1375 card.id != $scope.patron.card.id) {
1376 $scope.patron.card = card;
1383 $scope.set_addr_type = function(addr, type) {
1384 var addrs = $scope.patron.addresses;
1385 if (addr['_is_'+type]) {
1386 angular.forEach(addrs, function(a) {
1387 if (a.id != addr.id) a['_is_'+type] = false;
1390 // unchecking mailing/billing means we have to randomly
1391 // select another address to fill that role. Select the
1392 // first address in the list (that does not match the
1394 for (var i = 0; i < addrs.length; i++) {
1395 if (addrs[i].id != addr.id) {
1396 addrs[i]['_is_' + type] = true;
1404 // Translate hold notify preferences from the form/scope back into a
1405 // single user setting value for opac.hold_notify.
1406 function compress_hold_notify() {
1407 var hold_notify = '';
1409 if ($scope.hold_notify_phone) {
1410 hold_notify = 'phone';
1413 if ($scope.hold_notify_email) {
1414 hold_notify = splitter + 'email';
1417 if ($scope.hold_notify_sms) {
1418 hold_notify = splitter + 'sms';
1421 $scope.user_settings['opac.hold_notify'] = hold_notify;
1424 // dialog for selecting additional permission groups
1425 $scope.secondary_groups_dialog = function() {
1427 templateUrl: './circ/patron/t_patron_groups_dialog',
1429 ['$scope','$modalInstance','linked_groups','pgt_depth',
1430 function($scope , $modalInstance , linked_groups , pgt_depth) {
1432 $scope.pgt_depth = pgt_depth;
1434 linked_groups : linked_groups,
1435 edit_profiles : patronRegSvc.edit_profiles,
1436 new_profile : patronRegSvc.edit_profiles[0]
1439 // add a new group to the linked groups list
1440 $scope.link_group = function($event, grp) {
1441 var found = false; // avoid duplicates
1442 angular.forEach($scope.args.linked_groups,
1443 function(g) {if (g.id() == grp.id()) found = true});
1444 if (!found) $scope.args.linked_groups.push(grp);
1445 $event.preventDefault(); // avoid close
1448 // remove a group from the linked groups list
1449 $scope.unlink_group = function($event, grp) {
1450 $scope.args.linked_groups =
1451 $scope.args.linked_groups.filter(function(g) {
1452 return g.id() != grp.id()
1454 $event.preventDefault(); // avoid close
1457 $scope.ok = function() { $modalInstance.close($scope.args) }
1458 $scope.cancel = function () { $modalInstance.dismiss() }
1461 linked_groups : function() { return $scope.patron.groups },
1462 pgt_depth : function() { return $scope.pgt_depth }
1466 var ids = args.linked_groups.map(function(g) {return g.id()});
1467 console.log('linking permission groups ' + ids);
1468 return egCore.net.request(
1470 'open-ils.actor.user.set_groups',
1471 egCore.auth.token(), $scope.patron.id, ids)
1472 .then(function(resp) {
1474 $scope.patron.groups = args.linked_groups;
1476 // debugging -- should be no events
1477 alert('linked groups failure ' + egCore.evt.parse(resp));
1484 function extract_hold_notify() {
1485 notify = $scope.user_settings['opac.hold_notify'];
1486 if (!notify) return;
1487 $scope.hold_notify_phone = Boolean(notify.match(/phone/));
1488 $scope.hold_notify_email = Boolean(notify.match(/email/));
1489 $scope.hold_notify_sms = Boolean(notify.match(/sms/));
1492 $scope.invalidate_field = function(field) {
1493 patronRegSvc.invalidate_field($scope.patron, field);
1497 $scope.dupe_value_changed = function(type, value) {
1498 $scope.dupe_counts[type] = 0;
1499 patronRegSvc.dupe_patron_search($scope.patron, type, value)
1500 .then(function(res) {
1501 $scope.dupe_counts[type] = res.count;
1503 $scope.dupe_search_encoded =
1504 encodeURIComponent(js2JSON(res.search));
1506 $scope.dupe_search_encoded = '';
1511 $scope.handle_home_org_changed = function() {
1512 org_id = $scope.patron.home_ou.id();
1513 patronRegSvc.has_perms_for_org(org_id).then(function(map) {
1514 angular.forEach(map, function(v, k) { $scope.perms[k] = v });
1518 // This is called with every character typed in a form field,
1519 // since that's the only way to gaurantee something has changed.
1520 // See handle_field_changed for ng-change vs. ng-blur.
1521 $scope.field_modified = function() {
1522 // Call attach with every field change, regardless of whether
1523 // it's been called before. This will allow for re-attach after
1524 // the user clicks through the unload warning. egUnloadPrompt
1525 // will ensure we only attach once.
1526 egUnloadPrompt.attach($scope);
1529 // obj could be the patron, an address, etc.
1530 // This is called any time a form field achieves then loses focus.
1531 // It does not necessarily mean the field has changed.
1532 // The alternative is ng-change, but it's called with each character
1533 // typed, which would be overkill for many of the actions called here.
1534 $scope.handle_field_changed = function(obj, field_name) {
1535 var cls = obj.classname; // set by egIdl
1536 var value = obj[field_name];
1538 console.log('changing field ' + field_name + ' to ' + value);
1540 switch (field_name) {
1542 if ($scope.patron.day_phone &&
1543 $scope.patron.isnew &&
1544 $scope.org_settings['patron.password.use_phone']) {
1545 $scope.patron.passwd = phone.substr(-4);
1547 case 'evening_phone' :
1548 case 'other_phone' :
1549 $scope.dupe_value_changed('phone', value);
1553 case 'ident_value2':
1554 $scope.dupe_value_changed('ident', value);
1557 case 'first_given_name':
1559 $scope.dupe_value_changed('name', value);
1563 $scope.dupe_value_changed('email', value);
1569 // dupe search on address wants the address object as the value.
1570 $scope.dupe_value_changed('address', obj);
1574 $scope.post_code_changed(obj);
1578 patronRegSvc.check_dupe_username(value)
1579 .then(function(yes) {$scope.dupe_username = Boolean(yes)});
1583 // TODO: finish barcode_changed handler.
1584 $scope.barcode_changed(value);
1588 maintain_juvenile_flag();
1593 // patron.juvenile is set to true if the user was born after
1594 function maintain_juvenile_flag() {
1595 if ( !($scope.patron && $scope.patron.dob) ) return;
1598 $scope.org_settings['global.juvenile_age_threshold']
1601 var base = new Date();
1603 base.setTime(base.getTime() -
1604 Number(egCore.date.intervalToSeconds(juv_interval) + '000'));
1606 $scope.patron.juvenile = ($scope.patron.dob > base);
1609 // returns true (disable) for orgs that cannot have users.
1610 $scope.disable_home_org = function(org_id) {
1611 if (!org_id) return;
1612 var org = egCore.org.get(org_id);
1616 org.ou_type().can_have_users() == 'f'
1620 // Returns true if any input elements are tagged as invalid
1621 $scope.edit_passthru.has_invalid_fields = function() {
1622 return $('#patron-reg-container .ng-invalid').length > 0;
1625 // Returns true if the Save and Save & Clone buttons should be disabled.
1626 $scope.edit_passthru.hide_save_actions = function() {
1627 var can_save = $scope.patron.isnew ?
1628 $scope.perms.CREATE_USER : $scope.perms.UPDATE_USER;
1632 $scope.dupe_username ||
1633 $scope.dupe_barcode ||
1634 $scope.edit_passthru.has_invalid_fields()
1638 $scope.edit_passthru.save = function(save_args) {
1639 if (!save_args) save_args = {};
1641 // remove page unload warning prompt
1642 egUnloadPrompt.clear();
1644 // toss the deleted addresses back into the patron's list of
1645 // addresses so it's included in the update
1646 $scope.patron.addresses =
1647 $scope.patron.addresses.concat(deleted_addresses);
1649 compress_hold_notify();
1653 patronRegSvc.save_user($scope.patron)
1654 .then(function(new_user) {
1655 if (new_user && new_user.classname) {
1656 updated_user = new_user;
1657 return patronRegSvc.save_user_settings(
1658 new_user, $scope.user_settings);
1660 alert('Patron update failed. \n\n' + js2JSON(new_user));
1663 }).then(function() {
1665 // only remove the staged user if the update succeeded.
1667 return patronRegSvc.remove_staged_user();
1669 }).then(function() {
1671 // reloading the page means potentially losing some information
1672 // (e.g. last patron search), but is the only way to ensure all
1673 // components are properly updated to reflect the modified patron.
1674 if (updated_user && save_args.clone) {
1675 // open a separate tab for registering a new
1676 // patron from our cloned data.
1677 var url = 'https://'
1678 + $window.location.hostname
1679 + egCore.env.basePath
1680 + '/circ/patron/register/clone/'
1681 + updated_user.id();
1682 $window.open(url, '_blank').focus();
1685 // reload the current page
1686 $window.location.href = location.href;
1692 // This controller may be loaded from different modules (patron edit vs.
1693 // register new patron), so we have to inject the controller params manually.
1694 PatronRegCtrl.$inject = ['$scope', '$routeParams', '$q', '$modal',
1695 '$window', 'egCore', 'patronSvc', 'patronRegSvc', 'egUnloadPrompt'];