]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/services/ui.js
LP#1581126: webstaff: make egDateInput respect format.date OUS
[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 /**
83  * egAlertDialog.open({message : 'hello {{name}}'}).result.then(
84  *     function() { console.log('alert closed') });
85  */
86 .factory('egAlertDialog', 
87
88         ['$uibModal','$interpolate',
89 function($uibModal , $interpolate) {
90     var service = {};
91
92     service.open = function(message, msg_scope) {
93         return $uibModal.open({
94             templateUrl: './share/t_alert_dialog',
95             controller: ['$scope', '$uibModalInstance',
96                 function($scope, $uibModalInstance) {
97                     $scope.message = $interpolate(message)(msg_scope);
98                     $scope.ok = function() {
99                         if (msg_scope && msg_scope.ok) msg_scope.ok();
100                         $uibModalInstance.close()
101                     }
102                 }
103             ]
104         });
105     }
106
107     return service;
108 }])
109
110 /**
111  * egConfirmDialog.open("some message goes {{here}}", {
112  *  here : 'foo', ok : function() {}, cancel : function() {}},
113  *  'OK', 'Cancel');
114  */
115 .factory('egConfirmDialog', 
116     
117        ['$uibModal','$interpolate',
118 function($uibModal, $interpolate) {
119     var service = {};
120
121     service.open = function(title, message, msg_scope, ok_button_label, cancel_button_label) {
122         return $uibModal.open({
123             templateUrl: './share/t_confirm_dialog',
124             controller: ['$scope', '$uibModalInstance',
125                 function($scope, $uibModalInstance) {
126                     $scope.title = $interpolate(title)(msg_scope);
127                     $scope.message = $interpolate(message)(msg_scope);
128                     $scope.ok_button_label = $interpolate(ok_button_label || '')(msg_scope);
129                     $scope.cancel_button_label = $interpolate(cancel_button_label || '')(msg_scope);
130                     $scope.ok = function() {
131                         if (msg_scope.ok) msg_scope.ok();
132                         $uibModalInstance.close()
133                     }
134                     $scope.cancel = function() {
135                         if (msg_scope.cancel) msg_scope.cancel();
136                         $uibModalInstance.dismiss();
137                     }
138                 }
139             ]
140         })
141     }
142
143     return service;
144 }])
145
146 /**
147  * egPromptDialog.open(
148  *    "prompt message goes {{here}}", 
149  *    promptValue,  // optional
150  *    {
151  *      here : 'foo',  
152  *      ok : function(value) {console.log(value)}, 
153  *      cancel : function() {console.log('prompt denied')}
154  *    }
155  *  );
156  */
157 .factory('egPromptDialog', 
158     
159        ['$uibModal','$interpolate',
160 function($uibModal, $interpolate) {
161     var service = {};
162
163     service.open = function(message, promptValue, msg_scope) {
164         return $uibModal.open({
165             templateUrl: './share/t_prompt_dialog',
166             controller: ['$scope', '$uibModalInstance',
167                 function($scope, $uibModalInstance) {
168                     $scope.message = $interpolate(message)(msg_scope);
169                     $scope.args = {value : promptValue || ''};
170                     $scope.focus = true;
171                     $scope.ok = function() {
172                         if (msg_scope.ok) msg_scope.ok($scope.args.value);
173                         $uibModalInstance.close()
174                     }
175                     $scope.cancel = function() {
176                         if (msg_scope.cancel) msg_scope.cancel();
177                         $uibModalInstance.dismiss();
178                     }
179                 }
180             ]
181         })
182     }
183
184     return service;
185 }])
186
187 /**
188  * Warn on page unload and give the user a chance to avoid navigating
189  * away from the current page.  
190  * Only one handler is supported per page.
191  * NOTE: we can't use an egUnloadDialog as the dialog builder, because
192  * it renders asynchronously, which allows the page to redirect before
193  * the dialog appears.
194  */
195 .factory('egUnloadPrompt', [
196         '$window','egStrings', 
197 function($window , egStrings) {
198     var service = {attached : false};
199
200     // attach a page/scope unload prompt
201     service.attach = function($scope, msg) {
202         if (service.attached) return;
203         service.attached = true;
204
205         // handle page change
206         $($window).on('beforeunload', function() { 
207             service.clear();
208             return msg || egStrings.EG_UNLOAD_PAGE_PROMPT_MSG;
209         });
210
211         if (!$scope) return;
212
213         // If a scope was provided, attach a scope-change handler,
214         // similar to the page-page prompt.
215         service.locChangeCancel = 
216             $scope.$on('$locationChangeStart', function(evt, next, current) {
217             if (confirm(msg || egStrings.EG_UNLOAD_CTRL_PROMPT_MSG)) {
218                 // user allowed the page to change.  
219                 // Clear the unload handler.
220                 service.clear();
221             } else {
222                 evt.preventDefault();
223             }
224         });
225     };
226
227     // remove the page unload prompt
228     service.clear = function() {
229         $($window).off('beforeunload');
230         if (service.locChangeCancel)
231             service.locChangeCancel();
232         service.attached = false;
233     }
234
235     return service;
236 }])
237
238 .directive('aDisabled', function() {
239     return {
240         restrict : 'A',
241         compile: function(tElement, tAttrs, transclude) {
242             //Disable ngClick
243             tAttrs["ngClick"] = ("ng-click", "!("+tAttrs["aDisabled"]+") && ("+tAttrs["ngClick"]+")");
244
245             //Toggle "disabled" to class when aDisabled becomes true
246             return function (scope, iElement, iAttrs) {
247                 scope.$watch(iAttrs["aDisabled"], function(newValue) {
248                     if (newValue !== undefined) {
249                         iElement.toggleClass("disabled", newValue);
250                     }
251                 });
252
253                 //Disable href on click
254                 iElement.on("click", function(e) {
255                     if (scope.$eval(iAttrs["aDisabled"])) {
256                         e.preventDefault();
257                     }
258                 });
259             };
260         }
261     };
262 })
263
264 .directive('egBasicComboBox', function() {
265     return {
266         restrict: 'E',
267         replace: true,
268         scope: {
269             list: "=", // list of strings
270             selected: "=",
271             egDisabled: "="
272         },
273         template:
274             '<div class="input-group">'+
275                 '<input type="text" ng-disabled="egDisabled" class="form-control" ng-model="selected" ng-change="makeOpen()">'+
276                 '<div class="input-group-btn" dropdown ng-class="{open:isopen}">'+
277                     '<button type="button" ng-click="showAll()" class="btn btn-default dropdown-toggle"><span class="caret"></span></button>'+
278                     '<ul class="dropdown-menu dropdown-menu-right">'+
279                         '<li ng-repeat="item in list|filter:selected"><a href ng-click="changeValue(item)">{{item}}</a></li>'+
280                         '<li ng-if="all" class="divider"><span></span></li>'+
281                         '<li ng-if="all" ng-repeat="item in list"><a href ng-click="changeValue(item)">{{item}}</a></li>'+
282                     '</ul>'+
283                 '</div>'+
284             '</div>',
285         controller: ['$scope','$filter',
286             function( $scope , $filter) {
287
288                 $scope.all = false;
289                 $scope.isopen = false;
290
291                 $scope.showAll = function () {
292                     if ($scope.selected.length > 0)
293                         $scope.all = true;
294                 }
295
296                 $scope.makeOpen = function () {
297                     $scope.isopen = $filter('filter')(
298                         $scope.list,
299                         $scope.selected
300                     ).length > 0 && $scope.selected.length > 0;
301                     $scope.all = false;
302                 }
303
304                 $scope.changeValue = function (newVal) {
305                     $scope.selected = newVal;
306                     $scope.isopen = false;
307                 }
308
309             }
310         ]
311     };
312 })
313
314 /**
315  * Nested org unit selector modeled as a Bootstrap dropdown button.
316  */
317 .directive('egOrgSelector', function() {
318     return {
319         restrict : 'AE',
320         transclude : true,
321         replace : true, // makes styling easier
322         scope : {
323             selected : '=', // defaults to workstation or root org,
324                             // unless the nodefault attibute exists
325
326             // Each org unit is passed into this function and, for
327             // any org units where the response value is true, the
328             // org unit will not be added to the selector.
329             hiddenTest : '=',
330
331             // Each org unit is passed into this function and, for
332             // any org units where the response value is true, the
333             // org unit will not be available for selection.
334             disableTest : '=',
335
336             // if set to true, disable the UI element altogether
337             alldisabled : '@',
338
339             // Caller can either $watch(selected, ..) or register an
340             // onchange handler.
341             onchange : '=',
342
343             // optional primary drop-down button label
344             label : '@',
345
346             // optional name of settings key for persisting
347             // the last selected org unit
348             stickySetting : '@'
349         },
350
351         // any reason to move this into a TT2 template?
352         template : 
353             '<div class="btn-group eg-org-selector" uib-dropdown>'
354             + '<button type="button" class="btn btn-default" uib-dropdown-toggle ng-disabled="disable_button">'
355              + '<span style="padding-right: 5px;">{{getSelectedName()}}</span>'
356              + '<span class="caret"></span>'
357            + '</button>'
358            + '<ul uib-dropdown-menu class="scrollable-menu">'
359              + '<li ng-repeat="org in orgList" ng-hide="hiddenTest(org.id)">'
360                + '<a href ng-click="orgChanged(org)" a-disabled="disableTest(org.id)" '
361                  + 'style="padding-left: {{org.depth * 10 + 5}}px">'
362                  + '{{org.shortname}}'
363                + '</a>'
364              + '</li>'
365            + '</ul>'
366           + '</div>',
367
368         controller : ['$scope','$timeout','egOrg','egAuth','egCore','egStartup',
369               function($scope , $timeout , egOrg , egAuth , egCore , egStartup) {
370
371             if ($scope.alldisabled) {
372                 $scope.disable_button = $scope.alldisabled == 'true' ? true : false;
373             } else {
374                 $scope.disable_button = false;
375             }
376
377             $scope.egOrg = egOrg; // for use in the link function
378             $scope.egAuth = egAuth; // for use in the link function
379             $scope.hatch = egCore.hatch // for use in the link function
380
381             // avoid linking the full fleshed tree to the scope by 
382             // tossing in a flattened list.
383             // --
384             // Run-time code referencing post-start data should be run
385             // from within a startup block, otherwise accessing this
386             // module before startup completes will lead to failure.
387             egStartup.go().then(function() {
388
389                 $scope.orgList = egOrg.list().map(function(org) {
390                     return {
391                         id : org.id(),
392                         shortname : org.shortname(), 
393                         depth : org.ou_type().depth()
394                     }
395                 });
396
397                 if (!$scope.selected)
398                     $scope.selected = egOrg.get(egAuth.user().ws_ou());
399             });
400
401             $scope.getSelectedName = function() {
402                 if ($scope.selected && $scope.selected.shortname)
403                     return $scope.selected.shortname();
404                 return $scope.label;
405             }
406
407             $scope.orgChanged = function(org) {
408                 $scope.selected = egOrg.get(org.id);
409                 if ($scope.stickySetting) {
410                     egCore.hatch.setLocalItem($scope.stickySetting, org.id);
411                 }
412                 if ($scope.onchange) $scope.onchange($scope.selected);
413             }
414
415         }],
416         link : function(scope, element, attrs, egGridCtrl) {
417
418             // boolean fields are presented as value-less attributes
419             angular.forEach(
420                 ['nodefault'],
421                 function(field) {
422                     if (angular.isDefined(attrs[field]))
423                         scope[field] = true;
424                     else
425                         scope[field] = false;
426                 }
427             );
428
429             if (scope.stickySetting) {
430                 var orgId = scope.hatch.getLocalItem(scope.stickySetting);
431                 if (orgId) {
432                     scope.selected = scope.egOrg.get(orgId);
433                 }
434             }
435
436             if (!scope.selected && !scope.nodefault)
437                 scope.selected = scope.egOrg.get(scope.egAuth.user().ws_ou());
438         }
439
440     }
441 })
442
443 /* http://eric.sau.pe/angularjs-detect-enter-key-ngenter/ */
444 .directive('egEnter', function () {
445     return function (scope, element, attrs) {
446         element.bind("keydown keypress", function (event) {
447             if(event.which === 13) {
448                 scope.$apply(function (){
449                     scope.$eval(attrs.egEnter);
450                 });
451  
452                 event.preventDefault();
453             }
454         });
455     };
456 })
457
458 /*
459 * Handy wrapper directive for uib-datapicker-popup
460 */
461 .directive(
462     'egDateInput', ['egStrings', 'egCore',
463     function(egStrings, egCore) {
464         return {
465             scope : {
466                 closeText : '@',
467                 ngModel : '=',
468                 ngChange : '=',
469                 ngBlur : '=',
470                 ngDisabled : '=',
471                 ngRequired : '=',
472                 hideDatePicker : '=',
473                 dateFormat : '=?'
474             },
475             require: 'ngModel',
476             templateUrl: './share/t_datetime',
477             replace: true,
478             link : function(scope, elm, attrs) {
479                 if (!scope.closeText)
480                     scope.closeText = egStrings.EG_DATE_INPUT_CLOSE_TEXT;
481
482                 if ('showTimePicker' in attrs)
483                     scope.showTimePicker = true;
484
485                 var default_format = 'mediumDate';
486                 egCore.org.settings(['format.date']).then(function(set) {
487                     default_format = set['format.date'];
488                     scope.date_format = (scope.dateFormat) ?
489                         scope.dateFormat :
490                         default_format;
491                 });
492             }
493         };
494     }
495 ])
496
497 .factory('egWorkLog', ['egCore', function(egCore) {
498     var service = {};
499
500     service.retrieve_all = function() {
501         var workLog = egCore.hatch.getLocalItem('eg.work_log') || [];
502         var patronLog = egCore.hatch.getLocalItem('eg.patron_log') || [];
503
504         return { 'work_log' : workLog, 'patron_log' : patronLog };
505     }
506
507     service.record = function(message,data) {
508         var max_entries;
509         var max_patrons;
510         if (typeof egCore != 'undefined') {
511             if (typeof egCore.env != 'undefined') {
512                 if (typeof egCore.env.aous != 'undefined') {
513                     max_entries = egCore.env.aous['ui.admin.work_log.max_entries'];
514                     max_patrons = egCore.env.aous['ui.admin.patron_log.max_entries'];
515                 } else {
516                     console.log('worklog: missing egCore.env.aous');
517                 }
518             } else {
519                 console.log('worklog: missing egCore.env');
520             }
521         } else {
522             console.log('worklog: missing egCore');
523         }
524         if (!max_entries) {
525             if (typeof egCore.org != 'undefined') {
526                 if (typeof egCore.org.cachedSettings != 'undefined') {
527                     max_entries = egCore.org.cachedSettings['ui.admin.work_log.max_entries'];
528                 } else {
529                     console.log('worklog: missing egCore.org.cachedSettings');
530                 }
531             } else {
532                 console.log('worklog: missing egCore.org');
533             }
534         }
535         if (!max_patrons) {
536             if (typeof egCore.org != 'undefined') {
537                 if (typeof egCore.org.cachedSettings != 'undefined') {
538                     max_patrons = egCore.org.cachedSettings['ui.admin.patron_log.max_entries'];
539                 } else {
540                     console.log('worklog: missing egCore.org.cachedSettings');
541                 }
542             } else {
543                 console.log('worklog: missing egCore.org');
544             }
545         }
546         if (!max_entries) {
547             max_entries = 20;
548             console.log('worklog: defaulting to max_entries = ' + max_entries);
549         }
550         if (!max_patrons) {
551             max_patrons = 10;
552             console.log('worklog: defaulting to max_patrons = ' + max_patrons);
553         }
554
555         var workLog = egCore.hatch.getLocalItem('eg.work_log') || [];
556         var patronLog = egCore.hatch.getLocalItem('eg.patron_log') || [];
557         var entry = {
558             'when' : new Date(),
559             'msg' : message,
560             'data' : data,
561             'action' : data.action,
562             'actor' : egCore.auth.user().usrname()
563         };
564         if (data.action == 'checkin') {
565             entry['item'] = data.response.params.copy_barcode;
566             entry['user'] = data.response.data.au.family_name();
567             entry['item_id'] = data.response.data.acp.id();
568             entry['patron_id'] = data.response.data.au.id();
569         }
570         if (data.action == 'checkout') {
571             entry['item'] = data.response.params.copy_barcode;
572             entry['user'] = data.response.data.au.family_name();
573             entry['item_id'] = data.response.data.acp.id();
574             entry['patron_id'] = data.response.data.au.id();
575         }
576         if (data.action == 'renew') {
577             entry['item'] = data.response.params.copy_barcode;
578             entry['user'] = data.response.data.au.family_name();
579             entry['item_id'] = data.response.data.acp.id();
580             entry['patron_id'] = data.response.data.au.id();
581         }
582         if (data.action == 'requested_hold'
583             || data.action == 'edited_patron'
584             || data.action == 'registered_patron'
585             || data.action == 'paid_bill') {
586             entry['patron_id'] = data.patron_id;
587         }
588         if (data.action == 'paid_bill') {
589             entry['amount'] = data.total_amount;
590         }
591
592         workLog.push( entry );
593         if (workLog.length > max_entries) workLog.shift();
594         egCore.hatch.setLocalItem('eg.work_log',workLog); // hatch JSONifies the data, so should be okay re: memory leaks?
595
596         if (entry['patron_id']) {
597             var temp = [];
598             for (var i = 0; i < patronLog.length; i++) { // filter out any matching patron
599                 if (patronLog[i]['patron_id'] != entry['patron_id']) temp.push(patronLog[i]);
600             }
601             temp.push( entry );
602             if (temp.length > max_patrons) temp.shift();
603             patronLog = temp;
604             egCore.hatch.setLocalItem('eg.patron_log',patronLog);
605         }
606
607         console.log('worklog',entry);
608     }
609
610     return service;
611 }]);