# Custom Expression Function Scope

Canonical page: https://www.adaptabletools.com/docs/adaptable-ql-expression-functions-custom-scope

- Custom Expression Functions are available in every relevant Module by default
- Limit an individual function with its own `isAvailable` property
- Use `isExpressionFunctionAvailable` for one global rule covering many functions

By default a Custom Expression Function is available in **all Modules that host that kind of Expression**.

There are 2 ways in which this default scope can be restricted:

- using the `isAvailable` property in the Function object
- doing a global setting using the `isExpressionFunctionAvailable` property in Expression Options

- Use `isAvailable` to keep the rule next to the function it applies to
- Use the global override for one rule that covers many functions (including System functions)

## Using `isAvailable`

The Function object allows you to configure which Modules can access your Custom Function.

This is done by using the `isAvailable` property.

Omit `isAvailable` (or return `true` from the callback) to keep the default: available in every relevant Module

The `isAvailable` property can be one of 2 types:

- a hard-coded list of Modules

The Modules are of type [`AdaptableStandardExpressionModule`](https://www.adaptabletools.com/docs/reference/adaptablestandardexpressionmodule.md) and [`AdaptableAggregatedExpressionModule`](https://www.adaptabletools.com/docs/reference/adaptableaggregatedexpressionmodule.md)

- a function that receives the context and returns `true` / `false`

- Use the function option when a hard-coded list of Modules is not enough
- e.g. when the decision depends on `context.module`, `context.functionName`, or (for Column Filter) `context.column`

### Limiting Custom Expression Functions to specific Modules

Define the [Custom Functions](https://www.adaptabletools.com/docs/adaptable-ql-expression-functions-custom-standard/index.md) in `expressionOptions.customStandardFunctions`

In this example we provide 2 functions: `THIS_BUSINESS_YEAR` and `USD_CONVERT`

In this example we use both forms of `isAvailable`:

- `THIS_BUSINESS_YEAR` provides a hard-coded list of [`AdaptableStandardExpressionModule`](https://www.adaptabletools.com/docs/reference/adaptablestandardexpressionmodule.md) names
- `USD_CONVERT` provides a callback that receives [`ExpressionFunctionAvailabilityContext`](https://www.adaptabletools.com/docs/reference/expressionfunctionavailabilitycontext.md) and returns `true` / `false`

```ts [[1,2, "customStandardFunctions"], [2,3, "THIS_BUSINESS_YEAR"], [3,7, "isAvailable"], [2,9, "USD_CONVERT"], [3,13, "isAvailable"]]
expressionOptions: {
  customStandardFunctions: {
    THIS_BUSINESS_YEAR: {
      handler(args, context) { /* ... */ },
      returnType: 'boolean',
      operands: [['date']],
      isAvailable: ['Alert'],
    },
    USD_CONVERT: {
      handler(args, context) { /* ... */ },
      returnType: 'number',
      operands: [['number', 'text']],
      isAvailable: (context) => context.module === 'CalculatedColumn',
    },
  },
}
```

## Using a Global Override

The other way to limit which modules can access your function is by setting a global override.

This is achieved by leveraging the `isExpressionFunctionAvailable` property in [Expression Options](https://www.adaptabletools.com/docs/technical-reference-expression/index.md).

The callback receives [`GlobalExpressionFunctionAvailabilityContext`](https://www.adaptabletools.com/docs/reference/globalexpressionfunctionavailabilitycontext.md) (the per-function context plus `defaultAvailability`).

- This runs **after** each function's own `isAvailable`, and receives that result as `context.defaultAvailability`
- It has the final say: it can hide a function, and it can also re-enable one that `isAvailable` excluded

```ts {3}
// hide every Custom Function from the Grid Filter, while leaving all other decisions unchanged
expressionOptions: {
  isExpressionFunctionAvailable: (context) => {
    if (context.isCustom && context.module === 'GridFilter') {
      return false;
    }
    return context.defaultAvailability;
  },
}
```

- Use it for a cross-cutting rule (hide a System operator everywhere, or vary Column Filter operators per Column)
- Return `context.defaultAvailability` to keep the per-function result

**Example: AdapTableQL: Custom Functions Scope**

Limiting Custom Expression Functions to specific Modules

- This example creates 2 Custom Expression Functions, each limited to one Module using a different mechanism:
  - `THIS_BUSINESS_YEAR` — `Alert` only, via its own `isAvailable` property (hard-coded list)
  - `USD_CONVERT` — `Calculated Column` only, via the global `isExpressionFunctionAvailable` override in Expression Options

- Open an [Alerts](https://www.adaptabletools.com/docs/handbook-alerting/index.md) Expression — `THIS_BUSINESS_YEAR` is in the Custom menu; `USD_CONVERT` is not
- Open the `Dollar Price` [Calculated Column](https://www.adaptabletools.com/docs/handbook-calculated-column/index.md) — `USD_CONVERT` is listed; `THIS_BUSINESS_YEAR` is not
- Open [Format Column](https://www.adaptabletools.com/docs/handbook-column-formatting/index.md) or Grid Filter — neither custom function is listed

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

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts
  gridOptions.ts       [template]
  index.ts             [template]
  onAdaptableReady.ts  [template]
  rowData.ts
  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, ExpressionContext} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Custom Expression Functions Scope',
  expressionOptions: {
    isExpressionFunctionAvailable: context => {
      if (context.functionName === 'USD_CONVERT') {
        return context.module === 'CalculatedColumn';
      }
      return context.defaultAvailability;
    },
    customStandardFunctions: {
      THIS_BUSINESS_YEAR: {
        handler(args: any[], context: ExpressionContext) {
          const startBusinessYear = new Date(2023, 4, 1);
          return new Date(args[0]) > startBusinessYear;
        },
        returnType: 'boolean',
        operands: [['date']],
        description: 'Returns true if Date is in current Business year',
        signatures: ['THIS_BUSINESS_YEAR(dateToCheck: Date)'],
        examples: ['THIS_BUSINESS_YEAR([purchased])'],
        category: 'custom',
        isAvailable: ['Alert'],
      },
      USD_CONVERT: {
        handler(args: any[], context: ExpressionContext) {
          const inputValue: number = args[0];
          if (isNaN(inputValue)) {
            return undefined;
          }
          const oldCurrency = args[1];
          if (oldCurrency === 'USD') {
            return inputValue;
          }

          if (oldCurrency === 'EUR') {
            return inputValue * 1.15;
          } else if (oldCurrency === 'GBP') {
            return inputValue * 1.2;
          }
          return undefined;
        },
        returnType: 'number',
        operands: [['number', 'text']],
        description: 'Converts EUR & GBP Currencies to Dollar',
        signatures: [
          'USD_CONVERT(currentValue: number, currentCurrency: string)',
        ],
        examples: [
          'USD_CONVERT([value],[currency])',
          'USD_CONVERT([value], "GBP")',
        ],
        category: 'custom',
      },
    },
  },
  initialState: {
    Dashboard: {
      PinnedToolbars: ['GridFilter'],
      ModuleButtons: [
        'Alert',
        'CalculatedColumn',
        'FormatColumn',
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    Alert: {
      AlertDefinitions: [
        {
          Name: 'This Business Year',
          MessageType: 'Info',
          Scope: {
            All: true,
          },
          Rule: 'THIS_BUSINESS_YEAR([purchased])',
          AlertProperties: {
            HighlightCell: true,
          },
        },
      ],
    },
    CalculatedColumn: {
      CalculatedColumns: [
        {
          ColumnId: 'dollar_price',
          FriendlyName: 'Dollar Price',
          Expression: 'USD_CONVERT([amount], [currency])',
          CalculatedColumnSettings: {
            DataType: 'number',
          },
        },
      ],
    },
    FormatColumn: {
      FormatColumns: [
        {
          Name: 'formatColumn-purchased',
          Scope: {
            ColumnIds: ['purchased'],
          },
          DisplayFormat: {
            Formatter: 'DateFormatter',
            Options: {
              Pattern: 'yyyy/MM/dd',
            },
          },
        },
        {
          Name: 'formatColumn-dollar_price',
          Scope: {
            ColumnIds: ['dollar_price'],
          },
          DisplayFormat: {
            Formatter: 'NumberFormatter',
            Options: {
              FractionDigits: 2,
              Prefix: '$',
            },
          },
          Style: {
            Alignment: 'Right',
          },
        },
      ],
    },
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          Name: 'Standard Layout',
          TableColumns: [
            'item',
            'amount',
            'currency',
            'purchased',
            'dollar_price',
          ],
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

**`src/columnDefs.ts`**

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

export const columnDefs: ColDef[] = [
  {
    headerName: 'id',
    field: 'Id',
    filter: true,
    editable: false,
    sortable: true,
    cellDataType: 'text',
  },
  {
    headerName: 'Item',
    field: 'item',
    filter: true,
    editable: false,
    sortable: true,
    cellDataType: 'text',
  },
  {
    headerName: 'Amount',
    field: 'amount',
    filter: true,
    editable: true,
    sortable: true,
    cellDataType: 'number',
  },
  {
    headerName: 'Currency',
    field: 'currency',
    filter: true,
    editable: true,
    sortable: true,
    cellDataType: 'text',
  },
  {
    headerName: 'Purchased',
    field: 'purchased',
    filter: true,
    editable: true,
    sortable: true,
    cellDataType: 'date',
  },
];
```

**`src/rowData.ts`**

```ts
export const rowData = [
  {
    id: 1,
    item: 'Washing Machine',
    amount: 500.35,
    currency: 'EUR',
    purchased: new Date(2023, 5, 11),
  },
  {
    id: 2,
    item: 'Football',
    amount: 2.7,
    currency: 'GBP',
    purchased: new Date(2022, 7, 19),
  },
  {
    id: 3,
    item: 'Fridge',
    amount: 385.75,
    currency: 'USD',
    purchased: new Date(2021, 4, 5),
  },
  {
    id: 4,
    item: 'Food',
    amount: 195,
    currency: 'CHF',
    purchased: new Date(2021, 3, 15),
  },
  {
    id: 5,
    item: 'Holiday',
    amount: 1187.5,
    currency: 'GBP',
    purchased: new Date(2019, 8, 7),
  },
  {
    id: 6,
    item: 'Misc',
    amount: 56.23,
    currency: 'EUR',
    purchased: new Date(2023, 4, 5),
  },
  {
    id: 7,
    item: 'Laptop',
    amount: 2500,
    currency: 'EUR',
    purchased: new Date(2022, 8, 3),
  },
  {
    id: 8,
    item: 'Sport Tickets',
    amount: 904,
    currency: 'EUR',
    purchased: new Date(2019, 2, 24),
  },
  {
    id: 9,
    item: 'Clothes',
    amount: 480.25,
    currency: 'USD',
    purchased: new Date(2023, 5, 29),
  },
  {
    id: 10,
    item: 'Concert Ticket',
    amount: 235.45,
    currency: 'USD',
    purchased: new Date(2023, 7, 15),
  },
  {
    id: 11,
    item: 'Rent',
    amount: 652.75,
    currency: 'GBP',
    purchased: new Date(2021, 4, 23),
  },
];
```

- In both use cases, `context.column` is set **only** when AdapTable is resolving operators for a specific Column Filter
- It is `undefined` on the module-level pass — guard before using it
