]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/circ/patron/regctl.js
LP#1452950 patron dupe search / plumbing
[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             // TODO hide dupe results links matching the type 
385             // of the current search
386
387             case 'name':
388                 var fname = patron.first_given_name;   
389                 var lname = patron.family_name;   
390                 if (!(fname && lname)) return;
391                 search = {
392                     first_given_name : {value : fname, group : 0},
393                     family_name : {value : lname, group : 0}
394                 };
395                 break;
396
397             case 'email':
398                 search = {email : {value : value, group : 0}};
399                 break;
400
401             case 'ident':
402                 search = {ident : {value : value, group : 2}};
403                 break;
404
405             case 'phone':
406                 search = {phone : {value : value, group : 2}};
407                 break;
408
409             case 'address':
410                 search = {};
411                 angular.forEach(['street1', 'street2', 'city', 'post_code'],
412                     function(field) {
413                         if(value[field])
414                             search[field] = {value : value[field], group: 1};
415                     }
416                 );
417                 break;
418         }
419
420         return egCore.net.request( 
421             'open-ils.actor', 
422             'open-ils.actor.patron.search.advanced',
423             egCore.auth.token(), search, null, null, 1
424         ).then(function(res) {
425
426             res = res.filter(function(id) {return id != patron.id});
427             if (res.length == 0) return;
428
429             console.log(js2JSON(res));
430         });
431     }
432
433     service.init_patron = function(current) {
434
435         if (!current)
436             return service.init_new_patron();
437
438         service.patron = current;
439         return service.init_existing_patron(current)
440     }
441
442     service.ingest_address = function(patron, addr) {
443         addr.valid = addr.valid == 't';
444         addr.within_city_limits = addr.within_city_limits == 't';
445         addr._is_mailing = (patron.mailing_address && 
446             addr.id == patron.mailing_address.id);
447         addr._is_billing = (patron.billing_address && 
448             addr.id == patron.billing_address.id);
449     }
450
451     /*
452      * Existing patron objects reqire some data munging before insertion
453      * into the scope.
454      *
455      * 1. Turn everything into a hash
456      * 2. ... Except certain fields (selectors) whose widgets require objects
457      * 3. Bools must be Boolean, not t/f.
458      */
459     service.init_existing_patron = function(current) {
460
461         var patron = egCore.idl.toHash(current);
462
463         patron.home_ou = egCore.org.get(patron.home_ou.id);
464         patron.expire_date = new Date(Date.parse(patron.expire_date));
465         patron.dob = patron.dob ?
466             new Date(Date.parse(patron.dob)) : null;
467         patron.profile = current.profile(); // pre-hash version
468         patron.net_access_level = current.net_access_level();
469         patron.ident_type = current.ident_type();
470         patron.groups = current.groups(); // pre-hash
471
472         angular.forEach(
473             ['juvenile', 'barred', 'active', 'master_account'],
474             function(field) { patron[field] = patron[field] == 't'; }
475         );
476
477         angular.forEach(patron.cards, function(card) {
478             card.active = card.active == 't';
479             if (card.id == patron.card.id) {
480                 patron.card = card;
481                 card._primary = 'on';
482             }
483         });
484
485         angular.forEach(patron.addresses, 
486             function(addr) { service.ingest_address(patron, addr) });
487
488         // toss entries for existing stat cat maps into our living 
489         // stat cat entry map, which is modified within the template.
490         angular.forEach(patron.stat_cat_entries, function(map) {
491             var entry;
492             angular.forEach(service.stat_cats, function(cat) {
493                 angular.forEach(cat.entries(), function(ent) {
494                     if (ent.id() == map.stat_cat_entry)
495                         entry = ent;
496                 });
497             });
498             service.stat_cat_entry_maps[map.stat_cat.id] = entry;
499         });
500
501         return patron;
502     }
503
504     service.init_new_patron = function() {
505         var addr = {
506             id : service.virt_id--,
507             isnew : true,
508             valid : true,
509             address_type : egCore.strings.REG_ADDR_TYPE,
510             _is_mailing : true,
511             _is_billing : true,
512             within_city_limits : false,
513             stat_cat_entries : []
514         };
515
516         var card = {
517             id : service.virt_id--,
518             isnew : true,
519             active : true,
520             _primary : 'on'
521         };
522
523         return {
524             isnew : true,
525             active : true,
526             card : card,
527             cards : [card],
528             home_ou : egCore.org.get(egCore.auth.user().ws_ou()),
529                         
530             // TODO default profile group?
531             addresses : [addr]
532         };
533     }
534
535     // translate the patron back into IDL form
536     service.save_user = function(phash) {
537
538         var patron = egCore.idl.fromHash('au', phash);
539
540         patron.home_ou(patron.home_ou().id());
541         patron.expire_date(patron.expire_date().toISOString());
542         patron.profile(patron.profile().id());
543         if (patron.dob()) 
544             patron.dob(patron.dob().toISOString().replace(/T.*/,''));
545         if (patron.ident_type()) 
546             patron.ident_type(patron.ident_type().id());
547         if (patron.net_access_level())
548             patron.net_access_level(patron.net_access_level().id());
549
550         angular.forEach(
551             ['juvenile', 'barred', 'active', 'master_account'],
552             function(field) { patron[field](phash[field] ? 't' : 'f'); }
553         );
554
555         var card_hashes = patron.cards();
556         patron.cards([]);
557         angular.forEach(card_hashes, function(chash) {
558             var card = egCore.idl.fromHash('ac', chash)
559             card.usr(patron.id());
560             card.active(chash.active ? 't' : 'f');
561             patron.cards().push(card);
562             if (chash._primary) {
563                 patron.card(card);
564             }
565         });
566
567         var addr_hashes = patron.addresses();
568         patron.addresses([]);
569         angular.forEach(addr_hashes, function(addr_hash) {
570             if (!addr_hash.isnew && !addr_hash.isdeleted) 
571                 addr_hash.ischanged = true;
572             var addr = egCore.idl.fromHash('aua', addr_hash);
573             patron.addresses().push(addr);
574             addr.valid(addr.valid() ? 't' : 'f');
575             addr.within_city_limits(addr.within_city_limits() ? 't' : 'f');
576             if (addr_hash._is_mailing) patron.mailing_address(addr);
577             if (addr_hash._is_billing) patron.billing_address(addr);
578         });
579
580         patron.survey_responses([]);
581         angular.forEach(service.survey_responses, function(answer) {
582             var question = service.survey_questions[answer.question()];
583             var resp = new egCore.idl.asvr();
584             resp.isnew(true);
585             resp.survey(question.survey());
586             resp.question(question.id());
587             resp.answer(answer.id());
588             resp.usr(patron.id());
589             resp.answer_date('now');
590             patron.survey_responses().push(resp);
591         });
592         
593         // re-object-ify the patron stat cat entry maps
594         var maps = [];
595         angular.forEach(patron.stat_cat_entries(), function(entry) {
596             var e = egCore.idl.fromHash('actscecm', entry);
597             e.stat_cat(e.stat_cat().id);
598             maps.push(e);
599         });
600         patron.stat_cat_entries(maps);
601
602         // service.stat_cat_entry_maps maps stats to entries
603         // patron.stat_cat_entries is an array of stat_cat_entry_usr_map's
604         angular.forEach(service.stat_cat_entry_maps, function(entry) {
605
606             // see if we already have a mapping for this entry
607             var existing = patron.stat_cat_entries().filter(function(e) {
608                 return e.stat_cat() == entry.stat_cat();
609             })[0];
610
611             if (existing) { // we have a mapping
612                 // if the existing mapping matches the new one,
613                 // there' nothing left to do
614                 if (existing.stat_cat_entry() == entry.id()) return;
615
616                 // mappings differ.  delete the old one and create
617                 // a new one below.
618                 existing.isdeleted(true);
619             }
620
621             var newmap = new egCore.idl.actscecm();
622             newmap.target_usr(patron.id());
623             newmap.isnew(true);
624             newmap.stat_cat(entry.stat_cat());
625             newmap.stat_cat_entry(entry.id());
626             patron.stat_cat_entries().push(newmap);
627         });
628
629         angular.forEach(patron.stat_cat_entries(), function(entry) {
630             console.log(egCore.idl.toString(entry));
631         });
632
633         if (!patron.isnew()) patron.ischanged(true);
634
635         return egCore.net.request(
636             'open-ils.actor', 
637             'open-ils.actor.patron.update',
638             egCore.auth.token(), patron);
639     }
640
641     service.save_user_settings = function(new_user, user_settings) {
642         // user_settings contains the values from the scope/form.
643         // service.user_settings contain the values from page load time.
644
645         var settings = {};
646         if (service.patron_id) {
647             // only update modified settings for existing patrons
648             angular.forEach(user_settings, function(val, key) {
649                 if (val !== service.user_settings[key])
650                     settings[key] = val;
651             });
652
653         } else {
654             // all non-null setting values are updated for new patrons
655             angular.forEach(user_settings, function(val, key) {
656                 if (val !== null) settings[key] = val;
657             });
658         }
659
660         if (Object.keys(settings).length == 0) return $q.when();
661
662         return egCore.net.request(
663             'open-ils.actor',
664             'open-ils.actor.patron.settings.update',
665             egCore.auth.token(), new_user.id(), settings
666         ).then(function(resp) {
667             console.log('settings returned ' + resp);
668             return resp;
669         });
670     }
671
672     return service;
673 }]);
674
675
676 function PatronRegCtrl($scope, $routeParams, 
677     $q, $modal, $window, egCore, patronSvc, patronRegSvc) {
678
679     $scope.page_data_loaded = false;
680     $scope.clone_id = $routeParams.clone_id;
681     $scope.stage_username = $routeParams.stage_username;
682     $scope.patron_id = 
683         patronRegSvc.patron_id = $routeParams.edit_id || $routeParams.id;
684
685     // for existing patrons, disable barcode input by default
686     $scope.disable_bc = $scope.focus_usrname = Boolean($scope.patron_id);
687     $scope.focus_bc = !Boolean($scope.patron_id);
688
689     if (!$scope.edit_passthru) {
690         // in edit more, scope.edit_passthru is delivered to us by
691         // the enclosing controller.  In register mode, there is 
692         // no enclosing controller, so we create our own.
693         $scope.edit_passthru = {};
694     }
695
696     // 0=all, 1=suggested, 2=all
697     $scope.edit_passthru.vis_level = 0; 
698     // TODO: add save/clone handlers here
699
700     // Apply default values for new patrons during initial registration
701     // prs is shorthand for patronSvc
702     function set_new_patron_defaults(prs) {
703         $scope.generate_password();
704         $scope.hold_notify_phone = true;
705         $scope.hold_notify_email = true;
706
707         if (prs.org_settings['ui.patron.default_ident_type']) {
708             // $scope.patron needs this field to be an object
709             var id = prs.org_settings['ui.patron.default_ident_type'];
710             var ident_type = $scope.ident_types.filter(
711                 function(type) { return type.id() == id })[0];
712             $scope.patron.ident_type = ident_type;
713         }
714         if (prs.org_settings['ui.patron.default_inet_access_level']) {
715             // $scope.patron needs this field to be an object
716             var id = prs.org_settings['ui.patron.default_inet_access_level'];
717             var level = $scope.net_access_levels.filter(
718                 function(lvl) { return lvl.id() == id })[0];
719             $scope.patron.net_access_level = level;
720         }
721         if (prs.org_settings['ui.patron.default_country']) {
722             $scope.patron.addresses[0].country = 
723                 prs.org_settings['ui.patron.default_country'];
724         }
725     }
726
727     function handle_home_org_changed() {
728         org_id = $scope.patron.home_ou.id();
729
730         patronRegSvc.has_group_link_perms(org_id)
731         .then(function(bool) {$scope.has_group_link_perm = bool});
732     }
733
734     $q.all([
735
736         $scope.initTab ? // initTab comes from patron app
737             $scope.initTab('edit', $routeParams.id) : $q.when(),
738
739         patronRegSvc.init()
740
741     ]).then(function() {
742         // called after initTab and patronRegSvc.init have completed
743
744         var prs = patronRegSvc; // brevity
745         // in standalone mode, we have no patronSvc
746         $scope.patron = prs.init_patron(patronSvc ? patronSvc.current : null);
747         $scope.field_doc = prs.field_doc;
748         $scope.edit_profiles = prs.edit_profiles;
749         $scope.ident_types = prs.ident_types;
750         $scope.net_access_levels = prs.net_access_levels;
751         $scope.user_setting_types = prs.user_setting_types;
752         $scope.opt_in_setting_types = prs.opt_in_setting_types;
753         $scope.org_settings = prs.org_settings;
754         $scope.sms_carriers = prs.sms_carriers;
755         $scope.stat_cats = prs.stat_cats;
756         $scope.surveys = prs.surveys;
757         $scope.survey_responses = prs.survey_responses;
758         $scope.stat_cat_entry_maps = prs.stat_cat_entry_maps;
759
760         $scope.user_settings = prs.user_settings;
761         // clone the user settings back into the patronRegSvc so
762         // we have a copy of the original state of the settings.
763         prs.user_settings = {};
764         angular.forEach($scope.user_settings, function(val, key) {
765             prs.user_settings[key] = val;
766         });
767
768         extract_hold_notify();
769         handle_home_org_changed();
770
771         if ($scope.org_settings['ui.patron.edit.default_suggested'])
772             $scope.edit_passthru.vis_level = 1;
773
774         if ($scope.patron.isnew) 
775             set_new_patron_defaults(prs);
776
777         $scope.page_data_loaded = true;
778     });
779
780     // update the currently displayed field documentation
781     $scope.set_selected_field_doc = function(cls, field) {
782         $scope.selected_field_doc = $scope.field_doc[cls][field];
783     }
784
785     // returns the tree depth of the selected profile group tree node.
786     $scope.pgt_depth = function(grp) {
787         var d = 0;
788         while (grp = egCore.env.pgt.map[grp.parent()]) d++;
789         return d;
790     }
791
792     // IDL fields used for labels in the UI.
793     $scope.idl_fields = {
794         au  : egCore.idl.classes.au.field_map,
795         ac  : egCore.idl.classes.ac.field_map,
796         aua : egCore.idl.classes.aua.field_map
797     };
798
799     // field visibility cache.  Some fields are universally required.
800     var field_visibility = {
801         'ac.barcode' : 2,
802         'au.usrname' : 2,
803         'au.passwd' :  2,
804         // TODO passwd2 2,
805         'au.first_given_name' : 2,
806         'au.family_name' : 2,
807         'au.ident_type' : 2,
808         'au.home_ou' : 2,
809         'au.profile' : 2,
810         'au.expire_date' : 2,
811         'au.net_access_level' : 2,
812         'aua.address_type' : 2,
813         'aua.post_code' : 2,
814         'aua.street1' : 2,
815         'aua.street2' : 2,
816         'aua.city' : 2,
817         'aua.county' : 2,
818         'aua.state' : 2,
819         'aua.country' : 2,
820         'aua.valid' : 2,
821         'aua.within_city_limits' : 2,
822         'stat_cats' : 1,
823         'surveys' : 1
824     }; 
825
826     // returns true if the selected field should be visible
827     // given the current required/suggested/all setting.
828     $scope.show_field = function(field_key) {
829
830         if (field_visibility[field_key] == undefined) {
831             // compile and cache the visibility for the selected field
832
833             // org settings have not been received yet.
834             if (!$scope.org_settings) return false;
835
836             var req_set = 'ui.patron.edit.' + field_key + '.require';
837             var sho_set = 'ui.patron.edit.' + field_key + '.show';
838             var sug_set = 'ui.patron.edit.' + field_key + '.suggest';
839
840             if ($scope.org_settings[req_set]) {
841                 field_visibility[field_key] = 2;
842             } else if ($scope.org_settings[sho_set]) {
843                 field_visibility[field_key] = 2;
844             } else if ($scope.org_settings[sug_set]) {
845                 field_visibility[field_key] = 1;
846             } else {
847                 field_visibility[field_key] = 0;
848             }
849         }
850
851         return field_visibility[field_key] >= $scope.edit_passthru.vis_level;
852     }
853
854     // generates a random 4-digit password
855     $scope.generate_password = function() {
856         $scope.patron.passwd = Math.floor(Math.random()*9000) + 1000;
857     }
858
859     $scope.set_expire_date = function() {
860         if (!$scope.patron.profile) return;
861         var seconds = egCore.date.intervalToSeconds(
862             $scope.patron.profile.perm_interval());
863         var now_epoch = new Date().getTime();
864         $scope.patron.expire_date = new Date(
865             now_epoch + (seconds * 1000 /* milliseconds */))
866     }
867
868     // grp is the pgt object
869     $scope.set_profile = function(grp) {
870         $scope.patron.profile = grp;
871         $scope.set_expire_date();
872     }
873
874     $scope.new_address = function() {
875         var addr = egCore.idl.toHash(new egCore.idl.aua());
876         patronRegSvc.ingest_address($scope.patron, addr);
877         addr.id = patronRegSvc.virt_id--;
878         addr.isnew = true;
879         addr.valid = true;
880         addr.within_city_limits = true;
881         $scope.patron.addresses.push(addr);
882     }
883
884     // keep deleted addresses out of the patron object so
885     // they won't appear in the UI.  They'll be re-inserted
886     // when the patron is updated.
887     deleted_addresses = [];
888     $scope.delete_address = function(id) {
889         var addresses = [];
890         angular.forEach($scope.patron.addresses, function(addr) {
891             if (addr.id == id) {
892                 if (id > 0) {
893                     addr.isdeleted = true;
894                     deleted_addresses.push(addr);
895                 }
896             } else {
897                 addresses.push(addr);
898             }
899         });
900         $scope.patron.addresses = addresses;
901     } 
902
903     $scope.post_code_changed = function(addr) { 
904         egCore.net.request(
905             'open-ils.search', 'open-ils.search.zip', addr.post_code)
906         .then(function(resp) {
907             if (!resp) return;
908             if (resp.city) addr.city = resp.city;
909             if (resp.state) addr.state = resp.state;
910             if (resp.county) addr.county = resp.county;
911             if (resp.alert) alert(resp.alert);
912         });
913     }
914
915     $scope.replace_card = function() {
916         $scope.patron.card.active = false;
917         $scope.patron.card.ischanged = true;
918         $scope.disable_bc = false;
919
920         var new_card = egCore.idl.toHash(new egCore.idl.ac());
921         new_card.id = patronRegSvc.virt_id--;
922         new_card.isnew = true;
923         new_card.active = true;
924         new_card._primary = 'on';
925         $scope.patron.card = new_card;
926         $scope.patron.cards.push(new_card);
927     }
928
929     $scope.day_phone_changed = function(phone) {
930         if (phone && $scope.org_settings['patron.password.use_phone']) {
931            $scope.patron.passwd = phone.substr(-4);
932         }
933     }
934
935     $scope.barcode_changed = function(bc) {
936         if (!bc) return;
937         egCore.net.request(
938             'open-ils.actor',
939             'open-ils.actor.barcode.exists',
940             egCore.auth.token(), bc
941         ).then(function(resp) {
942             if (resp == '1') {
943                 console.log('duplicate barcode detected: ' + bc);
944                 // DUPLICATE CARD
945             } else {
946                 if (!$scope.patron.usrname)
947                     $scope.patron.usrname = bc;
948                 // No dupe -- A-OK
949             }
950         });
951     }
952
953     $scope.cards_dialog = function() {
954         $modal.open({
955             templateUrl: './circ/patron/t_patron_cards_dialog',
956             controller: 
957                    ['$scope','$modalInstance','cards',
958             function($scope , $modalInstance , cards) {
959                 // scope here is the modal-level scope
960                 $scope.args = {cards : cards};
961                 $scope.ok = function() { $modalInstance.close($scope.args) }
962                 $scope.cancel = function () { $modalInstance.dismiss() }
963             }],
964             resolve : {
965                 cards : function() {
966                     // scope here is the controller-level scope
967                     return $scope.patron.cards;
968                 }
969             }
970         }).result.then(
971             function(args) {
972                 angular.forEach(args.cards, function(card) {
973                     card.ischanged = true; // assume cards need updating, OK?
974                     if (card._primary == 'on' && 
975                         card.id != $scope.patron.card.id) {
976                         $scope.patron.card = card;
977                     }
978                 });
979             }
980         );
981     }
982
983     $scope.set_addr_type = function(addr, type) {
984         var addrs = $scope.patron.addresses;
985         if (addr['_is_'+type]) {
986             angular.forEach(addrs, function(a) {
987                 if (a.id != addr.id) a['_is_'+type] = false;
988             });
989         } else {
990             // unchecking mailing/billing means we have to randomly
991             // select another address to fill that role.  Select the
992             // first address in the list (that does not match the
993             // modifed address)
994             for (var i = 0; i < addrs.length; i++) {
995                 if (addrs[i].id != addr.id) {
996                     addrs[i]['_is_' + type] = true;
997                     break;
998                 }
999             }
1000         }
1001     }
1002
1003
1004     // Translate hold notify preferences from the form/scope back into a 
1005     // single user setting value for opac.hold_notify.
1006     function compress_hold_notify() {
1007         var hold_notify = '';
1008         var splitter = '';
1009         if ($scope.hold_notify_phone) {
1010             hold_notify = 'phone';
1011             splitter = ':';
1012         }
1013         if ($scope.hold_notify_email) {
1014             hold_notify = splitter + 'email';
1015             splitter = ':';
1016         }
1017         if ($scope.hold_notify_sms) {
1018             hold_notify = splitter + 'sms';
1019             splitter = ':';
1020         }
1021         $scope.user_settings['opac.hold_notify'] = hold_notify;
1022     }
1023
1024     // dialog for selecting additional permission groups
1025     $scope.secondary_groups_dialog = function() {
1026         $modal.open({
1027             templateUrl: './circ/patron/t_patron_groups_dialog',
1028             controller: 
1029                    ['$scope','$modalInstance','linked_groups','pgt_depth',
1030             function($scope , $modalInstance , linked_groups , pgt_depth) {
1031
1032                 $scope.pgt_depth = pgt_depth;
1033                 $scope.args = {
1034                     linked_groups : linked_groups,
1035                     edit_profiles : patronRegSvc.edit_profiles,
1036                     new_profile   : patronRegSvc.edit_profiles[0]
1037                 };
1038
1039                 // add a new group to the linked groups list
1040                 $scope.link_group = function($event, grp) {
1041                     var found = false; // avoid duplicates
1042                     angular.forEach($scope.args.linked_groups, 
1043                         function(g) {if (g.id() == grp.id()) found = true});
1044                     if (!found) $scope.args.linked_groups.push(grp);
1045                     $event.preventDefault(); // avoid close
1046                 }
1047
1048                 // remove a group from the linked groups list
1049                 $scope.unlink_group = function($event, grp) {
1050                     $scope.args.linked_groups = 
1051                         $scope.args.linked_groups.filter(function(g) {
1052                         return g.id() != grp.id()
1053                     });
1054                     $event.preventDefault(); // avoid close
1055                 }
1056
1057                 $scope.ok = function() { $modalInstance.close($scope.args) }
1058                 $scope.cancel = function () { $modalInstance.dismiss() }
1059             }],
1060             resolve : {
1061                 linked_groups : function() { return $scope.patron.groups },
1062                 pgt_depth : function() { return $scope.pgt_depth }
1063             }
1064         }).result.then(
1065             function(args) {
1066                 var ids = args.linked_groups.map(function(g) {return g.id()});
1067                 console.log('linking permission groups ' + ids);
1068                 return egCore.net.request(
1069                     'open-ils.actor',
1070                     'open-ils.actor.user.set_groups',
1071                     egCore.auth.token(), $scope.patron.id, ids)
1072                 .then(function(resp) {
1073                     if (resp == 1) {
1074                         $scope.patron.groups = args.linked_groups;
1075                     } else {
1076                         // debugging -- should be no events
1077                         alert('linked groups failure ' + egCore.evt.parse(resp));
1078                     }
1079                 });
1080             }
1081         );
1082     }
1083
1084     function extract_hold_notify() {
1085         notify = $scope.user_settings['opac.hold_notify'];
1086         if (!notify) return;
1087         $scope.hold_notify_phone = Boolean(notify.match(/phone/));
1088         $scope.hold_notify_email = Boolean(notify.match(/email/));
1089         $scope.hold_notify_sms = Boolean(notify.match(/sms/));
1090     }
1091
1092     $scope.invalidate_field = function(field) {
1093         patronRegSvc.invalidate_field($scope.patron, field);
1094     }
1095
1096     $scope.dupe_value_changed = function(type, value) {
1097         patronRegSvc.dupe_patron_search($scope.patron, type, value);
1098     }
1099
1100     $scope.edit_passthru.save = function() {
1101
1102         // toss the deleted addresses back into the patron's list of
1103         // addresses so it's included in the update
1104         $scope.patron.addresses = 
1105             $scope.patron.addresses.concat(deleted_addresses);
1106         
1107         compress_hold_notify();
1108
1109         patronRegSvc.save_user($scope.patron)
1110         .then(function(new_user) { 
1111             if (new_user && new_user.classname) {
1112                 return patronRegSvc.save_user_settings(
1113                     new_user, $scope.user_settings); 
1114             } else {
1115                 alert('Patron update failed. \n\n' + js2JSON(new_user));
1116                 return true; // ensure page reloads to reset
1117             }
1118         }).then(function(keep_going) {
1119             // reloading the page means potentially losing some information
1120             // (e.g. last patron search), but is the only way to ensure all
1121             // components are properly updated to reflect the modified patron.
1122             $window.location.href = location.href;
1123         });
1124     }
1125 }
1126
1127 // This controller may be loaded from different modules (patron edit vs.
1128 // register new patron), so we have to inject the controller params manually.
1129 PatronRegCtrl.$inject = ['$scope', '$routeParams', '$q', '$modal', 
1130     '$window', 'egCore', 'patronSvc', 'patronRegSvc'];
1131