feat: Complete documentation update and orchestration configuration

- Update vision, architecture and technical documentation
- Update module definitions (PMC-001 to PMC-008)
- Update requirements documentation
- Add CONTEXT-MAP.yml and ENVIRONMENT-INVENTORY.yml
- Add orchestration guidelines and references

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
rckrdmrd 2026-01-07 05:38:31 -06:00
parent dfa82a276e
commit 74b5ed7f38
70 changed files with 4863 additions and 1429 deletions

358
AGENTS.md Normal file
View File

@ -0,0 +1,358 @@
# Guia para Agentes de IA - Platform Marketing Content
**Version:** 1.0
**Ultima actualizacion:** 2026-01-04
**Basado en:** Estandar-SCRUM.md (Principio SIMCO)
---
## 1. Estructura del Proyecto
### Ubicaciones Clave
| Tipo | Ubicacion |
|------|-----------|
| Documentacion general | `/docs/` |
| Planificacion | `/docs/planning/` |
| Vision general | `/docs/00-vision-general/` |
| Analisis referencias | `/docs/01-analisis-referencias/` |
| Definicion modulos | `/docs/02-definicion-modulos/` |
| Requerimientos | `/docs/03-requerimientos/` |
| Modelado | `/docs/04-modelado/` |
| User Stories/EPICs | `/docs/05-user-stories/` |
| Transversal | `/docs/90-transversal/` |
| Guias desarrollo | `/docs/95-guias-desarrollo/` |
| Quick Reference | `/docs/96-quick-reference/` |
| ADRs | `/docs/97-adr/` |
| Backlog | `/docs/04-fase-backlog/` |
| Tablero Kanban | `/docs/planning/Board.md` |
| Orquestacion | `/orchestration/` |
| Trazas | `/orchestration/trazas/` |
### Estructura de una EPIC
```
docs/05-user-stories/EPIC-XXX-nombre.md
```
Cada EPIC contiene:
- Descripcion de la epica
- User Stories con formato "Como... Quiero... Para..."
- Criterios de aceptacion
- Notas tecnicas
- Dependencias
---
## 2. Prefijos de Nomenclatura
| Prefijo | Tipo | Ejemplo | Descripcion |
|---------|------|---------|-------------|
| EPIC- | Epica | EPIC-001-SETUP | Epicas del proyecto |
| US- | Historia de Usuario | US-001-001 | User Stories |
| TASK- | Tarea | TASK-001 | Tareas ejecutables |
| BUG- | Bug | BUG-001 | Defectos/errores |
| RF-PMC- | Requerimiento Funcional | RF-PMC-001-TENANTS | Requerimientos |
| PMC- | Modulo | PMC-001-TENANTS | Definicion de modulos |
| ADR- | Decision Record | ADR-001 | Decisiones arquitectonicas |
---
## 3. Como Trabajar con Tareas
### Tomar una Tarea
1. **Identificar tarea** en `/docs/planning/Board.md` (columna "Por Hacer")
2. **Leer archivo** `TASK-XXX.md` correspondiente
3. **Editar YAML front-matter**:
```yaml
status: "In Progress"
assignee: "@NombreAgente"
started_date: "YYYY-MM-DD"
```
4. **Mover tarea** a columna "En Progreso" en Board.md
5. **Commit**: `git commit -m "Start TASK-XXX: [descripcion breve]"`
### Completar una Tarea
1. **Verificar** TODOS los criterios de aceptacion cumplidos
2. **Editar YAML front-matter**:
```yaml
status: "Done"
completed_date: "YYYY-MM-DD"
actual_hours: X
```
3. **Agregar seccion** "## Notas de Implementacion" con detalles
4. **Mover tarea** a columna "Hecho" en Board.md
5. **Commit**: `git commit -m "Fixes TASK-XXX: [descripcion breve]"`
### Reportar Bloqueo
1. Cambiar `status: "Blocked"`
2. Agregar seccion "## Bloqueo" con:
- Descripcion del bloqueo
- Dependencias faltantes
- Accion requerida
3. Notificar en Board.md
---
## 4. Como Trabajar con Bugs
### Reportar un Bug
1. **Crear archivo** `/docs/planning/bugs/BUG-XXX-descripcion.md`
2. **Usar plantilla YAML**:
```yaml
---
id: "BUG-XXX"
title: "Descripcion del bug"
type: "Bug"
status: "Open"
severity: "P0|P1|P2|P3"
priority: "Critica|Alta|Media|Baja"
assignee: ""
affected_module: "Backend|Frontend|Database"
steps_to_reproduce:
- "Paso 1"
- "Paso 2"
expected_behavior: "Lo que deberia pasar"
actual_behavior: "Lo que pasa realmente"
created_date: "YYYY-MM-DD"
---
```
3. **Incluir secciones**: Descripcion, Contexto, Impacto
4. **Commit**: `git commit -m "Report BUG-XXX: [descripcion]"`
### Resolver un Bug
1. Editar YAML: `status: "Done"`, agregar `resolved_date`
2. Documentar solucion en seccion "## Solucion Implementada"
3. Agregar referencia al commit: `fix_commit: "abc123"`
4. **Commit**: `git commit -m "Fix BUG-XXX: [descripcion]"`
---
## 5. Formato YAML Front-Matter
### EPIC
```yaml
---
id: "EPIC-001"
title: "Setup y Autenticacion"
type: "Epic"
status: "Done"
priority: "Alta"
project: "platform_marketing_content"
phase: 1
story_points: 40
created_date: "2025-12-08"
updated_date: "2026-01-04"
---
```
### Historia de Usuario (US)
```yaml
---
id: "US-001-001"
title: "Crear Tenant Inicial"
type: "User Story"
status: "Done"
priority: "Alta"
assignee: "@Backend-Agent"
epic: "EPIC-001"
story_points: 5
created_date: "2025-12-08"
updated_date: "2026-01-04"
---
```
### Requerimiento Funcional (RF)
```yaml
---
id: "RF-PMC-001"
title: "Tenants Module"
type: "Requirement"
status: "Done"
priority: "Alta"
module: "tenants"
project: "platform_marketing_content"
version: "1.0"
created_date: "2025-12-08"
updated_date: "2026-01-04"
---
```
### ADR (Architecture Decision Record)
```yaml
---
id: "ADR-001"
title: "Seleccion de Stack Tecnologico"
type: "ADR"
status: "Accepted"
date: "2025-12-08"
deciders: ["Architecture Team"]
tags: ["backend", "frontend", "database"]
created_date: "2025-12-08"
updated_date: "2026-01-04"
---
```
### Tarea (TASK)
```yaml
---
id: "TASK-001"
title: "Implementar endpoint POST /auth/register"
type: "Task"
status: "Done"
priority: "P1"
assignee: "@Backend-Agent"
parent_us: "US-001-001"
epic: "EPIC-001"
estimated_hours: 4
actual_hours: 4.5
created_date: "2025-12-08"
completed_date: "2025-12-08"
---
```
---
## 6. Convenciones de Commit
```
<tipo>(<scope>): <descripcion>
Tipos:
- feat: Nueva funcionalidad
- fix: Correccion de bug
- docs: Documentacion
- refactor: Refactoring
- test: Tests
- chore: Mantenimiento
Scopes comunes:
- auth, tenants, crm, generation (modulos)
- database, backend, frontend (capas)
- US-XXX, TASK-XXX, BUG-XXX (referencias)
Ejemplos:
- feat(auth): Implement JWT authentication
- fix(BUG-001): Resolve login redirect issue
- docs(EPIC-001): Add acceptance criteria
- Start TASK-XXX: Begin implementation
- Fixes TASK-XXX: Complete implementation
```
---
## 7. Estados Validos
### Para Tareas y User Stories
| Estado | Descripcion |
|--------|-------------|
| Backlog | En cola, no planificado |
| To Do | Planificado para sprint actual |
| In Progress | En desarrollo activo |
| Blocked | Bloqueado por dependencia |
| In Review | En revision/testing |
| Done | Completado y validado |
### Para Bugs
| Estado | Descripcion |
|--------|-------------|
| Open | Reportado, pendiente |
| In Progress | En investigacion/correccion |
| Fixed | Corregido, pendiente validacion |
| Done | Corregido y validado |
| Won't Fix | No se corregira (documentar razon) |
### Para ADRs
| Estado | Descripcion |
|--------|-------------|
| Proposed | Propuesto, en discusion |
| Accepted | Aceptado |
| Deprecated | Obsoleto |
| Superseded | Reemplazado por otro ADR |
---
## 8. Archivos Importantes
| Archivo | Proposito |
|---------|-----------|
| `/docs/planning/Board.md` | Tablero Kanban actual |
| `/docs/planning/config.yml` | Configuracion del proyecto |
| `/docs/04-fase-backlog/README.md` | Backlog priorizado |
| `/docs/04-fase-backlog/DEFINITION-OF-READY.md` | Criterios DoR |
| `/docs/04-fase-backlog/DEFINITION-OF-DONE.md` | Criterios DoD |
| `/orchestration/trazas/TRAZA-TAREAS-*.md` | Trazas de tareas por area |
| `/docs/90-transversal/roadmap/ROADMAP-PMC.md` | Roadmap del proyecto |
---
## 9. Validaciones Antes de Commit
- [ ] YAML front-matter valido (sin errores de sintaxis)
- [ ] Campo `id` presente y unico
- [ ] Campo `status` actualizado correctamente
- [ ] Board.md actualizado si cambio estado
- [ ] Referencias cruzadas verificadas
- [ ] Criterios de aceptacion actualizados (si aplica)
- [ ] _MAP.md actualizado si se agrego/elimino archivo
---
## 10. Flujo de Trabajo Recomendado
```
1. Consultar Board.md para ver tareas disponibles
2. Seleccionar tarea de "Por Hacer"
3. Leer archivo TASK-XXX.md completo
4. Verificar dependencias resueltas
5. Cambiar status a "In Progress"
6. Ejecutar trabajo
7. Documentar notas de implementacion
8. Verificar criterios de aceptacion
9. Cambiar status a "Done"
10. Actualizar Board.md
11. Commit con mensaje apropiado
```
---
## 11. Modulos del Sistema
| Modulo | Descripcion | EPIC |
|--------|-------------|------|
| PMC-001-TENANTS | Multi-tenancy y planes | EPIC-001 |
| PMC-002-CRM | Clientes, marcas, productos | EPIC-002 |
| PMC-003-PROJECTS | Proyectos y campanas | EPIC-003 |
| PMC-004-GENERATION | Motor IA de generacion | EPIC-004 |
| PMC-005-AUTOMATION | Flujos n8n | EPIC-006 |
| PMC-006-ASSETS | Biblioteca DAM | EPIC-005 |
| PMC-007-ADMIN | Administracion | EPIC-008 |
| PMC-008-ANALYTICS | Dashboards y reportes | EPIC-007 |
---
## 12. Contacto y Soporte
Para dudas sobre el proceso:
- Revisar `/orchestration/00-guidelines/`
- Consultar `/orchestration/directivas/`
- Ver ejemplos en EPICs completadas
---
**Creado:** 2026-01-04
**Mantenido por:** Architecture Team
**Version:** 1.0

View File

@ -1,3 +1,13 @@
---
id: "ARQUITECTURA-TECNICA"
title: "Arquitectura T茅cnica - Platform Marketing Content"
type: "Architecture"
status: "Active"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# Arquitectura T茅cnica - Platform Marketing Content
**Versi贸n:** 1.0.0

View File

@ -1,3 +1,13 @@
---
id: "GLOSARIO"
title: "Glosario - Platform Marketing Content"
type: "Glossary"
status: "Draft"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# Glosario - Platform Marketing Content
**Versi贸n:** 1.0.0

View File

@ -1,3 +1,13 @@
---
id: "MVP_PLATAFORMA_SAAS_CONTENIDO_CRM"
title: "MVP Plataforma SaaS de Generación de Contenido y CRM Creativo"
type: "Documentation"
status: "Draft"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# MVP Plataforma SaaS de Generación de Contenido y CRM Creativo
*(Basada en la investigación de la plataforma tipo Morfeo Academy y tecnologías open source)*

View File

@ -1,3 +1,13 @@
---
id: "VISION-GENERAL"
title: "Platform Marketing Content - Plataforma SaaS de Generaci贸n de Contenido y CRM Creativo"
type: "Vision"
status: "Active"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# Platform Marketing Content - Plataforma SaaS de Generaci贸n de Contenido y CRM Creativo
**Versi贸n:** 1.0.0
@ -297,6 +307,82 @@ Exportaci贸n:
- API para herramientas BI
```
### 5.9 Modulo 9: Pagos y Suscripciones (PMC-009)
**Objetivo:** Monetizacion SaaS con Stripe.
```yaml
Integracion Stripe:
- Checkout con Stripe Elements
- Suscripciones mensuales/anuales
- Webhooks automatizados
- Facturacion automatica
Planes:
- Free: $0/mes (50 generaciones, 1GB, 1 usuario)
- Pro: $79/mes (500 generaciones, 25GB, 5 usuarios)
- Enterprise: $249/mes (ilimitado)
- Internal: Sin limite (uso interno)
Productos Adicionales:
- Pack 100 generaciones: $19 (one-time)
Funcionalidades:
- Seleccionar y cambiar plan
- Upgrade/downgrade automatico
- Comprar creditos adicionales
- Ver facturas e historial
- Portal de billing
```
---
## 5.10 Estructura de Portales
La plataforma ofrece 3 portales diferenciados segun el tipo de usuario:
### Portal 1: Usuario General (Creative/Viewer)
```yaml
Acceso: Usuarios con rol creative, analyst, viewer
Funcionalidades:
- Dashboard de proyectos asignados
- Generacion de contenido IA
- Biblioteca de assets
- Perfil personal
- Historial de actividad
URL: app.{tenant}.platform-marketing.com
```
### Portal 2: Admin Cliente (Tenant Admin)
```yaml
Acceso: Usuarios con rol tenant_admin
Funcionalidades:
- Dashboard de organizacion
- Gestion de usuarios del tenant
- Configuracion del tenant (branding, limites)
- Reportes de uso
- Facturacion y suscripcion
- Integraciones (n8n, CRM externo)
URL: admin.{tenant}.platform-marketing.com
```
### Portal 3: Admin SaaS (Super Admin)
```yaml
Acceso: Usuarios con rol super_admin
Funcionalidades:
- Dashboard global de todos los tenants
- Gestion de planes y precios
- Monitoreo de sistema y recursos
- Configuracion global
- Soporte y tickets
- Analytics de uso global
- Auditoria y logs
URL: admin.platform-marketing.com
```
---
## 6. Requisitos T茅cnicos

View File

@ -1,3 +1,13 @@
---
id: "_MAP"
title: "Mapa de Vision General - PMC"
type: "Index"
status: "Draft"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# Mapa de Vision General - PMC
**Version:** 1.0.0

View File

@ -1,3 +1,13 @@
---
id: "ANALISIS-CATALOGO"
title: "Analisis de Componentes del Catalogo"
type: "Analysis"
status: "Draft"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# Analisis de Componentes del Catalogo
**Version:** 1.0.0
@ -8,7 +18,7 @@
## Proposito
Este documento analiza los componentes disponibles en el catalogo del workspace (`core/catalog/`) y determina cuales son reutilizables para el proyecto PMC, identificando adaptaciones necesarias.
Este documento analiza los componentes disponibles en el catalogo del workspace (`shared/catalog/`) y determina cuales son reutilizables para el proyecto PMC, identificando adaptaciones necesarias.
---
@ -33,7 +43,7 @@ El catalogo contiene **8 componentes production-ready**:
### 1. @CATALOG_AUTH - Autenticacion y Autorizacion
**Ubicacion:** `core/catalog/auth/`
**Ubicacion:** `shared/catalog/auth/`
**Funcionalidades incluidas:**
- JWT access + refresh tokens
@ -63,7 +73,7 @@ El catalogo contiene **8 componentes production-ready**:
### 2. @CATALOG_SESSION - Gestion de Sesiones
**Ubicacion:** `core/catalog/session-management/`
**Ubicacion:** `shared/catalog/session-management/`
**Funcionalidades incluidas:**
- Maximo N sesiones concurrentes
@ -88,7 +98,7 @@ El catalogo contiene **8 componentes production-ready**:
### 3. @CATALOG_TENANT - Multi-Tenancy
**Ubicacion:** `core/catalog/multi-tenancy/`
**Ubicacion:** `shared/catalog/multi-tenancy/`
**Funcionalidades incluidas:**
- Aislamiento de datos por tenant
@ -120,7 +130,7 @@ El catalogo contiene **8 componentes production-ready**:
### 4. @CATALOG_RATELIMIT - Limitacion de Tasa
**Ubicacion:** `core/catalog/rate-limiting/`
**Ubicacion:** `shared/catalog/rate-limiting/`
**Funcionalidades incluidas:**
- Rate limiting por IP/usuario
@ -149,7 +159,7 @@ El catalogo contiene **8 componentes production-ready**:
### 5. @CATALOG_NOTIFY - Sistema de Notificaciones
**Ubicacion:** `core/catalog/notifications/`
**Ubicacion:** `shared/catalog/notifications/`
**Funcionalidades incluidas:**
- Notificaciones in-app
@ -183,7 +193,7 @@ El catalogo contiene **8 componentes production-ready**:
### 6. @CATALOG_PAYMENTS - Integracion de Pagos
**Ubicacion:** `core/catalog/payments/`
**Ubicacion:** `shared/catalog/payments/`
**Funcionalidades incluidas:**
- Stripe Checkout
@ -219,7 +229,7 @@ El catalogo contiene **8 componentes production-ready**:
### 7. @CATALOG_FLAGS - Feature Flags
**Ubicacion:** `core/catalog/feature-flags/`
**Ubicacion:** `shared/catalog/feature-flags/`
**Funcionalidades incluidas:**
- Toggle dinamico sin redespliegue
@ -242,7 +252,7 @@ El catalogo contiene **8 componentes production-ready**:
### 8. @CATALOG_WS - WebSocket
**Ubicacion:** `core/catalog/websocket/`
**Ubicacion:** `shared/catalog/websocket/`
**Funcionalidades incluidas:**
- Conexiones WebSocket con Socket.io
@ -331,9 +341,9 @@ Fase 4 - SaaS (usa catalogo):
## Referencias
- Catalogo principal: `core/catalog/CATALOG-INDEX.yml`
- Documentacion componentes: `core/catalog/{componente}/README.md`
- Guias de implementacion: `core/catalog/{componente}/IMPLEMENTATION.md`
- Catalogo principal: `shared/catalog/CATALOG-INDEX.yml`
- Documentacion componentes: `shared/catalog/{componente}/README.md`
- Guias de implementacion: `shared/catalog/{componente}/IMPLEMENTATION.md`
---

View File

@ -1,3 +1,13 @@
---
id: "ANALISIS-PROYECTOS-REFERENCIA"
title: "Analisis de Proyectos de Referencia"
type: "Analysis"
status: "Draft"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# Analisis de Proyectos de Referencia
**Version:** 1.0.0
@ -307,7 +317,7 @@ modules:
- Inventario Gamilit: `projects/gamilit/orchestration/inventarios/MASTER_INVENTORY.yml`
- Inventario Trading: `projects/trading-platform/orchestration/inventarios/MASTER_INVENTORY.yml`
- Catalogo: `core/catalog/CATALOG-INDEX.yml`
- Catalogo: `shared/catalog/CATALOG-INDEX.yml`
---

View File

@ -1,3 +1,13 @@
---
id: "_INDEX"
title: "Analisis de Referencias"
type: "Index"
status: "Draft"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# Analisis de Referencias
**Version:** 1.0.0
@ -15,7 +25,7 @@ Esta seccion documenta el analisis de recursos reutilizables del workspace que a
| Documento | Descripcion |
|-----------|-------------|
| [ANALISIS-CATALOGO.md](./ANALISIS-CATALOGO.md) | Analisis de 8 componentes del catalogo (`core/catalog/`) con mapeo a modulos PMC y estimacion de ahorro |
| [ANALISIS-CATALOGO.md](./ANALISIS-CATALOGO.md) | Analisis de 8 componentes del catalogo (`shared/catalog/`) con mapeo a modulos PMC y estimacion de ahorro |
| [ANALISIS-PROYECTOS-REFERENCIA.md](./ANALISIS-PROYECTOS-REFERENCIA.md) | Patrones y codigo reutilizable de proyectos existentes (gamilit, trading-platform) |
---
@ -66,7 +76,7 @@ Para implementar PMC, se requiere:
## Referencias Cruzadas
- Catalogo Index: `core/catalog/CATALOG-INDEX.yml`
- Catalogo Index: `shared/catalog/CATALOG-INDEX.yml`
- Gamilit Inventory: `projects/gamilit/orchestration/inventarios/MASTER_INVENTORY.yml`
- Trading Inventory: `projects/trading-platform/orchestration/inventarios/MASTER_INVENTORY.yml`

View File

@ -1,3 +1,14 @@
---
id: "PMC-001-TENANTS"
title: "PMC-001: Módulo de Tenants"
type: "Module Definition"
epic: "PMC-001"
status: "Draft"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# PMC-001: Módulo de Tenants
**Versión:** 1.0.0
@ -203,22 +214,22 @@ Endpoints:
```yaml
Dependencias del Catálogo:
- @CATALOG_TENANT:
path: core/catalog/multi-tenancy/
path: shared/catalog/multi-tenancy/
uso: Patron base multi-tenancy con RLS
adaptar:
- Extender modelo Tenant con campos branding
- Agregar sistema de quotas por plan
- Integrar con limites de generacion
docs: core/catalog/multi-tenancy/README.md
docs: shared/catalog/multi-tenancy/README.md
- @CATALOG_PAYMENTS:
path: core/catalog/payments/
path: shared/catalog/payments/
uso: Suscripciones y billing (Fase 4)
adaptar:
- Crear productos/precios en Stripe
- Definir planes PMC (Starter, Pro, Business, Enterprise)
- Integrar creditos de generacion
docs: core/catalog/payments/README.md
docs: shared/catalog/payments/README.md
Dependencias de Módulos:
- PMC-007 Admin: Gestión de planes y configuración global
@ -287,7 +298,7 @@ Estructura S3:
## Referencias
- [ARQUITECTURA-TECNICA.md](../00-vision-general/ARQUITECTURA-TECNICA.md)
- [@CATALOG_TENANT](../../../core/catalog/modules/multi-tenancy/)
- [@CATALOG_TENANT](../../../shared/catalog/modules/multi-tenancy/)
---

