# Filters Panel Component Documentation (`app-filters-panel`)

## Overview

The `app-filters-panel` component provides a comprehensive filtering interface for data tables and search results. It supports multiple field types, aggregation-based filtering, and customizable rendering options with real-time data updates and flexible configuration management.

### Key Features

- Dynamic field rendering with multiple input types
- Aggregation-based filtering with bucket management
- Real-time query synchronization and state management
- Custom template integration for specialized components
- Internationalization support with role-based access control

## Quick Start Guide

### Basic Implementation

```typescript
import { Component } from '@angular/core';
import { FieldConfigModel, AggregationResponse, FormQueryModel } from './types';

@Component({
 template: `
  <app-filters-panel
   [aggregations]="aggregations"
   [fields]="filterFields"
   [activeQuery]="currentQuery"
   (filterChanged)="onFilterChange($event)"
  >
  </app-filters-panel>
 `
})
export class MyComponent {
 aggregations: Record<string, AggregationResponse> = {
  priority_agg: {
   id: 'priority_agg',
   field: 'priority',
   buckets: [
    { key: 'high', docCount: 25 },
    { key: 'medium', docCount: 48 },
    { key: 'low', docCount: 12 }
   ],
   properties: {}
  }
 };

 filterFields: FieldConfigModel[] = [
  {
   type: 'aggregation',
   config: {
    label: 'FILTERS.priority',
    fieldKey: 'priority',
    aggregation: 'priority_agg',
    sendMode: 'queryParam',
    render: {
     type: 'checkbox',
     options: { showTotal: true }
    }
   }
  }
 ];

 currentQuery: FormQueryModel = {};

 onFilterChange(filters: Record<string, any>) {
  console.log('Filter changed:', filters);
 }
}
```

---

## Component Interface

### Input Properties

```typescript
@Component({
 selector: 'app-filters-panel'
})
export class FiltersPanel {
 @Input() aggregations: Record<string, AggregationResponse>;
 @Input() fields: FieldConfigModel[];
 @Input() activeQuery: FormQueryModel;
 @Input() customTemplateRef: TemplateRef<any>;

 @Output() filterChanged = new EventEmitter<Record<string, any>>();
}
```

#### Property Specifications

| Property            | Type                                  | Required | Description                                                   |
| ------------------- | ------------------------------------- | -------- | ------------------------------------------------------------- |
| `aggregations`      | `Record<string, AggregationResponse>` | ✅       | Collection of aggregation data indexed by aggregation ID      |
| `fields`            | `FieldConfigModel[]`                  | ✅       | Array of filter field configurations defining UI and behavior |
| `activeQuery`       | `FormQueryModel`                      | ✅       | Current query state for synchronizing filter values           |
| `customTemplateRef` | `TemplateRef<any>`                    | ❌       | Template reference for aggregation field custom rendering     |

#### Event Emissions

| Event           | Type                                | Description                                                        |
| --------------- | ----------------------------------- | ------------------------------------------------------------------ |
| `filterChanged` | `EventEmitter<Record<string, any>>` | Emitted when filter values change, containing updated filter state |

---

## Data Models

### `AggregationResponse` Interface

```typescript
export interface AggregationResponse {
 'entity-type'?: string;
 id: string;
 field?: string;
 properties: Record<string, any>;
 ranges?: any[];
 selection?: any[];
 type?: string;
 buckets: AggregationBucket[];
 extendedBuckets?: AggregationBucket[];
}
```

| Property          | Type                  | Required | Description                                               |
| ----------------- | --------------------- | -------- | --------------------------------------------------------- |
| `entity-type`     | `string`              | ❌       | Entity classification for the aggregation                 |
| `id`              | `string`              | ✅       | Unique identifier                                         |
| `field`           | `string`              | ❌       | Source field key used for aggregation                     |
| `properties`      | `Record<string, any>` | ✅       | Additional metadata and configuration properties          |
| `ranges`          | `any[]`               | ❌       | Predefined ranges for range-based aggregations            |
| `selection`       | `any[]`               | ❌       | Currently selected values for the aggregation             |
| `type`            | `string`              | ❌       | Aggregation type identifier                               |
| `buckets`         | `AggregationBucket[]` | ✅       | Primary aggregation results containing filterable options |
| `extendedBuckets` | `AggregationBucket[]` | ❌       | Additional bucket data for extended functionality         |

### `AggregationBucket` Interface

```typescript
export interface AggregationBucket {
 key: string;
 docCount: number;
 fetchedKey?: Record<string, any>;
 from?: number;
 to?: number;
 fromAsDate?: Record<string, any>;
 toAsDate?: Record<string, any>;
}
```

