# cbrito475/saasfactura architecture

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

- Interactive diagram: https://gitdiagram.com/cbrito475/saasfactura
- Repository: https://github.com/cbrito475/saasfactura

## Overview

1. **Overall shape**
   FacturaVE is a monorepo with three main runtime surfaces: a **NestJS API** in `apps/api`, a **React/Vite SPA** in `apps/web`, and shared domain libraries plus Prisma schema in `packages/`. The architecture is centered on a **multi-tenant SaaS** for Venezuelan invoicing, accounting, tax, and admin operations.

2. **Backend entry point and composition**
   The API boots from `apps/api/src/main.ts` into `AppModule`, then composes many bounded modules. Cross-cutting infrastructure sits first: **Prisma/PostgreSQL**, **Redis**, tenant context middleware, and observability/audit interceptor. The API is structured as a set of Nest modules with clear internal layering.

3. **Module layering pattern**
   Most business areas follow the same split: **HTTP controllers** at the edge, **application services/use-cases** for orchestration, **domain services/entities/ports** for rules, and **Prisma repositories/adapters** for persistence or external integration. This makes the architecture diagram strongly layered, with dependencies flowing inward from controllers to application to domain, and outward through ports to infrastructure.

4. **Tenant, auth, and authorization boundary**
   Authentication is split into two domains:
   - `auth` for tenant user access
   - `saas-auth` for SaaS administrator access  
   These modules provide JWT strategies, guards, decorators, and repositories. Tenant isolation is enforced by a **tenant context middleware** plus guards like `tenant.guard`, `permission.guard`, `onboarding.guard`, and SaaS-specific role guards. This is one of the key architectural boundaries.

5. **Core business domain: company operations**
   The business core is organized around modules such as `empresa`, `sucursal`, `cliente`, `proveedor`, `producto`, `canal-venta`, `caja`, `contabilidad`, `nomina`, `operations`, `serie-numeracion`, and `fiscal-calendar`. These modules handle master data, POS/cash handling, accounting movements, payroll, stock/aging calculations, numbering series, and fiscal period logic.

6. **Tax and invoicing subsystem**
   Tax and invoicing are further split into specialized modules: `tax-engine`, `tax-books`, `tax-declarations`, `invoicing`, `factura-compra`, and `retencion`. These modules coordinate invoice emission, PDF generation, tax totals, IVA previews, purchase/sales books, withholding documents, and validation rules. The `shared-domain` package contributes reusable tax/calculation logic used by these services.

7. **Accounting and fiscal record integrity**
   `accounting` provides journal entries, auto-posting, closures, financial statements, and legal books. The repo’s compliance-oriented design is reinforced by append-only fiscal rules in the database, and a **hash-chain audit log** in `empresa_log`. This means the architecture is not just CRUD; it includes tamper-evident fiscal records and verifiable logs.

8. **Flows and job orchestration**
   The `flows` module is a dedicated workflow engine with flow definitions, execution entities, DSL persistence, step resolution, and action execution adapters. It is complemented by `jobs`, which handles queued work and retry policy. These two modules form the async/process-orchestration layer for tenant-specific automation.

9. **External Services Manager**
   The `esm` module is the integration boundary for external services. It has production/emulator adapters, assignment resolution, cryptography, and service-account/admin workflows. In a diagram, this should sit between the app and external providers, abstracting environment-specific behavior behind ports and adapters.

10. **Backend infrastructure**
   Persistence is Prisma + PostgreSQL, with repositories per module and a central Prisma service/module. Redis is present as a separate infrastructure module. The repository also includes generated `dist/` output for the API, indicating build artifacts are committed or available in the tree, but the source of truth is under `src/`.

11. **Frontend architecture**
   The SPA in `apps/web` is organized around route-level pages and reusable layout components. State is coordinated through `AuthContext`, `EmpresaContext`, and `FeaturesContext`. API access is centralized through `lib/api.ts` and `lib/saas-api.ts`, so the frontend depends on backend contracts rather than direct data access.

