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