# NDF Reports Component (`app-ndf-reports`) - Documentation

## Overview

The `app-ndf-reports` is a highly configurable and extensible Angular component for rendering dynamic reports with Chart.js integration. It supports multiple chart types, advanced filtering, data transformation, and responsive layouts.

### Key Features

- Server-side configuration loading via report keys
- Direct configuration injection for programmatic usage
- Dynamic report rendering with multiple chart types
- Query change event emission for external integration
- Navigation integration for seamless user experience

### Input Properties

```typescript
@Component({
 selector: 'app-ndf-reports'
})
export class NdfReportsComponent {
 @Input() jsonEditorEnabled: boolean = false;
 @Input() reportsKey: string;
 @Input() navigateRoute: string[] = [];
 @Input() config: NdfReportsConfig;

 @Output() onQueryChange = new EventEmitter();
}
```

#### Property Specifications

| Property          | Type               | Required | Default | Description                                         |
| ----------------- | ------------------ | -------- | ------- | --------------------------------------------------- |
| jsonEditorEnabled | `boolean`          | ❌       | `false` | Enable navigation to configuration editor interface |
| reportsKey        | `string`           | ⚠️       | -       | Server-side configuration identifier                |
| navigateRoute     | `string[]`         | ❌       | `[]`    | Angular route array for navigation purposes         |
| config            | `NdfReportsConfig` | ⚠️       | -       | Direct configuration object for report definitions  |

> **⚠️ Configuration Requirement**: Either `reportsKey` OR `config` must be provided. These inputs are mutually exclusive.

#### Output Events

| Event         | Type                | Description                                       |
| ------------- | ------------------- | ------------------------------------------------- |
| onQueryChange | `EventEmitter<any>` | Emitted when report query parameters are modified |

## Configuration Loading Strategy

### Server-Side Configuration Loading

```html
<app-ndf-reports
 [reportsKey]="'ARCHIVE_REPORTS_CONFIG'"
 [jsonEditorEnabled]="true"
 [navigateRoute]="['/reports', 'editor']"
 (onQueryChange)="handleQueryChange($event)"
>
</app-ndf-reports>
```

### Direct Configuration Injection

```html
<app-ndf-reports
 [config]="reportsConfiguration"
 [jsonEditorEnabled]="false"
 (onQueryChange)="handleQueryChange($event)"
>
</app-ndf-reports>
```

## Quick Start Guide

### Basic Setup

```typescript
const basicConfig: NdfReportsConfig = {
 request: {
  pageProvider: 'PP_SALES_DATA'
 },
 reports: {
  items: [
   {
    id: 'sales-total',
    label: 'Total Sales',
    mode: 'digit',
    datasource: {
     propertyPath: 'totalSales'
    }
   }
  ]
 }
};
```

### With Filters

```typescript
const configWithFilters: NdfReportsConfig = {
 request: {
  pageProvider: 'PP_SALES_DATA'
 },
 filters: {
  mode: 'payload',
  visible: true,
  fields: [
   {
    type: 'predicate',
    config: {
     label: 'FILTERS.requestNumber',
     fieldKey: 'requestcase:requestNumber',
     sendMode: 'payload',
     valueType: 'valueObject',
     render: {
      type: 'input',
      options: { debounceTime: 300 }
     }
    }
   },
   {
    type: 'aggregation',
    config: {
     label: 'LISTING.Last_Contributors',
     aggregation: 'dublincore_lastContributor_agg',
     fieldKey: 'dc:lastContributor',
     order: 0,
     sendMode: 'queryParam',
     valueType: 'property',
     // ✅ jexl expression — returns value directly, no variable assignment
     condition:
      "!isEmpty(values['ecm:currentLifeCycleState']) && values['ecm:currentLifeCycleState'].includes('ended')",
     render: {
      type: 'checkbox',
      options: { showTotal: true }
     }
    }
   }
  ]
 },
 reports: {
  items: [
   /* report definitions */
  ]
 }
};
```

## Core Configuration

### `NdfReportsConfig` Interface

