# Glossary

# Glossary

<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)
- [db-meta/diff-entities-vs-database.json](db-meta/diff-entities-vs-database.json)
- [db-meta/snapshot-database.json](db-meta/snapshot-database.json)
- [db-meta/snapshot-entities.json](db-meta/snapshot-entities.json)
- [docs/gitflow.md](docs/gitflow.md)
- [package.json](package.json)
- [scripts/fix-missing-audit-records.ts](scripts/fix-missing-audit-records.ts)
- [scripts/setup-casdoor.ts](scripts/setup-casdoor.ts)
- [src/db/repository/repository.ts](src/db/repository/repository.ts)
- [src/domain/entities/entity-decorators.ts](src/domain/entities/entity-decorators.ts)
- [src/domain/entities/entity-meta.ts](src/domain/entities/entity-meta.ts)
- [src/lib/audit/delta-calculator.ts](src/lib/audit/delta-calculator.ts)
- [src/lib/export/index.ts](src/lib/export/index.ts)
- [src/modules/auth/permissions.ts](src/modules/auth/permissions.ts)
- [src/modules/auth/router.ts](src/modules/auth/router.ts)
- [src/modules/auth/session-context.ts](src/modules/auth/session-context.ts)
- [src/modules/customers/customers_dal.ts](src/modules/customers/customers_dal.ts)
- [templates/customer_export_template_2.xlsx](templates/customer_export_template_2.xlsx)

</details>



This page defines the domain concepts, technical abbreviations, and codebase-specific terms used throughout the Primebrick backend. It serves as a bridge between business requirements and the underlying implementation.

## Domain Concepts

### Audit Trail
The system-wide mechanism for tracking every mutation to "Auditable" entities. Unlike simple logging, the audit trail stores a structured **Delta** representing exactly which fields changed.
*   **Implementation**: Controlled by the `@Auditable()` decorator [src/domain/entities/entity-decorators.ts:4]().
*   **Data Flow**: When a `Repository` method like `update` or `insertMany` is called, it triggers the `AuditService` to calculate differences and write to a shadow table (e.g., `customers_audit`) [src/db/repository/repository.ts:91-114]().

### Delta
A JSON object representing the difference between two states of an entity.
*   **Structure**: `{ "field_name": { "old": value, "new": value } }` [src/lib/audit/delta-calculator.ts:22]().
*   **Logic**: Managed by the `calculateDelta` function which compares keys in the entity persistence metadata [src/db/repository/repository.ts:22]().

### Entity
A TypeScript class decorated with `@Entity` that maps directly to a PostgreSQL table.
*   **Registry**: All entities must be registered in the system to be recognized by the `Repository` and the schema comparison tools [src/domain/entities/entity-meta.ts:9]().
*   **Metadata**: Includes column types, primary keys (`@Key`), and soft-delete fields (`@DeletableField`) [src/domain/entities/entity-decorators.ts:13-14]().

### Soft Delete
A pattern where records are not physically removed from the database but marked with a timestamp.
*   **Fields**: Usually `deleted_at` and `deleted_by` [src/modules/customers/customers_dal.ts:164-165]().
*   **Query Behavior**: The `Repository` automatically filters out records where `deleted_at` is NOT NULL unless `deletedRecords: true` is passed in `FindOptions` [src/db/repository/repository.ts:129-130]().

---

## Technical Abbreviations & Terms

| Term | Definition | Code Pointer |
| :--- | :--- | :--- |
| **DAL** | Data Access Layer. Classes that encapsulate complex query logic for specific modules (e.g., `CustomersDal`). | [src/modules/customers/customers_dal.ts:207]() |
| **DSL** | Domain Specific Language. Refers to the type-safe query builder used to construct SQL filters and joins. | [src/db/repository/dsl.ts:7]() |
| **IDP** | Identity Provider. The external system (Casdoor) used for authentication and role management. | [src/modules/auth/router.ts:17]() |
| **JWT** | JSON Web Token. The standard used for secure identity exchange between the IDP, Frontend, and Backend. | [src/modules/auth/router.ts:113]() |
| **RBAC** | Role-Based Access Control. The system that grants permissions based on user roles. | [src/modules/auth/rbac.middleware.ts:13]() |
| **Snapshot** | A JSON representation of the database schema or entity definitions used to detect drifts. | [db-meta/snapshot-entities.json:1]() |

