]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/services/ui.js
51aac05ad7e56e164c5f667ecea69da6170eb922
[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
77 // 'reverse' filter 
78 // <div ng-repeat="item in items | reverse">{{item.name}}</div>
79 // http://stackoverflow.com/questions/15266671/angular-ng-repeat-in-reverse
80 // TODO: perhaps this should live elsewhere
81 .filter('reverse', function() {
82     return function(items) {
83         return items.slice().reverse();
84     };
85 })
86
87 // 'date' filter
88 // Overriding the core angular date filter with a moment-js based one for
89 // better timezone and formatting support.
90 .filter('date',function() {
91
92     var formatMap = {
93         short  : 'l LT',
94         medium : 'lll',
95         long   : 'LLL',
96         full   : 'LLLL',
97
98         shortDate  : 'l',
99         mediumDate : 'll',
100         longDate   : 'LL',
101         fullDate   : 'LL',
102
103         shortTime  : 'LT',
104         mediumTime : 'LTS'
105     };
106
107     var formatReplace = [
108         [ /yyyy/g, 'YYYY' ],
109         [ /yy/g,   'YY'   ],
110         [ /y/g,    'Y'    ],
111         [ /ww/g,   'WW'   ],
112         [ /w/g,    'W'    ],
113         [ /dd/g,   'DD'   ],
114         [ /d/g,    'D'    ],
115         [ /sss/g,  'SSS'  ],
116         [ /EEEE/g, 'dddd' ],
117         [ /EEE/g,  'ddd'  ],
118         [ /Z/g,    'ZZ'   ]
119     ];
120
121     return function (date, format, tz) {
122         if (!date) return '';
123
124         if (date == 'now') 
125             date = new Date().toISOString();
126
127         if (format) {
128             var fmt = formatMap[format] || format;
129             angular.forEach(formatReplace, function (r) {
130                 fmt = fmt.replace(r[0],r[1]);
131             });
132         }
133
134         var d = moment(date);
135         if (tz && tz !== '-') d.tz(tz);
136
137         return d.isValid() ? d.format(fmt) : '';
138     }
139
140 })
141
142 // 'egOrgDate' filter
143 // Uses moment.js and moment-timezone.js to put dates into the most appropriate
144 // timezone for a given (optional) org unit based on its lib.timezone setting
145 .filter('egOrgDate',['$filter','egCore',
146              function($filter , egCore) {
147
148     var tzcache = {};
149
150     function eg_date_filter (date, fmt, ouID) {
151         if (ouID) {
152             if (angular.isObject(ouID)) {
153                 if (angular.isFunction(ouID.id)) {
154                     ouID = ouID.id();
155                 } else {
156                     ouID = ouID.id;
157                 }
158             }
159     
160             if (!tzcache[ouID]) {
161                 tzcache[ouID] = '-';
162                 egCore.org.settings('lib.timezone', ouID)
163                 .then(function(s) {
164                     tzcache[ouID] = s['lib.timezone'] || OpenSRF.tz;
165                 });
166             }
167         }
168
169         return $filter('date')(date, fmt, tzcache[ouID]);
170     }
171
172     eg_date_filter.$stateful = true;
173
174     return eg_date_filter;
175 }])
176
177 // 'egOrgDateInContext' filter
178 // Uses the egOrgDate filter to make time and date location aware, and further
179 // modifies the format if one of [short, medium, long, full] to show only the
180 // date if the optional interval parameter is day-granular.  This is
181 // particularly useful for due dates on circulations.
182 .filter('egOrgDateInContext',['$filter','egCore',
183                       function($filter , egCore) {
184
185     function eg_context_date_filter (date, format, orgID, interval) {
186         var fmt = format;
187         if (!fmt) fmt = 'shortDate';
188
189         // if this is a simple, one-word format, and it doesn't say "Date" in it...
190         if (['short','medium','long','full'].filter(function(x){return fmt == x}).length > 0 && interval) {
191             var secs = egCore.date.intervalToSeconds(interval);
192             if (secs !== null && secs % 86400 == 0) fmt += 'Date';
193         }
194
195         return $filter('egOrgDate')(date, fmt, orgID);
196     }
197
198     eg_context_date_filter.$stateful = true;
199
200     return eg_context_date_filter;
201 }])
202
203 // 'egDueDate' filter
204 // Uses the egOrgDateInContext filter to make time and date location aware, but
205 // only if the supplied interval is day-granular.  This is as wrapper for
206 // egOrgDateInContext to be used for circulation due date /only/.
207 .filter('egDueDate',['$filter','egCore',
208                       function($filter , egCore) {
209
210     function eg_context_due_date_filter (date, format, orgID, interval) {
211         if (interval) {
212             var secs = egCore.date.intervalToSeconds(interval);
213             if (secs === null || secs % 86400 != 0) {
214                 orgID = null;
215                 interval = null;
216             }
217         }
218         return $filter('egOrgDateInContext')(date, format, orgID, interval);
219     }
220
221     eg_context_due_date_filter.$stateful = true;
222
223     return eg_context_due_date_filter;
224 }])
225
226 // 'join' filter
227 // TODO: perhaps this should live elsewhere
228 .filter('join', function() {
229     return function(arr,sep) {
230         if (typeof arr == 'object' && arr.constructor == Array) {
231             return arr.join(sep || ',');
232         } else {
233             return '';
234         }
235     };
236 })
237
238 /**
239  * Progress Dialog. 
240  *
241  * egProgressDialog.open();
242  * egProgressDialog.open({value : 0});
243  * egProgressDialog.open({value : 0, max : 123});
244  * egProgressDialog.increment();
245  * egProgressDialog.increment();
246  * egProgressDialog.close();
247  *
248  * Each dialog has 2 numbers, 'max' and 'value'.
249  * The content of these values determines how the dialog displays.  
250  *
251  * There are 3 flavors:
252  *
253  * -- value is set, max is set
254  * determinate: shows a progression with a percent complete.
255  *
256  * -- value is set, max is unset
257  * semi-determinate, with a value report.  Shows a value-less
258  * <progress/>, but shows the value as a number in the dialog.
259  *
260  * This is useful in cases where the total number of items to retrieve
261  * from the server is unknown, but we know how many items we've
262  * retrieved thus far.  It helps to reinforce that something specific
263  * is happening, but we don't know when it will end.
264  *
265  * -- value is unset
266  * indeterminate: shows a generic value-less <progress/> with no 
267  * clear indication of progress.
268  *
269  * Only 1 egProgressDialog instance will be activate at a time.
270  * Each invocation of .open() destroys any existing instance.
271  */
272
273 /* Simple storage class for egProgressDialog data maintenance.
274  * This data lives outside of egProgressDialog so it can be 
275  * directly imported into egProgressDialog's $uibModalInstance.
276  */
277 .factory('egProgressData', [
278     function() {
279         var service = {}; // max/value initially unset
280
281         service.reset = function() {
282             delete service.max;
283             delete service.value;
284         }
285
286         service.hasvalue = function() {
287             return Number.isInteger(service.value);
288         }
289
290         service.hasmax = function() {
291             return Number.isInteger(service.max);
292         }
293
294         service.percent = function() {
295             if (service.hasvalue()  && 
296                 service.hasmax()    && 
297                 service.max > 0     &&
298                 service.value <= service.max)
299                 return Math.floor((service.value / service.max) * 100);
300             return 100;
301         }
302
303         return service;
304     }
305 ])
306
307 .factory('egProgressDialog', [
308             'egProgressData','$uibModal', 
309     function(egProgressData , $uibModal) {
310     var service = {};
311
312     service.open = function(args) {
313         service.close(); // force-kill existing instances.
314
315         // Reset to an indeterminate progress bar, 
316         // overlay with caller values.
317         egProgressData.reset();
318         service.update(angular.extend({}, args));
319
320         return $uibModal.open({
321             templateUrl: './share/t_progress_dialog',
322             controller: ['$scope','$uibModalInstance','egProgressData',
323                 function( $scope , $uibModalInstance , egProgressData) {
324                   service.currentInstance = $uibModalInstance;
325                   $scope.data = egProgressData; // tiny service
326                 }
327             ]
328         });
329     };
330
331     service.close = function() {
332         if (service.currentInstance) {
333             service.currentInstance.close();
334             delete service.currentInstance;
335         }
336     }
337
338     // Set the current state of the progress bar.
339     service.update = function(args) {
340         if (args.max != undefined) 
341             egProgressData.max = args.max;
342         if (args.value != undefined) 
343             egProgressData.value = args.value;
344     }
345
346     // Increment the current value.  If no amount is specified,
347     // it increments by 1.  Calling increment() on an indetermite
348     // progress bar will force it to be a (semi-)determinate bar.
349     service.increment = function(amt) {
350         if (!Number.isInteger(amt)) amt = 1;
351
352         if (!egProgressData.hasvalue())
353             egProgressData.value = 0;
354
355         egProgressData.value += amt;
356     }
357
358     return service;
359 }])
360
361 /**
362  * egAlertDialog.open({message : 'hello {{name}}'}).result.then(
363  *     function() { console.log('alert closed') });
364  */
365 .factory('egAlertDialog', 
366
367         ['$uibModal','$interpolate',
368 function($uibModal , $interpolate) {
369     var service = {};
370
371     service.open = function(message, msg_scope) {
372         return $uibModal.open({
373             templateUrl: './share/t_alert_dialog',
374             controller: ['$scope', '$uibModalInstance',
375                 function($scope, $uibModalInstance) {
376                     $scope.message = $interpolate(message)(msg_scope);
377                     $scope.ok = function() {
378                         if (msg_scope && msg_scope.ok) msg_scope.ok();
379                         $uibModalInstance.close()
380                     }
381                 }
382             ]
383         });
384     }
385
386     return service;
387 }])
388
389 /**
390  * egConfirmDialog.open("some message goes {{here}}", {
391  *  here : 'foo', ok : function() {}, cancel : function() {}},
392  *  'OK', 'Cancel');
393  */
394 .factory('egConfirmDialog', 
395     
396        ['$uibModal','$interpolate',
397 function($uibModal, $interpolate) {
398     var service = {};
399
400     service.open = function(title, message, msg_scope, ok_button_label, cancel_button_label) {
401         return $uibModal.open({
402             templateUrl: './share/t_confirm_dialog',
403             controller: ['$scope', '$uibModalInstance',
404                 function($scope, $uibModalInstance) {
405                     $scope.title = $interpolate(title)(msg_scope);
406                     $scope.message = $interpolate(message)(msg_scope);
407                     $scope.ok_button_label = $interpolate(ok_button_label || '')(msg_scope);
408                     $scope.cancel_button_label = $interpolate(cancel_button_label || '')(msg_scope);
409                     $scope.ok = function() {
410                         if (msg_scope.ok) msg_scope.ok();
411                         $uibModalInstance.close()
412                     }
413                     $scope.cancel = function() {
414                         if (msg_scope.cancel) msg_scope.cancel();
415                         $uibModalInstance.dismiss();
416                     }
417                 }
418             ]
419         })
420     }
421
422     return service;
423 }])
424
425 /**
426  * egPromptDialog.open(
427  *    "prompt message goes {{here}}", 
428  *    promptValue,  // optional
429  *    {
430  *      here : 'foo',  
431  *      ok : function(value) {console.log(value)}, 
432  *      cancel : function() {console.log('prompt denied')}
433  *    }
434  *  );
435  */
436 .factory('egPromptDialog', 
437     
438        ['$uibModal','$interpolate',
439 function($uibModal, $interpolate) {
440     var service = {};
441
442     service.open = function(message, promptValue, msg_scope) {
443         return $uibModal.open({
444             templateUrl: './share/t_prompt_dialog',
445             controller: ['$scope', '$uibModalInstance',
446                 function($scope, $uibModalInstance) {
447                     $scope.message = $interpolate(message)(msg_scope);
448                     $scope.args = {value : promptValue || ''};
449                     $scope.focus = true;
450                     $scope.ok = function() {
451                         if (msg_scope.ok) msg_scope.ok($scope.args.value);
452                         $uibModalInstance.close()
453                     }
454                     $scope.cancel = function() {
455                         if (msg_scope.cancel) msg_scope.cancel();
456                         $uibModalInstance.dismiss();
457                     }
458                 }
459             ]
460         })
461     }
462
463     return service;
464 }])
465
466 /**
467  * egSelectDialog.open(
468  *    "message goes {{here}}", 
469  *    list,           // ['values','for','dropdown'],
470  *    selectedValue,  // optional
471  *    {
472  *      here : 'foo',
473  *      ok : function(value) {console.log(value)}, 
474  *      cancel : function() {console.log('prompt denied')}
475  *    }
476  *  );
477  */
478 .factory('egSelectDialog', 
479     
480        ['$uibModal','$interpolate',
481 function($uibModal, $interpolate) {
482     var service = {};
483
484     service.open = function(message, inputList, selectedValue, msg_scope) {
485         return $uibModal.open({
486             templateUrl: './share/t_select_dialog',
487             controller: ['$scope', '$uibModalInstance',
488                 function($scope, $uibModalInstance) {
489                     $scope.message = $interpolate(message)(msg_scope);
490                     $scope.args = {
491                         list  : inputList,
492                         value : selectedValue
493                     };
494                     $scope.focus = true;
495                     $scope.ok = function() {
496                         if (msg_scope.ok) msg_scope.ok($scope.args.value);
497                         $uibModalInstance.close()
498                     }
499                     $scope.cancel = function() {
500                         if (msg_scope.cancel) msg_scope.cancel();
501                         $uibModalInstance.dismiss();
502                     }
503                 }
504             ]
505         })
506     }
507
508     return service;
509 }])
510
511 /**
512  * Warn on page unload and give the user a chance to avoid navigating
513  * away from the current page.  
514  * Only one handler is supported per page.
515  * NOTE: we can't use an egUnloadDialog as the dialog builder, because
516  * it renders asynchronously, which allows the page to redirect before
517  * the dialog appears.
518  */
519 .factory('egUnloadPrompt', [
520         '$window','egStrings', 
521 function($window , egStrings) {
522     var service = {attached : false};
523
524     // attach a page/scope unload prompt
525     service.attach = function($scope, msg) {
526         if (service.attached) return;
527         service.attached = true;
528
529         // handle page change
530         $($window).on('beforeunload', function() { 
531             service.clear();
532             return msg || egStrings.EG_UNLOAD_PAGE_PROMPT_MSG;
533         });
534
535         if (!$scope) return;
536
537         // If a scope was provided, attach a scope-change handler,
538         // similar to the page-page prompt.
539         service.locChangeCancel = 
540             $scope.$on('$locationChangeStart', function(evt, next, current) {
541             if (confirm(msg || egStrings.EG_UNLOAD_CTRL_PROMPT_MSG)) {
542                 // user allowed the page to change.  
543                 // Clear the unload handler.
544                 service.clear();
545             } else {
546                 evt.preventDefault();
547             }
548         });
549     };
550
551     // remove the page unload prompt
552     service.clear = function() {
553         $($window).off('beforeunload');
554         if (service.locChangeCancel)
555             service.locChangeCancel();
556         service.attached = false;
557     }
558
559     return service;
560 }])
561
562 .directive('aDisabled', function() {
563     return {
564         restrict : 'A',
565         compile: function(tElement, tAttrs, transclude) {
566             //Disable ngClick
567             tAttrs["ngClick"] = ("ng-click", "!("+tAttrs["aDisabled"]+") && ("+tAttrs["ngClick"]+")");
568
569             //Toggle "disabled" to class when aDisabled becomes true
570             return function (scope, iElement, iAttrs) {
571                 scope.$watch(iAttrs["aDisabled"], function(newValue) {
572                     if (newValue !== undefined) {
573                         iElement.toggleClass("disabled", newValue);
574                     }
575                 });
576
577                 //Disable href on click
578                 iElement.on("click", function(e) {
579                     if (scope.$eval(iAttrs["aDisabled"])) {
580                         e.preventDefault();
581                     }
582                 });
583             };
584         }
585     };
586 })
587
588 .directive('egBasicComboBox', function() {
589     return {
590         restrict: 'E',
591         replace: true,
592         scope: {
593             list: "=", // list of strings
594             selected: "=",
595             onSelect: "=",
596             egDisabled: "=",
597             allowAll: "@",
598             placeholder: "@",
599             focusMe: "=?"
600         },
601         template:
602             '<div class="input-group">'+
603                 '<input placeholder="{{placeholder}}" type="text" ng-disabled="egDisabled" class="form-control" ng-model="selected" ng-change="makeOpen()" focus-me="focusMe">'+
604                 '<div class="input-group-btn" dropdown ng-class="{open:isopen}">'+
605                     '<button type="button" ng-click="showAll()" ng-disabled="egDisabled" class="btn btn-default dropdown-toggle"><span class="caret"></span></button>'+
606                     '<ul class="dropdown-menu dropdown-menu-right">'+
607                         '<li ng-repeat="item in list|filter:selected:compare"><a href ng-click="changeValue(item)">{{item}}</a></li>'+
608                         '<li ng-if="complete_list" class="divider"><span></span></li>'+
609                         '<li ng-if="complete_list" ng-repeat="item in list"><a href ng-click="changeValue(item)">{{item}}</a></li>'+
610                     '</ul>'+
611                 '</div>'+
612             '</div>',
613         controller: ['$scope','$filter',
614             function( $scope , $filter) {
615
616                 $scope.complete_list = false;
617                 $scope.isopen = false;
618                 $scope.clickedopen = false;
619                 $scope.clickedclosed = null;
620
621                 $scope.compare = function (ex, act) {
622                     if (act === null || act === undefined) return true;
623                     if (act.toString) act = act.toString();
624                     return new RegExp(act.toLowerCase()).test(ex)
625                 }
626
627                 $scope.showAll = function () {
628
629                     $scope.clickedopen = !$scope.clickedopen;
630
631                     if ($scope.clickedclosed === null) {
632                         if (!$scope.clickedopen) {
633                             $scope.clickedclosed = true;
634                         }
635                     } else {
636                         $scope.clickedclosed = !$scope.clickedopen;
637                     }
638
639                     if ($scope.selected && $scope.selected.length > 0) $scope.complete_list = true;
640                     if (!$scope.selected || $scope.selected.length == 0) $scope.complete_list = false;
641                     $scope.makeOpen();
642                 }
643
644                 $scope.makeOpen = function () {
645                     $scope.isopen = $scope.clickedopen || ($filter('filter')(
646                         $scope.list,
647                         $scope.selected
648                     ).length > 0 && $scope.selected.length > 0);
649                     if ($scope.clickedclosed) {
650                         $scope.isopen = false;
651                         $scope.clickedclosed = null;
652                     }
653                 }
654
655                 $scope.changeValue = function (newVal) {
656                     $scope.selected = newVal;
657                     $scope.isopen = false;
658                     $scope.clickedclosed = null;
659                     $scope.clickedopen = false;
660                     if ($scope.selected.length == 0) $scope.complete_list = false;
661                     if ($scope.onSelect) $scope.onSelect();
662                 }
663
664             }
665         ]
666     };
667 })
668
669 /**
670  * Nested org unit selector modeled as a Bootstrap dropdown button.
671  */
672 .directive('egOrgSelector', function() {
673     return {
674         restrict : 'AE',
675         transclude : true,
676         replace : true, // makes styling easier
677         scope : {
678             selected : '=', // defaults to workstation or root org,
679                             // unless the nodefault attibute exists
680
681             // Each org unit is passed into this function and, for
682             // any org units where the response value is true, the
683             // org unit will not be added to the selector.
684             hiddenTest : '=',
685
686             // Each org unit is passed into this function and, for
687             // any org units where the response value is true, the
688             // org unit will not be available for selection.
689             disableTest : '=',
690
691             // if set to true, disable the UI element altogether
692             alldisabled : '@',
693
694             // Caller can either $watch(selected, ..) or register an
695             // onchange handler.
696             onchange : '=',
697
698             // optional primary drop-down button label
699             label : '@',
700
701             // optional name of settings key for persisting
702             // the last selected org unit
703             stickySetting : '@'
704         },
705
706         // any reason to move this into a TT2 template?
707         template : 
708             '<div class="btn-group eg-org-selector" uib-dropdown>'
709             + '<button type="button" class="btn btn-default" uib-dropdown-toggle ng-disabled="disable_button">'
710              + '<span style="padding-right: 5px;">{{getSelectedName()}}</span>'
711              + '<span class="caret"></span>'
712            + '</button>'
713            + '<ul uib-dropdown-menu class="scrollable-menu">'
714              + '<li ng-repeat="org in orgList" ng-hide="hiddenTest(org.id)">'
715                + '<a href ng-click="orgChanged(org)" a-disabled="disableTest(org.id)" '
716                  + 'style="padding-left: {{org.depth * 10 + 5}}px">'
717                  + '{{org.shortname}}'
718                + '</a>'
719              + '</li>'
720            + '</ul>'
721           + '</div>',
722
723         controller : ['$scope','$timeout','egCore','egStartup','egLovefield','$q',
724               function($scope , $timeout , egCore , egStartup , egLovefield , $q) {
725
726             if ($scope.alldisabled) {
727                 $scope.disable_button = $scope.alldisabled == 'true' ? true : false;
728             } else {
729                 $scope.disable_button = false;
730             }
731
732             // avoid linking the full fleshed tree to the scope by 
733             // tossing in a flattened list.
734             // --
735             // Run-time code referencing post-start data should be run
736             // from within a startup block, otherwise accessing this
737             // module before startup completes will lead to failure.
738             //
739             // controller() runs before link().
740             // This post-startup code runs after link().
741             egStartup.go(
742             ).then(
743                 function() {
744                     return egCore.env.classLoaders.aou();
745                 }
746             ).then(
747                 function() {
748
749                     $scope.orgList = egCore.org.list().map(function(org) {
750                         return {
751                             id : org.id(),
752                             shortname : org.shortname(), 
753                             depth : org.ou_type().depth()
754                         }
755                     });
756                     
757     
758                     // Apply default values
759     
760                     if ($scope.stickySetting) {
761                         var orgId = egCore.hatch.getLocalItem($scope.stickySetting);
762                         if (orgId) {
763                             $scope.selected = egCore.org.get(orgId);
764                         }
765                     }
766     
767                     if (!$scope.selected && !$scope.nodefault && egCore.auth.user()) {
768                         $scope.selected = 
769                             egCore.org.get(egCore.auth.user().ws_ou());
770                     }
771     
772                     fire_orgsel_onchange(); // no-op if nothing is selected
773                 }
774             );
775
776             /**
777              * Fire onchange handler after a timeout, so the
778              * $scope.selected value has a chance to propagate to
779              * the page controllers before the onchange fires.  This
780              * way, the caller does not have to manually capture the
781              * $scope.selected value during onchange.
782              */
783             function fire_orgsel_onchange() {
784                 if (!$scope.selected || !$scope.onchange) return;
785                 $timeout(function() {
786                     console.debug(
787                         'egOrgSelector onchange('+$scope.selected.id()+')');
788                     $scope.onchange($scope.selected)
789                 });
790             }
791
792             $scope.getSelectedName = function() {
793                 if ($scope.selected && $scope.selected.shortname)
794                     return $scope.selected.shortname();
795                 return $scope.label;
796             }
797
798             $scope.orgChanged = function(org) {
799                 $scope.selected = egCore.org.get(org.id);
800                 if ($scope.stickySetting) {
801                     egCore.hatch.setLocalItem($scope.stickySetting, org.id);
802                 }
803                 fire_orgsel_onchange();
804             }
805
806         }],
807         link : function(scope, element, attrs, egGridCtrl) {
808
809             // boolean fields are presented as value-less attributes
810             angular.forEach(
811                 ['nodefault'],
812                 function(field) {
813                     if (angular.isDefined(attrs[field]))
814                         scope[field] = true;
815                     else
816                         scope[field] = false;
817                 }
818             );
819         }
820     }
821 })
822
823 .directive('nextOnEnter', function () {
824     return function (scope, element, attrs) {
825         element.bind("keydown keypress", function (event) {
826             if(event.which === 13) {
827                 $('#'+attrs.nextOnEnter).focus();
828                 event.preventDefault();
829             }
830         });
831     };
832 })
833
834 /* http://eric.sau.pe/angularjs-detect-enter-key-ngenter/ */
835 .directive('egEnter', function () {
836     return function (scope, element, attrs) {
837         element.bind("keydown keypress", function (event) {
838             if(event.which === 13) {
839                 scope.$apply(function (){
840                     scope.$eval(attrs.egEnter);
841                 });
842  
843                 event.preventDefault();
844             }
845         });
846     };
847 })
848
849 /*
850 * Handy wrapper directive for uib-datapicker-popup
851 */
852 .directive(
853     'egDateInput', ['egStrings', 'egCore',
854     function(egStrings, egCore) {
855         return {
856             scope : {
857                 id : '@',
858                 closeText : '@',
859                 ngModel : '=',
860                 ngChange : '=',
861                 ngBlur : '=',
862                 minDate : '=?',
863                 maxDate : '=?',
864                 ngDisabled : '=',
865                 ngRequired : '=',
866                 hideDatePicker : '=',
867                 dateFormat : '=?',
868                 outOfRange : '=?',
869                 focusMe : '=?'
870             },
871             require: 'ngModel',
872             templateUrl: './share/t_datetime',
873             replace: true,
874             controller : ['$scope', function($scope) {
875                 $scope.options = {
876                     minDate : $scope.minDate,
877                     maxDate : $scope.maxDate
878                 };
879
880                 var maxDateObj = $scope.maxDate ? new Date($scope.maxDate) : null;
881                 var minDateObj = $scope.minDate ? new Date($scope.minDate) : null;
882
883                 if ($scope.outOfRange !== undefined && (maxDateObj || minDateObj)) {
884                     $scope.$watch('ngModel', function (n,o) {
885                         if (n && n != o) {
886                             var bad = false;
887                             var newdate = new Date(n);
888                             if (maxDateObj && newdate.getTime() > maxDateObj.getTime()) bad = true;
889                             if (minDateObj && newdate.getTime() < minDateObj.getTime()) bad = true;
890                             $scope.outOfRange = bad;
891                         }
892                     });
893                 }
894             }],
895             link : function(scope, elm, attrs) {
896                 if (!scope.closeText)
897                     scope.closeText = egStrings.EG_DATE_INPUT_CLOSE_TEXT;
898
899                 if ('showTimePicker' in attrs)
900                     scope.showTimePicker = true;
901
902                 var default_format = 'mediumDate';
903                 egCore.org.settings(['format.date']).then(function(set) {
904                     default_format = set['format.date'];
905                     scope.date_format = (scope.dateFormat) ?
906                         scope.dateFormat :
907                         default_format;
908                 });
909             }
910         };
911     }
912 ])
913
914 /*
915  *  egFmValueSelector - widget for selecting a value from list specified
916  *                      by IDL class
917  */
918 .directive('egFmValueSelector', function() {
919     return {
920         restrict : 'E',
921         transclude : true,
922         scope : {
923             idlClass : '@',
924             ngModel : '=',
925
926             // optional filter for refining the set of rows that
927             // get returned. Example:
928             //
929             // filter="{'column':{'=':null}}"
930             filter : '=',
931
932             // optional name of settings key for persisting
933             // the last selected value
934             stickySetting : '@',
935
936             // optional OU setting for fetching default value;
937             // used only if sticky setting not set
938             ouSetting : '@'
939         },
940         require: 'ngModel',
941         templateUrl : './share/t_fm_value_selector',
942         controller : ['$scope','egCore', function($scope , egCore) {
943
944             $scope.org = egCore.org; // for use in the link function
945             $scope.auth = egCore.auth; // for use in the link function
946             $scope.hatch = egCore.hatch // for use in the link function
947
948             function flatten_linked_values(cls, list) {
949                 var results = [];
950                 var fields = egCore.idl.classes[cls].fields;
951                 var id_field;
952                 var selector;
953                 angular.forEach(fields, function(fld) {
954                     if (fld.datatype == 'id') {
955                         id_field = fld.name;
956                         selector = fld.selector ? fld.selector : id_field;
957                         return;
958                     }
959                 });
960                 angular.forEach(list, function(item) {
961                     var rec = egCore.idl.toHash(item);
962                     results.push({
963                         id : rec[id_field],
964                         name : rec[selector]
965                     });
966                 });
967                 return results;
968             }
969
970             var search = {};
971             search[egCore.idl.classes[$scope.idlClass].pkey] = {'!=' : null};
972             if ($scope.filter) {
973                 angular.extend(search, $scope.filter);
974             }
975             egCore.pcrud.search(
976                 $scope.idlClass, search, {}, {atomic : true}
977             ).then(function(list) {
978                 $scope.linked_values = flatten_linked_values($scope.idlClass, list);
979             });
980
981             $scope.handleChange = function(value) {
982                 if ($scope.stickySetting) {
983                     egCore.hatch.setLocalItem($scope.stickySetting, value);
984                 }
985             }
986
987         }],
988         link : function(scope, element, attrs) {
989             if (scope.stickySetting && (angular.isUndefined(scope.ngModel) || (scope.ngModel === null))) {
990                 var value = scope.hatch.getLocalItem(scope.stickySetting);
991                 scope.ngModel = value;
992             }
993             if (scope.ouSetting && (angular.isUndefined(scope.ngModel) || (scope.ngModel === null))) {
994                 scope.org.settings([scope.ouSetting], scope.auth.user().ws_ou())
995                 .then(function(set) {
996                     var value = parseInt(set[scope.ouSetting]);
997                     if (!isNaN(value))
998                         scope.ngModel = value;
999                 });
1000             }
1001         }
1002     }
1003 })
1004
1005 /*
1006  *  egShareDepthSelector - widget for selecting a share depth
1007  */
1008 .directive('egShareDepthSelector', function() {
1009     return {
1010         restrict : 'E',
1011         transclude : true,
1012         scope : {
1013             ngModel : '=',
1014         },
1015         require: 'ngModel',
1016         templateUrl : './share/t_share_depth_selector',
1017         controller : ['$scope','egCore', function($scope , egCore) {
1018             $scope.values = [];
1019             egCore.pcrud.search('aout',
1020                 { id : {'!=' : null} },
1021                 { order_by : {aout : ['depth', 'name']} },
1022                 { atomic : true }
1023             ).then(function(list) {
1024                 var scratch = [];
1025                 angular.forEach(list, function(aout) {
1026                     var depth = parseInt(aout.depth());
1027                     if (depth in scratch) {
1028                         scratch[depth].push(aout.name());
1029                     } else {
1030                         scratch[depth] = [ aout.name() ]
1031                     }
1032                 });
1033                 scratch.forEach(function(val, idx) {
1034                     $scope.values.push({ id : idx,  name : scratch[idx].join(' / ') });
1035                 });
1036             });
1037         }]
1038     }
1039 })
1040
1041 /*
1042  * egHelpPopover - a helpful widget
1043  */
1044 .directive('egHelpPopover', function() {
1045     return {
1046         restrict : 'E',
1047         transclude : true,
1048         scope : {
1049             helpText : '@',
1050             helpLink : '@'
1051         },
1052         templateUrl : './share/t_help_popover',
1053         controller : ['$scope','$sce', function($scope , $sce) {
1054             if ($scope.helpLink) {
1055                 $scope.helpHtml = $sce.trustAsHtml(
1056                     '<a target="_new" href="' + $scope.helpLink + '">' +
1057                     $scope.helpText + '</a>'
1058                 );
1059             }
1060         }]
1061     }
1062 })
1063
1064 .factory('egWorkLog', ['egCore', function(egCore) {
1065     var service = {};
1066
1067     service.retrieve_all = function() {
1068         var workLog = egCore.hatch.getLocalItem('eg.work_log') || [];
1069         var patronLog = egCore.hatch.getLocalItem('eg.patron_log') || [];
1070
1071         return { 'work_log' : workLog, 'patron_log' : patronLog };
1072     }
1073
1074     service.record = function(message,data) {
1075         var max_entries;
1076         var max_patrons;
1077         if (typeof egCore != 'undefined') {
1078             if (typeof egCore.env != 'undefined') {
1079                 if (typeof egCore.env.aous != 'undefined') {
1080                     max_entries = egCore.env.aous['ui.admin.work_log.max_entries'];
1081                     max_patrons = egCore.env.aous['ui.admin.patron_log.max_entries'];
1082                 } else {
1083                     console.log('worklog: missing egCore.env.aous');
1084                 }
1085             } else {
1086                 console.log('worklog: missing egCore.env');
1087             }
1088         } else {
1089             console.log('worklog: missing egCore');
1090         }
1091         if (!max_entries) {
1092             if (typeof egCore.org != 'undefined') {
1093                 if (typeof egCore.org.cachedSettings != 'undefined') {
1094                     max_entries = egCore.org.cachedSettings['ui.admin.work_log.max_entries'];
1095                 } else {
1096                     console.log('worklog: missing egCore.org.cachedSettings');
1097                 }
1098             } else {
1099                 console.log('worklog: missing egCore.org');
1100             }
1101         }
1102         if (!max_patrons) {
1103             if (typeof egCore.org != 'undefined') {
1104                 if (typeof egCore.org.cachedSettings != 'undefined') {
1105                     max_patrons = egCore.org.cachedSettings['ui.admin.patron_log.max_entries'];
1106                 } else {
1107                     console.log('worklog: missing egCore.org.cachedSettings');
1108                 }
1109             } else {
1110                 console.log('worklog: missing egCore.org');
1111             }
1112         }
1113         if (!max_entries) {
1114             max_entries = 20;
1115             console.log('worklog: defaulting to max_entries = ' + max_entries);
1116         }
1117         if (!max_patrons) {
1118             max_patrons = 10;
1119             console.log('worklog: defaulting to max_patrons = ' + max_patrons);
1120         }
1121
1122         var workLog = egCore.hatch.getLocalItem('eg.work_log') || [];
1123         var patronLog = egCore.hatch.getLocalItem('eg.patron_log') || [];
1124         var entry = {
1125             'when' : new Date(),
1126             'msg' : message,
1127             'action' : data.action,
1128             'actor' : egCore.auth.user().usrname()
1129         };
1130         if (data.action == 'checkin') {
1131             entry['item'] = data.response.params.copy_barcode;
1132             entry['item_id'] = data.response.data.acp.id();
1133             if (data.response.data.au) {
1134                 entry['user'] = data.response.data.au.family_name();
1135                 entry['patron_id'] = data.response.data.au.id();
1136             }
1137         }
1138         if (data.action == 'checkout') {
1139             entry['item'] = data.response.params.copy_barcode;
1140             entry['user'] = data.response.data.au.family_name();
1141             entry['item_id'] = data.response.data.acp.id();
1142             entry['patron_id'] = data.response.data.au.id();
1143         }
1144         if (data.action == 'noncat_checkout') {
1145             entry['user'] = data.response.data.au.family_name();
1146             entry['patron_id'] = data.response.data.au.id();
1147         }
1148         if (data.action == 'renew') {
1149             entry['item'] = data.response.params.copy_barcode;
1150             entry['user'] = data.response.data.au.family_name();
1151             entry['item_id'] = data.response.data.acp.id();
1152             entry['patron_id'] = data.response.data.au.id();
1153         }
1154         if (data.action == 'requested_hold'
1155             || data.action == 'edited_patron'
1156             || data.action == 'registered_patron'
1157             || data.action == 'paid_bill') {
1158             entry['patron_id'] = data.patron_id;
1159         }
1160         if (data.action == 'requested_hold') {
1161             entry['hold_id'] = data.hold_id;
1162         }
1163         if (data.action == 'paid_bill') {
1164             entry['amount'] = data.total_amount;
1165         }
1166
1167         workLog.push( entry );
1168         if (workLog.length > max_entries) workLog.shift();
1169         egCore.hatch.setLocalItem('eg.work_log',workLog); // hatch JSONifies the data, so should be okay re: memory leaks?
1170
1171         if (entry['patron_id']) {
1172             var temp = [];
1173             for (var i = 0; i < patronLog.length; i++) { // filter out any matching patron
1174                 if (patronLog[i]['patron_id'] != entry['patron_id']) temp.push(patronLog[i]);
1175             }
1176             temp.push( entry );
1177             if (temp.length > max_patrons) temp.shift();
1178             patronLog = temp;
1179             egCore.hatch.setLocalItem('eg.patron_log',patronLog);
1180         }
1181
1182         console.log('worklog',entry);
1183     }
1184
1185     return service;
1186 }]);