```typescript
export type NdfReportsConfig = {
 request: NdfReportsRequest;
 filters?: NdfReportsFilters;
 options?: {
  print?: boolean;
 };
 activeQuery?: Record<string, any>;
 reports: ReportsDefinition;
};
```

| Property    | Type                  | Required | Description                                |
| ----------- | --------------------- | -------- | ------------------------------------------ |
| request     | `NdfReportsRequest`   | ✅       | Core request parameters for data fetching  |
| filters     | `NdfReportsFilters`   | ❌       | Optional filtering configuration           |
| options     | `object`              | ❌       | Additional component options               |
| activeQuery | `Record<string, any>` | ❌       | Initial query parameters for first request |
| reports     | `ReportsDefinition`   | ✅       | Container for all report definitions       |

## Request Configuration

### `NdfReportsRequest` Type

```typescript
type NdfReportsRequest = {
 pageProvider: string;
 customUrl?: { url: string; method: 'post' | 'get' };
 payload?: Record<string, any>;
 params?: Record<string, any>;
 headers?: Record<string, any>;
 transformer?: string;
};
```

| Property     | Type                                       | Required | Description                                                 |
| ------------ | ------------------------------------------ | -------- | ----------------------------------------------------------- |
| pageProvider | `string`                                   | ✅       | Identifier for the data source provider                     |
| customUrl    | `{ url: string; method: 'post' \| 'get' }` | ❌       | Custom endpoint configuration                               |
| payload      | `Record<string, any>`                      | ❌       | Request body for POST requests                              |
| params       | `Record<string, any>`                      | ❌       | Query parameters                                            |
| headers      | `Record<string, any>`                      | ❌       | HTTP headers                                                |
| transformer  | `string`                                   | ❌       | Name of registered transformer in `ReportsDataTransformers` |

## Filters Configuration

### `NdfReportsFilters` Type

```typescript
type NdfReportsFilters = {
 mode: 'payload' | 'params';
 payload?: Record<string, any>;
 params?: Record<string, any>;
 fields: FieldConfigModel[];
 visible?: boolean;
 togglePanel?: boolean;
 reload?: NdfReportsFiltersReloadConfig;
};
```

| Property    | Type                            | Required | Description                                    |
| ----------- | ------------------------------- | -------- | ---------------------------------------------- |
| mode        | `'payload' \| 'params'`         | ✅       | Where to apply filter values                   |
| payload     | `Record<string, any>`           | ❌       | Default payload values                         |
| params      | `Record<string, any>`           | ❌       | Default query parameters                       |
| fields      | `FieldConfigModel[]`            | ✅       | Filter field configurations                    |
| visible     | `boolean`                       | ❌       | Initial visibility of filter UI                |
| togglePanel | `boolean`                       | ❌       | Allow users to show/hide filter panel          |
| reload      | `NdfReportsFiltersReloadConfig` | ❌       | When to reload field data after filter changes |

### Reload Strategy

```ts
type NdfReportsFiltersReloadConfig =
 | { strategy: 'always' }
 | { strategy: 'never' }
 | { strategy: 'onChange'; triggerFields: string[] };
```

| Strategy   | Description                                       |
| ---------- | ------------------------------------------------- |
| `always`   | Reload field data every time filters are applied  |
| `never`    | Only reload on programmatic configuration changes |
| `onChange` | Reload only when specific fields changed          |

## Report Definitions

### `ReportDefinitionModel` Union Type

```typescript
export type ReportDefinitionModel =
 | DigitChartDefinition
 | GraphChartDefinition
 | DynamicLineChartDefinition
 | CustomChartDefinition;
```

### Chart Defaults Configuration

```ts
type ChartDefaultsOptions = {
 globalPlugins?: Plugin[];
 fontFamily?: string;
 fontSize?: number;
 color?: string;
 borderColor?: string;
 backgroundColor?: string;
 maxBarThickness?: number;
 minBarLength?: number;
};

const CHART_DEFAULTS_OPTIONS = new InjectionToken<ChartDefaultsOptions>('CHART_DEFAULTS_OPTIONS');
```

