# hexdevop/crm architecture

> Architecture diagram of the GitHub repository hexdevop/crm, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-05-24). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/hexdevop/crm
- Repository: https://github.com/hexdevop/crm

## Overview

1. **System shape**
   Universal CRM is split into three runnable applications: a FastAPI backend, a React/TypeScript frontend, and a Telegram bot. PostgreSQL is the primary datastore, Redis supports permission caching and pub/sub notifications, and Docker Compose wires the whole stack together for dev and prod.

2. **Backend as the core application**
   The backend under `backend/app` is the central business layer. `main.py` boots FastAPI, `api/router.py` mounts versioned routes, and `core/` holds cross-cutting concerns like security, dependency injection, exceptions, and pagination. All domain operations flow through this API layer.

3. **Layered backend boundaries**
   The backend follows a clear separation: API routers call service classes, services orchestrate business rules, repositories perform tenant-scoped database access, and SQLAlchemy models define persistence. Pydantic schemas sit on the edge for request/response validation. This makes the repository the best place to draw a clean diagram with distinct API, service, data-access, and model layers.

4. **Multitenancy boundary**
   The key architectural constraint is row-level tenant isolation. Nearly every user-owned table includes `company_id`, and repositories require it in queries so records are always filtered by tenant. The README states that authentication middleware extracts `company_id` from the JWT and attaches it to the request, so tenant context is established once and then propagated downward through dependencies into repositories.

5. **Authentication and session flow**
   The auth subsystem uses a two-token JWT pattern: a short-lived access token returned in the login response and a long-lived refresh token stored in an HttpOnly cookie. Backend auth endpoints live in `backend/app/api/v1/auth.py`, with supporting logic in `services/auth.py`, `core/security.py`, and `schemas/auth.py`. The frontend keeps the access token in memory/Zustand, while refresh happens transparently via cookie-backed requests.

6. **RBAC and permission caching**
   Roles and permissions are modeled as first-class backend entities (`models/role.py`, `repositories/role.py`, `services/role.py`) and exposed through dedicated API routes. Permission checks are cached in Redis per user and invalidated when role assignments change. Superadmin access is an explicit bypass path that spans all companies.

7. **CRM domain modules**
   The main business domains are company management, users, roles, entities, entity records, movements, access expiration, uploads, and Telegram integration. Each domain has its own trio of router/service/repository files, which suggests the architecture is resource-oriented and domain-separated rather than monolithic. `entities` and `entity_records` are especially important because they implement the configurable CRM object model.

8. **Dynamic entity model**
   The entity builder is a core differentiator: entity definitions are stored relationally, while the actual record payload is stored as JSONB. This means schema changes happen at the application layer rather than through frequent migrations. In diagram terms, `entities` define structure, `entity_records` store data, and the JSONB field acts as the flexible data boundary.

9. **Background jobs and access expiry**
   `backend/app/tasks/` contains scheduler and checker jobs for access expiration. These background tasks periodically evaluate user/company access windows and update account state when access ends. That makes the system partly event/time-driven, not just request-driven.

10. **Telegram notification pipeline**
   Telegram integration is split between backend and a separate `bot/` service. The backend publishes notification events to Redis pub/sub; the bot subscribes and sends messages via aiogram 3 to Telegram users. A `/connect TOKEN` flow links Telegram accounts back to CRM users, so Redis is the bridge between application events and outbound messaging.

11. **Frontend structure**
   The frontend is a Vite-built React SPA in `frontend/src`. `api/` contains Axios clients for each backend resource, `hooks/` wraps those calls into reusable data hooks, `store/` holds app state like auth/theme/ui, and `pages/` is organized by domain: auth, dashboard, entities, records, roles, users, access, admin, and settings. The frontend is therefore a thin client over the backend API, not a separate business-logic system.

12. **Navigation, protection, and UI composition**
   `router/ProtectedRoute.tsx` and the `layouts/` directory show that access control is enforced in the client UI as well, primarily for navigation and UX. Shared UI components under `components/ui` and layout components like `Sidebar` and `Topbar` indicate a shell-based application UI around domain pages.

