erp-core/docs/02-fase-core-business/MGN-008-notifications/requerimientos/RF-NOTIF-002.md

5.9 KiB

RF-NOTIF-002: Notificaciones por Email

Identificacion

Campo Valor
ID RF-NOTIF-002
Modulo MGN-008 Notifications
Titulo Notificaciones por Email
Prioridad P0 - Critica
Estado Draft
Fecha 2025-12-05

Descripcion

El sistema debe enviar notificaciones por email para eventos importantes, usando templates personalizables y respetando las preferencias de cada usuario.


Requisitos Funcionales

RF-NOTIF-002.1: Configuracion de Email

Configuracion Descripcion
SMTP Host Servidor SMTP
SMTP Port Puerto (587, 465)
SMTP User Usuario autenticacion
SMTP Password Password (encriptado)
From Address Email remitente
From Name Nombre remitente
Reply To Email para respuestas

RF-NOTIF-002.2: Templates de Email

Estructura de template:

interface EmailTemplate {
  id: UUID;
  tenant_id?: UUID;      // null = global
  code: string;          // Identificador unico
  name: string;          // Nombre descriptivo
  subject: string;       // Asunto (con variables)
  body_html: string;     // Cuerpo HTML
  body_text: string;     // Cuerpo texto plano
  variables: string[];   // Variables disponibles
  category: string;      // Categoria del template
  is_active: boolean;
  created_at: TIMESTAMPTZ;
  updated_at: TIMESTAMPTZ;
}

RF-NOTIF-002.3: Variables en Templates

Sistema de variables con sintaxis Handlebars:

<h1>Hola {{user.firstName}},</h1>

<p>Se ha creado un nuevo pedido:</p>

<table>
  <tr>
    <td>Numero:</td>
    <td>{{order.number}}</td>
  </tr>
  <tr>
    <td>Total:</td>
    <td>{{formatCurrency order.total order.currency}}</td>
  </tr>
</table>

{{#if order.items}}
<ul>
  {{#each order.items}}
  <li>{{this.name}} x {{this.quantity}}</li>
  {{/each}}
</ul>
{{/if}}

<a href="{{actionUrl}}">Ver pedido</a>

RF-NOTIF-002.4: Templates Predefinidos

Codigo Descripcion Variables
welcome Bienvenida nuevo usuario user, tenant, activationUrl
password_reset Recuperar password user, resetUrl, expiresIn
order_created Pedido creado user, order, items
invoice_sent Factura enviada user, invoice, downloadUrl
payment_received Pago recibido user, payment, order
task_assigned Tarea asignada user, task, assigner
approval_request Solicitud aprobacion user, entity, approveUrl

RF-NOTIF-002.5: Personalizacion por Tenant

Cada tenant puede personalizar:

  • Logo en header
  • Colores del email
  • Footer con datos empresa
  • Templates especificos
interface TenantEmailConfig {
  logoUrl: string;
  primaryColor: string;
  footerHtml: string;
  customTemplates: UUID[];  // Templates propios
}

RF-NOTIF-002.6: Cola de Envio

Los emails se procesan via cola:

interface EmailJob {
  id: UUID;
  templateCode: string;
  to: string[];
  cc?: string[];
  bcc?: string[];
  variables: Record<string, any>;
  attachments?: Attachment[];
  priority: 'low' | 'normal' | 'high';
  scheduledAt?: TIMESTAMPTZ;
  status: 'pending' | 'processing' | 'sent' | 'failed';
  attempts: number;
  lastError?: string;
  sentAt?: TIMESTAMPTZ;
}

RF-NOTIF-002.7: Tracking de Emails

Opcionalmente, trackear apertura y clicks:

interface EmailTracking {
  emailJobId: UUID;
  openedAt?: TIMESTAMPTZ;
  openCount: number;
  clicks: {
    url: string;
    clickedAt: TIMESTAMPTZ;
  }[];
  userAgent?: string;
  ipAddress?: INET;
}

Operaciones

Enviar Email

POST /api/v1/notifications/email
{
  "template": "order_created",
  "to": ["cliente@example.com"],
  "variables": {
    "user": { "firstName": "Juan" },
    "order": { "number": "ORD-001", "total": 1500 }
  }
}

Response:
{
  "jobId": "uuid",
  "status": "queued",
  "scheduledAt": "2025-12-05T10:00:00Z"
}

Listar Templates

GET /api/v1/notifications/email/templates

Response:
{
  "data": [
    {
      "id": "uuid",
      "code": "welcome",
      "name": "Email de Bienvenida",
      "category": "auth",
      "variables": ["user", "tenant", "activationUrl"]
    }
  ]
}

Crear/Editar Template

POST /api/v1/notifications/email/templates
{
  "code": "custom_invoice",
  "name": "Factura Personalizada",
  "subject": "Factura {{invoice.number}}",
  "bodyHtml": "<html>...</html>",
  "bodyText": "...",
  "variables": ["user", "invoice"]
}

Preview de Template

POST /api/v1/notifications/email/templates/:id/preview
{
  "variables": {
    "user": { "firstName": "Juan" },
    "invoice": { "number": "INV-001" }
  }
}

Response:
{
  "subject": "Factura INV-001",
  "bodyHtml": "<html>...</html>",
  "bodyText": "..."
}

Historial de Envios

GET /api/v1/notifications/email/history?to=user@example.com

Response:
{
  "data": [
    {
      "id": "uuid",
      "template": "welcome",
      "to": ["user@example.com"],
      "status": "sent",
      "sentAt": "2025-12-05T10:00:00Z",
      "opened": true,
      "openedAt": "2025-12-05T10:05:00Z"
    }
  ]
}

Reglas de Negocio

ID Regla Severidad
BR-001 Reintentar 3 veces en caso de fallo Reliability
BR-002 Rate limit: 100 emails/min por tenant Performance
BR-003 Emails con tracking respetan privacidad Privacy
BR-004 Templates globales no editables por tenant Security
BR-005 Logs de email se retienen 90 dias Compliance

Criterios de Aceptacion

  • Configuracion SMTP funcional
  • Templates con variables Handlebars
  • Personalizacion por tenant
  • Cola de envio con reintentos
  • Tracking de apertura (opcional)
  • Preview de templates
  • Historial de envios

Historial

Version Fecha Autor Cambios
1.0 2025-12-05 Requirements-Analyst Creacion inicial