| Property     | Type                  | Required | Description                                       |
| ------------ | --------------------- | -------- | ------------------------------------------------- |
| `key`        | `string`              | ✅       | Unique identifier for the bucket value            |
| `docCount`   | `number`              | ✅       | Number of documents matching this bucket          |
| `fetchedKey` | `Record<string, any>` | ❌       | Additional key metadata from data source          |
| `from`       | `number`              | ❌       | Range start value for numeric range buckets       |
| `to`         | `number`              | ❌       | Range end value for numeric range buckets         |
| `fromAsDate` | `Record<string, any>` | ❌       | Range start as date object for date range buckets |
| `toAsDate`   | `Record<string, any>` | ❌       | Range end as date object for date range buckets   |

---

## Field Configuration

### `FieldConfigModel` Types

```typescript
type FieldConfigModel =
 | { type: 'aggregation'; config: AggregationFieldConfig }
 | { type: 'predicate'; config: PredicateFieldConfig }
 | { type: 'custom'; config: CustomFieldConfig };
```

### Base Field Configuration

```typescript
interface BaseFieldConfig {
 label: TranslateKey;
 fieldKey: string;
 values?: unknown;
 prefix?: string;
 order?: number;
 operator?: ComparisonOperator;
 valueType: 'valueObject' | 'property';
 visible?: boolean;
 roles?: string[];
 permission?: string;
 condition?: EvaluatedString;
}
```

