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