# NexusCRM Architecture

**Version**: 2026.1 (Strict)
**Status**: Stable, Audited

## Vision

NexusCRM is a **Metadata-Driven CRM Platform** built on strict Clean Architecture principles. It enforces a **Single Source of Truth (SSoT)** for all definitions, ensuring zero drift between Frontend, Backend, and Database.

- **Backend**: Go (Modular Monolith, Hexagonal Architecture)
- **Frontend**: React + Vite (Modern Stack)
- **Database**: TiDB Cloud (MySQL 8.0 Compatible)
- **Protocol**: REST (Native Salesforce Compatible)

---

## 1. High-Level Architecture

```mermaid
graph TD
    User([User / Browser]) -->|HTTPS / JSON| LoadBalancer
    LoadBalancer -->|Traffic| Backend
    
    subgraph "Frontend (React)"
        Store[Zustand Store] -->|Hooks| Components
        Components -->|QueryClient| APIClient
        APIClient -->|Axios| Backend
    end

    subgraph "Backend (Go)"
        Middleware[Middleware Layer] -->|Request ID| Handler[Interface Layer]
        Handler -->|DTO| Service[Application Layer]
        Service -->|Domain Objects| Domain[Domain Layer]
        Service -->|Repository Interface| Infra[Infrastructure Layer]
        Infra -->|MySQL Driver| TiDB[(TiDB Cloud)]
        
        CodeGen[CodeGen Tool] -->|Generates| Shared[Shared Kernel]
        Shared -->|Imports| Backend
        Shared -->|Imports| Frontend
    end
```

---

## 2. Core Pillars

### A. Single Source of Truth (SSoT)
All schema definitions (Objects, Fields, Types) originate from **ONE** location:
- **Source**: `backend/internal/bootstrap/system_tables.json`
- **Tool**: `backend/cmd/codegen`
- **Outputs**:
    1.  **Go Models**: `shared/pkg/models`
    2.  **Go Constants**: `shared/pkg/constants`
    3.  **TS Types**: `frontend/src/generated-schema.ts`

> **Rule**: Never manually modify generated files. Update `system_tables.json` and run `make generate`.

### B. Clean Architecture (Hexagonal)
The backend is strictly layered. Dependencies point **INWARD**.

1.  **Domain Layer** (`internal/domain`):
    -   **Pure Go**. No external dependencies (no SQL, no HTTP).
    -   Contains Entities and **Ports** (Interfaces) for infrastructure.
2.  **Application Layer** (`internal/application`):
    -   Orchestrates Use Cases.
    -   Depends on Domain. Implements Logic.
3.  **Interface Layer** (`internal/interfaces`):
    -   Delivery mechanics (REST, CLI).
    -   Converts HTTP to Domain objects.
4.  **Infrastructure Layer** (`internal/infrastructure`):
    -   Implements Domain Ports (`persistence`, `database`).
    -   Depends on External Libs (TiDB, Redis, etc.).

### C. Observability "Golden Thread"
Every request is traceable end-to-end.

1.  **Entry**: `middleware.RequestID()` generates specific UUID (`X-Request-ID`).
2.  **Context**: UUID is injected into `context.Context`.
3.  **Logs**: `LoggerService` automatically includes Request ID in all logs.
4.  **Errors**: All `AppError` responses include `request_id` for debugging.
5.  **Frontend**: `QueryClient` captures `request_id` on error and logs it to console/server.

---

## 3. Key Mechanisms

### Transactional Outbox (Event Bus)
To ensure data consistency between Database and Async Workers:
1.  **Write**: Application writes to `Table` AND `OutboxEvent` table in the **SAME Transaction**.
2.  **Poll**: `OutboxService` (Worker) polls `OutboxEvent` table (500ms).
3.  **Publish**: Worker pushes payload to Event Handler.
4.  **Ack**: Worker marks event as `Processed` (atomic).

### Metadata Engine
The system is self-describing.
-   **Schema**: Stored in `_System_Object` and `_System_Field`.
-   **Validation**: Loaded from `_System_Validation` into Memory Cache.
-   **UI**: Layouts stored in `_System_Layout` and rendered dynamically by Frontend `MetadataRenderer`.

### Error Handling Standard
-   **Backend**: `pkg/errors` defines standardized error codes (e.g., `INVALID_INPUT`, `UNAUTHORIZED`).
-   **Response**: `{ "error": { "code": "...", "message": "...", "request_id": "..." } }`
-   **Panic Safety**: `middleware.Recovery` catches panics, logs stack with Request ID, and returns safe 500 error.

---

## 4. System Field Architecture (Salesforce Native Schema)

After the 2026 refactor, physical database column names are **identical** to their logical Salesforce API names. There is no translation layer between the database and the API — the system achieves 100% Salesforce v63.0 REST wire-protocol parity.
