erp-suite/DEPLOYMENT.md

331 lines
12 KiB
Markdown

# ERP-Suite - Arquitectura de Despliegue
## Resumen Ejecutivo
ERP-Suite es un **monorepo de microservicios con base de datos compartida**. Cada vertical es un proyecto independiente que:
- Se compila y despliega por separado
- Tiene su propia configuración de puertos
- Comparte la misma instancia de PostgreSQL pero con **schemas separados**
- Hereda patrones arquitectónicos de erp-core (no código directo)
---
## 1. Arquitectura General
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ ERP-SUITE ARCHITECTURE │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────────────────────────────────────────────────────────────┐│
│ │ NGINX (80/443) ││
│ │ erp.isem.dev | construccion.erp.isem.dev | mecanicas.erp.isem.dev ││
│ └─────────────────────────────────────────────────────────────────────────┘│
│ │ │
│ ┌───────────┐ ┌───────────┐ ┌───────────┐ ┌───────────┐ ┌───────────┐ │
│ │ ERP-CORE │ │CONSTRUCCION│ │ VIDRIO │ │ MECANICAS │ │ RETAIL │ │
│ │ FE: 3010 │ │ FE: 3020 │ │ FE: 3030 │ │ FE: 3040 │ │ FE: 3050 │ │
│ │ BE: 3011 │ │ BE: 3021 │ │ BE: 3031 │ │ BE: 3041 │ │ BE: 3051 │ │
│ └───────────┘ └───────────┘ └───────────┘ └───────────┘ └───────────┘ │
│ │
│ ┌───────────┐ ┌───────────┐ │
│ │ CLINICAS │ │ POS-MICRO │ │
│ │ FE: 3060 │ │ FE: 3070 │ │
│ │ BE: 3061 │ │ BE: 3071 │ │
│ └───────────┘ └───────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────┐│
│ │ PostgreSQL (5432) - BD COMPARTIDA ││
│ │ ┌─────────┐ ┌─────────┐ ┌─────────────┐ ┌─────────────┐ ┌───────────┐ ││
│ │ │ auth │ │ core │ │ construccion│ │ mecanicas │ │ retail │ ││
│ │ │ schema │ │ schema │ │ schema │ │ schema │ │ schema │ ││
│ │ └─────────┘ └─────────┘ └─────────────┘ └─────────────┘ └───────────┘ ││
│ └─────────────────────────────────────────────────────────────────────────┘│
│ │
└─────────────────────────────────────────────────────────────────────────────┘
```
---
## 2. Matriz de Componentes
### 2.1 Proyectos y Puertos
| Componente | Frontend | Backend | DB Schema | Redis | Estado |
|------------|----------|---------|-----------|-------|--------|
| **erp-core** | 3010 | 3011 | auth, core, inventory | 6379 | ✅ 60% |
| **construccion** | 3020 | 3021 | construccion (7 sub-schemas) | 6380 | ✅ 35% |
| **vidrio-templado** | 3030 | 3031 | vidrio | 6381 | ⏳ 0% |
| **mecanicas-diesel** | 3040 | 3041 | service_mgmt, parts_mgmt, vehicle_mgmt | 6379 | ⏳ 0% |
| **retail** | 3050 | 3051 | retail | 6383 | ⏳ 25% |
| **clinicas** | 3060 | 3061 | clinicas | 6384 | ⏳ 0% |
| **pos-micro** | 3070 | 3071 | pos | 6379 | ⏳ Planificado |
### 2.2 Subdominios
| Vertical | Frontend | API |
|----------|----------|-----|
| erp-core | erp.isem.dev | api.erp.isem.dev |
| construccion | construccion.erp.isem.dev | api.construccion.erp.isem.dev |
| vidrio-templado | vidrio.erp.isem.dev | api.vidrio.erp.isem.dev |
| mecanicas-diesel | mecanicas.erp.isem.dev | api.mecanicas.erp.isem.dev |
| retail | retail.erp.isem.dev | api.retail.erp.isem.dev |
| clinicas | clinicas.erp.isem.dev | api.clinicas.erp.isem.dev |
| pos-micro | pos.erp.isem.dev | api.pos.erp.isem.dev |
---
## 3. Estructura de Base de Datos
### 3.1 Modelo de Schemas
```sql
-- ORDEN DE CARGA DDL
-- 1. ERP-CORE (base requerida)
CREATE SCHEMA auth; -- users, tenants, roles, permissions
CREATE SCHEMA core; -- partners, products, categories
CREATE SCHEMA inventory; -- stock, locations, movements
-- 2. VERTICALES (dependen de auth.*, core.*)
CREATE SCHEMA construccion; -- projects, budgets, hr, hse, estimates
CREATE SCHEMA mecanicas; -- service_management, parts, vehicles
CREATE SCHEMA retail; -- pos, sales, ecommerce
CREATE SCHEMA clinicas; -- patients, appointments, medical
CREATE SCHEMA vidrio; -- quotes, production, installation
```
### 3.2 Dependencias de Schemas por Vertical
| Vertical | Schemas Propios | Depende de |
|----------|----------------|------------|
| **erp-core** | auth, core, inventory | - (base) |
| **construccion** | construccion.* | auth.tenants, auth.users, core.partners |
| **mecanicas-diesel** | service_mgmt, parts_mgmt, vehicle_mgmt | auth.tenants, auth.users |
| **retail** | retail.* | auth.*, core.products, inventory.* |
| **clinicas** | clinicas.* | auth.*, core.partners |
| **vidrio** | vidrio.* | auth.*, core.*, inventory.* |
### 3.3 Row-Level Security (RLS)
Todas las tablas implementan multi-tenancy via RLS:
```sql
-- Política estándar por tenant
ALTER TABLE construccion.projects ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON construccion.projects
USING (tenant_id = current_setting('app.current_tenant')::uuid);
```
---
## 4. Estrategia de Despliegue
### 4.1 Opción Recomendada: Despliegue Independiente por Vertical
Cada vertical se despliega como un servicio independiente:
```bash
# Estructura de despliegue
/opt/apps/erp-suite/
├── erp-core/
│ ├── docker-compose.yml
│ └── .env.production
├── construccion/
│ ├── docker-compose.yml
│ └── .env.production
├── mecanicas-diesel/
│ ├── docker-compose.yml
│ └── .env.production
└── shared/
└── nginx/
```
### 4.2 Pipeline de Despliegue
```
[Git Push] → [Jenkins] → [Build Images] → [Push Registry] → [Deploy]
├── erp-core → erp-core-backend:latest, erp-core-frontend:latest
├── construccion → construccion-backend:latest, construccion-frontend:latest
├── mecanicas → mecanicas-backend:latest, mecanicas-frontend:latest
└── ...
```
### 4.3 Orden de Despliegue
**IMPORTANTE:** Respetar el orden de despliegue:
1. **PostgreSQL** (si no existe)
2. **Redis** (si no existe)
3. **ERP-Core** (siempre primero - carga schemas base)
4. **Verticales** (en cualquier orden después de core)
---
## 5. Variables de Entorno por Vertical
### 5.1 Variables Comunes
```bash
# Todas las verticales comparten:
NODE_ENV=production
DB_HOST=localhost
DB_PORT=5432
DB_SSL=true
REDIS_HOST=localhost
JWT_SECRET=${JWT_SECRET} # Compartido para SSO
```
### 5.2 Variables Específicas por Vertical
| Variable | erp-core | construccion | mecanicas | retail |
|----------|----------|--------------|-----------|--------|
| PORT | 3011 | 3021 | 3041 | 3051 |
| DB_NAME | erp_generic | erp_generic | erp_generic | erp_generic |
| DB_SCHEMA | auth,core | construccion | mecanicas | retail |
| FRONTEND_URL | erp.isem.dev | construccion.erp.isem.dev | mecanicas.erp.isem.dev | retail.erp.isem.dev |
| REDIS_DB | 0 | 1 | 2 | 3 |
---
## 6. Docker Images
### 6.1 Naming Convention
```
${REGISTRY}/${PROJECT}-${COMPONENT}:${VERSION}
Ejemplos:
- 72.60.226.4:5000/erp-core-backend:1.0.0
- 72.60.226.4:5000/erp-core-frontend:1.0.0
- 72.60.226.4:5000/construccion-backend:1.0.0
- 72.60.226.4:5000/construccion-frontend:1.0.0
```
### 6.2 Base Images
| Componente | Base Image | Tamaño Aprox |
|------------|------------|--------------|
| Backend | node:20-alpine | ~150MB |
| Frontend | nginx:alpine | ~25MB |
---
## 7. Health Checks
### 7.1 Endpoints por Vertical
| Vertical | Health Endpoint | Expected Response |
|----------|-----------------|-------------------|
| erp-core | /health | `{"status":"ok","db":true,"redis":true}` |
| construccion | /health | `{"status":"ok","db":true}` |
| mecanicas | /health | `{"status":"ok","db":true}` |
### 7.2 Script de Verificación
```bash
#!/bin/bash
VERTICALS=("erp-core:3011" "construccion:3021" "mecanicas:3041")
for v in "${VERTICALS[@]}"; do
name="${v%%:*}"
port="${v##*:}"
status=$(curl -s "http://localhost:${port}/health" | jq -r '.status')
echo "${name}: ${status}"
done
```
---
## 8. Comandos de Despliegue
### 8.1 Despliegue Individual
```bash
# ERP-Core
cd /opt/apps/erp-suite/erp-core
docker-compose pull && docker-compose up -d
# Construcción
cd /opt/apps/erp-suite/construccion
docker-compose pull && docker-compose up -d
```
### 8.2 Despliegue Completo
```bash
# Desde Jenkins o script
./scripts/deploy-all.sh production
# O manualmente
cd /opt/apps/erp-suite
docker-compose -f docker-compose.full.yml up -d
```
### 8.3 Rollback
```bash
# Rollback específico
cd /opt/apps/erp-suite/construccion
docker-compose down
docker-compose pull --tag previous
docker-compose up -d
```
---
## 9. Monitoreo
### 9.1 Logs
```bash
# Ver logs de un vertical
docker logs -f construccion-backend
# Logs centralizados (si configurado)
tail -f /var/log/erp-suite/construccion/app.log
```
### 9.2 Métricas Clave
| Métrica | Descripción | Alerta |
|---------|-------------|--------|
| Response Time | Tiempo de respuesta API | > 2s |
| Error Rate | % de requests con error | > 5% |
| DB Connections | Conexiones activas | > 80% pool |
| Memory Usage | Uso de memoria | > 80% |
---
## 10. Troubleshooting
### 10.1 Problemas Comunes
| Problema | Causa | Solución |
|----------|-------|----------|
| Connection refused | Servicio no iniciado | `docker-compose up -d` |
| Schema not found | DDL no cargado | Ejecutar migrations de erp-core primero |
| Auth failed | JWT secret diferente | Verificar JWT_SECRET compartido |
| Tenant not found | RLS mal configurado | Verificar `SET app.current_tenant` |
### 10.2 Verificar Estado
```bash
# Estado de contenedores
docker ps --filter "name=erp"
# Verificar conectividad BD
docker exec erp-core-backend npm run db:check
# Verificar schemas
psql -h localhost -U erp_admin -d erp_generic -c "\dn"
```
---
## Referencias
- **Inventario de Puertos:** `core/orchestration/inventarios/DEVENV-PORTS-INVENTORY.yml`
- **Herencia ERP-Core:** `apps/verticales/*/database/HERENCIA-ERP-CORE.md`
- **Arquitectura General:** `core/orchestration/deployment/DEPLOYMENT-ARCHITECTURE.md`