# Server-Side Row Model - Column Filtering

Canonical page: https://www.adaptabletools.com/docs/dev-guide-row-models-server-filtering

- Column Filters need to be evaluated remotely when using the Server-Side Row Model
- AdapTable provides functions that help developers retrieve the latest Filter state (to pass in to the server)
- Custom Filters, In Filter values, and the set of available operators can all be tailored for a remote implementation

When using the Server-Side Row Model, AG Grid **will not perform any filtering**.

- [Quick Search](https://www.adaptabletools.com/docs/handbook-quick-search/index.md) works fully in Server-Side Row Model, both for data already in the Grid and new data as it is fetched
- However [Quick Search as Filter](https://www.adaptabletools.com/docs/handbook-quick-search-as-filter/index.md) will not work (unless you implement it yourself)

Instead AG Grid hands off those tasks to developer to perform on the server.

When using the Server-Side Row Model, it is the developer's responsibility to perform the actual filtering on the server

In practice this requires developers to provide a server equivalent of [AdapTableQL](https://www.adaptabletools.com/docs/adaptable-ql-expression/index.md) to evaluate any [Column Filters](https://www.adaptabletools.com/docs/handbook-column-filter/index.md).

- [Grid Filter](https://www.adaptabletools.com/docs/dev-guide-row-models-server-grid-filter/index.md) covers evaluating the Grid Filter on the server
- [AdapTableQL Server Evaluation](https://www.adaptabletools.com/docs/adaptable-server-evaluation/index.md) provides instructions for managing the complexity and scope of Expressions

## Getting Filter State

When using the Server-Side Row Model, you need to fetch the current filter (and sort) state from AdapTable inside the `getRows` function.

The [Grid Filter Applied](https://www.adaptabletools.com/docs/technical-reference-filter/index.md) and [Column Filter Applied](https://www.adaptabletools.com/docs/technical-reference-filter/index.md) Events still fire, but are rarely subscribed to when using the SSRM

This is most easily done through the `getAdaptableFilterState` function in the [State API](https://www.adaptabletools.com/docs/technical-reference-adaptable-state/index.md#state-api) section of Adaptable API.

It returns an [`AdaptableFilterState`](https://www.adaptabletools.com/docs/reference/adaptablefilterstate.md) object defined as follows:

| Property | Type | Description |
| --- | --- | --- |
| [columnFilters](https://www.adaptabletools.com/docs/reference/adaptablefilterstate.md#columnfilters) | [`ColumnFilter`](https://www.adaptabletools.com/docs/reference/columnfilter.md)`[] \| undefined` | Currently applied Column Filters |
| [gridFilter](https://www.adaptabletools.com/docs/reference/adaptablefilterstate.md#gridfilter) | `string \| undefined` | Current Grid Filter |
| [gridFilterAST](https://www.adaptabletools.com/docs/reference/adaptablefilterstate.md#gridfilterast) | `any` | AST for Current Grid Filter |

## Columns Filters

[Column Filters](https://www.adaptabletools.com/docs/handbook-column-filter/index.md) can still be set and applied when using the Server-Side Row Model.

But instead of the Filters being evaluated by AdapTable, they are evaluated by developers on the server.

This can also include [Custom Filters](https://www.adaptabletools.com/docs/handbook-column-filter-custom-filters/index.md), which will also be evaluated remotely in a bespoke implementation

### In Filter Values

AdapTable provides an [In Filter](https://www.adaptabletools.com/docs/handbook-column-filter-in-filter/index.md), which allows users to select from a list of values for the Column.

By default, AdapTable simply lists all distinct values currently visible in the Grid's data source for the Column.

This is fine when using the Client-Side Row Model - as all data has been loaded - but can be unsatisfactory for the Server-Side Row Model, since it can result in a unnecessarily reduced list of values.

For this reason it is common when using the SSRM to implement the `customInFilterValues` property in [Filter Options](https://www.adaptabletools.com/docs/technical-reference-filter/index.md) in order to provide a fuller list of values.

- This is often coupled with [Suppressing Search in the In Filter](https://www.adaptabletools.com/docs/handbook-column-filter-in-filter/index.md#suppressing-results-search) so that the search can be evaluated on the Server
- Another common practice is [Manually Applying Filters](https://www.adaptabletools.com/docs/handbook-column-filter-manually-applying/index.md) so just one server invocation is made with all selected values

**Example: SSRM - Column Filtering**

Server-Side Row Model: Applying Column Filters

- The example shows how AdapTable Column Filters can still be used while using Server-Side Row Model:
- We convert current Column Filter and Grid Filter Expressions to AST and pass that to our mock server to evaluate
- We add a [Custom Filter](https://www.adaptabletools.com/docs/handbook-column-filter-custom-filters/index.md) called `Superstar` on the `Athlete` column - and which also gets evaluated on the mock server (using rule: `gold > 2 OR (gold + silver + bronze) > 3`)
- We also provide an implementation for `customInFilterValues` to control which values are displayed in the In Filter - this is also handled on our mock server

- Type `3` into the `Gold` Filter Bar and note how new data is fetched from the server that matches the Filter
- Run the `Superstar` Custom Filter on the Athlete column and note how our mock server evaluates it and returns the correct data
- Run the `In` Filter on the Athlete column and note how the server returns details of all athletes on the server (not just those already loaded)

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts
  gridOptions.ts
  index.ts             [template]
  onAdaptableReady.ts
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {
  AdaptableOptions,
  CustomInFilterValuesContext,
  DefaultFilterExpressionContext,
  GlobalExpressionFunctionAvailabilityContext,
} from '@adaptabletools/adaptable';

const API_BASE: string = process.env.NEXT_PUBLIC_ATHLETES_API_URL!;

export const getDistinctColumnValues = async (
  columnId: string
): Promise<{value: string}[]> => {
  const jsonResponse = await fetch(
    `${API_BASE}/permitted-values?columnId=${columnId}`
  );
  return jsonResponse.json();
};

export const adaptableOptions: AdaptableOptions = {
  primaryKey: 'id',
  adaptableId: 'SSRM - Column Filtering',
  expressionOptions: {
    customStandardFunctions: {
      // The custom filter is handled on the server.
      // It returns `gold > 2 OR (gold + silver + bronze) > 3`.
      SUPERSTAR: {
        label: 'Superstar',
        returnType: 'boolean',
        operands: [['text']],
        handler: () => true,
        isAvailable: ['ColumnFilter'],
      },
    },
    isExpressionFunctionAvailable: (
      context: GlobalExpressionFunctionAvailabilityContext
    ) => {
      if (
        context.functionName === 'SUPERSTAR' &&
        context.column &&
        context.column.columnId !== 'athlete'
      ) {
        return false;
      }
      return context.defaultAvailability;
    },
  },
  filterOptions: {
    customInFilterValues: async (context: CustomInFilterValuesContext) => {
      const columnId = context.column.columnId;
      const allColumnValues = await getDistinctColumnValues(columnId);

      const inFilterValues = allColumnValues.map(item => ({
        label: item.value,
        value: item.value,
      }));
      return {
        values: inFilterValues,
      };
    },
    columnFilterOptions: {
      defaultTextColumnFilter: (context: DefaultFilterExpressionContext) => {
        return context.column.columnId == 'athlete' ? 'IN' : 'CONTAINS';
      },
    },
  },
  initialState: {
    Dashboard: {
      Tabs: [
        {
          Name: 'Main',
          Toolbars: ['SystemStatus'],
        },
      ],
    },
    Theme: {
      CurrentTheme: 'dark',
    },
    Layout: {
      CurrentLayout: 'SSRM Layout',
      Layouts: [
        {
          Name: 'SSRM Layout',
          TableColumns: [
            'athlete',
            'gold',
            'silver',
            'bronze',
            'country',
            'sport',
            'year',
          ],
          ColumnSizing: {
            athlete: {Width: 175},
            bronze: {Width: 100},
            country: {Width: 125},
            gold: {Width: 100},
            silver: {Width: 100},
            sport: {Width: 175},
            year: {Width: 115},
          },
        },
      ],
    },
  },
};
```

**`src/onAdaptableReady.ts`**

```ts
import {AdaptableReadyInfo, AdaptableApi} from '@adaptabletools/adaptable';
import {
  ColDef,
  GridApi,
  IServerSideDatasource,
  IServerSideGetRowsParams,
  IServerSideGetRowsRequest,
} from 'ag-grid-enterprise';

export const onAdaptableReady = ({
  adaptableApi,
  agGridApi,
}: AdaptableReadyInfo) => {
  agGridApi.setGridOption(
    'serverSideDatasource',
    createDataSource(adaptableApi)
  );
};

const API_BASE: string = process.env.NEXT_PUBLIC_ATHLETES_API_URL!;

// v24 Column Filters are Expressions. The athletes mock server evaluates
// both Grid Filter and Column Filters from `gridFilterAST`.
function rewriteAutoGroupColumn(
  node: unknown,
  groupedColumnId?: string
): unknown {
  if (!groupedColumnId || node == null || typeof node !== 'object') {
    return node;
  }
  if (Array.isArray(node)) {
    return node.map(item => rewriteAutoGroupColumn(item, groupedColumnId));
  }
  const astNode = node as {type?: string; args?: unknown[]};
  if (astNode.type === 'COL' && astNode.args?.[0] === 'ag-Grid-AutoColumn') {
    return {
      ...astNode,
      args: [groupedColumnId, ...astNode.args.slice(1)],
    };
  }
  if (!astNode.args) {
    return node;
  }
  return {
    ...astNode,
    args: astNode.args.map(arg =>
      rewriteAutoGroupColumn(arg, groupedColumnId)
    ),
  };
}

function appendExpressionAst(
  astNodes: unknown[],
  ast: unknown,
  groupedColumnId?: string
) {
  if (ast == null) {
    return;
  }
  const nodes = Array.isArray(ast) ? ast : [ast];
  for (const node of nodes) {
    astNodes.push(rewriteAutoGroupColumn(node, groupedColumnId));
  }
}

function toServerFilterFields(
  adaptableApi: AdaptableApi,
  groupedColumnId?: string
) {
  const filterState = adaptableApi.stateApi.getAdaptableFilterState();
  const astNodes: unknown[] = [];
  appendExpressionAst(astNodes, filterState.gridFilterAST, groupedColumnId);
  for (const columnFilter of filterState.columnFilters ?? []) {
    if (!columnFilter.Expression) {
      continue;
    }
    appendExpressionAst(
      astNodes,
      adaptableApi.expressionApi.getASTForExpression(columnFilter.Expression),
      groupedColumnId
    );
  }
  return {
    adaptableFilters: [],
    gridFilterAST: astNodes.length ? astNodes : undefined,
  };
}

function createDataSource(adaptableApi: AdaptableApi): IServerSideDatasource {
  return {
    getRows(params: IServerSideGetRowsParams) {
      const getRowsRequest: IServerSideGetRowsRequest = params.request;
      const adaptableSortState = adaptableApi.stateApi.getAdaptableSortState();
      const groupedColumn = getRowsRequest.rowGroupCols?.[0];
      const serverFilters = toServerFilterFields(
        adaptableApi,
        groupedColumn?.field ?? groupedColumn?.id
      );

      const sortModel = getRowsRequest.sortModel.map(sort => {
        const customSort = adaptableSortState.customSorts.find(
          customSort => customSort.ColumnId === sort.colId
        );
        if (customSort) {
          return {
            ...sort,
            sortedValues: customSort.SortedValues,
          };
        }
        return sort;
      });

      const request = {
        ...getRowsRequest,
        sortModel,
        ...serverFilters,
        includeSQL: true,
      };
      console.log('request to server', request);

      fetch(API_BASE, {
        method: 'post',
        body: JSON.stringify(request),
        headers: {'Content-Type': 'application/json; charset=utf-8'},
      })
        .then(httpResponse => httpResponse.json())
        .then(response => {
          params.success({
            rowData: response.rows,
            rowCount: response.lastRow ?? 0,
          });

          if (response.pivotFields?.length) {
            addPivotColumnDefs(response, params.api);
          } else {
            if (!adaptableApi.layoutApi.isCurrentLayoutPivot()) {
              if (params.api.getPivotResultColumns() != null) {
                params.api.setPivotResultColumns(null);
              }
            }
          }

          adaptableApi.systemStatusApi.setInfoSystemStatus(
            `SQL: ${response.sql.slice(0, 40)}`,
            response.sql
          );
        })
        .catch(error => {
          params.fail();
        });
    },
  };
}

function addPivotColumnDefs(response: any, agGridApi: GridApi) {
  const existingPivotColDefs = agGridApi.getPivotResultColumns();
  if (existingPivotColDefs && existingPivotColDefs.length > 0) {
    return;
  }

  const pivotColDefs: ColDef[] = response.pivotFields.map(function (
    field: any,
    index: number
  ) {
    const [_key, value] = Object.entries(field)[0];
    const valueStr = `${value}`;
    return {
      headerName: valueStr,
      field: valueStr,
      filter: false,
      colId: `${Date.now()}_${index}`,
      cellDataType: 'number',
    };
  });

  agGridApi.setPivotResultColumns(pivotColDefs);
}
```

**`src/gridOptions.ts`**

```ts
import {GridOptions, themeBalham} from 'ag-grid-enterprise';

import {columnDefs} from './columnDefs';

export const gridOptions: GridOptions = {
  theme: themeBalham,
  defaultColDef: {
    sortable: true,
    filter: true,
    floatingFilter: true,
    enableRowGroup: true,
  },
  rowModelType: 'serverSide',
  columnDefs: columnDefs,
  sideBar: ['adaptable', 'columns', 'filters'],
};
```

**`src/columnDefs.ts`**

```ts
import {ColDef} from 'ag-grid-enterprise';

export const columnDefs: ColDef[] = [
  {field: 'id', hide: true, cellDataType: 'text'},
  {
    field: 'athlete',
    cellDataType: 'text',
    enableRowGroup: true,
    resizable: true,
  },
  {
    field: 'country',
    cellDataType: 'text',
    enableRowGroup: true,
    resizable: true,
  },
  {
    field: 'sport',
    cellDataType: 'text',
    enableRowGroup: true,
    resizable: true,
  },
  {
    field: 'year',
    cellDataType: 'number',
    enableRowGroup: true,
    resizable: true,
  },
  {
    field: 'gold',
    aggFunc: 'sum',
    cellDataType: 'number',
    enableValue: true,
    resizable: true,
  },
  {
    field: 'silver',
    aggFunc: 'sum',
    cellDataType: 'number',
    enableValue: true,
    resizable: true,
  },
  {
    field: 'bronze',
    aggFunc: 'sum',
    cellDataType: 'number',
    enableValue: true,
    resizable: true,
  },
];
```

### Limiting Available Operators

By default AdapTable offers every boolean [Expression Function](https://www.adaptabletools.com/docs/adaptable-ql-expression-functions/index.md) (operator) relevant to each Column's Data Type.

This means a bespoke server implementation needs to translate **every** operator into something meaningful.

Accordingly, AdapTable allows developers to [limit which operators are available](https://www.adaptabletools.com/docs/handbook-column-filter-system-filters/index.md) in order to make the server implementation more manageable.

This can be done using the `isExpressionFunctionAvailable` function in [Expression Options](https://www.adaptabletools.com/docs/technical-reference-expression/index.md) and can be set globally, per Module, or per Column.

**Example: SSRM - Limited Operators**

Server-Side Row Model: Limiting Column Filter Operators

- This demo uses `isExpressionFunctionAvailable` to offer only a small, server-friendly set of Column Filter operators:
  - `EQ`, `NEQ`, `GT`, `GTE`, `LT`, `LTE`, `IN`, `CONTAINS`, `IS_BLANK`
- Everything else (`REGEX`, `BETWEEN`, `STARTS_WITH`, date predicates, etc.) is hidden, so the server only needs to translate this subset

- Open the operator dropdown in the `Gold` Filter Bar and note the reduced list
- Open the `Athlete` Filter Bar dropdown and see the same subset (only operators relevant to text Columns appear)

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts
  gridOptions.ts
  index.ts             [template]
  onAdaptableReady.ts
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {
  AdaptableOptions,
  CustomInFilterValuesContext,
  GlobalExpressionFunctionAvailabilityContext,
} from '@adaptabletools/adaptable';

const API_BASE: string = process.env.NEXT_PUBLIC_ATHLETES_API_URL!;

// A small, server-friendly operator set. COL / AND / OR stay available via
// defaultAvailability (they are not offered in the Column Filter dropdown).
const columnFilterOperators = [
  'EQ',
  'NEQ',
  'GT',
  'GTE',
  'LT',
  'LTE',
  'IN',
  'CONTAINS',
  'IS_BLANK',
];

export const getDistinctColumnValues = async (
  columnId: string
): Promise<{value: string}[]> => {
  const jsonResponse = await fetch(
    `${API_BASE}/permitted-values?columnId=${columnId}`
  );
  return jsonResponse.json();
};

export const adaptableOptions: AdaptableOptions = {
  primaryKey: 'id',
  adaptableId: 'SSRM - Limited Operators',
  expressionOptions: {
    isExpressionFunctionAvailable: (
      context: GlobalExpressionFunctionAvailabilityContext
    ) => {
      if (context.module === 'ColumnFilter' && context.column) {
        return columnFilterOperators.includes(context.functionName);
      }
      return context.defaultAvailability;
    },
  },
  filterOptions: {
    customInFilterValues: async (context: CustomInFilterValuesContext) => {
      const columnId = context.column.columnId;
      const allColumnValues = await getDistinctColumnValues(columnId);

      const inFilterValues = allColumnValues.map(item => ({
        label: item.value,
        value: item.value,
      }));
      return {
        values: inFilterValues,
      };
    },
  },
  initialState: {
    Dashboard: {
      Tabs: [
        {
          Name: 'Main',
          Toolbars: ['SystemStatus'],
        },
      ],
    },
    Theme: {
      CurrentTheme: 'dark',
    },
    Layout: {
      CurrentLayout: 'SSRM Layout',
      Layouts: [
        {
          Name: 'SSRM Layout',
          TableColumns: [
            'athlete',
            'gold',
            'silver',
            'bronze',
            'country',
            'sport',
            'year',
          ],
          ColumnSizing: {
            athlete: {Width: 175},
            bronze: {Width: 100},
            country: {Width: 125},
            gold: {Width: 100},
            silver: {Width: 100},
            sport: {Width: 175},
            year: {Width: 115},
          },
        },
      ],
    },
  },
};
```

**`src/onAdaptableReady.ts`**

```ts
import {AdaptableReadyInfo, AdaptableApi} from '@adaptabletools/adaptable';
import {
  ColDef,
  GridApi,
  IServerSideDatasource,
  IServerSideGetRowsParams,
  IServerSideGetRowsRequest,
} from 'ag-grid-enterprise';

export const onAdaptableReady = ({
  adaptableApi,
  agGridApi,
}: AdaptableReadyInfo) => {
  agGridApi.setGridOption(
    'serverSideDatasource',
    createDataSource(adaptableApi)
  );
};

const API_BASE: string = process.env.NEXT_PUBLIC_ATHLETES_API_URL!;

// v24 Column Filters are Expressions. The athletes mock server evaluates
// both Grid Filter and Column Filters from `gridFilterAST`.
function rewriteAutoGroupColumn(
  node: unknown,
  groupedColumnId?: string
): unknown {
  if (!groupedColumnId || node == null || typeof node !== 'object') {
    return node;
  }
  if (Array.isArray(node)) {
    return node.map(item => rewriteAutoGroupColumn(item, groupedColumnId));
  }
  const astNode = node as {type?: string; args?: unknown[]};
  if (astNode.type === 'COL' && astNode.args?.[0] === 'ag-Grid-AutoColumn') {
    return {
      ...astNode,
      args: [groupedColumnId, ...astNode.args.slice(1)],
    };
  }
  if (!astNode.args) {
    return node;
  }
  return {
    ...astNode,
    args: astNode.args.map(arg =>
      rewriteAutoGroupColumn(arg, groupedColumnId)
    ),
  };
}

function appendExpressionAst(
  astNodes: unknown[],
  ast: unknown,
  groupedColumnId?: string
) {
  if (ast == null) {
    return;
  }
  const nodes = Array.isArray(ast) ? ast : [ast];
  for (const node of nodes) {
    astNodes.push(rewriteAutoGroupColumn(node, groupedColumnId));
  }
}

function toServerFilterFields(
  adaptableApi: AdaptableApi,
  groupedColumnId?: string
) {
  const filterState = adaptableApi.stateApi.getAdaptableFilterState();
  const astNodes: unknown[] = [];
  appendExpressionAst(astNodes, filterState.gridFilterAST, groupedColumnId);
  for (const columnFilter of filterState.columnFilters ?? []) {
    if (!columnFilter.Expression) {
      continue;
    }
    appendExpressionAst(
      astNodes,
      adaptableApi.expressionApi.getASTForExpression(columnFilter.Expression),
      groupedColumnId
    );
  }
  return {
    adaptableFilters: [],
    gridFilterAST: astNodes.length ? astNodes : undefined,
  };
}

function createDataSource(adaptableApi: AdaptableApi): IServerSideDatasource {
  return {
    getRows(params: IServerSideGetRowsParams) {
      const getRowsRequest: IServerSideGetRowsRequest = params.request;
      const adaptableSortState = adaptableApi.stateApi.getAdaptableSortState();
      const groupedColumn = getRowsRequest.rowGroupCols?.[0];
      const serverFilters = toServerFilterFields(
        adaptableApi,
        groupedColumn?.field ?? groupedColumn?.id
      );

      const sortModel = getRowsRequest.sortModel.map(sort => {
        const customSort = adaptableSortState.customSorts.find(
          customSort => customSort.ColumnId === sort.colId
        );
        if (customSort) {
          return {
            ...sort,
            sortedValues: customSort.SortedValues,
          };
        }
        return sort;
      });

      const request = {
        ...getRowsRequest,
        sortModel,
        ...serverFilters,
        includeSQL: true,
      };
      console.log('request to server', request);

      fetch(API_BASE, {
        method: 'post',
        body: JSON.stringify(request),
        headers: {'Content-Type': 'application/json; charset=utf-8'},
      })
        .then(httpResponse => httpResponse.json())
        .then(response => {
          params.success({
            rowData: response.rows,
            rowCount: response.lastRow ?? 0,
          });

          if (response.pivotFields?.length) {
            addPivotColumnDefs(response, params.api);
          } else {
            if (!adaptableApi.layoutApi.isCurrentLayoutPivot()) {
              if (params.api.getPivotResultColumns() != null) {
                params.api.setPivotResultColumns(null);
              }
            }
          }

          adaptableApi.systemStatusApi.setInfoSystemStatus(
            `SQL: ${response.sql.slice(0, 40)}`,
            response.sql
          );
        })
        .catch(error => {
          params.fail();
        });
    },
  };
}

function addPivotColumnDefs(response: any, agGridApi: GridApi) {
  const existingPivotColDefs = agGridApi.getPivotResultColumns();
  if (existingPivotColDefs && existingPivotColDefs.length > 0) {
    return;
  }

  const pivotColDefs: ColDef[] = response.pivotFields.map(function (
    field: any,
    index: number
  ) {
    const [_key, value] = Object.entries(field)[0];
    const valueStr = `${value}`;
    return {
      headerName: valueStr,
      field: valueStr,
      filter: false,
      colId: `${Date.now()}_${index}`,
      cellDataType: 'number',
    };
  });

  agGridApi.setPivotResultColumns(pivotColDefs);
}
```

**`src/gridOptions.ts`**

```ts
import {GridOptions, themeBalham} from 'ag-grid-enterprise';

import {columnDefs} from './columnDefs';

export const gridOptions: GridOptions = {
  theme: themeBalham,
  defaultColDef: {
    sortable: true,
    filter: true,
    floatingFilter: true,
    enableRowGroup: true,
  },
  rowModelType: 'serverSide',
  columnDefs: columnDefs,
  sideBar: ['adaptable', 'columns', 'filters'],
};
```

**`src/columnDefs.ts`**

```ts
import {ColDef} from 'ag-grid-enterprise';

export const columnDefs: ColDef[] = [
  {field: 'id', hide: true, cellDataType: 'text'},
  {
    field: 'athlete',
    cellDataType: 'text',
    enableRowGroup: true,
    resizable: true,
  },
  {
    field: 'country',
    cellDataType: 'text',
    enableRowGroup: true,
    resizable: true,
  },
  {
    field: 'sport',
    cellDataType: 'text',
    enableRowGroup: true,
    resizable: true,
  },
  {
    field: 'year',
    cellDataType: 'number',
    enableRowGroup: true,
    resizable: true,
  },
  {
    field: 'gold',
    aggFunc: 'sum',
    cellDataType: 'number',
    enableValue: true,
    resizable: true,
  },
  {
    field: 'silver',
    aggFunc: 'sum',
    cellDataType: 'number',
    enableValue: true,
    resizable: true,
  },
  {
    field: 'bronze',
    aggFunc: 'sum',
    cellDataType: 'number',
    enableValue: true,
    resizable: true,
  },
];
```

### Manually Applying Filters

When evaluating Column Filters on the server, it is common to [turn on Manually Applying Filters](https://www.adaptabletools.com/docs/handbook-column-filter-manually-applying/index.md).

This ensures that only one call to the server is made after all selections are complete.

- AdapTable disables the Filter Bar for any Column where Manually Applying Filters is turned on
- It shows an *Apply Filter* button in the Filter Form instead

**Example: SSRM - Manually Apply Filters**

Server-Side Row Model: Manually Applying Column Filters

- This demo is the same Column Filter setup as above, but with `manuallyApplyColumnFilter` turned on
- The Filter Bar is therefore hidden; Filters are applied only when the *Apply Filter* button is clicked

- Open the `Gold` Column Filter, enter `3`, and click *Apply Filter* — one request is sent to the server
- Open the `Athlete` In Filter, select a few values, then click *Apply Filter* to send them together

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts
  gridOptions.ts
  index.ts             [template]
  onAdaptableReady.ts
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {
  AdaptableOptions,
  CustomInFilterValuesContext,
  DefaultFilterExpressionContext,
  GlobalExpressionFunctionAvailabilityContext,
} from '@adaptabletools/adaptable';

const API_BASE: string = process.env.NEXT_PUBLIC_ATHLETES_API_URL!;

export const getDistinctColumnValues = async (
  columnId: string
): Promise<{value: string}[]> => {
  const jsonResponse = await fetch(
    `${API_BASE}/permitted-values?columnId=${columnId}`
  );
  return jsonResponse.json();
};

export const adaptableOptions: AdaptableOptions = {
  primaryKey: 'id',
  adaptableId: 'SSRM - Manually Apply Filters',
  expressionOptions: {
    customStandardFunctions: {
      // The custom filter is handled on the server.
      // It returns `gold > 2 OR (gold + silver + bronze) > 3`.
      SUPERSTAR: {
        label: 'Superstar',
        returnType: 'boolean',
        operands: [['text']],
        handler: () => true,
        isAvailable: ['ColumnFilter'],
      },
    },
    isExpressionFunctionAvailable: (
      context: GlobalExpressionFunctionAvailabilityContext
    ) => {
      if (
        context.functionName === 'SUPERSTAR' &&
        context.column &&
        context.column.columnId !== 'athlete'
      ) {
        return false;
      }
      return context.defaultAvailability;
    },
  },
  filterOptions: {
    customInFilterValues: async (context: CustomInFilterValuesContext) => {
      const columnId = context.column.columnId;
      const allColumnValues = await getDistinctColumnValues(columnId);

      const inFilterValues = allColumnValues.map(item => ({
        label: item.value,
        value: item.value,
      }));
      return {
        values: inFilterValues,
      };
    },
    columnFilterOptions: {
      manuallyApplyColumnFilter: true,
      defaultTextColumnFilter: (context: DefaultFilterExpressionContext) => {
        return context.column.columnId == 'athlete' ? 'IN' : 'CONTAINS';
      },
    },
  },
  initialState: {
    Dashboard: {
      Tabs: [
        {
          Name: 'Main',
          Toolbars: ['SystemStatus'],
        },
      ],
    },
    Theme: {
      CurrentTheme: 'dark',
    },
    Layout: {
      CurrentLayout: 'SSRM Layout',
      Layouts: [
        {
          Name: 'SSRM Layout',
          TableColumns: [
            'athlete',
            'gold',
            'silver',
            'bronze',
            'country',
            'sport',
            'year',
          ],
          ColumnSizing: {
            athlete: {Width: 175},
            bronze: {Width: 100},
            country: {Width: 125},
            gold: {Width: 100},
            silver: {Width: 100},
            sport: {Width: 175},
            year: {Width: 115},
          },
        },
      ],
    },
  },
};
```

**`src/onAdaptableReady.ts`**

```ts
import {AdaptableReadyInfo, AdaptableApi} from '@adaptabletools/adaptable';
import {
  ColDef,
  GridApi,
  IServerSideDatasource,
  IServerSideGetRowsParams,
  IServerSideGetRowsRequest,
} from 'ag-grid-enterprise';

export const onAdaptableReady = ({
  adaptableApi,
  agGridApi,
}: AdaptableReadyInfo) => {
  agGridApi.setGridOption(
    'serverSideDatasource',
    createDataSource(adaptableApi)
  );
};

const API_BASE: string = process.env.NEXT_PUBLIC_ATHLETES_API_URL!;

// v24 Column Filters are Expressions. The athletes mock server evaluates
// both Grid Filter and Column Filters from `gridFilterAST`.
function rewriteAutoGroupColumn(
  node: unknown,
  groupedColumnId?: string
): unknown {
  if (!groupedColumnId || node == null || typeof node !== 'object') {
    return node;
  }
  if (Array.isArray(node)) {
    return node.map(item => rewriteAutoGroupColumn(item, groupedColumnId));
  }
  const astNode = node as {type?: string; args?: unknown[]};
  if (astNode.type === 'COL' && astNode.args?.[0] === 'ag-Grid-AutoColumn') {
    return {
      ...astNode,
      args: [groupedColumnId, ...astNode.args.slice(1)],
    };
  }
  if (!astNode.args) {
    return node;
  }
  return {
    ...astNode,
    args: astNode.args.map(arg =>
      rewriteAutoGroupColumn(arg, groupedColumnId)
    ),
  };
}

function appendExpressionAst(
  astNodes: unknown[],
  ast: unknown,
  groupedColumnId?: string
) {
  if (ast == null) {
    return;
  }
  const nodes = Array.isArray(ast) ? ast : [ast];
  for (const node of nodes) {
    astNodes.push(rewriteAutoGroupColumn(node, groupedColumnId));
  }
}

function toServerFilterFields(
  adaptableApi: AdaptableApi,
  groupedColumnId?: string
) {
  const filterState = adaptableApi.stateApi.getAdaptableFilterState();
  const astNodes: unknown[] = [];
  appendExpressionAst(astNodes, filterState.gridFilterAST, groupedColumnId);
  for (const columnFilter of filterState.columnFilters ?? []) {
    if (!columnFilter.Expression) {
      continue;
    }
    appendExpressionAst(
      astNodes,
      adaptableApi.expressionApi.getASTForExpression(columnFilter.Expression),
      groupedColumnId
    );
  }
  return {
    adaptableFilters: [],
    gridFilterAST: astNodes.length ? astNodes : undefined,
  };
}

function createDataSource(adaptableApi: AdaptableApi): IServerSideDatasource {
  return {
    getRows(params: IServerSideGetRowsParams) {
      const getRowsRequest: IServerSideGetRowsRequest = params.request;
      const adaptableSortState = adaptableApi.stateApi.getAdaptableSortState();
      const groupedColumn = getRowsRequest.rowGroupCols?.[0];
      const serverFilters = toServerFilterFields(
        adaptableApi,
        groupedColumn?.field ?? groupedColumn?.id
      );

      const sortModel = getRowsRequest.sortModel.map(sort => {
        const customSort = adaptableSortState.customSorts.find(
          customSort => customSort.ColumnId === sort.colId
        );
        if (customSort) {
          return {
            ...sort,
            sortedValues: customSort.SortedValues,
          };
        }
        return sort;
      });

      const request = {
        ...getRowsRequest,
        sortModel,
        ...serverFilters,
        includeSQL: true,
      };
      console.log('request to server', request);

      fetch(API_BASE, {
        method: 'post',
        body: JSON.stringify(request),
        headers: {'Content-Type': 'application/json; charset=utf-8'},
      })
        .then(httpResponse => httpResponse.json())
        .then(response => {
          params.success({
            rowData: response.rows,
            rowCount: response.lastRow ?? 0,
          });

          if (response.pivotFields?.length) {
            addPivotColumnDefs(response, params.api);
          } else {
            if (!adaptableApi.layoutApi.isCurrentLayoutPivot()) {
              if (params.api.getPivotResultColumns() != null) {
                params.api.setPivotResultColumns(null);
              }
            }
          }

          adaptableApi.systemStatusApi.setInfoSystemStatus(
            `SQL: ${response.sql.slice(0, 40)}`,
            response.sql
          );
        })
        .catch(error => {
          params.fail();
        });
    },
  };
}

function addPivotColumnDefs(response: any, agGridApi: GridApi) {
  const existingPivotColDefs = agGridApi.getPivotResultColumns();
  if (existingPivotColDefs && existingPivotColDefs.length > 0) {
    return;
  }

  const pivotColDefs: ColDef[] = response.pivotFields.map(function (
    field: any,
    index: number
  ) {
    const [_key, value] = Object.entries(field)[0];
    const valueStr = `${value}`;
    return {
      headerName: valueStr,
      field: valueStr,
      filter: false,
      colId: `${Date.now()}_${index}`,
      cellDataType: 'number',
    };
  });

  agGridApi.setPivotResultColumns(pivotColDefs);
}
```

**`src/gridOptions.ts`**

```ts
import {GridOptions, themeBalham} from 'ag-grid-enterprise';

import {columnDefs} from './columnDefs';

export const gridOptions: GridOptions = {
  theme: themeBalham,
  defaultColDef: {
    sortable: true,
    filter: true,
    floatingFilter: true,
    enableRowGroup: true,
  },
  rowModelType: 'serverSide',
  columnDefs: columnDefs,
  sideBar: ['adaptable', 'columns', 'filters'],
};
```

**`src/columnDefs.ts`**

```ts
import {ColDef} from 'ag-grid-enterprise';

export const columnDefs: ColDef[] = [
  {field: 'id', hide: true, cellDataType: 'text'},
  {
    field: 'athlete',
    cellDataType: 'text',
    enableRowGroup: true,
    resizable: true,
  },
  {
    field: 'country',
    cellDataType: 'text',
    enableRowGroup: true,
    resizable: true,
  },
  {
    field: 'sport',
    cellDataType: 'text',
    enableRowGroup: true,
    resizable: true,
  },
  {
    field: 'year',
    cellDataType: 'number',
    enableRowGroup: true,
    resizable: true,
  },
  {
    field: 'gold',
    aggFunc: 'sum',
    cellDataType: 'number',
    enableValue: true,
    resizable: true,
  },
  {
    field: 'silver',
    aggFunc: 'sum',
    cellDataType: 'number',
    enableValue: true,
    resizable: true,
  },
  {
    field: 'bronze',
    aggFunc: 'sum',
    cellDataType: 'number',
    enableValue: true,
    resizable: true,
  },
];
```
