# Getting Started

# Getting Started

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

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

- [.githooks/pre-commit](.githooks/pre-commit)
- [AGENTS.md](AGENTS.md)
- [README.md](README.md)
- [docs/gitflow.md](docs/gitflow.md)
- [infra/docker-compose.postgres.yml](infra/docker-compose.postgres.yml)
- [package.json](package.json)
- [scripts/version-sync.mjs](scripts/version-sync.mjs)
- [src/modules/auth/avatar-svg-generator.ts](src/modules/auth/avatar-svg-generator.ts)
- [src/modules/customers/list-config.ts](src/modules/customers/list-config.ts)
- [src/openapi/openapi.ts](src/openapi/openapi.ts)

</details>



This page provides a step-by-step guide for setting up the Primebrick backend development environment. It covers prerequisites, infrastructure orchestration via Docker, environment configuration, and database initialization.

## Prerequisites

Before starting, ensure the following tools are installed on your system:

*   **Node.js**: Version 20 or higher (recommended).
*   **pnpm**: Fast, disk space efficient package manager.
*   **Docker & Docker Compose**: Required for running PostgreSQL, Casdoor, and NATS.
*   **Git**: For version control and managing the GitFlow workflow [docs/gitflow.md:1-4]().

## 1. Infrastructure Setup

The project uses Docker Compose to manage the local infrastructure stack. This includes **PostgreSQL 18**, **Casdoor** (Identity Provider), and **NATS** (Message Broker).

### Start the Stack
From the repository root, run:
```bash
docker compose -f infra/docker-compose.postgres.yml up -d
```

### Services Overview

| Service | Image | Internal Port | External Port | Role |
| :--- | :--- | :--- | :--- | :--- |
| `postgres` | `postgres:18-bookworm` | `5432` | `5432` | Primary database with `pg_partman` [infra/docker-compose.postgres.yml:31-52]() |
| `casdoor` | `casbin/casdoor:3.75.0` | `8000` | `8000` | OIDC Identity Provider [infra/docker-compose.postgres.yml:61-70]() |
| `nats` | `nats:latest` | `4222` | `4222` | Message broker with JetStream [infra/docker-compose.postgres.yml:86-93]() |

### Persistence
Data is persisted in Docker named volumes to survive container restarts:
*   `primebrick_pg18_data`: PostgreSQL data [infra/docker-compose.postgres.yml:103-105]().
*   `primebrick_casdoor_data`: Casdoor configurations and uploads [infra/docker-compose.postgres.yml:106-108]().
*   `primebrick_nats_data`: NATS JetStream state [infra/docker-compose.postgres.yml:109-111]().

**Sources:** [infra/docker-compose.postgres.yml:29-112](), [AGENTS.md:30-31]()

## 2. Environment Configuration

Create a `.env` file in the root directory. You can use the following default values for local development:

```env
DATABASE_URL=postgresql://primebrick:primebrick_dev@127.0.0.1:5432/primebrick
CASDOOR_ENDPOINT=http://127.0.0.1:8000
PORT=3001
```

> **Note**: If port `5432` is occupied by a local PostgreSQL instance, set `PG_HOST_PORT=5433` in your `.env` and recreate the containers [infra/docker-compose.postgres.yml:39-40]().

**Sources:** [infra/docker-compose.postgres.yml:33-40](), [AGENTS.md:42]()

## 3. Installation and Initialization

Follow these steps to prepare the application and database:

### Install Dependencies
```bash
pnpm install
```

### Setup Casdoor
Bootstrap the Identity Provider with necessary organizations, applications, and roles:
```bash
pnpm run setup:casdoor
```
This script initializes the Casdoor instance defined in the Docker stack [package.json:18]().

### Database Migrations
The project uses a patch-based migration system. Apply the latest patches to the database:
```bash
pnpm run db:migrate
```
This command checks the `public.primebrick_database_patch` table and applies missing `.sql` files [AGENTS.md:53-54]().

### Seed Demo Data
To populate the database with sample customers:
```bash
pnpm run db:seed:customers
```

**Sources:** [package.json:15-18](), [AGENTS.md:19-26]()

## 4. Running the Development Server

The backend uses `tsx watch` for hot-reloading during development.

```bash
pnpm run dev
```

The API will be available at `http://localhost:3001`.

### Port Management
If you encounter `EADDRINUSE` on port 3001, you can use the utility script to kill the existing process:
```bash
pnpm run dev:kill
```

**Sources:** [package.json:7-8](), [AGENTS.md:33-35]()

## Development Workflow and Data Flow

The following diagram illustrates the relationship between local development commands and the resulting infrastructure state.

### Infrastructure Initialization Flow
This diagram bridges the "Natural Language Space" of setup tasks to the "Code Entity Space" of scripts and configurations.

```mermaid
graph TD
    subgraph "Local_Commands"
        A["pnpm install"] --> B["docker compose up"]
        B --> C["pnpm run setup:casdoor"]
        C --> D["pnpm run db:migrate"]
        D --> E["pnpm run dev"]
    end

    subgraph "Code_Entities"
        B -- "uses" --> CFG["infra/docker-compose.postgres.yml"]
        C -- "executes" --> S1["scripts/setup-casdoor.ts"]
        D -- "executes" --> S2["scripts/database-patch-apply.ts"]
        E -- "executes" --> S3["src/index.ts"]
    end

    subgraph "Infrastructure_State"
        CFG -- "spawns" --> DB["primebrick-postgres-18"]
        CFG -- "spawns" --> IDP["primebrick-casdoor"]
        S2 -- "updates" --> TBL["public.primebrick_database_patch"]
    end
```
**Sources:** [package.json:6-18](), [infra/docker-compose.postgres.yml:29-62](), [AGENTS.md:51-54]()

### Request Flow Overview
When the dev server is running, requests flow through the following layers:

```mermaid
sequenceDiagram
    participant Client as "Client (Browser/Postman)"
    participant Express as "Express Server (src/index.ts)"
    participant Auth as "Auth Middleware (src/modules/auth/)"
    participant Router as "Module Router (e.g., src/modules/customers/)"
    participant DB as "PostgreSQL (Port 5432)"

    Client->>Express: HTTP Request
    Express->>Auth: Validate JWT / RBAC
    Auth->>Express: User Context (req.user)
    Express->>Router: Route Handler
    Router->>DB: SQL Query
    DB-->>Router: Result Set
    Router-->>Client: JSON Response
```
**Sources:** [package.json:7](), [AGENTS.md:75-138](), [src/openapi/openapi.ts:7-22]()

## GitFlow and Versioning

This repository strictly follows GitFlow. AI agents and developers must adhere to the following:

1.  **Branching**: Never work on `main` or `develop`. Create `feature/<slug>`, `release/<version>`, or `hotfix/<version>` branches [docs/gitflow.md:18-21]().
2.  **Version Sync**: The `package.json` version is automatically updated by `scripts/version-sync.mjs` during the `prebuild` hook and `pre-commit` hook [package.json:10](), [.githooks/pre-commit:5]().
3.  **Commits**: AI agents must never commit without explicit user instruction [AGENTS.md:5-9]().

**Sources:** [docs/gitflow.md:1-21](), [scripts/version-sync.mjs:69-91](), [.githooks/pre-commit:1-10]()

---