---

## System Architecture Mapping

The following diagrams illustrate how natural language concepts map to specific code entities and data structures within the Primebrick ecosystem.

### Authentication & Authorization Flow
This diagram bridges the concept of "Logging In" to the specific classes and functions handling the handshake with Casdoor and the local RBAC expansion.

```mermaid
graph TD
    subgraph "Natural Language Space"
        A["User Login Request"]
        B["Permission Check"]
    end

    subgraph "Code Entity Space"
        direction LR
        C["authRouter: /login"]:::code
        D["CasdoorApiClient"]:::code
        E["expandPermissions()"]:::code
        F["rbacHandler"]:::code
        G["Permission Enum"]:::code
    end

    A --> C
    C --> D
    D -- "Returns JWT" --> E
    E -- "Maps Roles to" --> G
    G -- "Enforced by" --> F
    F -- "Protects" --> B

    classDef code font-family:monospace, stroke-width:2px;
```
**Sources**: [src/modules/auth/router.ts:68-70](), [src/modules/auth/permissions.ts:34-87](), [src/modules/auth/rbac.middleware.ts:13]()

### Database Lifecycle & Schema Management
This diagram maps the concept of "Database Updates" to the specific scripts and metadata files used to maintain parity between TypeScript models and PostgreSQL.

```mermaid
graph LR
    subgraph "Natural Language Space"
        H["Code Change (New Column)"]
        I["Migration Execution"]
    end

    subgraph "Code Entity Space"
        J["@Column Decorator"]:::code
        K["db:meta:compare script"]:::code
        L["snapshot-entities.json"]:::code
        M["diff-entities-vs-database.json"]:::code
        N["db:migrate script"]:::code
        O["primebrick_database_patch table"]:::code
    end

    H --> J
    J --> K
    K --> L
    K --> M
    M -- "Generates SQL" --> N
    N --> O
    O --> I

    classDef code font-family:monospace, stroke-width:2px;
```
**Sources**: [AGENTS.md:52-54](), [db-meta/diff-entities-vs-database.json:1](), [package.json:14-15]()

---

## Core Entities & Data Structures

### `AuthUser`
The object attached to `req.user` after successful authentication.
*   **Properties**: `id`, `uuid`, `roles`, `permissions` (a Set of expanded strings), and `isAdmin` (boolean bypass).
*   **Source**: [src/modules/auth/session-context.ts]()

### `Repository`
The generic gateway for all CRUD operations. It translates DSL expressions into SQL.
*   **Key Functions**: 
    *   `findByPage`: Handles pagination logic [src/db/repository/repository.ts:177]().
    *   `insertMany`: Handles bulk insertion with automatic audit logging [src/db/repository/repository.ts:45]().
    *   `update`: Implements optimistic concurrency using the `version` column [src/db/repository/repository.ts:22]().

### `ExportConfig`
Defines the parameters for the template-based streaming export system.
*   **Metadata**: Includes field types (Date, Currency, Percentage) to ensure correct formatting in Excel [src/lib/export/index.ts:122]().
*   **Placeholders**: Uses `{#field}` for data loops and `{?key}` for translated headers [src/lib/export/index.ts:166-173]().

---
**Sources**: 
- [src/modules/auth/permissions.ts:1-179]()
- [src/db/repository/repository.ts:1-200]()
- [src/lib/audit/delta-calculator.ts:1-30]()
- [src/lib/export/index.ts:29-200]()
- [AGENTS.md:75-150]()
- [package.json:1-43]()
