# Project Structure

# Project Structure

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

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

- [.devin/rules/code-guardrails.md](.devin/rules/code-guardrails.md)
- [.devin/rules/file-operations.md](.devin/rules/file-operations.md)
- [.devin/rules/temp-files.md](.devin/rules/temp-files.md)
- [.devin/rules/workflow.md](.devin/rules/workflow.md)
- [package.json](package.json)
- [src/domain/entities/registry.ts](src/domain/entities/registry.ts)
- [src/index.ts](src/index.ts)
- [src/modules/system/service_registry_entity.ts](src/modules/system/service_registry_entity.ts)

</details>



This page documents the directory layout and architectural conventions of the Primebrick v3 backend. The project follows a modular monolith approach, separating domain logic, infrastructure, and feature modules to ensure maintainability and type safety.

## Directory Overview

The codebase is organized into functional areas that separate infrastructure, shared domain logic, and feature-specific modules.

| Directory | Purpose | Key Contents |
| :--- | :--- | :--- |
| `src/modules` | Feature-based vertical slices | Routers, DALs, and Entities for Customers, Auth, etc. |
| `src/domain` | Shared domain infrastructure | Entity decorators, the global registry, and core interfaces. |
| `src/db` | Database infrastructure | Connection pooling and migration management logic. |
| `src/http` | Cross-cutting HTTP concerns | Global error handlers and protected router factories. |
| `src/lib` | Shared utility libraries | Export engines, delta calculators, and audit services. |
| `scripts` | Maintenance & Dev tooling | Database migration runners, seeding scripts, and Casdoor setup. |
| `infra` | DevOps & Environment | Docker Compose configurations for local development. |
| `templates` | File generation assets | Export templates (XLSX/CSV) and Handlebars files. |

**Sources:** [src/index.ts:4-17](), [src/domain/entities/registry.ts:8-12](), [package.json:14-18]()

---

## The Module System (`src/modules`)

Each directory within `src/modules` represents a self-contained feature area. A standard module typically contains:
*   **Router**: Defines REST endpoints and applies RBAC middleware [src/modules/customers/router.ts]().
*   **DAL (Data Access Layer)**: Handles SQL generation and database interactions.
*   **Entity**: Defines the TypeScript class and PostgreSQL table mapping using decorators [src/modules/customers/customer_entity.ts]().

### Data Flow within a Module

The following diagram illustrates how a request flows through a typical module (e.g., `customers`).

**Request Processing Pipeline**
```mermaid
graph TD
    subgraph "Express Layer"
        A["Client Request"] --> B["app.use('/api/v1', ...)"]
        B --> C["rbacHandler(Permission)"]
    end

    subgraph "Module: Customers"
        C --> D["customersRouter"]
        D --> E["CustomersDal"]
        E --> F["Repository&lt;CustomerEntity&gt;"]
    end

    subgraph "Database"
        F --> G[("PostgreSQL")]
    end

    E -.-> H["AuditService"]
    H -.-> G
```
**Sources:** [src/index.ts:163-181](), [src/modules/auth/rbac.middleware.js:15]()

---

## Shared Domain & Registry (`src/domain`)

The `src/domain` directory contains the core metadata system. The backend uses a decorator-based approach to define database schemas directly in TypeScript classes.

*   **`ENTITY_REGISTRY`**: A centralized array in `src/domain/entities/registry.ts` that must include every `@Entity` class. This registry is consumed by the database patch tooling to compare the code-defined schema against the live database [src/domain/entities/registry.ts:1-21]().
*   **Decorators**: Located in `src/domain/entities/entity-meta.js`, these include `@Entity`, `@Column`, `@Key`, and `@AuditableField` [src/modules/system/service_registry_entity.ts:2-9]().

**Entity-to-Database Mapping**
```mermaid
classDiagram
    class ENTITY_REGISTRY {
        +CustomerEntity
        +UserProfileEntity
        +OrganizationEntity
    }
    class EntityDecorator {
        +tableName: string
    }
    class ColumnDecorator {
        +pgType: string
        +nullable: boolean
    }
    ENTITY_REGISTRY ..> EntityDecorator : defines
    EntityDecorator ..> ColumnDecorator : contains
```
**Sources:** [src/domain/entities/registry.ts:14-20](), [src/modules/system/service_registry_entity.ts:11-42]()

---

## Database Infrastructure (`src/db` & `db-meta`)

Database management is split between runtime connection handling and build-time metadata comparison.

*   **`src/db/pool.js`**: Manages the `pg.Pool` instance used by the entire application [src/index.ts:12]().
*   **`db-meta`**: (Implicitly referenced via scripts) Stores JSON snapshots of the database schema.
*   **Scripts**: 
    *   `db:meta:compare`: Compares `ENTITY_REGISTRY` against the current DB state [package.json:14]().
    *   `db:migrate`: Applies SQL patches to synchronize the schema [package.json:15]().

---

## Entry Point and Middleware Pipeline

The application entry point is `src/index.ts`. It initializes the Express server and mounts global middleware before attaching module routers.

### Initialization Sequence
1.  **Middleware Setup**: CORS, JSON parsing, and Cookie Parser are applied [src/index.ts:27-29]().
2.  **Health Check**: A public `/api/v1/health` endpoint is mounted to verify Database and IDP (Casdoor) status [src/index.ts:154-156]().
3.  **OpenAPI**: The `openApiRouter` is mounted to serve documentation [src/index.ts:161]().
4.  **Auth & RBAC**: The `authRouter` handles logins, while `makeProtectedRouter` provides a guarded space for feature modules [src/index.ts:164-180]().
5.  **Role Mapping**: On startup, `loadRoleMappings()` is called to cache RBAC configurations from the database [src/index.ts:184]().

**Sources:** [src/index.ts:24-189]()

---

## Utility Scripts (`scripts/`)

The `scripts` directory contains essential operational tools:
*   **IDP Setup**: `setup-casdoor.ts` bootstraps the authentication provider [package.json:18]().
*   **Data Seeding**: `seed-customers.ts` and `truncate-customers.ts` manage test data for the CRM module [package.json:16-17]().
*   **Dev Ops**: `kill-port-3001.mjs` handles cleanup of hung dev processes [package.json:8]().

**Sources:** [package.json:6-19]()

---
