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