]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/circ/patron/regctl.js
LP#1564685 Required-field org settings overlay defaults
[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         surveys : [],
16         survey_questions : {},
17         survey_answers : {},
18         survey_responses : {},     // survey.responses for loaded patron in progress
19         stat_cats : [],
20         stat_cat_entry_maps : {},   // cat.id to selected value
21         virt_id : -1,               // virtual ID for new objects
22         init_done : false           // have we loaded our initialization data?
23     };
24
25     // launch a series of parallel data retrieval calls
26     service.init = function(scope) {
27
28         // Data loaded here only needs to be retrieved the first time this
29         // tab becomes active within the current instance of the patron app.
30         // In other words, navigating between patron tabs will not cause
31         // all of this data to be reloaded.  Navigating to a separate app
32         // and returning will cause the data to be reloaded.
33         if (service.init_done) return $q.when();
34         service.init_done = true;
35
36         return $q.all([
37             service.get_field_doc(),
38             service.get_perm_groups(),
39             service.get_ident_types(),
40             service.get_user_settings(),
41             service.get_org_settings(),
42             service.get_stat_cats(),
43             service.get_surveys(),
44             service.get_clone_user(),
45             service.get_stage_user(),
46             service.get_net_access_levels()
47         ]);
48     };
49
50     service.get_clone_user = function() {
51         if (!service.clone_id) return $q.when();
52         // we could load egUser and use its get() function, but loading
53         // user.js into the standalone register UI would mean creating a
54         // new module, since egUser is not loaded into egCoreMod.  This
55         // is a lot simpler.
56         return egCore.net.request(
57             'open-ils.actor',
58             'open-ils.actor.user.fleshed.retrieve',
59             egCore.auth.token(), service.clone_id, 
60             ['billing_address', 'mailing_address'])
61         .then(function(cuser) {
62             if (e = egCore.evt.parse(cuser)) {
63                 alert(e);
64             } else {
65                 service.clone_user = cuser;
66             }
67         });
68     }
69
70     service.apply_secondary_groups = function(user_id, group_ids) {
71         return egCore.net.request(
72             'open-ils.actor',
73             'open-ils.actor.user.set_groups',
74             egCore.auth.token(), user_id, group_ids)
75         .then(function(resp) {
76             if (resp == 1) {
77                 return true;
78             } else {
79                 // debugging -- should be no events
80                 alert('linked groups failure ' + egCore.evt.parse(resp));
81             }
82         });
83     }
84
85     service.get_stage_user = function() {
86         if (!service.stage_username) return $q.when();
87
88         // fetch the staged user object
89         return egCore.net.request(
90             'open-ils.actor',
91             'open-ils.actor.user.stage.retrieve.by_username',
92             egCore.auth.token(), 
93             service.stage_username
94         ).then(function(suser) {
95             if (e = egCore.evt.parse(suser)) {
96                 alert(e);
97             } else {
98                 service.stage_user = suser;
99             }
100         }).then(function() {
101
102             if (!service.stage_user) return;
103             var requestor = service.stage_user.user.requesting_usr();
104
105             if (!requestor) return;
106
107             // fetch the requesting user
108             return egCore.net.request(
109                 'open-ils.actor', 
110                 'open-ils.actor.user.retrieve.parts',
111                 egCore.auth.token(),
112                 requestor, 
113                 ['family_name', 'first_given_name', 'second_given_name'] 
114             ).then(function(parts) {
115                 service.stage_user_requestor = 
116                     service.format_name(parts[0], parts[1], parts[2]);
117             })
118         });
119     }
120
121     // See note above about not loading egUser.
122     // TODO: i18n
123     service.format_name = function(last, first, middle) {
124         return last + ', ' + first + (middle ? ' ' + middle : '');
125     }
126
127     service.check_dupe_username = function(usrname) {
128
129         // empty usernames can't be dupes
130         if (!usrname) return $q.when(false);
131
132         // avoid dupe check if username matches the originally loaded usrname
133         if (service.existing_patron) {
134             if (usrname == service.existing_patron.usrname())
135                 return $q.when(false);
136         }
137
138         return egCore.net.request(
139             'open-ils.actor',
140             'open-ils.actor.username.exists',
141             egCore.auth.token(), usrname);
142     }
143
144     //service.check_grp_app_perm = function(grp_id) {
145
146     // determine which user groups our user is not allowed to modify
147     service.set_edit_profiles = function() {
148         var all_app_perms = [];
149         var failed_perms = [];
150
151         // extract the application permissions
152         angular.forEach(service.profiles, function(grp) {
153             if (grp.application_perm())
154                 all_app_perms.push(grp.application_perm());
155         }); 
156
157         // fill in service.edit_profiles by inspecting failed_perms
158         function traverse_grp_tree(grp, failed) {
159             failed = failed || 
160                 failed_perms.indexOf(grp.application_perm()) > -1;
161
162             if (!failed) service.edit_profiles.push(grp);
163
164             angular.forEach(
165                 service.profiles.filter( // children of grp
166                     function(p) { return p.parent() == grp.id() }),
167                 function(child) {traverse_grp_tree(child, failed)}
168             );
169         }
170
171         return egCore.perm.hasPermAt(all_app_perms, true).then(
172             function(perm_orgs) {
173                 angular.forEach(all_app_perms, function(p) {
174                     if (perm_orgs[p].length == 0)
175                         failed_perms.push(p);
176                 });
177
178                 traverse_grp_tree(egCore.env.pgt.tree);
179             }
180         );
181     }
182
183     // resolves to a hash of perm-name => boolean value indicating
184     // wether the user has the permission at org_id.
185     service.has_perms_for_org = function(org_id) {
186
187         var perms_needed = [
188             'UPDATE_USER',
189             'CREATE_USER',
190             'CREATE_USER_GROUP_LINK', 
191             'UPDATE_PATRON_COLLECTIONS_EXEMPT',
192             'UPDATE_PATRON_CLAIM_RETURN_COUNT',
193             'UPDATE_PATRON_CLAIM_NEVER_CHECKED_OUT_COUNT',
194             'UPDATE_PATRON_ACTIVE_CARD',
195             'UPDATE_PATRON_PRIMARY_CARD'
196         ];
197
198         return egCore.perm.hasPermAt(perms_needed, true)
199         .then(function(perm_map) {
200
201             angular.forEach(perms_needed, function(perm) {
202                 perm_map[perm] = 
203                     Boolean(perm_map[perm].indexOf(org_id) > -1);
204             });
205
206             return perm_map;
207         });
208     }
209
210     service.get_surveys = function() {
211         var org_ids = egCore.org.fullPath(egCore.auth.user().ws_ou(), true);
212
213         return egCore.pcrud.search('asv', {
214                 owner : org_ids,
215                 start_date : {'<=' : 'now'},
216                 end_date : {'>=' : 'now'}
217             }, {   
218                 flesh : 2, 
219                 flesh_fields : {
220                     asv : ['questions'], 
221                     asvq : ['answers']
222                 }
223             }, 
224             {atomic : true}
225         ).then(function(surveys) {
226             surveys = surveys.sort(function(a,b) {
227                 return a.name() < b.name() ? -1 : 1 });
228             service.surveys = surveys;
229             angular.forEach(surveys, function(survey) {
230                 angular.forEach(survey.questions(), function(question) {
231                     service.survey_questions[question.id()] = question;
232                     angular.forEach(question.answers(), function(answer) {
233                         service.survey_answers[answer.id()] = answer;
234                     });
235                 });
236             });
237         });
238     }
239
240     service.get_stat_cats = function() {
241         return egCore.net.request(
242             'open-ils.circ',
243             'open-ils.circ.stat_cat.actor.retrieve.all',
244             egCore.auth.token(), egCore.auth.user().ws_ou()
245         ).then(function(cats) {
246             cats = cats.sort(function(a, b) {
247                 return a.name() < b.name() ? -1 : 1});
248             angular.forEach(cats, function(cat) {
249                 cat.entries(
250                     cat.entries().sort(function(a,b) {
251                         return a.value() < b.value() ? -1 : 1
252                     })
253                 );
254             });
255             service.stat_cats = cats;
256         });
257     };
258
259     service.get_org_settings = function() {
260         return egCore.org.settings([
261             'global.password_regex',
262             'global.juvenile_age_threshold',
263             'patron.password.use_phone',
264             'ui.patron.default_inet_access_level',
265             'ui.patron.default_ident_type',
266             'ui.patron.default_country',
267             'ui.patron.registration.require_address',
268             'circ.holds.behind_desk_pickup_supported',
269             'circ.patron_edit.clone.copy_address',
270             'ui.patron.edit.au.prefix.require',
271             'ui.patron.edit.au.prefix.show',
272             'ui.patron.edit.au.prefix.suggest',
273             'ui.patron.edit.ac.barcode.regex',
274             'ui.patron.edit.au.second_given_name.show',
275             'ui.patron.edit.au.second_given_name.suggest',
276             'ui.patron.edit.au.suffix.show',
277             'ui.patron.edit.au.suffix.suggest',
278             'ui.patron.edit.au.alias.show',
279             'ui.patron.edit.au.alias.suggest',
280             'ui.patron.edit.au.dob.require',
281             'ui.patron.edit.au.dob.show',
282             'ui.patron.edit.au.dob.suggest',
283             'ui.patron.edit.au.dob.calendar',
284             'ui.patron.edit.au.juvenile.show',
285             'ui.patron.edit.au.juvenile.suggest',
286             'ui.patron.edit.au.ident_value.show',
287             'ui.patron.edit.au.ident_value.suggest',
288             'ui.patron.edit.au.ident_value2.show',
289             'ui.patron.edit.au.ident_value2.suggest',
290             'ui.patron.edit.au.email.require',
291             'ui.patron.edit.au.email.show',
292             'ui.patron.edit.au.email.suggest',
293             'ui.patron.edit.au.email.regex',
294             'ui.patron.edit.au.email.example',
295             'ui.patron.edit.au.day_phone.require',
296             'ui.patron.edit.au.day_phone.show',
297             'ui.patron.edit.au.day_phone.suggest',
298             'ui.patron.edit.au.day_phone.regex',
299             'ui.patron.edit.au.day_phone.example',
300             'ui.patron.edit.au.evening_phone.require',
301             'ui.patron.edit.au.evening_phone.show',
302             'ui.patron.edit.au.evening_phone.suggest',
303             'ui.patron.edit.au.evening_phone.regex',
304             'ui.patron.edit.au.evening_phone.example',
305             'ui.patron.edit.au.other_phone.require',
306             'ui.patron.edit.au.other_phone.show',
307             'ui.patron.edit.au.other_phone.suggest',
308             'ui.patron.edit.au.other_phone.regex',
309             'ui.patron.edit.au.other_phone.example',
310             'ui.patron.edit.phone.regex',
311             'ui.patron.edit.phone.example',
312             'ui.patron.edit.au.active.show',
313             'ui.patron.edit.au.active.suggest',
314             'ui.patron.edit.au.barred.show',
315             'ui.patron.edit.au.barred.suggest',
316             'ui.patron.edit.au.master_account.show',
317             'ui.patron.edit.au.master_account.suggest',
318             'ui.patron.edit.au.claims_returned_count.show',
319             'ui.patron.edit.au.claims_returned_count.suggest',
320             'ui.patron.edit.au.claims_never_checked_out_count.show',
321             'ui.patron.edit.au.claims_never_checked_out_count.suggest',
322             'ui.patron.edit.au.alert_message.show',
323             'ui.patron.edit.au.alert_message.suggest',
324             'ui.patron.edit.aua.post_code.regex',
325             'ui.patron.edit.aua.post_code.example',
326             'ui.patron.edit.aua.county.require',
327             'format.date',
328             'ui.patron.edit.default_suggested',
329             'opac.barcode_regex',
330             'opac.username_regex',
331             'sms.enable',
332             'ui.patron.edit.aua.state.require',
333             'ui.patron.edit.aua.state.suggest',
334             'ui.patron.edit.aua.state.show'
335         ]).then(function(settings) {
336             service.org_settings = settings;
337             return service.process_org_settings(settings);
338         });
339     };
340
341     // some org settings require the retrieval of additional data
342     service.process_org_settings = function(settings) {
343
344         var promises = [];
345
346         if (settings['sms.enable']) {
347             // fetch SMS carriers
348             promises.push(
349                 egCore.pcrud.search('csc', 
350                     {active: 'true'}, 
351                     {'order_by':[
352                         {'class':'csc', 'field':'name'},
353                         {'class':'csc', 'field':'region'}
354                     ]}, {atomic : true}
355                 ).then(function(carriers) {
356                     service.sms_carriers = carriers;
357                 })
358             );
359         } else {
360             // if other promises are added below, this is not necessary.
361             promises.push($q.when());  
362         }
363
364         // other post-org-settings processing goes here,
365         // adding to promises as needed.
366
367         return $q.all(promises);
368     };
369
370     service.get_ident_types = function() {
371         if (egCore.env.cit) {
372             service.ident_types = egCore.env.cit.list;
373             return $q.when();
374         } else {
375             return egCore.pcrud.retrieveAll('cit', {}, {atomic : true})
376             .then(function(types) { 
377                 egCore.env.absorbList(types, 'cit')
378                 service.ident_types = types 
379             });
380         }
381     };
382
383     service.get_net_access_levels = function() {
384         if (egCore.env.cnal) {
385             service.net_access_levels = egCore.env.cnal.list;
386             return $q.when();
387         } else {
388             return egCore.pcrud.retrieveAll('cnal', {}, {atomic : true})
389             .then(function(levels) { 
390                 egCore.env.absorbList(levels, 'cnal')
391                 service.net_access_levels = levels 
392             });
393         }
394     }
395
396     service.get_perm_groups = function() {
397         if (egCore.env.pgt) {
398             service.profiles = egCore.env.pgt.list;
399             return service.set_edit_profiles();
400         } else {
401             return egCore.pcrud.search('pgt', {parent : null}, 
402                 {flesh : -1, flesh_fields : {pgt : ['children']}}
403             ).then(
404                 function(tree) {
405                     egCore.env.absorbTree(tree, 'pgt')
406                     service.profiles = egCore.env.pgt.list;
407                     return service.set_edit_profiles();
408                 }
409             );
410         }
411     }
412
413     service.get_field_doc = function() {
414         return egCore.pcrud.search('fdoc', {
415             fm_class: ['au', 'ac', 'aua', 'actsc', 'asv', 'asvq', 'asva']})
416         .then(null, null, function(doc) {
417             if (!service.field_doc[doc.fm_class()]) {
418                 service.field_doc[doc.fm_class()] = {};
419             }
420             service.field_doc[doc.fm_class()][doc.field()] = doc;
421         });
422     };
423
424     service.get_user_settings = function() {
425         var org_ids = egCore.org.ancestors(egCore.auth.user().ws_ou(), true);
426
427         var static_types = [
428             'circ.holds_behind_desk', 
429             'circ.collections.exempt', 
430             'opac.hold_notify', 
431             'opac.default_phone', 
432             'opac.default_pickup_location', 
433             'opac.default_sms_carrier', 
434             'opac.default_sms_notify'];
435
436         return egCore.pcrud.search('cust', {
437             '-or' : [
438                 {name : static_types}, // common user settings
439                 {name : { // opt-in notification user settings
440                     'in': {
441                         select : {atevdef : ['opt_in_setting']}, 
442                         from : 'atevdef',
443                         // we only care about opt-in settings for 
444                         // event_defs our users encounter
445                         where : {'+atevdef' : {owner : org_ids}}
446                     }
447                 }}
448             ]
449         }, {}, {atomic : true}).then(function(setting_types) {
450
451             angular.forEach(setting_types, function(stype) {
452                 service.user_setting_types[stype.name()] = stype;
453                 if (static_types.indexOf(stype.name()) == -1) {
454                     service.opt_in_setting_types[stype.name()] = stype;
455                 }
456             });
457
458             if (service.patron_id) {
459                 // retrieve applied values for the current user 
460                 // for the setting types we care about.
461
462                 var setting_names = 
463                     setting_types.map(function(obj) { return obj.name() });
464
465                 return egCore.net.request(
466                     'open-ils.actor', 
467                     'open-ils.actor.patron.settings.retrieve.authoritative',
468                     egCore.auth.token(),
469                     service.patron_id,
470                     setting_names
471                 ).then(function(settings) {
472                     service.user_settings = settings;
473                 });
474             } else {
475
476                 // apply default user setting values
477                 angular.forEach(setting_types, function(stype, index) {
478                     if (stype.reg_default() != undefined) {
479                         service.user_settings[setting.name()] = 
480                             setting.reg_default();
481                     }
482                 });
483             }
484         });
485     }
486
487     service.invalidate_field = function(patron, field) {
488         console.log('Invalidating patron field ' + field);
489
490         return egCore.net.request(
491             'open-ils.actor',
492             'open-ils.actor.invalidate.' + field,
493             egCore.auth.token(), patron.id, null, patron.home_ou.id()
494
495         ).then(function(res) {
496             // clear the invalid value from the form
497             patron[field] = '';
498
499             // update last_xact_id so future save operations
500             // on this patron will be allowed
501             patron.last_xact_id = res.payload.last_xact_id[patron.id];
502         });
503     }
504
505     service.dupe_patron_search = function(patron, type, value) {
506         var search;
507
508         console.log('Dupe search called with "'+ type +'" and value '+ value);
509
510         switch (type) {
511
512             case 'name':
513                 var fname = patron.first_given_name;   
514                 var lname = patron.family_name;   
515                 if (!(fname && lname)) return $q.when({count:0});
516                 search = {
517                     first_given_name : {value : fname, group : 0},
518                     family_name : {value : lname, group : 0}
519                 };
520                 break;
521
522             case 'email':
523                 search = {email : {value : value, group : 0}};
524                 break;
525
526             case 'ident':
527                 search = {ident : {value : value, group : 2}};
528                 break;
529
530             case 'phone':
531                 search = {phone : {value : value, group : 2}};
532                 break;
533
534             case 'address':
535                 search = {};
536                 angular.forEach(['street1', 'street2', 'city', 'post_code'],
537                     function(field) {
538                         if(value[field])
539                             search[field] = {value : value[field], group: 1};
540                     }
541                 );
542                 break;
543         }
544
545         return egCore.net.request( 
546             'open-ils.actor', 
547             'open-ils.actor.patron.search.advanced',
548             egCore.auth.token(), search, null, null, 1
549         ).then(function(res) {
550             res = res.filter(function(id) {return id != patron.id});
551             return {
552                 count : res.length,
553                 search : search
554             };
555         });
556     }
557
558     service.init_patron = function(current) {
559
560         if (!current)
561             return service.init_new_patron();
562
563         service.patron = current;
564         return service.init_existing_patron(current)
565     }
566
567     service.ingest_address = function(patron, addr) {
568         addr.valid = addr.valid == 't';
569         addr.within_city_limits = addr.within_city_limits == 't';
570         addr._is_mailing = (patron.mailing_address && 
571             addr.id == patron.mailing_address.id);
572         addr._is_billing = (patron.billing_address && 
573             addr.id == patron.billing_address.id);
574     }
575
576     /*
577      * Existing patron objects reqire some data munging before insertion
578      * into the scope.
579      *
580      * 1. Turn everything into a hash
581      * 2. ... Except certain fields (selectors) whose widgets require objects
582      * 3. Bools must be Boolean, not t/f.
583      */
584     service.init_existing_patron = function(current) {
585
586         service.existing_patron = current;
587
588         var patron = egCore.idl.toHash(current);
589
590         patron.home_ou = egCore.org.get(patron.home_ou.id);
591         patron.expire_date = new Date(Date.parse(patron.expire_date));
592         patron.dob = service.parse_dob(patron.dob);
593         patron.profile = current.profile(); // pre-hash version
594         patron.net_access_level = current.net_access_level();
595         patron.ident_type = current.ident_type();
596         patron.groups = current.groups(); // pre-hash
597
598         angular.forEach(
599             ['juvenile', 'barred', 'active', 'master_account'],
600             function(field) { patron[field] = patron[field] == 't'; }
601         );
602
603         angular.forEach(patron.cards, function(card) {
604             card.active = card.active == 't';
605             if (card.id == patron.card.id) {
606                 patron.card = card;
607                 card._primary = 'on';
608             }
609         });
610
611         angular.forEach(patron.addresses, 
612             function(addr) { service.ingest_address(patron, addr) });
613
614         // toss entries for existing stat cat maps into our living 
615         // stat cat entry map, which is modified within the template.
616         angular.forEach(patron.stat_cat_entries, function(map) {
617             service.stat_cat_entry_maps[map.stat_cat.id] = map.stat_cat_entry;
618         });
619
620         return patron;
621     }
622
623     service.init_new_patron = function() {
624         var addr = {
625             id : service.virt_id--,
626             isnew : true,
627             valid : true,
628             address_type : egCore.strings.REG_ADDR_TYPE,
629             _is_mailing : true,
630             _is_billing : true,
631             within_city_limits : false,
632             country : service.org_settings['ui.patron.default_country'],
633         };
634
635         var card = {
636             id : service.virt_id--,
637             isnew : true,
638             active : true,
639             _primary : 'on'
640         };
641
642         var user = {
643             isnew : true,
644             active : true,
645             card : card,
646             cards : [card],
647             home_ou : egCore.org.get(egCore.auth.user().ws_ou()),
648             stat_cat_entries : [],
649             groups : [],
650             addresses : [addr]
651         };
652
653         if (service.clone_user)
654             service.copy_clone_data(user);
655
656         if (service.stage_user)
657             service.copy_stage_data(user);
658
659         return user;
660     }
661
662     // dob is always YYYY-MM-DD
663     // Dates of birth do not contain timezone info, which can lead to
664     // inconcistent timezone handling, potentially representing
665     // different points in time, depending on the implementation.
666     // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
667     // See "Differences in assumed time zone"
668     // TODO: move this into egDate ?
669     service.parse_dob = function(dob) {
670         if (!dob) return null;
671         var parts = dob.split('-');
672         var d = new Date(); // always local time zone, yay.
673         d.setFullYear(parts[0]);
674         d.setMonth(parts[1]);
675         d.setDate(parts[2]);
676         return d;
677     }
678
679     service.copy_stage_data = function(user) {
680         var cuser = service.stage_user;
681
682         // copy the data into our new user object
683
684         for (var key in egCore.idl.classes.stgu.field_map) {
685             if (egCore.idl.classes.au.field_map[key] &&
686                 !egCore.idl.classes.stgu.field_map[key].virtual) {
687                 if (cuser.user[key]() !== null)
688                     user[key] = cuser.user[key]();
689             }
690         }
691
692         if (user.home_ou) user.home_ou = egCore.org.get(user.home_ou);
693         if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
694         if (user.ident_type) 
695             user.ident_type = egCore.env.cit.map[user.ident_type];
696         user.dob = service.parse_dob(user.dob);
697
698         // Clear the usrname if it looks like a UUID
699         if (user.usrname.replace(/-/g,'').match(/[0-9a-f]{32}/)) 
700             user.usrname = '';
701
702         // Don't use stub address if we have one from the staged user.
703         if (cuser.mailing_addresses.length || cuser.billing_addresses.length)
704             user.addresses = [];
705
706         // is_mailing=false implies is_billing
707         function addr_from_stage(stage_addr) {
708             if (!stage_addr) return;
709             var cls = stage_addr.classname;
710
711             var addr = {
712                 id : service.virt_id--,
713                 usr : user.id,
714                 isnew : true,
715                 valid : true,
716                 _is_mailing : cls == 'stgma',
717                 _is_billing : cls == 'stgba'
718             };
719
720             user.mailing_address = addr;
721             user.addresses.push(addr);
722
723             for (var key in egCore.idl.classes[cls].field_map) {
724                 if (egCore.idl.classes.aua.field_map[key] &&
725                     !egCore.idl.classes[cls].field_map[key].virtual) {
726                     if (stage_addr[key]() !== null)
727                         addr[key] = stage_addr[key]();
728                 }
729             }
730         }
731
732         addr_from_stage(cuser.mailing_addresses[0]);
733         addr_from_stage(cuser.billing_addresses[0]);
734
735         if (user.addresses.length == 1) {
736             // If there is only one address, 
737             // use it as both mailing and billing.
738             var addr = user.addresses[0];
739             addr._is_mailing = addr._is_billing = true;
740             user.mailing_address = user.billing_address = addr;
741         }
742
743         if (cuser.cards.length) {
744             user.card = {
745                 id : service.virt_id--,
746                 barcode : cuser.cards[0].barcode(),
747                 isnew : true,
748                 active : true,
749                 _primary : 'on'
750             };
751
752             user.cards.push(user.card);
753             if (user.usrname == '') 
754                 user.usrname = card.barcode;
755         }
756     }
757
758     // copy select values from the cloned user to the new user.
759     // user is a hash
760     service.copy_clone_data = function(user) {
761         var clone_user = service.clone_user;
762
763         // flesh the home org locally
764         user.home_ou = egCore.org.get(clone_user.home_ou());
765         if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
766
767         if (!clone_user.billing_address() &&
768             !clone_user.mailing_address())
769             return; // no addresses to copy or link
770
771         // if the cloned user has any addresses, we don't need 
772         // the stub address created in init_new_patron.
773         user.addresses = [];
774
775         var copy_addresses = 
776             service.org_settings['circ.patron_edit.clone.copy_address'];
777
778         var clone_fields = [
779             'day_phone',
780             'evening_phone',
781             'other_phone',
782             'usrgroup'
783         ]; 
784
785         angular.forEach(clone_fields, function(field) {
786             user[field] = clone_user[field]();
787         });
788
789         if (copy_addresses) {
790             var bill_addr, mail_addr;
791
792             // copy the billing and mailing addresses into new addresses
793             function clone_addr(addr) {
794                 var new_addr = egCore.idl.toHash(addr);
795                 new_addr.id = service.virt_id--;
796                 new_addr.usr = user.id;
797                 new_addr.isnew = true;
798                 new_addr.valid = true;
799                 user.addresses.push(new_addr);
800                 return new_addr;
801             }
802
803             if (bill_addr = clone_user.billing_address()) {
804                 var addr = clone_addr(bill_addr);
805                 addr._is_billing = true;
806                 user.billing_address = addr;
807             }
808
809             if (mail_addr = clone_user.mailing_address()) {
810
811                 if (bill_addr && bill_addr.id() == mail_addr.id()) {
812                     user.mailing_address = user.billing_address;
813                     user.mailing_address._is_mailing = true;
814                 } else {
815                     var addr = clone_addr(mail_addr);
816                     addr._is_mailing = true;
817                     user.mailing_address = addr;
818                 }
819
820                 if (!bill_addr) {
821                     // if there is no billing addr, use the mailing addr
822                     user.billing_address = user.mailing_address;
823                     user.billing_address._is_billing = true;
824                 }
825             }
826
827
828         } else {
829
830             // link the billing and mailing addresses
831             var addr;
832             if (addr = clone_user.billing_address()) {
833                 user.billing_address = egCore.idl.toHash(addr);
834                 user.billing_address._is_billing = true;
835                 user.addresses.push(user.billing_address);
836                 user.billing_address._linked_owner_id = clone_user.id();
837                 user.billing_address._linked_owner = service.format_name(
838                     clone_user.family_name(),
839                     clone_user.first_given_name(),
840                     clone_user.second_given_name()
841                 );
842             }
843
844             if (addr = clone_user.mailing_address()) {
845                 if (user.billing_address && 
846                     addr.id() == user.billing_address.id) {
847                     // mailing matches billing
848                     user.mailing_address = user.billing_address;
849                     user.mailing_address._is_mailing = true;
850                 } else {
851                     user.mailing_address = egCore.idl.toHash(addr);
852                     user.mailing_address._is_mailing = true;
853                     user.addresses.push(user.mailing_address);
854                     user.mailing_address._linked_owner_id = clone_user.id();
855                     user.mailing_address._linked_owner = service.format_name(
856                         clone_user.family_name(),
857                         clone_user.first_given_name(),
858                         clone_user.second_given_name()
859                     );
860                 }
861             }
862         }
863     }
864
865     // translate the patron back into IDL form
866     service.save_user = function(phash) {
867
868         var patron = egCore.idl.fromHash('au', phash);
869
870         patron.home_ou(patron.home_ou().id());
871         patron.expire_date(patron.expire_date().toISOString());
872         patron.profile(patron.profile().id());
873         if (patron.dob()) 
874             patron.dob(patron.dob().toISOString().replace(/T.*/,''));
875         if (patron.ident_type()) 
876             patron.ident_type(patron.ident_type().id());
877         if (patron.net_access_level())
878             patron.net_access_level(patron.net_access_level().id());
879
880         angular.forEach(
881             ['juvenile', 'barred', 'active', 'master_account'],
882             function(field) { patron[field](phash[field] ? 't' : 'f'); }
883         );
884
885         var card_hashes = patron.cards();
886         patron.cards([]);
887         angular.forEach(card_hashes, function(chash) {
888             var card = egCore.idl.fromHash('ac', chash)
889             card.usr(patron.id());
890             card.active(chash.active ? 't' : 'f');
891             patron.cards().push(card);
892             if (chash._primary) {
893                 patron.card(card);
894             }
895         });
896
897         var addr_hashes = patron.addresses();
898         patron.addresses([]);
899         angular.forEach(addr_hashes, function(addr_hash) {
900             if (!addr_hash.isnew && !addr_hash.isdeleted) 
901                 addr_hash.ischanged = true;
902             var addr = egCore.idl.fromHash('aua', addr_hash);
903             patron.addresses().push(addr);
904             addr.valid(addr.valid() ? 't' : 'f');
905             addr.within_city_limits(addr.within_city_limits() ? 't' : 'f');
906             if (addr_hash._is_mailing) patron.mailing_address(addr);
907             if (addr_hash._is_billing) patron.billing_address(addr);
908         });
909
910         patron.survey_responses([]);
911         angular.forEach(service.survey_responses, function(answer) {
912             var question = service.survey_questions[answer.question()];
913             var resp = new egCore.idl.asvr();
914             resp.isnew(true);
915             resp.survey(question.survey());
916             resp.question(question.id());
917             resp.answer(answer.id());
918             resp.usr(patron.id());
919             resp.answer_date('now');
920             patron.survey_responses().push(resp);
921         });
922         
923         // re-object-ify the patron stat cat entry maps
924         var maps = [];
925         angular.forEach(patron.stat_cat_entries(), function(entry) {
926             var e = egCore.idl.fromHash('actscecm', entry);
927             e.stat_cat(e.stat_cat().id);
928             maps.push(e);
929         });
930         patron.stat_cat_entries(maps);
931
932         // service.stat_cat_entry_maps maps stats to values
933         // patron.stat_cat_entries is an array of stat_cat_entry_usr_map's
934         angular.forEach(
935             service.stat_cat_entry_maps, function(value, cat_id) {
936
937             // see if we already have a mapping for this entry
938             var existing = patron.stat_cat_entries().filter(
939                 function(e) { return e.stat_cat() == cat_id })[0];
940
941             if (existing) { // we have a mapping
942                 // if the existing mapping matches the new one,
943                 // there' nothing left to do
944                 if (existing.stat_cat_entry() == value) return;
945
946                 // mappings differ.  delete the old one and create
947                 // a new one below.
948                 existing.isdeleted(true);
949             }
950
951             var newmap = new egCore.idl.actscecm();
952             newmap.target_usr(patron.id());
953             newmap.isnew(true);
954             newmap.stat_cat(cat_id);
955             newmap.stat_cat_entry(value);
956             patron.stat_cat_entries().push(newmap);
957         });
958
959         if (!patron.isnew()) patron.ischanged(true);
960
961         return egCore.net.request(
962             'open-ils.actor', 
963             'open-ils.actor.patron.update',
964             egCore.auth.token(), patron);
965     }
966
967     service.remove_staged_user = function() {
968         if (!service.stage_user) return $q.when();
969         return egCore.net.request(
970             'open-ils.actor',
971             'open-ils.actor.user.stage.delete',
972             egCore.auth.token(),
973             service.stage_user.row_id()
974         );
975     }
976
977     service.save_user_settings = function(new_user, user_settings) {
978         // user_settings contains the values from the scope/form.
979         // service.user_settings contain the values from page load time.
980
981         var settings = {};
982         if (service.patron_id) {
983             // only update modified settings for existing patrons
984             angular.forEach(user_settings, function(val, key) {
985                 if (val !== service.user_settings[key])
986                     settings[key] = val;
987             });
988
989         } else {
990             // all non-null setting values are updated for new patrons
991             angular.forEach(user_settings, function(val, key) {
992                 if (val !== null) settings[key] = val;
993             });
994         }
995
996         if (Object.keys(settings).length == 0) return $q.when();
997
998         return egCore.net.request(
999             'open-ils.actor',
1000             'open-ils.actor.patron.settings.update',
1001             egCore.auth.token(), new_user.id(), settings
1002         ).then(function(resp) {
1003             return resp;
1004         });
1005     }
1006
1007     // Applies field-specific validation regex's from org settings 
1008     // to form fields.  Be careful not remove any pattern data we
1009     // are not explicitly over-writing in the provided patterns obj.
1010     service.set_field_patterns = function(patterns) {
1011         if (service.org_settings['opac.username_regex']) {
1012             patterns.au.usrname = 
1013                 new RegExp(service.org_settings['opac.username_regex']);
1014         }
1015
1016         if (service.org_settings['opac.barcode_regex']) {
1017             patterns.ac.barcode = 
1018                 new RegExp(service.org_settings['opac.barcode_regex']);
1019         }
1020
1021         if (service.org_settings['global.password_regex']) {
1022             patterns.au.passwd = 
1023                 new RegExp(service.org_settings['global.password_regex']);
1024         }
1025
1026         var phone_reg = service.org_settings['ui.patron.edit.phone.regex'];
1027         if (phone_reg) {
1028             // apply generic phone regex first, replace below as needed.
1029             patterns.au.day_phone = new RegExp(phone_reg);
1030             patterns.au.evening_phone = new RegExp(phone_reg);
1031             patterns.au.other_phone = new RegExp(phone_reg);
1032         }
1033
1034         // the remaining patterns fit a well-known key name pattern
1035
1036         angular.forEach(service.org_settings, function(val, key) {
1037             if (!val) return;
1038             var parts = key.match(/ui.patron.edit\.(\w+)\.(\w+)\.regex/);
1039             if (!parts) return;
1040             var cls = parts[1];
1041             var name = parts[2];
1042             patterns[cls][name] = new RegExp(val);
1043         });
1044     }
1045
1046     return service;
1047 }]);
1048
1049
1050 function PatronRegCtrl($scope, $routeParams, $q, $modal, $window, egCore, 
1051     patronSvc, patronRegSvc, egUnloadPrompt, egAlertDialog) {
1052
1053     $scope.page_data_loaded = false;
1054     $scope.clone_id = patronRegSvc.clone_id = $routeParams.clone_id;
1055     $scope.stage_username = 
1056         patronRegSvc.stage_username = $routeParams.stage_username;
1057     $scope.patron_id = 
1058         patronRegSvc.patron_id = $routeParams.edit_id || $routeParams.id;
1059
1060     // for existing patrons, disable barcode input by default
1061     $scope.disable_bc = $scope.focus_usrname = Boolean($scope.patron_id);
1062     $scope.focus_bc = !Boolean($scope.patron_id);
1063     $scope.dupe_counts = {};
1064
1065     // map of perm name to true/false for perms the logged in user
1066     // has at the currently selected patron home org unit.
1067     $scope.perms = {};
1068
1069     if (!$scope.edit_passthru) {
1070         // in edit more, scope.edit_passthru is delivered to us by
1071         // the enclosing controller.  In register mode, there is 
1072         // no enclosing controller, so we create our own.
1073         $scope.edit_passthru = {};
1074     }
1075
1076     // 0=all, 1=suggested, 2=all
1077     $scope.edit_passthru.vis_level = 0; 
1078
1079     // Apply default values for new patrons during initial registration
1080     // prs is shorthand for patronSvc
1081     function set_new_patron_defaults(prs) {
1082         if (!$scope.patron.passwd) {
1083             // passsword may originate from staged user.
1084             $scope.generate_password();
1085         }
1086         $scope.hold_notify_phone = true;
1087         $scope.hold_notify_email = true;
1088
1089         // staged users may be loaded w/ a profile.
1090         $scope.set_expire_date();
1091
1092         if (prs.org_settings['ui.patron.default_ident_type']) {
1093             // $scope.patron needs this field to be an object
1094             var id = prs.org_settings['ui.patron.default_ident_type'];
1095             var ident_type = $scope.ident_types.filter(
1096                 function(type) { return type.id() == id })[0];
1097             $scope.patron.ident_type = ident_type;
1098         }
1099         if (prs.org_settings['ui.patron.default_inet_access_level']) {
1100             // $scope.patron needs this field to be an object
1101             var id = prs.org_settings['ui.patron.default_inet_access_level'];
1102             var level = $scope.net_access_levels.filter(
1103                 function(lvl) { return lvl.id() == id })[0];
1104             $scope.patron.net_access_level = level;
1105         }
1106         if (prs.org_settings['ui.patron.default_country']) {
1107             $scope.patron.addresses[0].country = 
1108                 prs.org_settings['ui.patron.default_country'];
1109         }
1110     }
1111
1112     // A null or undefined pattern leads to exceptions.  Before the
1113     // patterns are loaded from the server, default all patterns
1114     // to an innocuous regex.  To avoid re-creating numerous
1115     // RegExp objects, cache the stub RegExp after initial creation.
1116     // note: angular docs say ng-pattern accepts a regexp or string,
1117     // but as of writing, it only works with a regexp object.
1118     // (Likely an angular 1.2 vs. 1.4 issue).
1119     var field_patterns = {au : {}, ac : {}, aua : {}};
1120     $scope.field_pattern = function(cls, field) { 
1121         if (!field_patterns[cls][field])
1122             field_patterns[cls][field] = new RegExp('.*');
1123         return field_patterns[cls][field];
1124     }
1125
1126     // Main page load function.  Kicks off tab init and data loading.
1127     $q.all([
1128
1129         $scope.initTab ? // initTab comes from patron app
1130             $scope.initTab('edit', $routeParams.id) : $q.when(),
1131
1132         patronRegSvc.init()
1133
1134     ]).then(function() {
1135         // called after initTab and patronRegSvc.init have completed
1136
1137         var prs = patronRegSvc; // brevity
1138         // in standalone mode, we have no patronSvc
1139         $scope.patron = prs.init_patron(patronSvc ? patronSvc.current : null);
1140         $scope.field_doc = prs.field_doc;
1141         $scope.edit_profiles = prs.edit_profiles;
1142         $scope.ident_types = prs.ident_types;
1143         $scope.net_access_levels = prs.net_access_levels;
1144         $scope.user_setting_types = prs.user_setting_types;
1145         $scope.opt_in_setting_types = prs.opt_in_setting_types;
1146         $scope.org_settings = prs.org_settings;
1147         $scope.sms_carriers = prs.sms_carriers;
1148         $scope.stat_cats = prs.stat_cats;
1149         $scope.surveys = prs.surveys;
1150         $scope.survey_responses = prs.survey_responses;
1151         $scope.stat_cat_entry_maps = prs.stat_cat_entry_maps;
1152         $scope.stage_user = prs.stage_user;
1153         $scope.stage_user_requestor = prs.stage_user_requestor;
1154
1155         $scope.user_settings = prs.user_settings;
1156         // clone the user settings back into the patronRegSvc so
1157         // we have a copy of the original state of the settings.
1158         prs.user_settings = {};
1159         angular.forEach($scope.user_settings, function(val, key) {
1160             prs.user_settings[key] = val;
1161         });
1162
1163         extract_hold_notify();
1164         $scope.handle_home_org_changed();
1165
1166         if ($scope.org_settings['ui.patron.edit.default_suggested'])
1167             $scope.edit_passthru.vis_level = 1;
1168
1169         if ($scope.patron.isnew) 
1170             set_new_patron_defaults(prs);
1171
1172         $scope.page_data_loaded = true;
1173
1174         prs.set_field_patterns(field_patterns);
1175         apply_username_regex();
1176     });
1177
1178
1179     // update the currently displayed field documentation
1180     $scope.set_selected_field_doc = function(cls, field) {
1181         $scope.selected_field_doc = $scope.field_doc[cls][field];
1182     }
1183
1184     // returns the tree depth of the selected profile group tree node.
1185     $scope.pgt_depth = function(grp) {
1186         var d = 0;
1187         while (grp = egCore.env.pgt.map[grp.parent()]) d++;
1188         return d;
1189     }
1190
1191     // IDL fields used for labels in the UI.
1192     $scope.idl_fields = {
1193         au  : egCore.idl.classes.au.field_map,
1194         ac  : egCore.idl.classes.ac.field_map,
1195         aua : egCore.idl.classes.aua.field_map
1196     };
1197
1198     // field visibility cache.  Some fields are universally required.
1199     // 3 == value universally required
1200     // 2 == field is visible by default
1201     // 1 == field is suggested by default
1202     var field_visibility = {};
1203     var default_field_visibility = {
1204         'ac.barcode' : 3,
1205         'au.usrname' : 3,
1206         'au.passwd' :  3,
1207         'au.first_given_name' : 3,
1208         'au.family_name' : 3,
1209         'au.ident_type' : 3,
1210         'au.home_ou' : 3,
1211         'au.profile' : 3,
1212         'au.expire_date' : 3,
1213         'au.net_access_level' : 3,
1214         'aua.address_type' : 3,
1215         'aua.post_code' : 3,
1216         'aua.street1' : 3,
1217         'aua.street2' : 2,
1218         'aua.city' : 3,
1219         'aua.county' : 2,
1220         'aua.state' : 2,
1221         'aua.country' : 3,
1222         'aua.valid' : 2,
1223         'aua.within_city_limits' : 2,
1224         'stat_cats' : 1,
1225         'surveys' : 1
1226     }; 
1227
1228     // Returns true if the selected field should be visible
1229     // given the current required/suggested/all setting.
1230     // The visibility flag applied to each field as a result of calling
1231     // this function also sets (via the same flag) the requiredness state.
1232     $scope.show_field = function(field_key) {
1233         // org settings have not been received yet.
1234         if (!$scope.org_settings) return false;
1235
1236         if (field_visibility[field_key] == undefined) {
1237             // compile and cache the visibility for the selected field
1238
1239             var req_set = 'ui.patron.edit.' + field_key + '.require';
1240             var sho_set = 'ui.patron.edit.' + field_key + '.show';
1241             var sug_set = 'ui.patron.edit.' + field_key + '.suggest';
1242
1243             if ($scope.org_settings[req_set]) {
1244                 field_visibility[field_key] = 3;
1245
1246             } else if ($scope.org_settings[sho_set]) {
1247                 field_visibility[field_key] = 2;
1248
1249             } else if ($scope.org_settings[sug_set]) {
1250                 field_visibility[field_key] = 1;
1251             }
1252         }
1253
1254         if (field_visibility[field_key] == undefined) {
1255             // No org settings were applied above.  Use the default
1256             // settings if present or assume the field has no
1257             // visibility flags applied.
1258             field_visibility[field_key] = 
1259                 default_field_visibility[field_key] || 0;
1260         }
1261
1262         return field_visibility[field_key] >= $scope.edit_passthru.vis_level;
1263     }
1264
1265     // See $scope.show_field().
1266     // A field with visbility level 3 means it's required.
1267     $scope.field_required = function(cls, field) {
1268
1269         // Value in the password field is not required
1270         // for existing patrons.
1271         if (field == 'passwd' && $scope.patron && !$scope.patron.isnew) 
1272           return false;
1273
1274         return (field_visibility[cls + '.' + field] == 3);
1275     }
1276
1277     // generates a random 4-digit password
1278     $scope.generate_password = function() {
1279         $scope.patron.passwd = Math.floor(Math.random()*9000) + 1000;
1280     }
1281
1282     $scope.set_expire_date = function() {
1283         if (!$scope.patron.profile) return;
1284         var seconds = egCore.date.intervalToSeconds(
1285             $scope.patron.profile.perm_interval());
1286         var now_epoch = new Date().getTime();
1287         $scope.patron.expire_date = new Date(
1288             now_epoch + (seconds * 1000 /* milliseconds */))
1289     }
1290
1291     // grp is the pgt object
1292     $scope.set_profile = function(grp) {
1293         $scope.patron.profile = grp;
1294         $scope.set_expire_date();
1295         $scope.field_modified();
1296     }
1297
1298     $scope.invalid_profile = function() {
1299         return !(
1300             $scope.patron && 
1301             $scope.patron.profile && 
1302             $scope.patron.profile.usergroup() == 't'
1303         );
1304     }
1305
1306     $scope.new_address = function() {
1307         var addr = egCore.idl.toHash(new egCore.idl.aua());
1308         patronRegSvc.ingest_address($scope.patron, addr);
1309         addr.id = patronRegSvc.virt_id--;
1310         addr.isnew = true;
1311         addr.valid = true;
1312         addr.within_city_limits = true;
1313         addr.country = $scope.org_settings['ui.patron.default_country'];
1314         $scope.patron.addresses.push(addr);
1315     }
1316
1317     // keep deleted addresses out of the patron object so
1318     // they won't appear in the UI.  They'll be re-inserted
1319     // when the patron is updated.
1320     deleted_addresses = [];
1321     $scope.delete_address = function(id) {
1322
1323         if ($scope.patron.isnew &&
1324             $scope.patron.addresses.length == 1 &&
1325             $scope.org_settings['ui.patron.registration.require_address']) {
1326             egAlertDialog.open(egCore.strings.REG_ADDR_REQUIRED);
1327             return;
1328         }
1329
1330         var addresses = [];
1331         angular.forEach($scope.patron.addresses, function(addr) {
1332             if (addr.id == id) {
1333                 if (id > 0) {
1334                     addr.isdeleted = true;
1335                     deleted_addresses.push(addr);
1336                 }
1337             } else {
1338                 addresses.push(addr);
1339             }
1340         });
1341         $scope.patron.addresses = addresses;
1342     } 
1343
1344     $scope.post_code_changed = function(addr) { 
1345         egCore.net.request(
1346             'open-ils.search', 'open-ils.search.zip', addr.post_code)
1347         .then(function(resp) {
1348             if (!resp) return;
1349             if (resp.city) addr.city = resp.city;
1350             if (resp.state) addr.state = resp.state;
1351             if (resp.county) addr.county = resp.county;
1352             if (resp.alert) alert(resp.alert);
1353         });
1354     }
1355
1356     $scope.replace_card = function() {
1357         $scope.patron.card.active = false;
1358         $scope.patron.card.ischanged = true;
1359         $scope.disable_bc = false;
1360
1361         var new_card = egCore.idl.toHash(new egCore.idl.ac());
1362         new_card.id = patronRegSvc.virt_id--;
1363         new_card.isnew = true;
1364         new_card.active = true;
1365         new_card._primary = 'on';
1366         $scope.patron.card = new_card;
1367         $scope.patron.cards.push(new_card);
1368     }
1369
1370     $scope.day_phone_changed = function(phone) {
1371         if (phone && $scope.patron.isnew && 
1372             $scope.org_settings['patron.password.use_phone']) {
1373             $scope.patron.passwd = phone.substr(-4);
1374         }
1375     }
1376
1377     $scope.barcode_changed = function(bc) {
1378         if (!bc) return;
1379         $scope.dupe_barcode = false;
1380         egCore.net.request(
1381             'open-ils.actor',
1382             'open-ils.actor.barcode.exists',
1383             egCore.auth.token(), bc
1384         ).then(function(resp) {
1385             if (resp == '1') { // duplicate card
1386                 $scope.dupe_barcode = true;
1387                 console.log('duplicate barcode detected: ' + bc);
1388             } else {
1389                 if (!$scope.patron.usrname)
1390                     $scope.patron.usrname = bc;
1391                 // No dupe -- A-OK
1392             }
1393         });
1394     }
1395
1396     $scope.cards_dialog = function() {
1397         $modal.open({
1398             templateUrl: './circ/patron/t_patron_cards_dialog',
1399             controller: 
1400                    ['$scope','$modalInstance','cards', 'perms',
1401             function($scope , $modalInstance , cards, perms) {
1402                 // scope here is the modal-level scope
1403                 $scope.args = {cards : cards};
1404                 $scope.perms = perms;
1405                 $scope.ok = function() { $modalInstance.close($scope.args) }
1406                 $scope.cancel = function () { $modalInstance.dismiss() }
1407             }],
1408             resolve : {
1409                 cards : function() {
1410                     // scope here is the controller-level scope
1411                     return $scope.patron.cards;
1412                 },
1413                 perms : function() {
1414                     return $scope.perms;
1415                 }
1416             }
1417         }).result.then(
1418             function(args) {
1419                 angular.forEach(args.cards, function(card) {
1420                     card.ischanged = true; // assume cards need updating, OK?
1421                     if (card._primary == 'on' && 
1422                         card.id != $scope.patron.card.id) {
1423                         $scope.patron.card = card;
1424                     }
1425                 });
1426             }
1427         );
1428     }
1429
1430     $scope.set_addr_type = function(addr, type) {
1431         var addrs = $scope.patron.addresses;
1432         if (addr['_is_'+type]) {
1433             angular.forEach(addrs, function(a) {
1434                 if (a.id != addr.id) a['_is_'+type] = false;
1435             });
1436         } else {
1437             // unchecking mailing/billing means we have to randomly
1438             // select another address to fill that role.  Select the
1439             // first address in the list (that does not match the
1440             // modifed address)
1441             for (var i = 0; i < addrs.length; i++) {
1442                 if (addrs[i].id != addr.id) {
1443                     addrs[i]['_is_' + type] = true;
1444                     break;
1445                 }
1446             }
1447         }
1448     }
1449
1450
1451     // Translate hold notify preferences from the form/scope back into a 
1452     // single user setting value for opac.hold_notify.
1453     function compress_hold_notify() {
1454         var hold_notify = '';
1455         var splitter = '';
1456         if ($scope.hold_notify_phone) {
1457             hold_notify = 'phone';
1458             splitter = ':';
1459         }
1460         if ($scope.hold_notify_email) {
1461             hold_notify = splitter + 'email';
1462             splitter = ':';
1463         }
1464         if ($scope.hold_notify_sms) {
1465             hold_notify = splitter + 'sms';
1466             splitter = ':';
1467         }
1468         $scope.user_settings['opac.hold_notify'] = hold_notify;
1469     }
1470
1471     // dialog for selecting additional permission groups
1472     $scope.secondary_groups_dialog = function() {
1473         $modal.open({
1474             templateUrl: './circ/patron/t_patron_groups_dialog',
1475             controller: 
1476                    ['$scope','$modalInstance','linked_groups','pgt_depth',
1477             function($scope , $modalInstance , linked_groups , pgt_depth) {
1478
1479                 $scope.pgt_depth = pgt_depth;
1480                 $scope.args = {
1481                     linked_groups : linked_groups,
1482                     edit_profiles : patronRegSvc.edit_profiles,
1483                     new_profile   : patronRegSvc.edit_profiles[0]
1484                 };
1485
1486                 // add a new group to the linked groups list
1487                 $scope.link_group = function($event, grp) {
1488                     var found = false; // avoid duplicates
1489                     angular.forEach($scope.args.linked_groups, 
1490                         function(g) {if (g.id() == grp.id()) found = true});
1491                     if (!found) $scope.args.linked_groups.push(grp);
1492                     $event.preventDefault(); // avoid close
1493                 }
1494
1495                 // remove a group from the linked groups list
1496                 $scope.unlink_group = function($event, grp) {
1497                     $scope.args.linked_groups = 
1498                         $scope.args.linked_groups.filter(function(g) {
1499                         return g.id() != grp.id()
1500                     });
1501                     $event.preventDefault(); // avoid close
1502                 }
1503
1504                 $scope.ok = function() { $modalInstance.close($scope.args) }
1505                 $scope.cancel = function () { $modalInstance.dismiss() }
1506             }],
1507             resolve : {
1508                 linked_groups : function() { return $scope.patron.groups },
1509                 pgt_depth : function() { return $scope.pgt_depth }
1510             }
1511         }).result.then(
1512             function(args) {
1513
1514                 if ($scope.patron.isnew) {
1515                     // groups must be linked for new patrons after the
1516                     // patron is created.
1517                     $scope.patron.groups = args.linked_groups;
1518                     return;
1519                 }
1520
1521                 // update links groups for existing users in real time.
1522                 var ids = args.linked_groups.map(function(g) {return g.id()});
1523                 patronRegSvc.apply_secondary_groups($scope.patron.id, ids)
1524                 .then(function(success) {
1525                     if (success)
1526                         $scope.patron.groups = args.linked_groups;
1527                 });
1528             }
1529         );
1530     }
1531
1532     function extract_hold_notify() {
1533         notify = $scope.user_settings['opac.hold_notify'];
1534         if (!notify) return;
1535         $scope.hold_notify_phone = Boolean(notify.match(/phone/));
1536         $scope.hold_notify_email = Boolean(notify.match(/email/));
1537         $scope.hold_notify_sms = Boolean(notify.match(/sms/));
1538     }
1539
1540     $scope.invalidate_field = function(field) {
1541         patronRegSvc.invalidate_field($scope.patron, field);
1542     }
1543
1544
1545     $scope.dupe_value_changed = function(type, value) {
1546         $scope.dupe_counts[type] = 0;
1547         patronRegSvc.dupe_patron_search($scope.patron, type, value)
1548         .then(function(res) {
1549             $scope.dupe_counts[type] = res.count;
1550             if (res.count) {
1551                 $scope.dupe_search_encoded = 
1552                     encodeURIComponent(js2JSON(res.search));
1553             } else {
1554                 $scope.dupe_search_encoded = '';
1555             }
1556         });
1557     }
1558
1559     $scope.handle_home_org_changed = function() {
1560         org_id = $scope.patron.home_ou.id();
1561         patronRegSvc.has_perms_for_org(org_id).then(function(map) {
1562             angular.forEach(map, function(v, k) { $scope.perms[k] = v });
1563         });
1564     }
1565
1566     // This is called with every character typed in a form field,
1567     // since that's the only way to gaurantee something has changed.
1568     // See handle_field_changed for ng-change vs. ng-blur.
1569     $scope.field_modified = function() {
1570         // Call attach with every field change, regardless of whether
1571         // it's been called before.  This will allow for re-attach after
1572         // the user clicks through the unload warning. egUnloadPrompt
1573         // will ensure we only attach once.
1574         egUnloadPrompt.attach($scope);
1575     }
1576
1577     // username regex (if present) must be removed any time
1578     // the username matches the barcode to avoid firing the
1579     // invalid field handlers.
1580     function apply_username_regex() {
1581         var regex = $scope.org_settings['opac.username_regex'];
1582         if (regex) {
1583             if ($scope.patron.card.barcode) {
1584                 // username must match the regex or the barcode
1585                 field_patterns.au.usrname = 
1586                     new RegExp(
1587                         regex + '|^' + $scope.patron.card.barcode + '$');
1588             } else {
1589                 // username must match the regex
1590                 field_patterns.au.usrname = new RegExp(regex);
1591             }
1592         } else {
1593             // username can be any format.
1594             field_patterns.au.usrname = new RegExp('.*');
1595         }
1596     }
1597
1598     // obj could be the patron, an address, etc.
1599     // This is called any time a form field achieves then loses focus.
1600     // It does not necessarily mean the field has changed.
1601     // The alternative is ng-change, but it's called with each character
1602     // typed, which would be overkill for many of the actions called here.
1603     $scope.handle_field_changed = function(obj, field_name) {
1604         var cls = obj.classname; // set by egIdl
1605         var value = obj[field_name];
1606
1607         console.log('changing field ' + field_name + ' to ' + value);
1608
1609         switch (field_name) {
1610             case 'day_phone' : 
1611                 if ($scope.patron.day_phone && 
1612                     $scope.patron.isnew && 
1613                     $scope.org_settings['patron.password.use_phone']) {
1614                     $scope.patron.passwd = phone.substr(-4);
1615                 }
1616             case 'evening_phone' : 
1617             case 'other_phone' : 
1618                 $scope.dupe_value_changed('phone', value);
1619                 break;
1620
1621             case 'ident_value':
1622             case 'ident_value2':
1623                 $scope.dupe_value_changed('ident', value);
1624                 break;
1625
1626             case 'first_given_name':
1627             case 'family_name':
1628                 $scope.dupe_value_changed('name', value);
1629                 break;
1630
1631             case 'email':
1632                 $scope.dupe_value_changed('email', value);
1633                 break;
1634
1635             case 'street1':
1636             case 'street2':
1637             case 'city':
1638                 // dupe search on address wants the address object as the value.
1639                 $scope.dupe_value_changed('address', obj);
1640                 break;
1641
1642             case 'post_code':
1643                 $scope.post_code_changed(obj);
1644                 break;
1645
1646             case 'usrname':
1647                 patronRegSvc.check_dupe_username(value)
1648                 .then(function(yes) {$scope.dupe_username = Boolean(yes)});
1649                 break;
1650
1651             case 'barcode':
1652                 // TODO: finish barcode_changed handler.
1653                 $scope.barcode_changed(value);
1654                 apply_username_regex();
1655                 break;
1656
1657             case 'dob':
1658                 maintain_juvenile_flag();
1659                 break;
1660         }
1661     }
1662
1663     // patron.juvenile is set to true if the user was born after
1664     function maintain_juvenile_flag() {
1665         if ( !($scope.patron && $scope.patron.dob) ) return;
1666
1667         var juv_interval = 
1668             $scope.org_settings['global.juvenile_age_threshold'] 
1669             || '18 years';
1670
1671         var base = new Date();
1672
1673         base.setTime(base.getTime() - 
1674             Number(egCore.date.intervalToSeconds(juv_interval) + '000'));
1675
1676         $scope.patron.juvenile = ($scope.patron.dob > base);
1677     }
1678
1679     // returns true (disable) for orgs that cannot have users.
1680     $scope.disable_home_org = function(org_id) {
1681         if (!org_id) return;
1682         var org = egCore.org.get(org_id);
1683         return (
1684             org &&
1685             org.ou_type() &&
1686             org.ou_type().can_have_users() == 'f'
1687         );
1688     }
1689
1690     // Returns true if the Save and Save & Clone buttons should be disabled.
1691     $scope.edit_passthru.hide_save_actions = function() {
1692         return $scope.patron.isnew ?
1693             !$scope.perms.CREATE_USER : 
1694             !$scope.perms.UPDATE_USER;
1695     }
1696
1697     // Returns true if any input elements are tagged as invalid
1698     // via Angular patterns or required attributes.
1699     function form_has_invalid_fields() {
1700         return $('#patron-reg-container .ng-invalid').length > 0;
1701     }
1702
1703     function form_is_incomplete() {
1704         return (
1705             $scope.dupe_username ||
1706             $scope.dupe_barcode ||
1707             form_has_invalid_fields()
1708         );
1709
1710     }
1711
1712     $scope.edit_passthru.save = function(save_args) {
1713         if (!save_args) save_args = {};
1714
1715         if (form_is_incomplete()) {
1716             // User has not provided valid values for all required fields.
1717             return egAlertDialog.open(egCore.strings.REG_INVALID_FIELDS);
1718         }
1719
1720         // remove page unload warning prompt
1721         egUnloadPrompt.clear();
1722
1723         // toss the deleted addresses back into the patron's list of
1724         // addresses so it's included in the update
1725         $scope.patron.addresses = 
1726             $scope.patron.addresses.concat(deleted_addresses);
1727         
1728         compress_hold_notify();
1729
1730         var updated_user;
1731
1732         patronRegSvc.save_user($scope.patron)
1733         .then(function(new_user) { 
1734             if (new_user && new_user.classname) {
1735                 updated_user = new_user;
1736                 return patronRegSvc.save_user_settings(
1737                     new_user, $scope.user_settings); 
1738             } else {
1739                 alert('Patron update failed. \n\n' + js2JSON(new_user));
1740             }
1741
1742         }).then(function() {
1743
1744             // only remove the staged user if the update succeeded.
1745             if (updated_user) 
1746                 return patronRegSvc.remove_staged_user();
1747
1748             return $q.when();
1749
1750         }).then(function() {
1751
1752             // linked groups for new users must be created after the new
1753             // user is created.
1754             if ($scope.patron.isnew && 
1755                 $scope.patron.groups && $scope.patron.groups.length) {
1756                 var ids = $scope.patron.groups.map(function(g) {return g.id()});
1757                 return patronRegSvc.apply_secondary_groups(updated_user.id(), ids)
1758             }
1759
1760             return $q.when();
1761
1762         }).then(function() {
1763
1764             // reloading the page means potentially losing some information
1765             // (e.g. last patron search), but is the only way to ensure all
1766             // components are properly updated to reflect the modified patron.
1767             if (updated_user && save_args.clone) {
1768                 // open a separate tab for registering a new 
1769                 // patron from our cloned data.
1770                 var url = 'https://' 
1771                     + $window.location.hostname 
1772                     + egCore.env.basePath 
1773                     + '/circ/patron/register/clone/' 
1774                     + updated_user.id();
1775                 $window.open(url, '_blank').focus();
1776
1777             } else {
1778                 // reload the current page
1779                 $window.location.href = location.href;
1780             }
1781         });
1782     }
1783 }
1784
1785 // This controller may be loaded from different modules (patron edit vs.
1786 // register new patron), so we have to inject the controller params manually.
1787 PatronRegCtrl.$inject = ['$scope', '$routeParams', '$q', '$modal', 
1788     '$window', 'egCore', 'patronSvc', 'patronRegSvc', 'egUnloadPrompt', 'egAlertDialog'];
1789