12. **Frontend domain surfaces**
   The UI reflects the backend boundaries: business pages like dashboard, facturación, compras, contabilidad, inventario, nómina, productos, clientes, tributario; POS screens for caja/ventas; onboarding flows; and a separate SaaS admin area for empresas, usuarios, flujos, operaciones, ESM, and auditoría. That separation mirrors the backend’s tenant vs SaaS-admin split.

13. **Shared packages**
   `packages/shared-domain` contains pure calculation and validation libraries for contabilidad, nomina, IVA, retenciones, IGTF, total factura, fiscal period, and RIF validation. `packages/shared-types` provides shared contracts. These packages are the lowest-level dependency layer and should be drawn as reusable, framework-agnostic building blocks used by both backend and, potentially, frontend contracts.

14. **Database, seeds, and compliance assets**
   `packages/prisma` contains the Prisma schema, seed scripts, and manual SQL migrations, including security and hash-chain triggers. The database layer is not just storage; it encodes tenant security, append-only rules, and compliance constraints. There is also an `uploads/` area under the API for generated artifacts such as PDFs.

15. **Operational state**
   Per the README, the repository is currently in **Phase 0 + Phase A**, meaning the platform boots, supports signup, company creation, dashboard navigation, and log verification. The architecture already includes placeholders and modules for later phases, but many features are scaffolding or partially implemented rather than fully exposed end-to-end.

