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