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