]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/circ/patron/regctl.js
44f936ca032788f57d3bd80ce5d53fbb8030eda7
[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         survey_questions : {},
16         survey_answers : {},
17         survey_responses : {},     // survey.responses for loaded patron in progress
18         stat_cat_entry_maps : {},   // cat.id to selected entry object map
19         virt_id : -1               // virtual ID for new objects
20     };
21
22     // launch a series of parallel data retrieval calls
23     service.init = function(scope) {
24         return $q.all([
25             service.get_field_doc(),
26             service.get_perm_groups(),
27             service.get_ident_types(),
28             service.get_user_settings(),
29             service.get_org_settings(),
30             service.get_stat_cats(),
31             service.get_surveys(),
32             service.get_net_access_levels()
33         ]);
34     };
35
36     //service.check_grp_app_perm = function(grp_id) {
37
38     // determine which user groups our user is not allowed to modify
39     service.set_edit_profiles = function() {
40         var all_app_perms = [];
41         var failed_perms = [];
42
43         // extract the application permissions
44         angular.forEach(service.profiles, function(grp) {
45             if (grp.application_perm())
46                 all_app_perms.push(grp.application_perm());
47         }); 
48
49         // fill in service.edit_profiles by inspecting failed_perms
50         function traverse_grp_tree(grp, failed) {
51             failed = failed || 
52                 failed_perms.indexOf(grp.application_perm()) > -1;
53
54             if (!failed) service.edit_profiles.push(grp);
55
56             angular.forEach(
57                 service.profiles.filter( // children of grp
58                     function(p) { return p.parent() == grp.id() }),
59                 function(child) {traverse_grp_tree(child, failed)}
60             );
61         }
62
63         return egCore.perm.hasPermAt(all_app_perms, true).then(
64             function(perm_orgs) {
65                 angular.forEach(all_app_perms, function(p) {
66                     if (perm_orgs[p].length == 0)
67                         failed_perms.push(p);
68                 });
69
70                 traverse_grp_tree(egCore.env.pgt.tree);
71             }
72         );
73     }
74
75     service.has_group_link_perms = function(org_id) {
76         return egCore.perm.hasPermAt('CREATE_USER_GROUP_LINK', true)
77         .then(function(p) { return p.indexOf(org_id) > -1; });
78     }
79
80     service.get_surveys = function() {
81         var org_ids = egCore.org.fullPath(egCore.auth.user().ws_ou(), true);
82
83         return egCore.pcrud.search('asv', {
84                 owner : org_ids,
85                 start_date : {'<=' : 'now'},
86                 end_date : {'>=' : 'now'}
87             }, {   
88                 flesh : 2, 
89                 flesh_fields : {
90                     asv : ['questions'], 
91                     asvq : ['answers']
92                 }
93             }, 
94             {atomic : true}
95         ).then(function(surveys) {
96             surveys = surveys.sort(function(a,b) {
97                 return a.name() < b.name() ? -1 : 1 });
98             service.surveys = surveys;
99             angular.forEach(surveys, function(survey) {
100                 angular.forEach(survey.questions(), function(question) {
101                     service.survey_questions[question.id()] = question;
102                     angular.forEach(question.answers(), function(answer) {
103                         service.survey_answers[answer.id()] = answer;
104                     });
105                 });
106             });
107         });
108     }
109
110     service.get_stat_cats = function() {
111         return egCore.net.request(
112             'open-ils.circ',
113             'open-ils.circ.stat_cat.actor.retrieve.all',
114             egCore.auth.token(), egCore.auth.user().ws_ou()
115         ).then(function(cats) {
116             cats = cats.sort(function(a, b) {
117                 return a.name() < b.name() ? -1 : 1});
118             angular.forEach(cats, function(cat) {
119                 cat.entries(
120                     cat.entries().sort(function(a,b) {
121                         return a.value() < b.value() ? -1 : 1
122                     })
123                 );
124             });
125             service.stat_cats = cats;
126         });
127     };
128
129     service.get_org_settings = function() {
130         return egCore.org.settings([
131             'global.password_regex',
132             'global.juvenile_age_threshold',
133             'patron.password.use_phone',
134             'ui.patron.default_inet_access_level',
135             'ui.patron.default_ident_type',
136             'ui.patron.default_country',
137             'ui.patron.registration.require_address',
138             'circ.holds.behind_desk_pickup_supported',
139             'circ.patron_edit.clone.copy_address',
140             'ui.patron.edit.au.prefix.require',
141             'ui.patron.edit.au.prefix.show',
142             'ui.patron.edit.au.prefix.suggest',
143             'ui.patron.edit.ac.barcode.regex',
144             'ui.patron.edit.au.second_given_name.show',
145             'ui.patron.edit.au.second_given_name.suggest',
146             'ui.patron.edit.au.suffix.show',
147             'ui.patron.edit.au.suffix.suggest',
148             'ui.patron.edit.au.alias.show',
149             'ui.patron.edit.au.alias.suggest',
150             'ui.patron.edit.au.dob.require',
151             'ui.patron.edit.au.dob.show',
152             'ui.patron.edit.au.dob.suggest',
153             'ui.patron.edit.au.dob.calendar',
154             'ui.patron.edit.au.juvenile.show',
155             'ui.patron.edit.au.juvenile.suggest',
156             'ui.patron.edit.au.ident_value.show',
157             'ui.patron.edit.au.ident_value.suggest',
158             'ui.patron.edit.au.ident_value2.show',
159             'ui.patron.edit.au.ident_value2.suggest',
160             'ui.patron.edit.au.email.require',
161             'ui.patron.edit.au.email.show',
162             'ui.patron.edit.au.email.suggest',
163             'ui.patron.edit.au.email.regex',
164             'ui.patron.edit.au.email.example',
165             'ui.patron.edit.au.day_phone.require',
166             'ui.patron.edit.au.day_phone.show',
167             'ui.patron.edit.au.day_phone.suggest',
168             'ui.patron.edit.au.day_phone.regex',
169             'ui.patron.edit.au.day_phone.example',
170             'ui.patron.edit.au.evening_phone.require',
171             'ui.patron.edit.au.evening_phone.show',
172             'ui.patron.edit.au.evening_phone.suggest',
173             'ui.patron.edit.au.evening_phone.regex',
174             'ui.patron.edit.au.evening_phone.example',
175             'ui.patron.edit.au.other_phone.require',
176             'ui.patron.edit.au.other_phone.show',
177             'ui.patron.edit.au.other_phone.suggest',
178             'ui.patron.edit.au.other_phone.regex',
179             'ui.patron.edit.au.other_phone.example',
180             'ui.patron.edit.phone.regex',
181             'ui.patron.edit.phone.example',
182             'ui.patron.edit.au.active.show',
183             'ui.patron.edit.au.active.suggest',
184             'ui.patron.edit.au.barred.show',
185             'ui.patron.edit.au.barred.suggest',
186             'ui.patron.edit.au.master_account.show',
187             'ui.patron.edit.au.master_account.suggest',
188             'ui.patron.edit.au.claims_returned_count.show',
189             'ui.patron.edit.au.claims_returned_count.suggest',
190             'ui.patron.edit.au.claims_never_checked_out_count.show',
191             'ui.patron.edit.au.claims_never_checked_out_count.suggest',
192             'ui.patron.edit.au.alert_message.show',
193             'ui.patron.edit.au.alert_message.suggest',
194             'ui.patron.edit.aua.post_code.regex',
195             'ui.patron.edit.aua.post_code.example',
196             'ui.patron.edit.aua.county.require',
197             'format.date',
198             'ui.patron.edit.default_suggested',
199             'opac.barcode_regex',
200             'opac.username_regex',
201             'sms.enable',
202             'ui.patron.edit.aua.state.require',
203             'ui.patron.edit.aua.state.suggest',
204             'ui.patron.edit.aua.state.show'
205         ]).then(function(settings) {
206             service.org_settings = settings;
207             return service.process_org_settings(settings);
208         });
209     };
210
211     // some org settings require the retrieval of additional data
212     service.process_org_settings = function(settings) {
213
214         var promises = [];
215
216         if (settings['sms.enable']) {
217             // fetch SMS carriers
218             promises.push(
219                 egCore.pcrud.search('csc', 
220                     {active: 'true'}, 
221                     {'order_by':[
222                         {'class':'csc', 'field':'name'},
223                         {'class':'csc', 'field':'region'}
224                     ]}, {atomic : true}
225                 ).then(function(carriers) {
226                     service.sms_carriers = carriers;
227                 })
228             );
229         } else {
230             // if other promises are added below, this is not necessary.
231             promises.push($q.when());  
232         }
233
234         // other post-org-settings processing goes here,
235         // adding to promises as needed.
236
237         return $q.all(promises);
238     };
239
240     service.get_ident_types = function() {
241         if (egCore.env.cit) {
242             service.ident_types = egCore.env.cit.list;
243             return $q.when();
244         } else {
245             return egCore.pcrud.retrieveAll('cit', {}, {atomic : true})
246             .then(function(types) { 
247                 egCore.env.absorbList(types, 'cit')
248                 service.ident_types = types 
249             });
250         }
251     };
252
253     service.get_net_access_levels = function() {
254         if (egCore.env.cnal) {
255             service.net_access_levels = egCore.env.cnal.list;
256             return $q.when();
257         } else {
258             return egCore.pcrud.retrieveAll('cnal', {}, {atomic : true})
259             .then(function(levels) { 
260                 egCore.env.absorbList(levels, 'cnal')
261                 service.net_access_levels = levels 
262             });
263         }
264     }
265
266     service.get_perm_groups = function() {
267         if (egCore.env.pgt) {
268             service.profiles = egCore.env.pgt.list;
269             return service.set_edit_profiles();
270         } else {
271             return egCore.pcrud.search('pgt', {parent : null}, 
272                 {flesh : -1, flesh_fields : {pgt : ['children']}}
273             ).then(
274                 function(tree) {
275                     egCore.env.absorbTree(tree, 'pgt')
276                     service.profiles = egCore.env.pgt.list;
277                     return service.set_edit_profiles();
278                 }
279             );
280         }
281     }
282
283     service.get_field_doc = function() {
284
285         return egCore.pcrud.search('fdoc', {
286             fm_class: ['au', 'ac', 'aua', 'actsc', 'asv', 'asvq', 'asva']})
287         .then(null, null, function(doc) {
288             if (!service.field_doc[doc.fm_class()]) {
289                 service.field_doc[doc.fm_class()] = {};
290             }
291             service.field_doc[doc.fm_class()][doc.field()] = doc;
292         });
293     };
294
295     service.get_user_settings = function() {
296         var org_ids = egCore.org.ancestors(egCore.auth.user().ws_ou(), true);
297
298         var static_types = [
299             'circ.holds_behind_desk', 
300             'circ.collections.exempt', 
301             'opac.hold_notify', 
302             'opac.default_phone', 
303             'opac.default_pickup_location', 
304             'opac.default_sms_carrier', 
305             'opac.default_sms_notify'];
306
307         return egCore.pcrud.search('cust', {
308             '-or' : [
309                 {name : static_types}, // common user settings
310                 {name : { // opt-in notification user settings
311                     'in': {
312                         select : {atevdef : ['opt_in_setting']}, 
313                         from : 'atevdef',
314                         // we only care about opt-in settings for 
315                         // event_defs our users encounter
316                         where : {'+atevdef' : {owner : org_ids}}
317                     }
318                 }}
319             ]
320         }, {}, {atomic : true}).then(function(setting_types) {
321
322             angular.forEach(setting_types, function(stype) {
323                 service.user_setting_types[stype.name()] = stype;
324                 if (static_types.indexOf(stype.name()) == -1) {
325                     service.opt_in_setting_types[stype.name()] = stype;
326                 }
327             });
328
329             if (service.patron_id) {
330                 // retrieve applied values for the current user 
331                 // for the setting types we care about.
332
333                 var setting_names = 
334                     setting_types.map(function(obj) { return obj.name() });
335
336                 return egCore.net.request(
337                     'open-ils.actor', 
338                     'open-ils.actor.patron.settings.retrieve.authoritative',
339                     egCore.auth.token(),
340                     service.patron_id,
341                     setting_names
342                 ).then(function(settings) {
343                     service.user_settings = settings;
344                 });
345             } else {
346
347                 // apply default user setting values
348                 angular.forEach(setting_types, function(stype, index) {
349                     if (stype.reg_default() != undefined) {
350                         service.user_settings[setting.name()] = 
351                             setting.reg_default();
352                     }
353                 });
354             }
355         });
356     }
357
358     service.invalidate_field = function(patron, field) {
359         console.log('Invalidating patron field ' + field);
360
361         return egCore.net.request(
362             'open-ils.actor',
363             'open-ils.actor.invalidate.' + field,
364             egCore.auth.token(), patron.id, null, patron.home_ou.id()
365
366         ).then(function(res) {
367             // clear the invalid value from the form
368             patron[field] = '';
369
370             // update last_xact_id so future save operations
371             // on this patron will be allowed
372             patron.last_xact_id = res.payload.last_xact_id[patron.id];
373         });
374     }
375
376     service.init_patron = function(current) {
377
378         if (!current)
379             return service.init_new_patron();
380
381         service.patron = current;
382         return service.init_existing_patron(current)
383     }
384
385     service.ingest_address = function(patron, addr) {
386         addr.valid = addr.valid == 't';
387         addr.within_city_limits = addr.within_city_limits == 't';
388         addr._is_mailing = (patron.mailing_address && 
389             addr.id == patron.mailing_address.id);
390         addr._is_billing = (patron.billing_address && 
391             addr.id == patron.billing_address.id);
392     }
393
394     /*
395      * Existing patron objects reqire some data munging before insertion
396      * into the scope.
397      *
398      * 1. Turn everything into a hash
399      * 2. ... Except certain fields (selectors) whose widgets require objects
400      * 3. Bools must be Boolean, not t/f.
401      */
402     service.init_existing_patron = function(current) {
403
404         var patron = egCore.idl.toHash(current);
405
406         patron.home_ou = egCore.org.get(patron.home_ou.id);
407         patron.expire_date = new Date(Date.parse(patron.expire_date));
408         patron.dob = patron.dob ?
409             new Date(Date.parse(patron.dob)) : null;
410         patron.profile = current.profile(); // pre-hash version
411         patron.net_access_level = current.net_access_level();
412         patron.ident_type = current.ident_type();
413         patron.groups = current.groups(); // pre-hash
414
415         angular.forEach(
416             ['juvenile', 'barred', 'active', 'master_account'],
417             function(field) { patron[field] = patron[field] == 't'; }
418         );
419
420         angular.forEach(patron.cards, function(card) {
421             card.active = card.active == 't';
422             if (card.id == patron.card.id) {
423                 patron.card = card;
424                 card._primary = 'on';
425             }
426         });
427
428         angular.forEach(patron.addresses, 
429             function(addr) { service.ingest_address(patron, addr) });
430
431         // toss entries for existing stat cat maps into our living 
432         // stat cat entry map, which is modified within the template.
433         angular.forEach(patron.stat_cat_entries, function(map) {
434             var entry;
435             angular.forEach(service.stat_cats, function(cat) {
436                 angular.forEach(cat.entries(), function(ent) {
437                     if (ent.id() == map.stat_cat_entry)
438                         entry = ent;
439                 });
440             });
441             service.stat_cat_entry_maps[map.stat_cat.id] = entry;
442         });
443
444         return patron;
445     }
446
447     service.init_new_patron = function() {
448         var addr = {
449             id : service.virt_id--,
450             isnew : true,
451             valid : true,
452             address_type : egCore.strings.REG_ADDR_TYPE,
453             _is_mailing : true,
454             _is_billing : true,
455             within_city_limits : false,
456             stat_cat_entries : []
457         };
458
459         var card = {
460             id : service.virt_id--,
461             isnew : true,
462             active : true,
463             _primary : 'on'
464         };
465
466         return {
467             isnew : true,
468             active : true,
469             card : card,
470             cards : [card],
471             home_ou : egCore.org.get(egCore.auth.user().ws_ou()),
472                         
473             // TODO default profile group?
474             addresses : [addr]
475         };
476     }
477
478     // translate the patron back into IDL form
479     service.save_user = function(phash) {
480
481         var patron = egCore.idl.fromHash('au', phash);
482
483         patron.home_ou(patron.home_ou().id());
484         patron.expire_date(
485             patron.expire_date().toISOString().replace(/T.*/,''));
486         patron.profile(patron.profile().id());
487         if (patron.dob()) 
488             patron.dob(patron.dob().toISOString().replace(/T.*/,''));
489         if (patron.ident_type()) 
490             patron.ident_type(patron.ident_type().id());
491         if (patron.net_access_level())
492             patron.net_access_level(patron.net_access_level().id());
493
494         angular.forEach(
495             ['juvenile', 'barred', 'active', 'master_account'],
496             function(field) { patron[field](phash[field] ? 't' : 'f'); }
497         );
498
499         var card_hashes = patron.cards();
500         patron.cards([]);
501         angular.forEach(card_hashes, function(chash) {
502             var card = egCore.idl.fromHash('ac', chash)
503             card.usr(patron.id());
504             card.active(chash.active ? 't' : 'f');
505             patron.cards().push(card);
506             if (chash._primary) {
507                 patron.card(card);
508             }
509         });
510
511         var addr_hashes = patron.addresses();
512         patron.addresses([]);
513         angular.forEach(addr_hashes, function(addr_hash) {
514             if (!addr_hash.isnew && !addr_hash.isdeleted) 
515                 addr_hash.ischanged = true;
516             var addr = egCore.idl.fromHash('aua', addr_hash);
517             patron.addresses().push(addr);
518             addr.valid(addr.valid() ? 't' : 'f');
519             addr.within_city_limits(addr.within_city_limits() ? 't' : 'f');
520             if (addr_hash._is_mailing) patron.mailing_address(addr);
521             if (addr_hash._is_billing) patron.billing_address(addr);
522         });
523
524         patron.survey_responses([]);
525         angular.forEach(service.survey_responses, function(answer) {
526             var question = service.survey_questions[answer.question()];
527             var resp = new egCore.idl.asvr();
528             resp.isnew(true);
529             resp.survey(question.survey());
530             resp.question(question.id());
531             resp.answer(answer.id());
532             resp.usr(patron.id());
533             resp.answer_date('now');
534             patron.survey_responses().push(resp);
535         });
536         
537         // re-object-ify the patron stat cat entry maps
538         var maps = [];
539         angular.forEach(patron.stat_cat_entries(), function(entry) {
540             var e = egCore.idl.fromHash('actscecm', entry);
541             e.stat_cat(e.stat_cat().id);
542             maps.push(e);
543         });
544         patron.stat_cat_entries(maps);
545
546         // service.stat_cat_entry_maps maps stats to entries
547         // patron.stat_cat_entries is an array of stat_cat_entry_usr_map's
548         angular.forEach(service.stat_cat_entry_maps, function(entry) {
549
550             // see if we already have a mapping for this entry
551             var existing = patron.stat_cat_entries().filter(function(e) {
552                 return e.stat_cat() == entry.stat_cat();
553             })[0];
554
555             if (existing) { // we have a mapping
556                 // if the existing mapping matches the new one,
557                 // there' nothing left to do
558                 if (existing.stat_cat_entry() == entry.id()) return;
559
560                 // mappings differ.  delete the old one and create
561                 // a new one below.
562                 existing.isdeleted(true);
563             }
564
565             var newmap = new egCore.idl.actscecm();
566             newmap.target_usr(patron.id());
567             newmap.isnew(true);
568             newmap.stat_cat(entry.stat_cat());
569             newmap.stat_cat_entry(entry.id());
570             patron.stat_cat_entries().push(newmap);
571         });
572
573         angular.forEach(patron.stat_cat_entries(), function(entry) {
574             console.log(egCore.idl.toString(entry));
575         });
576
577         if (!patron.isnew()) patron.ischanged(true);
578
579         return egCore.net.request(
580             'open-ils.actor', 
581             'open-ils.actor.patron.update',
582             egCore.auth.token(), patron);
583     }
584
585     service.save_user_settings = function(new_user, user_settings) {
586         // user_settings contains the values from the scope/form.
587         // service.user_settings contain the values from page load time.
588
589         var settings = {};
590         if (service.patron_id) {
591             // only update modified settings for existing patrons
592             angular.forEach(user_settings, function(val, key) {
593                 if (val !== service.user_settings[key])
594                     settings[key] = val;
595             });
596
597         } else {
598             // all non-null setting values are updated for new patrons
599             angular.forEach(user_settings, function(val, key) {
600                 if (val !== null) settings[key] = val;
601             });
602         }
603
604         if (Object.keys(settings).length == 0) return $q.when();
605
606         return egCore.net.request(
607             'open-ils.actor',
608             'open-ils.actor.patron.settings.update',
609             egCore.auth.token(), new_user.id(), settings
610         ).then(function(resp) {
611             console.log('settings returned ' + resp);
612             return resp;
613         });
614     }
615
616     return service;
617 }]);
618
619
620 function PatronRegCtrl($scope, $routeParams, 
621     $q, $modal, $window, egCore, patronSvc, patronRegSvc) {
622
623     $scope.page_data_loaded = false;
624     $scope.clone_id = $routeParams.clone_id;
625     $scope.stage_username = $routeParams.stage_username;
626     $scope.patron_id = 
627         patronRegSvc.patron_id = $routeParams.edit_id || $routeParams.id;
628
629     // for existing patrons, disable barcode input by default
630     $scope.disable_bc = $scope.focus_usrname = Boolean($scope.patron_id);
631     $scope.focus_bc = !Boolean($scope.patron_id);
632
633     if (!$scope.edit_passthru) {
634         // in edit more, scope.edit_passthru is delivered to us by
635         // the enclosing controller.  In register mode, there is 
636         // no enclosing controller, so we create our own.
637         $scope.edit_passthru = {};
638     }
639
640     // 0=all, 1=suggested, 2=all
641     $scope.edit_passthru.vis_level = 0; 
642     // TODO: add save/clone handlers here
643
644     // Apply default values for new patrons during initial registration
645     // prs is shorthand for patronSvc
646     function set_new_patron_defaults(prs) {
647         $scope.generate_password();
648         $scope.hold_notify_phone = true;
649         $scope.hold_notify_email = true;
650
651         if (prs.org_settings['ui.patron.default_ident_type']) {
652             // $scope.patron needs this field to be an object
653             var id = prs.org_settings['ui.patron.default_ident_type'];
654             var ident_type = $scope.ident_types.filter(
655                 function(type) { return type.id() == id })[0];
656             $scope.patron.ident_type = ident_type;
657         }
658         if (prs.org_settings['ui.patron.default_inet_access_level']) {
659             // $scope.patron needs this field to be an object
660             var id = prs.org_settings['ui.patron.default_inet_access_level'];
661             var level = $scope.net_access_levels.filter(
662                 function(lvl) { return lvl.id() == id })[0];
663             $scope.patron.net_access_level = level;
664         }
665         if (prs.org_settings['ui.patron.default_country']) {
666             $scope.patron.addresses[0].country = 
667                 prs.org_settings['ui.patron.default_country'];
668         }
669     }
670
671     function handle_home_org_changed() {
672         org_id = $scope.patron.home_ou.id();
673
674         patronRegSvc.has_group_link_perms(org_id)
675         .then(function(bool) {$scope.has_group_link_perm = bool});
676     }
677
678     $q.all([
679
680         $scope.initTab ? // initTab comes from patron app
681             $scope.initTab('edit', $routeParams.id) : $q.when(),
682
683         patronRegSvc.init()
684
685     ]).then(function() {
686         // called after initTab and patronRegSvc.init have completed
687
688         var prs = patronRegSvc; // brevity
689         // in standalone mode, we have no patronSvc
690         $scope.patron = prs.init_patron(patronSvc ? patronSvc.current : null);
691         $scope.field_doc = prs.field_doc;
692         $scope.edit_profiles = prs.edit_profiles;
693         $scope.ident_types = prs.ident_types;
694         $scope.net_access_levels = prs.net_access_levels;
695         $scope.user_setting_types = prs.user_setting_types;
696         $scope.opt_in_setting_types = prs.opt_in_setting_types;
697         $scope.org_settings = prs.org_settings;
698         $scope.sms_carriers = prs.sms_carriers;
699         $scope.stat_cats = prs.stat_cats;
700         $scope.surveys = prs.surveys;
701         $scope.survey_responses = prs.survey_responses;
702         $scope.stat_cat_entry_maps = prs.stat_cat_entry_maps;
703
704         $scope.user_settings = prs.user_settings;
705         // clone the user settings back into the patronRegSvc so
706         // we have a copy of the original state of the settings.
707         prs.user_settings = {};
708         angular.forEach($scope.user_settings, function(val, key) {
709             prs.user_settings[key] = val;
710         });
711
712         extract_hold_notify();
713         handle_home_org_changed();
714
715         if ($scope.org_settings['ui.patron.edit.default_suggested'])
716             $scope.edit_passthru.vis_level = 1;
717
718         if ($scope.patron.isnew) 
719             set_new_patron_defaults(prs);
720
721         $scope.page_data_loaded = true;
722     });
723
724     // update the currently displayed field documentation
725     $scope.set_selected_field_doc = function(cls, field) {
726         $scope.selected_field_doc = $scope.field_doc[cls][field];
727     }
728
729     // returns the tree depth of the selected profile group tree node.
730     $scope.pgt_depth = function(grp) {
731         var d = 0;
732         while (grp = egCore.env.pgt.map[grp.parent()]) d++;
733         return d;
734     }
735
736     // IDL fields used for labels in the UI.
737     $scope.idl_fields = {
738         au  : egCore.idl.classes.au.field_map,
739         ac  : egCore.idl.classes.ac.field_map,
740         aua : egCore.idl.classes.aua.field_map
741     };
742
743     // field visibility cache.  Some fields are universally required.
744     var field_visibility = {
745         'ac.barcode' : 2,
746         'au.usrname' : 2,
747         'au.passwd' :  2,
748         // TODO passwd2 2,
749         'au.first_given_name' : 2,
750         'au.family_name' : 2,
751         'au.ident_type' : 2,
752         'au.home_ou' : 2,
753         'au.profile' : 2,
754         'au.expire_date' : 2,
755         'au.net_access_level' : 2,
756         'aua.address_type' : 2,
757         'aua.post_code' : 2,
758         'aua.street1' : 2,
759         'aua.street2' : 2,
760         'aua.city' : 2,
761         'aua.county' : 2,
762         'aua.state' : 2,
763         'aua.country' : 2,
764         'aua.valid' : 2,
765         'aua.within_city_limits' : 2,
766         'stat_cats' : 1,
767         'surveys' : 1
768     }; 
769
770     // returns true if the selected field should be visible
771     // given the current required/suggested/all setting.
772     $scope.show_field = function(field_key) {
773
774         if (field_visibility[field_key] == undefined) {
775             // compile and cache the visibility for the selected field
776
777             // org settings have not been received yet.
778             if (!$scope.org_settings) return false;
779
780             var req_set = 'ui.patron.edit.' + field_key + '.require';
781             var sho_set = 'ui.patron.edit.' + field_key + '.show';
782             var sug_set = 'ui.patron.edit.' + field_key + '.suggest';
783
784             if ($scope.org_settings[req_set]) {
785                 field_visibility[field_key] = 2;
786             } else if ($scope.org_settings[sho_set]) {
787                 field_visibility[field_key] = 2;
788             } else if ($scope.org_settings[sug_set]) {
789                 field_visibility[field_key] = 1;
790             } else {
791                 field_visibility[field_key] = 0;
792             }
793         }
794
795         return field_visibility[field_key] >= $scope.edit_passthru.vis_level;
796     }
797
798     // generates a random 4-digit password
799     $scope.generate_password = function() {
800         $scope.patron.passwd = Math.floor(Math.random()*9000) + 1000;
801     }
802
803     $scope.set_expire_date = function() {
804         if (!$scope.patron.profile) return;
805         var seconds = egCore.date.intervalToSeconds(
806             $scope.patron.profile.perm_interval());
807         var now_epoch = new Date().getTime();
808         $scope.patron.expire_date = new Date(
809             now_epoch + (seconds * 1000 /* milliseconds */))
810     }
811
812     // grp is the pgt object
813     $scope.set_profile = function(grp) {
814         $scope.patron.profile = grp;
815         $scope.set_expire_date();
816     }
817
818     $scope.new_address = function() {
819         var addr = egCore.idl.toHash(new egCore.idl.aua());
820         patronRegSvc.ingest_address($scope.patron, addr);
821         addr.id = patronRegSvc.virt_id--;
822         addr.isnew = true;
823         addr.valid = true;
824         addr.within_city_limits = true;
825         $scope.patron.addresses.push(addr);
826     }
827
828     // keep deleted addresses out of the patron object so
829     // they won't appear in the UI.  They'll be re-inserted
830     // when the patron is updated.
831     deleted_addresses = [];
832     $scope.delete_address = function(id) {
833         var addresses = [];
834         angular.forEach($scope.patron.addresses, function(addr) {
835             if (addr.id == id) {
836                 if (id > 0) {
837                     addr.isdeleted = true;
838                     deleted_addresses.push(addr);
839                 }
840             } else {
841                 addresses.push(addr);
842             }
843         });
844         $scope.patron.addresses = addresses;
845     } 
846
847     $scope.post_code_changed = function(addr) { 
848         egCore.net.request(
849             'open-ils.search', 'open-ils.search.zip', addr.post_code)
850         .then(function(resp) {
851             if (!resp) return;
852             if (resp.city) addr.city = resp.city;
853             if (resp.state) addr.state = resp.state;
854             if (resp.county) addr.county = resp.county;
855             if (resp.alert) alert(resp.alert);
856         });
857     }
858
859     $scope.replace_card = function() {
860         $scope.patron.card.active = false;
861         $scope.patron.card.ischanged = true;
862         $scope.disable_bc = false;
863
864         var new_card = egCore.idl.toHash(new egCore.idl.ac());
865         new_card.id = patronRegSvc.virt_id--;
866         new_card.isnew = true;
867         new_card.active = true;
868         new_card._primary = 'on';
869         $scope.patron.card = new_card;
870         $scope.patron.cards.push(new_card);
871     }
872
873     $scope.day_phone_changed = function(phone) {
874         if (phone && $scope.org_settings['patron.password.use_phone']) {
875            $scope.patron.passwd = phone.substr(-4);
876         }
877     }
878
879     $scope.barcode_changed = function(bc) {
880         if (!bc) return;
881         egCore.net.request(
882             'open-ils.actor',
883             'open-ils.actor.barcode.exists',
884             egCore.auth.token(), bc
885         ).then(function(resp) {
886             if (resp == '1') {
887                 console.log('duplicate barcode detected: ' + bc);
888                 // DUPLICATE CARD
889             } else {
890                 if (!$scope.patron.usrname)
891                     $scope.patron.usrname = bc;
892                 // No dupe -- A-OK
893             }
894         });
895     }
896
897     $scope.cards_dialog = function() {
898         $modal.open({
899             templateUrl: './circ/patron/t_patron_cards_dialog',
900             controller: 
901                    ['$scope','$modalInstance','cards',
902             function($scope , $modalInstance , cards) {
903                 // scope here is the modal-level scope
904                 $scope.args = {cards : cards};
905                 $scope.ok = function() { $modalInstance.close($scope.args) }
906                 $scope.cancel = function () { $modalInstance.dismiss() }
907             }],
908             resolve : {
909                 cards : function() {
910                     // scope here is the controller-level scope
911                     return $scope.patron.cards;
912                 }
913             }
914         }).result.then(
915             function(args) {
916                 angular.forEach(args.cards, function(card) {
917                     card.ischanged = true; // assume cards need updating, OK?
918                     if (card._primary == 'on' && 
919                         card.id != $scope.patron.card.id) {
920                         $scope.patron.card = card;
921                     }
922                 });
923             }
924         );
925     }
926
927     $scope.set_addr_type = function(addr, type) {
928         var addrs = $scope.patron.addresses;
929         if (addr['_is_'+type]) {
930             angular.forEach(addrs, function(a) {
931                 if (a.id != addr.id) a['_is_'+type] = false;
932             });
933         } else {
934             // unchecking mailing/billing means we have to randomly
935             // select another address to fill that role.  Select the
936             // first address in the list (that does not match the
937             // modifed address)
938             for (var i = 0; i < addrs.length; i++) {
939                 if (addrs[i].id != addr.id) {
940                     addrs[i]['_is_' + type] = true;
941                     break;
942                 }
943             }
944         }
945     }
946
947
948     // Translate hold notify preferences from the form/scope back into a 
949     // single user setting value for opac.hold_notify.
950     function compress_hold_notify() {
951         var hold_notify = '';
952         var splitter = '';
953         if ($scope.hold_notify_phone) {
954             hold_notify = 'phone';
955             splitter = ':';
956         }
957         if ($scope.hold_notify_email) {
958             hold_notify = splitter + 'email';
959             splitter = ':';
960         }
961         if ($scope.hold_notify_sms) {
962             hold_notify = splitter + 'sms';
963             splitter = ':';
964         }
965         $scope.user_settings['opac.hold_notify'] = hold_notify;
966     }
967
968     // dialog for selecting additional permission groups
969     $scope.secondary_groups_dialog = function() {
970         $modal.open({
971             templateUrl: './circ/patron/t_patron_groups_dialog',
972             controller: 
973                    ['$scope','$modalInstance','linked_groups','pgt_depth',
974             function($scope , $modalInstance , linked_groups , pgt_depth) {
975
976                 $scope.pgt_depth = pgt_depth;
977                 $scope.args = {
978                     linked_groups : linked_groups,
979                     edit_profiles : patronRegSvc.edit_profiles,
980                     new_profile   : patronRegSvc.edit_profiles[0]
981                 };
982
983                 // add a new group to the linked groups list
984                 $scope.link_group = function($event, grp) {
985                     var found = false; // avoid duplicates
986                     angular.forEach($scope.args.linked_groups, 
987                         function(g) {if (g.id() == grp.id()) found = true});
988                     if (!found) $scope.args.linked_groups.push(grp);
989                     $event.preventDefault(); // avoid close
990                 }
991
992                 // remove a group from the linked groups list
993                 $scope.unlink_group = function($event, grp) {
994                     $scope.args.linked_groups = 
995                         $scope.args.linked_groups.filter(function(g) {
996                         return g.id() != grp.id()
997                     });
998                     $event.preventDefault(); // avoid close
999                 }
1000
1001                 $scope.ok = function() { $modalInstance.close($scope.args) }
1002                 $scope.cancel = function () { $modalInstance.dismiss() }
1003             }],
1004             resolve : {
1005                 linked_groups : function() { return $scope.patron.groups },
1006                 pgt_depth : function() { return $scope.pgt_depth }
1007             }
1008         }).result.then(
1009             function(args) {
1010                 var ids = args.linked_groups.map(function(g) {return g.id()});
1011                 console.log('linking permission groups ' + ids);
1012                 return egCore.net.request(
1013                     'open-ils.actor',
1014                     'open-ils.actor.user.set_groups',
1015                     egCore.auth.token(), $scope.patron.id, ids)
1016                 .then(function(resp) {
1017                     if (resp == 1) {
1018                         $scope.patron.groups = args.linked_groups;
1019                     } else {
1020                         // debugging -- should be no events
1021                         alert('linked groups failure ' + egCore.evt.parse(resp));
1022                     }
1023                 });
1024             }
1025         );
1026     }
1027
1028     function extract_hold_notify() {
1029         notify = $scope.user_settings['opac.hold_notify'];
1030         if (!notify) return;
1031         $scope.hold_notify_phone = Boolean(notify.match(/phone/));
1032         $scope.hold_notify_email = Boolean(notify.match(/email/));
1033         $scope.hold_notify_sms = Boolean(notify.match(/sms/));
1034     }
1035
1036     $scope.invalidate_field = function(field) {
1037         patronRegSvc.invalidate_field($scope.patron, field);
1038     }
1039
1040     $scope.edit_passthru.save = function() {
1041
1042         // toss the deleted addresses back into the patron's list of
1043         // addresses so it's included in the update
1044         $scope.patron.addresses = 
1045             $scope.patron.addresses.concat(deleted_addresses);
1046         
1047         compress_hold_notify();
1048
1049         patronRegSvc.save_user($scope.patron)
1050         .then(function(new_user) { 
1051             if (new_user && new_user.classname) {
1052                 return patronRegSvc.save_user_settings(
1053                     new_user, $scope.user_settings); 
1054             } else {
1055                 alert('Patron update failed. \n\n' + js2JSON(new_user));
1056                 return true; // ensure page reloads to reset
1057             }
1058         }).then(function(keep_going) {
1059             // reloading the page means potentially losing some information
1060             // (e.g. last patron search), but is the only way to ensure all
1061             // components are properly updated to reflect the modified patron.
1062             $window.location.href = location.href;
1063         });
1064     }
1065 }
1066
1067 // This controller may be loaded from different modules (patron edit vs.
1068 // register new patron), so we have to inject the controller params manually.
1069 PatronRegCtrl.$inject = ['$scope', '$routeParams', '$q', '$modal', 
1070     '$window', 'egCore', 'patronSvc', 'patronRegSvc'];
1071