# Customers Module

# Customers Module

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

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

- [src/modules/customers/customers_dal.ts](src/modules/customers/customers_dal.ts)
- [src/modules/customers/router.ts](src/modules/customers/router.ts)

</details>



The **Customers Module** provides a comprehensive API for managing customer records, including advanced searching, filtering, bulk operations, and audit trail tracking. It is built upon the `CustomerEntity` [src/modules/customers/customer_entity.ts:13-100](), which maps the domain model to the underlying PostgreSQL schema.

This module is split into two primary layers:
1.  **REST Router**: Handles HTTP request validation, RBAC enforcement, and response formatting.
2.  **Data Access Layer (DAL)**: Encapsulates complex SQL generation, ILIKE search logic, and streaming for exports.

### System Architecture Overview

The following diagram illustrates the relationship between the API endpoints, the logic layer, and the database entities.

**Customer Module Component Map**
```mermaid
graph TD
    subgraph "Natural Language Space"
        API["Customer API Endpoints"]
        Search["Advanced Search & Filters"]
        Bulk["Bulk Actions"]
        Export["Data Export"]
    end

    subgraph "Code Entity Space (src/modules/customers/)"
        Router["router.ts: customersRouter()"]
        DAL["customers_dal.ts: CustomersDal"]
        Entity["customer_entity.ts: CustomerEntity"]
        DTO["dto.ts: CustomerListQuerySchema"]
    end

    API --> Router
    Router --> DTO
    Router --> DAL
    DAL --> Entity
    Search --> DAL
    Bulk --> DAL
    Export --> DAL
```
Sources: [src/modules/customers/router.ts:38-48](), [src/modules/customers/customers_dal.ts:207-214](), [src/modules/customers/customer_entity.ts:13-15]()

---

### Key Functional Areas

#### 1. Customers API Router
The router defines the public surface of the module. It utilizes `rbacHandler` to enforce permissions such as `CUSTOMERS_READ_ALL` and `CUSTOMERS_WRITE` [src/modules/customers/router.ts:84-85](). It also manages metadata for the frontend, providing column configurations and default sort orders [src/modules/customers/router.ts:54-80]().

**Core Responsibilities:**
*   **Validation**: Uses Zod schemas (e.g., `CustomerListQuerySchema`) to validate incoming request data [src/modules/customers/router.ts:85]().
*   **Bulk Processing**: Leverages `runBulkAction` for efficient deletion, restoration, and duplication of multiple records [src/modules/customers/router.ts:253-276]().
*   **Streaming Exports**: Proxies data from the DAL to the `exportDataWithTemplateToStream` utility to generate XLSX, CSV, or HTML files [src/modules/customers/router.ts:152-214]().

For detailed endpoint documentation, see **[Customers API Router](#4.1)**.

#### 2. Customers Data Access Layer (DAL)
The `CustomersDal` class handles the translation of high-level search queries into optimized SQL. It extends the system's base `Repository` to provide specialized customer logic [src/modules/customers/customers_dal.ts:207-212]().

**Data Flow Association**
```mermaid
graph LR
    subgraph "Input"
        Req["Raw Query / JSON"]
    end

    subgraph "Processing (CustomersDal)"
        Ilike["buildIlikeNeedleFromSearch()"]
        Filter["translateFilterConditions()"]
        Repo["Repository.findByPage()"]
    end

    subgraph "Storage"
        DB[("PostgreSQL Table: customers")]
    end

    Req --> Ilike
    Ilike --> Filter
    Filter --> Repo
    Repo --> DB
```
Sources: [src/modules/customers/customers_dal.ts:19-54](), [src/modules/customers/customers_dal.ts:63-140](), [src/modules/customers/customers_dal.ts:285-334]()

**Core Responsibilities:**
*   **Search Pipeline**: Implements a custom ILIKE needle builder to handle escaped wildcards and pattern matching [src/modules/customers/customers_dal.ts:19-54]().
*   **Advanced Filtering**: Translates complex UI filter conditions (e.g., `BETWEEN`, `IN`, `ILIKE`) into the internal Query DSL [src/modules/customers/customers_dal.ts:63-140]().
*   **Soft-Delete Lifecycle**: Manages `deleted_at` timestamps to allow for record restoration [src/modules/customers/customers_dal.ts:511-536]().
*   **Audit Integration**: Works with the `AuditService` to log changes and retrieve historical versions of customer records [src/modules/customers/customers_dal.ts:566-600]().

For details on the search pipeline and query construction, see **[Customers Data Access Layer](#4.2)**.

---

### Entity Metadata
The customer entity includes standard fields (name, email, phone) as well as auditing fields.

| Field | Type | Role |
| :--- | :--- | :--- |
| `uuid` | UUID | Primary Key (Client-side generated) |
| `code` | String | Unique business identifier |
| `status` | Enum | Active, Inactive, Lead, etc. |
| `version` | Number | Optimistic concurrency control |
| `deleted_at` | Date | Soft-delete timestamp |

Sources: [src/modules/customers/customer_entity.ts:13-100](), [src/modules/customers/customers_dal.ts:142-166]()

---