| Property          | Type       | Required | Description                                                           |
| ----------------- | ---------- | -------- | --------------------------------------------------------------------- |
| `globalPlugins`   | `Plugin[]` | ❌       | List of globally applied Chart.js plugins                             |
| `fontFamily`      | `string`   | ❌       | Default font family for all chart text                                |
| `fontSize`        | `number`   | ❌       | Default font size for chart labels, titles, and ticks                 |
| `color`           | `string`   | ❌       | Default text color used in chart labels and legends                   |
| `borderColor`     | `string`   | ❌       | Default border color for bars, lines, and other chart elements        |
| `backgroundColor` | `string`   | ❌       | Default background color for chart elements                           |
| `maxBarThickness` | `number`   | ❌       | Maximum thickness (in pixels) for bars in bar charts                  |
| `minBarLength`    | `number`   | ❌       | Minimum pixel length for bars — useful for visibility of small values |

> 💡 Use `CHART_DEFAULTS_OPTIONS` to configure consistent styling and behavior across all your charts.

```ts
@NgModule({
 providers: [
  {
   provide: CHART_DEFAULTS_OPTIONS,
   useValue: {
    fontFamily: 'Arial, sans-serif',
    fontSize: 12,
    color: '#333',
    borderColor: '#ccc',
    backgroundColor: '#f5f5f5',
    maxBarThickness: 30,
    minBarLength: 5,
    globalPlugins: [logPlugin]
   }
  }
 ]
})
export class AppModule {}
```

## Chart Types

### Base Configuration

```typescript
export interface BaseReportConfig {
 id: string | number;
 label: string;
 mode: ReportMode;
 navigate?: {
  enabled?: boolean;
  route: any[];
  includeParams?: boolean;
 };
 details?: ReportDetailsConfig;
 layout?: {
  width?: GridWidth;
  columnPosition?: GridWidth;
  height?: number | 'auto';
  rowPosition?: number | 'auto';
  styleClass?: string;
  minContentHeight?: string;
 };
}
```

| Property            | Type                  | Required | Description                                                             |
| ------------------- | --------------------- | -------- | ----------------------------------------------------------------------- |
| id                  | `string \| number`    | ✅       | Unique identifier                                                       |
| label               | `string`              | ✅       | Display name (supports i18n keys)                                       |
| mode                | `ReportMode`          | ✅       | Chart type identifier                                                   |
| navigate            | `object`              | ❌       | Click navigation configuration                                          |
| └─ enabled          | `boolean`             | ❌       | Enable click-to-navigate                                                |
| └─ route            | `any[]`               | ✅       | Angular route array                                                     |
| └─ includeParams    | `boolean`             | ❌       | Include current filters in navigation                                   |
| details             | `ReportDetailsConfig` | ❌       | Detailed view configuration                                             |
| layout              | `object`              | ❌       | Grid layout configuration                                               |
| └─ width            | `GridWidth`           | ❌       | Column span (1-12 or 'auto')                                            |
| └─ columnPosition   | `GridWidth`           | ❌       | Starting column                                                         |
| └─ height           | `number \| 'auto'`    | ❌       | Row span or auto-size                                                   |
| └─ rowPosition      | `number \| 'auto'`    | ❌       | Starting row                                                            |
| └─ styleClass       | `string`              | ❌       | Custom CSS classes                                                      |
| └─ minContentHeight | `string`              | ❌       | Defines the minimum height of the content area (supports px, rem, etc.) |

### Digit Charts

#### `DigitChartDefinition` Type

```typescript
type DigitChartDefinition = BaseReportConfig & {
 mode: 'digit';
 datasource: {
  propertyPath: string;
  transformer?: string;
  bindValue?: string;
 };
};
```

| Property        | Type      | Required | Description                                              |
| --------------- | --------- | -------- | -------------------------------------------------------- |
| mode            | `'digit'` | ✅       | Chart type identifier                                    |
| └─ propertyPath | `string`  | ✅       | Path to data property in response                        |
| └─ transformer  | `string`  | ❌       | Transformer name (registered in `ChartDataTransformers`) |
| └─ bindValue    | `string`  | ❌       | Property to extract from data object/array               |

