]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/circ/patron/regctl.js
LP#1452950 patron reg. unload prompt stub
[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.dupe_patron_search = function(patron, type, value) {
377         var search;
378
379         console.log('Dupe search called with "' + 
380             type +"' and value " + value);
381
382         switch (type) {
383
384             case 'name':
385                 var fname = patron.first_given_name;   
386                 var lname = patron.family_name;   
387                 if (!(fname && lname)) return;
388                 search = {
389                     first_given_name : {value : fname, group : 0},
390                     family_name : {value : lname, group : 0}
391                 };
392                 break;
393
394             case 'email':
395                 search = {email : {value : value, group : 0}};
396                 break;
397
398             case 'ident':
399                 search = {ident : {value : value, group : 2}};
400                 break;
401
402             case 'phone':
403                 search = {phone : {value : value, group : 2}};
404                 break;
405
406             case 'address':
407                 search = {};
408                 angular.forEach(['street1', 'street2', 'city', 'post_code'],
409                     function(field) {
410                         if(value[field])
411                             search[field] = {value : value[field], group: 1};
412                     }
413                 );
414                 break;
415         }
416
417         return egCore.net.request( 
418             'open-ils.actor', 
419             'open-ils.actor.patron.search.advanced',
420             egCore.auth.token(), search, null, null, 1
421         ).then(function(res) {
422             res = res.filter(function(id) {return id != patron.id});
423             return {
424                 count : res.length,
425                 search : search
426             };
427         });
428     }
429
430     service.init_patron = function(current) {
431
432         if (!current)
433             return service.init_new_patron();
434
435         service.patron = current;
436         return service.init_existing_patron(current)
437     }
438
439     service.ingest_address = function(patron, addr) {
440         addr.valid = addr.valid == 't';
441         addr.within_city_limits = addr.within_city_limits == 't';
442         addr._is_mailing = (patron.mailing_address && 
443             addr.id == patron.mailing_address.id);
444         addr._is_billing = (patron.billing_address && 
445             addr.id == patron.billing_address.id);
446     }
447
448     /*
449      * Existing patron objects reqire some data munging before insertion
450      * into the scope.
451      *
452      * 1. Turn everything into a hash
453      * 2. ... Except certain fields (selectors) whose widgets require objects
454      * 3. Bools must be Boolean, not t/f.
455      */
456     service.init_existing_patron = function(current) {
457
458         var patron = egCore.idl.toHash(current);
459
460         patron.home_ou = egCore.org.get(patron.home_ou.id);
461         patron.expire_date = new Date(Date.parse(patron.expire_date));
462         patron.dob = patron.dob ?
463             new Date(Date.parse(patron.dob)) : null;
464         patron.profile = current.profile(); // pre-hash version
465         patron.net_access_level = current.net_access_level();
466         patron.ident_type = current.ident_type();
467         patron.groups = current.groups(); // pre-hash
468
469         angular.forEach(
470             ['juvenile', 'barred', 'active', 'master_account'],
471             function(field) { patron[field] = patron[field] == 't'; }
472         );
473
474         angular.forEach(patron.cards, function(card) {
475             card.active = card.active == 't';
476             if (card.id == patron.card.id) {
477                 patron.card = card;
478                 card._primary = 'on';
479             }
480         });
481
482         angular.forEach(patron.addresses, 
483             function(addr) { service.ingest_address(patron, addr) });
484
485         // toss entries for existing stat cat maps into our living 
486         // stat cat entry map, which is modified within the template.
487         angular.forEach(patron.stat_cat_entries, function(map) {
488             var entry;
489             angular.forEach(service.stat_cats, function(cat) {
490                 angular.forEach(cat.entries(), function(ent) {
491                     if (ent.id() == map.stat_cat_entry)
492                         entry = ent;
493                 });
494             });
495             service.stat_cat_entry_maps[map.stat_cat.id] = entry;
496         });
497
498         return patron;
499     }
500
501     service.init_new_patron = function() {
502         var addr = {
503             id : service.virt_id--,
504             isnew : true,
505             valid : true,
506             address_type : egCore.strings.REG_ADDR_TYPE,
507             _is_mailing : true,
508             _is_billing : true,
509             within_city_limits : false,
510             stat_cat_entries : []
511         };
512
513         var card = {
514             id : service.virt_id--,
515             isnew : true,
516             active : true,
517             _primary : 'on'
518         };
519
520         return {
521             isnew : true,
522             active : true,
523             card : card,
524             cards : [card],
525             home_ou : egCore.org.get(egCore.auth.user().ws_ou()),
526                         
527             // TODO default profile group?
528             addresses : [addr]
529         };
530     }
531
532     // translate the patron back into IDL form
533     service.save_user = function(phash) {
534
535         var patron = egCore.idl.fromHash('au', phash);
536
537         patron.home_ou(patron.home_ou().id());
538         patron.expire_date(patron.expire_date().toISOString());
539         patron.profile(patron.profile().id());
540         if (patron.dob()) 
541             patron.dob(patron.dob().toISOString().replace(/T.*/,''));
542         if (patron.ident_type()) 
543             patron.ident_type(patron.ident_type().id());
544         if (patron.net_access_level())
545             patron.net_access_level(patron.net_access_level().id());
546
547         angular.forEach(
548             ['juvenile', 'barred', 'active', 'master_account'],
549             function(field) { patron[field](phash[field] ? 't' : 'f'); }
550         );
551
552         var card_hashes = patron.cards();
553         patron.cards([]);
554         angular.forEach(card_hashes, function(chash) {
555             var card = egCore.idl.fromHash('ac', chash)
556             card.usr(patron.id());
557             card.active(chash.active ? 't' : 'f');
558             patron.cards().push(card);
559             if (chash._primary) {
560                 patron.card(card);
561             }
562         });
563
564         var addr_hashes = patron.addresses();
565         patron.addresses([]);
566         angular.forEach(addr_hashes, function(addr_hash) {
567             if (!addr_hash.isnew && !addr_hash.isdeleted) 
568                 addr_hash.ischanged = true;
569             var addr = egCore.idl.fromHash('aua', addr_hash);
570             patron.addresses().push(addr);
571             addr.valid(addr.valid() ? 't' : 'f');
572             addr.within_city_limits(addr.within_city_limits() ? 't' : 'f');
573             if (addr_hash._is_mailing) patron.mailing_address(addr);
574             if (addr_hash._is_billing) patron.billing_address(addr);
575         });
576
577         patron.survey_responses([]);
578         angular.forEach(service.survey_responses, function(answer) {
579             var question = service.survey_questions[answer.question()];
580             var resp = new egCore.idl.asvr();
581             resp.isnew(true);
582             resp.survey(question.survey());
583             resp.question(question.id());
584             resp.answer(answer.id());
585             resp.usr(patron.id());
586             resp.answer_date('now');
587             patron.survey_responses().push(resp);
588         });
589         
590         // re-object-ify the patron stat cat entry maps
591         var maps = [];
592         angular.forEach(patron.stat_cat_entries(), function(entry) {
593             var e = egCore.idl.fromHash('actscecm', entry);
594             e.stat_cat(e.stat_cat().id);
595             maps.push(e);
596         });
597         patron.stat_cat_entries(maps);
598
599         // service.stat_cat_entry_maps maps stats to entries
600         // patron.stat_cat_entries is an array of stat_cat_entry_usr_map's
601         angular.forEach(service.stat_cat_entry_maps, function(entry) {
602
603             // see if we already have a mapping for this entry
604             var existing = patron.stat_cat_entries().filter(function(e) {
605                 return e.stat_cat() == entry.stat_cat();
606             })[0];
607
608             if (existing) { // we have a mapping
609                 // if the existing mapping matches the new one,
610                 // there' nothing left to do
611                 if (existing.stat_cat_entry() == entry.id()) return;
612
613                 // mappings differ.  delete the old one and create
614                 // a new one below.
615                 existing.isdeleted(true);
616             }
617
618             var newmap = new egCore.idl.actscecm();
619             newmap.target_usr(patron.id());
620             newmap.isnew(true);
621             newmap.stat_cat(entry.stat_cat());
622             newmap.stat_cat_entry(entry.id());
623             patron.stat_cat_entries().push(newmap);
624         });
625
626         angular.forEach(patron.stat_cat_entries(), function(entry) {
627             console.log(egCore.idl.toString(entry));
628         });
629
630         if (!patron.isnew()) patron.ischanged(true);
631
632         return egCore.net.request(
633             'open-ils.actor', 
634             'open-ils.actor.patron.update',
635             egCore.auth.token(), patron);
636     }
637
638     service.save_user_settings = function(new_user, user_settings) {
639         // user_settings contains the values from the scope/form.
640         // service.user_settings contain the values from page load time.
641
642         var settings = {};
643         if (service.patron_id) {
644             // only update modified settings for existing patrons
645             angular.forEach(user_settings, function(val, key) {
646                 if (val !== service.user_settings[key])
647                     settings[key] = val;
648             });
649
650         } else {
651             // all non-null setting values are updated for new patrons
652             angular.forEach(user_settings, function(val, key) {
653                 if (val !== null) settings[key] = val;
654             });
655         }
656
657         if (Object.keys(settings).length == 0) return $q.when();
658
659         return egCore.net.request(
660             'open-ils.actor',
661             'open-ils.actor.patron.settings.update',
662             egCore.auth.token(), new_user.id(), settings
663         ).then(function(resp) {
664             console.log('settings returned ' + resp);
665             return resp;
666         });
667     }
668
669     return service;
670 }]);
671
672
673 function PatronRegCtrl($scope, $routeParams, 
674     $q, $modal, $window, egCore, patronSvc, patronRegSvc, egUnloadPrompt) {
675
676     $scope.page_data_loaded = false;
677     $scope.clone_id = $routeParams.clone_id;
678     $scope.stage_username = $routeParams.stage_username;
679     $scope.patron_id = 
680         patronRegSvc.patron_id = $routeParams.edit_id || $routeParams.id;
681
682     // for existing patrons, disable barcode input by default
683     $scope.disable_bc = $scope.focus_usrname = Boolean($scope.patron_id);
684     $scope.focus_bc = !Boolean($scope.patron_id);
685     $scope.dupe_counts = {};
686
687     if (!$scope.edit_passthru) {
688         // in edit more, scope.edit_passthru is delivered to us by
689         // the enclosing controller.  In register mode, there is 
690         // no enclosing controller, so we create our own.
691         $scope.edit_passthru = {};
692     }
693
694     // 0=all, 1=suggested, 2=all
695     $scope.edit_passthru.vis_level = 0; 
696     // TODO: add save/clone handlers here
697
698     // TODO: call attach() on the first instance of a modified value
699     //egUnloadPrompt.attach($scope);
700
701     // Apply default values for new patrons during initial registration
702     // prs is shorthand for patronSvc
703     function set_new_patron_defaults(prs) {
704         $scope.generate_password();
705         $scope.hold_notify_phone = true;
706         $scope.hold_notify_email = true;
707
708         if (prs.org_settings['ui.patron.default_ident_type']) {
709             // $scope.patron needs this field to be an object
710             var id = prs.org_settings['ui.patron.default_ident_type'];
711             var ident_type = $scope.ident_types.filter(
712                 function(type) { return type.id() == id })[0];
713             $scope.patron.ident_type = ident_type;
714         }
715         if (prs.org_settings['ui.patron.default_inet_access_level']) {
716             // $scope.patron needs this field to be an object
717             var id = prs.org_settings['ui.patron.default_inet_access_level'];
718             var level = $scope.net_access_levels.filter(
719                 function(lvl) { return lvl.id() == id })[0];
720             $scope.patron.net_access_level = level;
721         }
722         if (prs.org_settings['ui.patron.default_country']) {
723             $scope.patron.addresses[0].country = 
724                 prs.org_settings['ui.patron.default_country'];
725         }
726     }
727
728     function handle_home_org_changed() {
729         org_id = $scope.patron.home_ou.id();
730
731         patronRegSvc.has_group_link_perms(org_id)
732         .then(function(bool) {$scope.has_group_link_perm = bool});
733     }
734
735     $q.all([
736
737         $scope.initTab ? // initTab comes from patron app
738             $scope.initTab('edit', $routeParams.id) : $q.when(),
739
740         patronRegSvc.init()
741
742     ]).then(function() {
743         // called after initTab and patronRegSvc.init have completed
744
745         var prs = patronRegSvc; // brevity
746         // in standalone mode, we have no patronSvc
747         $scope.patron = prs.init_patron(patronSvc ? patronSvc.current : null);
748         $scope.field_doc = prs.field_doc;
749         $scope.edit_profiles = prs.edit_profiles;
750         $scope.ident_types = prs.ident_types;
751         $scope.net_access_levels = prs.net_access_levels;
752         $scope.user_setting_types = prs.user_setting_types;
753         $scope.opt_in_setting_types = prs.opt_in_setting_types;
754         $scope.org_settings = prs.org_settings;
755         $scope.sms_carriers = prs.sms_carriers;
756         $scope.stat_cats = prs.stat_cats;
757         $scope.surveys = prs.surveys;
758         $scope.survey_responses = prs.survey_responses;
759         $scope.stat_cat_entry_maps = prs.stat_cat_entry_maps;
760
761         $scope.user_settings = prs.user_settings;
762         // clone the user settings back into the patronRegSvc so
763         // we have a copy of the original state of the settings.
764         prs.user_settings = {};
765         angular.forEach($scope.user_settings, function(val, key) {
766             prs.user_settings[key] = val;
767         });
768
769         extract_hold_notify();
770         handle_home_org_changed();
771
772         if ($scope.org_settings['ui.patron.edit.default_suggested'])
773             $scope.edit_passthru.vis_level = 1;
774
775         if ($scope.patron.isnew) 
776             set_new_patron_defaults(prs);
777
778         $scope.page_data_loaded = true;
779     });
780
781     // update the currently displayed field documentation
782     $scope.set_selected_field_doc = function(cls, field) {
783         $scope.selected_field_doc = $scope.field_doc[cls][field];
784     }
785
786     // returns the tree depth of the selected profile group tree node.
787     $scope.pgt_depth = function(grp) {
788         var d = 0;
789         while (grp = egCore.env.pgt.map[grp.parent()]) d++;
790         return d;
791     }
792
793     // IDL fields used for labels in the UI.
794     $scope.idl_fields = {
795         au  : egCore.idl.classes.au.field_map,
796         ac  : egCore.idl.classes.ac.field_map,
797         aua : egCore.idl.classes.aua.field_map
798     };
799
800     // field visibility cache.  Some fields are universally required.
801     var field_visibility = {
802         'ac.barcode' : 2,
803         'au.usrname' : 2,
804         'au.passwd' :  2,
805         // TODO passwd2 2,
806         'au.first_given_name' : 2,
807         'au.family_name' : 2,
808         'au.ident_type' : 2,
809         'au.home_ou' : 2,
810         'au.profile' : 2,
811         'au.expire_date' : 2,
812         'au.net_access_level' : 2,
813         'aua.address_type' : 2,
814         'aua.post_code' : 2,
815         'aua.street1' : 2,
816         'aua.street2' : 2,
817         'aua.city' : 2,
818         'aua.county' : 2,
819         'aua.state' : 2,
820         'aua.country' : 2,
821         'aua.valid' : 2,
822         'aua.within_city_limits' : 2,
823         'stat_cats' : 1,
824         'surveys' : 1
825     }; 
826
827     // returns true if the selected field should be visible
828     // given the current required/suggested/all setting.
829     $scope.show_field = function(field_key) {
830
831         if (field_visibility[field_key] == undefined) {
832             // compile and cache the visibility for the selected field
833
834             // org settings have not been received yet.
835             if (!$scope.org_settings) return false;
836
837             var req_set = 'ui.patron.edit.' + field_key + '.require';
838             var sho_set = 'ui.patron.edit.' + field_key + '.show';
839             var sug_set = 'ui.patron.edit.' + field_key + '.suggest';
840
841             if ($scope.org_settings[req_set]) {
842                 field_visibility[field_key] = 2;
843             } else if ($scope.org_settings[sho_set]) {
844                 field_visibility[field_key] = 2;
845             } else if ($scope.org_settings[sug_set]) {
846                 field_visibility[field_key] = 1;
847             } else {
848                 field_visibility[field_key] = 0;
849             }
850         }
851
852         return field_visibility[field_key] >= $scope.edit_passthru.vis_level;
853     }
854
855     // generates a random 4-digit password
856     $scope.generate_password = function() {
857         $scope.patron.passwd = Math.floor(Math.random()*9000) + 1000;
858     }
859
860     $scope.set_expire_date = function() {
861         if (!$scope.patron.profile) return;
862         var seconds = egCore.date.intervalToSeconds(
863             $scope.patron.profile.perm_interval());
864         var now_epoch = new Date().getTime();
865         $scope.patron.expire_date = new Date(
866             now_epoch + (seconds * 1000 /* milliseconds */))
867     }
868
869     // grp is the pgt object
870     $scope.set_profile = function(grp) {
871         $scope.patron.profile = grp;
872         $scope.set_expire_date();
873     }
874
875     $scope.new_address = function() {
876         var addr = egCore.idl.toHash(new egCore.idl.aua());
877         patronRegSvc.ingest_address($scope.patron, addr);
878         addr.id = patronRegSvc.virt_id--;
879         addr.isnew = true;
880         addr.valid = true;
881         addr.within_city_limits = true;
882         $scope.patron.addresses.push(addr);
883     }
884
885     // keep deleted addresses out of the patron object so
886     // they won't appear in the UI.  They'll be re-inserted
887     // when the patron is updated.
888     deleted_addresses = [];
889     $scope.delete_address = function(id) {
890         var addresses = [];
891         angular.forEach($scope.patron.addresses, function(addr) {
892             if (addr.id == id) {
893                 if (id > 0) {
894                     addr.isdeleted = true;
895                     deleted_addresses.push(addr);
896                 }
897             } else {
898                 addresses.push(addr);
899             }
900         });
901         $scope.patron.addresses = addresses;
902     } 
903
904     $scope.post_code_changed = function(addr) { 
905         egCore.net.request(
906             'open-ils.search', 'open-ils.search.zip', addr.post_code)
907         .then(function(resp) {
908             if (!resp) return;
909             if (resp.city) addr.city = resp.city;
910             if (resp.state) addr.state = resp.state;
911             if (resp.county) addr.county = resp.county;
912             if (resp.alert) alert(resp.alert);
913         });
914     }
915
916     $scope.replace_card = function() {
917         $scope.patron.card.active = false;
918         $scope.patron.card.ischanged = true;
919         $scope.disable_bc = false;
920
921         var new_card = egCore.idl.toHash(new egCore.idl.ac());
922         new_card.id = patronRegSvc.virt_id--;
923         new_card.isnew = true;
924         new_card.active = true;
925         new_card._primary = 'on';
926         $scope.patron.card = new_card;
927         $scope.patron.cards.push(new_card);
928     }
929
930     $scope.day_phone_changed = function(phone) {
931         if (phone && $scope.org_settings['patron.password.use_phone']) {
932            $scope.patron.passwd = phone.substr(-4);
933         }
934     }
935
936     $scope.barcode_changed = function(bc) {
937         if (!bc) return;
938         egCore.net.request(
939             'open-ils.actor',
940             'open-ils.actor.barcode.exists',
941             egCore.auth.token(), bc
942         ).then(function(resp) {
943             if (resp == '1') {
944                 console.log('duplicate barcode detected: ' + bc);
945                 // DUPLICATE CARD
946             } else {
947                 if (!$scope.patron.usrname)
948                     $scope.patron.usrname = bc;
949                 // No dupe -- A-OK
950             }
951         });
952     }
953
954     $scope.cards_dialog = function() {
955         $modal.open({
956             templateUrl: './circ/patron/t_patron_cards_dialog',
957             controller: 
958                    ['$scope','$modalInstance','cards',
959             function($scope , $modalInstance , cards) {
960                 // scope here is the modal-level scope
961                 $scope.args = {cards : cards};
962                 $scope.ok = function() { $modalInstance.close($scope.args) }
963                 $scope.cancel = function () { $modalInstance.dismiss() }
964             }],
965             resolve : {
966                 cards : function() {
967                     // scope here is the controller-level scope
968                     return $scope.patron.cards;
969                 }
970             }
971         }).result.then(
972             function(args) {
973                 angular.forEach(args.cards, function(card) {
974                     card.ischanged = true; // assume cards need updating, OK?
975                     if (card._primary == 'on' && 
976                         card.id != $scope.patron.card.id) {
977                         $scope.patron.card = card;
978                     }
979                 });
980             }
981         );
982     }
983
984     $scope.set_addr_type = function(addr, type) {
985         var addrs = $scope.patron.addresses;
986         if (addr['_is_'+type]) {
987             angular.forEach(addrs, function(a) {
988                 if (a.id != addr.id) a['_is_'+type] = false;
989             });
990         } else {
991             // unchecking mailing/billing means we have to randomly
992             // select another address to fill that role.  Select the
993             // first address in the list (that does not match the
994             // modifed address)
995             for (var i = 0; i < addrs.length; i++) {
996                 if (addrs[i].id != addr.id) {
997                     addrs[i]['_is_' + type] = true;
998                     break;
999                 }
1000             }
1001         }
1002     }
1003
1004
1005     // Translate hold notify preferences from the form/scope back into a 
1006     // single user setting value for opac.hold_notify.
1007     function compress_hold_notify() {
1008         var hold_notify = '';
1009         var splitter = '';
1010         if ($scope.hold_notify_phone) {
1011             hold_notify = 'phone';
1012             splitter = ':';
1013         }
1014         if ($scope.hold_notify_email) {
1015             hold_notify = splitter + 'email';
1016             splitter = ':';
1017         }
1018         if ($scope.hold_notify_sms) {
1019             hold_notify = splitter + 'sms';
1020             splitter = ':';
1021         }
1022         $scope.user_settings['opac.hold_notify'] = hold_notify;
1023     }
1024
1025     // dialog for selecting additional permission groups
1026     $scope.secondary_groups_dialog = function() {
1027         $modal.open({
1028             templateUrl: './circ/patron/t_patron_groups_dialog',
1029             controller: 
1030                    ['$scope','$modalInstance','linked_groups','pgt_depth',
1031             function($scope , $modalInstance , linked_groups , pgt_depth) {
1032
1033                 $scope.pgt_depth = pgt_depth;
1034                 $scope.args = {
1035                     linked_groups : linked_groups,
1036                     edit_profiles : patronRegSvc.edit_profiles,
1037                     new_profile   : patronRegSvc.edit_profiles[0]
1038                 };
1039
1040                 // add a new group to the linked groups list
1041                 $scope.link_group = function($event, grp) {
1042                     var found = false; // avoid duplicates
1043                     angular.forEach($scope.args.linked_groups, 
1044                         function(g) {if (g.id() == grp.id()) found = true});
1045                     if (!found) $scope.args.linked_groups.push(grp);
1046                     $event.preventDefault(); // avoid close
1047                 }
1048
1049                 // remove a group from the linked groups list
1050                 $scope.unlink_group = function($event, grp) {
1051                     $scope.args.linked_groups = 
1052                         $scope.args.linked_groups.filter(function(g) {
1053                         return g.id() != grp.id()
1054                     });
1055                     $event.preventDefault(); // avoid close
1056                 }
1057
1058                 $scope.ok = function() { $modalInstance.close($scope.args) }
1059                 $scope.cancel = function () { $modalInstance.dismiss() }
1060             }],
1061             resolve : {
1062                 linked_groups : function() { return $scope.patron.groups },
1063                 pgt_depth : function() { return $scope.pgt_depth }
1064             }
1065         }).result.then(
1066             function(args) {
1067                 var ids = args.linked_groups.map(function(g) {return g.id()});
1068                 console.log('linking permission groups ' + ids);
1069                 return egCore.net.request(
1070                     'open-ils.actor',
1071                     'open-ils.actor.user.set_groups',
1072                     egCore.auth.token(), $scope.patron.id, ids)
1073                 .then(function(resp) {
1074                     if (resp == 1) {
1075                         $scope.patron.groups = args.linked_groups;
1076                     } else {
1077                         // debugging -- should be no events
1078                         alert('linked groups failure ' + egCore.evt.parse(resp));
1079                     }
1080                 });
1081             }
1082         );
1083     }
1084
1085     function extract_hold_notify() {
1086         notify = $scope.user_settings['opac.hold_notify'];
1087         if (!notify) return;
1088         $scope.hold_notify_phone = Boolean(notify.match(/phone/));
1089         $scope.hold_notify_email = Boolean(notify.match(/email/));
1090         $scope.hold_notify_sms = Boolean(notify.match(/sms/));
1091     }
1092
1093     $scope.invalidate_field = function(field) {
1094         patronRegSvc.invalidate_field($scope.patron, field);
1095     }
1096
1097     $scope.dupe_value_changed = function(type, value) {
1098         $scope.dupe_counts[type] = 0;
1099         patronRegSvc.dupe_patron_search($scope.patron, type, value)
1100         .then(function(res) {
1101             $scope.dupe_counts[type] = res.count;
1102             $scope.dupe_search_encoded = 
1103                 encodeURIComponent(js2JSON(res.search));
1104         });
1105     }
1106
1107     $scope.edit_passthru.save = function() {
1108
1109         // toss the deleted addresses back into the patron's list of
1110         // addresses so it's included in the update
1111         $scope.patron.addresses = 
1112             $scope.patron.addresses.concat(deleted_addresses);
1113         
1114         compress_hold_notify();
1115
1116         patronRegSvc.save_user($scope.patron)
1117         .then(function(new_user) { 
1118             if (new_user && new_user.classname) {
1119                 return patronRegSvc.save_user_settings(
1120                     new_user, $scope.user_settings); 
1121             } else {
1122                 alert('Patron update failed. \n\n' + js2JSON(new_user));
1123                 return true; // ensure page reloads to reset
1124             }
1125         }).then(function(keep_going) {
1126             // reloading the page means potentially losing some information
1127             // (e.g. last patron search), but is the only way to ensure all
1128             // components are properly updated to reflect the modified patron.
1129             $window.location.href = location.href;
1130         });
1131     }
1132 }
1133
1134 // This controller may be loaded from different modules (patron edit vs.
1135 // register new patron), so we have to inject the controller params manually.
1136 PatronRegCtrl.$inject = ['$scope', '$routeParams', '$q', '$modal', 
1137     '$window', 'egCore', 'patronSvc', 'patronRegSvc', 'egUnloadPrompt'];
1138