Skip to content

davila06/ERP

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ERP IA Multi-Tenant

SaaS ERP con IA conversacional nativa, arquitectura DDD + CQRS + Event Sourcing y multi-tenancy real.
Backend .NET 9 · Frontend React 19 · App Mobile Expo · Azure OpenAI

Backend CI Frontend CI codecov Tests Tests TypeScript .NET


Tabla de contenidos


Visión general

ERP IA Multi-Tenant es un sistema ERP empresarial SaaS diseñado para múltiples empresas (tenants) con:

  • IA conversacional nativa — chat RAG con Azure OpenAI que entiende el contexto del ERP (ventas, finanzas, inventario, RRHH)
  • Multi-tenancy real — aislamiento por schema SQL, resolución de tenant por subdominio / header / JWT
  • Arquitectura de dominio — DDD + CQRS con MediatR, Event Sourcing, Outbox Pattern
  • Full-stack tipado — tipos compartidos entre backend, web y mobile (packages/shared-types)
  • Cero errores — 0 errores TypeScript (exactOptionalPropertyTypes: true), 0 errores de build .NET

Módulos de negocio

Módulo Backend Web Mobile
Core / Platform (auth, tenants, permisos)
Finance — contabilidad de doble entrada NIIF
Billing — facturas, pagos, notas de crédito, PDF
Sales — clientes, pedidos, kanban pipeline
Inventory — productos, bodegas, movimientos de stock
Procurement — proveedores, órdenes de compra
HR — empleados, nómina, vacaciones (RRHH)
AI Chat — ERP conversacional con streaming SSE
Compliance & Auditoría

Stack tecnológico

Backend

Runtime .NET 9 / ASP.NET Core 9
ORM Entity Framework Core 9 + SQL Server 2022
CQRS MediatR 14 + ValidationBehavior (FluentValidation)
Errores de dominio ErrorOr 2 (sin excepciones para flujo de negocio)
Auth Microsoft.Identity.Web + JWT Entra ID
Mensajería Azure Service Bus + Outbox Pattern
IA Azure.AI.OpenAI 2.1 + Azure AI Search (hybrid RAG)
PDF QuestPDF 2024.12
Excel ClosedXML 0.104
Real-time ASP.NET Core SignalR
Observabilidad Serilog + Application Insights + OpenTelemetry
IaC Bicep (App Service, Azure SQL, Key Vault, Service Bus, OpenAI, Static Web Apps)

Frontend Web

Framework React 19 + Vite + TypeScript strict
UI Material UI 6 + MUI X DataGrid/DatePickers
Routing React Router DOM 6 (lazy-loaded, code-split)
Server state TanStack Query 5
Client state Zustand 5
Forms React Hook Form 7 + Zod 3
Auth @azure/msal-browser 3 + sessionStorage
i18n react-i18next (es / en)
Gráficos Recharts 2
Real-time @microsoft/signalr
Telemetría @microsoft/applicationinsights-web

App Mobile

Framework Expo SDK 52 + React Native 0.76
Routing expo-router v4 (file-based)
Estilos NativeWind v4 (mismo design token que web)
Auth expo-auth-session (PKCE) + expo-secure-store
Biometría expo-local-authentication
Push expo-notifications + Azure Function → Expo Push Service

Testing

Backend xUnit + FluentAssertions + Moq — 313 tests (unitarios + integración)
Frontend Vitest 3 + @testing-library/react 16 + MSW v2 (60 handlers) — 89 tests
E2E Playwright — billing, sales, HR
Coverage Threshold: 80% backend · 75% frontend (Codecov)

Arquitectura

┌─────────────────────────────────────────────────────────────────┐
│                          CLIENTES                               │
│  Web React 19      Mobile Expo        Chat IA (SSE/WS)          │
│  localhost:3000     Expo Go           /api/v1/ai/chat/stream     │
└───────────────────────┬─────────────────────────────────────────┘
                        │  HTTPS + Bearer JWT
                        ▼
┌─────────────────────────────────────────────────────────────────┐
│                ERP.Api  (ASP.NET Core 9 · :5219)               │
│  Middleware: CORS · RateLimit · Auth · TenantResolution         │
│  Controllers: Finance · Billing · Sales · Inventory ·           │
│               Procurement · HR · AI · Compliance · Search       │
│  Hubs: /hubs/notifications  (SignalR)                           │
└──────────┬──────────────────────────┬────────────────────────────┘
           │  MediatR CQRS            │  Domain Events
           ▼                          ▼
