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?|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.refreshSessions = function () {
131 return $http.get(formURL({action:'status',status_type:'sessions'})).then(function(res) {
133 $scope.sessions = res.data;
138 var creator_list = [$q.when()];
139 angular.forEach($scope.sessions, function (s) {
141 s.org = egCore.org.get(s.org).shortname();
142 creator_list.push(egCore.pcrud.retrieve('au',s.creator).then(function(u) {
143 s.creator = u.family_name();
145 angular.forEach(s.scripts, function(sc) {
150 return $q.all(creator_list);
154 $scope.reprintLast = function () {
155 egCore.print.reprintLast();
159 $scope.uploadPending = function (s, ind) {
160 return $scope.setSession(s, ind).then(function() {
162 egProgressDialog.open();
163 return $scope.createOfflineXactBlob().then(function(blob) {
165 var form = new FormData();
166 form.append("ses", egCore.auth.token());
167 form.append("org", $scope.org.id());
168 form.append("ws", $scope.current_workstation_name());
169 form.append("wc", 1);
170 form.append("action", "load");
171 form.append("seskey", $scope.current_session.key);
172 form.append("file", blob, "file");
175 '/cgi-bin/offline/offline.pl?' + new Date().getTime(),
178 transformRequest: angular.identity,
179 headers: {'Content-Type': undefined}
181 ).then(function(res) {
182 egProgressDialog.close();
183 if (res.data.ilsevent == "0") {
184 return $scope.clear_pending(true).then(function() {
185 return $scope.refreshSessions();
188 ngToast.warning(egCore.strings.OFFLINE_SESSION_UPLOAD_FAILED);
189 return $scope.refreshSessions();
191 },function () { egProgressDialog.close() });
196 $scope.retrieveDetails = function (x) {
197 alert(JSON.stringify(x, null, 2)); // egAlertDialog kills pretty printing
200 $scope.retrieveItem = function (bc) {
201 return egCore.pcrud.search('acp',{deleted: 'f', barcode: bc}).then(function(copy) {
204 egCore.env.basePath +
205 '/cat/item/' + copy.id(),
210 ngToast.warning(egCore.strings.ITEM_NOT_FOUND);
214 $scope.retrievePatron = function (bc) {
215 return egCore.pcrud.search('ac',{barcode: bc}).then(function(card) {
218 egCore.env.basePath +
219 '/circ/patron/' + card.usr() + '/checkout',
224 ngToast.warning(egCore.strings.PATRON_NOT_FOUND);
228 function formURL (params) {
229 var url = '/cgi-bin/offline/offline.pl?' + new Date().getTime();
232 org : $scope.org ? $scope.org.id() : null,
233 ws : $scope.current_workstation_name(),
235 ses : egCore.auth.token()
238 angular.extend(params, defaults)
241 for (var k in params) {
242 url += '&' + k + '=' + window.encodeURIComponent(params[k]);
247 $scope.$watch('org',function(n){if (n) $scope.refreshSessions()});
252 .controller('OfflineCtrl',
253 ['$q','$scope','$window','$location','$rootScope','egCore','egLovefield','$routeParams','$timeout','$http','ngToast','egConfirmDialog','egUnloadPrompt',
254 function($q , $scope , $window , $location , $rootScope , egCore , egLovefield , $routeParams , $timeout , $http , ngToast , egConfirmDialog , egUnloadPrompt) {
255 $scope.active_tab = $routeParams.tab || 'checkout';
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 return $location.path(path.replace('session','checkout'));
265 var today = new Date();
269 today.setMilliseconds(0);
271 $scope.minDate = today;
272 $scope.blocked_patron = null;
273 $scope.bad_barcode = null;
274 $scope.barcode_type = 'barcode';
275 $scope.focusMe = true;
276 $scope.shared = { outOfRange : false, due_date : null, due_date_offset : '' };
277 $scope.workstation_obj = null;
278 $scope.workstation = '';
279 $scope.workstation_owner = '';
280 $scope.workstations = [];
282 $scope.do_print = Boolean($scope.active_tab == 'checkout');
283 $scope.do_print_changed = false;
284 $scope.printed = false;
286 $scope.imported_pending_xacts = { data : '' };
288 $scope.xact_page = { checkin:[], checkout:[], renew:[], in_house_use:[] };
289 $scope.all_xact = [];
292 $scope.checkout = { noncat_type : '' };
293 $scope.renew = { noncat_type : '' };
294 $scope.in_house_use = {count : 1};
295 $scope.checkin = { backdate : new Date() };
297 $scope.current_workstation_owning_lib = function () {
298 return $scope.workstations.filter(function(w) {
299 return $scope.workstation == w.id
303 $scope.current_workstation_name = function () {
304 return $scope.workstations.filter(function(w) {
305 return $scope.workstation == w.id
309 $scope.$watch('workstation', function (n,o) {
311 $scope.org = egCore.org.get($scope.current_workstation_owning_lib());
314 $scope.changeCheck = function () {
315 $scope.strict_barcode = !$scope.strict_barcode;
316 $scope.do_check_changed = true;
317 egCore.hatch.setItem('eg.offline.strict_barcode', $scope.strict_barcode)
320 $scope.changePrint = function () {
321 $scope.do_print = !$scope.do_print;
322 $scope.do_print_changed = true;
323 egCore.hatch.setItem('eg.offline.print_receipt', $scope.do_print)
326 $scope.logged_in = egCore.auth.token() ? true : false;
328 if (!$scope.logged_in && $routeParams.tab == 'session')
329 $scope.active_tab = 'checkout';
331 egCore.hatch.getItem('eg.offline.print_receipt')
332 .then(function(setting) {
333 $scope.do_print = setting;
334 if (setting !== undefined) $scope.do_print_changed = true;
337 egCore.hatch.getItem('eg.offline.strict_barcode')
338 .then(function(setting) {
339 $scope.strict_barcode = setting;
340 if (setting !== undefined) $scope.do_check_changed = true;
343 egCore.hatch.getItem('eg.workstation.all')
344 .then(function(all) {
345 if (all && all.length) {
346 $scope.workstations = all;
348 if (ws = $location.search().ws) {
349 // user requested a workstation via URL
350 var match = all.filter(
351 function(w) {return ws == w.name} )[0];
354 // requested WS registered on this client
355 $scope.workstation = match.id;
357 // the requested WS is not registered on this client
358 $scope.wsNotRegistered = true;
361 // no workstation requested; use the default
362 egCore.hatch.getItem('eg.workstation.default')
364 var ws_obj = all.filter(function(w) {
368 $scope.workstation_obj = ws_obj;
369 $scope.workstation = ws_obj.id;
370 $scope.workstation_owner = ws_obj.owning_lib;
372 return egLovefield.reconstituteList('cnct').then(function () {
373 $scope.noncats = egCore.env.cnct.list;
380 $scope.downloadBlockList = function () {
381 var url = '/standalone/list.txt?ses='
382 + egCore.auth.token()
383 + '&' + new Date().getTime();
384 return $http.get(url).then(
387 var lines = res.data.split('\n');
388 egLovefield.destroyOfflineBlocks().then(function(){
389 angular.forEach(lines, function (l) {
390 var parts = l.split(' ');
391 egLovefield.addOfflineBlock(parts[0], parts[1]);
395 ngToast.create(egCore.strings.OFFLINE_BLOCKLIST_SUCCESS);
399 ngToast.warning(egCore.strings.OFFLINE_BLOCKLIST_FAIL);
400 egCore.audio.play('warning.offline.blocklist_fail');
405 $scope.createOfflineXactBlob = function () {
406 return egLovefield.retrievePendingOfflineXacts().then(function(list) {
408 angular.forEach(list, function (i) {
409 flat_list.push(JSON.stringify(i) + '\n');
412 var blob = new Blob(flat_list, {type: 'text/plain'});
418 $scope.pending_xacts = [];
419 $scope.retrieve_pending = function () {
420 return egLovefield.retrievePendingOfflineXacts().then(function(list) {
421 $scope.pending_xacts = list;
422 return $q.when(list);
426 $scope.save = function () {
427 var promises = [$q.when()];
428 angular.forEach($scope.all_xact, function (x) {
429 promises.push(egLovefield.addOfflineXact(x));
432 var prints = [$q.when()];
433 if ($scope.do_print) {
434 angular.forEach(['checkin','checkout','renew','in_house_use'], function(xtype) {
435 if ($scope.xact_page[xtype].length > 0) {
436 prints.push(egCore.print.print({
438 template : 'offline_'+xtype,
440 transactions : $scope.xact_page[xtype]
447 return $q.all(promises.concat(prints)).finally(function() {
448 egUnloadPrompt.clear();
449 if (prints.length > 1) $scope.printed = true;
450 $scope.all_xact = [];
451 $scope.xact_page = { checkin:[], checkout:[], renew:[], in_house_use:[] };
452 angular.forEach(['checkout','renew'], function (xtype) {
453 $scope[xtype].patron_barcode = '';
455 $scope.retrieve_pending();
459 $rootScope.save_offline_xacts = function () { return $scope.save() };
460 $rootScope.active_tab = function (t) { $scope.active_tab = t };
462 $scope.logout = function () {
463 egCore.auth.logout();
464 $window.location.href = location.href;
467 $scope.clear_pending = function (skip_confirm) {
469 return egLovefield.destroyPendingOfflineXacts().then(function () {
470 return $scope.retrieve_pending();
473 return egConfirmDialog.open(
474 egCore.strings.CONFIRM_CLEAR_PENDING,
475 egCore.strings.CONFIRM_CLEAR_PENDING_BODY,
477 ).result.then(function() {
478 return egLovefield.destroyPendingOfflineXacts().then(function () {
479 return $scope.retrieve_pending();
485 $scope.retrieve_pending();
486 $scope.$watch('active_tab', function (n,o) {
487 if (n != o && !$scope.do_check_changed && n != 'checkout') $scope.strict_barcode = false;
488 if (n != o && !$scope.do_check_changed && n == 'checkout') $scope.strict_barcode = true;
489 if (n != o && !$scope.do_print_changed && n != 'checkout') $scope.do_print = false;
490 if (n != o && !$scope.do_print_changed && n == 'checkout') $scope.do_print = true;
491 if (n != o && n == 'session') $scope.retrieve_pending();
494 $scope.$watch('imported_pending_xacts.data', function (n, o) {
496 var lines = n.split('\n');
499 angular.forEach(lines, function (l) {
504 egLovefield.addOfflineXact(JSON.parse(l))
507 ngToast.warning(err);
511 $q.all(promises).then(function () { $scope.retrieve_pending() });
515 $scope.resetDueDate = function (xtype) {
516 $scope.shared.due_date = new Date();
517 $scope.shared.due_date.setDate($scope.shared.due_date.getDate() + parseInt($scope.shared.due_date_offset));
520 $scope.notEnough = function (xtype) {
522 if (xtype == 'checkout') {
523 if ($scope.shared.outOfRange) return true;
525 $scope.checkout.patron_barcode &&
526 ($scope.shared.due_date || $scope.shared.due_date_offset) &&
527 ($scope.checkout.barcode || ($scope.checkout.noncat_type && $scope.checkout.noncat_count))
532 if (xtype == 'renew') {
533 if ($scope.shared.outOfRange) return true;
535 $scope.renew.barcode &&
536 ($scope.shared.due_date || $scope.shared.due_date_offset)
541 if (xtype == 'in_house_use') {
543 $scope.in_house_use.barcode && $scope.in_house_use.count
548 if (xtype == 'checkin') {
550 $scope.checkin.barcode && $scope.checkin.backdate
556 $scope.clear = function (xtype) {
558 if (xtype=="in_house_use") $scope[xtype].count = 1;
561 $scope.add = function (xtype,next_focus) {
563 var barcode = $scope[xtype].barcode;
565 if ($scope.xact_page[xtype].filter(function(x){ return x.barcode == barcode }).length > 0) {
566 ngToast.warning(egCore.strings.DUPLICATE_BARCODE);
567 egCore.audio.play('warning.offline.duplicate_barcode');
568 $scope[xtype].barcode = '';
569 if (next_focus) $('#'+next_focus).focus();
574 var pbarcode = $scope[xtype].patron_barcode;
576 egLovefield.testOfflineBlock(pbarcode).then(function (blocked) {
578 egCore.audio.play('warning.offline.blocked_patron');
579 egConfirmDialog.open(
580 egCore.strings.PATRON_BLOCKED,
581 egCore.strings.PATRON_BLOCKED_WHY[blocked],
582 {}, egCore.strings.ALLOW, egCore.strings.REJECT
584 function(){ // forced
585 $scope.blocked_patron = null;
586 _add_impl(xtype,true)
587 if (next_focus) $('#'+next_focus).focus();
588 },function(){ // stopped
589 $scope.blocked_patron = xtype;
590 if (next_focus) $('#'+next_focus).focus();
595 $scope.blocked_patron = null;
596 _add_impl(xtype,true)
597 if (next_focus) $('#'+next_focus).focus();
602 if (next_focus) $('#'+next_focus).focus();
606 function _add_impl (xtype,digest) {
607 var pbarcode = $scope[xtype].patron_barcode;
608 var backdate = $scope[xtype].backdate;
610 if ($scope.strict_barcode && pbarcode) {
611 if (!check_barcode(pbarcode)) {
612 $scope.bad_barcode = xtype;
613 egCore.audio.play('warning.offline.bad_barcode');
614 return egConfirmDialog.open(
615 egCore.strings.BAD_PATRON_BARCODE,
616 egCore.strings.BAD_PATRON_BARCODE_CD,
617 {}, egCore.strings.ALLOW, egCore.strings.REJECT
619 function(){ // forced
620 $scope.blocked_patron = null;
621 return _add_impl2(xtype,digest)
622 },function(){ // stopped
623 $scope.blocked_patron = xtype;
629 if ($scope.strict_barcode && $scope[xtype].barcode) {
630 if (!check_barcode($scope[xtype].barcode)) {
631 $scope.bad_barcode = xtype;
632 egCore.audio.play('warning.offline.bad_barcode');
633 return egConfirmDialog.open(
634 egCore.strings.BAD_BARCODE,
635 egCore.strings.BAD_BARCODE_CD,
636 {}, egCore.strings.ALLOW, egCore.strings.REJECT
638 function(){ // forced
639 $scope.blocked_patron = null;
640 return _add_impl2(xtype,digest)
641 },function(){ // stopped
642 $scope.blocked_patron = xtype;
648 return _add_impl2(xtype,digest);
651 function _add_impl2 (xtype,digest) {
652 var pbarcode = $scope[xtype].patron_barcode;
653 var backdate = $scope[xtype].backdate;
655 $scope.bad_barcode = null;
657 var now = new Date().getTime();
660 if ($scope[xtype].noncat_type) $scope[xtype].noncat = 1;
662 if ($scope.shared.due_date && (xtype == 'checkout' || xtype == 'renew')) {
663 $scope[xtype].due_date = $scope.shared.due_date.toISOString();
664 $scope[xtype].checkout_time = new Date().toISOString();
667 var xact = { timestamp : parseInt(now), type : xtype, delta : 0 };
669 $scope.xact_page[xtype].push(
670 angular.extend(xact, $scope[xtype])
673 $scope.all_xact.push(xact)
674 egUnloadPrompt.attach($rootScope);
678 if (pbarcode) $scope[xtype].patron_barcode = pbarcode;
679 if (backdate) $scope[xtype].backdate = backdate;
680 if (xtype=="in_house_use") $scope[xtype].count = 1;
682 if (digest) $timeout(function(){$scope.$apply()});
685 check_barcode = function(bc) {
686 if (bc != Number(bc)) return false;
688 // "16.00" == Number("16.00"), but the . is bad.
689 // Throw out any barcode that isn't just digits
690 if (bc.search(/\D/) != -1) return false;
691 var last_digit = bc.substr(bc.length-1);
692 var stripped_barcode = bc.substr(0,bc.length-1);
693 return barcode_checkdigit(stripped_barcode).toString() == last_digit;
696 barcode_checkdigit = function(bc) {
697 var reverse_barcode = bc.toString().split('').reverse();
698 var check_sum = 0; var multiplier = 2;
699 for (var i = 0; i < reverse_barcode.length; i++) {
700 var digit = reverse_barcode[i];
701 var product = digit * multiplier; product = product.toString();
703 for (var j = 0; j < product.length; j++) {
704 temp_sum += Number( product[j] );
706 check_sum += Number( temp_sum );
707 multiplier = ( multiplier == 2 ? 1 : 2 );
709 check_sum = check_sum.toString();
710 var next_multiple_of_10 = (check_sum.match(/(\d*)\d$/)[1] * 10) + 10;
711 var check_digit = next_multiple_of_10 - Number(check_sum);
712 if (check_digit == 10) check_digit = 0;
719 // dummy service so standalone patron editor can reference it
720 .factory('patronSvc', function() { return { /* dummy */ } })
722 .factory('patronRegSvc', ['$q', 'egCore', 'egLovefield', function($q, egCore, egLovefield) {
724 egLovefield.isOffline = true;
727 org : null, // will come from workstation org
728 field_doc : {}, // config.idl_field_doc
729 profiles : [], // permission groups
730 edit_profiles : [], // perm groups we can modify
732 user_settings : {}, // applied user settings
733 user_setting_types : {}, // config.usr_setting_type
734 opt_in_setting_types : {}, // config.usr_setting_type for event-def opt-in
736 survey_questions : {},
738 survey_responses : {}, // survey.responses for loaded patron in progress
740 stat_cat_entry_maps : {}, // cat.id to selected value
741 virt_id : -1, // virtual ID for new objects
742 init_done : false // have we loaded our initialization data?
745 service.offlineMode = function () {
749 // launch a series of parallel data retrieval calls
750 service.init = function(scope) {
752 // Data loaded here only needs to be retrieved the first time this
753 // tab becomes active within the current instance of the patron app.
754 // In other words, navigating between patron tabs will not cause
755 // all of this data to be reloaded. Navigating to a separate app
756 // and returning will cause the data to be reloaded.
757 if (service.init_done) return $q.when();
758 service.init_done = true;
761 service.get_field_doc(),
762 service.get_perm_groups(),
763 service.get_ident_types(),
764 service.get_user_settings(),
765 service.get_org_settings(),
766 service.get_stat_cats(),
767 service.get_surveys(),
768 service.get_net_access_levels()
772 service.get_linked_addr_users = function(addrs) {
776 service.apply_secondary_groups = function(user_id, group_ids) {
777 return $q.when(true);
780 // See note above about not loading egUser.
782 service.format_name = function(last, first, middle) {
783 return last + ', ' + first + (middle ? ' ' + middle : '');
786 service.check_dupe_username = function(usrname) {
787 return $q.when(false);
790 // determine which user groups our user is not allowed to modify
791 service.set_edit_profiles = function() {
792 service.edit_profiles = egCore.env.pgt.list.filter(
793 function (p) { return p.application_perm() == 'group_application.user.patron' }
798 // resolves to a hash of perm-name => boolean value indicating
799 // wether the user has the permission at org_id.
800 service.has_perms_for_org = function(org_id) {
805 'CREATE_USER_GROUP_LINK',
806 'UPDATE_PATRON_COLLECTIONS_EXEMPT',
807 'UPDATE_PATRON_CLAIM_RETURN_COUNT',
808 'UPDATE_PATRON_CLAIM_NEVER_CHECKED_OUT_COUNT',
809 'UPDATE_PATRON_ACTIVE_CARD',
810 'UPDATE_PATRON_PRIMARY_CARD'
814 angular.forEach(perms_needed, function (p) {
818 return $q.when(hash);
821 service.get_surveys = function() {
822 return egLovefield.reconstituteList('asv').then(function(offline) {
823 return egLovefield.reconstituteList('asvq')
825 return egLovefield.reconstituteList('asva');
827 angular.forEach(egCore.env.asv.list, function (s) {
828 s.questions( egCore.env.asva.list.filter( function (a) {
829 return q.survey().id == s.id();
833 angular.forEach(egCore.env.asvq.list, function (q) {
834 q.survey( egCore.env.asv.map[ q.survey().id ] );
835 q.answers( egCore.env.asva.list.filter( function (a) {
836 return q.id() == a.question();
840 angular.forEach(egCore.env.asva.list, function (a) {
841 a.question( egCore.env.asvq.map[ a.question().id ] );
844 service.surveys = egCore.env.asv.list;
845 service.survey_questions = egCore.env.asvq.list;
846 service.survey_answers = egCore.env.asva.list;
853 service.get_stat_cats = function() {
854 return egLovefield.getStatCatsCache().then(
856 service.stat_cats = cats;
862 service.get_org_settings = function() {
863 return egLovefield.getSettingsCache().then(
866 angular.forEach(list, function (s) {
867 hash[s.name] = s.value;
869 service.org_settings = hash;
870 if (egCore && egCore.env && !egCore.env.aous) {
871 egCore.env.aous = hash;
872 console.log('setting egCore.env.aous');
879 service.get_ident_types = function() {
880 return egLovefield.reconstituteList('cit').then(function() {
881 service.ident_types = egCore.env.cit.list;
886 service.get_net_access_levels = function() {
887 return egLovefield.reconstituteList('cnal').then(function() {
888 service.net_access_levels = egCore.env.cnal.list;
893 service.get_perm_groups = function() {
894 if (egCore.env.pgt) {
895 service.profiles = egCore.env.pgt.list;
896 return service.set_edit_profiles();
898 return egLovefield.reconstituteTree('pgt').then(function(offline) {
899 service.profiles = egCore.env.pgt.list;
900 return service.set_edit_profiles();
905 service.get_field_doc = function() {
906 return egLovefield.getListFromOfflineCache('fdoc').then(function (list) {
907 angular.forEach(list, function(doc) {
908 service.field_doc[doc.fm_class()][doc.field()] = doc;
914 service.get_user_settings = function() {
916 'circ.holds_behind_desk',
917 'circ.collections.exempt',
919 'opac.default_phone',
920 'opac.default_pickup_location',
921 'opac.default_sms_carrier',
922 'opac.default_sms_notify'];
924 angular.forEach(static_types, function (t) {
925 service.user_settings[t] = null;
928 return egLovefield.getListFromOfflineCache('cust').then(function (list) {
929 angular.forEach(list, function(stype) {
930 service.user_setting_types[stype.name()] = stype;
931 if (static_types.indexOf(stype.name()) == -1) {
932 service.opt_in_setting_types[stype.name()] = stype;
934 if (stype.reg_default() != undefined) {
935 service.user_settings[setting.name()] =
936 setting.reg_default();
943 service.invalidate_field = function(patron, field) {
947 service.dupe_patron_search = function(patron, type, value) {
948 return $q.when({ search : search, count : 0 });
951 service.init_patron = function(current) {
954 return service.init_new_patron();
956 service.patron = current;
957 return service.init_existing_patron(current)
960 service.ingest_address = function(patron, addr) {
961 addr.valid = addr.valid == 't';
962 addr.within_city_limits = addr.within_city_limits == 't';
963 addr._is_mailing = (patron.mailing_address &&
964 addr.id == patron.mailing_address.id);
965 addr._is_billing = (patron.billing_address &&
966 addr.id == patron.billing_address.id);
970 * Existing patron objects reqire some data munging before insertion
973 * 1. Turn everything into a hash
974 * 2. ... Except certain fields (selectors) whose widgets require objects
975 * 3. Bools must be Boolean, not t/f.
977 service.init_existing_patron = function(current) {
979 service.existing_patron = current;
981 var patron = egCore.idl.toHash(current);
983 patron.home_ou = egCore.org.get(patron.home_ou.id);
984 patron.expire_date = new Date(Date.parse(patron.expire_date));
985 patron.dob = service.parse_dob(patron.dob);
986 patron.profile = current.profile(); // pre-hash version
987 patron.net_access_level = current.net_access_level();
988 patron.ident_type = current.ident_type();
989 patron.groups = current.groups(); // pre-hash
992 ['juvenile', 'barred', 'active', 'master_account'],
993 function(field) { patron[field] = patron[field] == 't'; }
996 angular.forEach(patron.cards, function(card) {
997 card.active = card.active == 't';
998 if (card.id == patron.card.id) {
1000 card._primary = 'on';
1004 angular.forEach(patron.addresses,
1005 function(addr) { service.ingest_address(patron, addr) });
1007 service.get_linked_addr_users(patron.addresses);
1009 // Remove stat cat entries that link to out-of-scope stat
1010 // cats. With this, we avoid unnecessarily updating (or worse,
1011 // modifying) stat cat values that are not ours to modify.
1012 patron.stat_cat_entries = patron.stat_cat_entries.filter(
1015 // service.stat_cats only contains in-scope stat cats.
1016 service.stat_cats.filter(function(cat) {
1017 return (cat.id() == map.stat_cat.id) })[0]
1022 // toss entries for existing stat cat maps into our living
1023 // stat cat entry map, which is modified within the template.
1024 angular.forEach(patron.stat_cat_entries, function(map) {
1025 service.stat_cat_entry_maps[map.stat_cat.id] = map.stat_cat_entry;
1031 service.init_new_patron = function() {
1033 id : service.virt_id--,
1036 address_type : egCore.strings.REG_ADDR_TYPE,
1039 within_city_limits : false,
1040 country : service.org_settings['ui.patron.default_country'],
1044 id : service.virt_id--,
1050 var home_ou = egCore.org.get(service.org);
1058 stat_cat_entries : [],
1063 if (service.clone_user)
1064 service.copy_clone_data(user);
1066 if (service.stage_user)
1067 service.copy_stage_data(user);
1072 // dob is always YYYY-MM-DD
1073 // Dates of birth do not contain timezone info, which can lead to
1074 // inconcistent timezone handling, potentially representing
1075 // different points in time, depending on the implementation.
1076 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
1077 // See "Differences in assumed time zone"
1078 // TODO: move this into egDate ?
1079 service.parse_dob = function(dob) {
1080 if (!dob) return null;
1081 var parts = dob.split('-');
1082 var d = new Date(); // always local time zone, yay.
1083 d.setFullYear(parts[0]);
1084 d.setMonth(parts[1] - 1);
1085 d.setDate(parts[2]);
1089 service.copy_stage_data = function(user) {
1090 var cuser = service.stage_user;
1092 // copy the data into our new user object
1094 for (var key in egCore.idl.classes.stgu.field_map) {
1095 if (egCore.idl.classes.au.field_map[key] &&
1096 !egCore.idl.classes.stgu.field_map[key].virtual) {
1097 if (cuser.user[key]() !== null)
1098 user[key] = cuser.user[key]();
1102 if (user.home_ou) user.home_ou = egCore.org.get(user.home_ou);
1103 if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
1104 if (user.ident_type)
1105 user.ident_type = egCore.env.cit.map[user.ident_type];
1106 user.dob = service.parse_dob(user.dob);
1108 // Clear the usrname if it looks like a UUID
1109 if (user.usrname.replace(/-/g,'').match(/[0-9a-f]{32}/))
1112 // Don't use stub address if we have one from the staged user.
1113 if (cuser.mailing_addresses.length || cuser.billing_addresses.length)
1114 user.addresses = [];
1116 // is_mailing=false implies is_billing
1117 function addr_from_stage(stage_addr) {
1118 if (!stage_addr) return;
1119 var cls = stage_addr.classname;
1122 id : service.virt_id--,
1126 _is_mailing : cls == 'stgma',
1127 _is_billing : cls == 'stgba'
1130 user.mailing_address = addr;
1131 user.addresses.push(addr);
1133 for (var key in egCore.idl.classes[cls].field_map) {
1134 if (egCore.idl.classes.aua.field_map[key] &&
1135 !egCore.idl.classes[cls].field_map[key].virtual) {
1136 if (stage_addr[key]() !== null)
1137 addr[key] = stage_addr[key]();
1142 addr_from_stage(cuser.mailing_addresses[0]);
1143 addr_from_stage(cuser.billing_addresses[0]);
1145 if (user.addresses.length == 1) {
1146 // If there is only one address,
1147 // use it as both mailing and billing.
1148 var addr = user.addresses[0];
1149 addr._is_mailing = addr._is_billing = true;
1150 user.mailing_address = user.billing_address = addr;
1153 if (cuser.cards.length) {
1155 id : service.virt_id--,
1156 barcode : cuser.cards[0].barcode(),
1162 user.cards.push(user.card);
1163 if (user.usrname == '')
1164 user.usrname = card.barcode;
1167 angular.forEach(cuser.settings, function(setting) {
1168 service.user_settings[setting.setting()] = Boolean(setting.value());
1172 // copy select values from the cloned user to the new user.
1174 service.copy_clone_data = function(user) {
1175 var clone_user = service.clone_user;
1177 // flesh the home org locally
1178 user.home_ou = egCore.org.get(clone_user.home_ou());
1179 if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
1181 if (!clone_user.billing_address() &&
1182 !clone_user.mailing_address())
1183 return; // no addresses to copy or link
1185 // if the cloned user has any addresses, we don't need
1186 // the stub address created in init_new_patron.
1187 user.addresses = [];
1189 var copy_addresses =
1190 service.org_settings['circ.patron_edit.clone.copy_address'];
1192 var clone_fields = [
1199 angular.forEach(clone_fields, function(field) {
1200 user[field] = clone_user[field]();
1203 if (copy_addresses) {
1204 var bill_addr, mail_addr;
1206 // copy the billing and mailing addresses into new addresses
1207 function clone_addr(addr) {
1208 var new_addr = egCore.idl.toHash(addr);
1209 new_addr.id = service.virt_id--;
1210 new_addr.usr = user.id;
1211 new_addr.isnew = true;
1212 new_addr.valid = true;
1213 user.addresses.push(new_addr);
1217 if (bill_addr = clone_user.billing_address()) {
1218 var addr = clone_addr(bill_addr);
1219 addr._is_billing = true;
1220 user.billing_address = addr;
1223 if (mail_addr = clone_user.mailing_address()) {
1225 if (bill_addr && bill_addr.id() == mail_addr.id()) {
1226 user.mailing_address = user.billing_address;
1227 user.mailing_address._is_mailing = true;
1229 var addr = clone_addr(mail_addr);
1230 addr._is_mailing = true;
1231 user.mailing_address = addr;
1235 // if there is no billing addr, use the mailing addr
1236 user.billing_address = user.mailing_address;
1237 user.billing_address._is_billing = true;
1244 // link the billing and mailing addresses
1246 if (addr = clone_user.billing_address()) {
1247 user.billing_address = egCore.idl.toHash(addr);
1248 user.billing_address._is_billing = true;
1249 user.addresses.push(user.billing_address);
1250 user.billing_address._linked_owner_id = clone_user.id();
1251 user.billing_address._linked_owner = service.format_name(
1252 clone_user.family_name(),
1253 clone_user.first_given_name(),
1254 clone_user.second_given_name()
1258 if (addr = clone_user.mailing_address()) {
1259 if (user.billing_address &&
1260 addr.id() == user.billing_address.id) {
1261 // mailing matches billing
1262 user.mailing_address = user.billing_address;
1263 user.mailing_address._is_mailing = true;
1265 user.mailing_address = egCore.idl.toHash(addr);
1266 user.mailing_address._is_mailing = true;
1267 user.addresses.push(user.mailing_address);
1268 user.mailing_address._linked_owner_id = clone_user.id();
1269 user.mailing_address._linked_owner = service.format_name(
1270 clone_user.family_name(),
1271 clone_user.first_given_name(),
1272 clone_user.second_given_name()
1279 // translate the patron back into IDL form
1280 service.save_user = function(phash) {
1282 var patron = egCore.idl.fromHash('au', phash);
1284 patron.home_ou(patron.home_ou().id());
1285 patron.expire_date(patron.expire_date().toISOString());
1286 patron.profile(patron.profile().id());
1288 patron.dob(patron.dob().toISOString().replace(/T.*/,''));
1289 if (patron.ident_type())
1290 patron.ident_type(patron.ident_type().id());
1291 if (patron.net_access_level())
1292 patron.net_access_level(patron.net_access_level().id());
1295 ['juvenile', 'barred', 'active', 'master_account'],
1296 function(field) { patron[field](phash[field] ? 't' : 'f'); }
1299 var card_hashes = patron.cards();
1301 angular.forEach(card_hashes, function(chash) {
1302 var card = egCore.idl.fromHash('ac', chash)
1303 card.usr(patron.id());
1304 card.active(chash.active ? 't' : 'f');
1305 patron.cards().push(card);
1306 if (chash._primary) {
1311 var addr_hashes = patron.addresses();
1312 patron.addresses([]);
1313 angular.forEach(addr_hashes, function(addr_hash) {
1314 if (!addr_hash.isnew && !addr_hash.isdeleted)
1315 addr_hash.ischanged = true;
1316 var addr = egCore.idl.fromHash('aua', addr_hash);
1317 patron.addresses().push(addr);
1318 addr.valid(addr.valid() ? 't' : 'f');
1319 addr.within_city_limits(addr.within_city_limits() ? 't' : 'f');
1320 if (addr_hash._is_mailing) patron.mailing_address(addr);
1321 if (addr_hash._is_billing) patron.billing_address(addr);
1324 patron.survey_responses([]);
1325 angular.forEach(service.survey_responses, function(answer) {
1326 var question = service.survey_questions[answer.question()];
1327 var resp = new egCore.idl.asvr();
1329 resp.survey(question.survey());
1330 resp.question(question.id());
1331 resp.answer(answer.id());
1332 resp.usr(patron.id());
1333 resp.answer_date('now');
1334 patron.survey_responses().push(resp);
1337 // re-object-ify the patron stat cat entry maps
1339 angular.forEach(patron.stat_cat_entries(), function(entry) {
1340 var e = egCore.idl.fromHash('actscecm', entry);
1341 e.stat_cat(e.stat_cat().id);
1344 patron.stat_cat_entries(maps);
1346 // service.stat_cat_entry_maps maps stats to values
1347 // patron.stat_cat_entries is an array of stat_cat_entry_usr_map's
1349 service.stat_cat_entry_maps, function(value, cat_id) {
1351 // see if we already have a mapping for this entry
1352 var existing = patron.stat_cat_entries().filter(
1353 function(e) { return e.stat_cat() == cat_id })[0];
1355 if (existing) { // we have a mapping
1356 // if the existing mapping matches the new one,
1357 // there' nothing left to do
1358 if (existing.stat_cat_entry() == value) return;
1360 // mappings differ. delete the old one and create
1362 existing.isdeleted(true);
1365 var newmap = new egCore.idl.actscecm();
1366 newmap.target_usr(patron.id());
1368 newmap.stat_cat(cat_id);
1369 newmap.stat_cat_entry(value);
1370 patron.stat_cat_entries().push(newmap);
1373 if (!patron.isnew()) patron.ischanged(true);
1375 return egLovefield.addOfflineXact({
1376 user : egCore.idl.toHash(patron),
1377 timestamp : parseInt(new Date().getTime() / 1000),
1380 }).then(function (success) {
1381 if (success) return patron;
1385 service.remove_staged_user = function() {
1386 if (!service.stage_user) return $q.when();
1387 return egCore.net.request(
1389 'open-ils.actor.user.stage.delete',
1390 egCore.auth.token(),
1391 service.stage_user.user.row_id()
1395 service.save_user_settings = function(new_user, user_settings) {
1399 // Applies field-specific validation regex's from org settings
1400 // to form fields. Be careful not remove any pattern data we
1401 // are not explicitly over-writing in the provided patterns obj.
1402 service.set_field_patterns = function(patterns) {
1403 if (service.org_settings['opac.username_regex']) {
1404 patterns.au.usrname =
1405 new RegExp(service.org_settings['opac.username_regex']);
1408 if (service.org_settings['opac.barcode_regex']) {
1409 patterns.ac.barcode =
1410 new RegExp(service.org_settings['opac.barcode_regex']);
1413 if (service.org_settings['global.password_regex']) {
1414 patterns.au.passwd =
1415 new RegExp(service.org_settings['global.password_regex']);
1418 var phone_reg = service.org_settings['ui.patron.edit.phone.regex'];
1420 // apply generic phone regex first, replace below as needed.
1421 patterns.au.day_phone = new RegExp(phone_reg);
1422 patterns.au.evening_phone = new RegExp(phone_reg);
1423 patterns.au.other_phone = new RegExp(phone_reg);
1426 // the remaining patterns fit a well-known key name pattern
1428 angular.forEach(service.org_settings, function(val, key) {
1430 var parts = key.match(/ui.patron.edit\.(\w+)\.(\w+)\.regex/);
1433 var name = parts[2];
1434 patterns[cls][name] = new RegExp(val);
1441 .controller('PatronRegCtrl',
1442 ['$scope','$routeParams','$q','$uibModal','$window','egCore',
1443 'patronSvc','patronRegSvc','egUnloadPrompt','egAlertDialog',
1444 'egWorkLog','$timeout','egLovefield','$rootScope',
1445 function($scope , $routeParams , $q , $uibModal , $window , egCore ,
1446 patronSvc , patronRegSvc , egUnloadPrompt, egAlertDialog ,
1447 egWorkLog , $timeout , egLovefield , $rootScope) {
1449 $scope.rs = $rootScope;
1450 if ($scope.workstation_obj) patronRegSvc.org = $scope.workstation_obj.owning_lib;
1451 $scope.offline = true;
1453 $scope.page_data_loaded = false;
1454 $scope.clone_id = patronRegSvc.clone_id = $routeParams.clone_id;
1455 $scope.stage_username =
1456 patronRegSvc.stage_username = $routeParams.stage_username;
1458 patronRegSvc.patron_id = $routeParams.edit_id || $routeParams.id;
1460 // for existing patrons, disable barcode input by default
1461 $scope.disable_bc = $scope.focus_usrname = Boolean($scope.patron_id);
1462 $scope.focus_bc = !Boolean($scope.patron_id);
1463 $scope.address_alerts = [];
1464 $scope.dupe_counts = {};
1466 // map of perm name to true/false for perms the logged in user
1467 // has at the currently selected patron home org unit.
1470 $scope.edit_passthru = {};
1472 // 0=all, 1=suggested, 2=all
1473 $scope.edit_passthru.vis_level = 2;
1475 // Apply default values for new patrons during initial registration
1476 // prs is shorthand for patronSvc
1477 function set_new_patron_defaults(prs) {
1478 if (!$scope.patron.passwd) {
1479 // passsword may originate from staged user.
1480 $scope.generate_password();
1482 $scope.hold_notify_phone = true;
1483 $scope.hold_notify_email = true;
1485 // staged users may be loaded w/ a profile.
1486 $scope.set_expire_date();
1488 if (prs.org_settings['ui.patron.default_ident_type']) {
1489 // $scope.patron needs this field to be an object
1490 var id = prs.org_settings['ui.patron.default_ident_type'];
1491 var ident_type = $scope.ident_types.filter(
1492 function(type) { return type.id() == id })[0];
1493 $scope.patron.ident_type = ident_type;
1495 if (prs.org_settings['ui.patron.default_inet_access_level']) {
1496 // $scope.patron needs this field to be an object
1497 var id = prs.org_settings['ui.patron.default_inet_access_level'];
1498 var level = $scope.net_access_levels.filter(
1499 function(lvl) { return lvl.id() == id })[0];
1500 $scope.patron.net_access_level = level;
1502 if (prs.org_settings['ui.patron.default_country']) {
1503 $scope.patron.addresses[0].country =
1504 prs.org_settings['ui.patron.default_country'];
1508 // A null or undefined pattern leads to exceptions. Before the
1509 // patterns are loaded from the server, default all patterns
1510 // to an innocuous regex. To avoid re-creating numerous
1511 // RegExp objects, cache the stub RegExp after initial creation.
1512 // note: angular docs say ng-pattern accepts a regexp or string,
1513 // but as of writing, it only works with a regexp object.
1514 // (Likely an angular 1.2 vs. 1.4 issue).
1515 var field_patterns = {au : {}, ac : {}, aua : {}};
1516 $scope.field_pattern = function(cls, field) {
1517 if (!field_patterns[cls][field])
1518 field_patterns[cls][field] = new RegExp('.*');
1519 return field_patterns[cls][field];
1522 patronRegSvc.offlineMode($scope.offline); // force offline if ng-init'd to do so
1523 patronRegSvc.init().then(function() {
1524 // called after initTab and patronRegSvc.init have completed
1526 var prs = patronRegSvc; // brevity
1527 // in standalone mode, we have no patronSvc
1528 $scope.patron = prs.init_patron(patronSvc ? patronSvc.current : null);
1529 $scope.field_doc = prs.field_doc;
1530 $scope.edit_profiles = prs.edit_profiles;
1531 $scope.ident_types = prs.ident_types;
1532 $scope.net_access_levels = prs.net_access_levels;
1533 $scope.user_setting_types = prs.user_setting_types;
1534 $scope.opt_in_setting_types = prs.opt_in_setting_types;
1535 $scope.org_settings = prs.org_settings;
1536 $scope.sms_carriers = prs.sms_carriers;
1537 $scope.stat_cats = prs.stat_cats;
1538 $scope.surveys = prs.surveys;
1539 $scope.survey_responses = prs.survey_responses;
1540 $scope.stat_cat_entry_maps = prs.stat_cat_entry_maps;
1541 $scope.stage_user = prs.stage_user;
1542 $scope.stage_user_requestor = prs.stage_user_requestor;
1544 $scope.user_settings = prs.user_settings;
1545 // clone the user settings back into the patronRegSvc so
1546 // we have a copy of the original state of the settings.
1547 prs.user_settings = {};
1548 angular.forEach($scope.user_settings, function(val, key) {
1549 prs.user_settings[key] = val;
1552 extract_hold_notify();
1553 $scope.handle_home_org_changed();
1555 if ($scope.org_settings['ui.patron.edit.default_suggested'])
1556 $scope.edit_passthru.vis_level = 1;
1558 if ($scope.patron.isnew)
1559 set_new_patron_defaults(prs);
1561 $scope.page_data_loaded = true;
1563 prs.set_field_patterns(field_patterns);
1564 apply_username_regex();
1567 // update the currently displayed field documentation
1568 $scope.set_selected_field_doc = function(cls, field) {
1569 $scope.selected_field_doc = $scope.field_doc[cls][field];
1572 // returns the tree depth of the selected profile group tree node.
1573 $scope.pgt_depth = function(grp) {
1575 while (grp = egCore.env.pgt.map[grp.parent()]) d++;
1579 // IDL fields used for labels in the UI.
1580 $scope.idl_fields = {
1581 au : egCore.idl.classes.au.field_map,
1582 ac : egCore.idl.classes.ac.field_map,
1583 aua : egCore.idl.classes.aua.field_map
1586 // field visibility cache. Some fields are universally required.
1587 // 3 == value universally required
1588 // 2 == field is visible by default
1589 // 1 == field is suggested by default
1590 var field_visibility = {};
1591 var default_field_visibility = {
1595 'au.first_given_name' : 3,
1596 'au.family_name' : 3,
1597 'au.ident_type' : 3,
1600 'au.expire_date' : 3,
1601 'au.net_access_level' : 3,
1602 'aua.address_type' : 3,
1603 'aua.post_code' : 3,
1611 'aua.within_city_limits' : 2,
1616 // Returns true if the selected field should be visible
1617 // given the current required/suggested/all setting.
1618 // The visibility flag applied to each field as a result of calling
1619 // this function also sets (via the same flag) the requiredness state.
1620 $scope.show_field = function(field_key) {
1621 // org settings have not been received yet.
1622 if (!$scope.org_settings) return false;
1624 if (field_visibility[field_key] == undefined) {
1625 // compile and cache the visibility for the selected field
1627 var req_set = 'ui.patron.edit.' + field_key + '.require';
1628 var sho_set = 'ui.patron.edit.' + field_key + '.show';
1629 var sug_set = 'ui.patron.edit.' + field_key + '.suggest';
1631 if ($scope.org_settings[req_set]) {
1632 field_visibility[field_key] = 3;
1634 } else if ($scope.org_settings[sho_set]) {
1635 field_visibility[field_key] = 2;
1637 } else if ($scope.org_settings[sug_set]) {
1638 field_visibility[field_key] = 1;
1642 if (field_visibility[field_key] == undefined) {
1643 // No org settings were applied above. Use the default
1644 // settings if present or assume the field has no
1645 // visibility flags applied.
1646 field_visibility[field_key] =
1647 default_field_visibility[field_key] || 0;
1650 return field_visibility[field_key] >= $scope.edit_passthru.vis_level;
1653 // See $scope.show_field().
1654 // A field with visbility level 3 means it's required.
1655 $scope.field_required = function(cls, field) {
1657 // Value in the password field is not required
1658 // for existing patrons.
1659 if (field == 'passwd' && $scope.patron && !$scope.patron.isnew)
1662 return (field_visibility[cls + '.' + field] == 3 || default_field_visibility[cls + '.' + field] == 3);
1665 // generates a random 4-digit password
1666 $scope.generate_password = function() {
1667 $scope.patron.passwd = Math.floor(Math.random()*9000) + 1000;
1670 $scope.set_expire_date = function() {
1671 if (!$scope.patron.profile) return;
1672 var seconds = egCore.date.intervalToSeconds(
1673 $scope.patron.profile.perm_interval());
1674 var now_epoch = new Date().getTime();
1675 $scope.patron.expire_date = new Date(
1676 now_epoch + (seconds * 1000 /* milliseconds */))
1679 // grp is the pgt object
1680 $scope.set_profile = function(grp) {
1681 $scope.patron.profile = grp;
1682 $scope.set_expire_date();
1683 $scope.field_modified();
1686 $scope.invalid_profile = function() {
1689 $scope.patron.profile &&
1690 $scope.patron.profile.usergroup() == 't'
1694 $scope.new_address = function() {
1695 var addr = egCore.idl.toHash(new egCore.idl.aua());
1696 patronRegSvc.ingest_address($scope.patron, addr);
1697 addr.id = patronRegSvc.virt_id--;
1700 addr.within_city_limits = true;
1701 addr.country = $scope.org_settings['ui.patron.default_country'];
1702 $scope.patron.addresses.push(addr);
1705 // keep deleted addresses out of the patron object so
1706 // they won't appear in the UI. They'll be re-inserted
1707 // when the patron is updated.
1708 deleted_addresses = [];
1709 $scope.delete_address = function(id) {
1711 if ($scope.patron.isnew &&
1712 $scope.patron.addresses.length == 1 &&
1713 $scope.org_settings['ui.patron.registration.require_address']) {
1714 egAlertDialog.open(egCore.strings.REG_ADDR_REQUIRED);
1719 angular.forEach($scope.patron.addresses, function(addr) {
1720 if (addr.id == id) {
1722 addr.isdeleted = true;
1723 deleted_addresses.push(addr);
1726 addresses.push(addr);
1729 $scope.patron.addresses = addresses;
1732 $scope.post_code_changed = function(addr) {
1733 if ($scope.offline) return;
1735 'open-ils.search', 'open-ils.search.zip', addr.post_code)
1736 .then(function(resp) {
1738 if (resp.city) addr.city = resp.city;
1739 if (resp.state) addr.state = resp.state;
1740 if (resp.county) addr.county = resp.county;
1741 if (resp.alert) alert(resp.alert);
1745 $scope.replace_card = function() {
1746 $scope.patron.card.active = false;
1747 $scope.patron.card.ischanged = true;
1748 $scope.disable_bc = false;
1750 var new_card = egCore.idl.toHash(new egCore.idl.ac());
1751 new_card.id = patronRegSvc.virt_id--;
1752 new_card.isnew = true;
1753 new_card.active = true;
1754 new_card._primary = 'on';
1755 $scope.patron.card = new_card;
1756 $scope.patron.cards.push(new_card);
1759 $scope.day_phone_changed = function(phone) {
1760 if (phone && $scope.patron.isnew &&
1761 $scope.org_settings['patron.password.use_phone']) {
1762 $scope.patron.passwd = phone.substr(-4);
1766 $scope.barcode_changed = function(bc) {
1768 if (!$scope.patron.usrname)
1769 $scope.patron.usrname = bc;
1772 $scope.cards_dialog = function() {
1774 templateUrl: './circ/patron/t_patron_cards_dialog',
1776 ['$scope','$uibModalInstance','cards','perms',
1777 function($scope , $uibModalInstance , cards , perms) {
1778 // scope here is the modal-level scope
1779 $scope.args = {cards : cards};
1780 $scope.perms = perms;
1781 $scope.ok = function() { $uibModalInstance.close($scope.args) }
1782 $scope.cancel = function () { $uibModalInstance.dismiss() }
1785 cards : function() {
1786 // scope here is the controller-level scope
1787 return $scope.patron.cards;
1789 perms : function() {
1790 return $scope.perms;
1795 angular.forEach(args.cards, function(card) {
1796 card.ischanged = true; // assume cards need updating, OK?
1797 if (card._primary == 'on' &&
1798 card.id != $scope.patron.card.id) {
1799 $scope.patron.card = card;
1806 $scope.set_addr_type = function(addr, type) {
1807 var addrs = $scope.patron.addresses;
1808 if (addr['_is_'+type]) {
1809 angular.forEach(addrs, function(a) {
1810 if (a.id != addr.id) a['_is_'+type] = false;
1813 // unchecking mailing/billing means we have to randomly
1814 // select another address to fill that role. Select the
1815 // first address in the list (that does not match the
1817 for (var i = 0; i < addrs.length; i++) {
1818 if (addrs[i].id != addr.id) {
1819 addrs[i]['_is_' + type] = true;
1827 // Translate hold notify preferences from the form/scope back into a
1828 // single user setting value for opac.hold_notify.
1829 function compress_hold_notify() {
1830 var hold_notify = '';
1832 if ($scope.hold_notify_phone) {
1833 hold_notify = 'phone';
1836 if ($scope.hold_notify_email) {
1837 hold_notify = splitter + 'email';
1840 if ($scope.hold_notify_sms) {
1841 hold_notify = splitter + 'sms';
1844 $scope.user_settings['opac.hold_notify'] = hold_notify;
1847 // dialog for selecting additional permission groups
1848 $scope.secondary_groups_dialog = function() {
1850 templateUrl: './circ/patron/t_patron_groups_dialog',
1852 ['$scope','$uibModalInstance','linked_groups','pgt_depth',
1853 function($scope , $uibModalInstance , linked_groups , pgt_depth) {
1855 $scope.pgt_depth = pgt_depth;
1857 linked_groups : linked_groups,
1858 edit_profiles : patronRegSvc.edit_profiles,
1859 new_profile : patronRegSvc.edit_profiles[0]
1862 // add a new group to the linked groups list
1863 $scope.link_group = function($event, grp) {
1864 var found = false; // avoid duplicates
1865 angular.forEach($scope.args.linked_groups,
1866 function(g) {if (g.id() == grp.id()) found = true});
1867 if (!found) $scope.args.linked_groups.push(grp);
1868 $event.preventDefault(); // avoid close
1871 // remove a group from the linked groups list
1872 $scope.unlink_group = function($event, grp) {
1873 $scope.args.linked_groups =
1874 $scope.args.linked_groups.filter(function(g) {
1875 return g.id() != grp.id()
1877 $event.preventDefault(); // avoid close
1880 $scope.ok = function() { $uibModalInstance.close($scope.args) }
1881 $scope.cancel = function () { $uibModalInstance.dismiss() }
1884 linked_groups : function() { return $scope.patron.groups },
1885 pgt_depth : function() { return $scope.pgt_depth }
1890 if ($scope.patron.isnew) {
1891 // groups must be linked for new patrons after the
1892 // patron is created.
1893 $scope.patron.groups = args.linked_groups;
1897 // update links groups for existing users in real time.
1898 var ids = args.linked_groups.map(function(g) {return g.id()});
1899 patronRegSvc.apply_secondary_groups($scope.patron.id, ids)
1900 .then(function(success) {
1902 $scope.patron.groups = args.linked_groups;
1908 function extract_hold_notify() {
1909 notify = $scope.user_settings['opac.hold_notify'];
1910 if (!notify) return;
1911 $scope.hold_notify_phone = Boolean(notify.match(/phone/));
1912 $scope.hold_notify_email = Boolean(notify.match(/email/));
1913 $scope.hold_notify_sms = Boolean(notify.match(/sms/));
1916 $scope.invalidate_field = function(field) {
1917 patronRegSvc.invalidate_field($scope.patron, field);
1920 address_alert = function(addr) {
1921 if ($scope.offline) return;
1923 street1: addr.street1,
1924 street2: addr.street2,
1927 county: addr.county,
1928 country: addr.country,
1929 post_code: addr.post_code,
1930 mailing_address: addr._is_mailing,
1931 billing_address: addr._is_billing
1936 'open-ils.actor.address_alert.test',
1937 egCore.auth.token(), egCore.auth.user().ws_ou(), args
1938 ).then(function(res) {
1939 $scope.address_alerts = res;
1943 $scope.dupe_value_changed = function(type, value) {
1944 $scope.dupe_counts[type] = 0;
1945 patronRegSvc.dupe_patron_search($scope.patron, type, value)
1946 .then(function(res) {
1947 $scope.dupe_counts[type] = res.count;
1949 $scope.dupe_search_encoded =
1950 encodeURIComponent(js2JSON(res.search));
1952 $scope.dupe_search_encoded = '';
1957 // Dummy function in offline mode
1958 $scope.handle_home_org_changed = function() {}
1960 // This is called with every character typed in a form field,
1961 // since that's the only way to gaurantee something has changed.
1962 // See handle_field_changed for ng-change vs. ng-blur.
1963 $scope.field_modified = function() {
1964 // Call attach with every field change, regardless of whether
1965 // it's been called before. This will allow for re-attach after
1966 // the user clicks through the unload warning. egUnloadPrompt
1967 // will ensure we only attach once.
1968 egUnloadPrompt.attach($rootScope);
1971 // also monitor when form is changed *by the user*, as using
1972 // an ng-change handler doesn't work with eg-date-input
1973 $scope.$watch('reg_form.$pristine', function(newVal, oldVal) {
1974 if (!newVal) egUnloadPrompt.attach($rootScope);
1977 // username regex (if present) must be removed any time
1978 // the username matches the barcode to avoid firing the
1979 // invalid field handlers.
1980 function apply_username_regex() {
1981 var regex = $scope.org_settings['opac.username_regex'];
1983 if ($scope.patron.card.barcode) {
1984 // username must match the regex or the barcode
1985 field_patterns.au.usrname =
1987 regex + '|^' + $scope.patron.card.barcode + '$');
1989 // username must match the regex
1990 field_patterns.au.usrname = new RegExp(regex);
1993 // username can be any format.
1994 field_patterns.au.usrname = new RegExp('.*');
1998 // obj could be the patron, an address, etc.
1999 // This is called any time a form field achieves then loses focus.
2000 // It does not necessarily mean the field has changed.
2001 // The alternative is ng-change, but it's called with each character
2002 // typed, which would be overkill for many of the actions called here.
2003 $scope.handle_field_changed = function(obj, field_name) {
2006 var cls = obj.classname; // set by egIdl
2007 var value = obj[field_name];
2010 //console.log('changing field ' + field_name + ' to ' + value);
2012 switch (field_name) {
2014 if ($scope.patron.day_phone &&
2015 $scope.patron.isnew &&
2016 $scope.org_settings['patron.password.use_phone']) {
2017 $scope.patron.passwd = phone.substr(-4);
2022 apply_username_regex();
2023 $scope.barcode_changed(value);
2027 maintain_juvenile_flag();
2035 // patron.juvenile is set to true if the user was born after
2036 function maintain_juvenile_flag() {
2037 if ( !($scope.patron && $scope.patron.dob) ) return;
2040 $scope.org_settings['global.juvenile_age_threshold']
2043 var base = new Date();
2045 base.setTime(base.getTime() -
2046 Number(egCore.date.intervalToSeconds(juv_interval) + '000'));
2048 $scope.patron.juvenile = ($scope.patron.dob > base);
2051 // returns true (disable) for orgs that cannot have users.
2052 $scope.disable_home_org = function(org_id) {
2053 if (!org_id) return;
2054 var org = egCore.org.get(org_id);
2058 org.ou_type().can_have_users() == 'f'
2062 // Returns true if the Save and Save & Clone buttons should be disabled.
2063 $scope.edit_passthru.hide_save_actions = function() {
2067 // Returns true if any input elements are tagged as invalid
2068 // via Angular patterns or required attributes.
2069 function form_has_invalid_fields() {
2070 return $('#patron-reg-container .ng-invalid').length > 0;
2073 function form_is_incomplete() {
2075 $scope.dupe_username ||
2076 $scope.dupe_barcode ||
2077 form_has_invalid_fields()
2082 $scope.edit_passthru.save = function(save_args) {
2083 if (!save_args) save_args = {};
2085 if (form_is_incomplete()) {
2086 // User has not provided valid values for all required fields.
2087 return egAlertDialog.open(egCore.strings.REG_INVALID_FIELDS);
2090 // remove page unload warning prompt
2091 egUnloadPrompt.clear();
2093 // toss the deleted addresses back into the patron's list of
2094 // addresses so it's included in the update
2095 $scope.patron.addresses =
2096 $scope.patron.addresses.concat(deleted_addresses);
2098 compress_hold_notify();
2102 patronRegSvc.save_user($scope.patron)
2103 .then($scope.rs.save_offline_xacts)
2104 .then(function(new_user) {
2105 // reload the current page
2106 $window.location.href = location.href;