]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/circ/patron/regctl.js
9d02459ba6b5ec8c6dd7ac64bdfd4329d62389ef
[working/Evergreen.git] / Open-ILS / web / js / ui / default / staff / circ / patron / regctl.js
1
2 angular.module('egCoreMod')
3 // toss tihs onto egCoreMod since the page app may vary
4
5 .factory('patronRegSvc', ['$q', 'egCore', function($q, egCore) {
6
7     var service = {
8         field_doc : {},            // config.idl_field_doc
9         profiles : [],             // permission groups
10         edit_profiles : [],        // perm groups we can modify
11         sms_carriers : [],
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
15         surveys : [],
16         survey_questions : {},
17         survey_answers : {},
18         survey_responses : {},     // survey.responses for loaded patron in progress
19         stat_cats : [],
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?
23     };
24
25     // launch a series of parallel data retrieval calls
26     service.init = function(scope) {
27
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;
35
36         return $q.all([
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()
47         ]);
48     };
49
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
55         // is a lot simpler.
56         return egCore.net.request(
57             'open-ils.actor',
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)) {
63                 alert(e);
64             } else {
65                 service.clone_user = cuser;
66             }
67         });
68     }
69
70     // When editing a user with addresses linked to other users, fetch
71     // the linked user(s) so we can display their names and edit links.
72     service.get_linked_addr_users = function(addrs) {
73         angular.forEach(addrs, function(addr) {
74             if (addr.usr == service.existing_patron.id()) return;
75             egCore.pcrud.retrieve('au', addr.usr)
76             .then(function(usr) {
77                 addr._linked_owner_id = usr.id();
78                 addr._linked_owner = service.format_name(
79                     usr.family_name(),
80                     usr.first_given_name(),
81                     usr.second_given_name()
82                 );
83             })
84         });
85     }
86
87     service.apply_secondary_groups = function(user_id, group_ids) {
88         return egCore.net.request(
89             'open-ils.actor',
90             'open-ils.actor.user.set_groups',
91             egCore.auth.token(), user_id, group_ids)
92         .then(function(resp) {
93             if (resp == 1) {
94                 return true;
95             } else {
96                 // debugging -- should be no events
97                 alert('linked groups failure ' + egCore.evt.parse(resp));
98             }
99         });
100     }
101
102     service.get_stage_user = function() {
103         if (!service.stage_username) return $q.when();
104
105         // fetch the staged user object
106         return egCore.net.request(
107             'open-ils.actor',
108             'open-ils.actor.user.stage.retrieve.by_username',
109             egCore.auth.token(), 
110             service.stage_username
111         ).then(function(suser) {
112             if (e = egCore.evt.parse(suser)) {
113                 alert(e);
114             } else {
115                 service.stage_user = suser;
116             }
117         }).then(function() {
118
119             if (!service.stage_user) return;
120             var requestor = service.stage_user.user.requesting_usr();
121
122             if (!requestor) return;
123
124             // fetch the requesting user
125             return egCore.net.request(
126                 'open-ils.actor', 
127                 'open-ils.actor.user.retrieve.parts',
128                 egCore.auth.token(),
129                 requestor, 
130                 ['family_name', 'first_given_name', 'second_given_name'] 
131             ).then(function(parts) {
132                 service.stage_user_requestor = 
133                     service.format_name(parts[0], parts[1], parts[2]);
134             })
135         });
136     }
137
138     // See note above about not loading egUser.
139     // TODO: i18n
140     service.format_name = function(last, first, middle) {
141         return last + ', ' + first + (middle ? ' ' + middle : '');
142     }
143
144     service.check_dupe_username = function(usrname) {
145
146         // empty usernames can't be dupes
147         if (!usrname) return $q.when(false);
148
149         // avoid dupe check if username matches the originally loaded usrname
150         if (service.existing_patron) {
151             if (usrname == service.existing_patron.usrname())
152                 return $q.when(false);
153         }
154
155         return egCore.net.request(
156             'open-ils.actor',
157             'open-ils.actor.username.exists',
158             egCore.auth.token(), usrname);
159     }
160
161     //service.check_grp_app_perm = function(grp_id) {
162
163     // determine which user groups our user is not allowed to modify
164     service.set_edit_profiles = function() {
165         var all_app_perms = [];
166         var failed_perms = [];
167
168         // extract the application permissions
169         angular.forEach(service.profiles, function(grp) {
170             if (grp.application_perm())
171                 all_app_perms.push(grp.application_perm());
172         }); 
173
174         // fill in service.edit_profiles by inspecting failed_perms
175         function traverse_grp_tree(grp, failed) {
176             failed = failed || 
177                 failed_perms.indexOf(grp.application_perm()) > -1;
178
179             if (!failed) service.edit_profiles.push(grp);
180
181             angular.forEach(
182                 service.profiles.filter( // children of grp
183                     function(p) { return p.parent() == grp.id() }),
184                 function(child) {traverse_grp_tree(child, failed)}
185             );
186         }
187
188         return egCore.perm.hasPermAt(all_app_perms, true).then(
189             function(perm_orgs) {
190                 angular.forEach(all_app_perms, function(p) {
191                     if (perm_orgs[p].length == 0)
192                         failed_perms.push(p);
193                 });
194
195                 traverse_grp_tree(egCore.env.pgt.tree);
196             }
197         );
198     }
199
200     // resolves to a hash of perm-name => boolean value indicating
201     // wether the user has the permission at org_id.
202     service.has_perms_for_org = function(org_id) {
203
204         var perms_needed = [
205             'UPDATE_USER',
206             'CREATE_USER',
207             'CREATE_USER_GROUP_LINK', 
208             'UPDATE_PATRON_COLLECTIONS_EXEMPT',
209             'UPDATE_PATRON_CLAIM_RETURN_COUNT',
210             'UPDATE_PATRON_CLAIM_NEVER_CHECKED_OUT_COUNT',
211             'UPDATE_PATRON_ACTIVE_CARD',
212             'UPDATE_PATRON_PRIMARY_CARD'
213         ];
214
215         return egCore.perm.hasPermAt(perms_needed, true)
216         .then(function(perm_map) {
217
218             angular.forEach(perms_needed, function(perm) {
219                 perm_map[perm] = 
220                     Boolean(perm_map[perm].indexOf(org_id) > -1);
221             });
222
223             return perm_map;
224         });
225     }
226
227     service.get_surveys = function() {
228         var org_ids = egCore.org.fullPath(egCore.auth.user().ws_ou(), true);
229
230         return egCore.pcrud.search('asv', {
231                 owner : org_ids,
232                 start_date : {'<=' : 'now'},
233                 end_date : {'>=' : 'now'}
234             }, {   
235                 flesh : 2, 
236                 flesh_fields : {
237                     asv : ['questions'], 
238                     asvq : ['answers']
239                 }
240             }, 
241             {atomic : true}
242         ).then(function(surveys) {
243             surveys = surveys.sort(function(a,b) {
244                 return a.name() < b.name() ? -1 : 1 });
245             service.surveys = surveys;
246             angular.forEach(surveys, function(survey) {
247                 angular.forEach(survey.questions(), function(question) {
248                     service.survey_questions[question.id()] = question;
249                     angular.forEach(question.answers(), function(answer) {
250                         service.survey_answers[answer.id()] = answer;
251                     });
252                 });
253             });
254         });
255     }
256
257     service.get_stat_cats = function() {
258         return egCore.net.request(
259             'open-ils.circ',
260             'open-ils.circ.stat_cat.actor.retrieve.all',
261             egCore.auth.token(), egCore.auth.user().ws_ou()
262         ).then(function(cats) {
263             cats = cats.sort(function(a, b) {
264                 return a.name() < b.name() ? -1 : 1});
265             angular.forEach(cats, function(cat) {
266                 cat.entries(
267                     cat.entries().sort(function(a,b) {
268                         return a.value() < b.value() ? -1 : 1
269                     })
270                 );
271             });
272             service.stat_cats = cats;
273         });
274     };
275
276     service.get_org_settings = function() {
277         return egCore.org.settings([
278             'global.password_regex',
279             'global.juvenile_age_threshold',
280             'patron.password.use_phone',
281             'ui.patron.default_inet_access_level',
282             'ui.patron.default_ident_type',
283             'ui.patron.default_country',
284             'ui.patron.registration.require_address',
285             'circ.holds.behind_desk_pickup_supported',
286             'circ.patron_edit.clone.copy_address',
287             'ui.patron.edit.au.prefix.require',
288             'ui.patron.edit.au.prefix.show',
289             'ui.patron.edit.au.prefix.suggest',
290             'ui.patron.edit.ac.barcode.regex',
291             'ui.patron.edit.au.second_given_name.show',
292             'ui.patron.edit.au.second_given_name.suggest',
293             'ui.patron.edit.au.suffix.show',
294             'ui.patron.edit.au.suffix.suggest',
295             'ui.patron.edit.au.alias.show',
296             'ui.patron.edit.au.alias.suggest',
297             'ui.patron.edit.au.dob.require',
298             'ui.patron.edit.au.dob.show',
299             'ui.patron.edit.au.dob.suggest',
300             'ui.patron.edit.au.dob.calendar',
301             'ui.patron.edit.au.juvenile.show',
302             'ui.patron.edit.au.juvenile.suggest',
303             'ui.patron.edit.au.ident_value.show',
304             'ui.patron.edit.au.ident_value.suggest',
305             'ui.patron.edit.au.ident_value2.show',
306             'ui.patron.edit.au.ident_value2.suggest',
307             'ui.patron.edit.au.email.require',
308             'ui.patron.edit.au.email.show',
309             'ui.patron.edit.au.email.suggest',
310             'ui.patron.edit.au.email.regex',
311             'ui.patron.edit.au.email.example',
312             'ui.patron.edit.au.day_phone.require',
313             'ui.patron.edit.au.day_phone.show',
314             'ui.patron.edit.au.day_phone.suggest',
315             'ui.patron.edit.au.day_phone.regex',
316             'ui.patron.edit.au.day_phone.example',
317             'ui.patron.edit.au.evening_phone.require',
318             'ui.patron.edit.au.evening_phone.show',
319             'ui.patron.edit.au.evening_phone.suggest',
320             'ui.patron.edit.au.evening_phone.regex',
321             'ui.patron.edit.au.evening_phone.example',
322             'ui.patron.edit.au.other_phone.require',
323             'ui.patron.edit.au.other_phone.show',
324             'ui.patron.edit.au.other_phone.suggest',
325             'ui.patron.edit.au.other_phone.regex',
326             'ui.patron.edit.au.other_phone.example',
327             'ui.patron.edit.phone.regex',
328             'ui.patron.edit.phone.example',
329             'ui.patron.edit.au.active.show',
330             'ui.patron.edit.au.active.suggest',
331             'ui.patron.edit.au.barred.show',
332             'ui.patron.edit.au.barred.suggest',
333             'ui.patron.edit.au.master_account.show',
334             'ui.patron.edit.au.master_account.suggest',
335             'ui.patron.edit.au.claims_returned_count.show',
336             'ui.patron.edit.au.claims_returned_count.suggest',
337             'ui.patron.edit.au.claims_never_checked_out_count.show',
338             'ui.patron.edit.au.claims_never_checked_out_count.suggest',
339             'ui.patron.edit.au.alert_message.show',
340             'ui.patron.edit.au.alert_message.suggest',
341             'ui.patron.edit.aua.post_code.regex',
342             'ui.patron.edit.aua.post_code.example',
343             'ui.patron.edit.aua.county.require',
344             'format.date',
345             'ui.patron.edit.default_suggested',
346             'opac.barcode_regex',
347             'opac.username_regex',
348             'sms.enable',
349             'ui.patron.edit.aua.state.require',
350             'ui.patron.edit.aua.state.suggest',
351             'ui.patron.edit.aua.state.show',
352             'ui.admin.work_log.max_entries',
353             'ui.admin.patron_log.max_entries'
354         ]).then(function(settings) {
355             service.org_settings = settings;
356             if (egCore && egCore.env && !egCore.env.aous) {
357                 egCore.env.aous = settings;
358                 console.log('setting egCore.env.aous');
359             }
360             return service.process_org_settings(settings);
361         });
362     };
363
364     // some org settings require the retrieval of additional data
365     service.process_org_settings = function(settings) {
366
367         var promises = [];
368
369         if (settings['sms.enable']) {
370             // fetch SMS carriers
371             promises.push(
372                 egCore.pcrud.search('csc', 
373                     {active: 'true'}, 
374                     {'order_by':[
375                         {'class':'csc', 'field':'name'},
376                         {'class':'csc', 'field':'region'}
377                     ]}, {atomic : true}
378                 ).then(function(carriers) {
379                     service.sms_carriers = carriers;
380                 })
381             );
382         } else {
383             // if other promises are added below, this is not necessary.
384             promises.push($q.when());  
385         }
386
387         // other post-org-settings processing goes here,
388         // adding to promises as needed.
389
390         return $q.all(promises);
391     };
392
393     service.get_ident_types = function() {
394         if (egCore.env.cit) {
395             service.ident_types = egCore.env.cit.list;
396             return $q.when();
397         } else {
398             return egCore.pcrud.retrieveAll('cit', {}, {atomic : true})
399             .then(function(types) { 
400                 egCore.env.absorbList(types, 'cit')
401                 service.ident_types = types 
402             });
403         }
404     };
405
406     service.get_net_access_levels = function() {
407         if (egCore.env.cnal) {
408             service.net_access_levels = egCore.env.cnal.list;
409             return $q.when();
410         } else {
411             return egCore.pcrud.retrieveAll('cnal', {}, {atomic : true})
412             .then(function(levels) { 
413                 egCore.env.absorbList(levels, 'cnal')
414                 service.net_access_levels = levels 
415             });
416         }
417     }
418
419     service.get_perm_groups = function() {
420         if (egCore.env.pgt) {
421             service.profiles = egCore.env.pgt.list;
422             return service.set_edit_profiles();
423         } else {
424             return egCore.pcrud.search('pgt', {parent : null}, 
425                 {flesh : -1, flesh_fields : {pgt : ['children']}}
426             ).then(
427                 function(tree) {
428                     egCore.env.absorbTree(tree, 'pgt')
429                     service.profiles = egCore.env.pgt.list;
430                     return service.set_edit_profiles();
431                 }
432             );
433         }
434     }
435
436     service.get_field_doc = function() {
437         return egCore.pcrud.search('fdoc', {
438             fm_class: ['au', 'ac', 'aua', 'actsc', 'asv', 'asvq', 'asva']})
439         .then(null, null, function(doc) {
440             if (!service.field_doc[doc.fm_class()]) {
441                 service.field_doc[doc.fm_class()] = {};
442             }
443             service.field_doc[doc.fm_class()][doc.field()] = doc;
444         });
445     };
446
447     service.get_user_settings = function() {
448         var org_ids = egCore.org.ancestors(egCore.auth.user().ws_ou(), true);
449
450         var static_types = [
451             'circ.holds_behind_desk', 
452             'circ.collections.exempt', 
453             'opac.hold_notify', 
454             'opac.default_phone', 
455             'opac.default_pickup_location', 
456             'opac.default_sms_carrier', 
457             'opac.default_sms_notify'];
458
459         return egCore.pcrud.search('cust', {
460             '-or' : [
461                 {name : static_types}, // common user settings
462                 {name : { // opt-in notification user settings
463                     'in': {
464                         select : {atevdef : ['opt_in_setting']}, 
465                         from : 'atevdef',
466                         // we only care about opt-in settings for 
467                         // event_defs our users encounter
468                         where : {'+atevdef' : {owner : org_ids}}
469                     }
470                 }}
471             ]
472         }, {}, {atomic : true}).then(function(setting_types) {
473
474             angular.forEach(setting_types, function(stype) {
475                 service.user_setting_types[stype.name()] = stype;
476                 if (static_types.indexOf(stype.name()) == -1) {
477                     service.opt_in_setting_types[stype.name()] = stype;
478                 }
479             });
480
481             if (service.patron_id) {
482                 // retrieve applied values for the current user 
483                 // for the setting types we care about.
484
485                 var setting_names = 
486                     setting_types.map(function(obj) { return obj.name() });
487
488                 return egCore.net.request(
489                     'open-ils.actor', 
490                     'open-ils.actor.patron.settings.retrieve.authoritative',
491                     egCore.auth.token(),
492                     service.patron_id,
493                     setting_names
494                 ).then(function(settings) {
495                     service.user_settings = settings;
496                 });
497             } else {
498
499                 // apply default user setting values
500                 angular.forEach(setting_types, function(stype, index) {
501                     if (stype.reg_default() != undefined) {
502                         service.user_settings[setting.name()] = 
503                             setting.reg_default();
504                     }
505                 });
506             }
507         });
508     }
509
510     service.invalidate_field = function(patron, field) {
511         console.log('Invalidating patron field ' + field);
512
513         return egCore.net.request(
514             'open-ils.actor',
515             'open-ils.actor.invalidate.' + field,
516             egCore.auth.token(), patron.id, null, patron.home_ou.id()
517
518         ).then(function(res) {
519             // clear the invalid value from the form
520             patron[field] = '';
521
522             // update last_xact_id so future save operations
523             // on this patron will be allowed
524             patron.last_xact_id = res.payload.last_xact_id[patron.id];
525         });
526     }
527
528     service.dupe_patron_search = function(patron, type, value) {
529         var search;
530
531         console.log('Dupe search called with "'+ type +'" and value '+ value);
532
533         switch (type) {
534
535             case 'name':
536                 var fname = patron.first_given_name;   
537                 var lname = patron.family_name;   
538                 if (!(fname && lname)) return $q.when({count:0});
539                 search = {
540                     first_given_name : {value : fname, group : 0},
541                     family_name : {value : lname, group : 0}
542                 };
543                 break;
544
545             case 'email':
546                 search = {email : {value : value, group : 0}};
547                 break;
548
549             case 'ident':
550                 search = {ident : {value : value, group : 2}};
551                 break;
552
553             case 'phone':
554                 search = {phone : {value : value, group : 2}};
555                 break;
556
557             case 'address':
558                 search = {};
559                 angular.forEach(['street1', 'street2', 'city', 'post_code'],
560                     function(field) {
561                         if(value[field])
562                             search[field] = {value : value[field], group: 1};
563                     }
564                 );
565                 break;
566         }
567
568         return egCore.net.request( 
569             'open-ils.actor', 
570             'open-ils.actor.patron.search.advanced',
571             egCore.auth.token(), search, null, null, 1
572         ).then(function(res) {
573             res = res.filter(function(id) {return id != patron.id});
574             return {
575                 count : res.length,
576                 search : search
577             };
578         });
579     }
580
581     service.init_patron = function(current) {
582
583         if (!current)
584             return service.init_new_patron();
585
586         service.patron = current;
587         return $q.when(service.init_existing_patron(current));
588     }
589
590     service.ingest_address = function(patron, addr) {
591         addr.valid = addr.valid == 't';
592         addr.within_city_limits = addr.within_city_limits == 't';
593         addr._is_mailing = (patron.mailing_address && 
594             addr.id == patron.mailing_address.id);
595         addr._is_billing = (patron.billing_address && 
596             addr.id == patron.billing_address.id);
597     }
598
599     /*
600      * Existing patron objects reqire some data munging before insertion
601      * into the scope.
602      *
603      * 1. Turn everything into a hash
604      * 2. ... Except certain fields (selectors) whose widgets require objects
605      * 3. Bools must be Boolean, not t/f.
606      */
607     service.init_existing_patron = function(current) {
608
609         service.existing_patron = current;
610
611         var patron = egCore.idl.toHash(current);
612
613         patron.home_ou = egCore.org.get(patron.home_ou.id);
614         patron.expire_date = new Date(Date.parse(patron.expire_date));
615         patron.dob = service.parse_dob(patron.dob);
616         patron.profile = current.profile(); // pre-hash version
617         patron.net_access_level = current.net_access_level();
618         patron.ident_type = current.ident_type();
619         patron.groups = current.groups(); // pre-hash
620
621         angular.forEach(
622             ['juvenile', 'barred', 'active', 'master_account'],
623             function(field) { patron[field] = patron[field] == 't'; }
624         );
625
626         angular.forEach(patron.cards, function(card) {
627             card.active = card.active == 't';
628             if (card.id == patron.card.id) {
629                 patron.card = card;
630                 card._primary = 'on';
631             }
632         });
633
634         angular.forEach(patron.addresses, 
635             function(addr) { service.ingest_address(patron, addr) });
636
637         service.get_linked_addr_users(patron.addresses);
638
639         // Remove stat cat entries that link to out-of-scope stat
640         // cats.  With this, we avoid unnecessarily updating (or worse,
641         // modifying) stat cat values that are not ours to modify.
642         patron.stat_cat_entries = patron.stat_cat_entries.filter(
643             function(map) {
644                 return Boolean(
645                     // service.stat_cats only contains in-scope stat cats.
646                     service.stat_cats.filter(function(cat) { 
647                         return (cat.id() == map.stat_cat.id) })[0]
648                 );
649             }
650         );
651
652         // toss entries for existing stat cat maps into our living 
653         // stat cat entry map, which is modified within the template.
654         angular.forEach(patron.stat_cat_entries, function(map) {
655             service.stat_cat_entry_maps[map.stat_cat.id] = map.stat_cat_entry;
656         });
657
658         service.patron = patron;
659     }
660
661     service.init_new_patron = function() {
662         var addr = {
663             id : service.virt_id--,
664             isnew : true,
665             valid : true,
666             address_type : egCore.strings.REG_ADDR_TYPE,
667             _is_mailing : true,
668             _is_billing : true,
669             within_city_limits : false,
670             country : service.org_settings['ui.patron.default_country'],
671         };
672
673         var card = {
674             id : service.virt_id--,
675             isnew : true,
676             active : true,
677             _primary : 'on'
678         };
679
680         var user = {
681             isnew : true,
682             active : true,
683             card : card,
684             cards : [card],
685             home_ou : egCore.org.get(egCore.auth.user().ws_ou()),
686             stat_cat_entries : [],
687             groups : [],
688             addresses : [addr]
689         };
690
691         if (service.clone_user)
692             service.copy_clone_data(user);
693
694         if (service.stage_user)
695             service.copy_stage_data(user);
696
697         return user;
698     }
699
700     // dob is always YYYY-MM-DD
701     // Dates of birth do not contain timezone info, which can lead to
702     // inconcistent timezone handling, potentially representing
703     // different points in time, depending on the implementation.
704     // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
705     // See "Differences in assumed time zone"
706     // TODO: move this into egDate ?
707     service.parse_dob = function(dob) {
708         if (!dob) return null;
709         var parts = dob.split('-');
710         var d = new Date(); // always local time zone, yay.
711         d.setFullYear(parts[0]);
712         d.setMonth(parts[1] - 1);
713         d.setDate(parts[2]);
714         return d;
715     }
716
717     service.copy_stage_data = function(user) {
718         var cuser = service.stage_user;
719
720         // copy the data into our new user object
721
722         for (var key in egCore.idl.classes.stgu.field_map) {
723             if (egCore.idl.classes.au.field_map[key] &&
724                 !egCore.idl.classes.stgu.field_map[key].virtual) {
725                 if (cuser.user[key]() !== null)
726                     user[key] = cuser.user[key]();
727             }
728         }
729
730         if (user.home_ou) user.home_ou = egCore.org.get(user.home_ou);
731         if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
732         if (user.ident_type) 
733             user.ident_type = egCore.env.cit.map[user.ident_type];
734         user.dob = service.parse_dob(user.dob);
735
736         // Clear the usrname if it looks like a UUID
737         if (user.usrname.replace(/-/g,'').match(/[0-9a-f]{32}/)) 
738             user.usrname = '';
739
740         // Don't use stub address if we have one from the staged user.
741         if (cuser.mailing_addresses.length || cuser.billing_addresses.length)
742             user.addresses = [];
743
744         // is_mailing=false implies is_billing
745         function addr_from_stage(stage_addr) {
746             if (!stage_addr) return;
747             var cls = stage_addr.classname;
748
749             var addr = {
750                 id : service.virt_id--,
751                 usr : user.id,
752                 isnew : true,
753                 valid : true,
754                 _is_mailing : cls == 'stgma',
755                 _is_billing : cls == 'stgba'
756             };
757
758             user.mailing_address = addr;
759             user.addresses.push(addr);
760
761             for (var key in egCore.idl.classes[cls].field_map) {
762                 if (egCore.idl.classes.aua.field_map[key] &&
763                     !egCore.idl.classes[cls].field_map[key].virtual) {
764                     if (stage_addr[key]() !== null)
765                         addr[key] = stage_addr[key]();
766                 }
767             }
768         }
769
770         addr_from_stage(cuser.mailing_addresses[0]);
771         addr_from_stage(cuser.billing_addresses[0]);
772
773         if (user.addresses.length == 1) {
774             // If there is only one address, 
775             // use it as both mailing and billing.
776             var addr = user.addresses[0];
777             addr._is_mailing = addr._is_billing = true;
778             user.mailing_address = user.billing_address = addr;
779         }
780
781         if (cuser.cards.length) {
782             user.card = {
783                 id : service.virt_id--,
784                 barcode : cuser.cards[0].barcode(),
785                 isnew : true,
786                 active : true,
787                 _primary : 'on'
788             };
789
790             user.cards.push(user.card);
791             if (user.usrname == '') 
792                 user.usrname = card.barcode;
793         }
794
795         angular.forEach(cuser.settings, function(setting) {
796             service.user_settings[setting.setting()] = Boolean(setting.value());
797         });
798     }
799
800     // copy select values from the cloned user to the new user.
801     // user is a hash
802     service.copy_clone_data = function(user) {
803         var clone_user = service.clone_user;
804
805         // flesh the home org locally
806         user.home_ou = egCore.org.get(clone_user.home_ou());
807         if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
808
809         if (!clone_user.billing_address() &&
810             !clone_user.mailing_address())
811             return; // no addresses to copy or link
812
813         // if the cloned user has any addresses, we don't need 
814         // the stub address created in init_new_patron.
815         user.addresses = [];
816
817         var copy_addresses = 
818             service.org_settings['circ.patron_edit.clone.copy_address'];
819
820         var clone_fields = [
821             'day_phone',
822             'evening_phone',
823             'other_phone',
824             'usrgroup'
825         ]; 
826
827         angular.forEach(clone_fields, function(field) {
828             user[field] = clone_user[field]();
829         });
830
831         if (copy_addresses) {
832             var bill_addr, mail_addr;
833
834             // copy the billing and mailing addresses into new addresses
835             function clone_addr(addr) {
836                 var new_addr = egCore.idl.toHash(addr);
837                 new_addr.id = service.virt_id--;
838                 new_addr.usr = user.id;
839                 new_addr.isnew = true;
840                 new_addr.valid = true;
841                 user.addresses.push(new_addr);
842                 return new_addr;
843             }
844
845             if (bill_addr = clone_user.billing_address()) {
846                 var addr = clone_addr(bill_addr);
847                 addr._is_billing = true;
848                 user.billing_address = addr;
849             }
850
851             if (mail_addr = clone_user.mailing_address()) {
852
853                 if (bill_addr && bill_addr.id() == mail_addr.id()) {
854                     user.mailing_address = user.billing_address;
855                     user.mailing_address._is_mailing = true;
856                 } else {
857                     var addr = clone_addr(mail_addr);
858                     addr._is_mailing = true;
859                     user.mailing_address = addr;
860                 }
861
862                 if (!bill_addr) {
863                     // if there is no billing addr, use the mailing addr
864                     user.billing_address = user.mailing_address;
865                     user.billing_address._is_billing = true;
866                 }
867             }
868
869
870         } else {
871
872             // link the billing and mailing addresses
873             var addr;
874             if (addr = clone_user.billing_address()) {
875                 user.billing_address = egCore.idl.toHash(addr);
876                 user.billing_address._is_billing = true;
877                 user.addresses.push(user.billing_address);
878                 user.billing_address._linked_owner_id = clone_user.id();
879                 user.billing_address._linked_owner = service.format_name(
880                     clone_user.family_name(),
881                     clone_user.first_given_name(),
882                     clone_user.second_given_name()
883                 );
884             }
885
886             if (addr = clone_user.mailing_address()) {
887                 if (user.billing_address && 
888                     addr.id() == user.billing_address.id) {
889                     // mailing matches billing
890                     user.mailing_address = user.billing_address;
891                     user.mailing_address._is_mailing = true;
892                 } else {
893                     user.mailing_address = egCore.idl.toHash(addr);
894                     user.mailing_address._is_mailing = true;
895                     user.addresses.push(user.mailing_address);
896                     user.mailing_address._linked_owner_id = clone_user.id();
897                     user.mailing_address._linked_owner = service.format_name(
898                         clone_user.family_name(),
899                         clone_user.first_given_name(),
900                         clone_user.second_given_name()
901                     );
902                 }
903             }
904         }
905     }
906
907     // translate the patron back into IDL form
908     service.save_user = function(phash) {
909
910         var patron = egCore.idl.fromHash('au', phash);
911
912         patron.home_ou(patron.home_ou().id());
913         patron.expire_date(patron.expire_date().toISOString());
914         patron.profile(patron.profile().id());
915         if (patron.dob()) 
916             patron.dob(patron.dob().toISOString().replace(/T.*/,''));
917         if (patron.ident_type()) 
918             patron.ident_type(patron.ident_type().id());
919         if (patron.net_access_level())
920             patron.net_access_level(patron.net_access_level().id());
921
922         angular.forEach(
923             ['juvenile', 'barred', 'active', 'master_account'],
924             function(field) { patron[field](phash[field] ? 't' : 'f'); }
925         );
926
927         var card_hashes = patron.cards();
928         patron.cards([]);
929         angular.forEach(card_hashes, function(chash) {
930             var card = egCore.idl.fromHash('ac', chash)
931             card.usr(patron.id());
932             card.active(chash.active ? 't' : 'f');
933             patron.cards().push(card);
934             if (chash._primary) {
935                 patron.card(card);
936             }
937         });
938
939         var addr_hashes = patron.addresses();
940         patron.addresses([]);
941         angular.forEach(addr_hashes, function(addr_hash) {
942             if (!addr_hash.isnew && !addr_hash.isdeleted) 
943                 addr_hash.ischanged = true;
944             var addr = egCore.idl.fromHash('aua', addr_hash);
945             patron.addresses().push(addr);
946             addr.valid(addr.valid() ? 't' : 'f');
947             addr.within_city_limits(addr.within_city_limits() ? 't' : 'f');
948             if (addr_hash._is_mailing) patron.mailing_address(addr);
949             if (addr_hash._is_billing) patron.billing_address(addr);
950         });
951
952         patron.survey_responses([]);
953         angular.forEach(service.survey_responses, function(answer) {
954             var question = service.survey_questions[answer.question()];
955             var resp = new egCore.idl.asvr();
956             resp.isnew(true);
957             resp.survey(question.survey());
958             resp.question(question.id());
959             resp.answer(answer.id());
960             resp.usr(patron.id());
961             resp.answer_date('now');
962             patron.survey_responses().push(resp);
963         });
964         
965         // re-object-ify the patron stat cat entry maps
966         var maps = [];
967         angular.forEach(patron.stat_cat_entries(), function(entry) {
968             var e = egCore.idl.fromHash('actscecm', entry);
969             e.stat_cat(e.stat_cat().id);
970             maps.push(e);
971         });
972         patron.stat_cat_entries(maps);
973
974         // service.stat_cat_entry_maps maps stats to values
975         // patron.stat_cat_entries is an array of stat_cat_entry_usr_map's
976         angular.forEach(
977             service.stat_cat_entry_maps, function(value, cat_id) {
978
979             // see if we already have a mapping for this entry
980             var existing = patron.stat_cat_entries().filter(
981                 function(e) { return e.stat_cat() == cat_id })[0];
982
983             if (existing) { // we have a mapping
984                 // if the existing mapping matches the new one,
985                 // there' nothing left to do
986                 if (existing.stat_cat_entry() == value) return;
987
988                 // mappings differ.  delete the old one and create
989                 // a new one below.
990                 existing.isdeleted(true);
991             }
992
993             var newmap = new egCore.idl.actscecm();
994             newmap.target_usr(patron.id());
995             newmap.isnew(true);
996             newmap.stat_cat(cat_id);
997             newmap.stat_cat_entry(value);
998             patron.stat_cat_entries().push(newmap);
999         });
1000
1001         if (!patron.isnew()) patron.ischanged(true);
1002
1003         return egCore.net.request(
1004             'open-ils.actor', 
1005             'open-ils.actor.patron.update',
1006             egCore.auth.token(), patron);
1007     }
1008
1009     service.remove_staged_user = function() {
1010         if (!service.stage_user) return $q.when();
1011         return egCore.net.request(
1012             'open-ils.actor',
1013             'open-ils.actor.user.stage.delete',
1014             egCore.auth.token(),
1015             service.stage_user.user.row_id()
1016         );
1017     }
1018
1019     service.save_user_settings = function(new_user, user_settings) {
1020         // user_settings contains the values from the scope/form.
1021         // service.user_settings contain the values from page load time.
1022
1023         var settings = {};
1024         if (service.patron_id) {
1025             // only update modified settings for existing patrons
1026             angular.forEach(user_settings, function(val, key) {
1027                 if (val !== service.user_settings[key])
1028                     settings[key] = val;
1029             });
1030
1031         } else {
1032             // all non-null setting values are updated for new patrons
1033             angular.forEach(user_settings, function(val, key) {
1034                 if (val !== null) settings[key] = val;
1035             });
1036         }
1037
1038         if (Object.keys(settings).length == 0) return $q.when();
1039
1040         return egCore.net.request(
1041             'open-ils.actor',
1042             'open-ils.actor.patron.settings.update',
1043             egCore.auth.token(), new_user.id(), settings
1044         ).then(function(resp) {
1045             return resp;
1046         });
1047     }
1048
1049     // Applies field-specific validation regex's from org settings 
1050     // to form fields.  Be careful not remove any pattern data we
1051     // are not explicitly over-writing in the provided patterns obj.
1052     service.set_field_patterns = function(patterns) {
1053         if (service.org_settings['opac.username_regex']) {
1054             patterns.au.usrname = 
1055                 new RegExp(service.org_settings['opac.username_regex']);
1056         }
1057
1058         if (service.org_settings['opac.barcode_regex']) {
1059             patterns.ac.barcode = 
1060                 new RegExp(service.org_settings['opac.barcode_regex']);
1061         }
1062
1063         if (service.org_settings['global.password_regex']) {
1064             patterns.au.passwd = 
1065                 new RegExp(service.org_settings['global.password_regex']);
1066         }
1067
1068         var phone_reg = service.org_settings['ui.patron.edit.phone.regex'];
1069         if (phone_reg) {
1070             // apply generic phone regex first, replace below as needed.
1071             patterns.au.day_phone = new RegExp(phone_reg);
1072             patterns.au.evening_phone = new RegExp(phone_reg);
1073             patterns.au.other_phone = new RegExp(phone_reg);
1074         }
1075
1076         // the remaining patterns fit a well-known key name pattern
1077
1078         angular.forEach(service.org_settings, function(val, key) {
1079             if (!val) return;
1080             var parts = key.match(/ui.patron.edit\.(\w+)\.(\w+)\.regex/);
1081             if (!parts) return;
1082             var cls = parts[1];
1083             var name = parts[2];
1084             patterns[cls][name] = new RegExp(val);
1085         });
1086     }
1087
1088     return service;
1089 }])
1090
1091 .controller('PatronRegCtrl',
1092        ['$scope','$routeParams','$q','$uibModal','$window','egCore',
1093         'patronSvc','patronRegSvc','egUnloadPrompt','egAlertDialog',
1094         'egWorkLog',
1095 function($scope , $routeParams , $q , $uibModal , $window , egCore ,
1096          patronSvc , patronRegSvc , egUnloadPrompt, egAlertDialog ,
1097          egWorkLog) {
1098
1099     $scope.page_data_loaded = false;
1100     $scope.hold_notify_type = { phone : null, email : null, sms : null };
1101     $scope.clone_id = patronRegSvc.clone_id = $routeParams.clone_id;
1102     $scope.stage_username = 
1103         patronRegSvc.stage_username = $routeParams.stage_username;
1104     $scope.patron_id = 
1105         patronRegSvc.patron_id = $routeParams.edit_id || $routeParams.id;
1106
1107     // for existing patrons, disable barcode input by default
1108     $scope.disable_bc = $scope.focus_usrname = Boolean($scope.patron_id);
1109     $scope.focus_bc = !Boolean($scope.patron_id);
1110     $scope.address_alerts = [];
1111     $scope.dupe_counts = {};
1112
1113     // map of perm name to true/false for perms the logged in user
1114     // has at the currently selected patron home org unit.
1115     $scope.perms = {};
1116
1117     if (!$scope.edit_passthru) {
1118         // in edit more, scope.edit_passthru is delivered to us by
1119         // the enclosing controller.  In register mode, there is 
1120         // no enclosing controller, so we create our own.
1121         $scope.edit_passthru = {};
1122     }
1123
1124     // 0=all, 1=suggested, 2=all
1125     $scope.edit_passthru.vis_level = 0; 
1126
1127     // Apply default values for new patrons during initial registration
1128     // prs is shorthand for patronSvc
1129     function set_new_patron_defaults(prs) {
1130         if (!$scope.patron.passwd) {
1131             // passsword may originate from staged user.
1132             $scope.generate_password();
1133         }
1134         $scope.hold_notify_type.phone = true;
1135         $scope.hold_notify_type.email = true;
1136         $scope.hold_notify_type.sms = false;
1137
1138         // staged users may be loaded w/ a profile.
1139         $scope.set_expire_date();
1140
1141         if (prs.org_settings['ui.patron.default_ident_type']) {
1142             // $scope.patron needs this field to be an object
1143             var id = prs.org_settings['ui.patron.default_ident_type'];
1144             var ident_type = $scope.ident_types.filter(
1145                 function(type) { return type.id() == id })[0];
1146             $scope.patron.ident_type = ident_type;
1147         }
1148         if (prs.org_settings['ui.patron.default_inet_access_level']) {
1149             // $scope.patron needs this field to be an object
1150             var id = prs.org_settings['ui.patron.default_inet_access_level'];
1151             var level = $scope.net_access_levels.filter(
1152                 function(lvl) { return lvl.id() == id })[0];
1153             $scope.patron.net_access_level = level;
1154         }
1155         if (prs.org_settings['ui.patron.default_country']) {
1156             $scope.patron.addresses[0].country = 
1157                 prs.org_settings['ui.patron.default_country'];
1158         }
1159     }
1160
1161     // A null or undefined pattern leads to exceptions.  Before the
1162     // patterns are loaded from the server, default all patterns
1163     // to an innocuous regex.  To avoid re-creating numerous
1164     // RegExp objects, cache the stub RegExp after initial creation.
1165     // note: angular docs say ng-pattern accepts a regexp or string,
1166     // but as of writing, it only works with a regexp object.
1167     // (Likely an angular 1.2 vs. 1.4 issue).
1168     var field_patterns = {au : {}, ac : {}, aua : {}};
1169     $scope.field_pattern = function(cls, field) { 
1170         if (!field_patterns[cls][field])
1171             field_patterns[cls][field] = new RegExp('.*');
1172         return field_patterns[cls][field];
1173     }
1174
1175     // Main page load function.  Kicks off tab init and data loading.
1176     $q.all([
1177
1178         $scope.initTab ? // initTab comes from patron app
1179             $scope.initTab('edit', $routeParams.id) : $q.when(),
1180
1181         patronRegSvc.init(),
1182
1183     ]).then(function(){ return patronRegSvc.init_patron(patronSvc ? patronSvc.current : null) })
1184       .then(patronRegSvc.get_user_settings)
1185       .then(function() {
1186         // called after initTab and patronRegSvc.init have completed
1187         // in standalone mode, we have no patronSvc
1188         var prs = patronRegSvc;
1189         $scope.patron = prs.patron;
1190         $scope.field_doc = prs.field_doc;
1191         $scope.edit_profiles = prs.edit_profiles;
1192         $scope.ident_types = prs.ident_types;
1193         $scope.net_access_levels = prs.net_access_levels;
1194         $scope.user_setting_types = prs.user_setting_types;
1195         $scope.opt_in_setting_types = prs.opt_in_setting_types;
1196         $scope.org_settings = prs.org_settings;
1197         $scope.sms_carriers = prs.sms_carriers;
1198         $scope.stat_cats = prs.stat_cats;
1199         $scope.surveys = prs.surveys;
1200         $scope.survey_responses = prs.survey_responses;
1201         $scope.stat_cat_entry_maps = prs.stat_cat_entry_maps;
1202         $scope.stage_user = prs.stage_user;
1203         $scope.stage_user_requestor = prs.stage_user_requestor;
1204
1205         $scope.user_settings = prs.user_settings;
1206         prs.user_settings = {};
1207
1208         extract_hold_notify();
1209         $scope.handle_home_org_changed();
1210
1211         if ($scope.org_settings['ui.patron.edit.default_suggested'])
1212             $scope.edit_passthru.vis_level = 1;
1213
1214         if ($scope.patron.isnew) 
1215             set_new_patron_defaults(prs);
1216
1217         // Stat cats are fetched from open-ils.storage, where 't'==1
1218         $scope.hasRequiredStatCat = prs.stat_cats.filter(
1219                 function(cat) {return cat.required() == 1} ).length > 0;
1220
1221         $scope.page_data_loaded = true;
1222
1223         prs.set_field_patterns(field_patterns);
1224         apply_username_regex();
1225     });
1226
1227
1228     // update the currently displayed field documentation
1229     $scope.set_selected_field_doc = function(cls, field) {
1230         $scope.selected_field_doc = $scope.field_doc[cls][field];
1231     }
1232
1233     // returns the tree depth of the selected profile group tree node.
1234     $scope.pgt_depth = function(grp) {
1235         var d = 0;
1236         while (grp = egCore.env.pgt.map[grp.parent()]) d++;
1237         return d;
1238     }
1239
1240     // IDL fields used for labels in the UI.
1241     $scope.idl_fields = {
1242         au  : egCore.idl.classes.au.field_map,
1243         ac  : egCore.idl.classes.ac.field_map,
1244         aua : egCore.idl.classes.aua.field_map
1245     };
1246
1247     // field visibility cache.  Some fields are universally required.
1248     // 3 == value universally required
1249     // 2 == field is visible by default
1250     // 1 == field is suggested by default
1251     var field_visibility = {};
1252     var default_field_visibility = {
1253         'ac.barcode' : 3,
1254         'au.usrname' : 3,
1255         'au.passwd' :  3,
1256         'au.first_given_name' : 3,
1257         'au.family_name' : 3,
1258         'au.ident_type' : 3,
1259         'au.home_ou' : 3,
1260         'au.profile' : 3,
1261         'au.expire_date' : 3,
1262         'au.net_access_level' : 3,
1263         'aua.address_type' : 3,
1264         'aua.post_code' : 3,
1265         'aua.street1' : 3,
1266         'aua.street2' : 2,
1267         'aua.city' : 3,
1268         'aua.county' : 2,
1269         'aua.state' : 2,
1270         'aua.country' : 3,
1271         'aua.valid' : 2,
1272         'aua.within_city_limits' : 2,
1273         'stat_cats' : 1,
1274         'surveys' : 1
1275     }; 
1276
1277     // Returns true if the selected field should be visible
1278     // given the current required/suggested/all setting.
1279     // The visibility flag applied to each field as a result of calling
1280     // this function also sets (via the same flag) the requiredness state.
1281     $scope.show_field = function(field_key) {
1282         // org settings have not been received yet.
1283         if (!$scope.org_settings) return false;
1284
1285         if (field_visibility[field_key] == undefined) {
1286             // compile and cache the visibility for the selected field
1287
1288             var req_set = 'ui.patron.edit.' + field_key + '.require';
1289             var sho_set = 'ui.patron.edit.' + field_key + '.show';
1290             var sug_set = 'ui.patron.edit.' + field_key + '.suggest';
1291
1292             if ($scope.org_settings[req_set]) {
1293                 field_visibility[field_key] = 3;
1294
1295             } else if ($scope.org_settings[sho_set]) {
1296                 field_visibility[field_key] = 2;
1297
1298             } else if ($scope.org_settings[sug_set]) {
1299                 field_visibility[field_key] = 1;
1300             }
1301         }
1302
1303         if (field_visibility[field_key] == undefined) {
1304             // No org settings were applied above.  Use the default
1305             // settings if present or assume the field has no
1306             // visibility flags applied.
1307             field_visibility[field_key] = 
1308                 default_field_visibility[field_key] || 0;
1309         }
1310
1311         return field_visibility[field_key] >= $scope.edit_passthru.vis_level;
1312     }
1313
1314     // See $scope.show_field().
1315     // A field with visbility level 3 means it's required.
1316     $scope.field_required = function(cls, field) {
1317
1318         // Value in the password field is not required
1319         // for existing patrons.
1320         if (field == 'passwd' && $scope.patron && !$scope.patron.isnew) 
1321           return false;
1322
1323         return (field_visibility[cls + '.' + field] == 3);
1324     }
1325
1326     // generates a random 4-digit password
1327     $scope.generate_password = function() {
1328         $scope.patron.passwd = Math.floor(Math.random()*9000) + 1000;
1329     }
1330
1331     $scope.set_expire_date = function() {
1332         if (!$scope.patron.profile) return;
1333         var seconds = egCore.date.intervalToSeconds(
1334             $scope.patron.profile.perm_interval());
1335         var now_epoch = new Date().getTime();
1336         $scope.patron.expire_date = new Date(
1337             now_epoch + (seconds * 1000 /* milliseconds */))
1338     }
1339
1340     // grp is the pgt object
1341     $scope.set_profile = function(grp) {
1342         $scope.patron.profile = grp;
1343         $scope.set_expire_date();
1344         $scope.field_modified();
1345     }
1346
1347     $scope.invalid_profile = function() {
1348         return !(
1349             $scope.patron && 
1350             $scope.patron.profile && 
1351             $scope.patron.profile.usergroup() == 't'
1352         );
1353     }
1354
1355     $scope.new_address = function() {
1356         var addr = egCore.idl.toHash(new egCore.idl.aua());
1357         patronRegSvc.ingest_address($scope.patron, addr);
1358         addr.id = patronRegSvc.virt_id--;
1359         addr.isnew = true;
1360         addr.valid = true;
1361         addr.within_city_limits = true;
1362         addr.country = $scope.org_settings['ui.patron.default_country'];
1363         $scope.patron.addresses.push(addr);
1364     }
1365
1366     // keep deleted addresses out of the patron object so
1367     // they won't appear in the UI.  They'll be re-inserted
1368     // when the patron is updated.
1369     deleted_addresses = [];
1370     $scope.delete_address = function(id) {
1371
1372         if ($scope.patron.isnew &&
1373             $scope.patron.addresses.length == 1 &&
1374             $scope.org_settings['ui.patron.registration.require_address']) {
1375             egAlertDialog.open(egCore.strings.REG_ADDR_REQUIRED);
1376             return;
1377         }
1378
1379         var addresses = [];
1380         angular.forEach($scope.patron.addresses, function(addr) {
1381             if (addr.id == id) {
1382                 if (id > 0) {
1383                     addr.isdeleted = true;
1384                     deleted_addresses.push(addr);
1385                 }
1386             } else {
1387                 addresses.push(addr);
1388             }
1389         });
1390         $scope.patron.addresses = addresses;
1391     } 
1392
1393     $scope.post_code_changed = function(addr) { 
1394         egCore.net.request(
1395             'open-ils.search', 'open-ils.search.zip', addr.post_code)
1396         .then(function(resp) {
1397             if (!resp) return;
1398             if (resp.city) addr.city = resp.city;
1399             if (resp.state) addr.state = resp.state;
1400             if (resp.county) addr.county = resp.county;
1401             if (resp.alert) alert(resp.alert);
1402         });
1403     }
1404
1405     $scope.replace_card = function() {
1406         $scope.patron.card.active = false;
1407         $scope.patron.card.ischanged = true;
1408         $scope.disable_bc = false;
1409
1410         var new_card = egCore.idl.toHash(new egCore.idl.ac());
1411         new_card.id = patronRegSvc.virt_id--;
1412         new_card.isnew = true;
1413         new_card.active = true;
1414         new_card._primary = 'on';
1415         $scope.patron.card = new_card;
1416         $scope.patron.cards.push(new_card);
1417     }
1418
1419     $scope.day_phone_changed = function(phone) {
1420         if (phone && $scope.patron.isnew && 
1421             $scope.org_settings['patron.password.use_phone']) {
1422             $scope.patron.passwd = phone.substr(-4);
1423         }
1424     }
1425
1426     $scope.barcode_changed = function(bc) {
1427         if (!bc) return;
1428         $scope.dupe_barcode = false;
1429         egCore.net.request(
1430             'open-ils.actor',
1431             'open-ils.actor.barcode.exists',
1432             egCore.auth.token(), bc
1433         ).then(function(resp) {
1434             if (resp == '1') { // duplicate card
1435                 $scope.dupe_barcode = true;
1436                 console.log('duplicate barcode detected: ' + bc);
1437             } else {
1438                 if (!$scope.patron.usrname)
1439                     $scope.patron.usrname = bc;
1440                 // No dupe -- A-OK
1441             }
1442         });
1443     }
1444
1445     $scope.cards_dialog = function() {
1446         $uibModal.open({
1447             templateUrl: './circ/patron/t_patron_cards_dialog',
1448             controller: 
1449                    ['$scope','$uibModalInstance','cards','perms',
1450             function($scope , $uibModalInstance , cards , perms) {
1451                 // scope here is the modal-level scope
1452                 $scope.args = {cards : cards};
1453                 $scope.perms = perms;
1454                 $scope.ok = function() { $uibModalInstance.close($scope.args) }
1455                 $scope.cancel = function () { $uibModalInstance.dismiss() }
1456             }],
1457             resolve : {
1458                 cards : function() {
1459                     // scope here is the controller-level scope
1460                     return $scope.patron.cards;
1461                 },
1462                 perms : function() {
1463                     return $scope.perms;
1464                 }
1465             }
1466         }).result.then(
1467             function(args) {
1468                 angular.forEach(args.cards, function(card) {
1469                     card.ischanged = true; // assume cards need updating, OK?
1470                     if (card._primary == 'on' && 
1471                         card.id != $scope.patron.card.id) {
1472                         $scope.patron.card = card;
1473                     }
1474                 });
1475             }
1476         );
1477     }
1478
1479     $scope.set_addr_type = function(addr, type) {
1480         var addrs = $scope.patron.addresses;
1481         if (addr['_is_'+type]) {
1482             angular.forEach(addrs, function(a) {
1483                 if (a.id != addr.id) a['_is_'+type] = false;
1484             });
1485         } else {
1486             // unchecking mailing/billing means we have to randomly
1487             // select another address to fill that role.  Select the
1488             // first address in the list (that does not match the
1489             // modifed address)
1490             for (var i = 0; i < addrs.length; i++) {
1491                 if (addrs[i].id != addr.id) {
1492                     addrs[i]['_is_' + type] = true;
1493                     break;
1494                 }
1495             }
1496         }
1497     }
1498
1499
1500     // Translate hold notify preferences from the form/scope back into a 
1501     // single user setting value for opac.hold_notify.
1502     function compress_hold_notify() {
1503         var hold_notify = '';
1504         var splitter = '';
1505         if ($scope.hold_notify_type.phone) {
1506             hold_notify = 'phone';
1507             splitter = ':';
1508         }
1509         if ($scope.hold_notify_type.email) {
1510             hold_notify = hold_notify + splitter + 'email';
1511             splitter = ':';
1512         }
1513         if ($scope.hold_notify_type.sms) {
1514             hold_notify = hold_notify + splitter + 'sms';
1515             splitter = ':';
1516         }
1517         $scope.user_settings['opac.hold_notify'] = hold_notify;
1518     }
1519
1520     // dialog for selecting additional permission groups
1521     $scope.secondary_groups_dialog = function() {
1522         $uibModal.open({
1523             templateUrl: './circ/patron/t_patron_groups_dialog',
1524             controller: 
1525                    ['$scope','$uibModalInstance','linked_groups','pgt_depth',
1526             function($scope , $uibModalInstance , linked_groups , pgt_depth) {
1527
1528                 $scope.pgt_depth = pgt_depth;
1529                 $scope.args = {
1530                     linked_groups : linked_groups,
1531                     edit_profiles : patronRegSvc.edit_profiles,
1532                     new_profile   : patronRegSvc.edit_profiles[0]
1533                 };
1534
1535                 // add a new group to the linked groups list
1536                 $scope.link_group = function($event, grp) {
1537                     var found = false; // avoid duplicates
1538                     angular.forEach($scope.args.linked_groups, 
1539                         function(g) {if (g.id() == grp.id()) found = true});
1540                     if (!found) $scope.args.linked_groups.push(grp);
1541                     $event.preventDefault(); // avoid close
1542                 }
1543
1544                 // remove a group from the linked groups list
1545                 $scope.unlink_group = function($event, grp) {
1546                     $scope.args.linked_groups = 
1547                         $scope.args.linked_groups.filter(function(g) {
1548                         return g.id() != grp.id()
1549                     });
1550                     $event.preventDefault(); // avoid close
1551                 }
1552
1553                 $scope.ok = function() { $uibModalInstance.close($scope.args) }
1554                 $scope.cancel = function () { $uibModalInstance.dismiss() }
1555             }],
1556             resolve : {
1557                 linked_groups : function() { return $scope.patron.groups },
1558                 pgt_depth : function() { return $scope.pgt_depth }
1559             }
1560         }).result.then(
1561             function(args) {
1562
1563                 if ($scope.patron.isnew) {
1564                     // groups must be linked for new patrons after the
1565                     // patron is created.
1566                     $scope.patron.groups = args.linked_groups;
1567                     return;
1568                 }
1569
1570                 // update links groups for existing users in real time.
1571                 var ids = args.linked_groups.map(function(g) {return g.id()});
1572                 patronRegSvc.apply_secondary_groups($scope.patron.id, ids)
1573                 .then(function(success) {
1574                     if (success)
1575                         $scope.patron.groups = args.linked_groups;
1576                 });
1577             }
1578         );
1579     }
1580
1581     function extract_hold_notify() {
1582         var notify = $scope.user_settings['opac.hold_notify'];
1583         if (!notify) return;
1584         $scope.hold_notify_type.phone = Boolean(notify.match(/phone/));
1585         $scope.hold_notify_type.email = Boolean(notify.match(/email/));
1586         $scope.hold_notify_type.sms = Boolean(notify.match(/sms/));
1587     }
1588
1589     $scope.invalidate_field = function(field) {
1590         patronRegSvc.invalidate_field($scope.patron, field);
1591     }
1592
1593     address_alert = function(addr) {
1594         var args = {
1595             street1: addr.street1,
1596             street2: addr.street2,
1597             city: addr.city,
1598             state: addr.state,
1599             county: addr.county,
1600             country: addr.country,
1601             post_code: addr.post_code,
1602             mailing_address: addr._is_mailing,
1603             billing_address: addr._is_billing
1604         }
1605
1606         egCore.net.request(
1607             'open-ils.actor',
1608             'open-ils.actor.address_alert.test',
1609             egCore.auth.token(), egCore.auth.user().ws_ou(), args
1610             ).then(function(res) {
1611                 $scope.address_alerts = res;
1612         });
1613     }
1614
1615     $scope.dupe_value_changed = function(type, value) {
1616         $scope.dupe_counts[type] = 0;
1617         patronRegSvc.dupe_patron_search($scope.patron, type, value)
1618         .then(function(res) {
1619             $scope.dupe_counts[type] = res.count;
1620             if (res.count) {
1621                 $scope.dupe_search_encoded = 
1622                     encodeURIComponent(js2JSON(res.search));
1623             } else {
1624                 $scope.dupe_search_encoded = '';
1625             }
1626         });
1627     }
1628
1629     $scope.handle_home_org_changed = function() {
1630         org_id = $scope.patron.home_ou.id();
1631         patronRegSvc.has_perms_for_org(org_id).then(function(map) {
1632             angular.forEach(map, function(v, k) { $scope.perms[k] = v });
1633         });
1634     }
1635
1636     // This is called with every character typed in a form field,
1637     // since that's the only way to gaurantee something has changed.
1638     // See handle_field_changed for ng-change vs. ng-blur.
1639     $scope.field_modified = function() {
1640         // Call attach with every field change, regardless of whether
1641         // it's been called before.  This will allow for re-attach after
1642         // the user clicks through the unload warning. egUnloadPrompt
1643         // will ensure we only attach once.
1644         egUnloadPrompt.attach($scope);
1645     }
1646
1647     // also monitor when form is changed *by the user*, as using
1648     // an ng-change handler doesn't work with eg-date-input
1649     $scope.$watch('reg_form.$pristine', function(newVal, oldVal) {
1650         if (!newVal) egUnloadPrompt.attach($scope);
1651     });
1652
1653     // username regex (if present) must be removed any time
1654     // the username matches the barcode to avoid firing the
1655     // invalid field handlers.
1656     function apply_username_regex() {
1657         var regex = $scope.org_settings['opac.username_regex'];
1658         if (regex) {
1659             if ($scope.patron.card.barcode) {
1660                 // username must match the regex or the barcode
1661                 field_patterns.au.usrname = 
1662                     new RegExp(
1663                         regex + '|^' + $scope.patron.card.barcode + '$');
1664             } else {
1665                 // username must match the regex
1666                 field_patterns.au.usrname = new RegExp(regex);
1667             }
1668         } else {
1669             // username can be any format.
1670             field_patterns.au.usrname = new RegExp('.*');
1671         }
1672     }
1673
1674     // obj could be the patron, an address, etc.
1675     // This is called any time a form field achieves then loses focus.
1676     // It does not necessarily mean the field has changed.
1677     // The alternative is ng-change, but it's called with each character
1678     // typed, which would be overkill for many of the actions called here.
1679     $scope.handle_field_changed = function(obj, field_name) {
1680         var cls = obj.classname; // set by egIdl
1681         var value = obj[field_name];
1682
1683         console.log('changing field ' + field_name + ' to ' + value);
1684
1685         switch (field_name) {
1686             case 'day_phone' : 
1687                 if ($scope.patron.day_phone && 
1688                     $scope.patron.isnew && 
1689                     $scope.org_settings['patron.password.use_phone']) {
1690                     $scope.patron.passwd = phone.substr(-4);
1691                 }
1692             case 'evening_phone' : 
1693             case 'other_phone' : 
1694                 $scope.dupe_value_changed('phone', value);
1695                 break;
1696
1697             case 'ident_value':
1698             case 'ident_value2':
1699                 $scope.dupe_value_changed('ident', value);
1700                 break;
1701
1702             case 'first_given_name':
1703             case 'family_name':
1704                 $scope.dupe_value_changed('name', value);
1705                 break;
1706
1707             case 'email':
1708                 $scope.dupe_value_changed('email', value);
1709                 break;
1710
1711             case 'street1':
1712             case 'street2':
1713             case 'city':
1714                 // dupe search on address wants the address object as the value.
1715                 $scope.dupe_value_changed('address', obj);
1716                 address_alert(obj);
1717                 break;
1718
1719             case 'post_code':
1720                 $scope.post_code_changed(obj);
1721                 break;
1722
1723             case 'usrname':
1724                 patronRegSvc.check_dupe_username(value)
1725                 .then(function(yes) {$scope.dupe_username = Boolean(yes)});
1726                 break;
1727
1728             case 'barcode':
1729                 // TODO: finish barcode_changed handler.
1730                 $scope.barcode_changed(value);
1731                 apply_username_regex();
1732                 break;
1733
1734             case 'dob':
1735                 maintain_juvenile_flag();
1736                 break;
1737         }
1738     }
1739
1740     // patron.juvenile is set to true if the user was born after
1741     function maintain_juvenile_flag() {
1742         if ( !($scope.patron && $scope.patron.dob) ) return;
1743
1744         var juv_interval = 
1745             $scope.org_settings['global.juvenile_age_threshold'] 
1746             || '18 years';
1747
1748         var base = new Date();
1749
1750         base.setTime(base.getTime() - 
1751             Number(egCore.date.intervalToSeconds(juv_interval) + '000'));
1752
1753         $scope.patron.juvenile = ($scope.patron.dob > base);
1754     }
1755
1756     // returns true (disable) for orgs that cannot have users.
1757     $scope.disable_home_org = function(org_id) {
1758         if (!org_id) return;
1759         var org = egCore.org.get(org_id);
1760         return (
1761             org &&
1762             org.ou_type() &&
1763             org.ou_type().can_have_users() == 'f'
1764         );
1765     }
1766
1767     // Returns true if the Save and Save & Clone buttons should be disabled.
1768     $scope.edit_passthru.hide_save_actions = function() {
1769         return $scope.patron.isnew ?
1770             !$scope.perms.CREATE_USER : 
1771             !$scope.perms.UPDATE_USER;
1772     }
1773
1774     // Returns true if any input elements are tagged as invalid
1775     // via Angular patterns or required attributes.
1776     function form_has_invalid_fields() {
1777         return $('#patron-reg-container .ng-invalid').length > 0;
1778     }
1779
1780     function form_is_incomplete() {
1781         return (
1782             $scope.dupe_username ||
1783             $scope.dupe_barcode ||
1784             form_has_invalid_fields()
1785         );
1786
1787     }
1788
1789     $scope.edit_passthru.save = function(save_args) {
1790         if (!save_args) save_args = {};
1791
1792         if (form_is_incomplete()) {
1793             // User has not provided valid values for all required fields.
1794             return egAlertDialog.open(egCore.strings.REG_INVALID_FIELDS);
1795         }
1796
1797         // remove page unload warning prompt
1798         egUnloadPrompt.clear();
1799
1800         // toss the deleted addresses back into the patron's list of
1801         // addresses so it's included in the update
1802         $scope.patron.addresses = 
1803             $scope.patron.addresses.concat(deleted_addresses);
1804         
1805         compress_hold_notify();
1806
1807         var updated_user;
1808
1809         patronRegSvc.save_user($scope.patron)
1810         .then(function(new_user) { 
1811             if (new_user && new_user.classname) {
1812                 updated_user = new_user;
1813                 return patronRegSvc.save_user_settings(
1814                     new_user, $scope.user_settings); 
1815             } else {
1816                 alert('Patron update failed. \n\n' + js2JSON(new_user));
1817             }
1818
1819         }).then(function() {
1820
1821             // only remove the staged user if the update succeeded.
1822             if (updated_user) 
1823                 return patronRegSvc.remove_staged_user();
1824
1825             return $q.when();
1826
1827         }).then(function() {
1828
1829             // linked groups for new users must be created after the new
1830             // user is created.
1831             if ($scope.patron.isnew && 
1832                 $scope.patron.groups && $scope.patron.groups.length) {
1833                 var ids = $scope.patron.groups.map(function(g) {return g.id()});
1834                 return patronRegSvc.apply_secondary_groups(updated_user.id(), ids)
1835             }
1836
1837             return $q.when();
1838
1839         }).then(function() {
1840
1841             if (updated_user) {
1842                 egWorkLog.record(
1843                     $scope.patron.isnew
1844                     ? egCore.strings.EG_WORK_LOG_REGISTERED_PATRON
1845                     : egCore.strings.EG_WORK_LOG_EDITED_PATRON, {
1846                         'action' : $scope.patron.isnew ? 'registered_patron' : 'edited_patron',
1847                         'patron_id' : updated_user.id()
1848                     }
1849                 );
1850             }
1851
1852             // reloading the page means potentially losing some information
1853             // (e.g. last patron search), but is the only way to ensure all
1854             // components are properly updated to reflect the modified patron.
1855             if (updated_user && save_args.clone) {
1856                 // open a separate tab for registering a new 
1857                 // patron from our cloned data.
1858                 var url = 'https://' 
1859                     + $window.location.hostname 
1860                     + egCore.env.basePath 
1861                     + '/circ/patron/register/clone/' 
1862                     + updated_user.id();
1863                 $window.open(url, '_blank').focus();
1864
1865             } else {
1866                 // reload the current page
1867                 $window.location.href = location.href;
1868             }
1869         });
1870     }
1871 }])