Main entry points: [`apps/api/src/app.module.ts`](https://github.com/cbrito475/saasfactura/blob/main/apps/api/src/app.module.ts) (App module), [`apps/api/src/infrastructure/database/prisma.module.ts`](https://github.com/cbrito475/saasfactura/blob/main/apps/api/src/infrastructure/database/prisma.module.ts) (Prisma DB), [`apps/web/src/pages/Dashboard.tsx`](https://github.com/cbrito475/saasfactura/blob/main/apps/web/src/pages/Dashboard.tsx) (Business UI), [`apps/web/src/pages/saas/SaasEmpresas.tsx`](https://github.com/cbrito475/saasfactura/blob/main/apps/web/src/pages/saas/SaasEmpresas.tsx) (SaaS UI)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_api["API"]
  node_api_main(("main<br/>bootstrap<br/>[main.ts]"))
  node_api_app["App module<br/>composition root<br/>[app.module.ts]"]
  node_api_infra_db[("Prisma DB<br/>persistence infra<br/>[prisma.module.ts]")]
  node_api_infra_redis[("Redis<br/>cache/queue infra<br/>[redis.module.ts]")]
  node_api_observability(("Audit<br/>observability"))
  node_auth["Auth<br/>[auth.module.ts]"]
  node_saas_auth["SaaS auth<br/>admin auth module"]
  node_features["Features<br/>entitlement module<br/>[features.module.ts]"]
  node_empresa["Empresa<br/>tenant core module<br/>[empresa.module.ts]"]
  node_core_ops["Core ops<br/>business core"]
  node_tax_invoicing["Tax & billing<br/>fiscal domain"]
  node_accounting["Accounting<br/>ledger module"]
  node_flows_jobs["Flows & jobs<br/>workflow/async layer<br/>[flows.module.ts]"]
  node_esm["ESM<br/>integration module<br/>[esm.module.ts]"]
  node_mail["Mail<br/>notification adapter<br/>[mail.module.ts]"]
end

subgraph group_web["Web"]
  node_web_shell["Web shell<br/>SPA shell<br/>[App.tsx]"]
  node_web_business["Business UI<br/>tenant screens<br/>[Dashboard.tsx]"]
  node_web_saas["SaaS UI<br/>admin screens<br/>[SaasEmpresas.tsx]"]
end

subgraph group_shared["Shared"]
  node_shared_domain["Shared domain<br/>pure libs<br/>[index.ts]"]
  node_shared_types["Shared types<br/>contracts<br/>[index.ts]"]
  node_prisma_schema[("Schema<br/>[schema.prisma]")]
end

node_api_main -->|"boots"| node_api_app
node_api_app -->|"uses"| node_api_infra_db
node_api_app -->|"uses"| node_api_infra_redis
node_api_app -->|"wraps"| node_api_observability
node_api_app -->|"loads"| node_auth
node_api_app -->|"loads"| node_saas_auth
node_api_app -->|"loads"| node_features
node_api_app -->|"loads"| node_empresa
node_api_app -->|"loads"| node_core_ops
node_api_app -->|"loads"| node_tax_invoicing
node_api_app -->|"loads"| node_accounting
node_api_app -->|"loads"| node_flows_jobs
node_api_app -->|"loads"| node_esm
node_api_app -->|"loads"| node_mail
node_auth -->|"persists"| node_api_infra_db
node_saas_auth -->|"persists"| node_api_infra_db
node_empresa -->|"calculates"| node_shared_domain
node_tax_invoicing -->|"calculates"| node_shared_domain
node_accounting -->|"calculates"| node_shared_domain
node_flows_jobs -->|"queues"| node_api_infra_redis
node_esm -->|"persists"| node_api_infra_db
node_web_shell -->|"routes"| node_web_business
node_web_shell -->|"routes"| node_web_saas
node_web_shell -->|"types"| node_shared_types
node_web_business -->|"calls"| node_auth
node_web_business -->|"calls"| node_empresa
node_web_business -->|"calls"| node_tax_invoicing
node_web_saas -->|"calls"| node_saas_auth
node_web_saas -->|"calls"| node_features
node_web_saas -->|"calls"| node_esm
node_api_infra_db -->|"driven by"| node_prisma_schema
node_shared_domain -.->|"aligned with"| node_prisma_schema

click node_api_main "https://github.com/cbrito475/saasfactura/blob/main/apps/api/src/main.ts"
click node_api_app "https://github.com/cbrito475/saasfactura/blob/main/apps/api/src/app.module.ts"
click node_api_infra_db "https://github.com/cbrito475/saasfactura/blob/main/apps/api/src/infrastructure/database/prisma.module.ts"
click node_api_infra_redis "https://github.com/cbrito475/saasfactura/blob/main/apps/api/src/infrastructure/redis/redis.module.ts"
click node_api_observability "https://github.com/cbrito475/saasfactura/blob/main/apps/api/src/observability/audit.interceptor.ts"
click node_auth "https://github.com/cbrito475/saasfactura/blob/main/apps/api/src/modules/auth/auth.module.ts"
click node_saas_auth "https://github.com/cbrito475/saasfactura/blob/main/apps/api/src/modules/saas-auth/saas-auth.module.ts"
click node_features "https://github.com/cbrito475/saasfactura/blob/main/apps/api/src/modules/features/features.module.ts"
click node_empresa "https://github.com/cbrito475/saasfactura/blob/main/apps/api/src/modules/empresa/empresa.module.ts"
click node_tax_invoicing "https://github.com/cbrito475/saasfactura/blob/main/apps/api/src/modules/invoicing/invoicing.module.ts"
click node_accounting "https://github.com/cbrito475/saasfactura/blob/main/apps/api/src/modules/accounting/accounting.module.ts"
click node_flows_jobs "https://github.com/cbrito475/saasfactura/blob/main/apps/api/src/modules/flows/flows.module.ts"
click node_esm "https://github.com/cbrito475/saasfactura/blob/main/apps/api/src/modules/esm/esm.module.ts"
click node_mail "https://github.com/cbrito475/saasfactura/blob/main/apps/api/src/modules/mail/mail.module.ts"
click node_web_shell "https://github.com/cbrito475/saasfactura/blob/main/apps/web/src/App.tsx"
click node_web_business "https://github.com/cbrito475/saasfactura/blob/main/apps/web/src/pages/Dashboard.tsx"
click node_web_saas "https://github.com/cbrito475/saasfactura/blob/main/apps/web/src/pages/saas/SaasEmpresas.tsx"
click node_shared_domain "https://github.com/cbrito475/saasfactura/blob/main/packages/shared-domain/src/index.ts"
click node_shared_types "https://github.com/cbrito475/saasfactura/blob/main/packages/shared-types/src/index.ts"
click node_prisma_schema "https://github.com/cbrito475/saasfactura/blob/main/packages/prisma/schema.prisma"

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_api_main,node_api_app,node_api_infra_db,node_api_infra_redis,node_api_observability,node_auth,node_saas_auth,node_features,node_empresa,node_core_ops,node_tax_invoicing,node_accounting,node_flows_jobs,node_esm,node_mail toneBlue
class node_web_shell,node_web_business,node_web_saas toneAmber
class node_shared_domain,node_shared_types,node_prisma_schema toneMint
```

## Components

### API

NestJS backend surface

- [main](https://github.com/cbrito475/saasfactura/blob/main/apps/api/src/main.ts): bootstrap · API process entrypoint · `apps/api/src/main.ts`
- [App module](https://github.com/cbrito475/saasfactura/blob/main/apps/api/src/app.module.ts): composition root · Wires backend modules · `apps/api/src/app.module.ts`
- [Prisma DB](https://github.com/cbrito475/saasfactura/blob/main/apps/api/src/infrastructure/database/prisma.module.ts): persistence infra · PostgreSQL/tenant context bridge · `apps/api/src/infrastructure/database/prisma.module.ts`
- [Redis](https://github.com/cbrito475/saasfactura/blob/main/apps/api/src/infrastructure/redis/redis.module.ts): cache/queue infra · Shared Redis integration · `apps/api/src/infrastructure/redis/redis.module.ts`
- [Audit](https://github.com/cbrito475/saasfactura/blob/main/apps/api/src/observability/audit.interceptor.ts): observability · Audit interceptor · `apps/api/src/observability/audit.interceptor.ts`
- [Auth](https://github.com/cbrito475/saasfactura/blob/main/apps/api/src/modules/auth/auth.module.ts): tenant auth module · Tenant login, guards, and JWT strategy · `apps/api/src/modules/auth/auth.module.ts`
- [SaaS auth](https://github.com/cbrito475/saasfactura/blob/main/apps/api/src/modules/saas-auth/saas-auth.module.ts): admin auth module · SaaS admin access and roles · `apps/api/src/modules/saas-auth/saas-auth.module.ts`
- [Features](https://github.com/cbrito475/saasfactura/blob/main/apps/api/src/modules/features/features.module.ts): entitlement module · Feature flags and access rules · `apps/api/src/modules/features/features.module.ts`
- [Empresa](https://github.com/cbrito475/saasfactura/blob/main/apps/api/src/modules/empresa/empresa.module.ts): tenant core module · Company onboarding and fiscal config · `apps/api/src/modules/empresa/empresa.module.ts`
- **Core ops**: business core · Clientes, proveedores, productos, sucursales, series, caja
- [Tax & billing](https://github.com/cbrito475/saasfactura/blob/main/apps/api/src/modules/invoicing/invoicing.module.ts): fiscal domain · Invoicing, tax engine, declarations, retentions, books · `apps/api/src/modules/invoicing/invoicing.module.ts`
- [Accounting](https://github.com/cbrito475/saasfactura/blob/main/apps/api/src/modules/accounting/accounting.module.ts): ledger module · Journal entries, closures, statements, legal books · `apps/api/src/modules/accounting/accounting.module.ts`
- [Flows & jobs](https://github.com/cbrito475/saasfactura/blob/main/apps/api/src/modules/flows/flows.module.ts): workflow/async layer · Workflow DSL, execution, queueing, retries · `apps/api/src/modules/flows/flows.module.ts`
- [ESM](https://github.com/cbrito475/saasfactura/blob/main/apps/api/src/modules/esm/esm.module.ts): integration module · External service manager with adapters · `apps/api/src/modules/esm/esm.module.ts`
- [Mail](https://github.com/cbrito475/saasfactura/blob/main/apps/api/src/modules/mail/mail.module.ts): notification adapter · Outbound email port and adapter · `apps/api/src/modules/mail/mail.module.ts`

### Web

React/Vite frontend surface

- [Web shell](https://github.com/cbrito475/saasfactura/blob/main/apps/web/src/App.tsx): SPA shell · App composition, layout, contexts, API clients · `apps/web/src/App.tsx`
- [Business UI](https://github.com/cbrito475/saasfactura/blob/main/apps/web/src/pages/Dashboard.tsx): tenant screens · Dashboard, facturación, compras, contabilidad, POS, onboarding · `apps/web/src/pages/Dashboard.tsx`
- [SaaS UI](https://github.com/cbrito475/saasfactura/blob/main/apps/web/src/pages/saas/SaasEmpresas.tsx): admin screens · SaaS admin area for companies, users, flows, ESM, audit · `apps/web/src/pages/saas/SaasEmpresas.tsx`

### Shared

Reusable packages and schema

- [Shared domain](https://github.com/cbrito475/saasfactura/blob/main/packages/shared-domain/src/index.ts): pure libs · Tax, payroll, accounting calculations and validations · `packages/shared-domain/src/index.ts`
- [Shared types](https://github.com/cbrito475/saasfactura/blob/main/packages/shared-types/src/index.ts): contracts · Cross-package type contracts · `packages/shared-types/src/index.ts`
- [Schema](https://github.com/cbrito475/saasfactura/blob/main/packages/prisma/schema.prisma): database schema · Prisma schema, seeds, and SQL rules · `packages/prisma/schema.prisma`

## Connections

- main → App module: boots · Nest application starts from main into AppModule
- App module → Prisma DB: uses · Backend composes Prisma/PostgreSQL layer
- App module → Redis: uses · Backend composes Redis layer
- App module → Audit: wraps · Global audit/interceptor concern
- App module → Auth: loads · Tenant auth boundary
- App module → SaaS auth: loads · SaaS admin auth boundary
- App module → Features: loads · Feature gating and entitlement checks
- App module → Empresa: loads · Tenant onboarding and company management
- App module → Core ops: loads · Operational master-data modules
- App module → Tax & billing: loads · Tax, billing, and fiscal compliance modules
- App module → Accounting: loads · Ledger and reporting modules
- App module → Flows & jobs: loads · Workflow and async orchestration layer
- App module → ESM: loads · External service manager boundary
- App module → Mail: loads · Notification subsystem
- Auth → Prisma DB: persists · Tenant users and access state stored via Prisma
- SaaS auth → Prisma DB: persists · SaaS admins, users, and audit data stored via Prisma
- Empresa → Shared domain: calculates · Uses shared fiscal and accounting primitives
- Tax & billing → Shared domain: calculates · Uses shared tax/validation logic
- Accounting → Shared domain: calculates · Uses shared double-entry helpers
- Flows & jobs → Redis: queues · Async work and retries use Redis-backed infrastructure
- ESM → Prisma DB: persists · Service assignments and manager state stored via Prisma
- Web shell → Business UI: routes · Tenant UI is composed of business pages
- Web shell → SaaS UI: routes · Shell also serves SaaS admin pages
- Web shell → Shared types: types · Frontend consumes shared contracts
- Business UI → Auth: calls · Tenant UI authenticates against backend auth
- Business UI → Empresa: calls · Company onboarding and context APIs
- Business UI → Tax & billing: calls · Invoices, purchases, taxes, and accounting screens hit fiscal APIs
- SaaS UI → SaaS auth: calls · SaaS admin UI authenticates against SaaS auth
- SaaS UI → Features: calls · Feature management screens use entitlement APIs
- SaaS UI → ESM: calls · ESM admin screens use integration APIs
- Prisma DB → Schema: driven by · Database layer is defined by Prisma schema and SQL rules
- Shared domain → Schema: aligned with · Business rules reflect persisted fiscal model