13. **Infrastructure and deployment**
   Deployment is container-first. `docker-compose.dev.yml` brings up PostgreSQL, Redis, backend, frontend, and bot with hot reload; `docker-compose.prod.yml` is the production composition. Backend startup runs Alembic migrations via `entrypoint.sh`, and production uses nginx to serve the frontend and proxy API traffic, with SSL handled at the edge.

14. **Data ownership and external dependencies**
   PostgreSQL is the system of record for all CRM data, Alembic manages schema evolution, and Redis is a supporting dependency rather than a source of truth. External service interaction is limited mainly to Telegram’s Bot API and the browser client. That keeps the architecture centered on the backend database, with Redis and Telegram as auxiliary integration layers.

Main entry points: [`frontend/src/App.tsx`](https://github.com/hexdevop/crm/blob/master/frontend/src/App.tsx) (SPA shell), [`backend/app/main.py`](https://github.com/hexdevop/crm/blob/master/backend/app/main.py) (API app), [`backend/app/api/router.py`](https://github.com/hexdevop/crm/blob/master/backend/app/api/router.py) (Route mount), [`backend/app/api/v1/auth.py`](https://github.com/hexdevop/crm/blob/master/backend/app/api/v1/auth.py) (Auth API)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_backend["Backend"]
  node_backend_main["API app<br/>FastAPI entry<br/>[main.py]"]
  node_backend_router["Route mount<br/>API router<br/>[router.py]"]
  node_backend_auth_api["Auth API<br/>REST module<br/>[auth.py]"]
  node_backend_entity_api["Entity API<br/>REST module<br/>[entities.py]"]
  node_backend_record_api["Record API<br/>REST module<br/>[entity_records.py]"]
  node_backend_auth_service["Auth service<br/>business service<br/>[auth.py]"]
  node_backend_entity_service["Entity service<br/>business service<br/>[entity.py]"]
  node_backend_role_service["Role service<br/>business service<br/>[role.py]"]
  node_backend_entity_repo["Entity repo<br/>tenant repository<br/>[entity.py]"]
  node_backend_role_repo["Role repo<br/>tenant repository<br/>[role.py]"]
  node_backend_entity_model["Entity model<br/>SQLAlchemy model<br/>[entity.py]"]
  node_backend_entity_schema["Entity schema<br/>Pydantic schema<br/>[entity.py]"]
  node_backend_security["Security core<br/>core utilities<br/>[security.py]"]
  node_backend_redis[("Redis client<br/>cache/pubsub<br/>[redis_client.py]")]
  node_backend_scheduler["Expiry jobs<br/>background jobs<br/>[scheduler.py]"]
end

subgraph group_frontend["Frontend"]
  node_frontend_app["SPA shell<br/>React app<br/>[App.tsx]"]
  node_frontend_client["API client<br/>HTTP client<br/>[client.ts]"]
  node_frontend_auth_store["Auth store<br/>state store<br/>[auth.store.ts]"]
  node_frontend_protected["Protected route<br/>route guard<br/>[ProtectedRoute.tsx]"]
  node_frontend_entity_page["Builder page<br/>feature page"]
end

subgraph group_bot["Telegram Bot"]
  node_bot_main["Bot app<br/>aiogram entry<br/>[main.py]"]
  node_bot_dispatcher["Notifier<br/>pubsub worker<br/>[dispatcher.py]"]
  node_bot_connect["Connect flow<br/>command handler<br/>[connect.py]"]
end

subgraph group_infra["Infra"]
  node_compose["Compose stack<br/>deployment"]
  node_entrypoint["Backend start<br/>startup script<br/>[entrypoint.sh]"]
end

subgraph group_external["External Systems"]
  node_postgres[("PostgreSQL<br/>primary datastore")]
  node_telegram_api["Telegram API<br/>external service"]
  node_redis_ext[("Redis<br/>cache/pubsub")]
end

node_compose -->|"starts"| node_backend_main
node_compose -->|"serves"| node_frontend_app
node_compose -->|"starts"| node_bot_main
node_backend_main -->|"mounts"| node_backend_router
node_backend_router -->|"includes"| node_backend_auth_api
node_backend_router -->|"includes"| node_backend_entity_api
node_backend_router -->|"includes"| node_backend_record_api
node_backend_auth_api -->|"uses"| node_backend_auth_service
node_backend_entity_api -->|"uses"| node_backend_entity_service
node_backend_record_api -->|"uses"| node_backend_entity_service
node_backend_entity_service -->|"calls"| node_backend_entity_repo
node_backend_role_service -->|"calls"| node_backend_role_repo
node_backend_entity_repo -->|"maps to"| node_backend_entity_model
node_backend_entity_service -->|"validates"| node_backend_entity_schema
node_backend_auth_service -->|"depends on"| node_backend_security
node_backend_security -->|"caches permissions"| node_redis_ext
node_backend_scheduler -->|"updates"| node_postgres
node_backend_main -->|"reads/writes"| node_postgres
node_backend_main -->|"pub/sub"| node_redis_ext
node_bot_main -->|"runs"| node_bot_dispatcher
node_bot_dispatcher -->|"subscribes"| node_redis_ext
node_bot_dispatcher -->|"sends"| node_telegram_api
node_bot_connect -->|"links"| node_telegram_api
node_frontend_app -->|"calls"| node_frontend_client
node_frontend_app -->|"stores session"| node_frontend_auth_store
node_frontend_app -->|"guards"| node_frontend_protected
node_frontend_app -->|"renders"| node_frontend_entity_page
node_frontend_client -->|"requests"| node_backend_main
node_frontend_auth_store -->|"auth flow"| node_backend_auth_api
node_backend_auth_api -->|"issues tokens"| node_backend_security

click node_backend_main "https://github.com/hexdevop/crm/blob/master/backend/app/main.py"
click node_backend_router "https://github.com/hexdevop/crm/blob/master/backend/app/api/router.py"
click node_backend_auth_api "https://github.com/hexdevop/crm/blob/master/backend/app/api/v1/auth.py"
click node_backend_entity_api "https://github.com/hexdevop/crm/blob/master/backend/app/api/v1/entities.py"
click node_backend_record_api "https://github.com/hexdevop/crm/blob/master/backend/app/api/v1/entity_records.py"
click node_backend_auth_service "https://github.com/hexdevop/crm/blob/master/backend/app/services/auth.py"
click node_backend_entity_service "https://github.com/hexdevop/crm/blob/master/backend/app/services/entity.py"
click node_backend_role_service "https://github.com/hexdevop/crm/blob/master/backend/app/services/role.py"
click node_backend_entity_repo "https://github.com/hexdevop/crm/blob/master/backend/app/repositories/entity.py"
click node_backend_role_repo "https://github.com/hexdevop/crm/blob/master/backend/app/repositories/role.py"
click node_backend_entity_model "https://github.com/hexdevop/crm/blob/master/backend/app/models/entity.py"
click node_backend_entity_schema "https://github.com/hexdevop/crm/blob/master/backend/app/schemas/entity.py"
click node_backend_security "https://github.com/hexdevop/crm/blob/master/backend/app/core/security.py"
click node_backend_redis "https://github.com/hexdevop/crm/blob/master/backend/app/redis_client.py"
click node_backend_scheduler "https://github.com/hexdevop/crm/blob/master/backend/app/tasks/scheduler.py"
click node_frontend_app "https://github.com/hexdevop/crm/blob/master/frontend/src/App.tsx"
click node_frontend_client "https://github.com/hexdevop/crm/blob/master/frontend/src/api/client.ts"
click node_frontend_auth_store "https://github.com/hexdevop/crm/blob/master/frontend/src/store/auth.store.ts"
click node_frontend_protected "https://github.com/hexdevop/crm/blob/master/frontend/src/router/ProtectedRoute.tsx"
click node_frontend_entity_page "https://github.com/hexdevop/crm/blob/master/frontend/src/pages/entities/EntityBuilderPage.tsx"
click node_bot_main "https://github.com/hexdevop/crm/blob/master/bot/bot/main.py"
click node_bot_dispatcher "https://github.com/hexdevop/crm/blob/master/bot/bot/notifications/dispatcher.py"
click node_bot_connect "https://github.com/hexdevop/crm/blob/master/bot/bot/handlers/connect.py"
click node_compose "https://github.com/hexdevop/crm/blob/master/docker-compose.dev.yml"
click node_entrypoint "https://github.com/hexdevop/crm/blob/master/backend/entrypoint.sh"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_backend_main,node_backend_router,node_backend_auth_api,node_backend_entity_api,node_backend_record_api,node_backend_auth_service,node_backend_entity_service,node_backend_role_service,node_backend_entity_repo,node_backend_role_repo,node_backend_entity_model,node_backend_entity_schema,node_backend_security,node_backend_redis,node_backend_scheduler toneBlue
class node_frontend_app,node_frontend_client,node_frontend_auth_store,node_frontend_protected,node_frontend_entity_page toneAmber
class node_bot_main,node_bot_dispatcher,node_bot_connect toneMint
class node_compose,node_entrypoint toneRose
class node_postgres,node_telegram_api,node_redis_ext toneIndigo
```

## Components

### Backend

FastAPI API, business logic, persistence, and background jobs.

- [API app](https://github.com/hexdevop/crm/blob/master/backend/app/main.py): FastAPI entry · Bootstraps the backend application and middleware stack. · `backend/app/main.py`
- [Route mount](https://github.com/hexdevop/crm/blob/master/backend/app/api/router.py): API router · Collects and mounts versioned backend routes. · `backend/app/api/router.py`
- [Auth API](https://github.com/hexdevop/crm/blob/master/backend/app/api/v1/auth.py): REST module · Login, refresh, and authentication endpoints. · `backend/app/api/v1/auth.py`
- [Entity API](https://github.com/hexdevop/crm/blob/master/backend/app/api/v1/entities.py): REST module · Entity definitions and configurable CRM object endpoints. · `backend/app/api/v1/entities.py`
- [Record API](https://github.com/hexdevop/crm/blob/master/backend/app/api/v1/entity_records.py): REST module · Entity record CRUD and payload handling. · `backend/app/api/v1/entity_records.py`
- [Auth service](https://github.com/hexdevop/crm/blob/master/backend/app/services/auth.py): business service · Token issuance, session logic, and authentication rules. · `backend/app/services/auth.py`
- [Entity service](https://github.com/hexdevop/crm/blob/master/backend/app/services/entity.py): business service · Coordinates entity definitions and record operations. · `backend/app/services/entity.py`
- [Role service](https://github.com/hexdevop/crm/blob/master/backend/app/services/role.py): business service · Manages roles, permissions, and access changes. · `backend/app/services/role.py`
- [Entity repo](https://github.com/hexdevop/crm/blob/master/backend/app/repositories/entity.py): tenant repository · Tenant-scoped persistence for entity definitions and records. · `backend/app/repositories/entity.py`
- [Role repo](https://github.com/hexdevop/crm/blob/master/backend/app/repositories/role.py): tenant repository · Persistence for roles and permission assignments. · `backend/app/repositories/role.py`
- [Entity model](https://github.com/hexdevop/crm/blob/master/backend/app/models/entity.py): SQLAlchemy model · Relational definition of configurable CRM entities. · `backend/app/models/entity.py`
- [Entity schema](https://github.com/hexdevop/crm/blob/master/backend/app/schemas/entity.py): Pydantic schema · Validation layer for entity requests and responses. · `backend/app/schemas/entity.py`
- [Security core](https://github.com/hexdevop/crm/blob/master/backend/app/core/security.py): core utilities · JWT, dependency, and request context helpers. · `backend/app/core/security.py`
- [Redis client](https://github.com/hexdevop/crm/blob/master/backend/app/redis_client.py): cache/pubsub · Permission cache and notification bus integration. · `backend/app/redis_client.py`
- [Expiry jobs](https://github.com/hexdevop/crm/blob/master/backend/app/tasks/scheduler.py): background jobs · Scheduled checks for access expiration and state updates. · `backend/app/tasks/scheduler.py`

### Frontend

React/TypeScript SPA that consumes the backend API.

- [SPA shell](https://github.com/hexdevop/crm/blob/master/frontend/src/App.tsx): React app · Application root for the client-side UI. · `frontend/src/App.tsx`
- [API client](https://github.com/hexdevop/crm/blob/master/frontend/src/api/client.ts): HTTP client · Axios layer for backend resource calls. · `frontend/src/api/client.ts`
- [Auth store](https://github.com/hexdevop/crm/blob/master/frontend/src/store/auth.store.ts): state store · Keeps access token and session UI state in memory. · `frontend/src/store/auth.store.ts`
- [Protected route](https://github.com/hexdevop/crm/blob/master/frontend/src/router/ProtectedRoute.tsx): route guard · Client-side navigation protection and UX gating. · `frontend/src/router/ProtectedRoute.tsx`
- [Builder page](https://github.com/hexdevop/crm/blob/master/frontend/src/pages/entities/EntityBuilderPage.tsx): feature page · UI for configuring CRM entities and related records. · `frontend/src/pages/entities/EntityBuilderPage.tsx`

### Telegram Bot

Separate aiogram service for outbound notifications and account linking.

- [Bot app](https://github.com/hexdevop/crm/blob/master/bot/bot/main.py): aiogram entry · Starts the Telegram bot service. · `bot/bot/main.py`
- [Notifier](https://github.com/hexdevop/crm/blob/master/bot/bot/notifications/dispatcher.py): pubsub worker · Consumes notification events and dispatches Telegram messages. · `bot/bot/notifications/dispatcher.py`
- [Connect flow](https://github.com/hexdevop/crm/blob/master/bot/bot/handlers/connect.py): command handler · Links Telegram accounts back to CRM users. · `bot/bot/handlers/connect.py`

### Infra

Container orchestration and deployment entrypoints.

- [Compose stack](https://github.com/hexdevop/crm/blob/master/docker-compose.dev.yml): deployment · Wires backend, frontend, bot, Redis, and PostgreSQL for dev and prod. · `docker-compose.dev.yml`
- [Backend start](https://github.com/hexdevop/crm/blob/master/backend/entrypoint.sh): startup script · Runs migrations and launches the backend container. · `backend/entrypoint.sh`

### External Systems

Datastore and third-party services the app depends on.

- **PostgreSQL**: primary datastore · System of record for CRM data.
- **Telegram API**: external service · Outbound messaging and account linking destination.
- **Redis**: cache/pubsub · Shared cache and event transport.

## Connections

- Compose stack → API app: starts · Docker Compose launches the backend service.
- Compose stack → SPA shell: serves · Compose includes the frontend runtime.
- Compose stack → Bot app: starts · Compose launches the Telegram bot service.
- API app → Route mount: mounts · The backend app attaches the versioned router set.
- Route mount → Auth API: includes · Auth endpoints are part of the API surface.
- Route mount → Entity API: includes · Entity endpoints are part of the API surface.
- Route mount → Record API: includes · Record endpoints are part of the API surface.
- Auth API → Auth service: uses · Endpoints delegate auth logic to services.
- Entity API → Entity service: uses · Entity endpoints delegate domain operations.
- Record API → Entity service: uses · Record endpoints reuse entity orchestration.
- Entity service → Entity repo: calls · Services persist through repositories.
- Role service → Role repo: calls · Role logic is mediated by role repositories.
- Entity repo → Entity model: maps to · Repositories operate on SQLAlchemy models.
- Entity service → Entity schema: validates · Schema boundary protects API inputs and outputs.
- Auth service → Security core: depends on · Security core provides JWT and dependency helpers.
- Security core → Redis: caches permissions · Permission checks are cached in Redis.
- Expiry jobs → PostgreSQL: updates · Background jobs evaluate and mutate expiry state in the database.
- API app → PostgreSQL: reads/writes · The API uses PostgreSQL through the database layer.
- API app → Redis: pub/sub · Backend publishes notification events to Redis.
- Bot app → Notifier: runs · The bot boots the notification worker.
- Notifier → Redis: subscribes · The bot consumes events from Redis pub/sub.
- Notifier → Telegram API: sends · Outbound messages are delivered through Telegram.
- Connect flow → Telegram API: links · The connect command binds Telegram accounts.
- SPA shell → API client: calls · The SPA uses the shared API client.
- SPA shell → Auth store: stores session · Client auth state is kept in the store.
- SPA shell → Protected route: guards · Protected routes enforce UX-level access control.
- SPA shell → Builder page: renders · Entity builder UI is one of the main domain pages.
- API client → API app: requests · Frontend API calls target the backend service.
- Auth store → Auth API: auth flow · Login and token refresh are driven by auth endpoints.
- Auth API → Security core: issues tokens · Auth endpoints rely on core security helpers.
