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