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