]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/services/ui.js
LP#1676608: copy alert and suppression matrix
[working/Evergreen.git] / Open-ILS / web / js / ui / default / staff / services / ui.js
1 /**
2   * UI tools and directives.
3   */
4 angular.module('egUiMod', ['egCoreMod', 'ui.bootstrap'])
5
6
7 /**
8  * <input focus-me="iAmOpen"/>
9  * $scope.iAmOpen = true;
10  */
11 .directive('focusMe', 
12        ['$timeout','$parse', 
13 function($timeout , $parse) {
14     return {
15         link: function(scope, element, attrs) {
16             var model = $parse(attrs.focusMe);
17             scope.$watch(model, function(value) {
18                 if(value === true) 
19                     $timeout(function() {element[0].focus()});
20             });
21             element.bind('blur', function() {
22                 $timeout(function() {
23                     scope.$apply(model.assign(scope, false));
24                 });
25             })
26         }
27     };
28 }])
29
30 /**
31  * <input blur-me="pleaseBlurMe"/>
32  * $scope.pleaseBlurMe = true
33  * Useful for de-focusing when no other obvious focus target exists
34  */
35 .directive('blurMe', 
36        ['$timeout','$parse', 
37 function($timeout , $parse) {
38     return {
39         link: function(scope, element, attrs) {
40             var model = $parse(attrs.blurMe);
41             scope.$watch(model, function(value) {
42                 if(value === true) 
43                     $timeout(function() {element[0].blur()});
44             });
45             element.bind('focus', function() {
46                 $timeout(function() {
47                     scope.$apply(model.assign(scope, false));
48                 });
49             })
50         }
51     };
52 }])
53
54
55 // <input select-me="iWantToBeSelected"/>
56 // $scope.iWantToBeSelected = true;
57 .directive('selectMe', 
58        ['$timeout','$parse', 
59 function($timeout , $parse) {
60     return {
61         link: function(scope, element, attrs) {
62             var model = $parse(attrs.selectMe);
63             scope.$watch(model, function(value) {
64                 if(value === true) 
65                     $timeout(function() {element[0].select()});
66             });
67             element.bind('blur', function() {
68                 $timeout(function() {
69                     scope.$apply(model.assign(scope, false));
70                 });
71             })
72         }
73     };
74 }])
75
76 // <select int-to-str ><option value="1">Value</option></select>
77 // use integer models for string values
78 .directive('intToStr', function() {
79     return {
80         restrict: 'A',
81         require: 'ngModel',
82         link: function(scope, element, attrs, ngModel) {
83             ngModel.$parsers.push(function(value) {
84                 return parseInt(value);
85             });
86             ngModel.$formatters.push(function(value) {
87                 return '' + value;
88             });
89         }
90     };
91 })
92
93 // <input str-to-int value="10"/>
94 .directive('strToInt', function() {
95     return {
96         restrict: 'A',
97         require: 'ngModel',
98         link: function(scope, element, attrs, ngModel) {
99             ngModel.$parsers.push(function(value) {
100                 return '' + value;
101             });
102             ngModel.$formatters.push(function(value) {
103                 return parseInt(value);
104             });
105         }
106     };
107 })
108
109 // <input float-to-str
110 .directive('floatToStr', function() {
111     return {
112         restrict: 'A',
113         require: 'ngModel',
114         link: function(scope, element, attrs, ngModel) {
115             ngModel.$parsers.push(function(value) {
116                 return parseFloat(value);
117             });
118             ngModel.$formatters.push(function(value) {
119                 return '' + value;
120             });
121         }
122     };
123 })
124
125 .directive('strToFloat', function() {
126     return {
127         restrict: 'A',
128         require: 'ngModel',
129         link: function(scope, element, attrs, ngModel) {
130             ngModel.$parsers.push(function(value) {
131                 return '' + value;
132             });
133             ngModel.$formatters.push(function(value) {
134                 return parseFloat(value);
135             });
136         }
137     };
138 })
139
140 // 'reverse' filter 
141 // <div ng-repeat="item in items | reverse">{{item.name}}</div>
142 // http://stackoverflow.com/questions/15266671/angular-ng-repeat-in-reverse
143 // TODO: perhaps this should live elsewhere
144 .filter('reverse', function() {
145     return function(items) {
146         return items.slice().reverse();
147     };
148 })
149
150 // 'date' filter
151 // Overriding the core angular date filter with a moment-js based one for
152 // better timezone and formatting support.
153 .filter('date',function() {
154
155     var formatMap = {
156         short  : 'l LT',
157         medium : 'lll',
158         long   : 'LLL',
159         full   : 'LLLL',
160
161         shortDate  : 'l',
162         mediumDate : 'll',
163         longDate   : 'LL',
164         fullDate   : 'LL',
165
166         shortTime  : 'LT',
167         mediumTime : 'LTS'
168     };
169
170     var formatReplace = [
171         [ /yyyy/g, 'YYYY' ],
172         [ /yy/g,   'YY'   ],
173         [ /y/g,    'Y'    ],
174         [ /ww/g,   'WW'   ],
175         [ /w/g,    'W'    ],
176         [ /dd/g,   'DD'   ],
177         [ /d/g,    'D'    ],
178         [ /sss/g,  'SSS'  ],
179         [ /EEEE/g, 'dddd' ],
180         [ /EEE/g,  'ddd'  ],
181         [ /Z/g,    'ZZ'   ]
182     ];
183
184     return function (date, format, tz) {
185         if (!date) return '';
186
187         if (date == 'now') 
188             date = new Date().toISOString();
189
190         if (format) {
191             var fmt = formatMap[format] || format;
192             angular.forEach(formatReplace, function (r) {
193                 fmt = fmt.replace(r[0],r[1]);
194             });
195         }
196
197         var d = moment(date);
198         if (tz && tz !== '-') d.tz(tz);
199
200         return d.isValid() ? d.format(fmt) : '';
201     }
202
203 })
204
205 // 'egOrgDate' filter
206 // Uses moment.js and moment-timezone.js to put dates into the most appropriate
207 // timezone for a given (optional) org unit based on its lib.timezone setting
208 .filter('egOrgDate',['$filter','egCore',
209              function($filter , egCore) {
210
211     var tzcache = {};
212
213     function eg_date_filter (date, fmt, ouID) {
214         if (ouID) {
215             if (angular.isObject(ouID)) {
216                 if (angular.isFunction(ouID.id)) {
217                     ouID = ouID.id();
218                 } else {
219                     ouID = ouID.id;
220                 }
221             }
222     
223             if (!tzcache[ouID]) {
224                 tzcache[ouID] = '-';
225                 egCore.org.settings('lib.timezone', ouID)
226                 .then(function(s) {
227                     tzcache[ouID] = s['lib.timezone'] || OpenSRF.tz;
228                 });
229             }
230         }
231
232         return $filter('date')(date, fmt, tzcache[ouID]);
233     }
234
235     eg_date_filter.$stateful = true;
236
237     return eg_date_filter;
238 }])
239
240 // 'egOrgDateInContext' filter
241 // Uses the egOrgDate filter to make time and date location aware, and further
242 // modifies the format if one of [short, medium, long, full] to show only the
243 // date if the optional interval parameter is day-granular.  This is
244 // particularly useful for due dates on circulations.
245 .filter('egOrgDateInContext',['$filter','egCore',
246                       function($filter , egCore) {
247
248     function eg_context_date_filter (date, format, orgID, interval) {
249         var fmt = format;
250         if (!fmt) fmt = 'shortDate';
251
252         // if this is a simple, one-word format, and it doesn't say "Date" in it...
253         if (['short','medium','long','full'].filter(function(x){return fmt == x}).length > 0 && interval) {
254             var secs = egCore.date.intervalToSeconds(interval);
255             if (secs !== null && secs % 86400 == 0) fmt += 'Date';
256         }
257
258         return $filter('egOrgDate')(date, fmt, orgID);
259     }
260
261     eg_context_date_filter.$stateful = true;
262
263     return eg_context_date_filter;
264 }])
265
266 // 'egDueDate' filter
267 // Uses the egOrgDateInContext filter to make time and date location aware, but
268 // only if the supplied interval is day-granular.  This is as wrapper for
269 // egOrgDateInContext to be used for circulation due date /only/.
270 .filter('egDueDate',['$filter','egCore',
271                       function($filter , egCore) {
272
273     function eg_context_due_date_filter (date, format, orgID, interval) {
274         if (interval) {
275             var secs = egCore.date.intervalToSeconds(interval);
276             if (secs === null || secs % 86400 != 0) {
277                 orgID = null;
278                 interval = null;
279             }
280         }
281         return $filter('egOrgDateInContext')(date, format, orgID, interval);
282     }
283
284     eg_context_due_date_filter.$stateful = true;
285
286     return eg_context_due_date_filter;
287 }])
288
289 // 'join' filter
290 // TODO: perhaps this should live elsewhere
291 .filter('join', function() {
292     return function(arr,sep) {
293         if (typeof arr == 'object' && arr.constructor == Array) {
294             return arr.join(sep || ',');
295         } else {
296             return '';
297         }
298     };
299 })
300
301 /**
302  * Progress Dialog. 
303  *
304  * egProgressDialog.open();
305  * egProgressDialog.open({value : 0});
306  * egProgressDialog.open({value : 0, max : 123});
307  * egProgressDialog.increment();
308  * egProgressDialog.increment();
309  * egProgressDialog.close();
310  *
311  * Each dialog has 2 numbers, 'max' and 'value'.
312  * The content of these values determines how the dialog displays.  
313  *
314  * There are 3 flavors:
315  *
316  * -- value is set, max is set
317  * determinate: shows a progression with a percent complete.
318  *
319  * -- value is set, max is unset
320  * semi-determinate, with a value report.  Shows a value-less
321  * <progress/>, but shows the value as a number in the dialog.
322  *
323  * This is useful in cases where the total number of items to retrieve
324  * from the server is unknown, but we know how many items we've
325  * retrieved thus far.  It helps to reinforce that something specific
326  * is happening, but we don't know when it will end.
327  *
328  * -- value is unset
329  * indeterminate: shows a generic value-less <progress/> with no 
330  * clear indication of progress.
331  *
332  * Only 1 egProgressDialog instance will be activate at a time.
333  * Each invocation of .open() destroys any existing instance.
334  */
335
336 /* Simple storage class for egProgressDialog data maintenance.
337  * This data lives outside of egProgressDialog so it can be 
338  * directly imported into egProgressDialog's $uibModalInstance.
339  */
340 .factory('egProgressData', [
341     function() {
342         var service = {}; // max/value initially unset
343
344         service.reset = function() {
345             delete service.max;
346             delete service.value;
347         }
348
349         service.hasvalue = function() {
350             return Number.isInteger(service.value);
351         }
352
353         service.hasmax = function() {
354             return Number.isInteger(service.max);
355         }
356
357         service.percent = function() {
358             if (service.hasvalue()  && 
359                 service.hasmax()    && 
360                 service.max > 0     &&
361                 service.value <= service.max)
362                 return Math.floor((service.value / service.max) * 100);
363             return 100;
364         }
365
366         return service;
367     }
368 ])
369
370 .factory('egProgressDialog', [
371             'egProgressData','$uibModal', 
372     function(egProgressData , $uibModal) {
373     var service = {};
374
375     service.open = function(args) {
376         return $uibModal.open({
377             templateUrl: './share/t_progress_dialog',
378             /* backdrop: 'static', */ /* allow 'cancelling' of progress dialog */
379             controller: ['$scope','$uibModalInstance','egProgressData',
380                 function( $scope , $uibModalInstance , egProgressData) {
381                     // Once the new modal instance is available, force-
382                     // kill any other instances
383                     service.close(true); 
384
385                     // Reset to an indeterminate progress bar, 
386                     // overlay with caller values.
387                     egProgressData.reset();
388                     service.update(angular.extend({}, args));
389
390                     service.currentInstance = $uibModalInstance;
391                     $scope.data = egProgressData; // tiny service
392                 }
393             ]
394         });
395     };
396
397     service.close = function(warn) {
398         if (service.currentInstance) {
399             if (warn) {
400                 console.warn("egProgressDialog replacing existing instance. "
401                     + "Only one may be open at a time.");
402             }
403             service.currentInstance.close();
404             delete service.currentInstance;
405         }
406     }
407
408     // Set the current state of the progress bar.
409     service.update = function(args) {
410         if (args.max != undefined) 
411             egProgressData.max = args.max;
412         if (args.value != undefined) 
413             egProgressData.value = args.value;
414     }
415
416     // Increment the current value.  If no amount is specified,
417     // it increments by 1.  Calling increment() on an indetermite
418     // progress bar will force it to be a (semi-)determinate bar.
419     service.increment = function(amt) {
420         if (!Number.isInteger(amt)) amt = 1;
421
422         if (!egProgressData.hasvalue())
423             egProgressData.value = 0;
424
425         egProgressData.value += amt;
426     }
427
428     return service;
429 }])
430
431 /**
432  * egAlertDialog.open({message : 'hello {{name}}'}).result.then(
433  *     function() { console.log('alert closed') });
434  */
435 .factory('egAlertDialog', 
436
437         ['$uibModal','$interpolate',
438 function($uibModal , $interpolate) {
439     var service = {};
440
441     service.open = function(message, msg_scope) {
442         return $uibModal.open({
443             templateUrl: './share/t_alert_dialog',
444             backdrop: 'static',
445             controller: ['$scope', '$uibModalInstance',
446                 function($scope, $uibModalInstance) {
447                     $scope.message = $interpolate(message)(msg_scope);
448                     $scope.ok = function() {
449                         if (msg_scope && msg_scope.ok) msg_scope.ok();
450                         $uibModalInstance.close()
451                     }
452                 }
453             ]
454         });
455     }
456
457     return service;
458 }])
459
460 /**
461  * egConfirmDialog.open("some message goes {{here}}", {
462  *  here : 'foo', ok : function() {}, cancel : function() {}},
463  *  'OK', 'Cancel');
464  */
465 .factory('egConfirmDialog', 
466     
467        ['$uibModal','$interpolate',
468 function($uibModal, $interpolate) {
469     var service = {};
470
471     service.open = function(title, message, msg_scope, ok_button_label, cancel_button_label) {
472         msg_scope = msg_scope || {};
473         return $uibModal.open({
474             templateUrl: './share/t_confirm_dialog',
475             backdrop: 'static',
476             controller: ['$scope', '$uibModalInstance',
477                 function($scope, $uibModalInstance) {
478                     $scope.title = $interpolate(title)(msg_scope);
479                     $scope.message = $interpolate(message)(msg_scope);
480                     $scope.ok_button_label = $interpolate(ok_button_label || '')(msg_scope);
481                     $scope.cancel_button_label = $interpolate(cancel_button_label || '')(msg_scope);
482                     $scope.ok = function() {
483                         if (msg_scope.ok) msg_scope.ok();
484                         $uibModalInstance.close()
485                     }
486                     $scope.cancel = function() {
487                         if (msg_scope.cancel) msg_scope.cancel();
488                         $uibModalInstance.dismiss();
489                     }
490                 }
491             ]
492         })
493     }
494
495     return service;
496 }])
497
498 /**
499  * egPromptDialog.open(
500  *    "prompt message goes {{here}}", 
501  *    promptValue,  // optional
502  *    {
503  *      here : 'foo',  
504  *      ok : function(value) {console.log(value)}, 
505  *      cancel : function() {console.log('prompt denied')}
506  *    }
507  *  );
508  */
509 .factory('egPromptDialog', 
510     
511        ['$uibModal','$interpolate',
512 function($uibModal, $interpolate) {
513     var service = {};
514
515     service.open = function(message, promptValue, msg_scope) {
516         return $uibModal.open({
517             templateUrl: './share/t_prompt_dialog',
518             backdrop: 'static',
519             controller: ['$scope', '$uibModalInstance',
520                 function($scope, $uibModalInstance) {
521                     $scope.message = $interpolate(message)(msg_scope);
522                     $scope.args = {value : promptValue || ''};
523                     $scope.focus = true;
524                     $scope.ok = function() {
525                         if (msg_scope && msg_scope.ok) msg_scope.ok($scope.args.value);
526                         $uibModalInstance.close($scope.args);
527                     }
528                     $scope.cancel = function() {
529                         if (msg_scope && msg_scope.cancel) msg_scope.cancel();
530                         $uibModalInstance.dismiss();
531                     }
532                 }
533             ]
534         })
535     }
536
537     return service;
538 }])
539
540 /**
541  * egSelectDialog.open(
542  *    "message goes {{here}}", 
543  *    list,           // ['values','for','dropdown'],
544  *    selectedValue,  // optional
545  *    {
546  *      here : 'foo',
547  *      ok : function(value) {console.log(value)}, 
548  *      cancel : function() {console.log('prompt denied')}
549  *    }
550  *  );
551  */
552 .factory('egSelectDialog', 
553     
554        ['$uibModal','$interpolate',
555 function($uibModal, $interpolate) {
556     var service = {};
557
558     service.open = function(message, inputList, selectedValue, msg_scope) {
559         return $uibModal.open({
560             templateUrl: './share/t_select_dialog',
561             backdrop: 'static',
562             controller: ['$scope', '$uibModalInstance',
563                 function($scope, $uibModalInstance) {
564                     $scope.message = $interpolate(message)(msg_scope);
565                     $scope.args = {
566                         list  : inputList,
567                         value : selectedValue
568                     };
569                     $scope.focus = true;
570                     $scope.ok = function() {
571                         if (msg_scope.ok) msg_scope.ok($scope.args.value);
572                         $uibModalInstance.close()
573                     }
574                     $scope.cancel = function() {
575                         if (msg_scope.cancel) msg_scope.cancel();
576                         $uibModalInstance.dismiss();
577                     }
578                 }
579             ]
580         })
581     }
582
583     return service;
584 }])
585
586 /**
587  * Warn on page unload and give the user a chance to avoid navigating
588  * away from the current page.  
589  * Only one handler is supported per page.
590  * NOTE: we can't use an egUnloadDialog as the dialog builder, because
591  * it renders asynchronously, which allows the page to redirect before
592  * the dialog appears.
593  */
594 .factory('egUnloadPrompt', [
595         '$window','egStrings', 
596 function($window , egStrings) {
597     var service = {attached : false};
598
599     // attach a page/scope unload prompt
600     service.attach = function($scope, msg) {
601         if (service.attached) return;
602         service.attached = true;
603
604         // handle page change
605         $($window).on('beforeunload', function() { 
606             service.clear();
607             return msg || egStrings.EG_UNLOAD_PAGE_PROMPT_MSG;
608         });
609
610         if (!$scope) return;
611
612         // If a scope was provided, attach a scope-change handler,
613         // similar to the page-page prompt.
614         service.locChangeCancel = 
615             $scope.$on('$locationChangeStart', function(evt, next, current) {
616             if (confirm(msg || egStrings.EG_UNLOAD_CTRL_PROMPT_MSG)) {
617                 // user allowed the page to change.  
618                 // Clear the unload handler.
619                 service.clear();
620             } else {
621                 evt.preventDefault();
622             }
623         });
624     };
625
626     // remove the page unload prompt
627     service.clear = function() {
628         $($window).off('beforeunload');
629         if (service.locChangeCancel)
630             service.locChangeCancel();
631         service.attached = false;
632     }
633
634     return service;
635 }])
636
637 /**
638  * egAddCopyAlertDialog - manage copy alerts
639  */
640 .factory('egAddCopyAlertDialog', 
641        ['$uibModal','$interpolate','egCore',
642 function($uibModal , $interpolate , egCore) {
643     var service = {};
644
645     service.open = function(args) {
646         return $uibModal.open({
647             templateUrl: './share/t_add_copy_alert_dialog',
648             controller: ['$scope','$q','$uibModalInstance',
649                 function( $scope , $q , $uibModalInstance) {
650
651                     $scope.copy_ids = args.copy_ids;
652                     egCore.pcrud.search('ccat',
653                         { active : 't' },
654                         {},
655                         { atomic : true }
656                     ).then(function (ccat) {
657                         $scope.alert_types = ccat;
658                     }); 
659
660                     $scope.copy_alert = {
661                         create_staff : egCore.auth.user().id(),
662                         note         : '',
663                         temp         : false
664                     };
665
666                     $scope.ok = function(copy_alert) {
667                         if (typeof(copy_alert.note) != 'undefined' &&
668                             copy_alert.note != '') {
669                             copy_alerts = [];
670                             angular.forEach($scope.copy_ids, function (cp_id) {
671                                 var a = new egCore.idl.aca();
672                                 a.isnew(1);
673                                 a.create_staff(copy_alert.create_staff);
674                                 a.note(copy_alert.note);
675                                 a.temp(copy_alert.temp ? 't' : 'f');
676                                 a.copy(cp_id);
677                                 a.ack_time(null);
678                                 a.alert_type(
679                                     $scope.alert_types.filter(function(at) {
680                                         return at.id() == copy_alert.alert_type;
681                                     })[0]
682                                 );
683                                 copy_alerts.push( a );
684                             });
685                             if (copy_alerts.length > 0) {
686                                 egCore.pcrud.apply(copy_alerts);
687                             }
688                         }
689                         if (args.ok) args.ok();
690                         $uibModalInstance.close()
691                     }
692                     $scope.cancel = function() {
693                         if (args.cancel) args.cancel();
694                         $uibModalInstance.dismiss();
695                     }
696                 }
697             ]
698         })
699     }
700
701     return service;
702 }])
703
704 /**
705  * egCopyAlertManagerDialog - manage copy alerts
706  */
707 .factory('egCopyAlertManagerDialog', 
708        ['$uibModal','$interpolate','egCore',
709 function($uibModal , $interpolate , egCore) {
710     var service = {};
711
712     service.get_user_copy_alerts = function(copy_id) {
713         return egCore.pcrud.search('aca', { copy : copy_id, ack_time : null },
714             { flesh : 1, flesh_fields : { aca : ['alert_type'] } },
715             { atomic : true }
716         );
717     }
718
719     service.open = function(args) {
720         return $uibModal.open({
721             templateUrl: './share/t_copy_alert_manager_dialog',
722             controller: ['$scope','$q','$uibModalInstance',
723                 function( $scope , $q , $uibModalInstance) {
724
725                     function init(args) {
726                         var defer = $q.defer();
727                         if (args.copy_id) {
728                             service.get_user_copy_alerts(args.copy_id).then(function(aca) {
729                                 defer.resolve(aca);
730                             });
731                         } else {
732                             defer.resolve(args.alerts);
733                         }
734                         return defer.promise;
735                     }
736
737                     // returns a promise resolved with the list of circ statuses
738                     $scope.get_copy_statuses = function() {
739                         if (egCore.env.ccs)
740                             return $q.when(egCore.env.ccs.list);
741
742                         return egCore.pcrud.retrieveAll('ccs', null, {atomic : true})
743                         .then(function(list) {
744                             egCore.env.absorbList(list, 'ccs');
745                             return list;
746                         });
747                     };
748
749                     $scope.mode = args.mode || 'checkin';
750
751                     var next_statuses = [];
752                     var seen_statuses = {};
753                     $scope.next_statuses = [];
754                     $scope.params = {
755                         'the_next_status' : null
756                     }
757                     init(args).then(function(copy_alerts) {
758                         $scope.alerts = copy_alerts;
759                         angular.forEach($scope.alerts, function(copy_alert) {
760                             var state = copy_alert.alert_type().state();
761                             copy_alert.evt = copy_alert.alert_type().event();
762
763                             copy_alert.message = copy_alert.note() ||
764                                 egCore.strings.ON_DEMAND_COPY_ALERT[copy_alert.evt][state];
765
766                             if (copy_alert.temp() == 't') {
767                                 angular.forEach(copy_alert.alert_type().next_status(), function (st) {
768                                     if (!seen_statuses[st]) {
769                                         seen_statuses[st] = true;
770                                         next_statuses.push(st);
771                                     }
772                                 });
773                             }
774                         });
775                         if ($scope.mode == 'checkin' && next_statuses.length > 0) {
776                             $scope.get_copy_statuses().then(function() {
777                                 angular.forEach(next_statuses, function(st) {
778                                     if (egCore.env.ccs.map[st])
779                                         $scope.next_statuses.push(egCore.env.ccs.map[st]);
780                                 });
781                                 $scope.params.the_next_status = $scope.next_statuses[0].id();
782                             });
783                         }
784                     });
785
786                     $scope.isAcknowledged = function(copy_alert) {
787                         return (copy_alert.acked);
788                     };
789                     $scope.canBeAcknowledged = function(copy_alert) {
790                         return (!copy_alert.ack_time() && copy_alert.temp() == 't');
791                     };
792                     $scope.canBeRemoved = function(copy_alert) {
793                         return (!copy_alert.ack_time() && copy_alert.temp() == 'f');
794                     };
795
796                     $scope.ok = function() {
797                         var acks = [];
798                         angular.forEach($scope.alerts, function (copy_alert) {
799                             if (copy_alert.acked) {
800                                 copy_alert.ack_time('now');
801                                 copy_alert.ack_staff(egCore.auth.user().id());
802                                 copy_alert.ischanged(true);
803                                 acks.push(copy_alert);
804                             }
805                         });
806                         if (acks.length > 0) {
807                             egCore.pcrud.apply(acks);
808                         }
809                         if (args.ok) args.ok($scope.params.the_next_status);
810                         $uibModalInstance.close()
811                     }
812                     $scope.cancel = function() {
813                         if (args.cancel) args.cancel();
814                         $uibModalInstance.dismiss();
815                     }
816                 }
817             ]
818         })
819     }
820
821     return service;
822 }])
823
824 /**
825  * egCopyAlertEditorDialog - manage copy alerts
826  */
827 .factory('egCopyAlertEditorDialog', 
828        ['$uibModal','$interpolate','egCore',
829 function($uibModal , $interpolate , egCore) {
830     var service = {};
831
832     service.get_user_copy_alerts = function(copy_id) {
833         return egCore.pcrud.search('aca', { copy : copy_id, ack_time : null },
834             { flesh : 1, flesh_fields : { aca : ['alert_type'] } },
835             { atomic : true }
836         );
837     }
838
839     service.get_copy_alert_types = function() {
840         return egCore.pcrud.search('ccat',
841             { active : 't' },
842             {},
843             { atomic : true }
844         );
845     };
846
847     service.open = function(args) {
848         return $uibModal.open({
849             templateUrl: './share/t_copy_alert_editor_dialog',
850             controller: ['$scope','$q','$uibModalInstance',
851                 function( $scope , $q , $uibModalInstance) {
852
853                     function init(args) {
854                         var defer = $q.defer();
855                         if (args.copy_id) {
856                             service.get_user_copy_alerts(args.copy_id).then(function(aca) {
857                                 defer.resolve(aca);
858                             });
859                         } else {
860                             defer.resolve(args.alerts);
861                         }
862                         return defer.promise;
863                     }
864
865                     init(args).then(function(copy_alerts) {
866                         $scope.copy_alert_list = copy_alerts;
867                     });
868                     service.get_copy_alert_types().then(function(ccat) {
869                         $scope.alert_types = ccat;
870                     });
871
872                     $scope.ok = function() {
873                         egCore.pcrud.apply($scope.copy_alert_list);
874                         $uibModalInstance.close()
875                     }
876                     $scope.cancel = function() {
877                         if (args.cancel) args.cancel();
878                         $uibModalInstance.dismiss();
879                     }
880                 }
881             ]
882         })
883     }
884
885     return service;
886 }])
887 .directive('aDisabled', function() {
888     return {
889         restrict : 'A',
890         compile: function(tElement, tAttrs, transclude) {
891             //Disable ngClick
892             tAttrs["ngClick"] = ("ng-click", "!("+tAttrs["aDisabled"]+") && ("+tAttrs["ngClick"]+")");
893
894             //Toggle "disabled" to class when aDisabled becomes true
895             return function (scope, iElement, iAttrs) {
896                 scope.$watch(iAttrs["aDisabled"], function(newValue) {
897                     if (newValue !== undefined) {
898                         iElement.toggleClass("disabled", newValue);
899                     }
900                 });
901
902                 //Disable href on click
903                 iElement.on("click", function(e) {
904                     if (scope.$eval(iAttrs["aDisabled"])) {
905                         e.preventDefault();
906                     }
907                 });
908             };
909         }
910     };
911 })
912
913 .directive('egBasicComboBox', function() {
914     return {
915         restrict: 'E',
916         replace: true,
917         scope: {
918             list: "=", // list of strings
919             selected: "=",
920             onSelect: "=",
921             egDisabled: "=",
922             allowAll: "@",
923             placeholder: "@",
924             focusMe: "=?"
925         },
926         template:
927             '<div class="input-group">'+
928                 '<input placeholder="{{placeholder}}" type="text" ng-disabled="egDisabled" class="form-control" ng-model="selected" ng-change="makeOpen()" focus-me="focusMe">'+
929                 '<div class="input-group-btn" uib-dropdown ng-class="{open:isopen}">'+
930                     '<button type="button" ng-click="showAll()" ng-disabled="egDisabled" class="btn btn-default" uib-dropdown-toggle><span class="caret"></span></button>'+
931                     '<ul dropdown-menu class="dropdown-menu-right">'+
932                         '<li ng-repeat="item in list|filter:selected:compare"><a href ng-click="changeValue(item)">{{item}}</a></li>'+
933                         '<li ng-if="complete_list" class="divider"><span></span></li>'+
934                         '<li ng-if="complete_list" ng-repeat="item in list"><a href ng-click="changeValue(item)">{{item}}</a></li>'+
935                     '</ul>'+
936                 '</div>'+
937             '</div>',
938         controller: ['$scope','$filter',
939             function( $scope , $filter) {
940
941                 $scope.complete_list = false;
942                 $scope.isopen = false;
943                 $scope.clickedopen = false;
944                 $scope.clickedclosed = null;
945
946                 $scope.compare = function (ex, act) {
947                     if (act === null || act === undefined) return true;
948                     if (act.toString) act = act.toString();
949                     return new RegExp(act.toLowerCase()).test(ex)
950                 }
951
952                 $scope.showAll = function () {
953
954                     $scope.clickedopen = !$scope.clickedopen;
955
956                     if ($scope.clickedclosed === null) {
957                         if (!$scope.clickedopen) {
958                             $scope.clickedclosed = true;
959                         }
960                     } else {
961                         $scope.clickedclosed = !$scope.clickedopen;
962                     }
963
964                     if ($scope.selected && $scope.selected.length > 0) $scope.complete_list = true;
965                     if (!$scope.selected || $scope.selected.length == 0) $scope.complete_list = false;
966                     $scope.makeOpen();
967                 }
968
969                 $scope.makeOpen = function () {
970                     $scope.isopen = $scope.clickedopen || ($filter('filter')(
971                         $scope.list,
972                         $scope.selected
973                     ).length > 0 && $scope.selected.length > 0);
974                     if ($scope.clickedclosed) {
975                         $scope.isopen = false;
976                         $scope.clickedclosed = null;
977                     }
978                 }
979
980                 $scope.changeValue = function (newVal) {
981                     $scope.selected = newVal;
982                     $scope.isopen = false;
983                     $scope.clickedclosed = null;
984                     $scope.clickedopen = false;
985                     if ($scope.selected.length == 0) $scope.complete_list = false;
986                     if ($scope.onSelect) $scope.onSelect();
987                 }
988
989             }
990         ]
991     };
992 })
993
994 /**
995  * Nested org unit selector modeled as a Bootstrap dropdown button.
996  */
997 .directive('egOrgSelector', function() {
998     return {
999         restrict : 'AE',
1000         transclude : true,
1001         replace : true, // makes styling easier
1002         scope : {
1003             selected : '=', // defaults to workstation or root org,
1004                             // unless the nodefault attibute exists
1005
1006             // Each org unit is passed into this function and, for
1007             // any org units where the response value is true, the
1008             // org unit will not be added to the selector.
1009             hiddenTest : '=',
1010
1011             // Each org unit is passed into this function and, for
1012             // any org units where the response value is true, the
1013             // org unit will not be available for selection.
1014             disableTest : '=',
1015
1016             // if set to true, disable the UI element altogether
1017             alldisabled : '@',
1018
1019             // Caller can either $watch(selected, ..) or register an
1020             // onchange handler.
1021             onchange : '=',
1022
1023             // optional primary drop-down button label
1024             label : '@',
1025
1026             // optional name of settings key for persisting
1027             // the last selected org unit
1028             stickySetting : '@'
1029         },
1030
1031         // any reason to move this into a TT2 template?
1032         template : 
1033             '<div class="btn-group eg-org-selector" uib-dropdown>'
1034             + '<button type="button" class="btn btn-default" uib-dropdown-toggle ng-disabled="disable_button">'
1035              + '<span style="padding-right: 5px;">{{getSelectedName()}}</span>'
1036              + '<span class="caret"></span>'
1037            + '</button>'
1038            + '<ul uib-dropdown-menu class="scrollable-menu">'
1039              + '<li ng-repeat="org in orgList" ng-hide="hiddenTest(org.id)">'
1040                + '<a href ng-click="orgChanged(org)" a-disabled="disableTest(org.id)" '
1041                  + 'style="padding-left: {{org.depth * 10 + 5}}px">'
1042                  + '{{org.shortname}}'
1043                + '</a>'
1044              + '</li>'
1045            + '</ul>'
1046           + '</div>',
1047
1048         controller : ['$scope','$timeout','egCore','egStartup','egLovefield','$q',
1049               function($scope , $timeout , egCore , egStartup , egLovefield , $q) {
1050
1051             if ($scope.alldisabled) {
1052                 $scope.disable_button = $scope.alldisabled == 'true' ? true : false;
1053             } else {
1054                 $scope.disable_button = false;
1055             }
1056
1057             // avoid linking the full fleshed tree to the scope by 
1058             // tossing in a flattened list.
1059             // --
1060             // Run-time code referencing post-start data should be run
1061             // from within a startup block, otherwise accessing this
1062             // module before startup completes will lead to failure.
1063             //
1064             // controller() runs before link().
1065             // This post-startup code runs after link().
1066             egStartup.go(
1067             ).then(
1068                 function() {
1069                     return egCore.env.classLoaders.aou();
1070                 }
1071             ).then(
1072                 function() {
1073
1074                     $scope.orgList = egCore.org.list().map(function(org) {
1075                         return {
1076                             id : org.id(),
1077                             shortname : org.shortname(), 
1078                             depth : org.ou_type().depth()
1079                         }
1080                     });
1081                     
1082     
1083                     // Apply default values
1084     
1085                     if ($scope.stickySetting) {
1086                         var orgId = egCore.hatch.getLocalItem($scope.stickySetting);
1087                         if (orgId) {
1088                             $scope.selected = egCore.org.get(orgId);
1089                         }
1090                     }
1091     
1092                     if (!$scope.selected && !$scope.nodefault && egCore.auth.user()) {
1093                         $scope.selected = 
1094                             egCore.org.get(egCore.auth.user().ws_ou());
1095                     }
1096     
1097                     fire_orgsel_onchange(); // no-op if nothing is selected
1098                 }
1099             );
1100
1101             /**
1102              * Fire onchange handler after a timeout, so the
1103              * $scope.selected value has a chance to propagate to
1104              * the page controllers before the onchange fires.  This
1105              * way, the caller does not have to manually capture the
1106              * $scope.selected value during onchange.
1107              */
1108             function fire_orgsel_onchange() {
1109                 if (!$scope.selected || !$scope.onchange) return;
1110                 $timeout(function() {
1111                     console.debug(
1112                         'egOrgSelector onchange('+$scope.selected.id()+')');
1113                     $scope.onchange($scope.selected)
1114                 });
1115             }
1116
1117             $scope.getSelectedName = function() {
1118                 if ($scope.selected && $scope.selected.shortname)
1119                     return $scope.selected.shortname();
1120                 return $scope.label;
1121             }
1122
1123             $scope.orgChanged = function(org) {
1124                 $scope.selected = egCore.org.get(org.id);
1125                 if ($scope.stickySetting) {
1126                     egCore.hatch.setLocalItem($scope.stickySetting, org.id);
1127                 }
1128                 fire_orgsel_onchange();
1129             }
1130
1131         }],
1132         link : function(scope, element, attrs, egGridCtrl) {
1133
1134             // boolean fields are presented as value-less attributes
1135             angular.forEach(
1136                 ['nodefault'],
1137                 function(field) {
1138                     if (angular.isDefined(attrs[field]))
1139                         scope[field] = true;
1140                     else
1141                         scope[field] = false;
1142                 }
1143             );
1144         }
1145     }
1146 })
1147
1148 .directive('nextOnEnter', function () {
1149     return function (scope, element, attrs) {
1150         element.bind("keydown keypress", function (event) {
1151             if(event.which === 13) {
1152                 $('#'+attrs.nextOnEnter).focus();
1153                 event.preventDefault();
1154             }
1155         });
1156     };
1157 })
1158
1159 /* http://eric.sau.pe/angularjs-detect-enter-key-ngenter/ */
1160 .directive('egEnter', function () {
1161     return function (scope, element, attrs) {
1162         element.bind("keydown keypress", function (event) {
1163             if(event.which === 13) {
1164                 scope.$apply(function (){
1165                     scope.$eval(attrs.egEnter);
1166                 });
1167  
1168                 event.preventDefault();
1169             }
1170         });
1171     };
1172 })
1173
1174 /*
1175 * Handy wrapper directive for uib-datapicker-popup
1176 */
1177 .directive(
1178     'egDateInput', ['egStrings', 'egCore',
1179     function(egStrings, egCore) {
1180         return {
1181             scope : {
1182                 id : '@',
1183                 closeText : '@',
1184                 ngModel : '=',
1185                 ngChange : '=',
1186                 ngBlur : '=',
1187                 minDate : '=?',
1188                 maxDate : '=?',
1189                 ngDisabled : '=',
1190                 ngRequired : '=',
1191                 hideDatePicker : '=',
1192                 dateFormat : '=?',
1193                 outOfRange : '=?',
1194                 focusMe : '=?'
1195             },
1196             require: 'ngModel',
1197             templateUrl: './share/t_datetime',
1198             replace: true,
1199             controller : ['$scope', function($scope) {
1200                 $scope.options = {
1201                     minDate : $scope.minDate,
1202                     maxDate : $scope.maxDate
1203                 };
1204
1205                 var maxDateObj = $scope.maxDate ? new Date($scope.maxDate) : null;
1206                 var minDateObj = $scope.minDate ? new Date($scope.minDate) : null;
1207
1208                 if ($scope.outOfRange !== undefined && (maxDateObj || minDateObj)) {
1209                     $scope.$watch('ngModel', function (n,o) {
1210                         if (n && n != o) {
1211                             var bad = false;
1212                             var newdate = new Date(n);
1213                             if (maxDateObj && newdate.getTime() > maxDateObj.getTime()) bad = true;
1214                             if (minDateObj && newdate.getTime() < minDateObj.getTime()) bad = true;
1215                             $scope.outOfRange = bad;
1216                         }
1217                     });
1218                 }
1219             }],
1220             link : function(scope, elm, attrs) {
1221                 if (!scope.closeText)
1222                     scope.closeText = egStrings.EG_DATE_INPUT_CLOSE_TEXT;
1223
1224                 if ('showTimePicker' in attrs)
1225                     scope.showTimePicker = true;
1226
1227                 var default_format = 'mediumDate';
1228                 egCore.org.settings(['format.date']).then(function(set) {
1229                     default_format = set['format.date'];
1230                     scope.date_format = (scope.dateFormat) ?
1231                         scope.dateFormat :
1232                         default_format;
1233                 });
1234             }
1235         };
1236     }
1237 ])
1238
1239 /*
1240  *  egFmValueSelector - widget for selecting a value from list specified
1241  *                      by IDL class
1242  */
1243 .directive('egFmValueSelector', function() {
1244     return {
1245         restrict : 'E',
1246         transclude : true,
1247         scope : {
1248             idlClass : '@',
1249             ngModel : '=',
1250
1251             // optional filter for refining the set of rows that
1252             // get returned. Example:
1253             //
1254             // filter="{'column':{'=':null}}"
1255             filter : '=',
1256
1257             // optional name of settings key for persisting
1258             // the last selected value
1259             stickySetting : '@',
1260
1261             // optional OU setting for fetching default value;
1262             // used only if sticky setting not set
1263             ouSetting : '@'
1264         },
1265         require: 'ngModel',
1266         templateUrl : './share/t_fm_value_selector',
1267         controller : ['$scope','egCore', function($scope , egCore) {
1268
1269             $scope.org = egCore.org; // for use in the link function
1270             $scope.auth = egCore.auth; // for use in the link function
1271             $scope.hatch = egCore.hatch // for use in the link function
1272
1273             function flatten_linked_values(cls, list) {
1274                 var results = [];
1275                 var fields = egCore.idl.classes[cls].fields;
1276                 var id_field;
1277                 var selector;
1278                 angular.forEach(fields, function(fld) {
1279                     if (fld.datatype == 'id') {
1280                         id_field = fld.name;
1281                         selector = fld.selector ? fld.selector : id_field;
1282                         return;
1283                     }
1284                 });
1285                 angular.forEach(list, function(item) {
1286                     var rec = egCore.idl.toHash(item);
1287                     results.push({
1288                         id : rec[id_field],
1289                         name : rec[selector]
1290                     });
1291                 });
1292                 return results;
1293             }
1294
1295             var search = {};
1296             search[egCore.idl.classes[$scope.idlClass].pkey] = {'!=' : null};
1297             if ($scope.filter) {
1298                 angular.extend(search, $scope.filter);
1299             }
1300             egCore.pcrud.search(
1301                 $scope.idlClass, search, {}, {atomic : true}
1302             ).then(function(list) {
1303                 $scope.linked_values = flatten_linked_values($scope.idlClass, list);
1304             });
1305
1306             $scope.handleChange = function(value) {
1307                 if ($scope.stickySetting) {
1308                     egCore.hatch.setLocalItem($scope.stickySetting, value);
1309                 }
1310             }
1311
1312         }],
1313         link : function(scope, element, attrs) {
1314             if (scope.stickySetting && (angular.isUndefined(scope.ngModel) || (scope.ngModel === null))) {
1315                 var value = scope.hatch.getLocalItem(scope.stickySetting);
1316                 scope.ngModel = value;
1317             }
1318             if (scope.ouSetting && (angular.isUndefined(scope.ngModel) || (scope.ngModel === null))) {
1319                 scope.org.settings([scope.ouSetting], scope.auth.user().ws_ou())
1320                 .then(function(set) {
1321                     var value = parseInt(set[scope.ouSetting]);
1322                     if (!isNaN(value))
1323                         scope.ngModel = value;
1324                 });
1325             }
1326         }
1327     }
1328 })
1329
1330 /*
1331  *  egShareDepthSelector - widget for selecting a share depth
1332  */
1333 .directive('egShareDepthSelector', function() {
1334     return {
1335         restrict : 'E',
1336         transclude : true,
1337         scope : {
1338             ngModel : '=',
1339         },
1340         require: 'ngModel',
1341         templateUrl : './share/t_share_depth_selector',
1342         controller : ['$scope','egCore', function($scope , egCore) {
1343             $scope.values = [];
1344             egCore.pcrud.search('aout',
1345                 { id : {'!=' : null} },
1346                 { order_by : {aout : ['depth', 'name']} },
1347                 { atomic : true }
1348             ).then(function(list) {
1349                 var scratch = [];
1350                 angular.forEach(list, function(aout) {
1351                     var depth = parseInt(aout.depth());
1352                     if (depth in scratch) {
1353                         scratch[depth].push(aout.name());
1354                     } else {
1355                         scratch[depth] = [ aout.name() ]
1356                     }
1357                 });
1358                 scratch.forEach(function(val, idx) {
1359                     $scope.values.push({ id : idx,  name : scratch[idx].join(' / ') });
1360                 });
1361             });
1362         }]
1363     }
1364 })
1365
1366 /*
1367  * egHelpPopover - a helpful widget
1368  */
1369 .directive('egHelpPopover', function() {
1370     return {
1371         restrict : 'E',
1372         transclude : true,
1373         scope : {
1374             helpText : '@',
1375             helpLink : '@'
1376         },
1377         templateUrl : './share/t_help_popover',
1378         controller : ['$scope','$sce', function($scope , $sce) {
1379             if ($scope.helpLink) {
1380                 $scope.helpHtml = $sce.trustAsHtml(
1381                     '<a target="_new" href="' + $scope.helpLink + '">' +
1382                     $scope.helpText + '</a>'
1383                 );
1384             }
1385         }]
1386     }
1387 })
1388
1389 .factory('egWorkLog', ['egCore', function(egCore) {
1390     var service = {};
1391
1392     service.retrieve_all = function() {
1393         var workLog = egCore.hatch.getLocalItem('eg.work_log') || [];
1394         var patronLog = egCore.hatch.getLocalItem('eg.patron_log') || [];
1395
1396         return { 'work_log' : workLog, 'patron_log' : patronLog };
1397     }
1398
1399     service.record = function(message,data) {
1400         var max_entries;
1401         var max_patrons;
1402         if (typeof egCore != 'undefined') {
1403             if (typeof egCore.env != 'undefined') {
1404                 if (typeof egCore.env.aous != 'undefined') {
1405                     max_entries = egCore.env.aous['ui.admin.work_log.max_entries'];
1406                     max_patrons = egCore.env.aous['ui.admin.patron_log.max_entries'];
1407                 } else {
1408                     console.log('worklog: missing egCore.env.aous');
1409                 }
1410             } else {
1411                 console.log('worklog: missing egCore.env');
1412             }
1413         } else {
1414             console.log('worklog: missing egCore');
1415         }
1416         if (!max_entries) {
1417             if (typeof egCore.org != 'undefined') {
1418                 if (typeof egCore.org.cachedSettings != 'undefined') {
1419                     max_entries = egCore.org.cachedSettings['ui.admin.work_log.max_entries'];
1420                 } else {
1421                     console.log('worklog: missing egCore.org.cachedSettings');
1422                 }
1423             } else {
1424                 console.log('worklog: missing egCore.org');
1425             }
1426         }
1427         if (!max_patrons) {
1428             if (typeof egCore.org != 'undefined') {
1429                 if (typeof egCore.org.cachedSettings != 'undefined') {
1430                     max_patrons = egCore.org.cachedSettings['ui.admin.patron_log.max_entries'];
1431                 } else {
1432                     console.log('worklog: missing egCore.org.cachedSettings');
1433                 }
1434             } else {
1435                 console.log('worklog: missing egCore.org');
1436             }
1437         }
1438         if (!max_entries) {
1439             max_entries = 20;
1440             console.log('worklog: defaulting to max_entries = ' + max_entries);
1441         }
1442         if (!max_patrons) {
1443             max_patrons = 10;
1444             console.log('worklog: defaulting to max_patrons = ' + max_patrons);
1445         }
1446
1447         var workLog = egCore.hatch.getLocalItem('eg.work_log') || [];
1448         var patronLog = egCore.hatch.getLocalItem('eg.patron_log') || [];
1449         var entry = {
1450             'when' : new Date(),
1451             'msg' : message,
1452             'action' : data.action,
1453             'actor' : egCore.auth.user().usrname()
1454         };
1455         if (data.action == 'checkin') {
1456             entry['item'] = data.response.params.copy_barcode;
1457             entry['item_id'] = data.response.data.acp.id();
1458             if (data.response.data.au) {
1459                 entry['user'] = data.response.data.au.family_name();
1460                 entry['patron_id'] = data.response.data.au.id();
1461             }
1462         }
1463         if (data.action == 'checkout') {
1464             entry['item'] = data.response.params.copy_barcode;
1465             entry['user'] = data.response.data.au.family_name();
1466             entry['item_id'] = data.response.data.acp.id();
1467             entry['patron_id'] = data.response.data.au.id();
1468         }
1469         if (data.action == 'noncat_checkout') {
1470             entry['user'] = data.response.data.au.family_name();
1471             entry['patron_id'] = data.response.data.au.id();
1472         }
1473         if (data.action == 'renew') {
1474             entry['item'] = data.response.params.copy_barcode;
1475             entry['user'] = data.response.data.au.family_name();
1476             entry['item_id'] = data.response.data.acp.id();
1477             entry['patron_id'] = data.response.data.au.id();
1478         }
1479         if (data.action == 'requested_hold'
1480             || data.action == 'edited_patron'
1481             || data.action == 'registered_patron'
1482             || data.action == 'paid_bill') {
1483             entry['patron_id'] = data.patron_id;
1484         }
1485         if (data.action == 'requested_hold') {
1486             entry['hold_id'] = data.hold_id;
1487         }
1488         if (data.action == 'paid_bill') {
1489             entry['amount'] = data.total_amount;
1490         }
1491
1492         workLog.push( entry );
1493         if (workLog.length > max_entries) workLog.shift();
1494         egCore.hatch.setLocalItem('eg.work_log',workLog); // hatch JSONifies the data, so should be okay re: memory leaks?
1495
1496         if (entry['patron_id']) {
1497             var temp = [];
1498             for (var i = 0; i < patronLog.length; i++) { // filter out any matching patron
1499                 if (patronLog[i]['patron_id'] != entry['patron_id']) temp.push(patronLog[i]);
1500             }
1501             temp.push( entry );
1502             if (temp.length > max_patrons) temp.shift();
1503             patronLog = temp;
1504             egCore.hatch.setLocalItem('eg.patron_log',patronLog);
1505         }
1506
1507         console.log('worklog',entry);
1508     }
1509
1510     return service;
1511 }]);