2 * App to drive the offline UI
7 angular.module('egOffline', ['ngRoute', 'ui.bootstrap', 'egCoreMod', 'egUiMod', 'ngToast', 'tableSort'])
10 ['$routeProvider','$locationProvider','$compileProvider',
11 function($routeProvider , $locationProvider , $compileProvider) {
13 $locationProvider.html5Mode(true);
14 $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|mailto|blob):/);
17 * Route resolvers allow us to run async commands
18 * before the page controller is instantiated.
20 var resolver = {delay : ['egCore',
22 return egCore.startup.go();
26 $routeProvider.when('/offline-interface/:tab', {
27 templateUrl: 'offline-template',
28 controller: 'OfflineCtrl',
33 $routeProvider.otherwise({
34 templateUrl : 'offline-template',
35 controller : 'OfflineCtrl',
40 .controller('OfflineSessionCtrl',
41 ['$scope','$window','egCore','$routeParams','$http','$q','$timeout','egPromptDialog','ngToast','egProgressDialog',
42 function($scope , $window , egCore , $routeParams , $http , $q , $timeout , egPromptDialog , ngToast , egProgressDialog) {
43 $scope.active_session_tab = 'pending';
45 $scope.lookupNoncatTypeName = function (type) {
46 var nc = $scope.noncats.filter(function(n){ return n.id() == type })[0];
47 if (nc) return nc.name();
51 $scope.createDate = function (ts, epoch) {
53 if (epoch) ts = ts * 1000;
57 $scope.setSession = function (s, ind) {
58 $scope.current_session = s;
59 $scope.current_session_index = ind;
61 return $scope.refreshExceptions(s);
64 $scope.createSession = function () {
66 return egPromptDialog.open(
67 egCore.strings.OFFLINE_SESSION_DESC, '',
68 {ok : function(value) {
71 return $http.get(formURL({action:'create',desc:value})).then(function(res) {
72 if (res.data.ilsevent == "0") return $q.when(res.data.payload);
74 }).then(function (seskey) {
75 return $scope.refreshSessions().then(function() {
77 var s = $scope.sessions.filter(function(s){ s.key == seskey })[0];
78 var ind = $scope.sessions.length - 1; // sorted by create time, so new one is last
79 return $scope.setSession(s, ind);
83 ngToast.warning(egCore.strings.OFFLINE_SESSION_CREATE_FAILED);
90 $scope.processSession = function (s, ind) {
91 return $scope.setSession(s, ind).then(function() {
92 egProgressDialog.open();
95 formURL({action:'execute',seskey:$scope.current_session.key})
96 ).then(function(res) {
97 if (res.data.ilsevent == "0") return $q.when(res.data.payload);
100 egProgressDialog.close();
101 return $scope.refreshSessions()
102 .then(function(){ return $scope.refreshExceptions(s) });
104 egProgressDialog.close();
105 return $scope.refreshSessions().then(function() {
106 ngToast.warning(egCore.strings.OFFLINE_SESSION_PROCESSING_FAILED);
112 $scope.refreshExceptions = function (s) {
116 status_type : 'exceptions',
119 ).then(function(res) {
120 if (res.data.ilsevent) {
121 $scope.current_session.exceptions = [];
123 $scope.current_session.exceptions = res.data;
129 $scope.sessions = [];
130 $scope.refreshSessions = function () {
132 return $http.get(formURL({action:'status',status_type:'sessions'})).then(function(res) {
133 if (angular.isArray(res.data)) {
134 $scope.sessions = res.data;
139 var creator_list = [$q.when()];
140 angular.forEach($scope.sessions, function (s) {
142 s.org = egCore.org.get(s.org).shortname();
143 creator_list.push(egCore.pcrud.retrieve('au',s.creator).then(function(u) {
144 s.creator = u.family_name();
146 angular.forEach(s.scripts, function(sc) {
151 return $q.all(creator_list);
155 $scope.reprintLast = function () {
156 egCore.print.reprintLast();
160 $scope.uploadPending = function (s, ind) {
161 return $scope.setSession(s, ind).then(function() {
163 egProgressDialog.open();
164 return $scope.createOfflineXactBlob().then(function(blob) {
166 var form = new FormData();
167 form.append("ses", egCore.auth.token());
168 form.append("org", $scope.org.id());
169 form.append("ws", $scope.current_workstation_name());
170 form.append("wc", 1);
171 form.append("action", "load");
172 form.append("seskey", $scope.current_session.key);
173 form.append("file", blob, "file");
176 '/cgi-bin/offline/offline.pl?' + new Date().getTime(),
179 transformRequest: angular.identity,
180 headers: {'Content-Type': undefined}
182 ).then(function(res) {
183 egProgressDialog.close();
184 if (res.data.ilsevent == "0") {
185 return $scope.clear_pending(true).then(function() {
186 return $scope.refreshSessions();
189 ngToast.warning(egCore.strings.OFFLINE_SESSION_UPLOAD_FAILED);
190 return $scope.refreshSessions();
192 },function () { egProgressDialog.close() });
197 $scope.retrieveDetails = function (x) {
198 alert(JSON.stringify(x, null, 2)); // egAlertDialog kills pretty printing
201 $scope.retrieveItem = function (bc) {
202 return egCore.pcrud.search('acp',{deleted: 'f', barcode: bc}).then(function(copy) {
205 egCore.env.basePath +
206 '/cat/item/' + copy.id(),
211 ngToast.warning(egCore.strings.ITEM_NOT_FOUND);
215 $scope.retrievePatron = function (bc) {
216 return egCore.pcrud.search('ac',{barcode: bc}).then(function(card) {
219 egCore.env.basePath +
220 '/circ/patron/' + card.usr() + '/checkout',
225 ngToast.warning(egCore.strings.PATRON_NOT_FOUND);
229 function formURL (params) {
230 var url = '/cgi-bin/offline/offline.pl?' + new Date().getTime();
233 org : $scope.org ? $scope.org.id() : null,
234 ws : $scope.current_workstation_name(),
236 ses : egCore.auth.token()
239 angular.extend(params, defaults)
242 for (var k in params) {
243 url += '&' + k + '=' + window.encodeURIComponent(params[k]);
248 $scope.$watch('org',function(n){if (n) $scope.refreshSessions()});
253 .controller('OfflineCtrl',
254 ['$q','$scope','$window','$location','$rootScope','egCore','egLovefield','$routeParams','$timeout','$http','ngToast','egConfirmDialog','egUnloadPrompt',
255 function($q , $scope , $window , $location , $rootScope , egCore , egLovefield , $routeParams , $timeout , $http , ngToast , egConfirmDialog , egUnloadPrompt) {
257 // Immediately redirect if we're really offline
258 if (!$window.navigator.onLine) {
259 if ($location.path().match(/session$/)) {
260 var path = $location.path();
261 console.log('internal redirect');
262 return $location.path(path.replace('session','checkout'));
266 var today = new Date();
270 today.setMilliseconds(0);
272 $scope.minDate = today;
273 $scope.blocked_patron = null;
274 $scope.bad_barcode = null;
275 $scope.barcode_type = 'barcode';
276 $scope.focusMe = true;
277 $scope.shared = { outOfRange : false, due_date : null, due_date_offset : '' };
278 $scope.workstation_obj = null;
279 $scope.workstation = '';
280 $scope.workstation_owner = '';
281 $scope.workstations = [];
283 $scope.do_print = Boolean($scope.active_tab == 'checkout');
284 $scope.do_print_changed = false;
285 $scope.printed = false;
287 $scope.imported_pending_xacts = { data : '' };
289 $scope.xact_page = { checkin:[], checkout:[], renew:[], in_house_use:[] };
290 $scope.all_xact = [];
293 $scope.checkout = { noncat_type : '' };
294 $scope.renew = { noncat_type : '' };
295 $scope.in_house_use = {count : 1};
296 $scope.checkin = { backdate : new Date() };
298 $scope.current_workstation_owning_lib = function () {
299 return $scope.workstations.filter(function(w) {
300 return $scope.workstation == w.id
304 $scope.current_workstation_name = function () {
305 return $scope.workstations.filter(function(w) {
306 return $scope.workstation == w.id
310 $scope.$watch('workstation', function (n,o) {
312 $scope.org = egCore.org.get($scope.current_workstation_owning_lib());
315 $scope.changeCheck = function () {
316 $scope.strict_barcode = !$scope.strict_barcode;
317 $scope.do_check_changed = true;
318 egCore.hatch.setItem('eg.offline.strict_barcode', $scope.strict_barcode)
321 $scope.changePrint = function () {
322 $scope.do_print = !$scope.do_print;
323 $scope.do_print_changed = true;
324 egCore.hatch.setItem('eg.offline.print_receipt', $scope.do_print)
327 $scope.logged_in = egCore.auth.token() ? true : false;
330 $scope.active_tab = $routeParams.tab;
332 if (!$scope.logged_in) {
333 $scope.active_tab = 'checkout';
335 $scope.active_tab = 'session';
339 egCore.hatch.getItem('eg.offline.print_receipt')
340 .then(function(setting) {
341 $scope.do_print = setting;
342 if (setting !== undefined) $scope.do_print_changed = true;
345 egCore.hatch.getItem('eg.offline.strict_barcode')
346 .then(function(setting) {
347 $scope.strict_barcode = setting;
348 if (setting !== undefined) $scope.do_check_changed = true;
351 egCore.hatch.getItem('eg.workstation.all')
352 .then(function(all) {
353 if (all && all.length) {
354 $scope.workstations = all;
356 if (ws = $location.search().ws) {
357 // user requested a workstation via URL
358 var match = all.filter(
359 function(w) {return ws == w.name} )[0];
362 // requested WS registered on this client
363 $scope.workstation_obj = match;
364 $scope.workstation = match.id;
365 $scope.workstation_owner = match.owning_lib;
367 // the requested WS is not registered on this client
368 $scope.wsNotRegistered = true;
371 // no workstation requested; use the default
372 egCore.hatch.getItem('eg.workstation.default')
374 var ws_obj = all.filter(function(w) {
378 $scope.workstation_obj = ws_obj;
379 $scope.workstation = ws_obj.id;
380 $scope.workstation_owner = ws_obj.owning_lib;
382 return egLovefield.reconstituteList('cnct').then(function () {
383 $scope.noncats = egCore.env.cnct.list;
390 $scope.downloadBlockList = function () {
391 var url = '/standalone/list.txt?ses='
392 + egCore.auth.token()
393 + '&' + new Date().getTime();
394 return $http.get(url).then(
397 var lines = res.data.split('\n');
398 egLovefield.destroyOfflineBlocks().then(function(){
399 angular.forEach(lines, function (l) {
400 var parts = l.split(' ');
401 egLovefield.addOfflineBlock(parts[0], parts[1]);
405 ngToast.create(egCore.strings.OFFLINE_BLOCKLIST_SUCCESS);
409 ngToast.warning(egCore.strings.OFFLINE_BLOCKLIST_FAIL);
410 egCore.audio.play('warning.offline.blocklist_fail');
415 $scope.createOfflineXactBlob = function () {
416 return egLovefield.retrievePendingOfflineXacts().then(function(list) {
418 angular.forEach(list, function (i) {
419 flat_list.push(JSON.stringify(i) + '\n');
422 var blob = new Blob(flat_list, {type: 'text/plain'});
428 $scope.pending_xacts = [];
429 $scope.retrieve_pending = function () {
430 return egLovefield.retrievePendingOfflineXacts().then(function(list) {
431 $scope.pending_xacts = list;
432 return $q.when(list);
436 $scope.save = function () {
437 var promises = [$q.when()];
438 angular.forEach($scope.all_xact, function (x) {
439 promises.push(egLovefield.addOfflineXact(x));
442 var prints = [$q.when()];
443 if ($scope.do_print) {
444 angular.forEach(['checkin','checkout','renew','in_house_use'], function(xtype) {
445 if ($scope.xact_page[xtype].length > 0) {
446 prints.push(egCore.print.print({
448 template : 'offline_'+xtype,
450 transactions : $scope.xact_page[xtype]
457 return $q.all(promises.concat(prints)).finally(function() {
458 egUnloadPrompt.clear();
459 if (prints.length > 1) $scope.printed = true;
460 $scope.all_xact = [];
461 $scope.xact_page = { checkin:[], checkout:[], renew:[], in_house_use:[] };
462 angular.forEach(['checkout','renew'], function (xtype) {
463 $scope[xtype].patron_barcode = '';
465 $scope.retrieve_pending();
469 $rootScope.save_offline_xacts = function () { return $scope.save() };
470 $rootScope.active_tab = function (t) { $scope.active_tab = t };
472 $scope.logout = function () {
473 egCore.auth.logout();
474 $window.location.href = location.href;
477 $scope.clear_pending = function (skip_confirm) {
479 return egLovefield.destroyPendingOfflineXacts().then(function () {
480 return $scope.retrieve_pending();
483 return egConfirmDialog.open(
484 egCore.strings.CONFIRM_CLEAR_PENDING,
485 egCore.strings.CONFIRM_CLEAR_PENDING_BODY,
487 ).result.then(function() {
488 return egLovefield.destroyPendingOfflineXacts().then(function () {
489 return $scope.retrieve_pending();
495 $scope.retrieve_pending();
496 $scope.$watch('active_tab', function (n,o) {
497 console.log('watch caught change to active_tab: ' + o + ' -> ' + n);
498 if (n != o && !$scope.do_check_changed && n != 'checkout') $scope.strict_barcode = false;
499 if (n != o && !$scope.do_check_changed && n == 'checkout') $scope.strict_barcode = true;
500 if (n != o && !$scope.do_print_changed && n != 'checkout') $scope.do_print = false;
501 if (n != o && !$scope.do_print_changed && n == 'checkout') $scope.do_print = true;
502 if (n != o && n == 'session') $scope.retrieve_pending();
505 $scope.$watch('imported_pending_xacts.data', function (n, o) {
507 var lines = n.split('\n');
510 angular.forEach(lines, function (l) {
515 egLovefield.addOfflineXact(JSON.parse(l))
518 ngToast.warning(err);
522 $q.all(promises).then(function () { $scope.retrieve_pending() });
526 $scope.resetDueDate = function (xtype) {
527 $scope.shared.due_date = new Date();
528 $scope.shared.due_date.setDate($scope.shared.due_date.getDate() + parseInt($scope.shared.due_date_offset));
531 $scope.notEnough = function (xtype) {
533 if (xtype == 'checkout') {
534 if ($scope.shared.outOfRange) return true;
536 $scope.checkout.patron_barcode &&
537 ($scope.shared.due_date || $scope.shared.due_date_offset) &&
538 ($scope.checkout.barcode || ($scope.checkout.noncat_type && $scope.checkout.noncat_count))
543 if (xtype == 'renew') {
544 if ($scope.shared.outOfRange) return true;
546 $scope.renew.barcode &&
547 ($scope.shared.due_date || $scope.shared.due_date_offset)
552 if (xtype == 'in_house_use') {
554 $scope.in_house_use.barcode && $scope.in_house_use.count
559 if (xtype == 'checkin') {
561 $scope.checkin.barcode && $scope.checkin.backdate
567 $scope.clear = function (xtype) {
569 if (xtype=="in_house_use") $scope[xtype].count = 1;
572 $scope.add = function (xtype,next_focus) {
574 var barcode = $scope[xtype].barcode;
576 if ($scope.xact_page[xtype].filter(function(x){ return x.barcode == barcode }).length > 0) {
577 ngToast.warning(egCore.strings.DUPLICATE_BARCODE);
578 egCore.audio.play('warning.offline.duplicate_barcode');
579 $scope[xtype].barcode = '';
580 if (next_focus) $('#'+next_focus).focus();
585 var pbarcode = $scope[xtype].patron_barcode;
587 egLovefield.testOfflineBlock(pbarcode).then(function (blocked) {
589 egCore.audio.play('warning.offline.blocked_patron');
590 egConfirmDialog.open(
591 egCore.strings.PATRON_BLOCKED,
592 egCore.strings.PATRON_BLOCKED_WHY[blocked],
593 {}, egCore.strings.ALLOW, egCore.strings.REJECT
595 function(){ // forced
596 $scope.blocked_patron = null;
597 _add_impl(xtype,true)
598 if (next_focus) $('#'+next_focus).focus();
599 },function(){ // stopped
600 $scope.blocked_patron = xtype;
601 if (next_focus) $('#'+next_focus).focus();
606 $scope.blocked_patron = null;
607 _add_impl(xtype,true)
608 if (next_focus) $('#'+next_focus).focus();
613 if (next_focus) $('#'+next_focus).focus();
617 function _add_impl (xtype,digest) {
618 var pbarcode = $scope[xtype].patron_barcode;
619 var backdate = $scope[xtype].backdate;
621 if ($scope.strict_barcode && pbarcode) {
622 if (!check_barcode(pbarcode)) {
623 $scope.bad_barcode = xtype;
624 egCore.audio.play('warning.offline.bad_barcode');
625 return egConfirmDialog.open(
626 egCore.strings.BAD_PATRON_BARCODE,
627 egCore.strings.BAD_PATRON_BARCODE_CD,
628 {}, egCore.strings.ALLOW, egCore.strings.REJECT
630 function(){ // forced
631 $scope.blocked_patron = null;
632 return _add_impl2(xtype,digest)
633 },function(){ // stopped
634 $scope.blocked_patron = xtype;
640 if ($scope.strict_barcode && $scope[xtype].barcode) {
641 if (!check_barcode($scope[xtype].barcode)) {
642 $scope.bad_barcode = xtype;
643 egCore.audio.play('warning.offline.bad_barcode');
644 return egConfirmDialog.open(
645 egCore.strings.BAD_BARCODE,
646 egCore.strings.BAD_BARCODE_CD,
647 {}, egCore.strings.ALLOW, egCore.strings.REJECT
649 function(){ // forced
650 $scope.blocked_patron = null;
651 return _add_impl2(xtype,digest)
652 },function(){ // stopped
653 $scope.blocked_patron = xtype;
659 return _add_impl2(xtype,digest);
662 function _add_impl2 (xtype,digest) {
663 var pbarcode = $scope[xtype].patron_barcode;
664 var backdate = $scope[xtype].backdate;
666 $scope.bad_barcode = null;
668 var now = new Date().getTime();
671 if ($scope[xtype].noncat_type) $scope[xtype].noncat = 1;
673 if ($scope.shared.due_date && (xtype == 'checkout' || xtype == 'renew')) {
674 $scope[xtype].due_date = $scope.shared.due_date.toISOString();
675 $scope[xtype].checkout_time = new Date().toISOString();
678 var xact = { timestamp : parseInt(now), type : xtype, delta : 0 };
680 $scope.xact_page[xtype].push(
681 angular.extend(xact, $scope[xtype])
684 $scope.all_xact.push(xact)
685 egUnloadPrompt.attach($rootScope);
689 if (pbarcode) $scope[xtype].patron_barcode = pbarcode;
690 if (backdate) $scope[xtype].backdate = backdate;
691 if (xtype=="in_house_use") $scope[xtype].count = 1;
693 if (digest) $timeout(function(){$scope.$apply()});
696 check_barcode = function(bc) {
697 if (bc != Number(bc)) return false;
699 // "16.00" == Number("16.00"), but the . is bad.
700 // Throw out any barcode that isn't just digits
701 if (bc.search(/\D/) != -1) return false;
702 var last_digit = bc.substr(bc.length-1);
703 var stripped_barcode = bc.substr(0,bc.length-1);
704 return barcode_checkdigit(stripped_barcode).toString() == last_digit;
707 barcode_checkdigit = function(bc) {
708 var reverse_barcode = bc.toString().split('').reverse();
709 var check_sum = 0; var multiplier = 2;
710 for (var i = 0; i < reverse_barcode.length; i++) {
711 var digit = reverse_barcode[i];
712 var product = digit * multiplier; product = product.toString();
714 for (var j = 0; j < product.length; j++) {
715 temp_sum += Number( product[j] );
717 check_sum += Number( temp_sum );
718 multiplier = ( multiplier == 2 ? 1 : 2 );
720 check_sum = check_sum.toString();
721 var next_multiple_of_10 = (check_sum.match(/(\d*)\d$/)[1] * 10) + 10;
722 var check_digit = next_multiple_of_10 - Number(check_sum);
723 if (check_digit == 10) check_digit = 0;
727 function fetch_org_after_tree_exists () {
730 $scope.org = egCore.org.get($scope.current_workstation_owning_lib());
732 fetch_org_after_tree_exists();
737 fetch_org_after_tree_exists();
741 // dummy service so standalone patron editor can reference it
742 .factory('patronSvc', function() { return { /* dummy */ } })
744 .factory('patronRegSvc', ['$q', 'egCore', 'egLovefield', function($q, egCore, egLovefield) {
746 egLovefield.isOffline = true;
749 org : null, // will come from workstation org
750 field_doc : {}, // config.idl_field_doc
751 profiles : [], // permission groups
752 edit_profiles : [], // perm groups we can modify
754 user_settings : {}, // applied user settings
755 user_setting_types : {}, // config.usr_setting_type
756 opt_in_setting_types : {}, // config.usr_setting_type for event-def opt-in
758 survey_questions : {},
760 survey_responses : {}, // survey.responses for loaded patron in progress
762 stat_cat_entry_maps : {}, // cat.id to selected value
763 virt_id : -1, // virtual ID for new objects
764 init_done : false // have we loaded our initialization data?
767 service.offlineMode = function () {
771 // launch a series of parallel data retrieval calls
772 service.init = function(scope) {
774 // Data loaded here only needs to be retrieved the first time this
775 // tab becomes active within the current instance of the patron app.
776 // In other words, navigating between patron tabs will not cause
777 // all of this data to be reloaded. Navigating to a separate app
778 // and returning will cause the data to be reloaded.
779 if (service.init_done) return $q.when();
780 service.init_done = true;
783 service.get_field_doc(),
784 service.get_perm_groups(),
785 service.get_ident_types(),
786 service.get_user_settings(),
787 service.get_org_settings(),
788 service.get_stat_cats(),
789 service.get_surveys(),
790 service.get_net_access_levels()
794 service.get_linked_addr_users = function(addrs) {
798 service.apply_secondary_groups = function(user_id, group_ids) {
799 return $q.when(true);
802 // See note above about not loading egUser.
804 service.format_name = function(last, first, middle) {
805 return last + ', ' + first + (middle ? ' ' + middle : '');
808 service.check_dupe_username = function(usrname) {
809 return $q.when(false);
812 // determine which user groups our user is not allowed to modify
813 service.set_edit_profiles = function() {
814 service.edit_profiles = egCore.env.pgt.list.filter(
815 function (p) { return p.application_perm() == 'group_application.user.patron' }
820 // resolves to a hash of perm-name => boolean value indicating
821 // wether the user has the permission at org_id.
822 service.has_perms_for_org = function(org_id) {
827 'CREATE_USER_GROUP_LINK',
828 'UPDATE_PATRON_COLLECTIONS_EXEMPT',
829 'UPDATE_PATRON_CLAIM_RETURN_COUNT',
830 'UPDATE_PATRON_CLAIM_NEVER_CHECKED_OUT_COUNT',
831 'UPDATE_PATRON_ACTIVE_CARD',
832 'UPDATE_PATRON_PRIMARY_CARD'
836 angular.forEach(perms_needed, function (p) {
840 return $q.when(hash);
843 service.get_surveys = function() {
844 return egLovefield.reconstituteList('asv').then(function(offline) {
845 return egLovefield.reconstituteList('asvq')
847 return egLovefield.reconstituteList('asva');
849 angular.forEach(egCore.env.asv.list, function (s) {
850 s.questions( egCore.env.asva.list.filter( function (a) {
851 return q.survey().id == s.id();
855 angular.forEach(egCore.env.asvq.list, function (q) {
856 q.survey( egCore.env.asv.map[ q.survey().id ] );
857 q.answers( egCore.env.asva.list.filter( function (a) {
858 return q.id() == a.question();
862 angular.forEach(egCore.env.asva.list, function (a) {
863 a.question( egCore.env.asvq.map[ a.question().id ] );
866 service.surveys = egCore.env.asv.list;
867 service.survey_questions = egCore.env.asvq.list;
868 service.survey_answers = egCore.env.asva.list;
875 service.get_stat_cats = function() {
876 return egLovefield.getStatCatsCache().then(
878 service.stat_cats = cats;
884 service.get_org_settings = function() {
885 return egLovefield.getSettingsCache().then(
888 angular.forEach(list, function (s) {
889 hash[s.name] = s.value;
891 service.org_settings = hash;
892 if (egCore && egCore.env && !egCore.env.aous) {
893 egCore.env.aous = hash;
894 console.log('setting egCore.env.aous');
901 service.get_ident_types = function() {
902 return egLovefield.reconstituteList('cit').then(function() {
903 service.ident_types = egCore.env.cit.list;
908 service.get_net_access_levels = function() {
909 return egLovefield.reconstituteList('cnal').then(function() {
910 service.net_access_levels = egCore.env.cnal.list;
915 service.get_perm_groups = function() {
916 if (egCore.env.pgt) {
917 service.profiles = egCore.env.pgt.list;
918 return service.set_edit_profiles();
920 return egLovefield.reconstituteTree('pgt').then(function(offline) {
921 service.profiles = egCore.env.pgt.list;
922 return service.set_edit_profiles();
927 service.get_field_doc = function() {
928 return egLovefield.getListFromOfflineCache('fdoc').then(function (list) {
929 angular.forEach(list, function(doc) {
930 if (!service.field_doc[doc.fm_class()])
931 service.field_doc[doc.fm_class()] = {};
932 service.field_doc[doc.fm_class()][doc.field()] = doc;
938 service.get_user_settings = function() {
940 'circ.holds_behind_desk',
941 'circ.collections.exempt',
943 'opac.default_phone',
944 'opac.default_pickup_location',
945 'opac.default_sms_carrier',
946 'opac.default_sms_notify'];
948 angular.forEach(static_types, function (t) {
949 service.user_settings[t] = null;
952 return egLovefield.getListFromOfflineCache('cust').then(function (list) {
953 angular.forEach(list, function(stype) {
954 service.user_setting_types[stype.name()] = stype;
955 if (static_types.indexOf(stype.name()) == -1) {
956 service.opt_in_setting_types[stype.name()] = stype;
958 if (stype.reg_default() != undefined) {
959 service.user_settings[setting.name()] =
960 setting.reg_default();
967 service.invalidate_field = function(patron, field) {
971 service.dupe_patron_search = function(patron, type, value) {
972 return $q.when({ search : search, count : 0 });
975 service.init_patron = function(current) {
978 return service.init_new_patron();
980 service.patron = current;
981 return service.init_existing_patron(current)
984 service.ingest_address = function(patron, addr) {
985 addr.valid = addr.valid == 't';
986 addr.within_city_limits = addr.within_city_limits == 't';
987 addr._is_mailing = (patron.mailing_address &&
988 addr.id == patron.mailing_address.id);
989 addr._is_billing = (patron.billing_address &&
990 addr.id == patron.billing_address.id);
994 * Existing patron objects reqire some data munging before insertion
997 * 1. Turn everything into a hash
998 * 2. ... Except certain fields (selectors) whose widgets require objects
999 * 3. Bools must be Boolean, not t/f.
1001 service.init_existing_patron = function(current) {
1003 service.existing_patron = current;
1005 var patron = egCore.idl.toHash(current);
1007 patron.home_ou = egCore.org.get(patron.home_ou.id);
1008 patron.expire_date = new Date(Date.parse(patron.expire_date));
1009 patron.dob = service.parse_dob(patron.dob);
1010 patron.profile = current.profile(); // pre-hash version
1011 patron.net_access_level = current.net_access_level();
1012 patron.ident_type = current.ident_type();
1013 patron.groups = current.groups(); // pre-hash
1016 ['juvenile', 'barred', 'active', 'master_account'],
1017 function(field) { patron[field] = patron[field] == 't'; }
1020 angular.forEach(patron.cards, function(card) {
1021 card.active = card.active == 't';
1022 if (card.id == patron.card.id) {
1024 card._primary = 'on';
1028 angular.forEach(patron.addresses,
1029 function(addr) { service.ingest_address(patron, addr) });
1031 service.get_linked_addr_users(patron.addresses);
1033 // Remove stat cat entries that link to out-of-scope stat
1034 // cats. With this, we avoid unnecessarily updating (or worse,
1035 // modifying) stat cat values that are not ours to modify.
1036 patron.stat_cat_entries = patron.stat_cat_entries.filter(
1039 // service.stat_cats only contains in-scope stat cats.
1040 service.stat_cats.filter(function(cat) {
1041 return (cat.id() == map.stat_cat.id) })[0]
1046 // toss entries for existing stat cat maps into our living
1047 // stat cat entry map, which is modified within the template.
1048 angular.forEach(patron.stat_cat_entries, function(map) {
1049 service.stat_cat_entry_maps[map.stat_cat.id] = map.stat_cat_entry;
1055 service.init_new_patron = function() {
1057 id : service.virt_id--,
1060 address_type : egCore.strings.REG_ADDR_TYPE,
1063 within_city_limits : false,
1064 country : service.org_settings['ui.patron.default_country'],
1068 id : service.virt_id--,
1074 var home_ou = egCore.org.get(service.org);
1082 stat_cat_entries : [],
1087 if (service.clone_user)
1088 service.copy_clone_data(user);
1090 if (service.stage_user)
1091 service.copy_stage_data(user);
1096 // dob is always YYYY-MM-DD
1097 // Dates of birth do not contain timezone info, which can lead to
1098 // inconcistent timezone handling, potentially representing
1099 // different points in time, depending on the implementation.
1100 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
1101 // See "Differences in assumed time zone"
1102 // TODO: move this into egDate ?
1103 service.parse_dob = function(dob) {
1104 if (!dob) return null;
1105 var parts = dob.split('-');
1106 var d = new Date(); // always local time zone, yay.
1107 d.setFullYear(parts[0]);
1108 d.setMonth(parts[1] - 1);
1109 d.setDate(parts[2]);
1113 service.copy_stage_data = function(user) {
1114 var cuser = service.stage_user;
1116 // copy the data into our new user object
1118 for (var key in egCore.idl.classes.stgu.field_map) {
1119 if (egCore.idl.classes.au.field_map[key] &&
1120 !egCore.idl.classes.stgu.field_map[key].virtual) {
1121 if (cuser.user[key]() !== null)
1122 user[key] = cuser.user[key]();
1126 if (user.home_ou) user.home_ou = egCore.org.get(user.home_ou);
1127 if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
1128 if (user.ident_type)
1129 user.ident_type = egCore.env.cit.map[user.ident_type];
1130 user.dob = service.parse_dob(user.dob);
1132 // Clear the usrname if it looks like a UUID
1133 if (user.usrname.replace(/-/g,'').match(/[0-9a-f]{32}/))
1136 // Don't use stub address if we have one from the staged user.
1137 if (cuser.mailing_addresses.length || cuser.billing_addresses.length)
1138 user.addresses = [];
1140 // is_mailing=false implies is_billing
1141 function addr_from_stage(stage_addr) {
1142 if (!stage_addr) return;
1143 var cls = stage_addr.classname;
1146 id : service.virt_id--,
1150 _is_mailing : cls == 'stgma',
1151 _is_billing : cls == 'stgba'
1154 user.mailing_address = addr;
1155 user.addresses.push(addr);
1157 for (var key in egCore.idl.classes[cls].field_map) {
1158 if (egCore.idl.classes.aua.field_map[key] &&
1159 !egCore.idl.classes[cls].field_map[key].virtual) {
1160 if (stage_addr[key]() !== null)
1161 addr[key] = stage_addr[key]();
1166 addr_from_stage(cuser.mailing_addresses[0]);
1167 addr_from_stage(cuser.billing_addresses[0]);
1169 if (user.addresses.length == 1) {
1170 // If there is only one address,
1171 // use it as both mailing and billing.
1172 var addr = user.addresses[0];
1173 addr._is_mailing = addr._is_billing = true;
1174 user.mailing_address = user.billing_address = addr;
1177 if (cuser.cards.length) {
1179 id : service.virt_id--,
1180 barcode : cuser.cards[0].barcode(),
1186 user.cards.push(user.card);
1187 if (user.usrname == '')
1188 user.usrname = card.barcode;
1191 angular.forEach(cuser.settings, function(setting) {
1192 service.user_settings[setting.setting()] = Boolean(setting.value());
1196 // copy select values from the cloned user to the new user.
1198 service.copy_clone_data = function(user) {
1199 var clone_user = service.clone_user;
1201 // flesh the home org locally
1202 user.home_ou = egCore.org.get(clone_user.home_ou());
1203 if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
1205 if (!clone_user.billing_address() &&
1206 !clone_user.mailing_address())
1207 return; // no addresses to copy or link
1209 // if the cloned user has any addresses, we don't need
1210 // the stub address created in init_new_patron.
1211 user.addresses = [];
1213 var copy_addresses =
1214 service.org_settings['circ.patron_edit.clone.copy_address'];
1216 var clone_fields = [
1223 angular.forEach(clone_fields, function(field) {
1224 user[field] = clone_user[field]();
1227 if (copy_addresses) {
1228 var bill_addr, mail_addr;
1230 // copy the billing and mailing addresses into new addresses
1231 function clone_addr(addr) {
1232 var new_addr = egCore.idl.toHash(addr);
1233 new_addr.id = service.virt_id--;
1234 new_addr.usr = user.id;
1235 new_addr.isnew = true;
1236 new_addr.valid = true;
1237 user.addresses.push(new_addr);
1241 if (bill_addr = clone_user.billing_address()) {
1242 var addr = clone_addr(bill_addr);
1243 addr._is_billing = true;
1244 user.billing_address = addr;
1247 if (mail_addr = clone_user.mailing_address()) {
1249 if (bill_addr && bill_addr.id() == mail_addr.id()) {
1250 user.mailing_address = user.billing_address;
1251 user.mailing_address._is_mailing = true;
1253 var addr = clone_addr(mail_addr);
1254 addr._is_mailing = true;
1255 user.mailing_address = addr;
1259 // if there is no billing addr, use the mailing addr
1260 user.billing_address = user.mailing_address;
1261 user.billing_address._is_billing = true;
1268 // link the billing and mailing addresses
1270 if (addr = clone_user.billing_address()) {
1271 user.billing_address = egCore.idl.toHash(addr);
1272 user.billing_address._is_billing = true;
1273 user.addresses.push(user.billing_address);
1274 user.billing_address._linked_owner_id = clone_user.id();
1275 user.billing_address._linked_owner = service.format_name(
1276 clone_user.family_name(),
1277 clone_user.first_given_name(),
1278 clone_user.second_given_name()
1282 if (addr = clone_user.mailing_address()) {
1283 if (user.billing_address &&
1284 addr.id() == user.billing_address.id) {
1285 // mailing matches billing
1286 user.mailing_address = user.billing_address;
1287 user.mailing_address._is_mailing = true;
1289 user.mailing_address = egCore.idl.toHash(addr);
1290 user.mailing_address._is_mailing = true;
1291 user.addresses.push(user.mailing_address);
1292 user.mailing_address._linked_owner_id = clone_user.id();
1293 user.mailing_address._linked_owner = service.format_name(
1294 clone_user.family_name(),
1295 clone_user.first_given_name(),
1296 clone_user.second_given_name()
1303 // translate the patron back into IDL form
1304 service.save_user = function(phash) {
1306 var patron = egCore.idl.fromHash('au', phash);
1308 patron.home_ou(patron.home_ou().id());
1309 patron.expire_date(patron.expire_date().toISOString());
1310 patron.profile(patron.profile().id());
1312 patron.dob(patron.dob().toISOString().replace(/T.*/,''));
1313 if (patron.ident_type())
1314 patron.ident_type(patron.ident_type().id());
1315 if (patron.net_access_level())
1316 patron.net_access_level(patron.net_access_level().id());
1319 ['juvenile', 'barred', 'active', 'master_account'],
1320 function(field) { patron[field](phash[field] ? 't' : 'f'); }
1323 var card_hashes = patron.cards();
1325 angular.forEach(card_hashes, function(chash) {
1326 var card = egCore.idl.fromHash('ac', chash)
1327 card.usr(patron.id());
1328 card.active(chash.active ? 't' : 'f');
1329 patron.cards().push(card);
1330 if (chash._primary) {
1335 var addr_hashes = patron.addresses();
1336 patron.addresses([]);
1337 angular.forEach(addr_hashes, function(addr_hash) {
1338 if (!addr_hash.isnew && !addr_hash.isdeleted)
1339 addr_hash.ischanged = true;
1340 var addr = egCore.idl.fromHash('aua', addr_hash);
1341 patron.addresses().push(addr);
1342 addr.valid(addr.valid() ? 't' : 'f');
1343 addr.within_city_limits(addr.within_city_limits() ? 't' : 'f');
1344 if (addr_hash._is_mailing) patron.mailing_address(addr);
1345 if (addr_hash._is_billing) patron.billing_address(addr);
1348 patron.survey_responses([]);
1349 angular.forEach(service.survey_responses, function(answer) {
1350 var question = service.survey_questions[answer.question()];
1351 var resp = new egCore.idl.asvr();
1353 resp.survey(question.survey());
1354 resp.question(question.id());
1355 resp.answer(answer.id());
1356 resp.usr(patron.id());
1357 resp.answer_date('now');
1358 patron.survey_responses().push(resp);
1361 // re-object-ify the patron stat cat entry maps
1363 angular.forEach(patron.stat_cat_entries(), function(entry) {
1364 var e = egCore.idl.fromHash('actscecm', entry);
1365 e.stat_cat(e.stat_cat().id);
1368 patron.stat_cat_entries(maps);
1370 // service.stat_cat_entry_maps maps stats to values
1371 // patron.stat_cat_entries is an array of stat_cat_entry_usr_map's
1373 service.stat_cat_entry_maps, function(value, cat_id) {
1375 // see if we already have a mapping for this entry
1376 var existing = patron.stat_cat_entries().filter(
1377 function(e) { return e.stat_cat() == cat_id })[0];
1379 if (existing) { // we have a mapping
1380 // if the existing mapping matches the new one,
1381 // there' nothing left to do
1382 if (existing.stat_cat_entry() == value) return;
1384 // mappings differ. delete the old one and create
1386 existing.isdeleted(true);
1389 var newmap = new egCore.idl.actscecm();
1390 newmap.target_usr(patron.id());
1392 newmap.stat_cat(cat_id);
1393 newmap.stat_cat_entry(value);
1394 patron.stat_cat_entries().push(newmap);
1397 if (!patron.isnew()) patron.ischanged(true);
1399 return egLovefield.addOfflineXact({
1400 user : egCore.idl.toHash(patron),
1401 timestamp : parseInt(new Date().getTime() / 1000),
1404 }).then(function (success) {
1405 if (success) return patron;
1409 service.remove_staged_user = function() {
1410 if (!service.stage_user) return $q.when();
1411 return egCore.net.request(
1413 'open-ils.actor.user.stage.delete',
1414 egCore.auth.token(),
1415 service.stage_user.user.row_id()
1419 service.save_user_settings = function(new_user, user_settings) {
1423 // Applies field-specific validation regex's from org settings
1424 // to form fields. Be careful not remove any pattern data we
1425 // are not explicitly over-writing in the provided patterns obj.
1426 service.set_field_patterns = function(patterns) {
1427 if (service.org_settings['opac.username_regex']) {
1428 patterns.au.usrname =
1429 new RegExp(service.org_settings['opac.username_regex']);
1432 if (service.org_settings['opac.barcode_regex']) {
1433 patterns.ac.barcode =
1434 new RegExp(service.org_settings['opac.barcode_regex']);
1437 if (service.org_settings['global.password_regex']) {
1438 patterns.au.passwd =
1439 new RegExp(service.org_settings['global.password_regex']);
1442 var phone_reg = service.org_settings['ui.patron.edit.phone.regex'];
1444 // apply generic phone regex first, replace below as needed.
1445 patterns.au.day_phone = new RegExp(phone_reg);
1446 patterns.au.evening_phone = new RegExp(phone_reg);
1447 patterns.au.other_phone = new RegExp(phone_reg);
1450 // the remaining patterns fit a well-known key name pattern
1452 angular.forEach(service.org_settings, function(val, key) {
1454 var parts = key.match(/ui.patron.edit\.(\w+)\.(\w+)\.regex/);
1457 var name = parts[2];
1458 patterns[cls][name] = new RegExp(val);
1465 .controller('PatronRegCtrl',
1466 ['$scope','$routeParams','$q','$uibModal','$window','egCore',
1467 'patronSvc','patronRegSvc','egUnloadPrompt','egAlertDialog',
1468 'egWorkLog','$timeout','egLovefield','$rootScope',
1469 function($scope , $routeParams , $q , $uibModal , $window , egCore ,
1470 patronSvc , patronRegSvc , egUnloadPrompt, egAlertDialog ,
1471 egWorkLog , $timeout , egLovefield , $rootScope) {
1473 $scope.rs = $rootScope;
1474 if ($scope.workstation_obj) patronRegSvc.org = $scope.workstation_obj.owning_lib;
1475 $scope.offline = true;
1477 $scope.page_data_loaded = false;
1478 $scope.clone_id = patronRegSvc.clone_id = $routeParams.clone_id;
1479 $scope.stage_username =
1480 patronRegSvc.stage_username = $routeParams.stage_username;
1482 patronRegSvc.patron_id = $routeParams.edit_id || $routeParams.id;
1484 // for existing patrons, disable barcode input by default
1485 $scope.disable_bc = $scope.focus_usrname = Boolean($scope.patron_id);
1486 $scope.focus_bc = !Boolean($scope.patron_id);
1487 $scope.address_alerts = [];
1488 $scope.dupe_counts = {};
1490 // map of perm name to true/false for perms the logged in user
1491 // has at the currently selected patron home org unit.
1494 $scope.edit_passthru = {};
1496 // 0=all, 1=suggested, 2=all
1497 $scope.edit_passthru.vis_level = 2;
1499 // Apply default values for new patrons during initial registration
1500 // prs is shorthand for patronSvc
1501 function set_new_patron_defaults(prs) {
1502 if (!$scope.patron.passwd) {
1503 // passsword may originate from staged user.
1504 $scope.generate_password();
1506 $scope.hold_notify_phone = true;
1507 $scope.hold_notify_email = true;
1509 // staged users may be loaded w/ a profile.
1510 $scope.set_expire_date();
1512 if (prs.org_settings['ui.patron.default_ident_type']) {
1513 // $scope.patron needs this field to be an object
1514 var id = prs.org_settings['ui.patron.default_ident_type'];
1515 var ident_type = $scope.ident_types.filter(
1516 function(type) { return type.id() == id })[0];
1517 $scope.patron.ident_type = ident_type;
1519 if (prs.org_settings['ui.patron.default_inet_access_level']) {
1520 // $scope.patron needs this field to be an object
1521 var id = prs.org_settings['ui.patron.default_inet_access_level'];
1522 var level = $scope.net_access_levels.filter(
1523 function(lvl) { return lvl.id() == id })[0];
1524 $scope.patron.net_access_level = level;
1526 if (prs.org_settings['ui.patron.default_country']) {
1527 $scope.patron.addresses[0].country =
1528 prs.org_settings['ui.patron.default_country'];
1532 // A null or undefined pattern leads to exceptions. Before the
1533 // patterns are loaded from the server, default all patterns
1534 // to an innocuous regex. To avoid re-creating numerous
1535 // RegExp objects, cache the stub RegExp after initial creation.
1536 // note: angular docs say ng-pattern accepts a regexp or string,
1537 // but as of writing, it only works with a regexp object.
1538 // (Likely an angular 1.2 vs. 1.4 issue).
1539 var field_patterns = {au : {}, ac : {}, aua : {}};
1540 $scope.field_pattern = function(cls, field) {
1541 if (!field_patterns[cls][field])
1542 field_patterns[cls][field] = new RegExp('.*');
1543 return field_patterns[cls][field];
1546 patronRegSvc.offlineMode($scope.offline); // force offline if ng-init'd to do so
1547 patronRegSvc.init().then(function() {
1548 // called after initTab and patronRegSvc.init have completed
1550 var prs = patronRegSvc; // brevity
1551 // in standalone mode, we have no patronSvc
1552 $scope.patron = prs.init_patron(patronSvc ? patronSvc.current : null);
1553 $scope.field_doc = prs.field_doc;
1554 $scope.edit_profiles = prs.edit_profiles;
1555 $scope.ident_types = prs.ident_types;
1556 $scope.net_access_levels = prs.net_access_levels;
1557 $scope.user_setting_types = prs.user_setting_types;
1558 $scope.opt_in_setting_types = prs.opt_in_setting_types;
1559 $scope.org_settings = prs.org_settings;
1560 $scope.sms_carriers = prs.sms_carriers;
1561 $scope.stat_cats = prs.stat_cats;
1562 $scope.surveys = prs.surveys;
1563 $scope.survey_responses = prs.survey_responses;
1564 $scope.stat_cat_entry_maps = prs.stat_cat_entry_maps;
1565 $scope.stage_user = prs.stage_user;
1566 $scope.stage_user_requestor = prs.stage_user_requestor;
1568 $scope.user_settings = prs.user_settings;
1569 // clone the user settings back into the patronRegSvc so
1570 // we have a copy of the original state of the settings.
1571 prs.user_settings = {};
1572 angular.forEach($scope.user_settings, function(val, key) {
1573 prs.user_settings[key] = val;
1576 extract_hold_notify();
1577 $scope.handle_home_org_changed();
1579 if ($scope.org_settings['ui.patron.edit.default_suggested'])
1580 $scope.edit_passthru.vis_level = 1;
1582 if ($scope.patron.isnew)
1583 set_new_patron_defaults(prs);
1585 $scope.page_data_loaded = true;
1587 prs.set_field_patterns(field_patterns);
1588 apply_username_regex();
1591 // update the currently displayed field documentation
1592 $scope.set_selected_field_doc = function(cls, field) {
1593 $scope.selected_field_doc = $scope.field_doc[cls][field];
1596 // returns the tree depth of the selected profile group tree node.
1597 $scope.pgt_depth = function(grp) {
1599 while (grp = egCore.env.pgt.map[grp.parent()]) d++;
1603 // IDL fields used for labels in the UI.
1604 $scope.idl_fields = {
1605 au : egCore.idl.classes.au.field_map,
1606 ac : egCore.idl.classes.ac.field_map,
1607 aua : egCore.idl.classes.aua.field_map
1610 // field visibility cache. Some fields are universally required.
1611 // 3 == value universally required
1612 // 2 == field is visible by default
1613 // 1 == field is suggested by default
1614 var field_visibility = {};
1615 var default_field_visibility = {
1619 'au.first_given_name' : 3,
1620 'au.family_name' : 3,
1621 'au.ident_type' : 3,
1624 'au.expire_date' : 3,
1625 'au.net_access_level' : 3,
1626 'aua.address_type' : 3,
1627 'aua.post_code' : 3,
1635 'aua.within_city_limits' : 2,
1640 // Returns true if the selected field should be visible
1641 // given the current required/suggested/all setting.
1642 // The visibility flag applied to each field as a result of calling
1643 // this function also sets (via the same flag) the requiredness state.
1644 $scope.show_field = function(field_key) {
1645 // org settings have not been received yet.
1646 if (!$scope.org_settings) return false;
1648 if (field_visibility[field_key] == undefined) {
1649 // compile and cache the visibility for the selected field
1651 var req_set = 'ui.patron.edit.' + field_key + '.require';
1652 var sho_set = 'ui.patron.edit.' + field_key + '.show';
1653 var sug_set = 'ui.patron.edit.' + field_key + '.suggest';
1655 if ($scope.org_settings[req_set]) {
1656 field_visibility[field_key] = 3;
1658 } else if ($scope.org_settings[sho_set]) {
1659 field_visibility[field_key] = 2;
1661 } else if ($scope.org_settings[sug_set]) {
1662 field_visibility[field_key] = 1;
1666 if (field_visibility[field_key] == undefined) {
1667 // No org settings were applied above. Use the default
1668 // settings if present or assume the field has no
1669 // visibility flags applied.
1670 field_visibility[field_key] =
1671 default_field_visibility[field_key] || 0;
1674 return field_visibility[field_key] >= $scope.edit_passthru.vis_level;
1677 // See $scope.show_field().
1678 // A field with visbility level 3 means it's required.
1679 $scope.field_required = function(cls, field) {
1681 // Value in the password field is not required
1682 // for existing patrons.
1683 if (field == 'passwd' && $scope.patron && !$scope.patron.isnew)
1686 return (field_visibility[cls + '.' + field] == 3 || default_field_visibility[cls + '.' + field] == 3);
1689 // generates a random 4-digit password
1690 $scope.generate_password = function() {
1691 $scope.patron.passwd = Math.floor(Math.random()*9000) + 1000;
1694 $scope.set_expire_date = function() {
1695 if (!$scope.patron.profile) return;
1696 var seconds = egCore.date.intervalToSeconds(
1697 $scope.patron.profile.perm_interval());
1698 var now_epoch = new Date().getTime();
1699 $scope.patron.expire_date = new Date(
1700 now_epoch + (seconds * 1000 /* milliseconds */))
1703 // grp is the pgt object
1704 $scope.set_profile = function(grp) {
1705 $scope.patron.profile = grp;
1706 $scope.set_expire_date();
1707 $scope.field_modified();
1710 $scope.invalid_profile = function() {
1713 $scope.patron.profile &&
1714 $scope.patron.profile.usergroup() == 't'
1718 $scope.new_address = function() {
1719 var addr = egCore.idl.toHash(new egCore.idl.aua());
1720 patronRegSvc.ingest_address($scope.patron, addr);
1721 addr.id = patronRegSvc.virt_id--;
1724 addr.within_city_limits = true;
1725 addr.country = $scope.org_settings['ui.patron.default_country'];
1726 $scope.patron.addresses.push(addr);
1729 // keep deleted addresses out of the patron object so
1730 // they won't appear in the UI. They'll be re-inserted
1731 // when the patron is updated.
1732 deleted_addresses = [];
1733 $scope.delete_address = function(id) {
1735 if ($scope.patron.isnew &&
1736 $scope.patron.addresses.length == 1 &&
1737 $scope.org_settings['ui.patron.registration.require_address']) {
1738 egAlertDialog.open(egCore.strings.REG_ADDR_REQUIRED);
1743 angular.forEach($scope.patron.addresses, function(addr) {
1744 if (addr.id == id) {
1746 addr.isdeleted = true;
1747 deleted_addresses.push(addr);
1750 addresses.push(addr);
1753 $scope.patron.addresses = addresses;
1756 $scope.post_code_changed = function(addr) {
1757 if ($scope.offline) return;
1759 'open-ils.search', 'open-ils.search.zip', addr.post_code)
1760 .then(function(resp) {
1762 if (resp.city) addr.city = resp.city;
1763 if (resp.state) addr.state = resp.state;
1764 if (resp.county) addr.county = resp.county;
1765 if (resp.alert) alert(resp.alert);
1769 $scope.replace_card = function() {
1770 $scope.patron.card.active = false;
1771 $scope.patron.card.ischanged = true;
1772 $scope.disable_bc = false;
1774 var new_card = egCore.idl.toHash(new egCore.idl.ac());
1775 new_card.id = patronRegSvc.virt_id--;
1776 new_card.isnew = true;
1777 new_card.active = true;
1778 new_card._primary = 'on';
1779 $scope.patron.card = new_card;
1780 $scope.patron.cards.push(new_card);
1783 $scope.day_phone_changed = function(phone) {
1784 if (phone && $scope.patron.isnew &&
1785 $scope.org_settings['patron.password.use_phone']) {
1786 $scope.patron.passwd = phone.substr(-4);
1790 $scope.barcode_changed = function(bc) {
1792 if (!$scope.patron.usrname)
1793 $scope.patron.usrname = bc;
1796 $scope.cards_dialog = function() {
1798 templateUrl: './circ/patron/t_patron_cards_dialog',
1801 ['$scope','$uibModalInstance','cards','perms',
1802 function($scope , $uibModalInstance , cards , perms) {
1803 // scope here is the modal-level scope
1804 $scope.args = {cards : cards};
1805 $scope.perms = perms;
1806 $scope.ok = function() { $uibModalInstance.close($scope.args) }
1807 $scope.cancel = function () { $uibModalInstance.dismiss() }
1810 cards : function() {
1811 // scope here is the controller-level scope
1812 return $scope.patron.cards;
1814 perms : function() {
1815 return $scope.perms;
1820 angular.forEach(args.cards, function(card) {
1821 card.ischanged = true; // assume cards need updating, OK?
1822 if (card._primary == 'on' &&
1823 card.id != $scope.patron.card.id) {
1824 $scope.patron.card = card;
1831 $scope.set_addr_type = function(addr, type) {
1832 var addrs = $scope.patron.addresses;
1833 if (addr['_is_'+type]) {
1834 angular.forEach(addrs, function(a) {
1835 if (a.id != addr.id) a['_is_'+type] = false;
1838 // unchecking mailing/billing means we have to randomly
1839 // select another address to fill that role. Select the
1840 // first address in the list (that does not match the
1842 for (var i = 0; i < addrs.length; i++) {
1843 if (addrs[i].id != addr.id) {
1844 addrs[i]['_is_' + type] = true;
1852 // Translate hold notify preferences from the form/scope back into a
1853 // single user setting value for opac.hold_notify.
1854 function compress_hold_notify() {
1855 var hold_notify = '';
1857 if ($scope.hold_notify_phone) {
1858 hold_notify = 'phone';
1861 if ($scope.hold_notify_email) {
1862 hold_notify = splitter + 'email';
1865 if ($scope.hold_notify_sms) {
1866 hold_notify = splitter + 'sms';
1869 $scope.user_settings['opac.hold_notify'] = hold_notify;
1872 // dialog for selecting additional permission groups
1873 $scope.secondary_groups_dialog = function() {
1875 templateUrl: './circ/patron/t_patron_groups_dialog',
1878 ['$scope','$uibModalInstance','linked_groups','pgt_depth',
1879 function($scope , $uibModalInstance , linked_groups , pgt_depth) {
1881 $scope.pgt_depth = pgt_depth;
1883 linked_groups : linked_groups,
1884 edit_profiles : patronRegSvc.edit_profiles,
1885 new_profile : patronRegSvc.edit_profiles[0]
1888 // add a new group to the linked groups list
1889 $scope.link_group = function($event, grp) {
1890 var found = false; // avoid duplicates
1891 angular.forEach($scope.args.linked_groups,
1892 function(g) {if (g.id() == grp.id()) found = true});
1893 if (!found) $scope.args.linked_groups.push(grp);
1894 $event.preventDefault(); // avoid close
1897 // remove a group from the linked groups list
1898 $scope.unlink_group = function($event, grp) {
1899 $scope.args.linked_groups =
1900 $scope.args.linked_groups.filter(function(g) {
1901 return g.id() != grp.id()
1903 $event.preventDefault(); // avoid close
1906 $scope.ok = function() { $uibModalInstance.close($scope.args) }
1907 $scope.cancel = function () { $uibModalInstance.dismiss() }
1910 linked_groups : function() { return $scope.patron.groups },
1911 pgt_depth : function() { return $scope.pgt_depth }
1916 if ($scope.patron.isnew) {
1917 // groups must be linked for new patrons after the
1918 // patron is created.
1919 $scope.patron.groups = args.linked_groups;
1923 // update links groups for existing users in real time.
1924 var ids = args.linked_groups.map(function(g) {return g.id()});
1925 patronRegSvc.apply_secondary_groups($scope.patron.id, ids)
1926 .then(function(success) {
1928 $scope.patron.groups = args.linked_groups;
1934 function extract_hold_notify() {
1935 notify = $scope.user_settings['opac.hold_notify'];
1936 if (!notify) return;
1937 $scope.hold_notify_phone = Boolean(notify.match(/phone/));
1938 $scope.hold_notify_email = Boolean(notify.match(/email/));
1939 $scope.hold_notify_sms = Boolean(notify.match(/sms/));
1942 $scope.invalidate_field = function(field) {
1943 patronRegSvc.invalidate_field($scope.patron, field);
1946 address_alert = function(addr) {
1947 if ($scope.offline) return;
1949 street1: addr.street1,
1950 street2: addr.street2,
1953 county: addr.county,
1954 country: addr.country,
1955 post_code: addr.post_code,
1956 mailing_address: addr._is_mailing,
1957 billing_address: addr._is_billing
1962 'open-ils.actor.address_alert.test',
1963 egCore.auth.token(), egCore.auth.user().ws_ou(), args
1964 ).then(function(res) {
1965 $scope.address_alerts = res;
1969 $scope.dupe_value_changed = function(type, value) {
1970 $scope.dupe_counts[type] = 0;
1971 patronRegSvc.dupe_patron_search($scope.patron, type, value)
1972 .then(function(res) {
1973 $scope.dupe_counts[type] = res.count;
1975 $scope.dupe_search_encoded =
1976 encodeURIComponent(js2JSON(res.search));
1978 $scope.dupe_search_encoded = '';
1983 // Dummy function in offline mode
1984 $scope.handle_home_org_changed = function() {}
1986 // This is called with every character typed in a form field,
1987 // since that's the only way to gaurantee something has changed.
1988 // See handle_field_changed for ng-change vs. ng-blur.
1989 $scope.field_modified = function() {
1990 // Call attach with every field change, regardless of whether
1991 // it's been called before. This will allow for re-attach after
1992 // the user clicks through the unload warning. egUnloadPrompt
1993 // will ensure we only attach once.
1994 egUnloadPrompt.attach($rootScope);
1997 // also monitor when form is changed *by the user*, as using
1998 // an ng-change handler doesn't work with eg-date-input
1999 $scope.$watch('reg_form.$pristine', function(newVal, oldVal) {
2000 if (!newVal) egUnloadPrompt.attach($rootScope);
2003 // username regex (if present) must be removed any time
2004 // the username matches the barcode to avoid firing the
2005 // invalid field handlers.
2006 function apply_username_regex() {
2007 var regex = $scope.org_settings['opac.username_regex'];
2009 if ($scope.patron.card.barcode) {
2010 // username must match the regex or the barcode
2011 field_patterns.au.usrname =
2013 regex + '|^' + $scope.patron.card.barcode + '$');
2015 // username must match the regex
2016 field_patterns.au.usrname = new RegExp(regex);
2019 // username can be any format.
2020 field_patterns.au.usrname = new RegExp('.*');
2024 // obj could be the patron, an address, etc.
2025 // This is called any time a form field achieves then loses focus.
2026 // It does not necessarily mean the field has changed.
2027 // The alternative is ng-change, but it's called with each character
2028 // typed, which would be overkill for many of the actions called here.
2029 $scope.handle_field_changed = function(obj, field_name) {
2032 var cls = obj.classname; // set by egIdl
2033 var value = obj[field_name];
2036 //console.log('changing field ' + field_name + ' to ' + value);
2038 switch (field_name) {
2040 if ($scope.patron.day_phone &&
2041 $scope.patron.isnew &&
2042 $scope.org_settings['patron.password.use_phone']) {
2043 $scope.patron.passwd = phone.substr(-4);
2048 apply_username_regex();
2049 $scope.barcode_changed(value);
2053 maintain_juvenile_flag();
2061 // patron.juvenile is set to true if the user was born after
2062 function maintain_juvenile_flag() {
2063 if ( !($scope.patron && $scope.patron.dob) ) return;
2066 $scope.org_settings['global.juvenile_age_threshold']
2069 var base = new Date();
2071 base.setTime(base.getTime() -
2072 Number(egCore.date.intervalToSeconds(juv_interval) + '000'));
2074 $scope.patron.juvenile = ($scope.patron.dob > base);
2077 // returns true (disable) for orgs that cannot have users.
2078 $scope.disable_home_org = function(org_id) {
2079 if (!org_id) return;
2080 var org = egCore.org.get(org_id);
2084 org.ou_type().can_have_users() == 'f'
2088 // Returns true if the Save and Save & Clone buttons should be disabled.
2089 $scope.edit_passthru.hide_save_actions = function() {
2093 // Returns true if any input elements are tagged as invalid
2094 // via Angular patterns or required attributes.
2095 function form_has_invalid_fields() {
2096 return $('#patron-reg-container .ng-invalid').length > 0;
2099 function form_is_incomplete() {
2101 $scope.dupe_username ||
2102 $scope.dupe_barcode ||
2103 form_has_invalid_fields()
2108 $scope.edit_passthru.save = function(save_args) {
2109 if (!save_args) save_args = {};
2111 if (form_is_incomplete()) {
2112 // User has not provided valid values for all required fields.
2113 return egAlertDialog.open(egCore.strings.REG_INVALID_FIELDS);
2116 // remove page unload warning prompt
2117 egUnloadPrompt.clear();
2119 // toss the deleted addresses back into the patron's list of
2120 // addresses so it's included in the update
2121 $scope.patron.addresses =
2122 $scope.patron.addresses.concat(deleted_addresses);
2124 compress_hold_notify();
2128 patronRegSvc.save_user($scope.patron)
2129 .then($scope.rs.save_offline_xacts)
2130 .then(function(new_user) {
2131 // reload the current page
2132 $window.location.href = location.href;