### Graph Charts

#### `GraphChartDefinition` Type

```typescript
type GraphChartDefinition<TType extends ChartType = ChartType> = BaseReportConfig & {
 mode: 'graph';
 datasource: ReportDataSource[];
 chart: GraphChartOptionsDefinition<TType>;
 prefix?: string;
 print?: boolean;
 typeConfig?: ChartTypeConfig;
 dialog?: GraphDialogConfig;
};
```

#### Chart Configuration

```typescript
type GraphChartOptionsDefinition<TType extends ChartType = ChartType> = {
 type: TType;
 options?: CustomChartOptions<TType>;
 datasets?: Omit<ChartDataset<TType>, 'data'>[];
 overrides?: ChartOptionsByType;
 plugins?: string[];
 colors?: string[];
 direction?: 'horizontal' | 'vertical';
 callbacks?: Array<CallbackDefinition>;
};
```

| Property  | Type                                  | Required | Description                                |
| --------- | ------------------------------------- | -------- | ------------------------------------------ |
| type      | `TType`                               | ✅       | Chart.js chart type                        |
| options   | `CustomChartOptions<TType>`           | ❌       | Chart.js options with extensions           |
| datasets  | `Omit<ChartDataset<TType>, 'data'>[]` | ❌       | Dataset configurations                     |
| overrides | `ChartOptionsByType`                  | ❌       | Type-specific overrides                    |
| plugins   | `string[]`                            | ❌       | Plugin names (must be pre-registered)      |
| colors    | `string[]`                            | ❌       | Color palette (CSS colors/variables)       |
| direction | `'horizontal' \| 'vertical'`          | ❌       | Chart orientation (bar charts only)        |
| callbacks | `Array<CallbackDefinition>`           | ❌       | List of dynamic Chart.js callback bindings |

##### `CallbackDefinition`

```ts
type CallbackDefinition = {
 path: string;
 callback: EvaluatedString;
};
```

| Property   | Type              | Required | Description                                                                                                                              |
| ---------- | ----------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `path`     | `string`          | ✅       | Dot-notated path to the Chart.js callback option (e.g., `options.plugins.tooltip.callbacks.label`)                                       |
| `callback` | `EvaluatedString` | ✅       | **Jexl expression** evaluated at runtime and assigned as the callback. Use `resolve('fnName')` to look up a registered function by name. |

**Example**

```json
{
 "callbacks": [
  {
   "path": "tooltip.callbacks.label",
   "callback": "resolve('convertDecimalHoursToString')"
  },
  {
   "path": "plugins.datalabels.formatter",
   "callback": "resolve('formatValue')"
  }
 ]
}
```

> `resolve` looks up a registered callback by name from the `ChartPluginsCallbacks` registry. Register callbacks before use:
>
> ```typescript
> this._chartPluginsCallbacks.register({
>  convertDecimalHoursToString: (context) => convertDecimalHourToString(context.raw)
> });
> ```

#### Data Source Configuration

```typescript
type ReportDataSource = {
 propertyPath: string;
 bindLabel?: { ar: string; en: string };
 bindValue?: string;
 dataFormat?: string;
 transformer?: string;
};
```

### Report Details Configuration

#### Simple Configuration (String Key)

```json
{
 "details": {
  "enabled": true,
  "source": "DETAIL_REPORT"
 }
}
```

#### Advanced Configuration

```typescript
export type ReportConfigOptions = {
 request?: Partial<NdfReportsRequest> & {
  actions?: {
   beforeSubmit?: EvaluatedString;
  };
 };
 columns?: TableColumnConfig[];
 fields?: Record<string, string>;
 prefix?: string;
 quickFilters?: string;
 columnsOptions?: {
  toggle?: boolean;
  sortable?: TableSortConfig;
 };
 sortingBy?: TableSortOptions;
 export?: TableExportConfig;
};
```

