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