]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/services/ui.js
LP#1522638 egProgressDialog features and docs
[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                 scope.$apply(model.assign(scope, false));
23             })
24         }
25     };
26 }])
27
28 /**
29  * <input blur-me="pleaseBlurMe"/>
30  * $scope.pleaseBlurMe = true
31  * Useful for de-focusing when no other obvious focus target exists
32  */
33 .directive('blurMe', 
34        ['$timeout','$parse', 
35 function($timeout , $parse) {
36     return {
37         link: function(scope, element, attrs) {
38             var model = $parse(attrs.blurMe);
39             scope.$watch(model, function(value) {
40                 if(value === true) 
41                     $timeout(function() {element[0].blur()});
42             });
43             element.bind('focus', function() {
44                 scope.$apply(model.assign(scope, false));
45             })
46         }
47     };
48 }])
49
50
51 // <input select-me="iWantToBeSelected"/>
52 // $scope.iWantToBeSelected = true;
53 .directive('selectMe', 
54        ['$timeout','$parse', 
55 function($timeout , $parse) {
56     return {
57         link: function(scope, element, attrs) {
58             var model = $parse(attrs.selectMe);
59             scope.$watch(model, function(value) {
60                 if(value === true) 
61                     $timeout(function() {element[0].select()});
62             });
63             element.bind('blur', function() {
64                 scope.$apply(model.assign(scope, false));
65             })
66         }
67     };
68 }])
69
70
71 // 'reverse' filter 
72 // <div ng-repeat="item in items | reverse">{{item.name}}</div>
73 // http://stackoverflow.com/questions/15266671/angular-ng-repeat-in-reverse
74 // TODO: perhaps this should live elsewhere
75 .filter('reverse', function() {
76     return function(items) {
77         return items.slice().reverse();
78     };
79 })
80
81 /**
82  * Progress Dialog. 
83  *
84  * egProgressDialog.open();
85  * egProgressDialog.open({value : 0});
86  * egProgressDialog.open({value : 0, max : 123});
87  * egProgressDialog.increment();
88  * egProgressDialog.increment();
89  * egProgressDialog.close();
90  *
91  * Each dialog has 2 numbers, 'max' and 'value'.
92  * The content of these values determines how the dialog displays.  
93  *
94  * There are 3 flavors:
95  *
96  * -- value is set, max is set
97  * determinate: shows a progression with a percent complete.
98  *
99  * -- value is set, max is unset
100  * semi-determinate, with a value report.  Shows a value-less
101  * <progress/>, but shows the value as a number in the dialog.
102  *
103  * This is useful in cases where the total number of items to retrieve
104  * from the server is unknown, but we know how many items we've
105  * retrieved thus far.  It helps to reinforce that something specific
106  * is happening, but we don't know when it will end.
107  *
108  * -- value is unset
109  * indeterminate: shows a generic value-less <progress/> with no 
110  * clear indication of progress.
111  *
112  * Only 1 egProgressDialog instance will be activate at a time.
113  * Each invocation of .open() destroys any existing instance.
114  */
115
116 /* Simple storage class for egProgressDialog data maintenance.
117  * This data lives outside of egProgressDialog so it can be 
118  * directly imported into egProgressDialog's $uibModalInstance.
119  */
120 .factory('egProgressData', [
121     function() {
122         var service = {}; // max/value initially unset
123
124         service.reset = function() {
125             delete service.max;
126             delete service.value;
127         }
128
129         service.hasvalue = function() {
130             return Number.isInteger(service.value);
131         }
132
133         service.hasmax = function() {
134             return Number.isInteger(service.max);
135         }
136
137         service.percent = function() {
138             if (service.hasvalue()  && 
139                 service.hasmax()    && 
140                 service.max > 0     &&
141                 service.value <= service.max)
142                 return Math.floor((service.value / service.max) * 100);
143             return 100;
144         }
145
146         return service;
147     }
148 ])
149
150 .factory('egProgressDialog', [
151             'egProgressData','$uibModal', 
152     function(egProgressData , $uibModal) {
153     var service = {};
154
155     service.open = function(args) {
156         service.close(); // force-kill existing instances.
157
158         // Reset to an indeterminate progress bar, 
159         // overlay with caller values.
160         egProgressData.reset();
161         service.update(angular.extend({}, args));
162
163         return $uibModal.open({
164             templateUrl: './share/t_progress_dialog',
165             controller: ['$scope','$uibModalInstance','egProgressData',
166                 function( $scope , $uibModalInstance , egProgressData) {
167                   service.currentInstance = $uibModalInstance;
168                   $scope.data = egProgressData; // tiny service
169                 }
170             ]
171         });
172     };
173
174     service.close = function() {
175         if (service.currentInstance) {
176             service.currentInstance.close();
177             delete service.currentInstance;
178         }
179     }
180
181     // Set the current state of the progress bar.
182     service.update = function(args) {
183         if (args.max != undefined) 
184             egProgressData.max = args.max;
185         if (args.value != undefined) 
186             egProgressData.value = args.value;
187     }
188
189     // Increment the current value.  If no amount is specified,
190     // it increments by 1.  Calling increment() on an indetermite
191     // progress bar will force it to be a (semi-)determinate bar.
192     service.increment = function(amt) {
193         if (!Number.isInteger(amt)) amt = 1;
194
195         if (!egProgressData.hasvalue())
196             egProgressData.value = 0;
197
198         egProgressData.value += amt;
199     }
200
201     return service;
202 }])
203
204 /**
205  * egAlertDialog.open({message : 'hello {{name}}'}).result.then(
206  *     function() { console.log('alert closed') });
207  */
208 .factory('egAlertDialog', 
209
210         ['$uibModal','$interpolate',
211 function($uibModal , $interpolate) {
212     var service = {};
213
214     service.open = function(message, msg_scope) {
215         return $uibModal.open({
216             templateUrl: './share/t_alert_dialog',
217             controller: ['$scope', '$uibModalInstance',
218                 function($scope, $uibModalInstance) {
219                     $scope.message = $interpolate(message)(msg_scope);
220                     $scope.ok = function() {
221                         if (msg_scope && msg_scope.ok) msg_scope.ok();
222                         $uibModalInstance.close()
223                     }
224                 }
225             ]
226         });
227     }
228
229     return service;
230 }])
231
232 /**
233  * egConfirmDialog.open("some message goes {{here}}", {
234  *  here : 'foo', ok : function() {}, cancel : function() {}},
235  *  'OK', 'Cancel');
236  */
237 .factory('egConfirmDialog', 
238     
239        ['$uibModal','$interpolate',
240 function($uibModal, $interpolate) {
241     var service = {};
242
243     service.open = function(title, message, msg_scope, ok_button_label, cancel_button_label) {
244         return $uibModal.open({
245             templateUrl: './share/t_confirm_dialog',
246             controller: ['$scope', '$uibModalInstance',
247                 function($scope, $uibModalInstance) {
248                     $scope.title = $interpolate(title)(msg_scope);
249                     $scope.message = $interpolate(message)(msg_scope);
250                     $scope.ok_button_label = $interpolate(ok_button_label || '')(msg_scope);
251                     $scope.cancel_button_label = $interpolate(cancel_button_label || '')(msg_scope);
252                     $scope.ok = function() {
253                         if (msg_scope.ok) msg_scope.ok();
254                         $uibModalInstance.close()
255                     }
256                     $scope.cancel = function() {
257                         if (msg_scope.cancel) msg_scope.cancel();
258                         $uibModalInstance.dismiss();
259                     }
260                 }
261             ]
262         })
263     }
264
265     return service;
266 }])
267
268 /**
269  * egPromptDialog.open(
270  *    "prompt message goes {{here}}", 
271  *    promptValue,  // optional
272  *    {
273  *      here : 'foo',  
274  *      ok : function(value) {console.log(value)}, 
275  *      cancel : function() {console.log('prompt denied')}
276  *    }
277  *  );
278  */
279 .factory('egPromptDialog', 
280     
281        ['$uibModal','$interpolate',
282 function($uibModal, $interpolate) {
283     var service = {};
284
285     service.open = function(message, promptValue, msg_scope) {
286         return $uibModal.open({
287             templateUrl: './share/t_prompt_dialog',
288             controller: ['$scope', '$uibModalInstance',
289                 function($scope, $uibModalInstance) {
290                     $scope.message = $interpolate(message)(msg_scope);
291                     $scope.args = {value : promptValue || ''};
292                     $scope.focus = true;
293                     $scope.ok = function() {
294                         if (msg_scope.ok) msg_scope.ok($scope.args.value);
295                         $uibModalInstance.close()
296                     }
297                     $scope.cancel = function() {
298                         if (msg_scope.cancel) msg_scope.cancel();
299                         $uibModalInstance.dismiss();
300                     }
301                 }
302             ]
303         })
304     }
305
306     return service;
307 }])
308
309 /**
310  * egSelectDialog.open(
311  *    "message goes {{here}}", 
312  *    list,           // ['values','for','dropdown'],
313  *    selectedValue,  // optional
314  *    {
315  *      here : 'foo',
316  *      ok : function(value) {console.log(value)}, 
317  *      cancel : function() {console.log('prompt denied')}
318  *    }
319  *  );
320  */
321 .factory('egSelectDialog', 
322     
323        ['$uibModal','$interpolate',
324 function($uibModal, $interpolate) {
325     var service = {};
326
327     service.open = function(message, inputList, selectedValue, msg_scope) {
328         return $uibModal.open({
329             templateUrl: './share/t_select_dialog',
330             controller: ['$scope', '$uibModalInstance',
331                 function($scope, $uibModalInstance) {
332                     $scope.message = $interpolate(message)(msg_scope);
333                     $scope.args = {
334                         list  : inputList,
335                         value : selectedValue
336                     };
337                     $scope.focus = true;
338                     $scope.ok = function() {
339                         if (msg_scope.ok) msg_scope.ok($scope.args.value);
340                         $uibModalInstance.close()
341                     }
342                     $scope.cancel = function() {
343                         if (msg_scope.cancel) msg_scope.cancel();
344                         $uibModalInstance.dismiss();
345                     }
346                 }
347             ]
348         })
349     }
350
351     return service;
352 }])
353
354 /**
355  * Warn on page unload and give the user a chance to avoid navigating
356  * away from the current page.  
357  * Only one handler is supported per page.
358  * NOTE: we can't use an egUnloadDialog as the dialog builder, because
359  * it renders asynchronously, which allows the page to redirect before
360  * the dialog appears.
361  */
362 .factory('egUnloadPrompt', [
363         '$window','egStrings', 
364 function($window , egStrings) {
365     var service = {attached : false};
366
367     // attach a page/scope unload prompt
368     service.attach = function($scope, msg) {
369         if (service.attached) return;
370         service.attached = true;
371
372         // handle page change
373         $($window).on('beforeunload', function() { 
374             service.clear();
375             return msg || egStrings.EG_UNLOAD_PAGE_PROMPT_MSG;
376         });
377
378         if (!$scope) return;
379
380         // If a scope was provided, attach a scope-change handler,
381         // similar to the page-page prompt.
382         service.locChangeCancel = 
383             $scope.$on('$locationChangeStart', function(evt, next, current) {
384             if (confirm(msg || egStrings.EG_UNLOAD_CTRL_PROMPT_MSG)) {
385                 // user allowed the page to change.  
386                 // Clear the unload handler.
387                 service.clear();
388             } else {
389                 evt.preventDefault();
390             }
391         });
392     };
393
394     // remove the page unload prompt
395     service.clear = function() {
396         $($window).off('beforeunload');
397         if (service.locChangeCancel)
398             service.locChangeCancel();
399         service.attached = false;
400     }
401
402     return service;
403 }])
404
405 .directive('aDisabled', function() {
406     return {
407         restrict : 'A',
408         compile: function(tElement, tAttrs, transclude) {
409             //Disable ngClick
410             tAttrs["ngClick"] = ("ng-click", "!("+tAttrs["aDisabled"]+") && ("+tAttrs["ngClick"]+")");
411
412             //Toggle "disabled" to class when aDisabled becomes true
413             return function (scope, iElement, iAttrs) {
414                 scope.$watch(iAttrs["aDisabled"], function(newValue) {
415                     if (newValue !== undefined) {
416                         iElement.toggleClass("disabled", newValue);
417                     }
418                 });
419
420                 //Disable href on click
421                 iElement.on("click", function(e) {
422                     if (scope.$eval(iAttrs["aDisabled"])) {
423                         e.preventDefault();
424                     }
425                 });
426             };
427         }
428     };
429 })
430
431 .directive('egBasicComboBox', function() {
432     return {
433         restrict: 'E',
434         replace: true,
435         scope: {
436             list: "=", // list of strings
437             selected: "=",
438             egDisabled: "=",
439             allowAll: "@",
440         },
441         template:
442             '<div class="input-group">'+
443                 '<input type="text" ng-disabled="egDisabled" class="form-control" ng-model="selected" ng-change="makeOpen()">'+
444                 '<div class="input-group-btn" dropdown ng-class="{open:isopen}">'+
445                     '<button type="button" ng-click="showAll()" class="btn btn-default dropdown-toggle"><span class="caret"></span></button>'+
446                     '<ul class="dropdown-menu dropdown-menu-right">'+
447                         '<li ng-repeat="item in list|filter:selected"><a href ng-click="changeValue(item)">{{item}}</a></li>'+
448                         '<li ng-if="complete_list" class="divider"><span></span></li>'+
449                         '<li ng-if="complete_list" ng-repeat="item in list"><a href ng-click="changeValue(item)">{{item}}</a></li>'+
450                     '</ul>'+
451                 '</div>'+
452             '</div>',
453         controller: ['$scope','$filter',
454             function( $scope , $filter) {
455
456                 $scope.complete_list = false;
457                 $scope.isopen = false;
458                 $scope.clickedopen = false;
459                 $scope.clickedclosed = null;
460
461                 $scope.showAll = function () {
462
463                     $scope.clickedopen = !$scope.clickedopen;
464
465                     if ($scope.clickedclosed === null) {
466                         if (!$scope.clickedopen) {
467                             $scope.clickedclosed = true;
468                         }
469                     } else {
470                         $scope.clickedclosed = !$scope.clickedopen;
471                     }
472
473                     if ($scope.selected.length > 0) $scope.complete_list = true;
474                     if ($scope.selected.length == 0) $scope.complete_list = false;
475                     $scope.makeOpen();
476                 }
477
478                 $scope.makeOpen = function () {
479                     $scope.isopen = $scope.clickedopen || ($filter('filter')(
480                         $scope.list,
481                         $scope.selected
482                     ).length > 0 && $scope.selected.length > 0);
483                     if ($scope.clickedclosed) $scope.isopen = false;
484                 }
485
486                 $scope.changeValue = function (newVal) {
487                     $scope.selected = newVal;
488                     $scope.isopen = false;
489                     $scope.clickedclosed = null;
490                     $scope.clickedopen = false;
491                     if ($scope.selected.length == 0) $scope.complete_list = false;
492                 }
493
494             }
495         ]
496     };
497 })
498
499 /**
500  * Nested org unit selector modeled as a Bootstrap dropdown button.
501  */
502 .directive('egOrgSelector', function() {
503     return {
504         restrict : 'AE',
505         transclude : true,
506         replace : true, // makes styling easier
507         scope : {
508             selected : '=', // defaults to workstation or root org,
509                             // unless the nodefault attibute exists
510
511             // Each org unit is passed into this function and, for
512             // any org units where the response value is true, the
513             // org unit will not be added to the selector.
514             hiddenTest : '=',
515
516             // Each org unit is passed into this function and, for
517             // any org units where the response value is true, the
518             // org unit will not be available for selection.
519             disableTest : '=',
520
521             // if set to true, disable the UI element altogether
522             alldisabled : '@',
523
524             // Caller can either $watch(selected, ..) or register an
525             // onchange handler.
526             onchange : '=',
527
528             // optional primary drop-down button label
529             label : '@',
530
531             // optional name of settings key for persisting
532             // the last selected org unit
533             stickySetting : '@'
534         },
535
536         // any reason to move this into a TT2 template?
537         template : 
538             '<div class="btn-group eg-org-selector" uib-dropdown>'
539             + '<button type="button" class="btn btn-default" uib-dropdown-toggle ng-disabled="disable_button">'
540              + '<span style="padding-right: 5px;">{{getSelectedName()}}</span>'
541              + '<span class="caret"></span>'
542            + '</button>'
543            + '<ul uib-dropdown-menu class="scrollable-menu">'
544              + '<li ng-repeat="org in orgList" ng-hide="hiddenTest(org.id)">'
545                + '<a href ng-click="orgChanged(org)" a-disabled="disableTest(org.id)" '
546                  + 'style="padding-left: {{org.depth * 10 + 5}}px">'
547                  + '{{org.shortname}}'
548                + '</a>'
549              + '</li>'
550            + '</ul>'
551           + '</div>',
552
553         controller : ['$scope','$timeout','egOrg','egAuth','egCore','egStartup',
554               function($scope , $timeout , egOrg , egAuth , egCore , egStartup) {
555
556             if ($scope.alldisabled) {
557                 $scope.disable_button = $scope.alldisabled == 'true' ? true : false;
558             } else {
559                 $scope.disable_button = false;
560             }
561
562             $scope.egOrg = egOrg; // for use in the link function
563             $scope.egAuth = egAuth; // for use in the link function
564             $scope.hatch = egCore.hatch // for use in the link function
565
566             // avoid linking the full fleshed tree to the scope by 
567             // tossing in a flattened list.
568             // --
569             // Run-time code referencing post-start data should be run
570             // from within a startup block, otherwise accessing this
571             // module before startup completes will lead to failure.
572             egStartup.go().then(function() {
573
574                 $scope.orgList = egOrg.list().map(function(org) {
575                     return {
576                         id : org.id(),
577                         shortname : org.shortname(), 
578                         depth : org.ou_type().depth()
579                     }
580                 });
581
582                 if (!$scope.selected && !$scope.nodefault)
583                     $scope.selected = egOrg.get(egAuth.user().ws_ou());
584             });
585
586             $scope.getSelectedName = function() {
587                 if ($scope.selected && $scope.selected.shortname)
588                     return $scope.selected.shortname();
589                 return $scope.label;
590             }
591
592             $scope.orgChanged = function(org) {
593                 $scope.selected = egOrg.get(org.id);
594                 if ($scope.stickySetting) {
595                     egCore.hatch.setLocalItem($scope.stickySetting, org.id);
596                 }
597                 if ($scope.onchange) $scope.onchange($scope.selected);
598             }
599
600         }],
601         link : function(scope, element, attrs, egGridCtrl) {
602
603             // boolean fields are presented as value-less attributes
604             angular.forEach(
605                 ['nodefault'],
606                 function(field) {
607                     if (angular.isDefined(attrs[field]))
608                         scope[field] = true;
609                     else
610                         scope[field] = false;
611                 }
612             );
613
614             if (scope.stickySetting) {
615                 var orgId = scope.hatch.getLocalItem(scope.stickySetting);
616                 if (orgId) {
617                     scope.selected = scope.egOrg.get(orgId);
618                     if (scope.onchange)
619                         scope.onchange(scope.selected);
620                 }
621             }
622
623             if (!scope.selected && !scope.nodefault)
624                 scope.selected = scope.egOrg.get(scope.egAuth.user().ws_ou());
625         }
626
627     }
628 })
629
630 /* http://eric.sau.pe/angularjs-detect-enter-key-ngenter/ */
631 .directive('egEnter', function () {
632     return function (scope, element, attrs) {
633         element.bind("keydown keypress", function (event) {
634             if(event.which === 13) {
635                 scope.$apply(function (){
636                     scope.$eval(attrs.egEnter);
637                 });
638  
639                 event.preventDefault();
640             }
641         });
642     };
643 })
644
645 /*
646 * Handy wrapper directive for uib-datapicker-popup
647 */
648 .directive(
649     'egDateInput', ['egStrings', 'egCore',
650     function(egStrings, egCore) {
651         return {
652             scope : {
653                 closeText : '@',
654                 ngModel : '=',
655                 ngChange : '=',
656                 ngBlur : '=',
657                 ngDisabled : '=',
658                 ngRequired : '=',
659                 hideDatePicker : '=',
660                 dateFormat : '=?'
661             },
662             require: 'ngModel',
663             templateUrl: './share/t_datetime',
664             replace: true,
665             link : function(scope, elm, attrs) {
666                 if (!scope.closeText)
667                     scope.closeText = egStrings.EG_DATE_INPUT_CLOSE_TEXT;
668
669                 if ('showTimePicker' in attrs)
670                     scope.showTimePicker = true;
671
672                 var default_format = 'mediumDate';
673                 egCore.org.settings(['format.date']).then(function(set) {
674                     default_format = set['format.date'];
675                     scope.date_format = (scope.dateFormat) ?
676                         scope.dateFormat :
677                         default_format;
678                 });
679             }
680         };
681     }
682 ])
683
684 /*
685  *  egFmValueSelector - widget for selecting a value from list specified
686  *                      by IDL class
687  */
688 .directive('egFmValueSelector', function() {
689     return {
690         restrict : 'E',
691         transclude : true,
692         scope : {
693             idlClass : '@',
694             ngModel : '=',
695
696             // optional filter for refining the set of rows that
697             // get returned. Example:
698             //
699             // filter="{'column':{'=':null}}"
700             filter : '=',
701
702             // optional name of settings key for persisting
703             // the last selected value
704             stickySetting : '@',
705
706             // optional OU setting for fetching default value;
707             // used only if sticky setting not set
708             ouSetting : '@'
709         },
710         require: 'ngModel',
711         templateUrl : './share/t_fm_value_selector',
712         controller : ['$scope','egCore', function($scope , egCore) {
713
714             $scope.org = egCore.org; // for use in the link function
715             $scope.auth = egCore.auth; // for use in the link function
716             $scope.hatch = egCore.hatch // for use in the link function
717
718             function flatten_linked_values(cls, list) {
719                 var results = [];
720                 var fields = egCore.idl.classes[cls].fields;
721                 var id_field;
722                 var selector;
723                 angular.forEach(fields, function(fld) {
724                     if (fld.datatype == 'id') {
725                         id_field = fld.name;
726                         selector = fld.selector ? fld.selector : id_field;
727                         return;
728                     }
729                 });
730                 angular.forEach(list, function(item) {
731                     var rec = egCore.idl.toHash(item);
732                     results.push({
733                         id : rec[id_field],
734                         name : rec[selector]
735                     });
736                 });
737                 return results;
738             }
739
740             var search = {};
741             search[egCore.idl.classes[$scope.idlClass].pkey] = {'!=' : null};
742             if ($scope.filter) {
743                 angular.extend(search, $scope.filter);
744             }
745             egCore.pcrud.search(
746                 $scope.idlClass, search, {}, {atomic : true}
747             ).then(function(list) {
748                 $scope.linked_values = flatten_linked_values($scope.idlClass, list);
749             });
750
751             $scope.handleChange = function(value) {
752                 if ($scope.stickySetting) {
753                     egCore.hatch.setLocalItem($scope.stickySetting, value);
754                 }
755             }
756
757         }],
758         link : function(scope, element, attrs) {
759             if (scope.stickySetting && (angular.isUndefined(scope.ngModel) || (scope.ngModel === null))) {
760                 var value = scope.hatch.getLocalItem(scope.stickySetting);
761                 scope.ngModel = value;
762             }
763             if (scope.ouSetting && (angular.isUndefined(scope.ngModel) || (scope.ngModel === null))) {
764                 scope.org.settings([scope.ouSetting], scope.auth.user().ws_ou())
765                 .then(function(set) {
766                     var value = parseInt(set[scope.ouSetting]);
767                     if (!isNaN(value))
768                         scope.ngModel = value;
769                 });
770             }
771         }
772     }
773 })
774
775 .factory('egWorkLog', ['egCore', function(egCore) {
776     var service = {};
777
778     service.retrieve_all = function() {
779         var workLog = egCore.hatch.getLocalItem('eg.work_log') || [];
780         var patronLog = egCore.hatch.getLocalItem('eg.patron_log') || [];
781
782         return { 'work_log' : workLog, 'patron_log' : patronLog };
783     }
784
785     service.record = function(message,data) {
786         var max_entries;
787         var max_patrons;
788         if (typeof egCore != 'undefined') {
789             if (typeof egCore.env != 'undefined') {
790                 if (typeof egCore.env.aous != 'undefined') {
791                     max_entries = egCore.env.aous['ui.admin.work_log.max_entries'];
792                     max_patrons = egCore.env.aous['ui.admin.patron_log.max_entries'];
793                 } else {
794                     console.log('worklog: missing egCore.env.aous');
795                 }
796             } else {
797                 console.log('worklog: missing egCore.env');
798             }
799         } else {
800             console.log('worklog: missing egCore');
801         }
802         if (!max_entries) {
803             if (typeof egCore.org != 'undefined') {
804                 if (typeof egCore.org.cachedSettings != 'undefined') {
805                     max_entries = egCore.org.cachedSettings['ui.admin.work_log.max_entries'];
806                 } else {
807                     console.log('worklog: missing egCore.org.cachedSettings');
808                 }
809             } else {
810                 console.log('worklog: missing egCore.org');
811             }
812         }
813         if (!max_patrons) {
814             if (typeof egCore.org != 'undefined') {
815                 if (typeof egCore.org.cachedSettings != 'undefined') {
816                     max_patrons = egCore.org.cachedSettings['ui.admin.patron_log.max_entries'];
817                 } else {
818                     console.log('worklog: missing egCore.org.cachedSettings');
819                 }
820             } else {
821                 console.log('worklog: missing egCore.org');
822             }
823         }
824         if (!max_entries) {
825             max_entries = 20;
826             console.log('worklog: defaulting to max_entries = ' + max_entries);
827         }
828         if (!max_patrons) {
829             max_patrons = 10;
830             console.log('worklog: defaulting to max_patrons = ' + max_patrons);
831         }
832
833         var workLog = egCore.hatch.getLocalItem('eg.work_log') || [];
834         var patronLog = egCore.hatch.getLocalItem('eg.patron_log') || [];
835         var entry = {
836             'when' : new Date(),
837             'msg' : message,
838             'data' : data,
839             'action' : data.action,
840             'actor' : egCore.auth.user().usrname()
841         };
842         if (data.action == 'checkin') {
843             entry['item'] = data.response.params.copy_barcode;
844             entry['item_id'] = data.response.data.acp.id();
845             if (data.response.data.au) {
846                 entry['user'] = data.response.data.au.family_name();
847                 entry['patron_id'] = data.response.data.au.id();
848             }
849         }
850         if (data.action == 'checkout') {
851             entry['item'] = data.response.params.copy_barcode;
852             entry['user'] = data.response.data.au.family_name();
853             entry['item_id'] = data.response.data.acp.id();
854             entry['patron_id'] = data.response.data.au.id();
855         }
856         if (data.action == 'renew') {
857             entry['item'] = data.response.params.copy_barcode;
858             entry['user'] = data.response.data.au.family_name();
859             entry['item_id'] = data.response.data.acp.id();
860             entry['patron_id'] = data.response.data.au.id();
861         }
862         if (data.action == 'requested_hold'
863             || data.action == 'edited_patron'
864             || data.action == 'registered_patron'
865             || data.action == 'paid_bill') {
866             entry['patron_id'] = data.patron_id;
867         }
868         if (data.action == 'paid_bill') {
869             entry['amount'] = data.total_amount;
870         }
871
872         workLog.push( entry );
873         if (workLog.length > max_entries) workLog.shift();
874         egCore.hatch.setLocalItem('eg.work_log',workLog); // hatch JSONifies the data, so should be okay re: memory leaks?
875
876         if (entry['patron_id']) {
877             var temp = [];
878             for (var i = 0; i < patronLog.length; i++) { // filter out any matching patron
879                 if (patronLog[i]['patron_id'] != entry['patron_id']) temp.push(patronLog[i]);
880             }
881             temp.push( entry );
882             if (temp.length > max_patrons) temp.shift();
883             patronLog = temp;
884             egCore.hatch.setLocalItem('eg.patron_log',patronLog);
885         }
886
887         console.log('worklog',entry);
888     }
889
890     return service;
891 }]);