erp-core/docs/01-fase-foundation/MGN-004-tenants/requerimientos/INDICE-RF-TENANT.md

14 KiB

Indice de Requerimientos Funcionales - MGN-004 Tenants

Resumen del Modulo

Campo Valor
Modulo MGN-004
Nombre Tenants (Multi-Tenancy)
Descripcion Arquitectura multi-tenant con aislamiento de datos
Total RFs 4
Story Points 100
Estado Ready
Fecha 2025-12-05

Lista de Requerimientos

ID Nombre Prioridad SP Estado
RF-TENANT-001 Gestion de Tenants P0 29 Ready
RF-TENANT-002 Configuracion de Tenant P0 19 Ready
RF-TENANT-003 Aislamiento de Datos P0 20 Ready
RF-TENANT-004 Subscripciones y Limites P1 32 Ready

Diagrama de Arquitectura Multi-Tenant

┌─────────────────────────────────────────────────────────────────┐
│                      Platform Layer                              │
├─────────────────────────────────────────────────────────────────┤
│  Platform Admin UI     │    API Gateway    │    Auth Service    │
│  (Gestion tenants)     │   (Routing)       │   (JWT + tenant)   │
└─────────────────────────────────────────────────────────────────┘
                                │
                                ▼
┌─────────────────────────────────────────────────────────────────┐
│                      Application Layer                           │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐             │
│  │ TenantGuard │  │  RbacGuard  │  │LimitGuard   │             │
│  │(Contexto)   │  │ (Permisos)  │  │(Subscripcion)│             │
│  └─────────────┘  └─────────────┘  └─────────────┘             │
│                                                                  │
│  ┌─────────────────────────────────────────────────────────────┐│
│  │              TenantAwareServices                             ││
│  │  (Todos los servicios heredan contexto de tenant)           ││
│  └─────────────────────────────────────────────────────────────┘│
│                                                                  │
└─────────────────────────────────────────────────────────────────┘
                                │
                                ▼
┌─────────────────────────────────────────────────────────────────┐
│                      Data Layer                                  │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  PostgreSQL Database (Shared)                                    │
│                                                                  │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐             │
│  │  Tenant A   │  │  Tenant B   │  │  Tenant C   │             │
│  │  tenant_id  │  │  tenant_id  │  │  tenant_id  │             │
│  │  =uuid-a    │  │  =uuid-b    │  │  =uuid-c    │             │
│  └─────────────┘  └─────────────┘  └─────────────┘             │
│                                                                  │
│  Row Level Security (RLS) - Aislamiento automatico              │
│  SET app.current_tenant_id = 'tenant-uuid'                      │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

Flujo de Request Multi-Tenant

┌─────────────────────────────────────────────────────────────────┐
│                        Request Flow                              │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  1. Request HTTP                                                 │
│     └─> Authorization: Bearer {JWT con tenant_id}               │
│                                                                  │
│  2. JwtAuthGuard                                                │
│     └─> Valida token, extrae user + tenant_id                   │
│                                                                  │
│  3. TenantGuard                                                 │
│     └─> Verifica tenant activo                                  │
│     └─> Inyecta tenant en request                               │
│                                                                  │
│  4. TenantContextMiddleware                                     │
│     └─> SET app.current_tenant_id = :tenantId                   │
│                                                                  │
│  5. LimitGuard (si aplica)                                      │
│     └─> Verifica limites de subscripcion                        │
│                                                                  │
│  6. RbacGuard                                                   │
│     └─> Valida permisos del usuario                             │
│                                                                  │
│  7. Controller                                                  │
│     └─> Ejecuta logica de negocio                               │
│                                                                  │
│  8. TenantAwareService                                          │
│     └─> Automaticamente filtra por tenant                       │
│                                                                  │
│  9. PostgreSQL RLS                                              │
│     └─> Ultima linea de defensa                                 │
│     └─> WHERE tenant_id = current_setting('app.current_tenant_id')│
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

