]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/services/grid.js
lp1635386 Items Column & Styles for Bill Item Status
[working/Evergreen.git] / Open-ILS / web / js / ui / default / staff / services / grid.js
1 angular.module('egGridMod', 
2     ['egCoreMod', 'egUiMod', 'ui.bootstrap'])
3
4 .directive('egGrid', function() {
5     return {
6         restrict : 'AE',
7         transclude : true,
8         scope : {
9
10             // IDL class hint (e.g. "aou")
11             idlClass : '@',
12
13             // default page size
14             pageSize : '@',
15
16             // if true, grid columns are derived from all non-virtual
17             // fields on the base idlClass
18             autoFields : '@',
19
20             // grid preferences will be stored / retrieved with this key
21             persistKey : '@',
22
23             // field whose value is unique and may be used for item
24             // reference / lookup.  This will usually be someting like
25             // "id".  This is not needed when using autoFields, since we
26             // can determine the primary key directly from the IDL.
27             idField : '@',
28
29             // Reference to externally provided egGridDataProvider
30             itemsProvider : '=',
31
32             // Reference to externally provided item-selection handler
33             onSelect : '=',
34
35             // Reference to externally provided after-item-selection handler
36             afterSelect : '=',
37
38             // comma-separated list of supported or disabled grid features
39             // supported features:
40             //  startSelected : init the grid with all rows selected by default
41             //  allowAll : add an "All" option to row count (really 10000)
42             //  -menu : don't show any menu buttons (or use space for them)
43             //  -picker : don't show the column picker
44             //  -pagination : don't show any pagination elements, and set
45             //                the limit to 10000
46             //  -actions : don't show the actions dropdown
47             //  -index : don't show the row index column (can't use "index"
48             //           as the idField in this case)
49             //  -display : columns are hidden by default
50             //  -sort    : columns are unsortable by default 
51             //  -multisort : sort priorities config disabled by default
52             //  -multiselect : only one row at a time can be selected;
53             //                 choosing this also disables the checkbox
54             //                 column
55             features : '@',
56
57             // optional: object containing function to conditionally apply
58             //    class to each row.
59             rowClass : '=',
60
61             // optional: object that enables status icon field and contains
62             //    function to handle what status icons should exist and why.
63             statusCell : '=',
64
65             // optional primary grid label
66             mainLabel : '@',
67
68             // if true, use the IDL class label as the mainLabel
69             autoLabel : '=', 
70
71             // optional context menu label
72             menuLabel : '@',
73
74             dateformat : '@', // optional: passed down to egGridValueFilter
75             datecontext: '@', // optional: passed down to egGridValueFilter to choose TZ
76             datefilter: '@', // optional: passed down to egGridValueFilter to choose specialized date filters
77             dateonlyinterval: '@', // optional: passed down to egGridValueFilter to choose a "better" format
78
79             // Hash of control functions.
80             //
81             //  These functions are defined by the calling scope and 
82             //  invoked as-is by the grid w/ the specified parameters.
83             //
84             //  collectStarted    : function() {}
85             //  itemRetrieved     : function(item) {}
86             //  allItemsRetrieved : function() {}
87             //
88             //  ---
89             //  If defined, the grid will watch the return value from
90             //  the function defined at watchQuery on each digest and 
91             //  re-draw the grid when query changes occur.
92             //
93             //  watchQuery : function() { /* return grid query */ }
94             //
95             //  ---------------
96             //  These functions are defined by the grid and thus
97             //  replace any values defined for these attributes from the
98             //  calling scope.
99             //
100             //  activateItem  : function(item) {}
101             //  allItems      : function(allItems) {}
102             //  selectedItems : function(selected) {}
103             //  selectItems   : function(ids) {}
104             //  setQuery      : function(queryStruct) {} // causes reload
105             //  setSort       : function(sortSturct) {} // causes reload
106             gridControls : '=',
107         },
108
109         // TODO: avoid hard-coded url
110         templateUrl : '/eg/staff/share/t_autogrid', 
111
112         link : function(scope, element, attrs) {     
113             // link() is called after page compilation, which means our
114             // eg-grid-field's have been parsed and loaded.  Now it's 
115             // safe to perform our initial page load.
116
117             // load auto fields after eg-grid-field's so they are not clobbered
118             scope.handleAutoFields();
119             scope.collect();
120
121             var statusCell = scope.statusCell;
122             var rowClass = scope.rowClass;
123
124             scope.grid_element = element;
125             $(element)
126                 .find('.eg-grid-content-body')
127                 .bind('contextmenu', scope.showActionContextMenu);
128         },
129
130         controller : [
131                     '$scope','$q','egCore','egGridFlatDataProvider','$location',
132                     'egGridColumnsProvider','$filter','$window','$sce','$timeout',
133                     'egProgressDialog','$uibModal',
134             function($scope,  $q , egCore,  egGridFlatDataProvider , $location,
135                      egGridColumnsProvider , $filter , $window , $sce , $timeout,
136                      egProgressDialog , $uibModal) {
137
138             var grid = this;
139
140             grid.init = function() {
141                 grid.offset = 0;
142                 $scope.items = [];
143                 $scope.showGridConf = false;
144                 grid.totalCount = -1;
145                 $scope.selected = {};
146                 $scope.actionGroups = [{actions:[]}]; // Grouped actions for selected items
147                 $scope.menuItems = []; // global actions
148
149                 // returns true if any rows are selected.
150                 $scope.hasSelected = function() {
151                     return grid.getSelectedItems().length > 0 };
152
153                 var features = ($scope.features) ? 
154                     $scope.features.split(',') : [];
155                 delete $scope.features;
156
157                 $scope.showIndex = (features.indexOf('-index') == -1);
158
159                 $scope.allowAll = (features.indexOf('allowAll') > -1);
160                 $scope.startSelected = $scope.selectAll = (features.indexOf('startSelected') > -1);
161                 $scope.showActions = (features.indexOf('-actions') == -1);
162                 $scope.showPagination = (features.indexOf('-pagination') == -1);
163                 $scope.showPicker = (features.indexOf('-picker') == -1);
164
165                 $scope.showMenu = (features.indexOf('-menu') == -1);
166
167                 // remove some unneeded values from the scope to reduce bloat
168
169                 grid.idlClass = $scope.idlClass;
170                 delete $scope.idlClass;
171
172                 grid.persistKey = $scope.persistKey;
173                 delete $scope.persistKey;
174
175                 var stored_limit = 0;
176                 if ($scope.showPagination) {
177                     if (grid.persistKey) {
178                         var stored_limit = Number(
179                             egCore.hatch.getLocalItem('eg.grid.' + grid.persistKey + '.limit')
180                         );
181                     }
182                 } else {
183                     stored_limit = 10000; // maybe support "Inf"?
184                 }
185
186                 grid.limit = Number(stored_limit) || Number($scope.pageSize) || 25;
187
188                 grid.indexField = $scope.idField;
189                 delete $scope.idField;
190
191                 grid.dataProvider = $scope.itemsProvider;
192
193                 if (!grid.indexField && grid.idlClass)
194                     grid.indexField = egCore.idl.classes[grid.idlClass].pkey;
195
196                 grid.columnsProvider = egGridColumnsProvider.instance({
197                     idlClass : grid.idlClass,
198                     clientSort : (features.indexOf('clientsort') > -1 && features.indexOf('-clientsort') == -1),
199                     defaultToHidden : (features.indexOf('-display') > -1),
200                     defaultToNoSort : (features.indexOf('-sort') > -1),
201                     defaultToNoMultiSort : (features.indexOf('-multisort') > -1),
202                     defaultDateFormat : $scope.dateformat,
203                     defaultDateContext : $scope.datecontext,
204                     defaultDateFilter : $scope.datefilter,
205                     defaultDateOnlyInterval : $scope.dateonlyinterval
206                 });
207                 $scope.canMultiSelect = (features.indexOf('-multiselect') == -1);
208
209                 $scope.handleAutoFields = function() {
210                     if ($scope.autoFields) {
211                         if (grid.autoLabel) {
212                             $scope.mainLabel = 
213                                 egCore.idl.classes[grid.idlClass].label;
214                         }
215                         grid.columnsProvider.compileAutoColumns();
216                         delete $scope.autoFields;
217                     }
218                 }
219    
220                 if (!grid.dataProvider) {
221                     // no provider, um, provided.
222                     // Use a flat data provider
223
224                     grid.selfManagedData = true;
225                     grid.dataProvider = egGridFlatDataProvider.instance({
226                         indexField : grid.indexField,
227                         idlClass : grid.idlClass,
228                         columnsProvider : grid.columnsProvider,
229                         query : $scope.query
230                     });
231                 }
232
233                 // make grid ref available in get() to set totalCount, if known.
234                 // this allows us disable the 'next' paging button correctly
235                 grid.dataProvider.grid = grid;
236
237                 grid.dataProvider.columnsProvider = grid.columnsProvider;
238
239                 $scope.itemFieldValue = grid.dataProvider.itemFieldValue;
240                 $scope.indexValue = function(item) {
241                     return grid.indexValue(item)
242                 };
243
244                 grid.applyControlFunctions();
245
246                 grid.loadConfig().then(function() { 
247                     // link columns to scope after loadConfig(), since it
248                     // replaces the columns array.
249                     $scope.columns = grid.columnsProvider.columns;
250                 });
251
252                 // NOTE: grid.collect() is first called from link(), not here.
253             }
254
255             // link our control functions into the gridControls 
256             // scope object so the caller can access them.
257             grid.applyControlFunctions = function() {
258
259                 // we use some of these controls internally, so sett
260                 // them up even if the caller doesn't request them.
261                 var controls = $scope.gridControls || {};
262
263                 controls.columnMap = function() {
264                     var m = {};
265                     angular.forEach(grid.columnsProvider.columns, function (c) {
266                         m[c.name] = c;
267                     });
268                     return m;
269                 }
270
271                 controls.columnsProvider = function() {
272                     return grid.columnsProvider;
273                 }
274
275                 // link in the control functions
276                 controls.selectedItems = function() {
277                     return grid.getSelectedItems()
278                 }
279
280                 controls.allItems = function() {
281                     return $scope.items;
282                 }
283
284                 controls.selectItems = function(ids) {
285                     if (!ids) return;
286                     $scope.selected = {};
287                     angular.forEach(ids, function(i) {
288                         $scope.selected[''+i] = true;
289                     });
290                 }
291
292                 // if the caller provided a functional setQuery,
293                 // extract the value before replacing it
294                 if (controls.setQuery) {
295                     grid.dataProvider.query = 
296                         controls.setQuery();
297                 }
298
299                 controls.setQuery = function(query) {
300                     grid.dataProvider.query = query;
301                     controls.refresh();
302                 }
303
304                 if (controls.watchQuery) {
305                     // capture the initial query value
306                     grid.dataProvider.query = controls.watchQuery();
307
308                     // watch for changes
309                     $scope.gridWatchQuery = controls.watchQuery;
310                     $scope.$watch('gridWatchQuery()', function(newv) {
311                         controls.setQuery(newv);
312                     }, true);
313                 }
314
315                 // if the caller provided a functional setSort
316                 // extract the value before replacing it
317                 grid.dataProvider.sort = 
318                     controls.setSort ?  controls.setSort() : [];
319
320                 controls.setSort = function(sort) {
321                     controls.refresh();
322                 }
323
324                 controls.refresh = function(noReset) {
325                     if (!noReset) grid.offset = 0;
326                     grid.collect();
327                 }
328
329                 controls.setLimit = function(limit,forget) {
330                     if (!forget && grid.persistKey)
331                         egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', limit);
332                     grid.limit = limit;
333                 }
334                 controls.getLimit = function() {
335                     return grid.limit;
336                 }
337                 controls.setOffset = function(offset) {
338                     grid.offset = offset;
339                 }
340                 controls.getOffset = function() {
341                     return grid.offset;
342                 }
343
344                 controls.saveConfig = function () {
345                     return $scope.saveConfig();
346                 }
347
348                 grid.dataProvider.refresh = controls.refresh;
349                 grid.controls = controls;
350             }
351
352             // If a menu item provides its own HTML template, translate it,
353             // using the menu item for the template scope.
354             // note: $sce is required to avoid security restrictions and
355             // is OK here, since the template comes directly from a
356             // local HTML template (not user input).
357             $scope.translateMenuItemTemplate = function(item) {
358                 var html = egCore.strings.$replace(item.template, {item : item});
359                 return $sce.trustAsHtml(html);
360             }
361
362             // add a new (global) grid menu item
363             grid.addMenuItem = function(item) {
364                 $scope.menuItems.push(item);
365                 var handler = item.handler;
366                 item.handler = function() {
367                     $scope.gridMenuIsOpen = false; // close menu
368                     if (handler) {
369                         handler(item, 
370                             item.handlerData, grid.getSelectedItems());
371                     }
372                 }
373             }
374
375             // add a selected-items action
376             grid.addAction = function(act) {
377                 var done = false;
378                 $scope.actionGroups.forEach(function(g){
379                     if (g.label === act.group) {
380                         g.actions.push(act);
381                         done = true;
382                     }
383                 });
384                 if (!done) {
385                     $scope.actionGroups.push({
386                         label : act.group,
387                         actions : [ act ]
388                     });
389                 }
390             }
391
392             // remove the stored column configuration preferenc, then recover 
393             // the column visibility information from the initial page load.
394             $scope.resetColumns = function() {
395                 $scope.gridColumnPickerIsOpen = false;
396                 egCore.hatch.removeItem('eg.grid.' + grid.persistKey)
397                 .then(function() {
398                     grid.columnsProvider.reset(); 
399                     if (grid.selfManagedData) grid.collect();
400                 });
401             }
402
403             $scope.showAllColumns = function() {
404                 $scope.gridColumnPickerIsOpen = false;
405                 grid.columnsProvider.showAllColumns();
406                 if (grid.selfManagedData) grid.collect();
407             }
408
409             $scope.hideAllColumns = function() {
410                 $scope.gridColumnPickerIsOpen = false;
411                 grid.columnsProvider.hideAllColumns();
412                 // note: no need to fetch new data if no columns are visible
413             }
414
415             $scope.toggleColumnVisibility = function(col) {
416                 $scope.gridColumnPickerIsOpen = false;
417                 col.visible = !col.visible;
418
419                 // egGridFlatDataProvider only retrieves data to be
420                 // displayed.  When column visibility changes, it's
421                 // necessary to fetch the newly visible column data.
422                 if (grid.selfManagedData) grid.collect();
423             }
424
425             // save the columns configuration (position, sort, width) to
426             // eg.grid.<persist-key>
427             $scope.saveConfig = function() {
428                 $scope.gridColumnPickerIsOpen = false;
429
430                 if (!grid.persistKey) {
431                     console.warn(
432                         "Cannot save settings without a grid persist-key");
433                     return;
434                 }
435
436                 // only store information about visible columns.
437                 var conf = grid.columnsProvider.columns.filter(
438                     function(col) {return Boolean(col.visible) });
439
440                 // now scrunch the data down to just the needed info
441                 conf = conf.map(function(col) {
442                     var c = {name : col.name}
443                     // Apart from the name, only store non-default values.
444                     // No need to store col.visible, since that's implicit
445                     if (col.align != 'left') c.align = col.align;
446                     if (col.flex != 2) c.flex = col.flex;
447                     if (Number(col.sort)) c.sort = Number(c.sort);
448                     return c;
449                 });
450
451                 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
452                 .then(function() { 
453                     // Save operation performed from the grid configuration UI.
454                     // Hide the configuration UI and re-draw w/ sort applied
455                     if ($scope.showGridConf) 
456                         $scope.toggleConfDisplay();
457                 });
458             }
459
460
461             // load the columns configuration (position, sort, width) from
462             // eg.grid.<persist-key> and apply the loaded settings to the
463             // columns on our columnsProvider
464             grid.loadConfig = function() {
465                 if (!grid.persistKey) return $q.when();
466
467                 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
468                 .then(function(conf) {
469                     if (!conf) return;
470
471                     var columns = grid.columnsProvider.columns;
472                     var new_cols = [];
473
474                     angular.forEach(conf, function(col) {
475                         var grid_col = columns.filter(
476                             function(c) {return c.name == col.name})[0];
477
478                         if (!grid_col) {
479                             // saved column does not match a column in the 
480                             // current grid.  skip it.
481                             return;
482                         }
483
484                         grid_col.align = col.align || 'left';
485                         grid_col.flex = col.flex || 2;
486                         grid_col.sort = col.sort || 0;
487                         // all saved columns are assumed to be true
488                         grid_col.visible = true;
489                         if (new_cols
490                                 .filter(function (c) {
491                                     return c.name == grid_col.name;
492                                 }).length == 0
493                         )
494                             new_cols.push(grid_col);
495                     });
496
497                     // columns which are not expressed within the saved 
498                     // configuration are marked as non-visible and 
499                     // appended to the end of the new list of columns.
500                     angular.forEach(columns, function(col) {
501                         var found = conf.filter(
502                             function(c) {return (c.name == col.name)})[0];
503                         if (!found) {
504                             col.visible = false;
505                             new_cols.push(col);
506                         }
507                     });
508
509                     grid.columnsProvider.columns = new_cols;
510                     grid.compileSort();
511
512                 });
513             }
514
515             $scope.onContextMenu = function($event) {
516                 var col = angular.element($event.target).attr('column');
517                 console.log('selected column ' + col);
518             }
519
520             $scope.page = function() {
521                 return (grid.offset / grid.limit) + 1;
522             }
523
524             $scope.goToPage = function(page) {
525                 page = Number(page);
526                 if (angular.isNumber(page) && page > 0) {
527                     grid.offset = (page - 1) * grid.limit;
528                     grid.collect();
529                 }
530             }
531
532             $scope.offset = function(o) {
533                 if (angular.isNumber(o))
534                     grid.offset = o;
535                 return grid.offset 
536             }
537
538             $scope.limit = function(l) { 
539                 if (angular.isNumber(l)) {
540                     if (grid.persistKey)
541                         egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', l);
542                     grid.limit = l;
543                 }
544                 return grid.limit 
545             }
546
547             $scope.onFirstPage = function() {
548                 return grid.offset == 0;
549             }
550
551             $scope.hasNextPage = function() {
552                 // we have less data than requested, there must
553                 // not be any more pages
554                 if (grid.count() < grid.limit) return false;
555
556                 // if the total count is not known, assume that a full
557                 // page of data implies more pages are available.
558                 if (grid.totalCount == -1) return true;
559
560                 // we have a full page of data, but is there more?
561                 return grid.totalCount > (grid.offset + grid.count());
562             }
563
564             $scope.incrementPage = function() {
565                 grid.offset += grid.limit;
566                 grid.collect();
567             }
568
569             $scope.decrementPage = function() {
570                 if (grid.offset < grid.limit) {
571                     grid.offset = 0;
572                 } else {
573                     grid.offset -= grid.limit;
574                 }
575                 grid.collect();
576             }
577
578             // number of items loaded for the current page of results
579             grid.count = function() {
580                 return $scope.items.length;
581             }
582
583             // returns the unique identifier value for the provided item
584             // for internal consistency, indexValue is always coerced 
585             // into a string.
586             grid.indexValue = function(item) {
587                 if (angular.isObject(item)) {
588                     if (item !== null) {
589                         if (angular.isFunction(item[grid.indexField]))
590                             return ''+item[grid.indexField]();
591                         return ''+item[grid.indexField]; // flat data
592                     }
593                 }
594                 // passed a non-object; assume it's an index
595                 return ''+item; 
596             }
597
598             // fires the hide handler function for a context action
599             $scope.actionHide = function(action) {
600                 if (typeof action.hide == 'undefined') {
601                     return false;
602                 }
603                 if (angular.isFunction(action.hide))
604                     return action.hide(action);
605                 return action.hide;
606             }
607
608             // fires the disable handler function for a context action
609             $scope.actionDisable = function(action) {
610                 if (typeof action.disabled == 'undefined') {
611                     return false;
612                 }
613                 if (angular.isFunction(action.disabled))
614                     return action.disabled(action);
615                 return action.disabled;
616             }
617
618             // fires the action handler function for a context action
619             $scope.actionLauncher = function(action) {
620                 if (!action.handler) {
621                     console.error(
622                         'No handler specified for "' + action.label + '"');
623                 } else {
624
625                     try {
626                         action.handler(grid.getSelectedItems());
627                     } catch(E) {
628                         console.error('Error executing handler for "' 
629                             + action.label + '" => ' + E + "\n" + E.stack);
630                     }
631
632                     if ($scope.action_context_showing) $scope.hideActionContextMenu();
633                 }
634
635             }
636
637             $scope.hideActionContextMenu = function () {
638                 $($scope.menu_dom).css({
639                     display: '',
640                     width: $scope.action_context_width,
641                     top: $scope.action_context_y,
642                     left: $scope.action_context_x
643                 });
644                 $($scope.action_context_parent).append($scope.menu_dom);
645                 $scope.action_context_oldy = $scope.action_context_oldx = 0;
646                 $('body').unbind('click.remove_context_menu_'+$scope.action_context_index);
647                 $scope.action_context_showing = false;
648             }
649
650             $scope.action_context_showing = false;
651             $scope.showActionContextMenu = function ($event) {
652
653                 // Have to gather these here, instead of inside link()
654                 if (!$scope.menu_dom) $scope.menu_dom = $($scope.grid_element).find('.grid-action-dropdown')[0];
655                 if (!$scope.action_context_parent) $scope.action_context_parent = $($scope.menu_dom).parent();
656
657                 if (!grid.getSelectedItems().length) // Nothing selected, fire the click event
658                     $event.target.click();
659
660                 if (!$scope.action_context_showing) {
661                     $scope.action_context_width = $($scope.menu_dom).css('width');
662                     $scope.action_context_y = $($scope.menu_dom).css('top');
663                     $scope.action_context_x = $($scope.menu_dom).css('left');
664                     $scope.action_context_showing = true;
665                     $scope.action_context_index = Math.floor((Math.random() * 1000) + 1);
666
667                     $('body').append($($scope.menu_dom));
668                     $('body').bind('click.remove_context_menu_'+$scope.action_context_index, $scope.hideActionContextMenu);
669                 }
670
671                 $($scope.menu_dom).css({
672                     display: 'block',
673                     width: $scope.action_context_width,
674                     top: $event.pageY,
675                     left: $event.pageX
676                 });
677
678                 return false;
679             }
680
681             // returns the list of selected item objects
682             grid.getSelectedItems = function() {
683                 return $scope.items.filter(
684                     function(item) {
685                         return Boolean($scope.selected[grid.indexValue(item)]);
686                     }
687                 );
688             }
689
690             grid.getItemByIndex = function(index) {
691                 for (var i = 0; i < $scope.items.length; i++) {
692                     var item = $scope.items[i];
693                     if (grid.indexValue(item) == index) 
694                         return item;
695                 }
696             }
697
698             // selects one row after deselecting all of the others
699             grid.selectOneItem = function(index) {
700                 $scope.selected = {};
701                 $scope.selected[index] = true;
702             }
703
704             // selects or deselects an item, without affecting the others.
705             // returns true if the item is selected; false if de-selected.
706             // we overwrite the object so that we can watch $scope.selected
707             grid.toggleSelectOneItem = function(index) {
708                 if ($scope.selected[index]) {
709                     delete $scope.selected[index];
710                     $scope.selected = angular.copy($scope.selected);
711                     return false;
712                 } else {
713                     $scope.selected[index] = true;
714                     $scope.selected = angular.copy($scope.selected);
715                     return true;
716                 }
717             }
718
719             $scope.updateSelected = function () { 
720                     return $scope.selected = angular.copy($scope.selected);
721             };
722
723             grid.selectAllItems = function() {
724                 angular.forEach($scope.items, function(item) {
725                     $scope.selected[grid.indexValue(item)] = true
726                 }); 
727                 $scope.selected = angular.copy($scope.selected);
728             }
729
730             $scope.$watch('selectAll', function(newVal) {
731                 if (newVal) {
732                     grid.selectAllItems();
733                 } else {
734                     $scope.selected = {};
735                 }
736             });
737
738             if ($scope.onSelect) {
739                 $scope.$watch('selected', function(newVal) {
740                     $scope.onSelect(grid.getSelectedItems());
741                     if ($scope.afterSelect) $scope.afterSelect();
742                 });
743             }
744
745             // returns true if item1 appears in the list before item2;
746             // false otherwise.  this is slightly more efficient that
747             // finding the position of each then comparing them.
748             // item1 / item2 may be an item or an item index
749             grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
750                 var idx1 = grid.indexValue(itemOrIndex1);
751                 var idx2 = grid.indexValue(itemOrIndex2);
752
753                 // use for() for early exit
754                 for (var i = 0; i < $scope.items.length; i++) {
755                     var idx = grid.indexValue($scope.items[i]);
756                     if (idx == idx1) return true;
757                     if (idx == idx2) return false;
758                 }
759                 return false;
760             }
761
762             // 0-based position of item in the current data set
763             grid.indexOf = function(item) {
764                 var idx = grid.indexValue(item);
765                 for (var i = 0; i < $scope.items.length; i++) {
766                     if (grid.indexValue($scope.items[i]) == idx)
767                         return i;
768                 }
769                 return -1;
770             }
771
772             grid.modifyColumnFlex = function(column, val) {
773                 column.flex += val;
774                 // prevent flex:0;  use hiding instead
775                 if (column.flex < 1)
776                     column.flex = 1;
777             }
778             $scope.modifyColumnFlex = function(col, val) {
779                 $scope.lastModColumn = col;
780                 grid.modifyColumnFlex(col, val);
781             }
782
783             $scope.isLastModifiedColumn = function(col) {
784                 if ($scope.lastModColumn)
785                     return $scope.lastModColumn === col;
786                 return false;
787             }
788
789             grid.modifyColumnPos = function(col, diff) {
790                 var srcIdx, targetIdx;
791                 angular.forEach(grid.columnsProvider.columns,
792                     function(c, i) { if (c.name == col.name) srcIdx = i });
793
794                 targetIdx = srcIdx + diff;
795                 if (targetIdx < 0) {
796                     targetIdx = 0;
797                 } else if (targetIdx >= grid.columnsProvider.columns.length) {
798                     // Target index follows the last visible column.
799                     var lastVisible = 0;
800                     angular.forEach(grid.columnsProvider.columns, 
801                         function(column, idx) {
802                             if (column.visible) lastVisible = idx;
803                         }
804                     );
805
806                     // When moving a column (down) causes one or more
807                     // visible columns to shuffle forward, our column
808                     // moves into the slot of the last visible column.
809                     // Otherwise, put it into the slot directly following 
810                     // the last visible column.
811                     targetIdx = 
812                         srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
813                 }
814
815                 // Splice column out of old position, insert at new position.
816                 grid.columnsProvider.columns.splice(srcIdx, 1);
817                 grid.columnsProvider.columns.splice(targetIdx, 0, col);
818             }
819
820             $scope.modifyColumnPos = function(col, diff) {
821                 $scope.lastModColumn = col;
822                 return grid.modifyColumnPos(col, diff);
823             }
824
825
826             // handles click, control-click, and shift-click
827             $scope.handleRowClick = function($event, item) {
828                 var index = grid.indexValue(item);
829
830                 var origSelected = Object.keys($scope.selected);
831
832                 if (!$scope.canMultiSelect) {
833                     grid.selectOneItem(index);
834                     grid.lastSelectedItemIndex = index;
835                     return;
836                 }
837
838                 if ($event.ctrlKey || $event.metaKey /* mac command */) {
839                     // control-click
840                     if (grid.toggleSelectOneItem(index)) 
841                         grid.lastSelectedItemIndex = index;
842
843                 } else if ($event.shiftKey) { 
844                     // shift-click
845
846                     if (!grid.lastSelectedItemIndex || 
847                             index == grid.lastSelectedItemIndex) {
848                         grid.selectOneItem(index);
849                         grid.lastSelectedItemIndex = index;
850
851                     } else {
852
853                         var selecting = false;
854                         var ascending = grid.itemComesBefore(
855                             grid.lastSelectedItemIndex, item);
856                         var startPos = 
857                             grid.indexOf(grid.lastSelectedItemIndex);
858
859                         // update to new last-selected
860                         grid.lastSelectedItemIndex = index;
861
862                         // select each row between the last selected and 
863                         // currently selected items
864                         while (true) {
865                             startPos += ascending ? 1 : -1;
866                             var curItem = $scope.items[startPos];
867                             if (!curItem) break;
868                             var curIdx = grid.indexValue(curItem);
869                             $scope.selected[curIdx] = true;
870                             if (curIdx == index) break; // all done
871                         }
872                         $scope.selected = angular.copy($scope.selected);
873                     }
874                         
875                 } else {
876                     grid.selectOneItem(index);
877                     grid.lastSelectedItemIndex = index;
878                 }
879             }
880
881             // Builds a sort expression from column sort priorities.
882             // called on page load and any time the priorities are modified.
883             grid.compileSort = function() {
884                 var sortList = grid.columnsProvider.columns.filter(
885                     function(col) { return Number(col.sort) != 0 }
886                 ).sort( 
887                     function(a, b) { 
888                         if (Math.abs(a.sort) < Math.abs(b.sort))
889                             return -1;
890                         return 1;
891                     }
892                 );
893
894                 if (sortList.length) {
895                     grid.dataProvider.sort = sortList.map(function(col) {
896                         var blob = {};
897                         blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
898                         return blob;
899                     });
900                 }
901             }
902
903             // builds a sort expression using a single column, 
904             // toggling between ascending and descending sort.
905             $scope.quickSort = function(col_name) {
906                 var sort = grid.dataProvider.sort;
907                 if (sort && sort.length &&
908                     sort[0] == col_name) {
909                     var blob = {};
910                     blob[col_name] = 'desc';
911                     grid.dataProvider.sort = [blob];
912                 } else {
913                     grid.dataProvider.sort = [col_name];
914                 }
915
916                 grid.offset = 0;
917                 grid.collect();
918             }
919
920             // show / hide the grid configuration row
921             $scope.toggleConfDisplay = function() {
922                 if ($scope.showGridConf) {
923                     $scope.showGridConf = false;
924                     if (grid.columnsProvider.hasSortableColumn()) {
925                         // only refresh the grid if the user has the
926                         // ability to modify the sort priorities.
927                         grid.compileSort();
928                         grid.offset = 0;
929                         grid.collect();
930                     }
931                 } else {
932                     $scope.showGridConf = true;
933                 }
934
935                 delete $scope.lastModColumn;
936                 $scope.gridColumnPickerIsOpen = false;
937             }
938
939             // called when a dragged column is dropped onto itself
940             // or any other column
941             grid.onColumnDrop = function(target) {
942                 if (angular.isUndefined(target)) return;
943                 if (target == grid.dragColumn) return;
944                 var srcIdx, targetIdx, srcCol;
945                 angular.forEach(grid.columnsProvider.columns,
946                     function(col, idx) {
947                         if (col.name == grid.dragColumn) {
948                             srcIdx = idx;
949                             srcCol = col;
950                         } else if (col.name == target) {
951                             targetIdx = idx;
952                         }
953                     }
954                 );
955
956                 if (srcIdx < targetIdx) targetIdx--;
957
958                 // move src column from old location to new location in 
959                 // the columns array, then force a page refresh
960                 grid.columnsProvider.columns.splice(srcIdx, 1);
961                 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
962                 $scope.$apply(); 
963             }
964
965             // prepares a string for inclusion within a CSV document
966             // by escaping commas and quotes and removing newlines.
967             grid.csvDatum = function(str) {
968                 str = ''+str;
969                 if (!str) return '';
970                 str = str.replace(/\n/g, '');
971                 if (str.match(/\,/) || str.match(/"/)) {                                     
972                     str = str.replace(/"/g, '""');
973                     str = '"' + str + '"';                                           
974                 } 
975                 return str;
976             }
977
978             /** Export the full data set as CSV.
979              *  Flow of events:
980              *  1. User clicks the 'download csv' link
981              *  2. All grid data is retrieved asychronously
982              *  3. Once all data is all present and CSV-ized, the download 
983              *     attributes are linked to the href.
984              *  4. The href .click() action is prgrammatically fired again,
985              *     telling the browser to download the data, now that the
986              *     data is available for download.
987              *  5 Once downloaded, the href attributes are reset.
988              */
989             grid.csvExportInProgress = false;
990             $scope.generateCSVExportURL = function($event) {
991
992                 if (grid.csvExportInProgress) {
993                     // This is secondary href click handler.  Give the
994                     // browser a moment to start the download, then reset
995                     // the CSV download attributes / state.
996                     $timeout(
997                         function() {
998                             $scope.csvExportURL = '';
999                             $scope.csvExportFileName = ''; 
1000                             grid.csvExportInProgress = false;
1001                         }, 500
1002                     );
1003                     return;
1004                 } 
1005
1006                 grid.csvExportInProgress = true;
1007                 $scope.gridColumnPickerIsOpen = false;
1008
1009                 // let the file name describe the grid
1010                 $scope.csvExportFileName = 
1011                     ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
1012                     .replace(/\s+/g, '_') + '_' + $scope.page();
1013
1014                 // toss the CSV into a Blob and update the export URL
1015                 grid.generateCSV().then(function(csv) {
1016                     var blob = new Blob([csv], {type : 'text/plain'});
1017                     $scope.csvExportURL = 
1018                         ($window.URL || $window.webkitURL).createObjectURL(blob);
1019
1020                     // Fire the 2nd click event now that the browser has
1021                     // information on how to download the CSV file.
1022                     $timeout(function() {$event.target.click()});
1023                 });
1024             }
1025
1026             /*
1027              * TODO: does this serve any purpose given we can 
1028              * print formatted HTML?  If so, generateCSV() now
1029              * returns a promise, needs light refactoring...
1030             $scope.printCSV = function() {
1031                 $scope.gridColumnPickerIsOpen = false;
1032                 egCore.print.print({
1033                     context : 'default', 
1034                     content : grid.generateCSV(),
1035                     content_type : 'text/plain'
1036                 });
1037             }
1038             */
1039
1040             // Given a row item and column definition, extract the
1041             // text content for printing.  Templated columns must be
1042             // processed and parsed as HTML, then boiled down to their 
1043             // text content.
1044             grid.getItemTextContent = function(item, col) {
1045                 var val;
1046                 if (col.template) {
1047                     val = $scope.translateCellTemplate(col, item);
1048                     if (val) {
1049                         var node = new DOMParser()
1050                             .parseFromString(val, 'text/html');
1051                         val = $(node).text();
1052                     }
1053                 } else {
1054                     val = grid.dataProvider.itemFieldValue(item, col);
1055                     val = $filter('egGridValueFilter')(val, col, item);
1056                 }
1057                 return val;
1058             }
1059
1060             /**
1061              * Fetches all grid data and transates each item into a simple
1062              * key-value pair of column name => text-value.
1063              * Included in the response for convenience is the list of 
1064              * currently visible column definitions.
1065              * TODO: currently fetches a maximum of 10k rows.  Does this
1066              * need to be configurable?
1067              */
1068             grid.getAllItemsAsText = function() {
1069                 var text_items = [];
1070
1071                 // we don't know the total number of rows we're about
1072                 // to retrieve, but we can indicate the number retrieved
1073                 // so far as each item arrives.
1074                 egProgressDialog.open({value : 0});
1075
1076                 var visible_cols = grid.columnsProvider.columns.filter(
1077                     function(c) { return c.visible });
1078
1079                 return grid.dataProvider.get(0, 10000).then(
1080                     function() { 
1081                         return {items : text_items, columns : visible_cols};
1082                     }, 
1083                     null,
1084                     function(item) { 
1085                         egProgressDialog.increment();
1086                         var text_item = {};
1087                         angular.forEach(visible_cols, function(col) {
1088                             text_item[col.name] = 
1089                                 grid.getItemTextContent(item, col);
1090                         });
1091                         text_items.push(text_item);
1092                     }
1093                 ).finally(egProgressDialog.close);
1094             }
1095
1096             // Fetch "all" of the grid data, translate it into print-friendly 
1097             // text, and send it to the printer service.
1098             $scope.printHTML = function() {
1099                 $scope.gridColumnPickerIsOpen = false;
1100                 return grid.getAllItemsAsText().then(function(text_items) {
1101                     return egCore.print.print({
1102                         template : 'grid_html',
1103                         scope : text_items
1104                     });
1105                 });
1106             }
1107
1108             $scope.showColumnDialog = function() {
1109                 return $uibModal.open({
1110                     templateUrl: './share/t_grid_columns',
1111                     backdrop: 'static',
1112                     size : 'lg',
1113                     controller: ['$scope', '$uibModalInstance',
1114                         function($dialogScope, $uibModalInstance) {
1115                             $dialogScope.modifyColumnPos = $scope.modifyColumnPos;
1116                             $dialogScope.disableMultiSort = $scope.disableMultiSort;
1117                             $dialogScope.columns = $scope.columns;
1118
1119                             // Push visible columns to the top of the list
1120                             $dialogScope.elevateVisible = function() {
1121                                 var new_cols = [];
1122                                 angular.forEach($dialogScope.columns, function(col) {
1123                                     if (col.visible) new_cols.push(col);
1124                                 });
1125                                 angular.forEach($dialogScope.columns, function(col) {
1126                                     if (!col.visible) new_cols.push(col);
1127                                 });
1128
1129                                 // Update all references to the list of columns
1130                                 $dialogScope.columns = 
1131                                     $scope.columns = 
1132                                     grid.columnsProvider.columns = 
1133                                     new_cols;
1134                             }
1135
1136                             $dialogScope.toggle = function(col) {
1137                                 col.visible = !Boolean(col.visible);
1138                             }
1139                             $dialogScope.ok = $dialogScope.cancel = function() {
1140                                 delete $scope.lastModColumn;
1141                                 $uibModalInstance.close()
1142                             }
1143                         }
1144                     ]
1145                 });
1146             },
1147
1148             // generates CSV for the currently visible grid contents
1149             grid.generateCSV = function() {
1150                 return grid.getAllItemsAsText().then(function(text_items) {
1151                     var columns = text_items.columns;
1152                     var items = text_items.items;
1153                     var csvStr = '';
1154
1155                     // column headers
1156                     angular.forEach(columns, function(col) {
1157                         csvStr += grid.csvDatum(col.label);
1158                         csvStr += ',';
1159                     });
1160
1161                     csvStr = csvStr.replace(/,$/,'\n');
1162
1163                     // items
1164                     angular.forEach(items, function(item) {
1165                         angular.forEach(columns, function(col) {
1166                             csvStr += grid.csvDatum(item[col.name]);
1167                             csvStr += ',';
1168                         });
1169                         csvStr = csvStr.replace(/,$/,'\n');
1170                     });
1171
1172                     return csvStr;
1173                 });
1174             }
1175
1176             // Interpolate the value for column.linkpath within the context
1177             // of the row item to generate the final link URL.
1178             $scope.generateLinkPath = function(col, item) {
1179                 return egCore.strings.$replace(col.linkpath, {item : item});
1180             }
1181
1182             // If a column provides its own HTML template, translate it,
1183             // using the current item for the template scope.
1184             // note: $sce is required to avoid security restrictions and
1185             // is OK here, since the template comes directly from a
1186             // local HTML template (not user input).
1187             $scope.translateCellTemplate = function(col, item) {
1188                 var html = egCore.strings.$replace(col.template, {item : item});
1189                 return $sce.trustAsHtml(html);
1190             }
1191
1192             $scope.collect = function() { grid.collect() }
1193
1194             // asks the dataProvider for a page of data
1195             grid.collect = function() {
1196
1197                 // avoid firing the collect if there is nothing to collect.
1198                 if (grid.selfManagedData && !grid.dataProvider.query) return;
1199
1200                 if (grid.collecting) return; // avoid parallel collect()
1201                 grid.collecting = true;
1202
1203                 console.debug('egGrid.collect() offset=' 
1204                     + grid.offset + '; limit=' + grid.limit);
1205
1206                 // ensure all of our dropdowns are closed
1207                 // TODO: git rid of these and just use dropdown-toggle, 
1208                 // which is more reliable.
1209                 $scope.gridColumnPickerIsOpen = false;
1210                 $scope.gridRowCountIsOpen = false;
1211                 $scope.gridPageSelectIsOpen = false;
1212
1213                 $scope.items = [];
1214                 $scope.selected = {};
1215
1216                 // Inform the caller we've asked the data provider
1217                 // for data.  This is useful for knowing when collection
1218                 // has started (e.g. to display a progress dialg) when 
1219                 // using the stock (flattener) data provider, where the 
1220                 // user is not directly defining a get() handler.
1221                 if (grid.controls.collectStarted)
1222                     grid.controls.collectStarted(grid.offset, grid.limit);
1223
1224                 grid.dataProvider.get(grid.offset, grid.limit).then(
1225                 function() {
1226                     if (grid.controls.allItemsRetrieved)
1227                         grid.controls.allItemsRetrieved();
1228                 },
1229                 null, 
1230                 function(item) {
1231                     if (item) {
1232                         $scope.items.push(item)
1233                         if (grid.controls.itemRetrieved)
1234                             grid.controls.itemRetrieved(item);
1235                         if ($scope.selectAll)
1236                             $scope.selected[grid.indexValue(item)] = true
1237                     }
1238                 }).finally(function() { 
1239                     console.debug('egGrid.collect() complete');
1240                     grid.collecting = false 
1241                     $scope.selected = angular.copy($scope.selected);
1242                 });
1243             }
1244
1245             grid.init();
1246         }]
1247     };
1248 })
1249
1250 /**
1251  * eg-grid-field : used for collecting custom field data from the templates.
1252  * This directive does not direct display, it just passes data up to the 
1253  * parent grid.
1254  */
1255 .directive('egGridField', function() {
1256     return {
1257         require : '^egGrid',
1258         restrict : 'AE',
1259         scope : {
1260             flesher: '=', // optional; function that can flesh a linked field, given the value
1261             comparator: '=', // optional; function that can sort the thing at the end of 'path' 
1262             name  : '@', // required; unique name
1263             path  : '@', // optional; flesh path
1264             ignore: '@', // optional; fields to ignore when path is a wildcard
1265             label : '@', // optional; display label
1266             flex  : '@',  // optional; default flex width
1267             align  : '@',  // optional; default alignment, left/center/right
1268             dateformat : '@', // optional: passed down to egGridValueFilter
1269             datecontext: '@', // optional: passed down to egGridValueFilter to choose TZ
1270             datefilter: '@', // optional: passed down to egGridValueFilter to choose specialized date filters
1271             dateonlyinterval: '@', // optional: passed down to egGridValueFilter to choose a "better" format
1272
1273             // if a field is part of an IDL object, but we are unable to
1274             // determine the class, because it's nested within a hash
1275             // (i.e. we can't navigate directly to the object via the IDL),
1276             // idlClass lets us specify the class.  This is particularly
1277             // useful for nested wildcard fields.
1278             parentIdlClass : '@', 
1279
1280             // optional: for non-IDL columns, specifying a datatype
1281             // lets the caller control which display filter is used.
1282             // datatype should match the standard IDL datatypes.
1283             datatype : '@',
1284
1285             // optional hash of functions that can be imported into
1286             // the directive's scope; meant for cases where the "compiled"
1287             // attribute is set
1288             handlers : '='
1289         },
1290         link : function(scope, element, attrs, egGridCtrl) {
1291
1292             // boolean fields are presented as value-less attributes
1293             angular.forEach(
1294                 [
1295                     'visible', 
1296                     'compiled', 
1297                     'hidden', 
1298                     'sortable', 
1299                     'nonsortable',
1300                     'multisortable',
1301                     'nonmultisortable',
1302                     'required' // if set, always fetch data for this column
1303                 ],
1304                 function(field) {
1305                     if (angular.isDefined(attrs[field]))
1306                         scope[field] = true;
1307                 }
1308             );
1309
1310             // any HTML content within the field is its custom template
1311             var tmpl = element.html();
1312             if (tmpl && !tmpl.match(/^\s*$/))
1313                 scope.template = tmpl
1314
1315             egGridCtrl.columnsProvider.add(scope);
1316             scope.$destroy();
1317         }
1318     };
1319 })
1320
1321 /**
1322  * eg-grid-action : used for specifying actions which may be applied
1323  * to items within the grid.
1324  */
1325 .directive('egGridAction', function() {
1326     return {
1327         require : '^egGrid',
1328         restrict : 'AE',
1329         transclude : true,
1330         scope : {
1331             group   : '@', // Action group, ungrouped if not set
1332             label   : '@', // Action label
1333             handler : '=',  // Action function handler
1334             hide    : '=',
1335             disabled : '=', // function
1336             divider : '='
1337         },
1338         link : function(scope, element, attrs, egGridCtrl) {
1339             egGridCtrl.addAction({
1340                 hide  : scope.hide,
1341                 group : scope.group,
1342                 label : scope.label,
1343                 divider : scope.divider,
1344                 handler : scope.handler,
1345                 disabled : scope.disabled,
1346             });
1347             scope.$destroy();
1348         }
1349     };
1350 })
1351
1352 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1353
1354     function ColumnsProvider(args) {
1355         var cols = this;
1356         cols.columns = [];
1357         cols.stockVisible = [];
1358         cols.idlClass = args.idlClass;
1359         cols.clientSort = args.clientSort;
1360         cols.defaultToHidden = args.defaultToHidden;
1361         cols.defaultToNoSort = args.defaultToNoSort;
1362         cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1363         cols.defaultDateFormat = args.defaultDateFormat;
1364         cols.defaultDateContext = args.defaultDateContext;
1365
1366         // resets column width, visibility, and sort behavior
1367         // Visibility resets to the visibility settings defined in the 
1368         // template (i.e. the original egGridField values).
1369         cols.reset = function() {
1370             angular.forEach(cols.columns, function(col) {
1371                 col.align = 'left';
1372                 col.flex = 2;
1373                 col.sort = 0;
1374                 if (cols.stockVisible.indexOf(col.name) > -1) {
1375                     col.visible = true;
1376                 } else {
1377                     col.visible = false;
1378                 }
1379             });
1380         }
1381
1382         // returns true if any columns are sortable
1383         cols.hasSortableColumn = function() {
1384             return cols.columns.filter(
1385                 function(col) {
1386                     return col.sortable || col.multisortable;
1387                 }
1388             ).length > 0;
1389         }
1390
1391         cols.showAllColumns = function() {
1392             angular.forEach(cols.columns, function(column) {
1393                 column.visible = true;
1394             });
1395         }
1396
1397         cols.hideAllColumns = function() {
1398             angular.forEach(cols.columns, function(col) {
1399                 delete col.visible;
1400             });
1401         }
1402
1403         cols.indexOf = function(name) {
1404             for (var i = 0; i < cols.columns.length; i++) {
1405                 if (cols.columns[i].name == name) 
1406                     return i;
1407             }
1408             return -1;
1409         }
1410
1411         cols.findColumn = function(name) {
1412             return cols.columns[cols.indexOf(name)];
1413         }
1414
1415         cols.compileAutoColumns = function() {
1416             var idl_class = egCore.idl.classes[cols.idlClass];
1417
1418             angular.forEach(
1419                 idl_class.fields,
1420                 function(field) {
1421                     if (field.virtual) return;
1422                     if (field.datatype == 'link' || field.datatype == 'org_unit') {
1423                         // if the field is a link and the linked class has a
1424                         // "selector" field specified, use the selector field
1425                         // as the display field for the columns.
1426                         // flattener will take care of the fleshing.
1427                         if (field['class']) {
1428                             var selector_field = egCore.idl.classes[field['class']].fields
1429                                 .filter(function(f) { return Boolean(f.selector) })[0];
1430                             if (selector_field) {
1431                                 field.path = field.name + '.' + selector_field.selector;
1432                             }
1433                         }
1434                     }
1435                     cols.add(field, true);
1436                 }
1437             );
1438         }
1439
1440         // if a column definition has a path with a wildcard, create
1441         // columns for all non-virtual fields at the specified 
1442         // position in the path.
1443         cols.expandPath = function(colSpec) {
1444
1445             var ignoreList = [];
1446             if (colSpec.ignore)
1447                 ignoreList = colSpec.ignore.split(' ');
1448
1449             var dotpath = colSpec.path.replace(/\.?\*$/,'');
1450             var class_obj;
1451             var idl_field;
1452
1453             if (colSpec.parentIdlClass) {
1454                 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1455             } else {
1456                 class_obj = egCore.idl.classes[cols.idlClass];
1457             }
1458             var idl_parent = class_obj;
1459             var old_field_label = '';
1460
1461             if (!class_obj) return;
1462
1463             //console.debug('egGrid: auto dotpath is: ' + dotpath);
1464             var path_parts = dotpath.split(/\./);
1465
1466             // find the IDL class definition for the last element in the
1467             // path before the .*
1468             // an empty path_parts means expand the root class
1469             if (path_parts) {
1470                 var old_field;
1471                 for (var path_idx in path_parts) {
1472                     old_field = idl_field;
1473
1474                     var part = path_parts[path_idx];
1475                     idl_field = class_obj.field_map[part];
1476
1477                     // unless we're at the end of the list, this field should
1478                     // link to another class.
1479                     if (idl_field && idl_field['class'] && (
1480                         idl_field.datatype == 'link' || 
1481                         idl_field.datatype == 'org_unit')) {
1482                         if (old_field_label) old_field_label += ' : ';
1483                         old_field_label += idl_field.label;
1484                         class_obj = egCore.idl.classes[idl_field['class']];
1485                         if (old_field) idl_parent = old_field;
1486                     } else {
1487                         if (path_idx < (path_parts.length - 1)) {
1488                             // we ran out of classes to hop through before
1489                             // we ran out of path components
1490                             console.error("egGrid: invalid IDL path: " + dotpath);
1491                         }
1492                     }
1493                 }
1494             }
1495
1496             if (class_obj) {
1497                 angular.forEach(class_obj.fields, function(field) {
1498
1499                     // Only show wildcard fields where we have data to show
1500                     // Virtual and un-fleshed links will not have any data.
1501                     if (field.virtual ||
1502                         (field.datatype == 'link' || field.datatype == 'org_unit') ||
1503                         ignoreList.indexOf(field.name) > -1
1504                     )
1505                         return;
1506
1507                     var col = cols.cloneFromScope(colSpec);
1508                     col.path = (dotpath ? dotpath + '.' + field.name : field.name);
1509
1510                     // log line below is very chatty.  disable until needed.
1511                     // console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_parent));
1512                     cols.add(col, false, true, 
1513                         {idl_parent : idl_parent, idl_field : field, idl_class : class_obj, field_parent_label : old_field_label });
1514                 });
1515
1516                 cols.columns = cols.columns.sort(
1517                     function(a, b) {
1518                         if (a.explicit) return -1;
1519                         if (b.explicit) return 1;
1520
1521                         if (a.idlclass && b.idlclass) {
1522                             if (a.idlclass < b.idlclass) return -1;
1523                             if (b.idlclass < a.idlclass) return 1;
1524                         }
1525
1526                         if (a.path && b.path && a.path.lastIndexOf('.') && b.path.lastIndexOf('.')) {
1527                             if (a.path.substring(0, a.path.lastIndexOf('.')) < b.path.substring(0, b.path.lastIndexOf('.'))) return -1;
1528                             if (b.path.substring(0, b.path.lastIndexOf('.')) < a.path.substring(0, a.path.lastIndexOf('.'))) return 1;
1529                         }
1530
1531                         if (a.label && b.label) {
1532                             if (a.label < b.label) return -1;
1533                             if (b.label < a.label) return 1;
1534                         }
1535
1536                         return a.name < b.name ? -1 : 1;
1537                     }
1538                 );
1539
1540
1541             } else {
1542                 console.error(
1543                     "egGrid: wildcard path does not resolve to an object: "
1544                     + dotpath);
1545             }
1546         }
1547
1548         // angular.clone(scopeObject) is not permittable.  Manually copy
1549         // the fields over that we need (so the scope object can go away).
1550         cols.cloneFromScope = function(colSpec) {
1551             return {
1552                 flesher  : colSpec.flesher,
1553                 comparator  : colSpec.comparator,
1554                 name  : colSpec.name,
1555                 label : colSpec.label,
1556                 path  : colSpec.path,
1557                 align  : colSpec.align || 'left',
1558                 flex  : Number(colSpec.flex) || 2,
1559                 sort  : Number(colSpec.sort) || 0,
1560                 required : colSpec.required,
1561                 linkpath : colSpec.linkpath,
1562                 template : colSpec.template,
1563                 visible  : colSpec.visible,
1564                 compiled : colSpec.compiled,
1565                 handlers : colSpec.handlers,
1566                 hidden   : colSpec.hidden,
1567                 datatype : colSpec.datatype,
1568                 sortable : colSpec.sortable,
1569                 nonsortable      : colSpec.nonsortable,
1570                 multisortable    : colSpec.multisortable,
1571                 nonmultisortable : colSpec.nonmultisortable,
1572                 dateformat       : colSpec.dateformat,
1573                 datecontext      : colSpec.datecontext,
1574                 datefilter      : colSpec.datefilter,
1575                 dateonlyinterval : colSpec.dateonlyinterval,
1576                 parentIdlClass   : colSpec.parentIdlClass
1577             };
1578         }
1579
1580
1581         // Add a column to the columns collection.
1582         // Columns may come from a slim eg-columns-field or 
1583         // directly from the IDL.
1584         cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1585
1586             // First added column with the specified path takes precedence.
1587             // This allows for specific definitions followed by wildcard
1588             // definitions.  If a match is found, back out.
1589             if (cols.columns.filter(function(c) {
1590                 return (c.path == colSpec.path) })[0]) {
1591                 console.debug('skipping pre-existing column ' + colSpec.path);
1592                 return;
1593             }
1594
1595             var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1596
1597             if (column.path && column.path.match(/\*$/)) 
1598                 return cols.expandPath(colSpec);
1599
1600             if (!fromExpand) column.explicit = true;
1601
1602             if (!column.name) column.name = column.path;
1603             if (!column.path) column.path = column.name;
1604
1605             if (column.visible || (!cols.defaultToHidden && !column.hidden))
1606                 column.visible = true;
1607
1608             if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1609                 column.sortable = true;
1610
1611             if (column.multisortable || 
1612                 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1613                 column.multisortable = true;
1614
1615             if (cols.defaultDateFormat && ! column.dateformat) {
1616                 column.dateformat = cols.defaultDateFormat;
1617             }
1618
1619             if (cols.defaultDateOnlyInterval && ! column.dateonlyinterval) {
1620                 column.dateonlyinterval = cols.defaultDateOnlyInterval;
1621             }
1622
1623             if (cols.defaultDateContext && ! column.datecontext) {
1624                 column.datecontext = cols.defaultDateContext;
1625             }
1626
1627             if (cols.defaultDateFilter && ! column.datefilter) {
1628                 column.datefilter = cols.defaultDateFilter;
1629             }
1630
1631             cols.columns.push(column);
1632
1633             // Track which columns are visible by default in case we
1634             // need to reset column visibility
1635             if (column.visible) 
1636                 cols.stockVisible.push(column.name);
1637
1638             if (fromIDL) return; // directly from egIDL.  nothing left to do.
1639
1640             // lookup the matching IDL field
1641             if (!idl_info && cols.idlClass) 
1642                 idl_info = cols.idlFieldFromPath(column.path);
1643
1644             if (!idl_info) {
1645                 // column is not represented within the IDL
1646                 column.adhoc = true; 
1647                 return; 
1648             }
1649
1650             column.datatype = idl_info.idl_field.datatype;
1651             
1652             if (!column.label) {
1653                 column.label = idl_info.idl_field.label || column.name;
1654             }
1655
1656             if (fromExpand && idl_info.idl_class) {
1657                 column.idlclass = '';
1658                 if (idl_info.field_parent_label && idl_info.idl_parent.label != idl_info.idl_class.label) {
1659                     column.idlclass = (idl_info.field_parent_label || idl_info.idl_parent.label || idl_info.idl_parent.name);
1660                 } else {
1661                     column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1662                 }
1663             }
1664         },
1665
1666         // finds the IDL field from the dotpath, using the columns
1667         // idlClass as the base.
1668         cols.idlFieldFromPath = function(dotpath) {
1669             var class_obj = egCore.idl.classes[cols.idlClass];
1670             if (!dotpath) return null;
1671
1672             var path_parts = dotpath.split(/\./);
1673
1674             var idl_parent;
1675             var idl_field;
1676             for (var path_idx in path_parts) {
1677                 var part = path_parts[path_idx];
1678                 idl_parent = idl_field;
1679                 idl_field = class_obj.field_map[part];
1680
1681                 if (idl_field) {
1682                     if (idl_field['class'] && (
1683                         idl_field.datatype == 'link' || 
1684                         idl_field.datatype == 'org_unit')) {
1685                         class_obj = egCore.idl.classes[idl_field['class']];
1686                     }
1687                 } else {
1688                     return null;
1689                 }
1690             }
1691
1692             return {
1693                 idl_parent: idl_parent,
1694                 idl_field : idl_field,
1695                 idl_class : class_obj
1696             };
1697         }
1698     }
1699
1700     return {
1701         instance : function(args) { return new ColumnsProvider(args) }
1702     }
1703 }])
1704
1705
1706 /*
1707  * Generic data provider template class.  This is basically an abstract
1708  * class factory service whose instances can be locally modified to 
1709  * meet the needs of each individual grid.
1710  */
1711 .factory('egGridDataProvider', 
1712            ['$q','$timeout','$filter','egCore',
1713     function($q , $timeout , $filter , egCore) {
1714
1715         function GridDataProvider(args) {
1716             var gridData = this;
1717             if (!args) args = {};
1718
1719             gridData.sort = [];
1720             gridData.get = args.get;
1721             gridData.query = args.query;
1722             gridData.idlClass = args.idlClass;
1723             gridData.columnsProvider = args.columnsProvider;
1724
1725             // Delivers a stream of array data via promise.notify()
1726             // Useful for passing an array of data to egGrid.get()
1727             // If a count is provided, the array will be trimmed to
1728             // the range defined by count and offset
1729             gridData.arrayNotifier = function(arr, offset, count) {
1730                 if (!arr || arr.length == 0) return $q.when();
1731
1732                 if (gridData.columnsProvider.clientSort
1733                     && gridData.sort
1734                     && gridData.sort.length > 0
1735                 ) {
1736                     var sorter_cache = [];
1737                     arr.sort(function(a,b) {
1738                         for (var si = 0; si < gridData.sort.length; si++) {
1739                             if (!sorter_cache[si]) { // Build sort structure on first comparison, reuse thereafter
1740                                 var field = gridData.sort[si];
1741                                 var dir = 'asc';
1742
1743                                 if (angular.isObject(field)) {
1744                                     dir = Object.values(field)[0];
1745                                     field = Object.keys(field)[0];
1746                                 }
1747
1748                                 var path = gridData.columnsProvider.findColumn(field).path || field;
1749                                 var comparator = gridData.columnsProvider.findColumn(field).comparator ||
1750                                     function (x,y) { if (x < y) return -1; if (x > y) return 1; return 0 };
1751
1752                                 sorter_cache[si] = {
1753                                     field       : path,
1754                                     dir         : dir,
1755                                     comparator  : comparator
1756                                 };
1757                             }
1758
1759                             var sc = sorter_cache[si];
1760
1761                             var af,bf;
1762
1763                             if (a._isfieldmapper || angular.isFunction(a[sc.field])) {
1764                                 try {af = a[sc.field](); bf = b[sc.field]() } catch (e) {};
1765                             } else {
1766                                 af = a[sc.field]; bf = b[sc.field];
1767                             }
1768                             if (af === undefined && sc.field.indexOf('.') > -1) { // assume an object, not flat path
1769                                 var parts = sc.field.split('.');
1770                                 af = a;
1771                                 bf = b;
1772                                 angular.forEach(parts, function (p) {
1773                                     if (af) {
1774                                         if (af._isfieldmapper || angular.isFunction(af[p])) af = af[p]();
1775                                         else af = af[p];
1776                                     }
1777                                     if (bf) {
1778                                         if (bf._isfieldmapper || angular.isFunction(bf[p])) bf = bf[p]();
1779                                         else bf = bf[p];
1780                                     }
1781                                 });
1782                             }
1783
1784                             if (af === undefined) af = null;
1785                             if (bf === undefined) bf = null;
1786
1787                             if (af === null && bf !== null) return 1;
1788                             if (bf === null && af !== null) return -1;
1789
1790                             if (!(bf === null && af === null)) {
1791                                 var partial = sc.comparator(af,bf);
1792                                 if (partial) {
1793                                     if (sc.dir == 'desc') {
1794                                         if (partial > 0) return -1;
1795                                         return 1;
1796                                     }
1797                                     return partial;
1798                                 }
1799                             }
1800                         }
1801
1802                         return 0;
1803                     });
1804                 }
1805
1806                 if (count) arr = arr.slice(offset, offset + count);
1807                 var def = $q.defer();
1808                 // promise notifications are only witnessed when delivered
1809                 // after the caller has his hands on the promise object
1810                 $timeout(function() {
1811                     angular.forEach(arr, def.notify);
1812                     def.resolve();
1813                 });
1814                 return def.promise;
1815             }
1816
1817             // Calls the grid refresh function.  Once instantiated, the
1818             // grid will replace this function with it's own refresh()
1819             gridData.refresh = function(noReset) { }
1820
1821             if (!gridData.get) {
1822                 // returns a promise whose notify() delivers items
1823                 gridData.get = function(index, count) {
1824                     console.error("egGridDataProvider.get() not implemented");
1825                 }
1826             }
1827
1828             // attempts a flat field lookup first.  If the column is not
1829             // found on the top-level object, attempts a nested lookup
1830             // TODO: consider a caching layer to speed up template 
1831             // rendering, particularly for nested objects?
1832             gridData.itemFieldValue = function(item, column) {
1833                 var val;
1834                 if (column.name in item) {
1835                     if (typeof item[column.name] == 'function') {
1836                         val = item[column.name]();
1837                     } else {
1838                         val = item[column.name];
1839                     }
1840                 } else {
1841                     val = gridData.nestedItemFieldValue(item, column);
1842                 }
1843
1844                 return val;
1845             }
1846
1847             // TODO: deprecate me
1848             gridData.flatItemFieldValue = function(item, column) {
1849                 console.warn('gridData.flatItemFieldValue deprecated; '
1850                     + 'leave provider.itemFieldValue unset');
1851                 return item[column.name];
1852             }
1853
1854             // given an object and a dot-separated path to a field,
1855             // extract the value of the field.  The path can refer
1856             // to function names or object attributes.  If the final
1857             // value is an IDL field, run the value through its
1858             // corresponding output filter.
1859             gridData.nestedItemFieldValue = function(obj, column) {
1860                 item = obj; // keep a copy around
1861
1862                 if (obj === null || obj === undefined || obj === '') return '';
1863                 if (!column.path) return obj;
1864
1865                 var idl_field;
1866                 var parts = column.path.split('.');
1867
1868                 angular.forEach(parts, function(step, idx) {
1869                     // object is not fleshed to the expected extent
1870                     if (typeof obj != 'object') {
1871                         if (typeof obj != 'undefined' && column.flesher) {
1872                             obj = column.flesher(obj, column, item);
1873                         } else {
1874                             obj = '';
1875                             return;
1876                         }
1877                     }
1878
1879                     if (!obj) return '';
1880
1881                     var cls = obj.classname;
1882                     if (cls && (class_obj = egCore.idl.classes[cls])) {
1883                         idl_field = class_obj.field_map[step];
1884                         obj = obj[step] ? obj[step]() : '';
1885                     } else {
1886                         if (angular.isFunction(obj[step])) {
1887                             obj = obj[step]();
1888                         } else {
1889                             obj = obj[step];
1890                         }
1891                     }
1892                 });
1893
1894                 // We found a nested IDL object which may or may not have 
1895                 // been configured as a top-level column.  Grab the datatype.
1896                 if (idl_field && !column.datatype) 
1897                     column.datatype = idl_field.datatype;
1898
1899                 if (obj === null || obj === undefined || obj === '') return '';
1900                 return obj;
1901             }
1902         }
1903
1904         return {
1905             instance : function(args) {
1906                 return new GridDataProvider(args);
1907             }
1908         };
1909     }
1910 ])
1911
1912
1913 // Factory service for egGridDataManager instances, which are
1914 // responsible for collecting flattened grid data.
1915 .factory('egGridFlatDataProvider', 
1916            ['$q','egCore','egGridDataProvider',
1917     function($q , egCore , egGridDataProvider) {
1918
1919         return {
1920             instance : function(args) {
1921                 var provider = egGridDataProvider.instance(args);
1922
1923                 provider.get = function(offset, count) {
1924
1925                     // no query means no call
1926                     if (!provider.query || 
1927                             angular.equals(provider.query, {})) 
1928                         return $q.when();
1929
1930                     // find all of the currently visible columns
1931                     var queryFields = {}
1932                     angular.forEach(provider.columnsProvider.columns, 
1933                         function(col) {
1934                             // only query IDL-tracked columns
1935                             if (!col.adhoc && col.name && col.path && (col.required || col.visible))
1936                                 queryFields[col.name] = col.path;
1937                         }
1938                     );
1939
1940                     return egCore.net.request(
1941                         'open-ils.fielder',
1942                         'open-ils.fielder.flattened_search',
1943                         egCore.auth.token(), provider.idlClass, 
1944                         queryFields, provider.query,
1945                         {   sort : provider.sort,
1946                             limit : count,
1947                             offset : offset
1948                         }
1949                     );
1950                 }
1951                 //provider.itemFieldValue = provider.flatItemFieldValue;
1952                 return provider;
1953             }
1954         };
1955     }
1956 ])
1957
1958 .directive('egGridColumnDragSource', function() {
1959     return {
1960         restrict : 'A',
1961         require : '^egGrid',
1962         link : function(scope, element, attrs, egGridCtrl) {
1963             angular.element(element).attr('draggable', 'true');
1964
1965             element.bind('dragstart', function(e) {
1966                 egGridCtrl.dragColumn = attrs.column;
1967                 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1968                 egGridCtrl.colResizeDir = 0;
1969
1970                 if (egGridCtrl.dragType == 'move') {
1971                     // style the column getting moved
1972                     angular.element(e.target).addClass(
1973                         'eg-grid-column-move-handle-active');
1974                 }
1975             });
1976
1977             element.bind('dragend', function(e) {
1978                 if (egGridCtrl.dragType == 'move') {
1979                     angular.element(e.target).removeClass(
1980                         'eg-grid-column-move-handle-active');
1981                 }
1982             });
1983         }
1984     };
1985 })
1986
1987 .directive('egGridColumnDragDest', function() {
1988     return {
1989         restrict : 'A',
1990         require : '^egGrid',
1991         link : function(scope, element, attrs, egGridCtrl) {
1992
1993             element.bind('dragover', function(e) { // required for drop
1994                 e.stopPropagation();
1995                 e.preventDefault();
1996                 e.dataTransfer.dropEffect = 'move';
1997
1998                 if (egGridCtrl.colResizeDir == 0) return; // move
1999
2000                 var cols = egGridCtrl.columnsProvider;
2001                 var srcCol = egGridCtrl.dragColumn;
2002                 var srcColIdx = cols.indexOf(srcCol);
2003
2004                 if (egGridCtrl.colResizeDir == -1) {
2005                     if (cols.indexOf(attrs.column) <= srcColIdx) {
2006                         egGridCtrl.modifyColumnFlex(
2007                             egGridCtrl.columnsProvider.findColumn(
2008                                 egGridCtrl.dragColumn), -1);
2009                         if (cols.columns[srcColIdx+1]) {
2010                             // source column shrinks by one, column to the
2011                             // right grows by one.
2012                             egGridCtrl.modifyColumnFlex(
2013                                 cols.columns[srcColIdx+1], 1);
2014                         }
2015                         scope.$apply();
2016                     }
2017                 } else {
2018                     if (cols.indexOf(attrs.column) > srcColIdx) {
2019                         egGridCtrl.modifyColumnFlex( 
2020                             egGridCtrl.columnsProvider.findColumn(
2021                                 egGridCtrl.dragColumn), 1);
2022                         if (cols.columns[srcColIdx+1]) {
2023                             // source column grows by one, column to the 
2024                             // right grows by one.
2025                             egGridCtrl.modifyColumnFlex(
2026                                 cols.columns[srcColIdx+1], -1);
2027                         }
2028
2029                         scope.$apply();
2030                     }
2031                 }
2032             });
2033
2034             element.bind('dragenter', function(e) {
2035                 e.stopPropagation();
2036                 e.preventDefault();
2037                 if (egGridCtrl.dragType == 'move') {
2038                     angular.element(e.target).addClass('eg-grid-col-hover');
2039                 } else {
2040                     // resize grips are on the right side of each column.
2041                     // dragenter will either occur on the source column 
2042                     // (dragging left) or the column to the right.
2043                     if (egGridCtrl.colResizeDir == 0) {
2044                         if (egGridCtrl.dragColumn == attrs.column) {
2045                             egGridCtrl.colResizeDir = -1; // west
2046                         } else {
2047                             egGridCtrl.colResizeDir = 1; // east
2048                         }
2049                     }
2050                 }
2051             });
2052
2053             element.bind('dragleave', function(e) {
2054                 e.stopPropagation();
2055                 e.preventDefault();
2056                 if (egGridCtrl.dragType == 'move') {
2057                     angular.element(e.target).removeClass('eg-grid-col-hover');
2058                 }
2059             });
2060
2061             element.bind('drop', function(e) {
2062                 e.stopPropagation();
2063                 e.preventDefault();
2064                 egGridCtrl.colResizeDir = 0;
2065                 if (egGridCtrl.dragType == 'move') {
2066                     angular.element(e.target).removeClass('eg-grid-col-hover');
2067                     egGridCtrl.onColumnDrop(attrs.column); // move the column
2068                 }
2069             });
2070         }
2071     };
2072 })
2073  
2074 .directive('egGridMenuItem', function() {
2075     return {
2076         restrict : 'AE',
2077         require : '^egGrid',
2078         scope : {
2079             label : '@',  
2080             checkbox : '@',  
2081             checked : '=',  
2082             standalone : '=',  
2083             handler : '=', // onclick handler function
2084             divider : '=', // if true, show a divider only
2085             handlerData : '=', // if set, passed as second argument to handler
2086             disabled : '=', // function
2087             hidden : '=' // function
2088         },
2089         link : function(scope, element, attrs, egGridCtrl) {
2090             egGridCtrl.addMenuItem({
2091                 checkbox : scope.checkbox,
2092                 checked : scope.checked ? true : false,
2093                 label : scope.label,
2094                 standalone : scope.standalone ? true : false,
2095                 handler : scope.handler,
2096                 divider : scope.divider,
2097                 disabled : scope.disabled,
2098                 hidden : scope.hidden,
2099                 handlerData : scope.handlerData
2100             });
2101             scope.$destroy();
2102         }
2103     };
2104 })
2105
2106 /* https://stackoverflow.com/questions/17343696/adding-an-ng-click-event-inside-a-filter/17344875#17344875 */
2107 .directive('compile', ['$compile', function ($compile) {
2108     return function(scope, element, attrs) {
2109       // pass through column defs from grid cell's scope
2110       scope.col = scope.$parent.col;
2111       scope.$watch(
2112         function(scope) {
2113           // watch the 'compile' expression for changes
2114           return scope.$eval(attrs.compile);
2115         },
2116         function(value) {
2117           // when the 'compile' expression changes
2118           // assign it into the current DOM
2119           element.html(value);
2120
2121           // compile the new DOM and link it to the current
2122           // scope.
2123           // NOTE: we only compile .childNodes so that
2124           // we don't get into infinite loop compiling ourselves
2125           $compile(element.contents())(scope);
2126         }
2127     );
2128   };
2129 }])
2130
2131
2132
2133 /**
2134  * Translates bare IDL object values into display values.
2135  * 1. Passes dates through the angular date filter
2136  * 2. Translates bools to Booleans so the browser can display translated 
2137  *    value.  (Though we could manually translate instead..)
2138  * Others likely to follow...
2139  */
2140 .filter('egGridValueFilter', ['$filter','egCore', function($filter,egCore) {
2141     function traversePath(obj,path) {
2142         var list = path.split('.');
2143         for (var part in path) {
2144             if (obj[path]) obj = obj[path]
2145             else return null;
2146         }
2147         return obj;
2148     }
2149
2150     var GVF = function(value, column, item) {
2151         switch(column.datatype) {
2152             case 'bool':
2153                 switch(value) {
2154                     // Browser will translate true/false for us
2155                     case 't' : 
2156                     case '1' :  // legacy
2157                     case true:
2158                         return ''+true;
2159                     case 'f' : 
2160                     case '0' :  // legacy
2161                     case false:
2162                         return ''+false;
2163                     // value may be null,  '', etc.
2164                     default : return '';
2165                 }
2166             case 'timestamp':
2167                 var interval = angular.isFunction(item[column.dateonlyinterval])
2168                     ? item[column.dateonlyinterval]()
2169                     : item[column.dateonlyinterval];
2170
2171                 if (column.dateonlyinterval && !interval) // try it as a dotted path
2172                     interval = traversePath(item, column.dateonlyinterval);
2173
2174                 var context = angular.isFunction(item[column.datecontext])
2175                     ? item[column.datecontext]()
2176                     : item[column.datecontext];
2177
2178                 if (column.datecontext && !context) // try it as a dotted path
2179                     context = traversePath(item, column.datecontext);
2180
2181                 var date_filter = column.datefilter || 'egOrgDateInContext';
2182
2183                 return $filter(date_filter)(value, column.dateformat, context, interval);
2184             case 'money':
2185                 return $filter('currency')(value);
2186             default:
2187                 return value;
2188         }
2189     };
2190
2191     GVF.$stateful = true;
2192     return GVF;
2193 }]);
2194