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