| Property     | Type                            | Required | Default       | Description                                                                                                                                                                                                                                                                                                                                                                |
| ------------ | ------------------------------- | -------- | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `label`      | `TranslateKey`                  | ✅       | -             | Internationalization key for field display label                                                                                                                                                                                                                                                                                                                           |
| `fieldKey`   | `string`                        | ✅       | -             | Unique identifier used for data binding and query construction                                                                                                                                                                                                                                                                                                             |
| `values`     | `unknown`                       | ❌       | -             | Static data source for field options                                                                                                                                                                                                                                                                                                                                       |
| `prefix`     | `string`                        | ❌       | -             | Translation key prefix for localized option values                                                                                                                                                                                                                                                                                                                         |
| `order`      | `number`                        | ❌       | `0`           | Display order priority in filter panel                                                                                                                                                                                                                                                                                                                                     |
| `operator`   | `ComparisonOperator`            | ❌       | -             | Comparison operator for filter logic                                                                                                                                                                                                                                                                                                                                       |
| `valueType`  | `'valueObject'` \| `'property'` | ❌       | `valueObject` | Value interpretation method for filtering                                                                                                                                                                                                                                                                                                                                  |
| `visible`    | `boolean`                       | ❌       | `true`        | Runtime visibility control                                                                                                                                                                                                                                                                                                                                                 |
| `roles`      | `string[]`                      | ❌       | -             | Required user roles for field access                                                                                                                                                                                                                                                                                                                                       |
| `permission` | `string`                        | ❌       | -             | Specific permission requirement                                                                                                                                                                                                                                                                                                                                            |
| `condition`  | `EvaluatedString`               | ❌       | -             | **Jexl expression** evaluated at runtime to determine field visibility. Has access to `values`, `user`, `language`, and `aggregations`. The expression return value is used directly — no variable assignment needed. Example: `"user.role === 'admin' && !isEmpty(values.status)"`. See [Evaluator](#evaluator) section for full syntax reference and built-in functions. |

---

## Field Types

## 1. Aggregation Fields

### `AggregationFieldConfig` interface

```ts
type AggregationFieldConfig = BaseFieldConfig & {
 aggregation: string;
 propertyPath?: string;
 bindLabel?: { ar: string; en: string };
 bindValue?: string;
 dataTransformer?: string;
 sendMode: FieldSendModeType;
 tooltip?: AggregationTooltipType;
 render:
  | CheckboxOptions
  | SwitchOptions
  | RadioOptions
  | DropdownOptions
  | AutocompleteOptions
  | CustomOptions
  | DateListOptions;
};
```

| Property          | Type                         | Required | Default    | Description                                                                                                    |
| ----------------- | ---------------------------- | -------- | ---------- | -------------------------------------------------------------------------------------------------------------- |
| `aggregation`     | `string`                     | ✅       | -          | **Aggregation identifier** that must match a key in the parent component's aggregations input for data binding |
| `sendMode`        | `FieldSendModeType`          | ✅       | -          | **Filter transmission mode** determining how selected values are sent to the backend                           |
| `propertyPath`    | `string`                     | ❌       | `fieldKey` | **Alternative property path** for nested object property access when aggregation field differs from fieldKey   |
| `bindLabel`       | `{ ar: string; en: string }` | ❌       | -          | **Localized property mappings** defining bucket properties containing Arabic and English labels                |
| `bindValue`       | `string`                     | ❌       | `'key'`    | **Value extraction property** specifying which bucket property serves as the filter value                      |
| `dataTransformer` | `string`                     | ❌       | -          | **Transformer function name** registered in `NdfTransformService` for custom bucket data processing            |
| `tooltip`         | `AggregationTooltipType`     | ❌       | -          | **Tooltip configuration** for displaying additional information about filter options                           |
| `render`          | `RenderOptions`              | ✅       | -          | **UI rendering configuration** defining component type and display options                                     |

### `FieldSendModeType` Options

| Mode         | Description                                        | Use Case                           |
| ------------ | -------------------------------------------------- | ---------------------------------- |
| `queryParam` | Sends filter values as URL query parameters        | RESTful APIs, bookmarkable filters |
| `payload`    | Includes filter values in request body             | Complex queries, large filter sets |
| `custom`     | Delegates filter handling to custom implementation | Specialized filtering logic        |

## Render Options

#### `CheckboxOptions`

```ts
type CheckboxOptions = {
 type: 'checkbox';
 options?: {
  showTotal?: boolean; // Display document count
  filter?: boolean; // Enable search within options
  collapse?: boolean; // Collapsible option list
  minVisibleCount?: number; // Items shown before collapse
  expandedCount?: number; // Items shown when expanded
  hideLabel?: boolean; // Hide field label
  sort?: boolean; // Sort options alphabetically
  search?: SearchConfig; // Advanced search configuration
 };
};
```

#### `SwitchOptions`

```typescript
type SwitchOptions = {
 type: 'switch';
 options?: {
  showTotal?: boolean; // Display document count
  filter?: boolean; // Enable search within options
  collapse?: boolean; // Collapsible option list
  multiple?: boolean; // Allow multiple selections
  hideLabel?: boolean; // Hide field label
  sort?: boolean; // Sort options alphabetically
  search?: SearchConfig; // Advanced search configuration
 };
};
```

#### `RadioOptions`

```typescript
type RadioOptions = {
 type: 'radio';
 options?: {
  showTotal?: boolean; // Display document count
  hideLabel?: boolean; // Hide field label
  sort?: boolean; // Sort options alphabetically
 };
};
```

#### `DropdownOptions`

```typescript
type DropdownOptions = {
 type: 'dropdown';
 options?: {
  showTotal?: boolean; // Display document count in options
  multiple?: boolean; // Allow multiple selections
  hideLabel?: boolean; // Hide field label
 };
};
```

#### `AutocompleteOptions`

```typescript
type AutocompleteOptions = {
 type: 'autocomplete';
 options?: {
  showTotal?: boolean; // Display document count
  multiple?: boolean; // Allow multiple selections
  hideLabel?: boolean; // Hide field label
  minChars?: number; // Minimum characters for search
  debounceTime?: number; // Search delay in milliseconds
 };
};
```

#### `DateListOptions`

```typescript
type DateListOptions = {
 type: 'dateList';
 options?: {
  showTotal?: boolean; // Display document count
  format?: string; // Date display format
  groupBy?: 'year' | 'month' | 'day'; // Date grouping
  hideLabel?: boolean; // Hide field label
 };
};
```

#### `CustomOptions`

```typescript
type CustomOptions = {
 type: 'custom';
 options?: Record<string, any>;
};
```

## Tooltip Configuration

```typescript
type AggregationTooltipType = {
 properties: Record<string, any>;
} & (TooltipPlainText | TooltipLocalizedText | TooltipFormattedDate | TooltipTranslationKey | TooltipTranslatedDate);

type TooltipPlainText = { type: 'text'; separator?: string };
type TooltipLocalizedText = { type: 'localizeValue'; translateKey: string };
type TooltipFormattedDate = {
 type: 'date';
 format: string;
 separator?: string;
};
type TooltipTranslationKey = {
 type: 'translate';
 prefix: string;
 separator?: string;
};
type TooltipTranslatedDate = {
 type: 'translatedDate';
 format: string;
 translateKey: string;
};
```

## Field Search Configuration

```ts
type SearchConfig = {
 placeholder?: string;
 query: {
  field?: string;
  method?: 'get' | 'post';
  url: string;
  operator?: ComparisonOperator;
  template?: EvaluatedString;
  params?: Record<string | number, string | number>;
  headers?: Record<string | number, string | number>;
 };
};
```

The `template` property supports `{{variableName}}` interpolation. The most common variable is `searchText`:

```typescript
"dc:title ILIKE '{{searchText}}%'";
```

## 2. Predicate Fields

### `PredicateFieldConfig` interface

```ts
type PredicateFieldConfig = BaseFieldConfig & {
 sendMode: Exclude<FieldSendModeType, 'custom'>;
 render: InputOptions | DateInputOptions;
};
```

#### `InputOptions`

```typescript
type InputOptions = {
 type: 'input';
 options?: {
  hideLabel?: boolean;
  inputType?: 'text' | 'search' | 'url';
  placeholder?: string;
  debounceTime?: number;
  mask?: InputMaskConfig;
  suffix?: InputSuffixConfig;
 };
};
```

## 3. Custom Fields

### `CustomFieldConfig` interface

```ts
type CustomFieldConfig = BaseFieldConfig & {
 sendMode: Exclude<FieldSendModeType, 'custom'>;
 render: ActiveUserSwitcherOptions | AggregationGroupOptions;
};
```

---

# Utilities & Advanced Features

## Query Encoding & Decoding

The `FilterQueryService` serializes and deserializes filter states into compact, URL-safe strings.

> **Note:** Call `registerKeys()` in your `CoreModule` or `AppModule` before using encode/decode.

```ts
// Register key mappings
this.filterQueryService.registerKeys({
 'ecm:primaryType': 'EPT',
 'requestcase:requestNumber': 'RRN'
});

// Encode
const encoded = this.filterQueryService.encodeQuery({
 'ecm:primaryType': ['Case'],
 'requestcase:requestNumber': { value: '12345', operator: 'EQUALS' }
});

// Safe decode
const decoded = this.filterQueryService.decodeQuery(encoded) || {};
```

---

## Evaluator

Field `condition` expressions are evaluated using **jexl** — a lightweight, safe expression language. The service runs on an **isolated jexl instance**, so all registrations are scoped and do not affect global state.

### Expression Syntax

Jexl expressions return their value directly. No variable assignment or wrapper needed.

```ts
// ✅ Correct
"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                 |

### 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 — useful when ternary readability is poor         |
| `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;
>    }
>   }
>  ]);
> }
> ```

### Expression Examples

```ts
// Role check
"user.role == 'admin'";

