michangarrito/orchestration/_archive/analisis/GAP-ANALYSIS-BD-2026-01-13.md
Adrian Flores Cortes 2fb9f3f6b5
Some checks are pending
CI/CD Pipeline / Backend CI (push) Waiting to run
CI/CD Pipeline / Frontend CI (push) Waiting to run
CI/CD Pipeline / WhatsApp Service CI (push) Waiting to run
CI/CD Pipeline / Mobile CI (push) Waiting to run
CI/CD Pipeline / Docker Build (./apps/backend, ./apps/backend/Dockerfile, backend) (push) Blocked by required conditions
CI/CD Pipeline / Docker Build (./apps/frontend, ./apps/frontend/Dockerfile, frontend) (push) Blocked by required conditions
CI/CD Pipeline / Docker Build (./apps/whatsapp-service, ./apps/whatsapp-service/Dockerfile, whatsapp-service) (push) Blocked by required conditions
CI/CD Pipeline / Deploy to Production (push) Blocked by required conditions
[ESTANDAR-ORCHESTRATION] refactor: Consolidate to standard structure
- Move 7 non-standard folders to _archive/
- Archive 3 extra root files
- Update _MAP.md with standardized structure

Standard: SIMCO-ESTANDAR-ORCHESTRATION v1.0.0
Level: CONSUMER (L2)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-24 14:38:04 -06:00

12 KiB

Gap Analysis - Base de Datos

Proyecto: michangarrito Fecha: 2026-01-13 Tipo: Analisis de gaps post-integracion template-saas Estado: COMPLETADO


Resumen Ejecutivo

La integracion de epicas desde template-saas (MCH-029 a MCH-035) requiere objetos de base de datos que actualmente no existen en el proyecto.

Categoria Existentes Requeridos Gap
Schemas 8 13 5 nuevos
Tablas auth 3 4 1 nueva
Archivos DDL 17 22 5 nuevos
EXPECTED_SCHEMAS 9 14 5 nuevos

1. Estado Actual de la Base de Datos

1.1 Schemas Existentes (01-schemas.sql)

auth         -- Autenticacion y usuarios
catalog      -- Productos y categorias
sales        -- Ventas, pagos y cortes
inventory    -- Stock y movimientos
customers    -- Clientes y fiados
orders       -- Pedidos y entregas
subscriptions -- Planes y tokens IA
messaging    -- WhatsApp y notificaciones

1.2 Archivos DDL Actuales

database/schemas/
├── 00-extensions.sql
├── 01-schemas.sql
├── 02-functions.sql
├── 03-public.sql
├── 04-auth.sql         <- Falta: oauth_connections
├── 05-catalog.sql
├── 06-sales.sql
├── 07-inventory.sql
├── 08-customers.sql
├── 09-orders.sql
├── 10-subscriptions.sql
├── 11-messaging.sql
├── 12-integrations.sql
├── 13-referrals.sql
├── 14-codi-spei.sql
├── 15-invoices.sql
└── 16-marketplace.sql

1.3 EXPECTED_SCHEMAS en recreate-database.sh (linea 148)

EXPECTED_SCHEMAS=("public" "auth" "catalog" "sales" "inventory" "customers" "orders" "subscriptions" "messaging")

2. Requerimientos por Epica

MCH-029: Infraestructura SaaS Avanzada

Componente Schema Tablas Requeridas Estado
Storage storage storage.files, storage.buckets FALTA
Webhooks webhooks webhooks.endpoints, webhooks.deliveries, webhooks.events FALTA
Rate Limiting public public.rate_limits FALTA
Redis Cache N/A Solo codigo, no DDL N/A

MCH-030: Auth Social (OAuth 2.0)

Componente Schema Tablas Requeridas Estado
OAuth Connections auth auth.oauth_connections FALTA

MCH-031: Auditoria Empresarial

Componente Schema Tablas Requeridas Estado
Audit Logs audit audit.logs, audit.events FALTA
Retention audit audit.retention_policies FALTA

MCH-032: Feature Flags por Plan

Componente Schema Tablas Requeridas Estado
Features features features.flags, features.tenant_flags FALTA

MCH-034: Analytics y Metricas

Componente Schema Tablas Requeridas Estado
Metricas analytics analytics.metrics, analytics.aggregations FALTA
Events analytics analytics.events FALTA

MCH-035: Sistema de Reportes

Componente Schema Tablas Requeridas Estado
Reportes analytics analytics.reports, analytics.report_exports FALTA

