--- id: "SAAS-007" title: "Notificaciones" type: "Module" status: "Published" priority: "P1" module: "notifications" version: "2.0.0" created_date: "2026-01-07" updated_date: "2026-01-10" --- # SAAS-007: Notificaciones ## Metadata - **Codigo:** SAAS-007 - **Modulo:** Notifications - **Prioridad:** P1 - **Estado:** Completado (v2.0) - **Fase:** 3 - Features Core - **Version Actual:** 2.0.0 - **Ultima Actualizacion:** 2026-01-10 - **Especificacion v2:** [ET-SAAS-007-notifications-v2.md](../02-especificaciones/ET-SAAS-007-notifications-v2.md) ## Descripcion Sistema de notificaciones multicanal: email transaccional, push notifications (web/mobile), y notificaciones in-app con preferencias por usuario. ## Objetivos 1. Email transaccional con templates 2. Push notifications (web) 3. Notificaciones in-app 4. Preferencias por usuario 5. Historial de notificaciones ## Alcance ### Incluido - Email via SendGrid/Resend - Push web via Web Push API - Notificaciones in-app en tiempo real - Templates de email personalizables - Preferencias de notificacion por usuario - Queue de envio con reintentos ### Excluido - SMS - fase posterior - Push mobile nativo - fase posterior **Nota:** WhatsApp Business esta implementado en [SAAS-014-whatsapp.md](./SAAS-014-whatsapp.md) e integrado con el sistema de notificaciones. ## Canales Soportados | Canal | Proveedor | Casos de Uso | |-------|-----------|--------------| | Email | SendGrid/SES/SMTP | Bienvenida, facturas, alertas | | Push Web | Web Push API (VAPID) | Alertas tiempo real | | In-App | WebSocket Gateway | Actualizaciones, menciones | | WhatsApp | WhatsApp Business API | Notificaciones via WhatsApp | ## Modelo de Datos ### Tablas (schema: notifications) **notification_templates** - id, code, name, description - channel (email/push/inapp) - subject_template, body_template - variables (JSONB), is_active **notifications** - id, tenant_id, user_id - template_code, channel - subject, body, data (JSONB) - status, sent_at, read_at - created_at **user_notification_preferences** - id, user_id, channel - enabled, categories (JSONB) - quiet_hours_start, quiet_hours_end **push_subscriptions** - id, user_id, endpoint - keys (JSONB), user_agent - created_at, last_used_at ## Templates Predefinidos | Codigo | Canal | Descripcion | |--------|-------|-------------| | welcome | email | Bienvenida nuevo usuario | | invite | email | Invitacion a tenant | | password_reset | email | Reset de password | | invoice_paid | email | Factura pagada | | trial_ending | email | Trial por terminar | | new_comment | inapp | Nuevo comentario | | mention | inapp/push | Mencion en comentario | ## Endpoints API | Metodo | Endpoint | Descripcion | |--------|----------|-------------| | GET | /notifications | Listar notificaciones | | GET | /notifications/unread | No leidas | | PUT | /notifications/:id/read | Marcar leida | | PUT | /notifications/read-all | Marcar todas leidas | | DELETE | /notifications/:id | Eliminar | | GET | /notifications/preferences | Preferencias | | PUT | /notifications/preferences | Actualizar preferencias | | POST | /notifications/push/subscribe | Suscribir push | | DELETE | /notifications/push/unsubscribe | Desuscribir push | ## Interfaz del Servicio ```typescript interface NotificationService { send(userId: string, template: string, data: object): Promise; sendBulk(userIds: string[], template: string, data: object): Promise; sendToTenant(tenantId: string, template: string, data: object): Promise; } interface NotificationPayload { template: string; channel?: 'email' | 'push' | 'inapp' | 'all'; data: Record; priority?: 'low' | 'normal' | 'high'; } ``` ## Flujo de Envio ``` 1. Evento dispara notificacion 2. NotificationService.send() 3. Cargar template y preferencias 4. Verificar canal habilitado 5. Renderizar template con datos 6. Encolar en BullMQ 7. Worker procesa y envia 8. Actualizar status 9. WebSocket notifica in-app ``` ## Email Templates (MJML) ```typescript // Template base const baseTemplate = ` {{content}} `; ``` ## Entregables | Entregable | Estado | Archivo | |------------|--------|---------| | notifications.module.ts | Completado | `modules/notifications/` | | notifications.service.ts | Completado | `services/` | | devices.service.ts | Completado | `services/` | | push-notification.service.ts | Completado | `services/` | | notification-queue.service.ts | Completado | `services/` | | notifications.gateway.ts | Completado | `gateways/` | | devices.controller.ts | Completado | `controllers/` | | DDL notifications schema | Completado | `ddl/schemas/notifications/` | | Seeds templates | Completado | `seeds/prod/` | ## Componentes Version 2.0 (Implementados) ### DevicesController Gestion de dispositivos para push notifications: | Metodo | Endpoint | Descripcion | |--------|----------|-------------| | GET | /notifications/devices | Listar dispositivos del usuario | | POST | /notifications/devices | Registrar nuevo dispositivo | | DELETE | /notifications/devices/:id | Eliminar dispositivo | ### NotificationsGateway (WebSocket) Gateway para notificaciones en tiempo real: - **Namespace:** `/notifications` - **Eventos emitidos:** `notification`, `read`, `delete` - **Autenticacion:** JWT en handshake - **Ejemplo cliente:** ```typescript const socket = io('/notifications', { auth: { token: 'jwt-token' } }); socket.on('notification', (data) => { // Nueva notificacion recibida }); ``` ### NotificationQueueService Procesamiento asincrono de notificaciones con BullMQ: - Cola para envios masivos - Reintentos automaticos con backoff - Dead letter queue para fallos permanentes - Dashboard Bull Board (opcional) ### Tablas Adicionales v2.0 | Tabla | Descripcion | |-------|-------------| | notifications.user_devices | Dispositivos registrados para push | | notifications.notification_queue | Cola de procesamiento | | notifications.notification_logs | Historial de envios | ### Integracion WhatsApp Las notificaciones pueden enviarse via WhatsApp usando el canal `whatsapp`. La configuracion se realiza en [SAAS-014-whatsapp.md](./SAAS-014-whatsapp.md). ## Dependencias ### Depende de - SAAS-001 (Auth) - SAAS-002 (Tenants) - SAAS-003 (Users) - SendGrid/Resend API key - VAPID keys para push ### Bloquea a - Alertas en otros modulos - Sistema de menciones ## Criterios de Aceptacion - [x] Email de bienvenida se envia - [x] Push notifications funcionan (Web Push VAPID) - [x] In-app muestra en tiempo real (WebSocket) - [x] Preferencias se respetan - [x] Cola BullMQ procesa envios - [x] Templates son personalizables - [x] Dispositivos se registran y gestionan - [x] WhatsApp integrado como canal ## Configuracion ```typescript { notifications: { email: { provider: 'sendgrid', // o 'resend' apiKey: process.env.SENDGRID_API_KEY, from: 'noreply@example.com', replyTo: 'support@example.com' }, push: { vapidPublicKey: process.env.VAPID_PUBLIC_KEY, vapidPrivateKey: process.env.VAPID_PRIVATE_KEY, subject: 'mailto:admin@example.com' }, defaults: { quietHoursStart: '22:00', quietHoursEnd: '08:00' } } } ``` --- ## Estado de Implementacion ### Version 2.0 (Actual - Implementada) | Componente | Estado | Notas | |------------|--------|-------| | DDL Schema | Completado | 6 tablas (incluye v2.0) | | Backend Service | Completado | CRUD + Templates + Queue | | Email Service | Completado | SendGrid/SES/SMTP | | Push Notifications | Completado | Web Push API (VAPID) | | WebSocket Gateway | Completado | Real-time in-app | | Cola BullMQ | Completado | Procesamiento asincrono | | Devices Service | Completado | Gestion dispositivos push | | Frontend UI | Completado | Drawer + Settings + DevicesManager | | Tests | Completado | 45+ tests (devices, push, queue, gateway) | ### Comparativa con gamilit | Caracteristica | gamilit | template-saas v2 | |----------------|---------|------------------| | Tablas DDL | 6 | 6 | | Push Web (VAPID) | Si | Si | | Cola BullMQ | Si | Si | | WebSocket | Si | Si | | Logs Entrega | Si | Si | | WhatsApp | No | Si | --- **Ultima actualizacion:** 2026-01-10