# Overview

# Overview

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

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

- [AGENTS.md](AGENTS.md)
- [README.md](README.md)
- [docs/gitflow.md](docs/gitflow.md)
- [package.json](package.json)
- [src/domain/entities/registry.ts](src/domain/entities/registry.ts)
- [src/index.ts](src/index.ts)

</details>



The Primebrick backend is a high-performance API designed to manage CRM and organizational data with a focus on auditability, type safety, and robust Role-Based Access Control (RBAC). It serves as the central data authority for the Primebrick ecosystem, integrating with Casdoor for identity management and PostgreSQL for persistent storage.

## Purpose and Scope

The API provides a suite of services for managing customers, organizations, and user profiles. Its architecture is built around a custom-designed Domain Entity System that bridges TypeScript classes with a PostgreSQL schema, featuring an automated migration and patching system to ensure database consistency.

Key capabilities include:
- **Audit Trails**: Automatic tracking of field-level changes (deltas) for sensitive entities.
- **Identity Integration**: Seamless authentication and role synchronization with Casdoor IDP.
- **Data Portability**: Template-based streaming exports for large datasets (XLSX/CSV).
- **Schema Management**: A snapshot-based diffing tool to synchronize code-defined entities with the database.

## Technology Stack

The project leverages a modern TypeScript stack with the following core components:

| Category | Technology | Usage |
| :--- | :--- | :--- |
| **Runtime** | [Node.js](https://nodejs.org/) | Core execution environment using ES Modules [package.json:5](). |
| **Language** | [TypeScript](https://www.typescriptlang.org/) | Static typing and decorator-based metadata [package.json:41](). |
| **Web Framework** | [Express](https://expressjs.com/) | REST API routing and middleware pipeline [package.json:26](). |
| **Database** | [PostgreSQL 18](https://www.postgresql.org/) | Relational storage and JSONB support [AGENTS.md:30](). |
| **Identity/Auth** | [Casdoor](https://casdoor.org/) | OIDC provider and role management [package.json:21](). |
| **Validation** | [Zod](https://zod.dev/) | Runtime schema validation [package.json:32](). |

Sources: [package.json:1-43](), [AGENTS.md:28-31](), [src/index.ts:1-30]()

## High-Level Architecture

The system follows a modular architecture where domain logic is encapsulated within specific modules (e.g., `customers`, `auth`). A centralized `ENTITY_REGISTRY` serves as the source of truth for the database schema.

### System Mapping: Logic to Code

The following diagram illustrates how high-level system concepts map to specific code entities within the repository.

**Diagram: Entity and Service Mapping**
```mermaid
graph TD
    subgraph "Natural Language Space"
        A["API Server"]
        B["Database Schema"]
        C["User Permissions"]
        D["Data Audit"]
    end

    subgraph "Code Entity Space"
        A1["src/index.ts"]
        B1["src/domain/entities/registry.ts"]
        C1["src/modules/auth/permissions.ts"]
        D1["src/modules/audit/audit_service.ts"]
    end

    A -- "Entry Point" --> A1
    B -- "ENTITY_REGISTRY" --> B1
    C -- "Permission Enum" --> C1
    D -- "AuditService" --> D1
```
Sources: [src/index.ts:24-189](), [src/domain/entities/registry.ts:1-21](), [AGENTS.md:75-120]()

### Request Flow and Middleware

Every request passing through the `primebrick-api` follows a structured pipeline from the Express application instance to the final route handler.

**Diagram: Request Processing Pipeline**
```mermaid
sequenceDiagram
    participant Client
    participant Express as "Express App [src/index.ts]"
    participant Auth as "AuthMiddleware"
    participant RBAC as "rbacHandler"
    participant Router as "Module Router"

    Client->>Express: HTTP Request
    Express->>Express: JSON/Cookie Parsing
    Express->>Auth: JWT Validation & Role Expansion
    Auth->>RBAC: Permission Check (isPermissionGranted)
    RBAC->>Router: Execute Handler
    Router-->>Client: JSON Response / Error
```
Sources: [src/index.ts:27-30](), [src/index.ts:164-181](), [AGENTS.md:120-138]()

## Key Architectural Patterns

1.  **Decorator-Driven Entities**: Database tables are defined using TypeScript decorators (e.g., `@Entity`, `@Column`). These are registered in the `ENTITY_REGISTRY` [src/domain/entities/registry.ts:14-20]().
2.  **Wildcard RBAC**: Permissions are structured in dot-notation (e.g., `customers.read.*`) and matched against user roles at runtime [AGENTS.md:79-110]().
3.  **Patch-Based Migrations**: Instead of traditional migration files, the system generates SQL patches by comparing code entities against the live database schema [AGENTS.md:50-54]().
4.  **Health-Aware Routing**: The system includes a sophisticated health check that monitors both the database connection and the Casdoor IDP status [src/index.ts:31-156]().

## Navigation Guide

To explore the codebase and setup your environment, follow these guides:

*   **[Getting Started](#1.1)**: Step-by-step guide for setting up the local development environment, including Docker infrastructure and database initialization.
*   **[Project Structure](#1.2)**: Explains the directory layout and the conventions governing the `src/modules`, `src/db`, and `src/domain` directories.
*   **Core Architecture**: Detailed breakdown of the server bootstrap process and the Entity/Repository system.
*   **Authentication and Authorization**: Deep dive into Casdoor integration and the wildcard-based RBAC system.
*   **Audit System**: Documentation on how the system calculates and stores field-level changes.

Sources: [package.json:6-18](), [AGENTS.md:1-27](), [docs/gitflow.md:1-113]()

---