| Property        | Type                               | Required | Description                                                                                                                                                                   |
| --------------- | ---------------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| request         | `Partial<NdfReportsRequest> & ...` | ❌       | Request configuration with optional pre-submit action                                                                                                                         |
| └─ beforeSubmit | `EvaluatedString`                  | ❌       | **Jexl expression** run before request submission to dynamically modify the payload. Has access to `payload`, `user`, `values`. Example: `"payload.userId = get(user, 'id')"` |
| columns         | `TableColumnConfig[]`              | ❌       | Table column definitions                                                                                                                                                      |
| fields          | `Record<string, string>`           | ❌       | Field name mapping (response → display)                                                                                                                                       |
| prefix          | `string`                           | ❌       | Translation key prefix                                                                                                                                                        |
| quickFilters    | `string`                           | ❌       | Quick filter configuration                                                                                                                                                    |
| columnsOptions  | `object`                           | ❌       | Global column behavior settings                                                                                                                                               |
| sortingBy       | `TableSortOptions`                 | ❌       | Default sorting configuration                                                                                                                                                 |
| export          | `TableExportConfig`                | ❌       | Export functionality configuration                                                                                                                                            |

**`beforeSubmit` expression examples**

```ts
// Set user ID from context
"payload.userId = get(user, 'id')";

// Conditionally set a field
"payload.lang = if(language === 'ar', 'arabic', 'english')";

// Use current timestamp
'payload.requestedAt = timestamp()';
```

### Dynamic Line Charts

#### `DynamicLineChartDefinition` Type

```typescript
export type DynamicLineChartDefinition = ReportChartConfig & {
 mode: 'dynamicLine';
 prefix?: string;
 colors?: string[];
 print?: boolean;
 request: NdfReportsRequest & {
  actions?: {
   beforeSubmit?: EvaluatedString;
  };
 };
 datasource: ({ aggregation: string } & ReportDataSource)[];
 group?: {
  active: boolean;
  selected?: TimeGroups;
 };
 chart: DynamicLineChartOptionsDefinition;
};
```

#### Time Grouping

```typescript
group?: {
 active: boolean;   // Enable time grouping controls in UI
 selected?: TimeGroups; // Default: 'month'
};
```

| Value   | Description         | Use Case                      |
| ------- | ------------------- | ----------------------------- |
| `day`   | Daily aggregation   | Detailed short-term analysis  |
| `week`  | Weekly aggregation  | Medium-term trend analysis    |
| `month` | Monthly aggregation | Long-term trend visualization |
| `year`  | Yearly aggregation  | Historical data overview      |

#### `beforeSubmit` on Dynamic Line Charts

Same jexl expression rules apply as in `ReportConfigOptions`. The expression has access to `payload`, `user`, `values`, and all built-in functions:

```json
{
 "request": {
  "pageProvider": "PP_RPT_Records",
  "actions": {
   "beforeSubmit": "payload.userId = get(user, 'id')"
  }
 }
}
```

### Custom Charts

#### `CustomChartDefinition` Type

```typescript
export interface CustomChartDefinition extends BaseReportConfig {
 mode: 'custom';
 type: string;
 prefix?: string;
 print?: boolean;
 datasource?: ReportDataSource[];
 options?: Record<string, any>;
 dialog?: GraphDialogConfig;
}
```

#### Component Registration

```typescript
export interface CustomReportRegistryDefinition {
 type: string;
 component: ComponentType<any>;
 category?: string;
 name?: string;
 description?: string;
}
```

#### Base Custom Report Class

```typescript
abstract class BaseCustomReport extends DestroySubject {
 abstract print(): void;
 @Input() direction: Direction = 'rtl';
 @Input() definition: CustomChartDefinition;
 @Input() data: ReportResponseModel;
 @Input() criteria: CriteriaModel;
 @Input() config: CustomChart;
}
```

#### Implementation Example