┌──────────────────────┐   ┌──────────────────────────────────────┐
│   Dominios (DDD)     │   │         ERP.Infrastructure           │
│  Core · Finance      │   │  EF Core · EventStore · Outbox       │
│  Billing · Sales     │   │  ServiceBusPublisher · AuditLogger   │
│  Inventory · Procure │   │  KeyVaultConnectionStringProvider    │
│  HR · Compliance     │   └──────────────────────────────────────┘
│  IAPlataform         │              │
└──────────────────────┘              ▼
                          ┌──────────────────────────────────────┐
                          │  SQL Server 2022 (multi-schema)      │
                          │  catalog · finance · billing · sales  │
                          │  inventory · procurement · hr · audit │
                          └──────────────────────────────────────┘

Principios aplicados

Principio Implementación
DDD Aggregate Roots, Value Objects, Domain Events, repositorios con interfaces
CQRS Commands / Queries separados vía MediatR; ValidationBehavior pipeline
Event Sourcing Tabla DomainEvents con versioning optimista; OutboxProcessor para mensajería
Multi-tenancy Schema por módulo; TenantResolutionMiddleware; roles por tenant en DB
Zero-trust JWT Entra ID + Policy-based auth + Security Headers + Rate Limiting
ErrorOr<T> Sin excepciones para flujo de negocio en todos los dominios

Estructura del monorepo

ERP/
├── src/                        # Proyectos .NET
│   ├── ERP.SharedKernel/       #   Base classes, interfaces, contratos
│   ├── ERP.Core/               #   Tenants, Users, Subscriptions
│   ├── ERP.Finance/            #   Cuentas, Asientos NIIF, Períodos
│   ├── ERP.Billing/            #   Facturas, Pagos, Notas de Crédito
│   ├── ERP.Sales/              #   Clientes, Pedidos, Pipeline Kanban
│   ├── ERP.Inventory/          #   Productos, Bodegas, Stock
│   ├── ERP.Procurement/        #   Proveedores, Órdenes de Compra
│   ├── ERP.HR/                 #   Empleados, Nómina, Vacaciones
│   ├── ERP.Compliance/         #   Auditoría, Compliance Score
│   ├── ERP.IAPlataform/        #   LLM, SkillRouter, RAG, VectorSearch
│   ├── ERP.Infrastructure/     #   EF Core, ServiceBus, Outbox, KeyVault
│   └── ERP.Api/                #   API Host, Controllers, SignalR Hubs
├── tests/                      # Suites de test por dominio
├── apps/
│   ├── web/                    # React 19 (Vite + MUI + TanStack Query)
│   │   └── e2e/                #   Tests E2E Playwright
│   ├── mobile/                 # Expo 52 (expo-router + NativeWind)
│   └── notification-func/      # Azure Function — push notifications
├── packages/
│   └── shared-types/           # Tipos compartidos web ↔ mobile
├── infra/
│   └── bicep/                  # IaC (App Service, SQL, KeyVault, OpenAI…)
├── tools/
│   └── ERP.MigrationRunner/    # Runner de migraciones por tenant
├── scripts/
│   └── dev.ps1                 # Comandos de desarrollo local
└── docker-compose.yml          # SQL Server 2022 + Service Bus Emulator

Inicio rápido

Prerrequisitos

1. Levantar servicios Docker

.\scripts\dev.ps1 up
# Levanta SQL Server 2022 (:1433) + Service Bus Emulator

2. Backend (.NET 9)

# Copiar configuración de desarrollo
cp src/ERP.Api/appsettings.Development.example.json src/ERP.Api/appsettings.Development.json

# Correr API (aplica migraciones automáticamente al arrancar)
dotnet run --project src/ERP.Api
# → http://localhost:5219
# → Swagger: http://localhost:5219/swagger

Dev Auth: "DevAuth:Enabled": true en appsettings.Development.json permite usar la API sin Azure App Registration real.

3. Frontend Web (React 19)

pnpm install

# Copiar variables de entorno
cp apps/web/.env.example apps/web/.env.local