Estados del Tenant

                         ┌──────────────┐
                         │   created    │
                         └──────┬───────┘
                                │
                                ▼
                         ┌──────────────┐
             ┌──────────│    trial     │──────────┐
             │          └──────┬───────┘          │
             │                 │                   │
             │ (upgrade)       │ (trial expires)  │ (convert)
             │                 │                   │
             │                 ▼                   │
             │          ┌──────────────┐          │
             │          │trial_expired │          │
             │          └──────────────┘          │
             │                                     │
             ▼                                     ▼
      ┌──────────────┐                     ┌──────────────┐
      │    active    │◄────────────────────│   active     │
      └──────┬───────┘    (reactivate)     └──────┬───────┘
             │                                     │
             │ (suspend)                           │
             │                                     │
             ▼                                     │
      ┌──────────────┐                            │
      │  suspended   │────────────────────────────┘
      └──────┬───────┘
             │
             │ (schedule delete)
             ▼
      ┌──────────────────┐
      │ pending_deletion │
      └────────┬─────────┘
               │
               │ (30 days grace)
               ▼
      ┌──────────────┐
      │   deleted    │
      └──────────────┘

Planes de Subscripcion

Plan Usuarios Storage Modulos API Calls Precio
Trial 5 1 GB Basicos 1K/mes Gratis
Starter 10 5 GB Basicos 10K/mes $29/mes
Professional 50 25 GB Standard 50K/mes $99/mes
Enterprise 100 GB Premium 500K/mes $299/mes
Custom Config Config Config Config Cotizacion

Tablas de Base de Datos

Tabla Descripcion
tenants Tenants registrados
tenant_settings Configuracion de cada tenant (JSONB)
subscriptions Subscripciones activas y pasadas
plans Planes de subscripcion disponibles
invoices Historial de facturacion
tenant_modules Modulos activos por tenant

Estimacion Total

Capa Story Points
Backend: CRUD Tenants 12
Backend: Settings 7
Backend: RLS & Guards 15
Backend: Subscriptions 15
Backend: Billing 10
Backend: Tests 12
Frontend: Platform Admin 15
Frontend: Tenant Settings 8
Frontend: Subscription UI 8
Frontend: Tests 6
Total 108 SP

Nota: Los 100 SP indicados en resumen corresponden a la suma de RF individuales.


Definition of Done del Modulo

  • RF-TENANT-001: CRUD de tenants funcional
  • RF-TENANT-002: Settings por tenant operativos
  • RF-TENANT-003: RLS aplicado en TODAS las tablas
  • RF-TENANT-003: Tests de aislamiento pasando
  • RF-TENANT-004: Planes y limites configurados
  • RF-TENANT-004: Enforcement de limites activo
  • Platform Admin UI completa
  • Tests unitarios > 80% coverage
  • Tests de aislamiento exhaustivos
  • Security review de RLS aprobado
  • Performance tests con multiples tenants

Consideraciones de Seguridad

Aislamiento de Datos

  • RLS como ultima linea de defensa
  • Validacion en TODAS las capas
  • Nunca confiar en input del cliente
  • Auditar accesos cross-tenant

Platform Admin

  • Autenticacion separada
  • 2FA obligatorio
  • Logs de todas las acciones
  • Switch de tenant explicito y auditado

Datos Sensibles

  • Encriptar datos sensibles por tenant
  • Claves de encriptacion por tenant
  • Backups separados (opcional enterprise)

Notas de Implementacion

Orden Recomendado

  1. Primero: RF-TENANT-003 (RLS) - Base para todo lo demas
  2. Segundo: RF-TENANT-001 (CRUD) - Crear tenants
  3. Tercero: RF-TENANT-002 (Settings) - Configurar tenants
  4. Cuarto: RF-TENANT-004 (Subscriptions) - Monetizacion

Migracion de Datos Existentes

Si hay datos sin tenant_id:

  1. Crear tenant "default"
  2. Asignar todos los datos al default
  3. Habilitar RLS
  4. Migrar datos a tenants especificos

Historial

Version Fecha Autor Cambios
1.0 2025-12-05 System Creacion inicial con 4 RFs