# PLAN DE CORRECCIÓN - SPRINT 5 (WhatsApp Integration)
**Fecha:** 2026-01-10
**Fase:** 3 - Planeación Detallada
**Basado en:** ANALISIS-VALIDACION-SPRINT-5-2026-01-10.md
**Estado:** PENDIENTE
---
## RESUMEN EJECUTIVO
Este plan detalla las correcciones necesarias para integrar completamente el módulo WhatsApp en template-saas. Se identificaron 9 GAPS críticos que deben ser resueltos en el orden especificado.
---
## FASE A: CORRECCIONES DDL (Bloqueantes para DB)
### TASK-A1: Agregar schema whatsapp a 01-schemas.sql
**Archivo:** `apps/database/ddl/01-schemas.sql`
**Línea:** Después de línea 19 (webhooks)
**Acción:** INSERT
```sql
-- Integration schemas
CREATE SCHEMA IF NOT EXISTS whatsapp;
```
**Y agregar comentario después de línea 32:**
```sql
COMMENT ON SCHEMA whatsapp IS 'WhatsApp: Business API integration, messages, configuration';
```
---
### TASK-A2: Mover ENUMs de WhatsApp a 02-enums.sql
**Archivo Origen:** `apps/database/ddl/schemas/whatsapp/tables/02-whatsapp-messages.sql`
**Archivo Destino:** `apps/database/ddl/02-enums.sql`
**Línea:** Después de línea 59 (final de webhooks enums)
**Acción:** INSERT en destino, REMOVE de origen
**Agregar en 02-enums.sql:**
```sql
-- WhatsApp enums
CREATE TYPE whatsapp.message_status AS ENUM ('pending', 'sent', 'delivered', 'read', 'failed');
CREATE TYPE whatsapp.message_type AS ENUM ('text', 'template', 'image', 'document', 'audio', 'video', 'location', 'contacts', 'interactive');
CREATE TYPE whatsapp.message_direction AS ENUM ('outbound', 'inbound');
```
**Remover de 02-whatsapp-messages.sql (líneas 8-23):**
```sql
-- ELIMINAR estas líneas:
CREATE TYPE whatsapp.message_status AS ENUM (
'pending',
'sent',
'delivered',
'read',
'failed'
);
CREATE TYPE whatsapp.message_type AS ENUM (
'text',
'template',
'image',
'document',
'audio',
'video',
'location',
'contacts',
'interactive'
);
CREATE TYPE whatsapp.message_direction AS ENUM (
'outbound',
'inbound'
);
```
---
### TASK-A3: Actualizar create-database.sh
**Archivo:** `apps/database/scripts/create-database.sh`
**Cambio 1 - Agregar GRANT USAGE (línea 131):**
```bash
GRANT USAGE ON SCHEMA whatsapp TO $DB_USER;
```
**Cambio 2 - Agregar a SCHEMA_ORDER (línea 148-149):**
```bash
"webhooks"
"whatsapp"
)
```
**Cambio 3 - Agregar GRANT PRIVILEGES (después de línea 180):**
```bash
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA whatsapp TO $DB_USER;
```
**Cambio 4 - Agregar GRANT SEQUENCES (después de línea 184):**
```bash
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA whatsapp TO $DB_USER;
```
**Cambio 5 - Agregar GRANT FUNCTIONS (después de línea 195):**
```bash
GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA whatsapp TO $DB_USER;
```
---
## FASE B: CORRECCIONES BACKEND (Bloqueantes para API)
### TASK-B1: Registrar WhatsAppModule en app.module.ts
**Archivo:** `apps/backend/src/app.module.ts`
**Cambio 1 - Agregar import (línea 28):**
```typescript
import { WhatsAppModule } from '@modules/whatsapp/whatsapp.module';
```
**Cambio 2 - Agregar a imports array (línea 85):**
```typescript
OnboardingModule,
WhatsAppModule,
```
---
### TASK-B2: Agregar configuración WhatsApp en env.config.ts
**Archivo:** `apps/backend/src/config/env.config.ts`
**Cambio 1 - Agregar a envConfig() después de email (línea 55):**
```typescript
whatsapp: {
apiVersion: process.env.WHATSAPP_API_VERSION || 'v17.0',
verifyToken: process.env.WHATSAPP_VERIFY_TOKEN || '',
appSecret: process.env.WHATSAPP_APP_SECRET || '',
},
```
**Cambio 2 - Agregar a validationSchema después de SMTP (línea 103):**
```typescript
// WhatsApp (optional)
WHATSAPP_API_VERSION: Joi.string().default('v17.0'),
WHATSAPP_VERIFY_TOKEN: Joi.string().allow('').default(''),
WHATSAPP_APP_SECRET: Joi.string().allow('').default(''),
```
---
### TASK-B3: Importar WhatsAppModule en notifications.module.ts
**Archivo:** `apps/backend/src/modules/notifications/notifications.module.ts`
**Cambio 1 - Agregar import (línea 23):**
```typescript
import { WhatsAppModule } from '../whatsapp/whatsapp.module';
```
**Cambio 2 - Agregar a imports array (línea 36):**
```typescript
EmailModule,
WhatsAppModule,
```
---
## FASE C: CORRECCIONES FRONTEND (Bloqueantes para UI)
### TASK-C1: Corregir import de API client
**Archivo:** `apps/frontend/src/services/whatsapp.api.ts`
**Cambio - Línea 1:**
```typescript
// ANTES:
import { apiClient } from './api-client';
// DESPUÉS:
import { api } from './api';
```
**Y reemplazar todas las ocurrencias de `apiClient` por `api` en el archivo (10 ocurrencias).**
---
### TASK-C2: Registrar ruta WhatsApp en router
**Archivo:** `apps/frontend/src/router/index.tsx`
**Cambio 1 - Agregar import (línea 22):**
```typescript
import { WhatsAppSettings } from '@/pages/admin/WhatsAppSettings';
```
**Cambio 2 - Agregar ruta en dashboard routes (línea 108):**
```typescript
} />
} />
```
---
### TASK-C3: Agregar WhatsApp a navegación
**Archivo:** `apps/frontend/src/layouts/DashboardLayout.tsx`
**Cambio 1 - Agregar import de icono (línea 21):**
```typescript
Flag,
MessageSquare,
```
**Cambio 2 - Agregar item a navigation array (línea 35):**
```typescript
{ name: 'Settings', href: '/dashboard/settings', icon: Settings },
{ name: 'WhatsApp', href: '/dashboard/whatsapp', icon: MessageSquare },
```
---
## FASE D: DOCUMENTACIÓN
### TASK-D1: Actualizar README de database
**Archivo:** `apps/database/README.md`
**Acción:** Agregar schema whatsapp a la tabla de schemas y estructura de archivos
### TASK-D2: Actualizar PROJECT-STATUS.md
**Archivo:** `orchestration/PROJECT-STATUS.md`
**Acción:** Documentar correcciones aplicadas
---
## VALIDACIÓN POST-EJECUCIÓN
### Test 1: Recrear base de datos
```bash
cd apps/database
FORCE=1 ./scripts/drop-and-recreate.sh
```
**Criterio:** 37 tablas creadas (35 existentes + 2 de whatsapp)
### Test 2: Verificar enums
```sql
SELECT typname FROM pg_type
JOIN pg_namespace ON pg_type.typnamespace = pg_namespace.oid
WHERE nspname = 'whatsapp';
```
**Criterio:** 3 enums listados (message_status, message_type, message_direction)
### Test 3: Tests backend
```bash
cd apps/backend
npm run test -- --testPathPattern=whatsapp
```
**Criterio:** 22 tests passing
### Test 4: Build frontend
```bash
cd apps/frontend
npm run build
```
**Criterio:** Build exitoso sin errores de import
### Test 5: Verificar endpoints
```bash
curl http://localhost:3001/whatsapp/config -H "Authorization: Bearer $TOKEN"
```
**Criterio:** Respuesta 200 o 401 (no 404)
---
## ORDEN DE EJECUCIÓN
```
FASE A (DDL)
├── TASK-A1: 01-schemas.sql
├── TASK-A2: 02-enums.sql + 02-whatsapp-messages.sql
├── TASK-A3: create-database.sh
└── VALIDACIÓN: drop-and-recreate.sh
FASE B (Backend)
├── TASK-B1: app.module.ts
├── TASK-B2: env.config.ts
├── TASK-B3: notifications.module.ts
└── VALIDACIÓN: npm run test
FASE C (Frontend)
├── TASK-C1: whatsapp.api.ts
├── TASK-C2: router/index.tsx
├── TASK-C3: DashboardLayout.tsx
└── VALIDACIÓN: npm run build
FASE D (Documentación)
├── TASK-D1: README.md
└── TASK-D2: PROJECT-STATUS.md
```
---
## ARCHIVOS AFECTADOS
| Archivo | Acción | Líneas |
|---------|--------|--------|
| apps/database/ddl/01-schemas.sql | EDIT | +2 |
| apps/database/ddl/02-enums.sql | EDIT | +4 |
| apps/database/ddl/schemas/whatsapp/tables/02-whatsapp-messages.sql | EDIT | -17 |
| apps/database/scripts/create-database.sh | EDIT | +5 |
| apps/backend/src/app.module.ts | EDIT | +2 |
| apps/backend/src/config/env.config.ts | EDIT | +9 |
| apps/backend/src/modules/notifications/notifications.module.ts | EDIT | +2 |
| apps/frontend/src/services/whatsapp.api.ts | EDIT | 11 cambios |
| apps/frontend/src/router/index.tsx | EDIT | +2 |
| apps/frontend/src/layouts/DashboardLayout.tsx | EDIT | +2 |
**Total cambios:** 10 archivos, ~50 líneas
---
**Creado:** 2026-01-10
**Estado:** COMPLETADO
---
## EJECUCION COMPLETADA
**Fecha Ejecución:** 2026-01-10
**Reporte:** REPORTE-EJECUCION-SPRINT-5-CORRECCION-2026-01-10.md
Todas las 9 tasks fueron ejecutadas exitosamente. Ver reporte para detalles.