# PLAN DE REESTRUCTURACION DOCUMENTAL # Proyecto: template-saas # Fecha: 2026-01-10 # Fase: Reestructuracion (Fase 5-7) # Estado: PENDIENTE APROBACION --- ## RESUMEN DE HALLAZGOS | Categoria | Encontrados | Criticos | Altos | Medios | |-----------|-------------|----------|-------|--------| | Discrepancias totales | 23 | 5 | 8 | 10 | | Referencias rotas | 34 | 19 (INT-0XX) | 14 (ADRs mal nombrados) | 1 | | Modulos sin documentar | 1 | WhatsApp | - | - | | Archivos obsoletos | ~15 | - | Sprints individuales | Analisis previos | --- ## ESTRUCTURA OBJETIVO (POST-REESTRUCTURACION) ``` docs/ ├── _MAP.md [ACTUALIZAR - Indice maestro] │ ├── 00-vision-general/ │ ├── README.md [MANTENER] │ ├── VISION-TEMPLATE-SAAS.md [MANTENER] │ ├── ESPECIFICACION-PLATAFORMA-SAAS.md [MANTENER] │ └── ARQUITECTURA-MULTI-TENANT.md [ACTUALIZAR - Quitar ref rota] │ ├── 01-modulos/ [MANTENER estructura plana] │ ├── SAAS-001-auth.md [MANTENER] │ ├── SAAS-002-tenants.md [MANTENER] │ ├── SAAS-003-users.md [MANTENER] │ ├── SAAS-004-billing.md [MANTENER] │ ├── SAAS-005-plans.md [MANTENER] │ ├── SAAS-006-ai-integration.md [MANTENER] │ ├── SAAS-007-notifications.md [MANTENER] │ ├── SAAS-008-audit-logs.md [MANTENER] │ ├── SAAS-009-feature-flags.md [MANTENER] │ ├── SAAS-010-webhooks.md [MANTENER] │ ├── SAAS-011-storage.md [MANTENER] │ ├── SAAS-012-crud-base.md [MANTENER] │ ├── SAAS-013-email.md [MANTENER] │ └── SAAS-014-whatsapp.md [CREAR - Nuevo] │ ├── 02-especificaciones/ │ ├── ET-SAAS-007-notifications-v2.md [MANTENER] │ └── PLAN-IMPLEMENTACION-NOTIFICATIONS-V2.md [MOVER a archivo] │ ├── 02-integraciones/ [DECISION: ELIMINAR o CONSOLIDAR] │ └── (vacio actualmente) │ ├── 02-devops/ │ └── CICD-GUIDE.md [MANTENER] │ └── architecture/ └── adr/ ├── ADR-001-multi-tenancy-rls.md [MANTENER] ├── ADR-002-authentication-jwt-oauth.md [MANTENER] ├── ADR-003-billing-stripe.md [MANTENER] ├── ADR-004-notifications-realtime.md [MANTENER] └── ADR-005-feature-flags.md [MANTENER] orchestration/ ├── CONTEXT-MAP.yml [ACTUALIZAR - Corregir refs] ├── PROJECT-STATUS.md [ACTUALIZAR - Agregar WhatsApp] ├── PROXIMA-ACCION.md [ACTUALIZAR] ├── GUIA-ORQUESTACION-SUBAGENTES.md [MANTENER] │ ├── 00-guidelines/ │ ├── CONTEXTO-PROYECTO.md [MANTENER] │ └── HERENCIA-SIMCO.md [MANTENER] │ ├── inventarios/ │ ├── MASTER_INVENTORY.yml [ACTUALIZAR - Agregar WhatsApp] │ ├── DATABASE_INVENTORY.yml [ACTUALIZAR - Schema whatsapp] │ ├── BACKEND_INVENTORY.yml [ACTUALIZAR - Modulo whatsapp] │ └── FRONTEND_INVENTORY.yml [ACTUALIZAR - WhatsApp UI] │ ├── planes/ │ └── HISTORICO-SPRINTS.md [CREAR - Consolidado] │ ├── _archivo/ [CREAR - Carpeta historico] │ ├── PLAN-SPRINT-1-TESTS.md [MOVER] │ ├── PLAN-SPRINT-2-ONBOARDING.md [MOVER] │ ├── PLAN-SPRINT-3-E2E.md [MOVER] │ ├── PLAN-SPRINT-4-DOCS.md [MOVER] │ ├── PLAN-SPRINT-5-WHATSAPP.md [MOVER] │ └── PLAN-CORRECCION-SPRINT-5*.md [MOVER] │ ├── trazas/ [EVALUAR - Mover a archivo] │ └── [archivos TRAZA-*.md] │ └── analisis/ [MANTENER solo actuales] ├── PLAN-MAESTRO-PURGA-DOCUMENTAL-2026-01-10.md ├── HALLAZGOS-ANALISIS-DOCUMENTAL-2026-01-10.md └── PLAN-REESTRUCTURACION-DOCUMENTAL-2026-01-10.md ``` --- ## ACCIONES DETALLADAS POR PRIORIDAD ### BLOQUE 1: ACCIONES CRITICAS (Ejecutar Primero) #### ACCION C1: Crear SAAS-014-whatsapp.md **Prioridad:** CRITICA **Dependencias:** Ninguna **Archivos afectados:** 1 nuevo **Detalle de contenido requerido:** ```markdown # SAAS-014: WhatsApp Business API ## Metadata - Codigo: SAAS-014 - Modulo: WhatsApp - Prioridad: P2 - Estado: Implementado - Fase: 5 - Integraciones - Sprint: Sprint 5 - Fecha Implementacion: 2026-01-10 ## Descripcion Integracion con WhatsApp Business API (Meta Cloud API) para envio de mensajes y notificaciones via WhatsApp. ## Alcance ### Incluido - Envio de mensajes de texto - Envio de templates pre-aprobados - Webhook para recibir status de entrega - Configuracion por tenant - Rate limiting - Historial de mensajes ### Excluido - Chatbots interactivos - Mensajes multimedia (imagenes, videos) - Grupos de WhatsApp ## Modelo de Datos ### Schema: whatsapp #### Tabla: whatsapp_configs - tenant_id (uuid, FK) - phone_number_id (varchar) - waba_id (varchar) - access_token (text, encrypted) - is_active (boolean) - rate_limit_per_minute (integer) #### Tabla: whatsapp_messages - id (uuid, PK) - tenant_id (uuid, FK) - to_phone (varchar) - message_type (enum) - template_name (varchar, nullable) - content (text) - status (enum) - wamid (varchar) - sent_at (timestamp) - delivered_at (timestamp, nullable) - read_at (timestamp, nullable) - error_message (text, nullable) ## Endpoints API - POST /whatsapp/config - Configurar credenciales - GET /whatsapp/config - Obtener configuracion - PUT /whatsapp/config - Actualizar configuracion - DELETE /whatsapp/config - Desactivar integracion - POST /whatsapp/test - Enviar mensaje de prueba - POST /whatsapp/send - Enviar mensaje - GET /whatsapp/messages - Historial de mensajes - POST /whatsapp/webhook - Webhook de Meta ## Dependencias - SAAS-002 (Tenants) - tenant_id en configs y messages - SAAS-007 (Notifications) - Canal adicional de notificacion ## Criterios de Aceptacion - [ ] Configuracion de credenciales por tenant - [ ] Envio de mensajes de texto exitoso - [ ] Envio de templates exitoso - [ ] Webhook recibe y procesa status - [ ] Rate limiting funciona correctamente - [ ] Historial de mensajes accesible ``` --- #### ACCION C2: Actualizar _MAP.md con nomenclatura correcta **Prioridad:** CRITICA **Dependencias:** C1 completada **Archivos afectados:** docs/_MAP.md **Cambios especificos:** 1. **Lineas 17-37**: Actualizar estructura propuesta a estructura real (archivos planos) 2. **Lineas 62-94**: Actualizar tabla de modulos con nomenclatura correcta: ```markdown | Modulo | Codigo | Estado | Descripcion | |--------|--------|--------|-------------| | Auth | SAAS-001 | Completado | JWT, OAuth, MFA | | Tenants | SAAS-002 | Completado | Gestion multi-tenant | | Users | SAAS-003 | Completado | Usuarios con RBAC | | Billing | SAAS-004 | Completado | Suscripciones Stripe | | Plans | SAAS-005 | Completado | Planes y limites | | AI Integration | SAAS-006 | Completado | Wrapper multi-proveedor LLM | | Notifications | SAAS-007 | Completado | Email, push, in-app, WhatsApp | | Audit Logs | SAAS-008 | Completado | Auditoria de acciones | | Feature Flags | SAAS-009 | Completado | Toggles por plan/tenant | | Webhooks | SAAS-010 | Completado | Webhooks outbound con BullMQ | | Storage | SAAS-011 | Completado | S3, R2, MinIO | | CRUD Base | SAAS-012 | Completado | Patrones base reutilizables | | Email | SAAS-013 | Completado | SendGrid, SES, SMTP | | WhatsApp | SAAS-014 | Completado | WhatsApp Business API | ``` 3. **Lineas 39-57**: Eliminar o actualizar seccion de integraciones INT-XXX - OPCION A: Eliminar completamente (ya cubierto en modulos) - OPCION B: Actualizar con nota "Ver documentacion en modulos SAAS-XXX correspondientes" 4. **Lineas 51-57**: Corregir nombres de ADRs: ```markdown | ADR | Titulo | Estado | |-----|--------|--------| | ADR-001 | Multi-tenancy con RLS | Completado | | ADR-002 | Authentication JWT + OAuth | Completado | | ADR-003 | Billing con Stripe | Completado | | ADR-004 | Notifications Real-time | Completado | | ADR-005 | Feature Flags por Tenant | Completado | ``` 5. **Linea 129**: Actualizar total de tablas de 38 a numero correcto (35-37) --- #### ACCION C3: Actualizar CONTEXT-MAP.yml **Prioridad:** CRITICA **Dependencias:** C1, C2 completadas **Archivos afectados:** orchestration/CONTEXT-MAP.yml **Cambios especificos:** 1. **Lineas 175-210**: Corregir referencias de modulos (de directorios a archivos): ```yaml modulos_saas: - SAAS-001-auth: descripcion: "Autenticacion JWT, OAuth, MFA" ruta: "@DOCS/01-modulos/SAAS-001-auth.md" # Cambiar de SAAS-001-auth/ a .md - SAAS-002-tenants: descripcion: "Gestion de organizaciones multi-tenant" ruta: "@DOCS/01-modulos/SAAS-002-tenants.md" # ... continuar con todos - SAAS-014-whatsapp: descripcion: "WhatsApp Business API Integration" ruta: "@DOCS/01-modulos/SAAS-014-whatsapp.md" ``` 2. **Lineas 213-227**: Actualizar o eliminar integraciones INT-XXX (decision pendiente) --- #### ACCION C4: Actualizar Inventarios con WhatsApp **Prioridad:** CRITICA **Dependencias:** C1 completada **Archivos afectados:** 4 archivos **MASTER_INVENTORY.yml:** ```yaml modulos: # ... existentes ... whatsapp: codigo: "SAAS-014" nombre: "WhatsApp Business API" estado: "completado" prioridad: "P2" fase: "5-integraciones" sprint: "Sprint 5" dependencias: - tenants - notifications backend: module: true service: true controller: true entities: 2 tests: 22 database: schema: "whatsapp" tables: 2 enums: 3 frontend: page: "WhatsAppSettings.tsx" hooks: 1 api: 1 ``` **DATABASE_INVENTORY.yml:** ```yaml schemas: # ... existentes (11) ... whatsapp: estado: "completado" tables: - name: "whatsapp_configs" columns: 8 rls: true - name: "whatsapp_messages" columns: 12 rls: true enums: - message_status - message_type - message_direction functions: [] ``` **BACKEND_INVENTORY.yml:** ```yaml modules: # ... existentes (15) ... whatsapp: estado: "completado" archivos: - whatsapp.module.ts - whatsapp.service.ts - whatsapp.controller.ts - whatsapp-webhook.controller.ts entities: - whatsapp-config.entity.ts - whatsapp-message.entity.ts dtos: - create-config.dto.ts - send-message.dto.ts tests: - whatsapp.service.spec.ts ``` **FRONTEND_INVENTORY.yml:** ```yaml pages: admin: # ... existentes ... - name: "WhatsAppSettings.tsx" ruta: "/admin/whatsapp" descripcion: "Configuracion de WhatsApp Business" hooks: # ... existentes ... - useWhatsApp.ts services: # ... existentes ... - whatsapp.api.ts ``` --- ### BLOQUE 2: ACCIONES ALTAS (Ejecutar Segundo) #### ACCION A1: Crear HISTORICO-SPRINTS.md consolidado **Prioridad:** ALTA **Dependencias:** Ninguna **Archivos afectados:** 1 nuevo + 6 movidos **Contenido:** ```markdown # HISTORICO DE SPRINTS - Template SaaS ## Linea de Tiempo ``` Sprint 1 ─── Sprint 2 ─── Sprint 3 ─── Sprint 4 ─── Sprint 5 Tests Onboarding E2E ADRs WhatsApp 76% cov 11 endpoints 47 tests 5 docs 8 endpoints ``` ## Sprint 1: Test Coverage (Completado 2026-01-10) - **Objetivo:** Subir cobertura de 62.56% a 80% - **Resultado:** 76.37% (+13.81%) - **Tests agregados:** +323 - **SP:** 8 ## Sprint 2: Onboarding Wizard (Completado 2026-01-10) - **Objetivo:** Backend para wizard de onboarding - **Resultado:** 11 endpoints, 23 archivos - **Tests agregados:** +66 - **SP:** 8 ## Sprint 3: E2E Tests (Completado 2026-01-10) - **Objetivo:** Tests E2E con Playwright - **Resultado:** 47 tests E2E, 5 flujos cubiertos - **SP:** 8 ## Sprint 4: ADR Documentation (Completado 2026-01-10) - **Objetivo:** Documentar decisiones arquitectonicas - **Resultado:** 5 ADRs formales - **SP:** 5 ## Sprint 5: WhatsApp Integration (Completado 2026-01-10) - **Objetivo:** Integrar WhatsApp Business API - **Resultado:** Modulo completo (DDL, Backend, Frontend) - **Tests agregados:** +22 - **SP:** 13 ## Totales - **Story Points:** 42 - **Tests agregados:** ~458 - **Cobertura final:** 76.37% - **Modulos nuevos:** 1 (WhatsApp) - **ADRs:** 5 ``` #### ACCION A2: Crear carpeta _archivo y mover sprints **Prioridad:** ALTA **Dependencias:** A1 completada **Archivos afectados:** 6 movidos ```bash mkdir -p orchestration/_archivo mv orchestration/planes/PLAN-SPRINT-*.md orchestration/_archivo/ mv orchestration/planes/PLAN-CORRECCION-*.md orchestration/_archivo/ ``` #### ACCION A3: Actualizar PROJECT-STATUS.md **Prioridad:** ALTA **Dependencias:** C1-C4 completadas **Archivos afectados:** orchestration/PROJECT-STATUS.md **Cambios:** 1. Agregar WhatsApp a seccion de modulos 2. Actualizar fase a "7 - Mantenimiento" 3. Agregar nota sobre reestructuracion documental completada #### ACCION A4: Eliminar referencia rota en ARQUITECTURA-MULTI-TENANT.md **Prioridad:** ALTA **Dependencias:** Ninguna **Archivos afectados:** docs/00-vision-general/ARQUITECTURA-MULTI-TENANT.md **Linea 471:** Eliminar o actualizar referencia a `../../database/README.md` --- ### BLOQUE 3: ACCIONES MEDIAS (Ejecutar Tercero) #### ACCION M1: Decidir sobre docs/02-integraciones/ **Prioridad:** MEDIA **Dependencias:** C2 completada **Decision requerida:** - **OPCION A:** Eliminar carpeta (integraciones ya documentadas en SAAS-XXX) - **OPCION B:** Crear documentos minimos con referencias a SAAS-XXX - **OPCION C:** Mantener vacia con nota "Consolidado en modulos" **Recomendacion:** OPCION A - Eliminar y actualizar _MAP.md #### ACCION M2: Limpiar analisis antiguos **Prioridad:** MEDIA **Dependencias:** Reestructuracion completada **Archivos afectados:** orchestration/analisis/ **Mover a _archivo:** - ANALISIS-MAESTRO-TEMPLATE-SAAS.md - Archivos de validacion de sprint anteriores #### ACCION M3: Actualizar fechas de ultima modificacion **Prioridad:** MEDIA **Dependencias:** Todas las acciones anteriores **Archivos afectados:** Todos los archivos modificados --- ## ORDEN DE EJECUCION ``` FASE 1: CRITICAS ├── C1: Crear SAAS-014-whatsapp.md ├── C2: Actualizar _MAP.md (depende de C1) ├── C3: Actualizar CONTEXT-MAP.yml (depende de C1, C2) └── C4: Actualizar inventarios (depende de C1) FASE 2: ALTAS ├── A1: Crear HISTORICO-SPRINTS.md ├── A2: Crear _archivo y mover sprints (depende de A1) ├── A3: Actualizar PROJECT-STATUS.md (depende de C1-C4) └── A4: Eliminar referencia rota FASE 3: MEDIAS ├── M1: Decidir sobre 02-integraciones/ ├── M2: Limpiar analisis antiguos └── M3: Actualizar fechas FASE 4: VALIDACION ├── V1: Verificar todas las referencias cruzadas ├── V2: Validar consistencia de nomenclatura └── V3: Generar reporte de validacion final ``` --- ## CRITERIOS DE VALIDACION ### Para cada archivo modificado: | Criterio | Descripcion | |----------|-------------| | Contenido actualizado | Refleja estado actual del codigo | | Referencias validas | Todos los links funcionan | | Sin duplicados | No hay definiciones repetidas | | Nomenclatura consistente | Usa misma convencion SAAS-XXX | | Fechas actualizadas | Ultima actualizacion correcta | ### Para el proyecto completo: | Criterio | Metrica | |----------|---------| | Cobertura documental | 100% modulos implementados | | Referencias rotas | 0 | | Modulos sin documentar | 0 | | Archivos obsoletos en ubicacion activa | 0 | --- ## RIESGOS Y MITIGACIONES | Riesgo | Probabilidad | Impacto | Mitigacion | |--------|--------------|---------|------------| | Referencias cruzadas adicionales no detectadas | Media | Medio | Busqueda exhaustiva post-cambio | | Perdida de informacion en consolidacion | Baja | Alto | Mover a _archivo, no eliminar | | Inconsistencias introducidas durante cambios | Media | Medio | Validacion por fases | --- ## ESTIMACION DE ESFUERZO | Fase | Acciones | Estimacion | |------|----------|------------| | Criticas | 4 | ~2 horas | | Altas | 4 | ~1 hora | | Medias | 3 | ~30 min | | Validacion | 3 | ~1 hora | | **Total** | **14** | **~4.5 horas** | --- ## APROBACION REQUERIDA ### Decisiones pendientes: 1. **Carpeta 02-integraciones/**: Eliminar, consolidar o mantener vacia? 2. **Documentacion adicional**: Crear README.md para apps/database/? 3. **Nivel de detalle en SAAS-014-whatsapp.md**: Completo o minimo? --- **Estado:** PENDIENTE APROBACION **Fecha:** 2026-01-10 **Siguiente paso:** Aprobacion del usuario para iniciar ejecucion