# Export Library

# Export Library

<details>
<summary>Relevant source files</summary>

The following files were used as context for generating this wiki page:

- [src/i18n/en-GB.json](src/i18n/en-GB.json)
- [src/i18n/it-IT.json](src/i18n/it-IT.json)
- [src/lib/export/README.md](src/lib/export/README.md)
- [src/lib/export/example.ts](src/lib/export/example.ts)
- [src/lib/export/helpers.ts](src/lib/export/helpers.ts)
- [src/lib/export/index.ts](src/lib/export/index.ts)
- [src/lib/export/types.ts](src/lib/export/types.ts)
- [templates/customer_export_template.html](templates/customer_export_template.html)
- [templates/customer_export_template.xlsx](templates/customer_export_template.xlsx)
- [templates/customer_export_template_2.xlsx](templates/customer_export_template_2.xlsx)

</details>



The Export Library is a template-based streaming system designed to generate high-volume XLSX and CSV files with constant memory usage [src/lib/export/README.md:3-7](). It supports locale-aware formatting, timezone conversions, and dynamic field mapping through a declarative configuration [src/lib/export/README.md:9-12]().

## System Architecture

The library operates in two distinct phases to ensure performance and layout fidelity. It leverages `ExcelJS` for spreadsheet manipulation and `Handlebars` for HTML-based exports [src/lib/export/index.ts:1-5]().

### Data Flow and Processing

1.  **Template Scanning**: The system reads the provided `.xlsx` template to identify placeholders and capture styles [src/lib/export/index.ts:131-150]().
2.  **Streaming Generation**: It initializes `ExcelJS.stream.xlsx.WorkbookWriter` to process data row-by-row, ensuring the server does not buffer large datasets in RAM [src/lib/export/index.ts:200-205]().

### Logic Entity Bridge: Export Components

The following diagram maps the logical export concepts to the specific TypeScript entities and interfaces defined in the codebase.

```mermaid
graph TD
    subgraph "Natural Language Space"
        Template["Excel Template (.xlsx)"]
        Locale["Locale (e.g., it-IT)"]
        DataStream["Data Source"]
        Config["Export Settings"]
    end

    subgraph "Code Entity Space"
        ExportConfig["interface ExportConfig"]
        ExportMetadata["interface ExportFieldMetadata"]
        HelperFuncs["helpers.ts (Intl Formatting)"]
        MainFunc["exportDataWithTemplate()"]
    end

    Template --> MainFunc
    Config --> ExportConfig
    Locale --> HelperFuncs
    DataStream --> ExportConfig
    ExportConfig --> MainFunc
    ExportMetadata --> ExportConfig
```
**Sources:** [src/lib/export/types.ts:7-37](), [src/lib/export/index.ts:111-124](), [src/lib/export/helpers.ts:1-3]()

## Placeholder Syntax

The library uses a specific placeholder syntax within Excel templates to define where data and translations should be injected.

| Syntax | Type | Description | Example |
| :--- | :--- | :--- | :--- |
| `{?field}` | **Scalar** | Injects a single value from translations or static data. Used for headers/titles. | `{?report_title}` [src/lib/export/README.md:16-24]() |
| `{#field}` | **Loop** | Defines a vertical data loop. The row containing this tag becomes the template for all data rows. | `{#first_name}` [src/lib/export/README.md:26-34]() |

### Template Pre-processing
For HTML exports, the library converts these custom tags into standard Handlebars syntax using regex [src/lib/export/index.ts:34-43]().
*   `{#field}` becomes `{{field}}`
*   `{?field}` becomes `{{field}}`

## Locale-Aware Formatting

The library uses the `Intl` API to dynamically generate Excel format patterns and HTML strings based on the user's locale [src/lib/export/helpers.ts:5-10]().

### Supported Field Types
The `ExportFieldMetadata` interface defines how fields are processed [src/lib/export/types.ts:7-12]():

*   **`string`**: Plain text.
*   **`number`**: Numeric values with configurable `precision` [src/lib/export/helpers.ts:45-49]().
*   **`date` / `datetime`**: Formatted using locale patterns (e.g., `dd/mm/yyyy`). Supports IANA timezones via `timezoneField` [src/lib/export/helpers.ts:10-38]().
*   **`currency`**: Automatically places currency symbols based on locale and ISO codes (e.g., `€` vs `$`) [src/lib/export/helpers.ts:58-74]().
*   **`percentage`**: Multiplies by 100 and appends `%` [src/lib/export/helpers.ts:81-84]().

**Sources:** [src/lib/export/types.ts:7-12](), [src/lib/export/helpers.ts:1-214]()

## Implementation Details

### Execution Flow: `exportDataWithTemplate`

This function is the primary entry point for the export system [src/lib/export/index.ts:111-115]().

```mermaid
sequenceDiagram
    participant App as Caller
    participant Lib as exportDataWithTemplate
    participant Tpl as Template Scanner
    participant Writer as WorkbookWriter (Stream)

    App->>Lib: Call with TemplatePath, OutputPaths, Config
    Lib->>Lib: loadTranslations(locale)
    Lib->>Tpl: readFile(templatePath)
    Tpl-->>Lib: Identify dataStartRow & colMapping
    Lib->>Writer: Initialize XLSX & CSV Streams
    loop For each record in config.data
        Lib->>Lib: applyTimezone() & format values
        Lib->>Writer: writeRow(formattedData)
    end
    Lib->>Writer: commit()
    Lib-->>App: Export Complete
```
**Sources:** [src/lib/export/index.ts:111-209](), [src/lib/export/helpers.ts:93-112]()

### Field Mapping
The `fieldMapping` object allows decoupling the template's placeholder names from the actual database/JSON property names [src/lib/export/index.ts:67-69]().
*   **Example**: Mapping `codice_cliente` in the template to the `id` property in the data source [src/lib/export/example.ts:45-46]().

### Timezone Handling
1.  If a field has a `timezoneField` defined in metadata, the library uses the value from that specific record [src/lib/export/example.ts:63-67]().
2.  Otherwise, it falls back to the `defaultTimezone` provided in the `ExportConfig` [src/lib/export/helpers.ts:93-95]().

## Customer Export Templates

The system includes pre-defined templates for customer data:
*   **Excel**: `templates/customer_export_template.xlsx` [templates/customer_export_template.xlsx:1]()
*   **HTML/PDF**: `templates/customer_export_template.html`. This template uses a CSS-heavy approach to ensure A4 print compatibility and styled table headers (`#2B4C7E`) [templates/customer_export_template.html:2-68](). It iterates through `{{#each data}}` to populate rows [templates/customer_export_template.html:80-87]().

**Sources:** [src/lib/export/index.ts:1-210](), [src/lib/export/types.ts:1-48](), [src/lib/export/helpers.ts:1-215](), [templates/customer_export_template.html:1-88]()

---