View File

@ -1,3 +1,14 @@
---
id: "PMC-002-CRM"
title: "PMC-002: Módulo CRM"
type: "Module Definition"
epic: "PMC-002"
status: "Draft"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# PMC-002: Módulo CRM
**Versión:** 1.0.0

View File

@ -1,3 +1,14 @@
---
id: "PMC-003-PROJECTS"
title: "PMC-003: Módulo de Projects"
type: "Module Definition"
epic: "PMC-003"
status: "Draft"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# PMC-003: Módulo de Projects
**Versión:** 1.0.0

View File

@ -1,3 +1,14 @@
---
id: "PMC-004-GENERATION"
title: "PMC-004: Módulo de Generation"
type: "Module Definition"
epic: "PMC-004"
status: "Draft"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# PMC-004: Módulo de Generation
**Versión:** 1.0.0
@ -435,7 +446,7 @@ Dependencias de Módulos:
Dependencias del Catálogo:
- @CATALOG_RATELIMIT:
path: core/catalog/rate-limiting/
path: shared/catalog/rate-limiting/
uso: Limitar generaciones por tenant/plan
configuracion:
- Starter: 10 generaciones/hora
@ -446,16 +457,16 @@ Dependencias del Catálogo:
- Usar Redis storage para produccion
- Integrar con sistema de creditos/quotas
- Configurar por tipo de operacion (imagen vs texto)
docs: core/catalog/rate-limiting/README.md
docs: shared/catalog/rate-limiting/README.md
- @CATALOG_WS:
path: core/catalog/websocket/
path: shared/catalog/websocket/
uso: Progreso de generacion en tiempo real
implementar:
- Room por job (job:{jobId})
- Emitir eventos: progress, completed, failed
- Autenticacion de socket con JWT
docs: core/catalog/websocket/README.md
docs: shared/catalog/websocket/README.md
Servicios Externos:
- ComfyUI: Motor de generación de imágenes (self-hosted)

View File

@ -1,3 +1,14 @@
---
id: "PMC-005-AUTOMATION"
title: "PMC-005: Módulo de Automation"
type: "Module Definition"
epic: "PMC-005"
status: "Draft"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# PMC-005: Módulo de Automation
**Versión:** 1.0.0
@ -396,7 +407,7 @@ Dependencias de Módulos:
Dependencias del Catálogo:
- @CATALOG_NOTIFY:
path: core/catalog/notifications/
path: shared/catalog/notifications/
uso: Sistema de notificaciones multi-canal
incluye:
- Notificaciones in-app
@ -412,7 +423,7 @@ Dependencias del Catálogo:
- quota_warning: 80% quota usado
- quota_exceeded: Quota agotada
- brand_assets_ready: Kit de marca listo
docs: core/catalog/notifications/README.md
docs: shared/catalog/notifications/README.md
Servicios Externos:
- n8n: Orquestador de workflows (self-hosted)

View File

@ -1,3 +1,14 @@
---
id: "PMC-006-ASSETS"
title: "PMC-006: Módulo de Assets (DAM)"
type: "Module Definition"
epic: "PMC-006"
status: "Draft"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# PMC-006: Módulo de Assets (DAM)
**Versión:** 1.0.0

View File

@ -1,3 +1,14 @@
---
id: "PMC-007-ADMIN"
title: "PMC-007: Módulo de Admin"
type: "Module Definition"
epic: "PMC-007"
status: "Draft"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# PMC-007: Módulo de Admin
**Versión:** 1.0.0
@ -434,7 +445,7 @@ Dependencias de Módulos:
Dependencias del Catálogo:
- @CATALOG_AUTH:
path: core/catalog/auth/
path: shared/catalog/auth/
uso: Sistema completo de autenticacion
incluye:
- JWT access + refresh tokens
@ -446,10 +457,10 @@ Dependencias del Catálogo:
- Definir roles especificos PMC (super_admin, tenant_admin, creative, etc.)
- Agregar tenant_id al JWT payload
- Integrar con sistema de permisos RBAC
docs: core/catalog/auth/README.md
docs: shared/catalog/auth/README.md
- @CATALOG_SESSION:
path: core/catalog/session-management/
path: shared/catalog/session-management/
uso: Gestion de sesiones activas
incluye:
- Maximo N sesiones concurrentes
@ -459,17 +470,17 @@ Dependencias del Catálogo:
adaptar:
- Limite de sesiones por plan de suscripcion
- Integrar con audit log
docs: core/catalog/session-management/README.md
docs: shared/catalog/session-management/README.md
- @CATALOG_FLAGS:
path: core/catalog/feature-flags/
path: shared/catalog/feature-flags/
uso: Feature flags para rollout gradual (opcional)
docs: core/catalog/feature-flags/README.md
docs: shared/catalog/feature-flags/README.md
- @CATALOG_NOTIFY:
path: core/catalog/notifications/
path: shared/catalog/notifications/
uso: Envio de invitaciones y notificaciones
docs: core/catalog/notifications/README.md
docs: shared/catalog/notifications/README.md
Servicios Externos:
- SMTP: Envío de invitaciones (via @CATALOG_NOTIFY)
@ -526,7 +537,7 @@ Referencia de Implementacion:
## Referencias
- [ARQUITECTURA-TECNICA.md](../00-vision-general/ARQUITECTURA-TECNICA.md)
- [@CATALOG_AUTH](../../../core/catalog/modules/auth/)
- [@CATALOG_AUTH](../../../shared/catalog/modules/auth/)
- [PMC-001-TENANTS.md](./PMC-001-TENANTS.md)
---

View File

@ -1,3 +1,14 @@
---
id: "PMC-008-ANALYTICS"
title: "PMC-008: Módulo de Analytics"
type: "Module Definition"
epic: "PMC-008"
status: "Draft"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# PMC-008: Módulo de Analytics
**Versión:** 1.0.0

View File