cd apps/web
pnpm dev
# → http://localhost:3000

4. App Mobile (Expo)

# Copiar variables de entorno (editar EXPO_PUBLIC_API_URL con tu IP local)
cp apps/mobile/.env.example apps/mobile/.env.local

cd apps/mobile
npx expo start
# Escanear QR con Expo Go

Dev Auth mobile: establece EXPO_PUBLIC_DEV_AUTH_ENABLED=true en .env.local para entrar sin MSAL.

Variables de entorno

Archivo Descripción
apps/web/.env.example Variables Vite (MSAL, API URL, App Insights)
apps/mobile/.env.example Variables Expo (MSAL, API URL, DevAuth flag)
src/ERP.Api/appsettings.Development.json Strings de conexión, DevAuth, Azure OpenAI

Testing

Backend

# Todos los tests
dotnet test ERP.sln

# Un proyecto específico
dotnet test tests/ERP.Finance.Tests
Suite Tests
ERP.SharedKernel.Tests 28
ERP.Core.Tests 40
ERP.Finance.Tests 51
ERP.Billing.Tests 34
ERP.Sales.Tests 25
ERP.Inventory.Tests 28
ERP.Procurement.Tests 19
ERP.HR.Tests 29
ERP.Compliance.Tests 13
ERP.Integration.Tests 46
Total 313 ✅

Frontend

cd apps/web

pnpm test              # Vitest (89 tests unitarios + componentes)
pnpm test:coverage     # Con reporte de cobertura
pnpm e2e               # Playwright E2E (requiere servidor corriendo)

Infraestructura Azure

Todos los recursos están definidos en infra/bicep/:

Recurso Módulo
App Service + Plan modules/appservice.bicep
Azure SQL Server modules/sqlserver.bicep
Azure Key Vault modules/keyvault.bicep
Service Bus (Namespace + Topics) modules/servicebus.bicep
Application Insights + Log Analytics modules/applicationinsights.bicep
Azure OpenAI + model deployments modules/openai.bicep
Azure Static Web Apps modules/staticwebapp.bicep
# Deploy a rg-erp-dev
az deployment group create \
  --resource-group rg-erp-dev \
  --template-file infra/bicep/main.bicep \
  --parameters infra/bicep/parameters/dev.bicepparam

App Registrations Entra ID:

.\infra\scripts\Setup-EntraAppRegistrations.ps1 `
  -TenantId "<azure-tenant-id>" `
  -SubscriptionId "<subscription-id>"

CI/CD

GitHub Actions

Workflow Disparador Jobs
backend.yml push a main / develop build → test → security scan (CodeQL) → deploy
frontend.yml push a main / develop type-check → lint → vitest coverage → e2e → deploy

Secrets requeridos

Secret Uso
AZURE_WEBAPP_PUBLISH_PROFILE Deploy backend → App Service
AZURE_STATIC_WEB_APPS_API_TOKEN Deploy frontend → Static Web Apps
CODECOV_TOKEN Upload cobertura
E2E_BASE_URL / E2E_USERNAME / E2E_PASSWORD Tests E2E Playwright

Seguridad

Control Estado
Sin secrets en código — Key Vault + Managed Identity
EF Core parametrizado (sin concatenación SQL)
FluentValidation en todos los Commands
CORS explícito sin *
Rate limiting SlidingWindow 300 req/min por tenant
Security Headers (CSP, X-Frame-Options, Referrer-Policy)
JWT en sessionStorage (no localStorage — protección XSS)
Audit log inmutable INSERT-only
CodeQL en CI
AI Chat: input length cap 4096 chars + history depth 20
SQL injection escaping en búsquedas LIKE

Contribuir

  1. Fork el repositorio y crea tu rama desde develop
  2. Sigue las convenciones del proyecto (.editorconfig + Directory.Build.props)
  3. Asegúrate de que dotnet test y pnpm test pasan sin errores
  4. Abre un Pull Request hacia develop

Para cambios en el dominio, agrega tests en la suite correspondiente (tests/ERP.<Modulo>.Tests).
Para cambios de UI, agrega/actualiza tests en apps/web/src/test/.


Construido con .NET 9 · React 19 · Expo 52 · Azure · TypeScript

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors