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