--- 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)