3. Plan de Acciones DDL

3.1 Actualizar 01-schemas.sql

Agregar los siguientes schemas:

-- Schema de almacenamiento
CREATE SCHEMA IF NOT EXISTS storage;
COMMENT ON SCHEMA storage IS 'Almacenamiento de archivos';

-- Schema de webhooks
CREATE SCHEMA IF NOT EXISTS webhooks;
COMMENT ON SCHEMA webhooks IS 'Sistema de webhooks salientes';

-- Schema de auditoria
CREATE SCHEMA IF NOT EXISTS audit;
COMMENT ON SCHEMA audit IS 'Logs de auditoria empresarial';

-- Schema de features
CREATE SCHEMA IF NOT EXISTS features;
COMMENT ON SCHEMA features IS 'Feature flags por plan/tenant';

-- Schema de analytics
CREATE SCHEMA IF NOT EXISTS analytics;
COMMENT ON SCHEMA analytics IS 'Metricas y reportes';

-- Permisos
GRANT USAGE ON SCHEMA storage TO michangarrito_dev;
GRANT USAGE ON SCHEMA webhooks TO michangarrito_dev;
GRANT USAGE ON SCHEMA audit TO michangarrito_dev;
GRANT USAGE ON SCHEMA features TO michangarrito_dev;
GRANT USAGE ON SCHEMA analytics TO michangarrito_dev;

3.2 Actualizar 04-auth.sql

Agregar tabla oauth_connections:

-- Conexiones OAuth (Google, Apple)
CREATE TABLE IF NOT EXISTS auth.oauth_connections (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,

    provider VARCHAR(20) NOT NULL,  -- 'google', 'apple'
    provider_user_id VARCHAR(255) NOT NULL,

    access_token TEXT,
    refresh_token TEXT,
    token_expires_at TIMESTAMPTZ,

    email VARCHAR(255),
    name VARCHAR(255),
    avatar_url TEXT,

    raw_data JSONB DEFAULT '{}',

    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW(),

    UNIQUE(provider, provider_user_id),
    UNIQUE(user_id, provider)
);

CREATE INDEX idx_oauth_connections_user ON auth.oauth_connections(user_id);
CREATE INDEX idx_oauth_connections_provider ON auth.oauth_connections(provider, provider_user_id);

3.3 Crear 17-storage.sql

-- Buckets de almacenamiento
CREATE TABLE IF NOT EXISTS storage.buckets (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name VARCHAR(100) NOT NULL UNIQUE,
    public BOOLEAN DEFAULT false,
    file_size_limit INTEGER,
    allowed_mime_types TEXT[],
    created_at TIMESTAMPTZ DEFAULT NOW()
);

-- Archivos almacenados
CREATE TABLE IF NOT EXISTS storage.files (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,
    bucket_id UUID NOT NULL REFERENCES storage.buckets(id) ON DELETE CASCADE,

    name VARCHAR(255) NOT NULL,
    path VARCHAR(500) NOT NULL,
    mime_type VARCHAR(100),
    size INTEGER NOT NULL,

    metadata JSONB DEFAULT '{}',

    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW(),

    UNIQUE(bucket_id, path)
);

3.4 Crear 18-webhooks.sql

