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