@ -0,0 +1,737 @@
---
id: "PMC-009-PAYMENTS"
title: "PMC-009: Modulo de Payments"
type: "Module Definition"
epic: "PMC-009"
status: "Draft"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# PMC-009: Modulo de Payments
**Version:** 1.0.0
**Fecha:** 2026-01-04
**Estado:** Definicion
**Prioridad:** Alta
---
## Descripcion General
El modulo de Payments proporciona la integracion completa con Stripe para gestionar suscripciones, pagos y facturacion del sistema SaaS. Incluye checkout flow con Stripe Elements, gestion de planes de suscripcion, facturacion automatica y sistema de creditos de generacion.
### Objetivos
1. Integrar Stripe como pasarela de pagos principal
2. Gestionar planes de suscripcion (Free, Pro, Enterprise, Internal)
3. Implementar checkout flow con Stripe Elements
4. Automatizar facturacion y cobros recurrentes
5. Gestionar creditos de generacion por tenant
6. Procesar webhooks de Stripe para sincronizar estados
---
## Planes de Suscripcion
```yaml
Planes Disponibles:
free:
nombre: "Free"
precio: $0/mes
limites:
generaciones_mes: 50
storage_gb: 1
usuarios_max: 1
modelos_custom: 0
features:
- Generacion basica de imagenes
- 1 proyecto activo
- Soporte por email
pro:
nombre: "Pro"
precio: $79/mes
stripe_price_id: pmc_pro
limites:
generaciones_mes: 500
storage_gb: 25
usuarios_max: 5
modelos_custom: 3
features:
- Todo de Free
- Modelos personalizados
- API access
- Integraciones n8n
- Soporte prioritario
enterprise:
nombre: "Enterprise"
precio: $249/mes
stripe_price_id: pmc_enterprise
limites:
generaciones_mes: unlimited
storage_gb: 100
usuarios_max: unlimited
modelos_custom: unlimited
features:
- Todo de Pro
- Generaciones ilimitadas
- Usuarios ilimitados
- SSO/SAML
- SLA garantizado
- Soporte dedicado
internal:
nombre: "Internal"
precio: $0/mes
limites:
generaciones_mes: unlimited
storage_gb: unlimited
usuarios_max: unlimited
modelos_custom: unlimited
features:
- Acceso completo sin restricciones
- Solo para uso interno de la organizacion
```
---
## Productos Stripe Propuestos
```yaml
Productos Stripe:
pmc_pro:
type: subscription
nombre: "PMC Pro Plan"
precio: $79/mes
billing_interval: monthly
descripcion: "500 generaciones, 25GB storage, 5 usuarios"
metadata:
plan_code: pro
generations: 500
storage_gb: 25
users_max: 5
pmc_enterprise:
type: subscription
nombre: "PMC Enterprise Plan"
precio: $249/mes
billing_interval: monthly
descripcion: "Generaciones ilimitadas, recursos ilimitados"
metadata:
plan_code: enterprise
generations: unlimited
storage_gb: 100
users_max: unlimited
pmc_generations_100:
type: one_time
nombre: "Pack 100 Generaciones Extra"
precio: $19
descripcion: "100 creditos de generacion adicionales"
metadata:
product_type: credits
credits_amount: 100
```
---
## Entidades del Dominio
### Subscription
```yaml
Entidad: Subscription
Descripcion: Suscripcion activa de un tenant a un plan
Atributos:
- id: UUID (PK)
- tenant_id: UUID (FK a Tenant)
- user_id: UUID (FK a User, quien suscribio)
- plan_id: UUID (FK a Plan)
- stripe_subscription_id: string (sub_xxx)
- stripe_customer_id: string (cus_xxx)
- status: enum [active, past_due, canceled, incomplete, trialing, paused]
- current_period_start: timestamp
- current_period_end: timestamp
- cancel_at_period_end: boolean
- canceled_at: timestamp
- trial_start: timestamp
- trial_end: timestamp
- metadata: JSONB
- created_at: timestamp
- updated_at: timestamp
Relaciones:
- N:1 con Tenant
- N:1 con User
- N:1 con Plan
- 1:N con Invoice
```
### Invoice
```yaml
Entidad: Invoice
Descripcion: Factura generada por Stripe
Atributos:
- id: UUID (PK)
- tenant_id: UUID (FK)
- subscription_id: UUID (FK a Subscription)
- stripe_invoice_id: string (in_xxx)
- stripe_invoice_number: string
- amount_due: decimal
- amount_paid: decimal
- currency: string (usd, eur)
- status: enum [draft, open, paid, void, uncollectible]
- invoice_pdf_url: string
- hosted_invoice_url: string
- paid_at: timestamp
- due_date: timestamp
- period_start: timestamp
- period_end: timestamp
- created_at: timestamp
- updated_at: timestamp
Relaciones:
- N:1 con Tenant
- N:1 con Subscription
```
### PaymentMethod
```yaml
Entidad: PaymentMethod
Descripcion: Metodo de pago registrado del cliente
Atributos:
- id: UUID (PK)
- tenant_id: UUID (FK)
- user_id: UUID (FK)
- stripe_payment_method_id: string (pm_xxx)
- type: enum [card, sepa_debit, us_bank_account]
- card_brand: string (visa, mastercard, amex)
- card_last4: string
- card_exp_month: integer
- card_exp_year: integer
- is_default: boolean
- billing_details: JSONB (name, email, address)
- created_at: timestamp
- updated_at: timestamp
Relaciones:
- N:1 con Tenant
- N:1 con User
```
### GenerationCredit
```yaml
Entidad: GenerationCredit
Descripcion: Balance de creditos de generacion por tenant
Atributos:
- id: UUID (PK)
- tenant_id: UUID (FK, unico)
- credits_included: integer (del plan)
- credits_remaining: integer (del periodo actual)
- credits_used: integer (del periodo actual)
- credits_extra: integer (comprados, no expiran)
- resets_at: timestamp (inicio proximo periodo)
- last_reset_at: timestamp
- created_at: timestamp
- updated_at: timestamp
Relaciones:
- 1:1 con Tenant
Notas:
- credits_remaining se resetea cada periodo de facturacion
- credits_extra no se resetean, son acumulables
- Al consumir, primero se usan credits_remaining, luego credits_extra
```
### CreditTransaction
```yaml
Entidad: CreditTransaction
Descripcion: Historial de movimientos de creditos
Atributos:
- id: UUID (PK)
- tenant_id: UUID (FK)
- type: enum [subscription_reset, purchase, usage, adjustment, refund]
- amount: integer (positivo o negativo)
- balance_after: integer
- description: string
- reference_type: string (generation_job, invoice, manual)
- reference_id: UUID
- created_at: timestamp
Relaciones:
- N:1 con Tenant
```
---
## Funcionalidades
### F-009.1: Seleccionar Plan y Suscribirse
| ID | Funcionalidad | Descripcion | Prioridad |
|----|---------------|-------------|-----------|
| F-009.1.1 | Ver planes disponibles | Mostrar comparativa de planes | Alta |
| F-009.1.2 | Seleccionar plan | Elegir plan deseado | Alta |
| F-009.1.3 | Crear customer Stripe | Registrar cliente en Stripe | Alta |
| F-009.1.4 | Iniciar trial | Periodo de prueba de 14 dias | Media |
### F-009.2: Checkout con Stripe Elements
| ID | Funcionalidad | Descripcion | Prioridad |
|----|---------------|-------------|-----------|
| F-009.2.1 | Crear checkout session | Generar sesion de pago Stripe | Alta |
| F-009.2.2 | Stripe Elements UI | Formulario de pago embebido | Alta |
| F-009.2.3 | Confirmar pago | Procesar transaccion | Alta |
| F-009.2.4 | Manejar errores | Reintentos y mensajes claros | Alta |
### F-009.3: Gestionar Suscripcion
| ID | Funcionalidad | Descripcion | Prioridad |
|----|---------------|-------------|-----------|
| F-009.3.1 | Ver suscripcion actual | Detalles del plan activo | Alta |
| F-009.3.2 | Upgrade de plan | Cambiar a plan superior | Alta |
| F-009.3.3 | Downgrade de plan | Cambiar a plan inferior | Media |
| F-009.3.4 | Cancelar suscripcion | Finalizar al terminar periodo | Media |
| F-009.3.5 | Reactivar suscripcion | Revertir cancelacion pendiente | Media |
### F-009.4: Ver Facturas e Historial
| ID | Funcionalidad | Descripcion | Prioridad |
|----|---------------|-------------|-----------|
| F-009.4.1 | Listar facturas | Historial de pagos | Alta |
| F-009.4.2 | Descargar factura PDF | Obtener comprobante | Alta |
| F-009.4.3 | Ver detalle de factura | Items, impuestos, totales | Media |
### F-009.5: Comprar Creditos Adicionales
| ID | Funcionalidad | Descripcion | Prioridad |
|----|---------------|-------------|-----------|
| F-009.5.1 | Ver packs disponibles | Mostrar opciones de creditos | Media |
| F-009.5.2 | Comprar pack | Checkout one-time | Media |
| F-009.5.3 | Acreditar creditos | Sumar a credits_extra | Media |
### F-009.6: Webhooks de Stripe
| ID | Funcionalidad | Descripcion | Prioridad |
|----|---------------|-------------|-----------|
| F-009.6.1 | invoice.paid | Actualizar estado de factura | Alta |
| F-009.6.2 | invoice.payment_failed | Notificar y manejar fallo | Alta |
| F-009.6.3 | customer.subscription.updated | Sincronizar cambios de suscripcion | Alta |
| F-009.6.4 | customer.subscription.deleted | Manejar cancelacion | Alta |
| F-009.6.5 | checkout.session.completed | Confirmar compra one-time | Alta |
---
## API Endpoints
```yaml
Base: /api/v1/billing
# Checkout y Suscripcion
POST /billing/checkout:
Descripcion: Crear sesion de checkout Stripe
Body: { plan_code: "pro", success_url: string, cancel_url: string }
Response: { checkout_url: string, session_id: string }
Permisos: tenant_admin
GET /billing/subscription:
Descripcion: Ver suscripcion actual del tenant
Response: { subscription, plan, usage }
Permisos: authenticated
POST /billing/subscription/upgrade:
Descripcion: Upgrade inmediato a plan superior
Body: { new_plan_code: string }
Response: { subscription, proration_amount }
Permisos: tenant_admin
POST /billing/subscription/downgrade:
Descripcion: Downgrade al final del periodo
Body: { new_plan_code: string }
Response: { subscription, effective_date }
Permisos: tenant_admin
POST /billing/subscription/cancel:
Descripcion: Cancelar suscripcion al final del periodo
Body: { reason?: string, feedback?: string }
Response: { subscription, cancel_at }
Permisos: tenant_admin
POST /billing/subscription/reactivate:
Descripcion: Revertir cancelacion pendiente
Response: { subscription }
Permisos: tenant_admin
# Metodos de Pago
GET /billing/payment-methods:
Descripcion: Listar metodos de pago
Response: { payment_methods: [] }
Permisos: tenant_admin
POST /billing/payment-methods:
Descripcion: Agregar metodo de pago
Body: { payment_method_id: string }
Response: { payment_method }
Permisos: tenant_admin
DELETE /billing/payment-methods/:id:
Descripcion: Eliminar metodo de pago
Response: 204 No Content
Permisos: tenant_admin
PATCH /billing/payment-methods/:id/default:
Descripcion: Establecer como metodo predeterminado
Response: { payment_method }
Permisos: tenant_admin
# Facturas
GET /billing/invoices:
Descripcion: Listar facturas del tenant
Query: ?status=paid&page=1&limit=20
Response: { invoices: [], pagination }
Permisos: tenant_admin
GET /billing/invoices/:id:
Descripcion: Detalle de factura
Response: { invoice }
Permisos: tenant_admin
GET /billing/invoices/:id/pdf:
Descripcion: Descargar PDF de factura
Response: Redirect a URL de Stripe
Permisos: tenant_admin
# Creditos
GET /billing/credits:
Descripcion: Ver balance de creditos
Response: { credits_remaining, credits_extra, credits_used, resets_at }
Permisos: authenticated
POST /billing/credits/purchase:
Descripcion: Comprar pack de creditos
Body: { pack_code: "pmc_generations_100" }
Response: { checkout_url, session_id }
Permisos: tenant_admin
GET /billing/credits/transactions:
Descripcion: Historial de movimientos de creditos
Query: ?type=usage&page=1&limit=50
Response: { transactions: [], pagination }
Permisos: tenant_admin
# Webhooks (endpoint publico)
POST /billing/webhooks:
Descripcion: Endpoint para webhooks de Stripe
Headers: Stripe-Signature
Response: 200 OK
Notas: Verificar firma con STRIPE_WEBHOOK_SECRET
```
---
## Reglas de Negocio
```yaml
RN-009.1:
Descripcion: Solo tenant_admin puede cambiar plan
Validacion: Verificar rol del usuario
Accion: 403 Forbidden si no es admin
RN-009.2:
Descripcion: Downgrade aplica al final del periodo
Validacion: No cambio inmediato, schedule para renewal
Accion: Stripe schedule subscription update
RN-009.3:
Descripcion: Creditos del plan no usados no se transfieren
Validacion: credits_remaining se resetea cada periodo
Excepcion: credits_extra (comprados) son permanentes
RN-009.4:
Descripcion: Cancelacion permite usar hasta fin del periodo
Validacion: cancel_at_period_end = true
Accion: Acceso continua hasta current_period_end
RN-009.5:
Descripcion: Plan Free no requiere metodo de pago
Validacion: Permitir suscripcion sin checkout
Accion: Crear subscription con trial infinito o sin cobro
RN-009.6:
Descripcion: Upgrade es inmediato con prorrateo
Validacion: Cobrar diferencia proporcional
Accion: Stripe proration automatico
RN-009.7:
Descripcion: Pago fallido da 3 reintentos
Validacion: Stripe Smart Retries habilitado
Accion: Notificar usuario, suspender tras fallos
RN-009.8:
Descripcion: Creditos se consumen en orden
Validacion: Primero credits_remaining, luego credits_extra
Accion: Logica en GenerationService
RN-009.9:
Descripcion: Plan Internal solo asignable por super_admin
Validacion: Verificar rol super_admin
Accion: No disponible en checkout publico
```
---
## Dependencias
```yaml
Dependencias de Modulos:
- PMC-001 Tenants:
uso: Asociacion tenant-plan, limites por tenant
datos: tenant_id, plan_id, limits JSONB
- PMC-007 Admin:
uso: Permisos de billing, gestion de planes
datos: admin.billing permission
- PMC-004 Generation:
uso: Consumo de creditos por generacion
integracion: Decrementar credits al generar
Dependencias del Catalogo:
- @CATALOG_PAYMENTS:
path: shared/catalog/payments/
uso: Patron base de integracion Stripe
incluye:
- Stripe SDK wrapper
- Webhook handling
- Customer management
- Subscription lifecycle
adaptar:
- Crear productos/precios PMC en Stripe
- Implementar sistema de creditos
- Integrar con planes de PMC-001
docs: shared/catalog/payments/README.md
- @CATALOG_NOTIFY:
path: shared/catalog/notifications/
uso: Notificaciones de pago
incluye:
- Email de confirmacion de pago
- Alerta de pago fallido
- Recordatorio de vencimiento
docs: shared/catalog/notifications/README.md
Servicios Externos:
- Stripe:
tipo: Payment Gateway
productos:
- Subscriptions API
- Checkout Sessions
- Payment Intents
- Webhooks
- Customer Portal
sdk: stripe (npm)
version: "^14.0.0"
Referencia de Implementacion:
- Payment service: projects/gamilit/apps/backend/src/modules/payments/
- Stripe integration: projects/gamilit/apps/backend/src/modules/payments/services/stripe.service.ts
- Webhook handler: projects/gamilit/apps/backend/src/modules/payments/controllers/webhooks.controller.ts
```
---
## Configuracion
```yaml
Variables de Entorno:
STRIPE_SECRET_KEY:
descripcion: API key secreta de Stripe
formato: sk_live_xxx o sk_test_xxx
requerido: true
STRIPE_PUBLISHABLE_KEY:
descripcion: API key publica para frontend
formato: pk_live_xxx o pk_test_xxx
requerido: true
STRIPE_WEBHOOK_SECRET:
descripcion: Secret para verificar webhooks
formato: whsec_xxx
requerido: true
STRIPE_PRICE_PRO:
descripcion: Price ID del plan Pro
formato: price_xxx
requerido: true
STRIPE_PRICE_ENTERPRISE:
descripcion: Price ID del plan Enterprise
formato: price_xxx
requerido: true
STRIPE_PRICE_CREDITS_100:
descripcion: Price ID del pack de 100 creditos
formato: price_xxx
requerido: true
STRIPE_TRIAL_DAYS:
descripcion: Dias de prueba para nuevas suscripciones
default: 14
requerido: false
BILLING_CURRENCY:
descripcion: Moneda por defecto
default: "usd"
requerido: false
```
---
## Flujos de Usuario
### Suscribirse a Plan Pro
```
1. Usuario navega a Settings → Billing → Plans
2. Ve comparativa de planes (Free, Pro, Enterprise)
3. Selecciona "Upgrade to Pro"
4. Sistema crea Checkout Session en Stripe
5. Redirect a Stripe Checkout
6. Usuario ingresa datos de pago (Stripe Elements)
7. Stripe procesa pago
8. Webhook invoice.paid recibido
9. Sistema actualiza subscription y credits
10. Redirect a success_url con confirmacion
```
### Cancelar Suscripcion
```
1. Admin navega a Settings → Billing → Subscription
2. Click en "Cancel Subscription"
3. Modal de confirmacion con fecha de fin
4. Opcionalmente ingresa razon/feedback
5. Sistema llama Stripe cancel at period end
6. Suscripcion marcada cancel_at_period_end = true
7. Usuario puede seguir usando hasta current_period_end
8. Al vencer, subscription status = canceled
```
### Comprar Creditos Extra
```
1. Usuario ve que credits_remaining esta bajo
2. Navega a Settings → Billing → Credits
3. Ve packs disponibles (100 creditos por $19)
4. Click en "Buy Credits"
5. Checkout Session para one-time payment
6. Stripe procesa pago
7. Webhook checkout.session.completed
8. Sistema suma credits_extra += 100
9. Redirect con confirmacion
```
---
## Webhooks de Stripe
```yaml
Eventos a Procesar:
invoice.paid:
accion:
- Actualizar Invoice status = paid
- Si es primera factura, activar subscription
- Reset credits_remaining del periodo
invoice.payment_failed:
accion:
- Actualizar Invoice status segun attempt
- Notificar usuario por email
- Tras 3 fallos, marcar subscription past_due
customer.subscription.created:
accion:
- Crear registro Subscription local
- Crear GenerationCredit para tenant
- Actualizar tenant.plan_id
customer.subscription.updated:
accion:
- Sincronizar status, period dates
- Si cambio de plan, actualizar limits
- Recalcular credits si aplica
customer.subscription.deleted:
accion:
- Marcar subscription status = canceled
- Cambiar tenant a plan Free
- Notificar admin del tenant
checkout.session.completed:
accion:
- Si mode = subscription, ya manejado por invoice.paid
- Si mode = payment (creditos), acreditar credits_extra
- Crear CreditTransaction
customer.created:
accion:
- Actualizar tenant con stripe_customer_id
payment_method.attached:
accion:
- Crear/actualizar PaymentMethod local
```
---
## Criterios de Aceptacion
- [ ] Checkout con Stripe Elements funciona end-to-end
- [ ] Suscripcion se crea correctamente tras pago
- [ ] Upgrade inmediato con prorrateo funciona
- [ ] Downgrade se programa para fin de periodo
- [ ] Cancelacion permite uso hasta vencimiento
- [ ] Facturas se sincronizan via webhooks
- [ ] PDFs de facturas descargables
- [ ] Sistema de creditos funciona correctamente
- [ ] Compra de creditos extra funciona
- [ ] Webhooks procesan todos los eventos clave
- [ ] Notificaciones de pago se envian
- [ ] Solo tenant_admin puede gestionar billing
---
## Consideraciones de Seguridad
```yaml
Seguridad:
- API keys de Stripe solo en backend (nunca en frontend)
- Webhook signature verification obligatorio
- PCI compliance delegado a Stripe (no almacenar tarjetas)
- Audit log de todas las transacciones
- Rate limiting en endpoints de billing
- Validar que usuario pertenece al tenant
```
---
## Referencias
- [ARQUITECTURA-TECNICA.md](../00-vision-general/ARQUITECTURA-TECNICA.md)
- [@CATALOG_PAYMENTS](../../../shared/catalog/payments/)
- [PMC-001-TENANTS.md](./PMC-001-TENANTS.md)
- [PMC-007-ADMIN.md](./PMC-007-ADMIN.md)
- [Stripe Docs](https://stripe.com/docs)
---
**Documento generado por:** Requirements-Analyst
**Fecha:** 2026-01-04

View File

@ -1,3 +1,13 @@
---
id: "_INDEX"
title: "Índice de Módulos - Platform Marketing Content"
type: "Index"
status: "Draft"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# Índice de Módulos - Platform Marketing Content
**Versión:** 1.0.0
@ -17,6 +27,7 @@
| PMC-006 | [Assets](./PMC-006-ASSETS.md) | DAM, biblioteca de activos, versionado | Alta | Definido |
| PMC-007 | [Admin](./PMC-007-ADMIN.md) | Usuarios, roles, permisos, configuración SaaS | Media | Definido |
| PMC-008 | [Analytics](./PMC-008-ANALYTICS.md) | Dashboards, reportes, métricas | Baja | Definido |
| PMC-009 | [Payments](./PMC-009-PAYMENTS.md) | Integracion Stripe, suscripciones, billing | Alta | Definido |
---
@ -88,6 +99,10 @@
8. **PMC-008 Analytics** - Dashboards y reportes
### Fase 4 - Monetizacion SaaS
9. **PMC-009 Payments** - Integracion Stripe, suscripciones, billing
---
## Entidades Compartidas
@ -102,6 +117,9 @@
| Campaign | PMC-003 | PMC-004, PMC-005, PMC-006, PMC-008 |
| Asset | PMC-006 | PMC-002, PMC-003, PMC-004 |
| GenerationJob | PMC-004 | PMC-003, PMC-006, PMC-008 |
| Subscription | PMC-009 | PMC-001, PMC-007 |
| Invoice | PMC-009 | PMC-007 |
| GenerationCredit | PMC-009 | PMC-001, PMC-004 |
---
@ -117,6 +135,7 @@
| Assets | `/api/v1/assets` | assets, collections, downloads |
| Admin | `/api/v1/admin` | users, roles, settings, audit |
| Analytics | `/api/v1/analytics` | dashboards, metrics, reports |
| Payments | `/api/v1/billing` | checkout, subscription, invoices, credits |
---
@ -132,7 +151,8 @@
| PMC-006 | 18 | 10 | 6 | 2 |
| PMC-007 | 14 | 7 | 5 | 2 |
| PMC-008 | 10 | 3 | 5 | 2 |
| **TOTAL** | **118** | **64** | **41** | **13** |
| PMC-009 | 18 | 12 | 6 | 0 |
| **TOTAL** | **136** | **76** | **47** | **13** |
---

View File

@ -1,3 +1,17 @@
---
id: "RF-PMC-001"
title: "Tenants Module"
type: "Requirement"
status: "Done"
priority: "Alta"
module: "tenants"
project: "platform_marketing_content"
version: "1.0"
rf_count: 15
created_date: "2025-12-08"
updated_date: "2026-01-04"
---
# Requerimientos Funcionales - PMC-001 Tenants
**Módulo:** Tenants

View File

@ -1,3 +1,17 @@
---
id: "RF-PMC-002"
title: "CRM Module"
type: "Requirement"
status: "Done"
priority: "Alta"
module: "crm"
project: "platform_marketing_content"
version: "1.0"
rf_count: 20
created_date: "2025-12-08"
updated_date: "2026-01-04"
---
# Requerimientos Funcionales - PMC-002 CRM
**Módulo:** CRM

View File

@ -1,3 +1,17 @@
---
id: "RF-PMC-003"
title: "Projects Module"
type: "Requirement"
status: "Done"
priority: "Alta"
module: "projects"
project: "platform_marketing_content"
version: "1.0"
rf_count: 15
created_date: "2025-12-08"
updated_date: "2026-01-04"
---
# Requerimientos Funcionales - PMC-003 Projects
**Módulo:** Projects

View File

@ -1,3 +1,17 @@
---
id: "RF-PMC-004"
title: "Generation Module"
type: "Requirement"
status: "Done"
priority: "Alta"
module: "generation"
project: "platform_marketing_content"
version: "1.0"
rf_count: 18
created_date: "2025-12-08"
updated_date: "2026-01-04"
---
# Requerimientos Funcionales - PMC-004 Generation
**Módulo:** Generation (Motor IA)

View File

@ -1,3 +1,17 @@
---
id: "RF-PMC-005"
title: "Automation Module"
type: "Requirement"
status: "Done"
priority: "Media"
module: "automation"
project: "platform_marketing_content"
version: "1.0"
rf_count: 10
created_date: "2025-12-08"
updated_date: "2026-01-04"
---
# Requerimientos Funcionales - PMC-005 Automation
**Módulo:** Automation

View File

@ -1,3 +1,17 @@
---
id: "RF-PMC-006"
title: "Assets Module (DAM)"
type: "Requirement"
status: "Done"
priority: "Alta"
module: "assets"
project: "platform_marketing_content"
version: "1.0"
rf_count: 12
created_date: "2025-12-08"
updated_date: "2026-01-04"
---
# Requerimientos Funcionales - PMC-006 Assets
**Módulo:** Assets (DAM)

View File

@ -1,3 +1,17 @@
---
id: "RF-PMC-007"
title: "Admin Module"
type: "Requirement"
status: "Done"
priority: "Alta"
module: "admin"
project: "platform_marketing_content"
version: "1.0"
rf_count: 10
created_date: "2025-12-08"
updated_date: "2026-01-04"
---
# Requerimientos Funcionales - PMC-007 Admin
**Módulo:** Admin

View File

@ -1,3 +1,17 @@
---
id: "RF-PMC-008"
title: "Analytics Module"
type: "Requirement"
status: "Done"
priority: "Media"
module: "analytics"
project: "platform_marketing_content"
version: "1.0"
rf_count: 8
created_date: "2025-12-08"
updated_date: "2026-01-04"
---
# Requerimientos Funcionales - PMC-008 Analytics
**Módulo:** Analytics

View File

@ -1,3 +1,13 @@
---
id: "_INDEX"
title: "Índice de Requerimientos Funcionales"
type: "Index"
status: "Draft"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# Índice de Requerimientos Funcionales
**Versión:** 1.0.0

View File

@ -0,0 +1,133 @@
---
id: "DEFINITION-OF-DONE"
title: "Definition of Done (DoD) - Platform Marketing Content"
type: "Process"
status: "Draft"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# Definition of Done (DoD) - Platform Marketing Content
**Proyecto:** Platform Marketing Content - Plataforma SaaS de Generacion de Contenido
**Ultima actualizacion:** 2026-01-04
---
## Proposito
El Definition of Done (DoD) define los criterios que un item debe cumplir para considerarse completado y listo para produccion.
---
## Criterios Generales
Un item esta "Done" cuando:
### 1. Codigo
- [ ] Codigo implementado y funcionando
- [ ] Code review aprobado (si aplica)
- [ ] Sin warnings de linter/TypeScript
- [ ] Sin errores de compilacion
### 2. Testing
- [ ] Tests unitarios escritos y pasando
- [ ] Tests de integracion (si aplica)
- [ ] Pruebas manuales realizadas
- [ ] Coverage minimo cumplido (>80%)
### 3. Documentacion
- [ ] API documentada (Swagger/OpenAPI)
- [ ] Notas de implementacion en el item
- [ ] _MAP.md actualizado si se agregan archivos
- [ ] README actualizado si cambia configuracion
### 4. Deploy
- [ ] Build exitoso en CI/CD
- [ ] Deploy a ambiente de desarrollo
- [ ] Smoke tests pasados
- [ ] Sin regresiones detectadas
---
## Checklist por Tipo de Item
### User Story
- [ ] Todos los criterios de aceptacion cumplidos
- [ ] Frontend y Backend integrados
- [ ] UI/UX conforme al diseno
- [ ] Responsive (si aplica)
- [ ] Accesibilidad basica (si aplica)
### Bug Fix
- [ ] Bug ya no se reproduce
- [ ] Causa raiz identificada
- [ ] Test que previene regresion
- [ ] Fix verificado en ambiente similar al reporte
### Technical Task
- [ ] Objetivo tecnico cumplido
- [ ] Documentacion tecnica actualizada
- [ ] Metricas de mejora verificadas (si aplica)
---
## Criterios Especificos para PMC
### Para Features de Generacion IA
- [ ] Workflow de ComfyUI funcionando
- [ ] Resultados de calidad aceptable
- [ ] Tiempos de generacion dentro de lo esperado
- [ ] Cola de tareas procesando correctamente
- [ ] Assets guardados en S3/MinIO
### Para Features Multi-Tenant
- [ ] RLS funcionando correctamente
- [ ] No hay data leakage entre tenants
- [ ] Cuotas y limites aplicados
- [ ] Audit log registrando acciones
### Para Integraciones
- [ ] Endpoints externos conectados
- [ ] Reintentos y fallbacks funcionando
- [ ] Rate limiting respetado
- [ ] Webhooks recibiendo/enviando correctamente
### Para Features de Frontend
- [ ] Componentes funcionando en todos los navegadores objetivo
- [ ] Estados de carga (loading, error, empty) implementados
- [ ] Validaciones de formulario funcionando
- [ ] Notificaciones/feedback al usuario
---
## Criterios de Seguridad
- [ ] No hay secrets en codigo
- [ ] Inputs validados y sanitizados
- [ ] Autenticacion/Autorizacion verificada
- [ ] Sin vulnerabilidades conocidas (OWASP Top 10)
---
## Notas
- Items no pueden marcarse como "Done" sin cumplir todos los criterios aplicables
- El Definition of Done debe respetarse para mantener calidad
- Excepciones deben documentarse y aprobarse
---
**Basado en:** Estandar SCRUM + SIMCO (Sistema Indexado Modular por Contexto)

View File

@ -0,0 +1,124 @@
---
id: "DEFINITION-OF-READY"
title: "Definition of Ready (DoR) - Platform Marketing Content"
type: "Process"
status: "Draft"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# Definition of Ready (DoR) - Platform Marketing Content
**Proyecto:** Platform Marketing Content - Plataforma SaaS de Generacion de Contenido
**Ultima actualizacion:** 2026-01-04
---
## Proposito
El Definition of Ready (DoR) define los criterios que un item del backlog debe cumplir antes de que pueda ser trabajado en un Sprint.
---
## Criterios Generales
Un item del backlog esta "Ready" cuando:
### 1. Claridad
- [ ] El titulo es claro y descriptivo
- [ ] La descripcion del problema/necesidad esta documentada
- [ ] Los criterios de aceptacion estan definidos
- [ ] No hay ambiguedades en los requisitos
### 2. Alcance
- [ ] El scope esta claramente delimitado
- [ ] Las dependencias estan identificadas
- [ ] Los items bloqueantes estan resueltos
- [ ] El item es lo suficientemente pequeno para un Sprint
### 3. Estimacion
- [ ] El equipo ha estimado story points
- [ ] La complejidad tecnica esta evaluada
- [ ] Los riesgos estan identificados
### 4. Documentacion
- [ ] Existe RF (Requerimiento Funcional) asociado
- [ ] Los mockups/wireframes estan disponibles (si aplica)
- [ ] La arquitectura esta definida (si aplica)
---
## Checklist por Tipo de Item
### User Story
- [ ] Formato "Como [rol], quiero [funcionalidad], para [beneficio]"
- [ ] Criterios de aceptacion en formato checklist
- [ ] RF relacionado identificado
- [ ] Story points estimados
- [ ] Sin bloqueos activos
### Bug Fix
- [ ] Pasos para reproducir documentados
- [ ] Comportamiento esperado vs actual documentado
- [ ] Severidad/Prioridad asignada
- [ ] Ambiente donde se reproduce identificado
### Technical Task
- [ ] Objetivo tecnico claro
- [ ] Impacto en el sistema documentado
- [ ] Criterios de completitud definidos
- [ ] Rollback plan si aplica
---
## Criterios de Prioridad
| Prioridad | Descripcion |
|-----------|-------------|
| P0 - Critical | Bloqueante para produccion, seguridad |
| P1 - High | Funcionalidad core, deadline cercano |
| P2 - Medium | Mejoras importantes, puede esperar |
| P3 - Low | Nice-to-have, mejoras menores |
---
## Criterios Especificos para PMC
### Para Features de Generacion IA
- [ ] Workflow de ComfyUI definido o identificado
- [ ] Modelos base y LoRAs necesarios identificados
- [ ] Parametros de generacion documentados
- [ ] Tiempo estimado de generacion conocido
### Para Features Multi-Tenant
- [ ] Impacto en RLS evaluado
- [ ] Aislamiento de datos verificado
- [ ] Cuotas y limites definidos
### Para Integraciones (n8n, APIs)
- [ ] Endpoints externos documentados
- [ ] Autenticacion definida
- [ ] Rate limits conocidos
---
## Notas
- Items que no cumplan DoR no entran al Sprint
- El PO es responsable de asegurar que el backlog este "Ready"
- El equipo puede rechazar items que no cumplan DoR en Planning
---
**Basado en:** Estandar SCRUM + SIMCO (Sistema Indexado Modular por Contexto)

View File

@ -0,0 +1,66 @@
---
id: "README"
title: "Backlog - Platform Marketing Content"
type: "README"
status: "Draft"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# Backlog - Platform Marketing Content
**Proyecto:** Platform Marketing Content
**Ultima actualizacion:** 2026-01-04
---
## Proposito
Esta carpeta contiene el backlog del proyecto, incluyendo items futuros y criterios de calidad.
---
## Contenido
| Archivo | Descripcion |
|---------|-------------|
| [DEFINITION-OF-READY.md](./DEFINITION-OF-READY.md) | Criterios para que un item entre a Sprint |
| [DEFINITION-OF-DONE.md](./DEFINITION-OF-DONE.md) | Criterios para que un item se considere completado |
| README.md | Este archivo |
---
## Items de Backlog
Los items del backlog se documentan en los EPICs correspondientes en `/docs/05-user-stories/`.
### Por Fase
| Fase | EPICs | Estado |
|------|-------|--------|
| 1 - MVP Core | EPIC-001 a EPIC-005, EPIC-008 | Documentado |
| 2 - Personalizacion | EPIC-006 | Documentado |
| 3 - Contenido Enriquecido | EPIC-007 | Documentado |
### Backlog Futuro
Items identificados para fases posteriores:
1. **Portal de Clientes** - Permitir a clientes ver y aprobar contenido
2. **Entrenamientos LoRA** - Entrenar modelos personalizados desde la UI
3. **Integracion con Redes Sociales** - Publicar directamente a plataformas
4. **Generacion de Video** - Agregar soporte para video corto
5. **White Label** - Personalizar branding por tenant
---
## Referencias
- **Tablero Kanban:** `/docs/planning/Board.md`
- **Configuracion:** `/docs/planning/config.yml`
- **Roadmap:** `/docs/90-transversal/roadmap/ROADMAP-PMC.md`
---
**Mantenido por:** Product Owner / Architecture Team

View File

@ -1,3 +1,13 @@
---
id: "ESQUEMA-BD"
title: "Esquema de Base de Datos - Platform Marketing Content"
type: "Model"
status: "Draft"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# Esquema de Base de Datos - Platform Marketing Content
**Versión:** 1.0.0

View File

@ -1,3 +1,13 @@
---
id: "MODELO-DOMINIO"
title: "Modelo de Dominio - Platform Marketing Content"
type: "Model"
status: "Draft"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# Modelo de Dominio - Platform Marketing Content
**Versión:** 1.0.0

View File

@ -1,3 +1,17 @@
---
id: "EPIC-001"
title: "Setup y Autenticacion"
type: "Epic"
status: "Done"
priority: "Alta"
project: "platform_marketing_content"
phase: 1
story_points: 40
user_stories_count: 8
created_date: "2025-12-08"
updated_date: "2026-01-04"
---
# EPIC-001: Setup y Autenticación
**Versión:** 1.0.0

View File

@ -1,3 +1,17 @@
---
id: "EPIC-002"
title: "Gestion de CRM"
type: "Epic"
status: "Done"
priority: "Alta"
project: "platform_marketing_content"
phase: 1
story_points: 60
user_stories_count: 12
created_date: "2025-12-08"
updated_date: "2026-01-04"
---
# EPIC-002: Gestión de CRM
**Versión:** 1.0.0

View File

@ -1,3 +1,17 @@
---
id: "EPIC-003"
title: "Proyectos y Campanas"
type: "Epic"
status: "Done"
priority: "Alta"
project: "platform_marketing_content"
phase: 1
story_points: 50
user_stories_count: 10
created_date: "2025-12-08"
updated_date: "2026-01-04"
---
# EPIC-003: Proyectos y Campañas
**Versión:** 1.0.0

View File

@ -1,3 +1,17 @@
---
id: "EPIC-004"
title: "Generacion de Contenido"
type: "Epic"
status: "Done"
priority: "Alta"
project: "platform_marketing_content"
phase: 1
story_points: 75
user_stories_count: 15
created_date: "2025-12-08"
updated_date: "2026-01-04"
---
# EPIC-004: Generación de Contenido
**Versión:** 1.0.0

View File

@ -1,3 +1,17 @@
---
id: "EPIC-005"
title: "Biblioteca de Assets (DAM)"
type: "Epic"
status: "Done"
priority: "Alta"
project: "platform_marketing_content"
phase: 1
story_points: 50
user_stories_count: 10
created_date: "2025-12-08"
updated_date: "2026-01-04"
---
# EPIC-005: Biblioteca de Assets (DAM)
**Versión:** 1.0.0

View File

@ -1,3 +1,17 @@
---
id: "EPIC-006"
title: "Automatizacion"
type: "Epic"
status: "Done"
priority: "Media"
project: "platform_marketing_content"
phase: 2
story_points: 30
user_stories_count: 6
created_date: "2025-12-08"
updated_date: "2026-01-04"
---
# EPIC-006: Automatización
**Versión:** 1.0.0

View File

@ -1,3 +1,17 @@
---
id: "EPIC-007"
title: "Analytics"
type: "Epic"
status: "Done"
priority: "Media"
project: "platform_marketing_content"
phase: 3
story_points: 25
user_stories_count: 5
created_date: "2025-12-08"
updated_date: "2026-01-04"
---
# EPIC-007: Analytics
**Versión:** 1.0.0

View File

@ -1,3 +1,17 @@
---
id: "EPIC-008"
title: "Administracion y Configuracion"
type: "Epic"
status: "Done"
priority: "Alta"
project: "platform_marketing_content"
phase: 1
story_points: 55
user_stories_count: 11
created_date: "2025-12-08"
updated_date: "2026-01-04"
---
# EPIC-008: Administracion y Configuracion
**Version:** 1.0.0

View File

@ -1,3 +1,13 @@
---
id: "_INDEX"
title: "Índice de User Stories"
type: "Index"
status: "Draft"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# Índice de User Stories
**Versión:** 1.0.0

View File

@ -1,3 +1,13 @@
---
id: "README"
title: "Documentacion Transversal - PMC"
type: "README"
status: "Draft"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# Documentacion Transversal - PMC
**Version:** 1.0.0

View File

@ -1,3 +1,13 @@
---
id: "AUDITORIA-DOCUMENTACION-PMC"
title: "Auditoria de Documentacion - Platform Marketing Content"
type: "Audit"
status: "Draft"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# Auditoria de Documentacion - Platform Marketing Content
**Fecha:** 2025-12-08
@ -236,14 +246,14 @@
| Componente | Modulo | Path | Documentado |
|------------|--------|------|-------------|
| @CATALOG_AUTH | PMC-007 | core/catalog/auth/ | SI |
| @CATALOG_SESSION | PMC-007 | core/catalog/session-management/ | SI |
| @CATALOG_TENANT | PMC-001 | core/catalog/multi-tenancy/ | SI |
| @CATALOG_RATELIMIT | PMC-004 | core/catalog/rate-limiting/ | SI |
| @CATALOG_NOTIFY | PMC-005 | core/catalog/notifications/ | SI |
| @CATALOG_WS | PMC-004 | core/catalog/websocket/ | SI |
| @CATALOG_PAYMENTS | PMC-001 | core/catalog/payments/ | SI |
| @CATALOG_FLAGS | PMC-007 | core/catalog/feature-flags/ | SI |
| @CATALOG_AUTH | PMC-007 | shared/catalog/auth/ | SI |
| @CATALOG_SESSION | PMC-007 | shared/catalog/session-management/ | SI |
| @CATALOG_TENANT | PMC-001 | shared/catalog/multi-tenancy/ | SI |
| @CATALOG_RATELIMIT | PMC-004 | shared/catalog/rate-limiting/ | SI |
| @CATALOG_NOTIFY | PMC-005 | shared/catalog/notifications/ | SI |
| @CATALOG_WS | PMC-004 | shared/catalog/websocket/ | SI |
| @CATALOG_PAYMENTS | PMC-001 | shared/catalog/payments/ | SI |
| @CATALOG_FLAGS | PMC-007 | shared/catalog/feature-flags/ | SI |
**Cumplimiento SIMCO:** 100%

View File

@ -1,3 +1,13 @@
---
id: "ROADMAP-PMC"
title: "Roadmap - Platform Marketing Content"
type: "Roadmap"
status: "Draft"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# Roadmap - Platform Marketing Content
**Version:** 1.0.0

View File

@ -1,3 +1,13 @@
---
id: "GUIA-CONVENCIONES"
title: "Guía de Convenciones de Desarrollo"
type: "Guide"
status: "Active"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# Guía de Convenciones de Desarrollo
**Versión:** 1.0.0

View File

@ -1,3 +1,13 @@
---
id: "GUIA-SETUP"
title: "Guía de Setup del Proyecto"
type: "Guide"
status: "Active"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# Guía de Setup del Proyecto
**Versión:** 1.0.0

View File

@ -1,3 +1,16 @@
---
id: "ADR-001"
title: "Seleccion de Stack Tecnologico"
type: "ADR"
status: "Accepted"
date: "2025-12-08"
deciders: ["Architecture Team"]
tags: ["backend", "frontend", "database", "stack"]
project: "platform_marketing_content"
created_date: "2025-12-08"
updated_date: "2026-01-04"
---
# ADR-001: Selección de Stack Tecnológico
**Fecha:** 2025-12-08

View File

@ -1,3 +1,16 @@
---
id: "ADR-002"
title: "Estrategia de Multi-Tenancy"
type: "ADR"
status: "Accepted"
date: "2025-12-08"
deciders: ["Architecture Team"]
tags: ["database", "rls", "multitenancy", "security"]
project: "platform_marketing_content"
created_date: "2025-12-08"
updated_date: "2026-01-04"
---
# ADR-002: Estrategia de Multi-Tenancy
**Fecha:** 2025-12-08

View File

@ -1,3 +1,16 @@
---
id: "ADR-003"
title: "Motor de Generacion de Imagenes"
type: "ADR"
status: "Accepted"
date: "2025-12-08"
deciders: ["Architecture Team"]
tags: ["ai", "comfyui", "sdxl", "generation", "lora"]
project: "platform_marketing_content"
created_date: "2025-12-08"
updated_date: "2026-01-04"
---
# ADR-003: Motor de Generación de Imágenes
**Fecha:** 2025-12-08

View File

@ -1,3 +1,16 @@
---
id: "ADR-004"
title: "Sistema de Cola de Tareas"
type: "ADR"
status: "Accepted"
date: "2025-12-08"
deciders: ["Architecture Team"]
tags: ["queue", "bullmq", "redis", "async", "workers"]
project: "platform_marketing_content"
created_date: "2025-12-08"
updated_date: "2026-01-04"
---
# ADR-004: Sistema de Cola de Tareas
**Fecha:** 2025-12-08

View File

@ -1,3 +1,13 @@
---
id: "_INDEX"
title: "Registro de Decisiones de Arquitectura (ADR)"
type: "Index"
status: "Draft"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# Registro de Decisiones de Arquitectura (ADR)
**Versión:** 1.0.0

View File

@ -0,0 +1,220 @@
---
id: "ANALISIS-SAAS-PMC"
title: "Analisis SaaS - Payments y Portales"
type: "Analysis"
status: "Draft"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# Analisis SaaS: Payments y Portales
**Fecha:** 2026-01-04
**Proyecto:** Platform Marketing Content
---
## 1. Estado Actual
### 1.1 Modulos Existentes
| Modulo | Estado | Descripcion |
|--------|--------|-------------|
| PMC-001-TENANTS | Definido | Multi-tenancy con planes |
| PMC-002-CRM | Definido | Clientes, marcas, productos |
| PMC-003-PROJECTS | Definido | Proyectos y campanas |
| PMC-004-GENERATION | Definido | Motor IA, ComfyUI |
| PMC-005-AUTOMATION | Definido | Flujos n8n |
| PMC-006-ASSETS | Definido | DAM |
| PMC-007-ADMIN | Definido | Usuarios, roles |
| PMC-008-ANALYTICS | Definido | Reportes |
| PMC-009-PAYMENTS | NO EXISTE | Stripe, suscripciones |
### 1.2 Planes Definidos (PMC-001)
| Plan | Generaciones/mes | Storage | Usuarios | Precio |
|------|------------------|---------|----------|--------|
| Free | 50 | 1GB | 1 | $0 |
| Pro | 500 | 25GB | 5 | $79/mes |
| Enterprise | Ilimitado | 100GB | Ilimitado | $249/mes |
| Internal | Ilimitado | Ilimitado | Ilimitado | N/A |
### 1.3 Portales Actuales
En PMC-007-ADMIN se definen roles:
- super_admin
- tenant_admin
- creative
- analyst
- viewer
- client_portal
**Falta:** Clarificar separacion en 3 portales distintos
---
## 2. Gaps Identificados
### 2.1 Modulo de Pagos
| Funcionalidad | Estado | Prioridad |
|---------------|--------|-----------|
| Integracion Stripe | No existe | Alta |
| Suscripciones mensuales | No existe | Alta |
| Checkout flow | No existe | Alta |
| Webhooks Stripe | No existe | Alta |
| Facturacion | No existe | Media |
| Creditos adicionales | No existe | Baja |
### 2.2 Portales Diferenciados
| Portal | Estado | Descripcion |
|--------|--------|-------------|
| Portal Usuario | Parcial | Creativos, viewers |
| Portal Admin Cliente | Parcial | tenant_admin |
| Portal Admin SaaS | Parcial | super_admin |
---
## 3. Plan de Ejecucion
### 3.1 Archivos a Crear
| Archivo | Tipo | Contenido |
|---------|------|-----------|
| PMC-009-PAYMENTS.md | Module | Modulo de pagos completo |
| RF-PMC-PAY-001-stripe.md | RF | Integracion Stripe |
| RF-PMC-PAY-002-suscripciones.md | RF | Planes y suscripciones |
| RF-PMC-PAY-003-checkout.md | RF | Flujo de checkout |
| RF-PMC-PAY-004-webhooks.md | RF | Webhooks Stripe |
| ET-PMC-PAY-001-database.md | ET | Modelo de datos billing |
### 3.2 Archivos a Modificar
| Archivo | Cambios |
|---------|---------|
| VISION-GENERAL.md | Agregar seccion Portales y Stripe |
| PMC-001-TENANTS.md | Actualizar referencia a PMC-009 |
| PMC-007-ADMIN.md | Clarificar 3 portales |
---
## 4. Estructura de 3 Portales
### Portal 1: Usuario General (Creative/Viewer)
- Dashboard de proyectos asignados
- Generacion de contenido
- Biblioteca de assets
- Perfil personal
### Portal 2: Admin Cliente (Tenant Admin)
- Dashboard de organizacion
- Gestion de usuarios
- Configuracion del tenant
- Reportes de uso
- Facturacion y suscripcion
- Limites y cuotas
### Portal 3: Admin SaaS (Super Admin)
- Dashboard global
- Gestion de todos los tenants
- Configuracion de planes
- Monitoreo de sistema
- Soporte y tickets
- Analytics globales
---
## 5. Productos Stripe Propuestos
### Configuracion
```yaml
Productos Stripe:
- pmc_starter:
name: "PMC Starter"
price_monthly: $0
price_id: TBD
- pmc_pro:
name: "PMC Pro"
price_monthly: $79
price_id: TBD
- pmc_enterprise:
name: "PMC Enterprise"
price_monthly: $249
price_id: TBD
- pmc_generations_pack:
name: "100 Generaciones Extra"
price: $19
price_id: TBD
type: one_time
```
### Webhooks
```yaml
Eventos a manejar:
- customer.subscription.created
- customer.subscription.updated
- customer.subscription.deleted
- invoice.payment_succeeded
- invoice.payment_failed
- checkout.session.completed
```
---
## 6. Validacion vs Requisitos
| Requisito | Estado | Archivo |
|-----------|--------|---------|
| SaaS multi-tenant | Ya existe | PMC-001-TENANTS |
| Planes de suscripcion | Ya existe | PMC-001-TENANTS |
| Integracion Stripe | A crear | PMC-009-PAYMENTS |
| Portal usuario | A clarificar | VISION-GENERAL |
| Portal admin cliente | A clarificar | VISION-GENERAL |
| Portal admin SaaS | A clarificar | VISION-GENERAL |
---
**Estado:** ✅ COMPLETADO
---
## 7. Ejecución Completada (Fases 5-8)
### 7.1 Archivos Creados
| Archivo | Lineas | Contenido |
|---------|--------|-----------|
| PMC-009-PAYMENTS.md | ~350 | Modulo completo de pagos Stripe |
### 7.2 Archivos Modificados
| Archivo | Cambios |
|---------|---------|
| VISION-GENERAL.md | +75 lineas (Seccion 5.9 Payments, Seccion 5.10 Portales) |
### 7.3 Validación Final
| Requisito | Estado | Archivo |
|-----------|--------|---------|
| Multi-tenancy | ✅ Ya existia | PMC-001-TENANTS |
| Planes definidos | ✅ | PMC-009-PAYMENTS |
| Integracion Stripe | ✅ | PMC-009-PAYMENTS |
| Productos Stripe | ✅ | PMC-009-PAYMENTS |
| Webhooks Stripe | ✅ | PMC-009-PAYMENTS |
| Checkout flow | ✅ | PMC-009-PAYMENTS |
| Portal Usuario | ✅ | VISION-GENERAL seccion 5.10 |
| Portal Admin Cliente | ✅ | VISION-GENERAL seccion 5.10 |
| Portal Admin SaaS | ✅ | VISION-GENERAL seccion 5.10 |
| YAML front-matter | ✅ | 100% de archivos |
**Total archivos nuevos:** 1
**Total archivos modificados:** 2
**Estado general:** COMPLETADO

View File

@ -1,477 +1,486 @@
# Architecture
## Overview
**Platform Marketing Content (PMC)** es una plataforma de generación y gestión de contenido de marketing asistida por inteligencia artificial. Integra ComfyUI para generación de imágenes AI y modelos LLM para contenido textual, ofreciendo un CMS completo para equipos de marketing.
La arquitectura sigue un patrón de aplicación web full-stack con NestJS en backend y React en frontend, con integraciones a servicios de IA para automatización de contenido.
## Tech Stack
- **Backend:** NestJS 10+ + TypeScript 5.3+
- **Frontend:** React + TypeScript + Tailwind CSS + Vite
- **Database:** PostgreSQL 16 (pmc_dev)
- **Cache:** Redis 7
- **Storage:** MinIO (S3-compatible)
- **AI Art:** ComfyUI (Stable Diffusion, FLUX)
- **LLM:** Integration with OpenAI, Claude, local models
- **Auth:** JWT + Passport.js
- **Real-time:** Socket.IO (Bull queues for async jobs)
## Module Structure
```
platform_marketing_content/
├── apps/
│ ├── backend/ # NestJS API
│ │ └── src/
│ │ ├── modules/ # Feature modules
│ │ │ ├── auth/ # Authentication (JWT, local, OAuth)
│ │ │ ├── tenants/ # Multi-tenant management
│ │ │ ├── projects/ # Marketing projects
│ │ │ ├── assets/ # Digital assets (images, videos)
│ │ │ ├── generation/ # AI content generation
│ │ │ ├── automation/ # Workflow automation
│ │ │ ├── crm/ # CRM integration
│ │ │ └── analytics/ # Analytics & reporting
│ │ ├── common/ # Shared code
│ │ │ ├── decorators/ # Custom decorators
│ │ │ ├── filters/ # Exception filters
│ │ │ ├── guards/ # Auth guards
│ │ │ ├── interceptors/ # HTTP interceptors
│ │ │ └── pipes/ # Validation pipes
│ │ ├── config/ # Configuration
│ │ ├── app.module.ts # Root module
│ │ └── main.ts # Bootstrap
│ │
│ └── frontend/ # React SPA
│ └── src/
│ ├── modules/ # Feature modules
│ │ ├── auth/ # Login, register
│ │ ├── dashboard/ # Main dashboard
│ │ ├── projects/ # Project management
│ │ ├── assets/ # Asset library
│ │ ├── generation/ # AI generation UI
│ │ ├── campaigns/ # Marketing campaigns
│ │ └── analytics/ # Analytics dashboard
│ ├── shared/ # Shared components
│ │ ├── components/ # UI components
│ │ ├── hooks/ # Custom hooks
│ │ └── utils/ # Utilities
│ └── lib/ # Libraries
├── database/ # Database
│ ├── schemas/ # Schema definitions
│ └── migrations/ # Database migrations
├── docs/ # Documentation
└── orchestration/ # Agent orchestration
```
## Database Schemas
### Core Schemas (6 schemas)
| Schema | Purpose | Key Tables |
|--------|---------|------------|
| **auth** | Authentication & users | users, sessions, oauth_accounts |
| **tenants** | Multi-tenant management | tenants, tenant_settings |
| **projects** | Marketing projects | projects, campaigns, schedules |
| **assets** | Digital asset management | assets, tags, collections |
| **generation** | AI generation | generation_jobs, templates, workflows |
| **analytics** | Metrics & reporting | events, conversions, performance |
## Data Flow Architecture
```
┌──────────────┐
│ Frontend │ (React SPA - Port 3110)
│ (Browser) │
└──────┬───────┘
│ HTTP/WebSocket
┌─────────────────────────────────────────────┐
│ Backend API (NestJS - Port 3111) │
│ ┌─────────────────────────────────────┐ │
│ │ Controllers (REST Endpoints) │ │
│ └────────┬────────────────────────────┘ │
│ ▼ │
│ ┌─────────────────────────────────────┐ │
│ │ Services (Business Logic) │ │
│ └────────┬──────────────┬─────────────┘ │
│ │ │ │
│ ▼ ▼ │
│ ┌──────────────┐ ┌──────────────┐ │
│ │ Repositories │ │ Bull Queue │ │
│ │ (TypeORM) │ │ (Redis) │ │
│ └──────┬───────┘ └──────┬───────┘ │
└─────────┼──────────────────┼────────────────┘
│ │
▼ ▼
┌─────────────────┐ ┌──────────────┐
│ PostgreSQL │ │ Redis │
│ (Database) │ │ (Cache) │
└─────────────────┘ └──────────────┘
┌──────────────────────────────────────────┐
│ AI Services (External) │
│ ┌──────────────┐ ┌──────────────┐ │
│ │ ComfyUI │ │ LLM API │ │
│ │ (Port 8188) │ │ (OpenAI) │ │
│ └──────────────┘ └──────────────┘ │
└──────────────────────────────────────────┘
┌──────────────┐
│ MinIO │ (S3-compatible storage)
│ (Port 9000) │
└──────────────┘
```
### AI Content Generation Flow
```
User requests content generation
Frontend → POST /api/generation/create
Backend validates request
Create generation_job (status: pending)
Add to Bull queue (async processing)
Worker picks up job
├─→ Text generation: Call LLM API (GPT-4, Claude)
│ ↓
│ Save to database
└─→ Image generation: Call ComfyUI API
Upload to MinIO
Save metadata to database
Update job status (completed/failed)
WebSocket notification to frontend
User sees generated content
```
## Key Design Decisions
### 1. NestJS Framework
**Decision:** Usar NestJS en lugar de Express.js básico.
**Rationale:**
- Arquitectura modular out-of-the-box
- Dependency injection incorporado
- TypeScript first-class support
- Decorators para routing y validation
- Integración nativa con TypeORM, Bull, WebSockets
**Trade-off:** Curva de aprendizaje mayor, pero mejor estructura para proyectos grandes
### 2. Bull Queue for Async Processing
**Decision:** Procesar generaciones de IA en background con Bull.
**Rationale:**
- Generaciones pueden tardar minutos (especialmente imágenes)
- No bloquear requests HTTP
- Retry automático si falla
- Priorización de jobs
- Dashboard de monitoreo
**Implementation:**
```typescript
// generation.processor.ts
@Processor('generation')
export class GenerationProcessor {
@Process('generate-image')
async handleImageGeneration(job: Job) {
const { prompt, settings } = job.data;
// Call ComfyUI
const result = await this.comfyUIService.generate(prompt, settings);
// Upload to MinIO
const url = await this.storageService.upload(result.image);
// Save to database
await this.generationRepository.update(job.data.id, {
status: 'completed',
resultUrl: url
});
}
}
```
### 3. MinIO for Object Storage
**Decision:** MinIO como almacenamiento S3-compatible en lugar de filesystem.
**Rationale:**
- Compatible con S3 (fácil migración a AWS S3 en producción)
- Versioning de assets
- Metadata y tags
- Pre-signed URLs para acceso controlado
- Replicación y backup
### 4. ComfyUI Integration
**Decision:** Integrar ComfyUI para generación de imágenes AI.
**Rationale:**
- Workflow visual poderoso
- Múltiples modelos (Stable Diffusion, FLUX, etc.)
- Control fino sobre generación
- Open-source y self-hosted
- API REST para integración
**Alternative:** Usar APIs directas (Replicate, Stability AI) - más simple pero menos flexible
### 5. Multi-Tenant Architecture
**Decision:** Soporte multi-tenant a nivel de aplicación.
**Rationale:**
- SaaS-ready desde el inicio
- Aislamiento de datos por tenant
- Diferentes planes y límites por tenant
- Escalable para múltiples clientes
**Implementation:** Similar a ERP-Suite (tenant_id en cada tabla, RLS opcional)
### 6. Repository Pattern with TypeORM
**Decision:** Usar Repository Pattern en lugar de Active Record.
**Rationale:**
- Mejor separación de concerns
- Facilita testing (mock repositories)
- Migrations automáticas (development)
- Type-safe queries
## Dependencies
### Critical Dependencies
| Dependency | Purpose | Criticality |
|------------|---------|-------------|
| **NestJS** | Backend framework | CRITICAL |
| **TypeORM** | ORM | CRITICAL |
| **PostgreSQL** | Database | CRITICAL |
| **Redis** | Cache, queues | HIGH |
| **Bull** | Job queues | HIGH |
| **MinIO** | Object storage | MEDIUM |
| **ComfyUI** | Image generation | MEDIUM |
### External Services
- **ComfyUI:** Image generation (local or cloud)
- **OpenAI/Claude:** Text generation
- **MinIO:** Object storage (S3-compatible)
- **Redis:** Caching and job queues
## Security Considerations
- **Authentication:** JWT with refresh tokens
- **Authorization:** Role-based (admin, user, viewer)
- **Multi-tenancy:** tenant_id isolation
- **File Upload:** Validation (type, size, malware scan)
- **API Rate Limiting:** Per tenant
- **CORS:** Configured for frontend origin
- **Input Validation:** Class-validator on DTOs
- **SQL Injection:** TypeORM parameterized queries
## Performance Optimizations
### Caching Strategy
- **Redis:** Cache generation results, frequently accessed assets
- **TTL:** Configurable per resource type
- **Invalidation:** Event-based
### Database
- Indexes on frequently queried columns
- Connection pooling
- Pagination on all list endpoints
- Lazy loading of relations
### Asset Delivery
- CDN for static assets (future)
- Image optimization (resize, compress)
- Pre-signed URLs with expiration
## Deployment Strategy
**Current:** Development environment
**Ports:**
- Frontend: 3110
- Backend: 3111
- MinIO API: 9000
- MinIO Console: 9001
- ComfyUI: 8188
**Future Production:**
- Docker containers
- Kubernetes orchestration
- AWS S3 for storage
- CloudFront CDN
- Managed PostgreSQL (RDS)
- Managed Redis (ElastiCache)
## Monitoring & Observability
**Planned:**
- NestJS Logger
- Error tracking (Sentry)
- Performance monitoring (Datadog/New Relic)
- Bull Board for queue monitoring
- Database monitoring
## Feature Modules
### Auth Module
- JWT authentication
- OAuth2 (Google, GitHub)
- Password reset
- Email verification
- Role-based access control
### Tenants Module
- Tenant management
- Settings & configuration
- Usage tracking
- Plan limits enforcement
### Projects Module
- Marketing projects
- Campaigns
- Schedules
- Team collaboration
### Assets Module
- Digital asset library
- Tags and collections
- Search and filtering
- Version control
- Sharing and permissions
### Generation Module
- AI text generation (GPT-4, Claude)
- AI image generation (ComfyUI)
- Template management
- Workflow automation
- Generation history
### Automation Module
- Scheduled generation
- Batch operations
- Webhooks
- API integrations
### CRM Module
- Contact management
- Segment creation
- Campaign targeting
- Email integration
### Analytics Module
- Performance metrics
- Conversion tracking
- Custom reports
- Dashboards
## Integration Points
### ComfyUI
**API Endpoints:**
- POST `/prompt` - Submit generation job
- GET `/history` - Get job status
- GET `/view` - Retrieve generated image
**Workflow:**
1. Build workflow JSON
2. Submit to ComfyUI
3. Poll for completion
4. Download result
5. Upload to MinIO
### LLM APIs
**OpenAI:**
```typescript
const completion = await openai.chat.completions.create({
model: 'gpt-4',
messages: [
{ role: 'system', content: 'You are a marketing content writer' },
{ role: 'user', content: prompt }
]
});
```
**Claude:**
```typescript
const message = await anthropic.messages.create({
model: 'claude-3-opus-20240229',
max_tokens: 1024,
messages: [{ role: 'user', content: prompt }]
});
```
### MinIO
```typescript
// Upload file
await minioClient.putObject(
'pmc-assets',
fileName,
fileBuffer,
fileSize,
{ 'Content-Type': mimeType }
);
// Get pre-signed URL
const url = await minioClient.presignedGetObject(
'pmc-assets',
fileName,
24 * 60 * 60 // 24 hours
);
```
## Future Improvements
### Short-term
- [ ] Implement real-time collaboration
- [ ] Add more AI models
- [ ] Improve asset search (full-text)
- [ ] Mobile responsive UI
### Medium-term
- [ ] Video generation support
- [ ] Social media scheduling
- [ ] A/B testing for content
- [ ] Brand kit management
### Long-term
- [ ] Marketplace for templates
- [ ] White-label solution
- [ ] Multi-language support
- [ ] Advanced analytics & ML insights
## References
- [CMS Guide](./CMS-GUIDE.md)
- [API Documentation](./API.md)
- [Contributing Guide](../CONTRIBUTING.md)
- [NestJS Documentation](https://nestjs.com/)
- [ComfyUI API](https://github.com/comfyanonymous/ComfyUI)
---
id: "ARCHITECTURE"
title: "Architecture"
type: "Documentation"
project: "platform_marketing_content"
version: "1.0.0"
updated_date: "2026-01-04"
---
# Architecture
## Overview
**Platform Marketing Content (PMC)** es una plataforma de generación y gestión de contenido de marketing asistida por inteligencia artificial. Integra ComfyUI para generación de imágenes AI y modelos LLM para contenido textual, ofreciendo un CMS completo para equipos de marketing.
La arquitectura sigue un patrón de aplicación web full-stack con NestJS en backend y React en frontend, con integraciones a servicios de IA para automatización de contenido.
## Tech Stack
- **Backend:** NestJS 10+ + TypeScript 5.3+
- **Frontend:** React + TypeScript + Tailwind CSS + Vite
- **Database:** PostgreSQL 16 (pmc_dev)
- **Cache:** Redis 7
- **Storage:** MinIO (S3-compatible)
- **AI Art:** ComfyUI (Stable Diffusion, FLUX)
- **LLM:** Integration with OpenAI, Claude, local models
- **Auth:** JWT + Passport.js
- **Real-time:** Socket.IO (Bull queues for async jobs)
## Module Structure
```
platform_marketing_content/
├── apps/
│ ├── backend/ # NestJS API
│ │ └── src/
│ │ ├── modules/ # Feature modules
│ │ │ ├── auth/ # Authentication (JWT, local, OAuth)
│ │ │ ├── tenants/ # Multi-tenant management
│ │ │ ├── projects/ # Marketing projects
│ │ │ ├── assets/ # Digital assets (images, videos)
│ │ │ ├── generation/ # AI content generation
│ │ │ ├── automation/ # Workflow automation
│ │ │ ├── crm/ # CRM integration
│ │ │ └── analytics/ # Analytics & reporting
│ │ ├── common/ # Shared code
│ │ │ ├── decorators/ # Custom decorators
│ │ │ ├── filters/ # Exception filters
│ │ │ ├── guards/ # Auth guards
│ │ │ ├── interceptors/ # HTTP interceptors
│ │ │ └── pipes/ # Validation pipes
│ │ ├── config/ # Configuration
│ │ ├── app.module.ts # Root module
│ │ └── main.ts # Bootstrap
│ │
│ └── frontend/ # React SPA
│ └── src/
│ ├── modules/ # Feature modules
│ │ ├── auth/ # Login, register
│ │ ├── dashboard/ # Main dashboard
│ │ ├── projects/ # Project management
│ │ ├── assets/ # Asset library
│ │ ├── generation/ # AI generation UI
│ │ ├── campaigns/ # Marketing campaigns
│ │ └── analytics/ # Analytics dashboard
│ ├── shared/ # Shared components
│ │ ├── components/ # UI components
│ │ ├── hooks/ # Custom hooks
│ │ └── utils/ # Utilities
│ └── lib/ # Libraries
├── database/ # Database
│ ├── schemas/ # Schema definitions
│ └── migrations/ # Database migrations
├── docs/ # Documentation
└── orchestration/ # Agent orchestration
```
## Database Schemas
### Core Schemas (6 schemas)
| Schema | Purpose | Key Tables |
|--------|---------|------------|
| **auth** | Authentication & users | users, sessions, oauth_accounts |
| **tenants** | Multi-tenant management | tenants, tenant_settings |
| **projects** | Marketing projects | projects, campaigns, schedules |
| **assets** | Digital asset management | assets, tags, collections |
| **generation** | AI generation | generation_jobs, templates, workflows |
| **analytics** | Metrics & reporting | events, conversions, performance |
## Data Flow Architecture
```
┌──────────────┐
│ Frontend │ (React SPA - Port 3110)
│ (Browser) │
└──────┬───────┘
│ HTTP/WebSocket
┌─────────────────────────────────────────────┐
│ Backend API (NestJS - Port 3111) │
│ ┌─────────────────────────────────────┐ │
│ │ Controllers (REST Endpoints) │ │
│ └────────┬────────────────────────────┘ │
│ ▼ │
│ ┌─────────────────────────────────────┐ │
│ │ Services (Business Logic) │ │
│ └────────┬──────────────┬─────────────┘ │
│ │ │ │
│ ▼ ▼ │
│ ┌──────────────┐ ┌──────────────┐ │
│ │ Repositories │ │ Bull Queue │ │
│ │ (TypeORM) │ │ (Redis) │ │
│ └──────┬───────┘ └──────┬───────┘ │
└─────────┼──────────────────┼────────────────┘
│ │
▼ ▼
┌─────────────────┐ ┌──────────────┐
│ PostgreSQL │ │ Redis │
│ (Database) │ │ (Cache) │
└─────────────────┘ └──────────────┘
┌──────────────────────────────────────────┐
│ AI Services (External) │
│ ┌──────────────┐ ┌──────────────┐ │
│ │ ComfyUI │ │ LLM API │ │
│ │ (Port 8188) │ │ (OpenAI) │ │
│ └──────────────┘ └──────────────┘ │
└──────────────────────────────────────────┘
┌──────────────┐
│ MinIO │ (S3-compatible storage)
│ (Port 9000) │
└──────────────┘
```
### AI Content Generation Flow
```
User requests content generation
Frontend → POST /api/generation/create
Backend validates request
Create generation_job (status: pending)
Add to Bull queue (async processing)
Worker picks up job
├─→ Text generation: Call LLM API (GPT-4, Claude)
│ ↓
│ Save to database
└─→ Image generation: Call ComfyUI API
Upload to MinIO
Save metadata to database
Update job status (completed/failed)
WebSocket notification to frontend
User sees generated content
```
## Key Design Decisions
### 1. NestJS Framework
**Decision:** Usar NestJS en lugar de Express.js básico.
**Rationale:**
- Arquitectura modular out-of-the-box
- Dependency injection incorporado
- TypeScript first-class support
- Decorators para routing y validation
- Integración nativa con TypeORM, Bull, WebSockets
**Trade-off:** Curva de aprendizaje mayor, pero mejor estructura para proyectos grandes
### 2. Bull Queue for Async Processing
**Decision:** Procesar generaciones de IA en background con Bull.
**Rationale:**
- Generaciones pueden tardar minutos (especialmente imágenes)
- No bloquear requests HTTP
- Retry automático si falla
- Priorización de jobs
- Dashboard de monitoreo
**Implementation:**
```typescript
// generation.processor.ts
@Processor('generation')
export class GenerationProcessor {
@Process('generate-image')
async handleImageGeneration(job: Job) {
const { prompt, settings } = job.data;
// Call ComfyUI
const result = await this.comfyUIService.generate(prompt, settings);
// Upload to MinIO
const url = await this.storageService.upload(result.image);
// Save to database
await this.generationRepository.update(job.data.id, {
status: 'completed',
resultUrl: url
});
}
}
```
### 3. MinIO for Object Storage
**Decision:** MinIO como almacenamiento S3-compatible en lugar de filesystem.
**Rationale:**
- Compatible con S3 (fácil migración a AWS S3 en producción)
- Versioning de assets
- Metadata y tags
- Pre-signed URLs para acceso controlado
- Replicación y backup
### 4. ComfyUI Integration
**Decision:** Integrar ComfyUI para generación de imágenes AI.
**Rationale:**
- Workflow visual poderoso
- Múltiples modelos (Stable Diffusion, FLUX, etc.)
- Control fino sobre generación
- Open-source y self-hosted
- API REST para integración
**Alternative:** Usar APIs directas (Replicate, Stability AI) - más simple pero menos flexible
### 5. Multi-Tenant Architecture
**Decision:** Soporte multi-tenant a nivel de aplicación.
**Rationale:**
- SaaS-ready desde el inicio
- Aislamiento de datos por tenant
- Diferentes planes y límites por tenant
- Escalable para múltiples clientes
**Implementation:** Similar a ERP-Suite (tenant_id en cada tabla, RLS opcional)
### 6. Repository Pattern with TypeORM
**Decision:** Usar Repository Pattern en lugar de Active Record.
**Rationale:**
- Mejor separación de concerns
- Facilita testing (mock repositories)
- Migrations automáticas (development)
- Type-safe queries
## Dependencies
### Critical Dependencies
| Dependency | Purpose | Criticality |
|------------|---------|-------------|
| **NestJS** | Backend framework | CRITICAL |
| **TypeORM** | ORM | CRITICAL |
| **PostgreSQL** | Database | CRITICAL |
| **Redis** | Cache, queues | HIGH |
| **Bull** | Job queues | HIGH |
| **MinIO** | Object storage | MEDIUM |
| **ComfyUI** | Image generation | MEDIUM |
### External Services
- **ComfyUI:** Image generation (local or cloud)
- **OpenAI/Claude:** Text generation
- **MinIO:** Object storage (S3-compatible)
- **Redis:** Caching and job queues
## Security Considerations
- **Authentication:** JWT with refresh tokens
- **Authorization:** Role-based (admin, user, viewer)
- **Multi-tenancy:** tenant_id isolation
- **File Upload:** Validation (type, size, malware scan)
- **API Rate Limiting:** Per tenant
- **CORS:** Configured for frontend origin
- **Input Validation:** Class-validator on DTOs
- **SQL Injection:** TypeORM parameterized queries
## Performance Optimizations
### Caching Strategy
- **Redis:** Cache generation results, frequently accessed assets
- **TTL:** Configurable per resource type
- **Invalidation:** Event-based
### Database
- Indexes on frequently queried columns
- Connection pooling
- Pagination on all list endpoints
- Lazy loading of relations
### Asset Delivery
- CDN for static assets (future)
- Image optimization (resize, compress)
- Pre-signed URLs with expiration
## Deployment Strategy
**Current:** Development environment
**Ports:**
- Frontend: 3110
- Backend: 3111
- MinIO API: 9000
- MinIO Console: 9001
- ComfyUI: 8188
**Future Production:**
- Docker containers
- Kubernetes orchestration
- AWS S3 for storage
- CloudFront CDN
- Managed PostgreSQL (RDS)
- Managed Redis (ElastiCache)
## Monitoring & Observability
**Planned:**
- NestJS Logger
- Error tracking (Sentry)
- Performance monitoring (Datadog/New Relic)
- Bull Board for queue monitoring
- Database monitoring
## Feature Modules
### Auth Module
- JWT authentication
- OAuth2 (Google, GitHub)
- Password reset
- Email verification
- Role-based access control
### Tenants Module
- Tenant management
- Settings & configuration
- Usage tracking
- Plan limits enforcement
### Projects Module
- Marketing projects
- Campaigns
- Schedules
- Team collaboration
### Assets Module
- Digital asset library
- Tags and collections
- Search and filtering
- Version control
- Sharing and permissions
### Generation Module
- AI text generation (GPT-4, Claude)
- AI image generation (ComfyUI)
- Template management
- Workflow automation
- Generation history
### Automation Module
- Scheduled generation
- Batch operations
- Webhooks
- API integrations
### CRM Module
- Contact management
- Segment creation
- Campaign targeting
- Email integration
### Analytics Module
- Performance metrics
- Conversion tracking
- Custom reports
- Dashboards
## Integration Points
### ComfyUI
**API Endpoints:**
- POST `/prompt` - Submit generation job
- GET `/history` - Get job status
- GET `/view` - Retrieve generated image
**Workflow:**
1. Build workflow JSON
2. Submit to ComfyUI
3. Poll for completion
4. Download result
5. Upload to MinIO
### LLM APIs
**OpenAI:**
```typescript
const completion = await openai.chat.completions.create({
model: 'gpt-4',
messages: [
{ role: 'system', content: 'You are a marketing content writer' },
{ role: 'user', content: prompt }
]
});
```
**Claude:**
```typescript
const message = await anthropic.messages.create({
model: 'claude-3-opus-20240229',
max_tokens: 1024,
messages: [{ role: 'user', content: prompt }]
});
```
### MinIO
```typescript
// Upload file
await minioClient.putObject(
'pmc-assets',
fileName,
fileBuffer,
fileSize,
{ 'Content-Type': mimeType }
);
// Get pre-signed URL
const url = await minioClient.presignedGetObject(
'pmc-assets',
fileName,
24 * 60 * 60 // 24 hours
);
```
## Future Improvements
### Short-term
- [ ] Implement real-time collaboration
- [ ] Add more AI models
- [ ] Improve asset search (full-text)
- [ ] Mobile responsive UI
### Medium-term
- [ ] Video generation support
- [ ] Social media scheduling
- [ ] A/B testing for content
- [ ] Brand kit management
### Long-term
- [ ] Marketplace for templates
- [ ] White-label solution
- [ ] Multi-language support
- [ ] Advanced analytics & ML insights
## References
- [CMS Guide](./CMS-GUIDE.md)
- [API Documentation](./API.md)
- [Contributing Guide](../CONTRIBUTING.md)
- [NestJS Documentation](https://nestjs.com/)
- [ComfyUI API](https://github.com/comfyanonymous/ComfyUI)

File diff suppressed because it is too large Load Diff

View File

@ -1,8 +1,18 @@
# Mapa de Documentacion: platform_marketing_content
---
id: "_MAP"
title: "Mapa de Documentacion: Platform Marketing Content"
type: "Index"
status: "Draft"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# Mapa de Documentacion: Platform Marketing Content
**Proyecto:** platform_marketing_content
**Actualizado:** 2026-01-04
**Generado por:** EPIC-008 adapt-simco.sh
**Sistema:** NEXUS v3.4 + SIMCO + Estandar SCRUM para Agentes IA
---
@ -10,31 +20,194 @@
```
docs/
├── _MAP.md # Este archivo (indice de navegacion)
├── 00-overview/ # Vision general del proyecto
├── 01-architecture/ # Arquitectura y decisiones (ADRs)
├── 02-specs/ # Especificaciones tecnicas
├── 03-api/ # Documentacion de APIs
├── 04-guides/ # Guias de desarrollo
└── 99-finiquito/ # Entregables cliente (si aplica)
├── _MAP.md # Este archivo (indice de navegacion)
├── ARCHITECTURE.md # Arquitectura general
├── CMS-GUIDE.md # Guia CMS
├── 00-vision-general/ # Vision, glosario, arquitectura
│ ├── _MAP.md
│ ├── VISION-GENERAL.md
│ ├── ARQUITECTURA-TECNICA.md
│ ├── GLOSARIO.md
│ └── MVP_Plataforma_SaaS_Contenido_CRM.md
├── 01-analisis-referencias/ # Analisis de proyectos referencia
│ ├── _INDEX.md
│ ├── ANALISIS-PROYECTOS-REFERENCIA.md
│ └── ANALISIS-CATALOGO.md
├── 02-definicion-modulos/ # Definicion de modulos del sistema
│ ├── _INDEX.md
│ ├── PMC-001-TENANTS.md
│ ├── PMC-002-CRM.md
│ ├── PMC-003-PROJECTS.md
│ ├── PMC-004-GENERATION.md
│ ├── PMC-005-AUTOMATION.md
│ ├── PMC-006-ASSETS.md
│ ├── PMC-007-ADMIN.md
│ └── PMC-008-ANALYTICS.md
├── 03-requerimientos/ # Requerimientos Funcionales
│ ├── _INDEX.md
│ ├── RF-PMC-001-TENANTS.md
│ ├── RF-PMC-002-CRM.md
│ ├── RF-PMC-003-PROJECTS.md
│ ├── RF-PMC-004-GENERATION.md
│ ├── RF-PMC-005-AUTOMATION.md
│ ├── RF-PMC-006-ASSETS.md
│ ├── RF-PMC-007-ADMIN.md
│ └── RF-PMC-008-ANALYTICS.md
├── 04-modelado/ # Modelado de datos
│ ├── ESQUEMA-BD.md
│ └── MODELO-DOMINIO.md
├── 04-fase-backlog/ # Backlog y definiciones SCRUM
│ ├── README.md
│ ├── DEFINITION-OF-READY.md
│ └── DEFINITION-OF-DONE.md
├── 05-user-stories/ # EPICs y User Stories
│ ├── _INDEX.md
│ ├── EPIC-001-SETUP.md # Setup y Autenticacion
│ ├── EPIC-002-CRM.md # Gestion de CRM
│ ├── EPIC-003-PROJECTS.md # Proyectos y Campanas
│ ├── EPIC-004-GENERATION.md # Generacion de Contenido
│ ├── EPIC-005-ASSETS.md # Biblioteca de Assets (DAM)
│ ├── EPIC-006-AUTOMATION.md # Automatizacion
│ ├── EPIC-007-ANALYTICS.md # Analytics
│ └── EPIC-008-ADMIN.md # Administracion
├── 90-transversal/ # Documentacion transversal
│ ├── README.md
│ ├── roadmap/
│ │ └── ROADMAP-PMC.md
│ └── reportes-implementacion/
│ └── AUDITORIA-DOCUMENTACION-PMC.md
├── 95-guias-desarrollo/ # Guias para desarrolladores
│ ├── GUIA-SETUP.md
│ └── GUIA-CONVENCIONES.md
├── 96-quick-reference/ # Cheatsheets (pendiente)
├── 97-adr/ # Architecture Decision Records
│ ├── _INDEX.md
│ ├── ADR-001-stack-tecnologico.md
│ ├── ADR-002-multi-tenancy.md
│ ├── ADR-003-motor-generacion.md
│ └── ADR-004-cola-tareas.md
├── archivados/ # Documentacion deprecada
└── planning/ # Planificacion SCRUM
├── Board.md # Tablero Kanban
├── config.yml # Configuracion del proyecto
├── tasks/ # Tareas activas
└── bugs/ # Bugs activos
```
## Navegacion Rapida
| Seccion | Descripcion | Estado |
|---------|-------------|--------|
| Overview | Vision general | - |
| Architecture | Decisiones arquitectonicas | - |
| Specs | Especificaciones tecnicas | - |
| API | Documentacion de endpoints | - |
| Guides | Guias de desarrollo | - |
## Estadisticas
- Total archivos en docs/: 50
- Fecha de adaptacion: 2026-01-04
---
**Nota:** Este archivo fue generado automaticamente por EPIC-008.
Actualizar manualmente con la estructura real del proyecto.
## Navegacion Rapida
### Documentacion Principal
| Seccion | Descripcion | Estado | Archivos |
|---------|-------------|--------|----------|
| [00-vision-general/](./00-vision-general/) | Vision y arquitectura | Completo | 5 |
| [01-analisis-referencias/](./01-analisis-referencias/) | Analisis de referencia | Completo | 3 |
| [02-definicion-modulos/](./02-definicion-modulos/) | Definicion de modulos | Completo | 9 |
| [03-requerimientos/](./03-requerimientos/) | Requerimientos funcionales | Completo | 9 |
| [04-modelado/](./04-modelado/) | Modelado de datos | Completo | 2 |
| [05-user-stories/](./05-user-stories/) | EPICs y User Stories | Completo | 9 |
### Documentacion Transversal
| Seccion | Descripcion | Estado | Archivos |
|---------|-------------|--------|----------|
| [90-transversal/](./90-transversal/) | Documentacion transversal | Completo | 3 |
| [95-guias-desarrollo/](./95-guias-desarrollo/) | Guias de desarrollo | Completo | 2 |
| [96-quick-reference/](./96-quick-reference/) | Cheatsheets | Pendiente | 0 |
| [97-adr/](./97-adr/) | Decision Records | Completo | 5 |
### Infraestructura SCRUM
| Seccion | Descripcion | Estado | Archivos |
|---------|-------------|--------|----------|
| [04-fase-backlog/](./04-fase-backlog/) | Backlog y DoR/DoD | Completo | 3 |
| [planning/](./planning/) | Planificacion activa | Completo | 2 |
---
## EPICs del Proyecto
| ID | Titulo | Fase | SP | US | Estado |
|----|--------|------|-----|-----|--------|
| [EPIC-001](./05-user-stories/EPIC-001-SETUP.md) | Setup y Autenticacion | 1 | 40 | 8 | Done |
| [EPIC-002](./05-user-stories/EPIC-002-CRM.md) | Gestion de CRM | 1 | 60 | 12 | Done |
| [EPIC-003](./05-user-stories/EPIC-003-PROJECTS.md) | Proyectos y Campanas | 1 | 50 | 10 | Done |
| [EPIC-004](./05-user-stories/EPIC-004-GENERATION.md) | Generacion de Contenido | 1 | 75 | 15 | Done |
| [EPIC-005](./05-user-stories/EPIC-005-ASSETS.md) | Biblioteca de Assets (DAM) | 1 | 50 | 10 | Done |
| [EPIC-006](./05-user-stories/EPIC-006-AUTOMATION.md) | Automatizacion | 2 | 30 | 6 | Done |
| [EPIC-007](./05-user-stories/EPIC-007-ANALYTICS.md) | Analytics | 3 | 25 | 5 | Done |
| [EPIC-008](./05-user-stories/EPIC-008-ADMIN.md) | Administracion | 1 | 55 | 11 | Done |
**Total Story Points:** 385 SP
**Total User Stories:** 77 US
---
## Requerimientos Funcionales
| ID | Modulo | Prioridad | RFs | Estado |
|----|--------|-----------|-----|--------|
| [RF-PMC-001](./03-requerimientos/RF-PMC-001-TENANTS.md) | Tenants | Alta | 15 | Done |
| [RF-PMC-002](./03-requerimientos/RF-PMC-002-CRM.md) | CRM | Alta | 20 | Done |
| [RF-PMC-003](./03-requerimientos/RF-PMC-003-PROJECTS.md) | Projects | Alta | 15 | Done |
| [RF-PMC-004](./03-requerimientos/RF-PMC-004-GENERATION.md) | Generation | Alta | 18 | Done |
| [RF-PMC-005](./03-requerimientos/RF-PMC-005-AUTOMATION.md) | Automation | Media | 10 | Done |
| [RF-PMC-006](./03-requerimientos/RF-PMC-006-ASSETS.md) | Assets | Alta | 12 | Done |
| [RF-PMC-007](./03-requerimientos/RF-PMC-007-ADMIN.md) | Admin | Alta | 10 | Done |
| [RF-PMC-008](./03-requerimientos/RF-PMC-008-ANALYTICS.md) | Analytics | Media | 8 | Done |
**Total RFs:** 108
---
## Architecture Decision Records
| ID | Titulo | Estado | Fecha |
|----|--------|--------|-------|
| [ADR-001](./97-adr/ADR-001-stack-tecnologico.md) | Stack Tecnologico | Accepted | 2025-12-08 |
| [ADR-002](./97-adr/ADR-002-multi-tenancy.md) | Multi-Tenancy | Accepted | 2025-12-08 |
| [ADR-003](./97-adr/ADR-003-motor-generacion.md) | Motor de Generacion | Accepted | 2025-12-08 |
| [ADR-004](./97-adr/ADR-004-cola-tareas.md) | Cola de Tareas | Accepted | 2025-12-08 |
---
## Estadisticas
| Metrica | Valor |
|---------|-------|
| Total archivos en docs/ | 55+ |
| EPICs documentadas | 8 |
| User Stories | 77 |
| Requerimientos Funcionales | 108 |
| ADRs | 4 |
| Fecha de estandarizacion | 2026-01-04 |
---
## Referencias
- **AGENTS.md:** [/AGENTS.md](../AGENTS.md) - Guia para agentes IA
- **Board.md:** [/docs/planning/Board.md](./planning/Board.md) - Tablero Kanban
- **config.yml:** [/docs/planning/config.yml](./planning/config.yml) - Configuracion
- **Orchestration:** [/orchestration/](../orchestration/) - Sistema de orquestacion
---
**Generado:** 2026-01-04
**Mantenido por:** Architecture Team
**Sistema:** NEXUS v3.4 + SIMCO

132
docs/planning/Board.md Normal file
View File

@ -0,0 +1,132 @@
---
id: "BOARD"
title: "Tablero Kanban - Platform Marketing Content"
type: "Planning"
status: "Draft"
project: "platform_marketing_content"
version: "1.0.0"
created_date: "2026-01-04"
updated_date: "2026-01-04"
---
# Tablero Kanban - Platform Marketing Content
**Sprint Actual:** Sprint 1 (MVP Core)
**Ultima actualizacion:** 2026-01-04
**Velocity Objetivo:** 40 SP
---
## Resumen del Sprint
| Metrica | Valor |
|---------|-------|
| Story Points Planificados | 40 |
| Story Points Completados | 0 |
| Tareas Pendientes | 0 |
| Tareas En Progreso | 0 |
| Tareas Completadas | 0 |
| Bugs Abiertos | 0 |
---
## Backlog
Items pendientes de planificacion para futuros sprints.
| ID | Titulo | Tipo | SP | Prioridad |
|----|--------|------|-----|-----------|
| - | Ver `/docs/04-fase-backlog/` | - | - | - |
---
## Por Hacer (To Do)
Items planificados para el sprint actual, pendientes de iniciar.
| ID | Titulo | Asignado | SP | Prioridad | Epic |
|----|--------|----------|-----|-----------|------|
| - | - | - | - | - | - |
---
## En Progreso (In Progress)
Items actualmente en desarrollo.
| ID | Titulo | Asignado | SP | Inicio | Epic |
|----|--------|----------|-----|--------|------|
| - | - | - | - | - | - |
---
## Bloqueado (Blocked)
Items bloqueados esperando dependencias o decision.
| ID | Titulo | Asignado | Bloqueado Por | Desde |
|----|--------|----------|---------------|-------|
| - | - | - | - | - |
---
## En Revision (Review)
Items completados pendientes de validacion.
| ID | Titulo | Asignado | Revisor | SP |
|----|--------|----------|---------|-----|
| - | - | - | - | - |
---
## Hecho (Done)
Items completados y validados en este sprint.
| ID | Titulo | Completado Por | SP | Fecha |
|----|--------|----------------|-----|-------|
| TASK-RDOC-002 | Reestructuracion Documentacion | @Claude | 5 | 2026-01-04 |
---
## Bugs Abiertos
| ID | Titulo | Severidad | Modulo | Asignado |
|----|--------|-----------|--------|----------|
| - | - | - | - | - |
*Ver detalle completo en `/orchestration/trazas/TRAZA-BUGS.md`*
---
## Notas del Sprint
- **2026-01-04:** Estandarizacion SCRUM iniciada
- Creado AGENTS.md (guia de agentes)
- Creado config.yml (configuracion del proyecto)
- Creado Board.md (tablero Kanban)
- Agregado YAML front-matter a EPICs
- Agregado YAML front-matter a RFs
- Agregado YAML front-matter a ADRs
---
## Historico de Sprints
| Sprint | Fechas | Velocity | Completado |
|--------|--------|----------|------------|
| Sprint 1 | 2026-01-04 - | 40 SP objetivo | En progreso |
---
## Referencias
- **Backlog completo:** `/docs/04-fase-backlog/README.md`
- **Configuracion:** `/docs/planning/config.yml`
- **Guia de agentes:** `/AGENTS.md`
- **Roadmap:** `/docs/90-transversal/roadmap/ROADMAP-PMC.md`
---
**Mantenido por:** Scrum Master / Architecture Team
**Actualizacion:** Al cambiar estado de cualquier item

204
docs/planning/config.yml Normal file
View File

@ -0,0 +1,204 @@
# Configuracion del Sistema de Planificacion Platform Marketing Content
# Basado en: Estandar-SCRUM.md (Principio SIMCO)
# Version: 1.0
# Fecha: 2026-01-04
project:
name: "Platform Marketing Content"
description: "Plataforma SaaS de generacion de contenido y CRM creativo"
version: "1.0.0"
repository: "platform_marketing_content"
# Estados validos para elementos de trabajo
states:
user_story:
- "Backlog"
- "To Do"
- "In Progress"
- "In Review"
- "Done"
task:
- "To Do"
- "In Progress"
- "Blocked"
- "Done"
bug:
- "Open"
- "In Progress"
- "Fixed"
- "Done"
- "Won't Fix"
adr:
- "Proposed"
- "Accepted"
- "Deprecated"
- "Superseded"
# Prioridades
priorities:
- id: "P0"
name: "Critico"
description: "Bloqueante para produccion o seguridad"
sla_hours: 4
- id: "P1"
name: "Alto"
description: "Funcionalidad core, deadline cercano"
sla_hours: 24
- id: "P2"
name: "Medio"
description: "Mejoras importantes, puede esperar"
sla_hours: 72
- id: "P3"
name: "Bajo"
description: "Nice-to-have, mejoras menores"
sla_hours: null
# Prefijos de nomenclatura
naming:
epic: "EPIC"
user_story: "US"
task: "TASK"
bug: "BUG"
requirement: "RF-PMC"
module: "PMC"
adr: "ADR"
# Modulos del proyecto
modules:
- prefix: "PMC-001"
name: "TENANTS"
epic: "EPIC-001"
description: "Multi-tenancy y planes"
- prefix: "PMC-002"
name: "CRM"
epic: "EPIC-002"
description: "Clientes, marcas, productos"
- prefix: "PMC-003"
name: "PROJECTS"
epic: "EPIC-003"
description: "Proyectos y campanas"
- prefix: "PMC-004"
name: "GENERATION"
epic: "EPIC-004"
description: "Motor IA de generacion"
- prefix: "PMC-005"
name: "AUTOMATION"
epic: "EPIC-006"
description: "Flujos n8n"
- prefix: "PMC-006"
name: "ASSETS"
epic: "EPIC-005"
description: "Biblioteca DAM"
- prefix: "PMC-007"
name: "ADMIN"
epic: "EPIC-008"
description: "Administracion"
- prefix: "PMC-008"
name: "ANALYTICS"
epic: "EPIC-007"
description: "Dashboards y reportes"
# Configuracion de sprints
sprint:
duration_days: 10
velocity_target: 40
current_sprint: 1
current_phase: 1
# Agentes disponibles
agents:
- id: "@Backend-Agent"
specialization: "NestJS, TypeORM, APIs"
- id: "@Frontend-Agent"
specialization: "React, TypeScript, UI/UX"
- id: "@Database-Agent"
specialization: "PostgreSQL, Migrations, Seeds"
- id: "@Generation-Agent"
specialization: "ComfyUI, SDXL, LoRAs"
- id: "@DevOps-Agent"
specialization: "Docker, Kubernetes, Deployment"
# Columnas del tablero Kanban
kanban_columns:
- id: "backlog"
name: "Backlog"
description: "Items no planificados"
- id: "todo"
name: "Por Hacer"
description: "Planificado para sprint actual"
- id: "in_progress"
name: "En Progreso"
description: "Trabajo activo"
- id: "blocked"
name: "Bloqueado"
description: "Esperando dependencias"
- id: "review"
name: "En Revision"
description: "Pendiente de validacion"
- id: "done"
name: "Hecho"
description: "Completado y validado"
# Campos requeridos por tipo de documento
required_fields:
epic:
- "id"
- "title"
- "status"
- "phase"
user_story:
- "id"
- "title"
- "status"
- "epic"
- "priority"
task:
- "id"
- "title"
- "status"
- "priority"
bug:
- "id"
- "title"
- "status"
- "severity"
- "affected_module"
requirement:
- "id"
- "title"
- "status"
- "module"
adr:
- "id"
- "title"
- "status"
- "date"
# Rutas importantes
paths:
planning: "/docs/planning/"
tasks: "/docs/planning/tasks/"
bugs: "/docs/planning/bugs/"
board: "/docs/planning/Board.md"
backlog: "/docs/04-fase-backlog/"
epics: "/docs/05-user-stories/"
requirements: "/docs/03-requerimientos/"
adr: "/docs/97-adr/"
trazas: "/orchestration/trazas/"
# Metricas del proyecto
metrics:
total_epics: 8
total_user_stories: 77
total_requirements: 8
total_adrs: 4
compliance_target: 100
current_compliance: 100
# Configuracion de validacion
validation:
require_yaml_frontmatter: true
require_acceptance_criteria: true
require_story_points: false
max_file_lines: 500
enforce_naming_convention: true

View File

@ -128,37 +128,37 @@ Funcionalidades reutilizables del catalogo:
```yaml
Requeridas:
- @CATALOG_AUTH:
path: core/catalog/auth/
path: shared/catalog/auth/
uso: Autenticacion JWT + OAuth
modulo: PMC-007
- @CATALOG_SESSION:
path: core/catalog/session-management/
path: shared/catalog/session-management/
uso: Gestion de sesiones
modulo: PMC-007
- @CATALOG_TENANT:
path: core/catalog/multi-tenancy/
path: shared/catalog/multi-tenancy/
uso: Multi-tenancy con RLS
modulo: PMC-001
- @CATALOG_NOTIFY:
path: core/catalog/notifications/
path: shared/catalog/notifications/
uso: Notificaciones email/push
modulo: PMC-005
- @CATALOG_RATELIMIT:
path: core/catalog/rate-limiting/
path: shared/catalog/rate-limiting/
uso: Limites de generacion
modulo: PMC-004
- @CATALOG_WS:
path: core/catalog/websocket/
path: shared/catalog/websocket/
uso: Progreso en tiempo real
modulo: PMC-004
Opcionales (Fase 4):
- @CATALOG_PAYMENTS:
path: core/catalog/payments/
path: shared/catalog/payments/
uso: Billing y suscripciones
modulo: PMC-001
- @CATALOG_FLAGS:
path: core/catalog/feature-flags/
path: shared/catalog/feature-flags/
uso: Feature toggles
modulo: PMC-007
```

View File

@ -75,14 +75,14 @@ PMC hereda y debe reutilizar los siguientes componentes del catalogo:
| Componente | Path | Modulo PMC | Uso |
|------------|------|------------|-----|
| @CATALOG_AUTH | core/catalog/auth/ | PMC-007 | Autenticacion JWT |
| @CATALOG_SESSION | core/catalog/session-management/ | PMC-007 | Gestion de sesiones |
| @CATALOG_TENANT | core/catalog/multi-tenancy/ | PMC-001 | Multi-tenancy RLS |
| @CATALOG_RATELIMIT | core/catalog/rate-limiting/ | PMC-004 | Limites de generacion |
| @CATALOG_NOTIFY | core/catalog/notifications/ | PMC-005 | Notificaciones |
| @CATALOG_WS | core/catalog/websocket/ | PMC-004 | WebSocket progreso |
| @CATALOG_PAYMENTS | core/catalog/payments/ | PMC-001 | Billing (Fase 4) |
| @CATALOG_FLAGS | core/catalog/feature-flags/ | PMC-007 | Feature toggles |
| @CATALOG_AUTH | shared/catalog/auth/ | PMC-007 | Autenticacion JWT |
| @CATALOG_SESSION | shared/catalog/session-management/ | PMC-007 | Gestion de sesiones |
| @CATALOG_TENANT | shared/catalog/multi-tenancy/ | PMC-001 | Multi-tenancy RLS |
| @CATALOG_RATELIMIT | shared/catalog/rate-limiting/ | PMC-004 | Limites de generacion |
| @CATALOG_NOTIFY | shared/catalog/notifications/ | PMC-005 | Notificaciones |
| @CATALOG_WS | shared/catalog/websocket/ | PMC-004 | WebSocket progreso |
| @CATALOG_PAYMENTS | shared/catalog/payments/ | PMC-001 | Billing (Fase 4) |
| @CATALOG_FLAGS | shared/catalog/feature-flags/ | PMC-007 | Feature toggles |
---
@ -190,12 +190,12 @@ Al crear/modificar funcionalidad, validar:
> **Nota:** Estos proyectos sirven como **inspiracion arquitectonica**, no como
> dependencias. Los patrones deben adaptarse a PMC y documentarse localmente.
> Para componentes reutilizables, usar siempre `core/catalog/`.
> Para componentes reutilizables, usar siempre `shared/catalog/`.
| Proyecto | Patrones de Inspiracion |
|----------|------------------------|
| Multi-tenancy | Ver `core/catalog/multi-tenancy/` |
| WebSocket/Colas | Ver `core/catalog/websocket/` |
| Multi-tenancy | Ver `shared/catalog/multi-tenancy/` |
| WebSocket/Colas | Ver `shared/catalog/websocket/` |
| Estructura modular | Ver `core/orchestration/templates/`|
---
@ -214,7 +214,7 @@ Actualizar cuando:
## Referencias
- SIMCO Quick Reference: `core/orchestration/directivas/simco/SIMCO-QUICK-REFERENCE.md`
- Catalogo Index: `core/catalog/CATALOG-INDEX.yml`
- Catalogo Index: `shared/catalog/CATALOG-INDEX.yml`
- Analisis Catalogo PMC: `docs/01-analisis-referencias/ANALISIS-CATALOGO.md`
---

View File

@ -0,0 +1,169 @@
# CONTEXT-MAP: PLATFORM_MARKETING_CONTENT
# Sistema: SIMCO - NEXUS v4.0
# Propósito: Mapear contexto automático por nivel y tarea
# Versión: 1.0.0
# Fecha: 2026-01-04
metadata:
proyecto: "platform_marketing_content"
nivel: "STANDALONE"
version: "1.0.0"
ultima_actualizacion: "2026-01-04"
workspace_root: "/home/isem/workspace-v1"
project_root: "/home/isem/workspace-v1/projects/platform_marketing_content"
# ═══════════════════════════════════════════════════════════════════════════════
# VARIABLES DEL PROYECTO (PRE-RESUELTAS)
# ═══════════════════════════════════════════════════════════════════════════════
variables:
# Identificación
PROJECT: "platform_marketing_content"
PROJECT_NAME: "PLATFORM-MARKETING-CONTENT"
PROJECT_LEVEL: "STANDALONE"
# Paths principales
APPS_ROOT: "/home/isem/workspace-v1/projects/platform_marketing_content/apps"
DATABASE_PATH: "/home/isem/workspace-v1/projects/platform_marketing_content/database"
DOCS_ROOT: "/home/isem/workspace-v1/projects/platform_marketing_content/docs"
ORCHESTRATION_PATH: "/home/isem/workspace-v1/projects/platform_marketing_content/orchestration"
# Backend
BACKEND_ROOT: "/home/isem/workspace-v1/projects/platform_marketing_content/backend"
# Frontend
FRONTEND_ROOT: "/home/isem/workspace-v1/projects/platform_marketing_content/frontend"
# ═══════════════════════════════════════════════════════════════════════════════
# ALIASES RESUELTOS
# ═══════════════════════════════════════════════════════════════════════════════
aliases:
# Directivas globales
"@SIMCO": "/home/isem/workspace-v1/orchestration/directivas/simco"
"@PRINCIPIOS": "/home/isem/workspace-v1/orchestration/directivas/principios"
"@PERFILES": "/home/isem/workspace-v1/orchestration/agents/perfiles"
"@CATALOG": "/home/isem/workspace-v1/shared/catalog"
# Proyecto específico
"@APPS": "/home/isem/workspace-v1/projects/platform_marketing_content/apps"
"@BACKEND": "/home/isem/workspace-v1/projects/platform_marketing_content/backend"
"@FRONTEND": "/home/isem/workspace-v1/projects/platform_marketing_content/frontend"
"@DATABASE": "/home/isem/workspace-v1/projects/platform_marketing_content/database"
"@DOCS": "/home/isem/workspace-v1/projects/platform_marketing_content/docs"
# Inventarios
"@INVENTORY": "/home/isem/workspace-v1/projects/platform_marketing_content/orchestration/inventarios"
# ═══════════════════════════════════════════════════════════════════════════════
# CONTEXTO POR NIVEL
# ═══════════════════════════════════════════════════════════════════════════════
contexto_por_nivel:
L0_sistema:
descripcion: "Principios fundamentales y perfil de agente"
tokens_estimados: 4500
obligatorio: true
archivos:
- path: "/home/isem/workspace-v1/orchestration/directivas/principios/PRINCIPIO-CAPVED.md"
proposito: "Ciclo de vida de tareas"
tokens: 800
- path: "/home/isem/workspace-v1/orchestration/directivas/principios/PRINCIPIO-DOC-PRIMERO.md"
proposito: "Documentación antes de código"
tokens: 500
- path: "/home/isem/workspace-v1/orchestration/directivas/principios/PRINCIPIO-ANTI-DUPLICACION.md"
proposito: "Verificar catálogo antes de crear"
tokens: 600
- path: "/home/isem/workspace-v1/orchestration/directivas/principios/PRINCIPIO-VALIDACION-OBLIGATORIA.md"
proposito: "Build/lint deben pasar"
tokens: 600
- path: "/home/isem/workspace-v1/orchestration/directivas/principios/PRINCIPIO-ECONOMIA-TOKENS.md"
proposito: "Límites de contexto"
tokens: 500
- path: "/home/isem/workspace-v1/orchestration/directivas/principios/PRINCIPIO-NO-ASUMIR.md"
proposito: "Preguntar si falta información"
tokens: 500
- path: "/home/isem/workspace-v1/orchestration/referencias/ALIASES.yml"
proposito: "Resolución de @ALIAS"
tokens: 400
L1_proyecto:
descripcion: "Contexto específico de PLATFORM_MARKETING_CONTENT"
tokens_estimados: 3000
obligatorio: true
archivos:
- path: "/home/isem/workspace-v1/projects/platform_marketing_content/orchestration/00-guidelines/CONTEXTO-PROYECTO.md"
proposito: "Variables y configuración del proyecto"
tokens: 1500
- path: "/home/isem/workspace-v1/projects/platform_marketing_content/orchestration/PROXIMA-ACCION.md"
proposito: "Estado actual y siguiente paso"
tokens: 500
L2_operacion:
descripcion: "SIMCO específicos según operación y dominio"
tokens_estimados: 2500
archivos_por_operacion:
CREAR:
- "/home/isem/workspace-v1/orchestration/directivas/simco/SIMCO-CREAR.md"
MODIFICAR:
- "/home/isem/workspace-v1/orchestration/directivas/simco/SIMCO-MODIFICAR.md"
VALIDAR:
- "/home/isem/workspace-v1/orchestration/directivas/simco/SIMCO-VALIDAR.md"
DELEGAR:
- "/home/isem/workspace-v1/orchestration/directivas/simco/SIMCO-DELEGACION.md"
L3_tarea:
descripcion: "Contexto específico de la tarea"
tokens_max: 8000
dinamico: true
# ═══════════════════════════════════════════════════════════════════════════════
# INFORMACIÓN ESPECÍFICA DEL PROYECTO
# ═══════════════════════════════════════════════════════════════════════════════
info_proyecto:
tipo: "Plataforma de Marketing y Contenido"
estado: "En desarrollo"
version: "1.0"
stack:
backend: "Backend API"
frontend: "Frontend Web"
database: "Base de datos"
# ═══════════════════════════════════════════════════════════════════════════════
# VALIDACIÓN DE TOKENS
# ═══════════════════════════════════════════════════════════════════════════════
validacion_tokens:
limite_absoluto: 25000
limite_seguro: 18000
limite_alerta: 20000
presupuesto:
L0_sistema: 4500
L1_proyecto: 3000
L2_operacion: 2500
L3_tarea_max: 8000
total_base: 10000
disponible_tarea: 8000
# ═══════════════════════════════════════════════════════════════════════════════
# HERENCIA
# ═══════════════════════════════════════════════════════════════════════════════
herencia:
tipo: "STANDALONE"
hereda_de:
- "/home/isem/workspace-v1/orchestration/"
# ═══════════════════════════════════════════════════════════════════════════════
# BÚSQUEDA DE HISTÓRICO
# ═══════════════════════════════════════════════════════════════════════════════
busqueda_historico:
habilitado: true
ubicaciones:
- "/home/isem/workspace-v1/projects/platform_marketing_content/orchestration/trazas/"
- "/home/isem/workspace-v1/orchestration/errores/REGISTRO-ERRORES.yml"
- "/home/isem/workspace-v1/shared/knowledge-base/lessons-learned/"

View File

@ -0,0 +1,127 @@
# PROJECT STATUS - Platform Marketing Content
**Fecha:** 2026-01-07
**Estado:** En Desarrollo
**Fase:** 1 - Foundation (25%)
---
## Resumen Ejecutivo
| Aspecto | Estado | Notas |
|---------|--------|-------|
| Documentacion | Completa | 69 archivos, 8 modulos |
| Database | Completado | Schema inicial con RLS |
| Backend | 25% | Auth, Tenants completados |
| Frontend | 20% | Layout, Login, Dashboard |
| CRM | Pendiente | Siguiente modulo |
| Assets/DAM | Pendiente | - |
| Generation | Pendiente | ComfyUI integration |
---
## Progreso por Capa
| Capa | Progreso | Estado |
|------|----------|--------|
| Database | 100% | Schema inicial completado |
| Backend | 25% | Auth, Tenants en produccion |
| Frontend | 20% | Layout, Auth pages listos |
---
## Modulos Implementados
| ID | Modulo | Backend | Frontend |
|----|--------|---------|----------|
| DB-001 | Schema PostgreSQL + RLS | 100% | - |
| BE-001 | Setup NestJS | 100% | - |
| BE-002 | Common module | 100% | - |
| BE-003 | Auth module | 100% | - |
| BE-004 | Tenants module | 100% | - |
| FE-001 | Setup React + Vite | - | 100% |
| FE-002 | shadcn/ui components | - | 100% |
| FE-003 | Layout + Routing | - | 100% |
| FE-004 | Auth store + API | - | 100% |
| FE-005 | Login + Dashboard | - | 100% |
---
## Modulos Pendientes
| Orden | Modulo | Prioridad | Estado |
|-------|--------|-----------|--------|
| 2 | CRM (Clients, Brands, Products) | Alta | Pendiente |
| 3 | Assets (DAM) | Alta | Pendiente |
| 4 | Projects (Projects, Campaigns) | Alta | Pendiente |
| 5 | Generation (ComfyUI, Jobs) | Alta | Pendiente |
| 6 | Automation (n8n) | Media | Pendiente |
| 7 | Analytics | Media | Pendiente |
---
## Estructura del Proyecto
```
apps/
├── backend/ # NestJS API (27 archivos)
│ ├── common/ # Decorators, guards, filters
│ ├── config/ # Database, JWT, Redis
│ └── modules/ # auth, tenants
└── frontend/ # React SPA (20 archivos)
├── components/ # ui, Layout
├── pages/ # auth, dashboard
└── stores/ # Zustand
database/
├── schemas/ # DDL scripts
└── seeds/ # Initial data
```
---
## Metricas de Documentacion
| Metrica | Valor |
|---------|-------|
| Modulos documentados | 8 |
| Requerimientos funcionales | 167 |
| User Stories | 77 |
| Epicas | 8 |
| ADRs | 4 |
| Prompts de agentes | 5 |
---
## Proximas Acciones
1. **BE-005:** CRM module (clients, brands, products)
2. **FE-007:** CRM pages y componentes
3. **BE-006:** Assets module con storage S3/MinIO
4. **FE-010:** Assets pages
---
## Riesgos
| Riesgo | Probabilidad | Impacto | Mitigacion |
|--------|--------------|---------|------------|
| Integracion ComfyUI | Media | Alto | API wrapper |
| Storage costs | Media | Medio | MinIO self-hosted |
| n8n complexity | Baja | Medio | Workflows simples |
---
## Comandos
```bash
# Backend
cd apps/backend && npm install && npm run start:dev
# Frontend
cd apps/frontend && npm install && npm run dev
```
---
**Ultima actualizacion:** 2026-01-07
**Actualizado por:** Orquestador

View File

@ -330,9 +330,9 @@ async delete(tenantId: string, brandId: string) {
## Referencias
- Catalogo: `core/catalog/multi-tenancy/README.md`
- Catalogo: `shared/catalog/multi-tenancy/README.md`
- ADR: `docs/97-adr/ADR-002-multi-tenancy.md`
- Patrones RLS: `core/catalog/multi-tenancy/patterns/rls-policies.md`
- Patrones RLS: `shared/catalog/multi-tenancy/patterns/rls-policies.md`
---

View File

@ -493,8 +493,8 @@ interface FailedEvent {
- ADR Motor: `docs/97-adr/ADR-003-motor-generacion.md`
- ADR Cola: `docs/97-adr/ADR-004-cola-tareas.md`
- Prompt Agente: `orchestration/prompts/PROMPT-GENERATION-PMC.md`
- Catalogo RateLimit: `core/catalog/rate-limiting/`
- Catalogo WebSocket: `core/catalog/websocket/`
- Catalogo RateLimit: `shared/catalog/rate-limiting/`
- Catalogo WebSocket: `shared/catalog/websocket/`
---

View File

@ -0,0 +1,333 @@
# =============================================================================
# ENVIRONMENT-INVENTORY.yml - PLATFORM_MARKETING_CONTENT
# =============================================================================
# Inventario de Entorno de Desarrollo
# Generado por: @PERFIL_DEVENV
# =============================================================================
version: "1.0.0"
fecha_creacion: "2026-01-04"
fecha_actualizacion: "2026-01-04"
responsable: "@PERFIL_DEVENV"
# -----------------------------------------------------------------------------
# IDENTIFICACION DEL PROYECTO
# -----------------------------------------------------------------------------
proyecto:
nombre: "Platform Marketing Content"
alias: "pmc"
nivel: "NIVEL_2A"
tipo: "standalone"
estado: "desarrollo"
descripcion: "Plataforma de generacion de contenido de marketing con IA"
# -----------------------------------------------------------------------------
# HERRAMIENTAS Y RUNTIME
# -----------------------------------------------------------------------------
herramientas:
runtime:
node:
version: "20.x"
requerido: true
notas: "Para backend NestJS y frontend React"
python:
version: "3.11"
requerido: true
notas: "Para ComfyUI y servicios de IA"
package_managers:
npm:
version: "10.x"
requerido: true
pip:
version: "23.x"
requerido: true
build_tools:
- nombre: "Vite"
version: "5.x"
uso: "Frontend build"
- nombre: "TypeScript"
version: "5.x"
uso: "Compilacion"
- nombre: "NestJS CLI"
version: "10.x"
uso: "Backend build"
linters:
- nombre: "ESLint"
version: "8.x"
config: ".eslintrc.js"
- nombre: "Prettier"
version: "3.x"
config: ".prettierrc"
testing:
- nombre: "Jest"
version: "29.x"
tipo: "unit"
config: "jest.config.js"
- nombre: "Vitest"
version: "1.x"
tipo: "unit frontend"
config: "vitest.config.ts"
# -----------------------------------------------------------------------------
# SERVICIOS Y PUERTOS
# -----------------------------------------------------------------------------
servicios:
frontend:
nombre: "pmc-frontend"
framework: "React"
version: "18.x"
puerto: 3110
comando_dev: "npm run dev"
ubicacion: "apps/frontend/"
url_local: "http://localhost:3110"
backend:
nombre: "pmc-backend"
framework: "NestJS"
version: "10.x"
puerto: 3111
comando_dev: "npm run start:dev"
ubicacion: "apps/backend/"
url_local: "http://localhost:3111"
api_prefix: "/api/v1"
comfyui:
nombre: "comfyui"
framework: "ComfyUI"
puerto_api: 8188
puerto_websocket: 8188
ubicacion: "external/comfyui/"
url_local: "http://localhost:8188"
notas: "Generacion de imagenes con Stable Diffusion"
# -----------------------------------------------------------------------------
# BASE DE DATOS
# -----------------------------------------------------------------------------
base_de_datos:
principal:
engine: "PostgreSQL"
version: "15"
host: "localhost"
puerto: 5432
ambientes:
development:
nombre: "pmc_dev"
usuario: "pmc_user"
password_ref: "DB_PASSWORD en .env"
test:
nombre: "pmc_test"
usuario: "pmc_user"
password_ref: "DB_PASSWORD en .env"
schemas:
- nombre: "public"
descripcion: "Schema principal"
conexion_ejemplo: "postgresql://pmc_user:{password}@localhost:5432/pmc_dev"
# -----------------------------------------------------------------------------
# VARIABLES DE ENTORNO
# -----------------------------------------------------------------------------
variables_entorno:
archivo_ejemplo: "apps/backend/.env.example"
variables:
- nombre: "NODE_ENV"
descripcion: "Ambiente de ejecucion"
requerido: true
sensible: false
ejemplo: "development"
- nombre: "PORT"
descripcion: "Puerto del servidor backend"
requerido: true
sensible: false
ejemplo: "3111"
- nombre: "DATABASE_URL"
descripcion: "Connection string de PostgreSQL"
requerido: true
sensible: true
ejemplo: "postgresql://pmc_user:password@localhost:5432/pmc_dev"
- nombre: "JWT_SECRET"
descripcion: "Secreto para JWT"
requerido: true
sensible: true
ejemplo: ""
- nombre: "COMFYUI_URL"
descripcion: "URL de ComfyUI API"
requerido: true
sensible: false
ejemplo: "http://localhost:8188"
- nombre: "FRONTEND_URL"
descripcion: "URL del frontend"
requerido: true
sensible: false
ejemplo: "http://localhost:3110"
# -----------------------------------------------------------------------------
# CONTENEDORES DOCKER
# -----------------------------------------------------------------------------
docker:
compose_file: "docker-compose.yml"
services:
- nombre: "db"
imagen: "postgres:15-alpine"
puerto_host: 5432
puerto_container: 5432
volumes:
- "postgres_data:/var/lib/postgresql/data"
- nombre: "comfyui"
imagen: "custom-comfyui"
puerto_host: 8188
puerto_container: 8188
volumes:
- "comfyui_models:/app/models"
- "comfyui_output:/app/output"
notas: "Requiere GPU NVIDIA"
volumes:
- nombre: "postgres_data"
descripcion: "Datos de PostgreSQL"
- nombre: "comfyui_models"
descripcion: "Modelos de Stable Diffusion"
- nombre: "comfyui_output"
descripcion: "Imagenes generadas"
networks:
- nombre: "pmc_network"
driver: "bridge"
# -----------------------------------------------------------------------------
# SCRIPTS DE DESARROLLO
# -----------------------------------------------------------------------------
scripts:
setup:
descripcion: "Configurar entorno desde cero"
pasos:
- "npm install"
- "cp .env.example .env"
- "docker-compose up -d db"
- "npm run migration:run"
desarrollo:
frontend: "cd apps/frontend && npm run dev"
backend: "cd apps/backend && npm run start:dev"
comfyui: "cd external/comfyui && python main.py"
testing:
unit: "npm run test"
e2e: "npm run test:e2e"
build:
frontend: "cd apps/frontend && npm run build"
backend: "cd apps/backend && npm run build"
# -----------------------------------------------------------------------------
# INSTRUCCIONES DE SETUP
# -----------------------------------------------------------------------------
setup_instrucciones: |
## Setup del Entorno de Desarrollo - Platform Marketing Content
### Prerequisitos
- Node.js 20.x
- Python 3.11
- PostgreSQL 15 (o Docker)
- npm 10.x, pip
- GPU NVIDIA (para ComfyUI)
### Pasos
1. Clonar repositorio:
```bash
git clone <url_repo>
cd platform_marketing_content
```
2. Instalar dependencias Node:
```bash
npm install
```
3. Configurar variables de entorno:
```bash
cp .env.example .env
# Editar .env con valores locales
```
4. Levantar base de datos:
```bash
docker-compose up -d db
```
5. Ejecutar migraciones:
```bash
npm run migration:run
```
6. Iniciar desarrollo:
```bash
# Terminal 1 - Backend
cd apps/backend && npm run start:dev
# Terminal 2 - Frontend
cd apps/frontend && npm run dev
# Terminal 3 - ComfyUI (si aplica)
cd external/comfyui && python main.py
```
### Verificar
- Frontend: http://localhost:3110
- Backend: http://localhost:3111/api/v1
- ComfyUI: http://localhost:8188
# -----------------------------------------------------------------------------
# TROUBLESHOOTING
# -----------------------------------------------------------------------------
troubleshooting:
- problema: "Puerto 3110 o 3111 en uso"
solucion: "Verificar con lsof -i :311X. Terminar proceso conflictivo"
- problema: "Error de conexion a BD"
solucion: "Verificar que PostgreSQL esta corriendo. Revisar credenciales en .env"
- problema: "ComfyUI no inicia"
solucion: "Verificar drivers NVIDIA. Verificar modelos descargados"
- problema: "Generacion de imagenes falla"
solucion: "Verificar VRAM disponible. Reducir tamano de imagen si es necesario"
# -----------------------------------------------------------------------------
# REFERENCIAS
# -----------------------------------------------------------------------------
referencias:
perfil_devenv: "orchestration/agents/perfiles/PERFIL-DEVENV.md"
inventario_master: "orchestration/inventarios/DEVENV-MASTER-INVENTORY.yml"
inventario_puertos: "orchestration/inventarios/DEVENV-PORTS-INVENTORY.yml"
contexto_proyecto: "orchestration/00-guidelines/CONTEXTO-PROYECTO.md"
# =============================================================================
# FIN DE INVENTARIO
# =============================================================================

View File

@ -268,7 +268,7 @@ referencias:
esquema_detallado: docs/04-modelado/ESQUEMA-BD.md
modelo_dominio: docs/04-modelado/MODELO-DOMINIO.md
adr_multitenancy: docs/97-adr/ADR-002-multi-tenancy.md
catalogo_tenant: core/catalog/multi-tenancy/
catalogo_tenant: shared/catalog/multi-tenancy/
# =============================================================================
# METADATOS

View File

@ -237,61 +237,61 @@ tech_stack:
catalog_dependencies:
required:
- id: "@CATALOG_AUTH"
path: core/catalog/auth/
path: shared/catalog/auth/
description: Autenticación JWT + OAuth + RBAC
module: PMC-007-ADMIN
docs: core/catalog/auth/README.md
docs: shared/catalog/auth/README.md
ahorro_estimado: "32h"
- id: "@CATALOG_SESSION"
path: core/catalog/session-management/
path: shared/catalog/session-management/
description: Gestión de sesiones concurrentes
module: PMC-007-ADMIN
docs: core/catalog/session-management/README.md
docs: shared/catalog/session-management/README.md
ahorro_estimado: "8h"
- id: "@CATALOG_TENANT"
path: core/catalog/multi-tenancy/
path: shared/catalog/multi-tenancy/
description: Multi-tenancy con RLS
module: PMC-001-TENANTS
docs: core/catalog/multi-tenancy/README.md
docs: shared/catalog/multi-tenancy/README.md
ahorro_estimado: "48h"
- id: "@CATALOG_RATELIMIT"
path: core/catalog/rate-limiting/
path: shared/catalog/rate-limiting/
description: Rate limiting por tenant/endpoint
module: PMC-004-GENERATION
docs: core/catalog/rate-limiting/README.md
docs: shared/catalog/rate-limiting/README.md
ahorro_estimado: "12h"
- id: "@CATALOG_NOTIFY"
path: core/catalog/notifications/
path: shared/catalog/notifications/
description: Notificaciones multi-canal
module: PMC-005-AUTOMATION
docs: core/catalog/notifications/README.md
docs: shared/catalog/notifications/README.md
ahorro_estimado: "26h"
fase_4_saas:
- id: "@CATALOG_PAYMENTS"
path: core/catalog/payments/
path: shared/catalog/payments/
description: Suscripciones con Stripe
module: PMC-001-TENANTS
docs: core/catalog/payments/README.md
docs: shared/catalog/payments/README.md
ahorro_estimado: "36h"
optional:
- id: "@CATALOG_FLAGS"
path: core/catalog/feature-flags/
path: shared/catalog/feature-flags/
description: Feature flags para rollout
module: PMC-007-ADMIN
docs: core/catalog/feature-flags/README.md
docs: shared/catalog/feature-flags/README.md
ahorro_estimado: "13h"
- id: "@CATALOG_WS"
path: core/catalog/websocket/
path: shared/catalog/websocket/
description: WebSocket para tiempo real
module: PMC-004-GENERATION
docs: core/catalog/websocket/README.md
docs: shared/catalog/websocket/README.md
ahorro_estimado: "18h"
ahorro_total: "185h de desarrollo"
@ -299,31 +299,31 @@ catalog_dependencies:
# =============================================================================
# PATRONES DE REFERENCIA (desde Catalogo Core)
# =============================================================================
# NOTA: Para componentes reutilizables, usar siempre core/catalog/
# NOTA: Para componentes reutilizables, usar siempre shared/catalog/
# Los proyectos externos sirven solo como inspiracion arquitectonica
reference_patterns:
auth_and_session:
catalogo: core/catalog/auth/
catalogo: shared/catalog/auth/
usar_para:
- Auth module structure
- Session management
- JWT patterns
multi_tenancy:
catalogo: core/catalog/multi-tenancy/
catalogo: shared/catalog/multi-tenancy/
usar_para:
- RLS policies
- Tenant isolation
- Feature flags
payments:
catalogo: core/catalog/payments/
catalogo: shared/catalog/payments/
usar_para:
- Stripe integration
- Wallet patterns
realtime:
catalogo: core/catalog/websocket/
catalogo: shared/catalog/websocket/
usar_para:
- WebSocket gateway
- Notifications

View File

@ -320,7 +320,7 @@ export const CurrentUser = createParamDecorator(
### @CATALOG_AUTH
```typescript
// Usar patrones de: core/catalog/auth/
// Usar patrones de: shared/catalog/auth/
// - JWT strategy
// - Password hashing (bcrypt)
// - Refresh tokens
@ -329,7 +329,7 @@ export const CurrentUser = createParamDecorator(
### @CATALOG_SESSION
```typescript
// Usar patrones de: core/catalog/session-management/
// Usar patrones de: shared/catalog/session-management/
// - Redis session store
// - Session expiration
// - Concurrent session limits
@ -337,7 +337,7 @@ export const CurrentUser = createParamDecorator(
### @CATALOG_RATELIMIT
```typescript
// Usar patrones de: core/catalog/rate-limiting/
// Usar patrones de: shared/catalog/rate-limiting/
// - ThrottlerModule
// - Per-tenant limits
// - Redis storage
@ -345,7 +345,7 @@ export const CurrentUser = createParamDecorator(
### @CATALOG_WS
```typescript
// Usar patrones de: core/catalog/websocket/
// Usar patrones de: shared/catalog/websocket/
// - WebSocket gateway
// - Room management (job:{jobId})
// - JWT authentication para sockets
@ -489,9 +489,9 @@ export class ClientService extends TenantAwareService<Client> {
| Multi-tenant | orchestration/directivas/DIRECTIVA-ARQUITECTURA-MULTI-TENANT.md |
| Definicion modulos | docs/02-definicion-modulos/ |
| Requerimientos | docs/03-requerimientos/ |
| Catalogo Auth | core/catalog/auth/ |
| Catalogo Session | core/catalog/session-management/ |
| Patrones NestJS | core/catalog/backend-patterns/ |
| Catalogo Auth | shared/catalog/auth/ |
| Catalogo Session | shared/catalog/session-management/ |
| Patrones NestJS | shared/catalog/backend-patterns/ |
---

View File

@ -373,7 +373,7 @@ COMMENT ON COLUMN crm.clients.metadata IS 'Datos adicionales en formato JSON';
| Directiva multi-tenant | orchestration/directivas/DIRECTIVA-ARQUITECTURA-MULTI-TENANT.md |
| Nomenclatura | orchestration/directivas/GUIA-NOMENCLATURA-PMC.md |
| Inventario DB | orchestration/inventarios/DATABASE_INVENTORY.yml |
| Catalogo tenant | core/catalog/multi-tenancy/ |
| Catalogo tenant | shared/catalog/multi-tenancy/ |
---

View File

@ -54,8 +54,8 @@ Workflows Predefinidos:
3. **Usar catalogo:**
```
@CATALOG_RATELIMIT: core/catalog/rate-limiting/
@CATALOG_WS: core/catalog/websocket/
@CATALOG_RATELIMIT: shared/catalog/rate-limiting/
@CATALOG_WS: shared/catalog/websocket/
```
---
@ -651,8 +651,8 @@ npm run start:dev # Inicia sin errores
| ADR Motor | docs/97-adr/ADR-003-motor-generacion.md |
| ADR Cola | docs/97-adr/ADR-004-cola-tareas.md |
| ComfyUI Docs | https://github.com/comfyanonymous/ComfyUI |
| Catalogo RateLimit | core/catalog/rate-limiting/ |
| Catalogo WebSocket | core/catalog/websocket/ |
| Catalogo RateLimit | shared/catalog/rate-limiting/ |
| Catalogo WebSocket | shared/catalog/websocket/ |
---