// Filter value presence
'!isEmpty(values.status)';

// Safe nested access
"get(values, 'doc:status') == 'active'";

// Year offset calculation
"currentYear() - toNumber(split(value, '+')[1])";

// ISO date comparison
'now() > values.expiryDate';

// Math
'round(abs(values.balance))';

// Inline conditional
"if(isEmpty(values.status), 'default', values.status)";

// Aggregation bucket check
'!isEmpty(aggregations.priority_agg.buckets)';

// Combined condition
"user.role == 'admin' && !isNil(values.priority)";

// Debug mid-expression (development only)
"debug(values['ecm:currentLifeCycleState']) == 'active'";
```

### No Method Chaining on Returned Values

Jexl cannot chain methods on values returned from functions. Wrap the full operation inside the registered function instead:

```ts
// ❌ Won't work
'now().getFullYear()';

// ✅ Use dedicated built-in
'currentYear()';
```

### Registering Custom Functions

```ts
// Individual functions
this.ndfEvaluatorService.registerFunctions([
 {
  name: 'translate',
  fn: (key: string) => this.translateService.instant(key)
 },
 {
  name: 'resolve',
  fn: (name: string) => this.chartPluginsCallbacks.get(name)
 }
]);

// Functions and transformers together
this.ndfEvaluatorService.register({
 functions: [
  {
   name: 'translate',
   fn: (key: string) => this.translateService.instant(key)
  }
 ],
 transformers: [{ name: 'uppercase', fn: (val: string) => val.toUpperCase() }]
});
```

### `JexlEvaluator` Type

```ts
export type JexlEvaluator = {
 name: string;
 fn: (...args: any[]) => any;
};
```

---

## Troubleshooting

### 1. Transformer Not Found

**Error:** `No transformer defined for type 'subject'`

```typescript
ndfTransformService.register('subject', (keys) => {});
```

### 2. Query Not Encoding

**Error:** `Query key mapping not found for 'SOME KEY'`

```typescript
filterQueryService.registerKey('long Key', 'short Key');
```

### 3. Field Condition Not Applied

```ts
// ❌ Old syntax
"show = values && values['any']?.includes('some');";

// ✅ New syntax
"!isEmpty(values['any']) && values['any'].includes('some')";
```

### 4. Expression Returns `null` Unexpectedly

Check the browser console for `[NdfEvaluator] evalSync error`. Use `debug()` to inspect intermediate values:

```ts
"debug(values['status']) === 'active'";
```

### 5. Method Chaining Error

**Error:** `Jexl Function getFullYear is not defined`

Jexl cannot call methods on objects returned from functions. Use a dedicated registered function:

```ts
// ❌ Won't work
'now().getFullYear()';

// ✅ Use built-in
'currentYear()';
```

### 6. Custom Function Not Available in Expression

Register the function before the expression is evaluated:

```ts
this.ndfEvaluatorService.registerFunctions([{ name: 'myFn', fn: myFunction }]);
```