-- Endpoints de webhook
CREATE TABLE IF NOT EXISTS webhooks.endpoints (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,

    url VARCHAR(500) NOT NULL,
    secret VARCHAR(255) NOT NULL,
    events TEXT[] NOT NULL,

    is_active BOOLEAN DEFAULT true,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- Entregas de webhook
CREATE TABLE IF NOT EXISTS webhooks.deliveries (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    endpoint_id UUID NOT NULL REFERENCES webhooks.endpoints(id) ON DELETE CASCADE,

    event_type VARCHAR(100) NOT NULL,
    payload JSONB NOT NULL,

    status VARCHAR(20) DEFAULT 'pending',
    response_code INTEGER,
    response_body TEXT,

    attempts INTEGER DEFAULT 0,
    next_retry_at TIMESTAMPTZ,

    created_at TIMESTAMPTZ DEFAULT NOW(),
    delivered_at TIMESTAMPTZ
);

3.5 Crear 19-audit.sql

-- Logs de auditoria
CREATE TABLE IF NOT EXISTS audit.logs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,

    user_id UUID,
    action VARCHAR(50) NOT NULL,
    resource_type VARCHAR(50) NOT NULL,
    resource_id UUID,

    old_values JSONB,
    new_values JSONB,

    ip_address VARCHAR(45),
    user_agent TEXT,

    created_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX idx_audit_logs_tenant ON audit.logs(tenant_id);
CREATE INDEX idx_audit_logs_created ON audit.logs(created_at DESC);
CREATE INDEX idx_audit_logs_action ON audit.logs(action);

-- Politicas de retencion
CREATE TABLE IF NOT EXISTS audit.retention_policies (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,

    retention_days INTEGER NOT NULL DEFAULT 90,
    created_at TIMESTAMPTZ DEFAULT NOW()
);

3.6 Crear 20-features.sql

-- Feature flags globales
CREATE TABLE IF NOT EXISTS features.flags (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

    key VARCHAR(100) NOT NULL UNIQUE,
    name VARCHAR(255) NOT NULL,
    description TEXT,

    default_value BOOLEAN DEFAULT false,

    plans_enabled TEXT[] DEFAULT '{}',

    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- Feature flags por tenant (override)
CREATE TABLE IF NOT EXISTS features.tenant_flags (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,
    flag_id UUID NOT NULL REFERENCES features.flags(id) ON DELETE CASCADE,

    enabled BOOLEAN NOT NULL,

    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW(),

    UNIQUE(tenant_id, flag_id)
);

3.7 Crear 21-analytics.sql

-- Metricas agregadas
CREATE TABLE IF NOT EXISTS analytics.metrics (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,

    metric_type VARCHAR(50) NOT NULL,
    period_type VARCHAR(20) NOT NULL, -- 'daily', 'weekly', 'monthly'
    period_start DATE NOT NULL,

    value DECIMAL(15, 2) NOT NULL,
    metadata JSONB DEFAULT '{}',

    created_at TIMESTAMPTZ DEFAULT NOW(),

    UNIQUE(tenant_id, metric_type, period_type, period_start)
);

CREATE INDEX idx_analytics_metrics_tenant ON analytics.metrics(tenant_id);
CREATE INDEX idx_analytics_metrics_period ON analytics.metrics(period_start DESC);

-- Eventos de analytics
CREATE TABLE IF NOT EXISTS analytics.events (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,

    event_type VARCHAR(100) NOT NULL,
    properties JSONB DEFAULT '{}',

    created_at TIMESTAMPTZ DEFAULT NOW()
);

-- Reportes generados
CREATE TABLE IF NOT EXISTS analytics.reports (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,

    report_type VARCHAR(50) NOT NULL,
    name VARCHAR(255) NOT NULL,

    parameters JSONB DEFAULT '{}',

    status VARCHAR(20) DEFAULT 'pending',
    file_url TEXT,
    file_format VARCHAR(10), -- 'pdf', 'xlsx', 'csv'

    created_at TIMESTAMPTZ DEFAULT NOW(),
    completed_at TIMESTAMPTZ,
    expires_at TIMESTAMPTZ
);

3.8 Actualizar recreate-database.sh

# Linea 148 - Actualizar array
EXPECTED_SCHEMAS=("public" "auth" "catalog" "sales" "inventory" "customers" "orders" "subscriptions" "messaging" "storage" "webhooks" "audit" "features" "analytics")

4. Matriz de Trazabilidad

Archivo DDL Epica Schemas Tablas Nuevas
01-schemas.sql MCH-029,031,032,034 storage,webhooks,audit,features,analytics -
04-auth.sql MCH-030 auth oauth_connections
17-storage.sql MCH-029 storage buckets, files
18-webhooks.sql MCH-029 webhooks endpoints, deliveries
19-audit.sql MCH-031 audit logs, retention_policies
20-features.sql MCH-032 features flags, tenant_flags
21-analytics.sql MCH-034,035 analytics metrics, events, reports

5. Checklist de Ejecucion

  • Actualizar 01-schemas.sql con 5 nuevos schemas
  • Agregar auth.oauth_connections a 04-auth.sql
  • Crear 17-storage.sql (111 lineas)
  • Crear 18-webhooks.sql (142 lineas)
  • Crear 19-audit.sql (201 lineas)
  • Crear 20-features.sql (182 lineas)
  • Crear 21-analytics.sql (290 lineas)
  • Actualizar EXPECTED_SCHEMAS en recreate-database.sh
  • Ejecutar scripts DDL directamente en PostgreSQL
  • Verificar schemas y tablas creados

Ejecucion: Scripts ejecutados directamente via psql (2026-01-13)


Generado por: Sistema SIMCO - Agente Orquestador Fecha: 2026-01-13 Version: 1.0.0