# Customer List & CRM

# Customer List & CRM

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

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

- [src/lib/entity-list/sheets/panels/FiltersPanel.svelte](src/lib/entity-list/sheets/panels/FiltersPanel.svelte)
- [src/lib/entity-list/types.ts](src/lib/entity-list/types.ts)
- [src/lib/i18n/date-format.ts](src/lib/i18n/date-format.ts)
- [src/routes/(app)/crm/pipeline/+page.svelte](src/routes/(app)/crm/pipeline/+page.svelte)
- [src/routes/(app)/customers/+page.svelte](src/routes/(app)/customers/+page.svelte)

</details>



The Customer List and CRM module provides the primary interface for managing customer entities and tracking sales pipelines. It leverages the `EntityListTable` architecture for high-performance data grids, featuring advanced server-side filtering, metadata-driven UI configuration, and robust state persistence.

## Customer List Architecture

The `/customers` route is a specialized implementation of the entity list pattern. It manages the lifecycle of customer data from metadata retrieval to paginated row loading.

### Lifecycle and Data Flow

The route follows a strict loading sequence: `loadMeta` (UI configuration) followed by `loadRows` (data).

1.  **Metadata Caching**: To prevent redundant API calls during navigation or HMR, customer metadata is cached in `globalThis.__pbCustomerMetaCache` [src/routes/(app)/customers/+page.svelte:149-163]().
2.  **State Restoration**: Upon mounting, the component restores `visibleKeys`, `sortKey`, and `searchInKeys` from `sessionStorage` [src/routes/(app)/customers/+page.svelte:107-111]().
3.  **Connectivity Recovery**: The route listens for `onConnectivityRestored` events to automatically refresh data after a network outage [src/routes/(app)/customers/+page.svelte:273-276]().

### Metadata and Row Lifecycle

The following diagram illustrates the initialization and data fetching sequence for the Customer List.

**Customer List Initialization Sequence**
```mermaid
sequenceDiagram
    participant B as Browser/User
    participant C as CustomerPage
    participant G as globalThis Cache
    participant A as API (/api/v1/customers)

    B->>C: Mount /customers
    C->>G: getMetaCache()
    alt Cache Miss
        C->>A: GET /meta
        A-->>C: CustomerMeta
        C->>G: setMetaCache(meta)
    else Cache Hit
        G-->>C: CustomerMeta
    end
    C->>C: restoreSessionState()
    C->>C: ensureVisibleKeys()
    C->>A: GET /rows (params: page, sort, filters)
    A-->>C: ListResponse (rows, total)
    C->>C: Update $state(rows)
```

**Sources:** [src/routes/(app)/customers/+page.svelte:165-244](), [src/routes/(app)/customers/+page.svelte:149-163](), [src/routes/(app)/customers/+page.svelte:107-111]()

---

## Filtering and Search

The module supports three layers of data restriction: global search, standard filters, and advanced logical filters.

### Search Implementation
*   **Search Syntax**: Supports wildcard tokens and field-specific overrides.
*   **Debouncing**: Search input is debounced via a `searchTimer` to prevent excessive API requests while typing [src/routes/(app)/customers/+page.svelte:73-73]().
*   **Search In Keys**: Users can restrict the search to specific columns, persisted in `sessionStorage` [src/routes/(app)/customers/+page.svelte:99-109]().

### Advanced Filters
The `FiltersPanel` provides a UI for complex queries using `AND`/`OR` connectors and various operators (e.g., `BETWEEN`, `contains`, `startsWith`) [src/lib/entity-list/types.ts:136-146]().

| Operator | Applicable Types | Description |
| :--- | :--- | :--- |
| `=` / `!=` | All | Exact match or inequality |
| `contains` | `text` | Substring search |
| `BETWEEN` | `date`, `datetime` | Range selection |
| `>` / `<` | `date`, `datetime`, `number` | Comparison operators |

**Sources:** [src/lib/entity-list/sheets/panels/FiltersPanel.svelte:74-85](), [src/lib/entity-list/types.ts:157-170]()

---

## Connectivity & Error Handling

The Customer List is designed for resilience, handling backend unavailability through the `AppError` system.

*   **RFC 7807 Handling**: API errors are parsed into Problem Details objects. If a fetch fails due to a database being unavailable (`ApiDatabaseUnavailableError`) or the server being unreachable (`ApiUnreachableError`), a `pushImpactError` is triggered with a `HIGH` impact level [src/routes/(app)/customers/+page.svelte:18-19]().
*   **Automatic Retry**: When the `onConnectivityRestored` event fires (managed by the `AppShell` health probe), the page automatically invokes `loadRows()` to refresh the UI [src/routes/(app)/customers/+page.svelte:273-276]().

**Entity State to Code Mapping**
```mermaid
graph TD
    subgraph "Natural Language Space"
        Error["Connection Lost"]
        Retry["Auto Refresh"]
        Meta["UI Config"]
    end

    subgraph "Code Entity Space"
        ApiErr["ApiUnreachableError"]
        ConnRest["onConnectivityRestored"]
        MetaCache["__pbCustomerMetaCache"]
        PushErr["pushImpactError"]
    end

    Error --> ApiErr
    ApiErr --> PushErr
    ConnRest --> Retry
    MetaCache --> Meta
```

**Sources:** [src/routes/(app)/customers/+page.svelte:18-20](), [src/lib/app-connectivity-events.ts](), [src/lib/errors/app-errors.ts]()

---

## Date and Time Localization

The customer list handles complex timezone scenarios, particularly for `datetime` columns.

*   **IANA Toggling**: Users can toggle between `browser` (local) and `record` (stored IANA) timezones for `datetime` columns [src/routes/(app)/customers/+page.svelte:104-105]().
*   **Formatting Pipeline**: Raw values are passed through `formatListCellValue`, which utilizes `Intl.DateTimeFormat` cached by locale tag and timezone [src/lib/i18n/date-format.ts:102-121]().
*   **UTC Normalization**: When applying date filters, values are converted to UTC ISO strings before being sent to the API, ensuring server-side consistency [src/lib/entity-list/sheets/panels/FiltersPanel.svelte:142-145]().

**Sources:** [src/lib/i18n/date-format.ts:4-7](), [src/lib/i18n/date-format.ts:102-121](), [src/lib/entity-list/sheets/panels/FiltersPanel.svelte:134-162]()

---

## CRM Pipeline

The CRM Pipeline (`/crm/pipeline`) serves as a placeholder for the upcoming sales management features.

*   **Structure**: Uses `AppPageScaffold` and `AppPageBreadcrumb` for shell consistency [src/routes/(app)/crm/pipeline/+page.svelte:10-24]().
*   **Navigation**: Integrates with `shellNav.modules` via the `crmModuleMenuSegment` to provide contextual breadcrumbs [src/routes/(app)/crm/pipeline/+page.svelte:15-20]().
*   **Content**: Currently displays static information regarding lead tracking and pipeline stages as defined in the i18n bundles [src/routes/(app)/crm/pipeline/+page.svelte:26-40]().

**Sources:** [src/routes/(app)/crm/pipeline/+page.svelte:1-42](), [src/lib/breadcrumb/crm-breadcrumb.ts]()

---
