michangarrito/docs/02-integraciones/INT-007-firebase-fcm.md
rckrdmrd 928eb795e6 [SIMCO-V38] feat: Actualizar a SIMCO v3.8.0 + cambios apps
- HERENCIA-SIMCO.md actualizado con directivas v3.7 y v3.8
- Cambios en backend y frontend

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-10 08:53:05 -06:00

6.5 KiB

id type title provider status integration_type created_at updated_at simco_version tags
INT-007 Integration Push Notifications Firebase (Google) Pendiente Notificaciones push 2026-01-10 2026-01-10 3.8.0
notificaciones
push
firebase
fcm
mobile
web

INT-007: Push Notifications

Metadata

Campo Valor
Codigo INT-007
Proveedor Firebase (Google)
Tipo Notificaciones push
Estado Pendiente
Multi-tenant Si
Fecha planeada 2026-Q1
Owner Backend Team

1. Descripcion

Integración con Firebase Cloud Messaging (FCM) para enviar notificaciones push a dispositivos móviles (Android/iOS) y navegadores web. Permite mantener informados a los dueños de changarros sobre ventas, inventario bajo, pedidos nuevos y alertas importantes del negocio en tiempo real.

Casos de uso principales:

  • Notificación instantánea de nuevas ventas realizadas
  • Alertas de inventario bajo o productos agotados
  • Notificaciones de pagos recibidos (SPEI, tarjeta)
  • Recordatorios de cierre de caja y cortes
  • Alertas de seguridad (accesos sospechosos, cambios de contraseña)

2. Credenciales Requeridas

Variables de Entorno

Variable Descripcion Tipo Obligatorio
FIREBASE_PROJECT_ID ID del proyecto en Firebase Console string SI
FIREBASE_PRIVATE_KEY Llave privada del service account string SI
FIREBASE_CLIENT_EMAIL Email del service account string SI
FIREBASE_DATABASE_URL URL de Firebase Realtime DB (opcional) string NO
FCM_SERVER_KEY Server key legacy (deprecado, usar service account) string NO

Ejemplo de .env

# Firebase Cloud Messaging
FIREBASE_PROJECT_ID=michangarrito-prod
FIREBASE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nMIIEvgIBA...\n-----END PRIVATE KEY-----\n"
FIREBASE_CLIENT_EMAIL=firebase-adminsdk@michangarrito-prod.iam.gserviceaccount.com
FIREBASE_DATABASE_URL=https://michangarrito-prod.firebaseio.com

Archivo de Service Account

Alternativamente, usar archivo JSON de credenciales:

GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json

3. Arquitectura

┌─────────────────────────────────────────────────────────────────┐
│                      MiChangarrito                              │
│  ┌──────────────┐    ┌──────────────┐    ┌──────────────────┐  │
│  │  Event Bus   │───▶│ Notification │───▶│   FCMService     │  │
│  │  (Eventos)   │    │   Manager    │    │                  │  │
│  └──────────────┘    └──────────────┘    └────────┬─────────┘  │
└────────────────────────────────────────────────────┼────────────┘
                                                     │
                                                     ▼
                                          ┌──────────────────┐
                                          │   Firebase FCM   │
                                          │   (Google)       │
                                          └────────┬─────────┘
                                                   │
                          ┌────────────────────────┼────────────────────────┐
                          │                        │                        │
                          ▼                        ▼                        ▼
                   ┌────────────┐          ┌────────────┐          ┌────────────┐
                   │  Android   │          │    iOS     │          │    Web     │
                   │    App     │          │    App     │          │  Browser   │
                   └────────────┘          └────────────┘          └────────────┘

Flujo de Notificación

  1. Evento ocurre en el sistema (venta, alerta, etc.)
  2. Event Bus dispara evento al Notification Manager
  3. Manager determina destinatarios y tipo de notificación
  4. FCMService formatea y envía mensaje a Firebase
  5. Firebase distribuye a dispositivos registrados
  6. Usuario recibe notificación en su dispositivo

4. Endpoints

Endpoints Consumidos (Firebase FCM API)

Método Endpoint Descripción
POST /v1/projects/{project}/messages:send Enviar notificación
POST /v1/projects/{project}/messages:sendAll Envío masivo (batch)
GET /v1/projects/{project}/messages/{id} Estado de mensaje

Endpoints Expuestos (MiChangarrito)

Método Endpoint Descripción
POST /api/v1/notifications/register Registrar device token
DELETE /api/v1/notifications/unregister Eliminar device token
GET /api/v1/notifications/settings Obtener preferencias
PUT /api/v1/notifications/settings Actualizar preferencias
POST /api/v1/notifications/test Enviar notificación de prueba

5. Notas de Implementacion

  • Usar Firebase Admin SDK para Node.js (firebase-admin)
  • Almacenar device tokens en BD, asociados al usuario/tenant
  • Implementar limpieza de tokens inválidos (error: NotRegistered)
  • Manejar tokens múltiples por usuario (varios dispositivos)
  • Respetar preferencias de notificación del usuario
  • FCM tiene límite de 500 destinatarios por mensaje multicast
  • Para envíos masivos usar topics o batching
  • Implementar cola de notificaciones para alto volumen
  • Las notificaciones web requieren HTTPS y service worker
  • Considerar notificaciones silenciosas para actualizar datos en background
  • iOS requiere configuración adicional de APNs en Firebase Console
  • Implementar analytics de delivery y apertura de notificaciones