```typescript
@Component({ selector: 'app-heatmap-chart', template: `...` })
export class HeatmapChartComponent extends BaseCustomReport implements OnInit, OnDestroy {
 static registerInfo(): CustomReportRegistryDefinition {
  return {
   type: 'heatmap-chart',
   component: HeatmapChartComponent,
   category: 'visualization',
   name: 'Heatmap Chart'
  };
 }

 print(): void {
  this._chartHelperService.printChart(
   this.chart.id,
   this._translateService.instant(this.config.label),
   this.options,
   []
  );
 }

 ngOnDestroy() {
  if (this.customChart) this.customChart.destroy();
  super.ngOnDestroy();
 }
}

// Registration
this.customReportsRegistry.registerComponent(HeatmapChartComponent.registerInfo());
```

---

## EvaluatedString Reference

Several fields across the component accept an `EvaluatedString` — a **jexl expression** evaluated at runtime by `NdfEvaluatorService`. The service runs on an **isolated jexl instance**, so all registrations are scoped and do not affect global state.

### Where `EvaluatedString` Is Used

| Field                              | Context                                        |
| ---------------------------------- | ---------------------------------------------- |
| `condition` on filter fields       | Determines field visibility                    |
| `beforeSubmit` on request actions  | Modifies payload before submission             |
| `callback` in `CallbackDefinition` | Assigns a function to a Chart.js callback path |

### Expression Syntax

```ts
// ✅ Correct — expression returns its value directly
"user.role === 'admin'";

// ❌ Old sandbox syntax — no longer supported
"show = user.role === 'admin';";
```

### Available Context Variables

| Variable       | Description                                   |
| -------------- | --------------------------------------------- |
| `values`       | Current filter field values                   |
| `user`         | Authenticated user object                     |
| `language`     | Active language string (`'ar'` / `'en'`)      |
| `aggregations` | Current aggregation data                      |
| `payload`      | Request payload (available in `beforeSubmit`) |

### Built-in Functions

#### Lodash

| Function     | Description                              |
| ------------ | ---------------------------------------- |
| `get`        | `get(obj, 'a.b.c')` — safe nested access |
| `has`        | Check if path exists on object           |
| `pick`       | Pick specific keys from object           |
| `merge`      | Deep merge two objects                   |
| `nth`        | Get element at index — `nth(arr, 2)`     |
| `first`      | First element of array                   |
| `last`       | Last element of array                    |
| `find`       | Find item in array by predicate          |
| `filter`     | Filter array by predicate                |
| `groupBy`    | Group array items by key                 |
| `sortBy`     | Sort array by key                        |
| `isEmpty`    | Check if value is empty                  |
| `isNil`      | Check if value is `null` or `undefined`  |
| `isEqual`    | Deep equality check                      |
| `isString`   | Type check for string                    |
| `isNumber`   | Type check for number                    |
| `isArray`    | Type check for array                     |
| `isObject`   | Type check for object                    |
| `startsWith` | `startsWith(str, 'prefix')`              |
| `endsWith`   | `endsWith(str, 'suffix')`                |
| `toNumber`   | Convert value to number                  |

#### Math

| Function         | Description                        |
| ---------------- | ---------------------------------- |
| `min(a, b)`      | Returns the smaller of two numbers |
| `max(a, b)`      | Returns the larger of two numbers  |
| `abs(n)`         | Absolute value                     |
| `ceil(n)`        | Round up                           |
| `floor(n)`       | Round down                         |
| `round(n)`       | Round to nearest integer           |
| `pow(base, exp)` | Raise to power                     |
| `sqrt(n)`        | Square root                        |

#### Date

| Function        | Description                            |
| --------------- | -------------------------------------- |
| `now()`         | Current datetime as ISO string         |
| `today()`       | Current date as `YYYY-MM-DD` string    |
| `currentYear()` | Current year as a number               |
| `timestamp()`   | Current Unix timestamp in milliseconds |

> **Important:** `now()` returns an ISO string, not a `Date` object. Method chaining like `now().getFullYear()` will not work — use `currentYear()` instead.

#### String

| Function             | Description                             |
| -------------------- | --------------------------------------- |
| `split(value, char)` | Split string by delimiter into an array |

#### Logical / Debug

