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