| Function                           | Description                                                          |
| ---------------------------------- | -------------------------------------------------------------------- |
| `if(condition, trueVal, falseVal)` | Inline conditional                                                   |
| `debug(value)`                     | Logs value and returns it — safe to use mid-expression               |
| `log(value)`                       | Logs value and returns `undefined` — use as a standalone side effect |

> `debug()` and `log()` are for development only. Guard registration behind an environment flag:
>
> ```typescript
> if (!environment.production) {
>  this.ndfEvaluatorService.registerFunctions([
>   {
>    name: 'debug',
>    fn: (v: any) => {
>     console.log('[jexl debug]', v);
>     return v;
>    }
>   },
>   {
>    name: 'log',
>    fn: (v: any) => {
>     console.log('[jexl log]', v);
>     return undefined;
>    }
>   }
>  ]);
> }
> ```

### No Method Chaining on Returned Values

Jexl cannot chain methods on values returned from functions. Wrap the full operation inside a registered function instead:

```ts
// ❌ Won't work
'now().getFullYear()';

// ✅ Use dedicated built-in
'currentYear()';
```

### Expression Examples

```ts
// Field visibility — role check
"user.role == 'admin'";

// Field visibility — filter dependency
"!isEmpty(values['ecm:currentLifeCycleState']) && values['ecm:currentLifeCycleState'].includes('ended')";

// beforeSubmit — set user from context
"payload.userId = get(user, 'id')";

// beforeSubmit — conditional field
"payload.lang = if(language == 'ar', 'arabic', 'english')";

// beforeSubmit — timestamp
'payload.requestedAt = timestamp()';

// callback — resolve registered function
"resolve('convertDecimalHoursToString')";

// Year offset label
"currentYear() - toNumber(split(value, '+')[1])";

// Debug mid-expression (development only)
"debug(values['status']) == 'active'";
```

---

## Related Types Reference

```typescript
export const REPORT_MODE = {
 graph: 'graph',
 digit: 'digit',
 dynamicLine: 'dynamicLine',
 custom: 'custom'
} as const;

export type ReportMode = (typeof REPORT_MODE)[keyof typeof REPORT_MODE];
export type GridWidth = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 'auto';
```

---

## Troubleshooting

### 1. Transformer Not Found

**Error:** `Transformer 'myTransformer' not registered`

```typescript
chartDataTransformers.registerDigitsTransformer('myTransformer', transformFunction);
chartDataTransformers.registerGraphTransformers('myTransformer', transformFunction);
```

### 2. Plugin Not Available

**Error:** `Plugin with key 'myPlugin' not found.`

```typescript
chartPluginsRegistry.register('myPlugin', myPluginImplementation);
```

### 3. Callback Not Resolving

**Error:** `resolve('fnName')` returns null or callback not executing

```typescript
this._chartPluginsCallbacks.register({
 convertDecimalHoursToString: (context) => convertDecimalHourToString(context.raw)
});
```

### 4. Field Condition Not Applied

```ts
// ❌ Old syntax
"show = values && values['ecm:currentLifeCycleState']?.includes('ended');";

// ✅ New syntax
"!isEmpty(values['ecm:currentLifeCycleState']) && values['ecm:currentLifeCycleState'].includes('ended')";
```

### 5. Method Chaining Error

**Error:** `Jexl Function getFullYear is not defined`

```ts
// ❌ Won't work
'now().getFullYear()';

// ✅ Use built-in
'currentYear()';
```

### 6. Expression Returns `null` Unexpectedly

Check the browser console for `[NdfEvaluator] evalSync error`. Use `debug()` to inspect values mid-expression:

```ts
"debug(payload) && payload.userId === get(user, 'id')";
```

### 7. Data Path Not Found

Verify the `propertyPath` matches your API response structure:

```typescript
// API: { data: { aggregation: { total: 1000 } } }
// propertyPath: "data.aggregation.total"
```

### 8. Layout Issues

```json
{
 "layout": {
  "width": 6,
  "height": "auto",
  "columnPosition": 1,
  "rowPosition": "auto"
 }
}
```
