# CMS Guide - Platform Marketing Content

## Overview

Esta guía explica cómo usar **Platform Marketing Content (PMC)** como un Content Management System (CMS) para gestión de contenido de marketing asistido por IA.

PMC combina las capacidades de un CMS tradicional con herramientas de generación de contenido AI, permitiendo a equipos de marketing crear, gestionar y distribuir contenido de manera eficiente.

## Core Concepts

### 1. Projects (Proyectos)

Los **proyectos** son contenedores organizacionales para campañas de marketing.

**Características:**
- Nombre y descripción
- Miembros del equipo
- Assets asociados
- Campañas
- Timeline y deadlines

**Casos de uso:**
- Lanzamiento de producto
- Campaña estacional
- Rebranding
- Serie de contenido

**Ejemplo:**
```
Proyecto: Lanzamiento Producto X
├── Assets
│   ├── Logo del producto
│   ├── Imágenes promocionales (10)
│   └── Videos demo (3)
├── Campañas
│   ├── Email marketing
│   ├── Social media
│   └── Blog posts
└── Miembros
    ├── John (Owner)
    ├── Sarah (Designer)
    └── Mike (Copywriter)
```

### 2. Assets (Recursos Digitales)

Los **assets** son archivos digitales (imágenes, videos, documentos) que se usan en las campañas.

**Tipos soportados:**
- Imágenes: JPG, PNG, SVG, WebP
- Videos: MP4, MOV, AVI
- Documentos: PDF, DOCX
- Otros: GIF, PSD (future)

**Metadata:**
- Tags (categorización)
- Colecciones
- Versiones
- Autor y fecha de creación
- Dimensiones (imágenes)
- Duración (videos)

**Organización:**
- Por proyecto
- Por tipo
- Por tags
- Por fecha

### 3. Templates (Plantillas)

Las **templates** son plantillas reutilizables para generación de contenido.

**Tipos:**
- Text templates (emails, blogs, social posts)
- Image templates (ComfyUI workflows)
- Video templates (future)

**Componentes:**
- Prompt base
- Variables dinámicas
- Configuración de modelo AI
- Post-processing rules

**Ejemplo:**
```markdown
**Template:** Email promocional de producto

**Prompt:**
Escribe un email promocional para {product_name} dirigido a {target_audience}.

Características del producto:
{product_features}

Tono: {tone} (profesional, casual, entusiasta)
Longitud: {length} palabras

Incluye:
- Subject line llamativo
- Introducción atractiva
- Beneficios clave
- Call to action claro
```

### 4. Campaigns (Campañas)

Las **campañas** agrupan contenido relacionado con un objetivo específico.

**Elementos:**
- Nombre y objetivo
- Canales (email, social, web)
- Schedule (fechas de publicación)
- Audience segments
- Performance metrics

**Workflow:**
```
1. Crear campaña
2. Definir audiencia
3. Generar contenido (AI)
4. Revisar y editar
5. Programar publicación
6. Monitorear resultados
```

### 5. Generation Jobs (Trabajos de Generación)

Los **generation jobs** son trabajos asíncronos de generación de contenido con IA.

**Estados:**
- `pending` - En cola
- `processing` - Generando
- `completed` - Completado
- `failed` - Falló

**Tipos:**
- Text generation (GPT-4, Claude)
- Image generation (ComfyUI)
- Batch generation (múltiples items)

## User Interface

### Dashboard

El **dashboard** principal muestra:

```
┌─────────────────────────────────────────────┐
│  Platform Marketing Content                 │
│  ┌────────────┐ ┌────────────┐ ┌─────────┐ │
│  │ Projects   │ │ Assets     │ │ Queue   │ │
│  │    12      │ │   1,234    │ │   5     │ │
│  └────────────┘ └────────────┘ └─────────┘ │
│                                              │
│  Recent Projects                             │
│  ┌────────────────────────────────────────┐ │
│  │ Product Launch Q1 2025        Active   │ │
│  │ Summer Campaign               Planning │ │
│  │ Rebranding Project            Paused   │ │
│  └────────────────────────────────────────┘ │
│                                              │
│  Recent Generations                          │
│  ┌────────────────────────────────────────┐ │
│  │ Email copy for Product X    Completed  │ │
│  │ Hero image variations       Processing │ │
│  │ Social media posts (10)     Pending    │ │
│  └────────────────────────────────────────┘ │
└─────────────────────────────────────────────┘
```

### Project View

**Tabs:**
1. **Overview** - Información general, timeline
2. **Assets** - Biblioteca de assets del proyecto
3. **Campaigns** - Campañas asociadas
4. **Generation** - Historial de generaciones
5. **Analytics** - Métricas de performance

### Asset Library

**Características:**
- Grid/List view
- Search bar (full-text)
- Filters (tipo, tags, fecha)
- Bulk operations (delete, tag, move)
- Preview modal
- Download/Share

**Actions:**
- Upload new asset
- Generate with AI
- Edit metadata
- Create collection
- Share with team

### Generation Interface

**Text Generation:**

```
┌─────────────────────────────────────────────┐
│  Generate Text Content                      │
│                                              │
│  Template: [Email Promocional ▼]            │
│                                              │
│  Variables:                                  │
│  Product Name: [________________]            │
│  Target Audience: [________________]         │
│  Tone: [Profesional ▼]                      │
│  Length: [200] words                         │
│                                              │
│  Model: [GPT-4 ▼]  Temperature: [0.7]       │
│                                              │
│  [Preview Prompt]  [Generate] [Schedule]    │
└─────────────────────────────────────────────┘
```

**Image Generation:**

```
┌─────────────────────────────────────────────┐
│  Generate Image                             │
│                                              │
│  Workflow: [Product Hero Image ▼]           │
│                                              │
│  Prompt:                                     │
│  ┌─────────────────────────────────────────┐│
│  │ Modern smartphone on clean background,  ││
│  │ professional product photography,        ││
│  │ soft lighting, high detail              ││
│  └─────────────────────────────────────────┘│
│                                              │
│  Negative Prompt: [________________]         │
│                                              │
│  Model: [FLUX-dev ▼]  Steps: [30]           │
│  Size: [1024x1024 ▼]  Batch: [4]            │
│                                              │
│  [Preview Settings]  [Generate]              │
└─────────────────────────────────────────────┘
```

## Common Workflows

### Workflow 1: Create Marketing Campaign

**Step 1: Create Project**
```
1. Dashboard → New Project
2. Name: "Summer Sale 2025"
3. Description: "Promote 30% discount on all products"
4. Add team members
5. Set deadline: June 1, 2025
```

**Step 2: Generate Email Content**
```
1. Projects → Summer Sale → Generate
2. Select template: "Promotional Email"
3. Fill variables:
   - Product: "All Products"
   - Discount: "30%"
   - Tone: "Enthusiastic"
4. Click Generate
5. Wait for job completion
6. Review and edit generated copy
```

**Step 3: Generate Visual Assets**
```
1. Projects → Summer Sale → Generate
2. Select workflow: "Sale Banner"
3. Prompt: "Summer sale banner, 30% off, beach theme"
4. Generate 4 variations
5. Download best variant
6. Upload to asset library
```

**Step 4: Create Campaign**
```
1. Projects → Summer Sale → New Campaign
2. Name: "Email Blast - Week 1"
3. Channel: Email
4. Audience: All subscribers
5. Schedule: June 1, 2025, 9:00 AM
6. Attach email copy and banner
```

**Step 5: Launch & Monitor**
```
1. Review campaign
2. Click Launch
3. Monitor analytics dashboard
4. Track opens, clicks, conversions
```

### Workflow 2: Batch Generate Social Media Posts

```typescript
// API example
POST /api/generation/batch

{
  "template_id": "social-media-post",
  "model": "gpt-4",
  "count": 10,
  "variables": {
    "product": "New Smartphone X",
    "platform": ["twitter", "instagram", "facebook"],
    "tone": "engaging",
    "include_hashtags": true
  }
}

// Response
{
  "job_id": "uuid",
  "status": "pending",
  "estimated_time": "2 minutes"
}
```

### Workflow 3: Create Asset Collection

**Purpose:** Organize brand assets

```
1. Asset Library → New Collection
2. Name: "Brand Kit 2025"
3. Description: "Official brand assets"
4. Add assets:
   - Logo (all formats)
   - Color palette
   - Typography guide
   - Brand guidelines PDF
5. Set permissions (view/download)
6. Share link with team
```

## AI Generation Features

### Text Generation

**Supported Models:**
- GPT-4 (OpenAI) - Best for long-form content
- GPT-3.5 Turbo - Faster, good for short content
- Claude 3 Opus (Anthropic) - Creative writing
- Claude 3 Sonnet - Balanced speed/quality

**Use Cases:**
- Email marketing copy
- Blog posts
- Social media captions
- Product descriptions
- Ad copy
- SEO meta descriptions

**Parameters:**
- `model` - AI model to use
- `temperature` - Creativity (0.0-1.0)
- `max_tokens` - Max output length
- `top_p` - Nucleus sampling
- `presence_penalty` - Avoid repetition
- `frequency_penalty` - Avoid common phrases

**Example:**
```typescript
{
  "model": "gpt-4",
  "temperature": 0.7,
  "max_tokens": 500,
  "prompt": "Write a blog post about the benefits of AI in marketing"
}
```

### Image Generation

**Supported Models:**
- Stable Diffusion 1.5
- Stable Diffusion XL
- FLUX-dev (realistic)
- FLUX-schnell (fast)

**Use Cases:**
- Product mockups
- Hero images
- Social media graphics
- Banner ads
- Illustrations
- Concept art

**Parameters:**
- `prompt` - Description of image
- `negative_prompt` - What to avoid
- `model` - AI model
- `steps` - Quality (20-50)
- `cfg_scale` - Prompt adherence (7-12)
- `width` / `height` - Dimensions
- `seed` - Reproducibility
- `batch_size` - Number of variations

**Example:**
```typescript
{
  "model": "flux-dev",
  "prompt": "Professional product photo of a smartwatch, clean background",
  "negative_prompt": "blurry, low quality, watermark",
  "steps": 30,
  "cfg_scale": 7.5,
  "width": 1024,
  "height": 1024,
  "batch_size": 4
}
```

### Advanced Features

**ControlNet (Images):**
- Pose control
- Depth control
- Edge detection
- Segmentation

**Inpainting:**
- Remove objects
- Replace backgrounds
- Modify specific areas

**Upscaling:**
- Increase resolution
- Enhance details

## Template System

### Create Text Template

**Structure:**
```yaml
name: "Product Launch Email"
description: "Email template for product launches"
category: "email"
variables:
  - name: product_name
    type: string
    required: true
  - name: launch_date
    type: date
    required: true
  - name: key_features
    type: array
    required: true
  - name: tone
    type: enum
    options: [professional, casual, enthusiastic]
    default: professional
prompt: |
  Write an email announcing the launch of {product_name} on {launch_date}.

  Key features:
  {key_features}

  Tone: {tone}

  Include:
  1. Exciting subject line
  2. Brief introduction
  3. 3-4 key benefits
  4. Clear CTA to learn more
  5. Professional sign-off

  Keep it under 200 words.
settings:
  model: gpt-4
  temperature: 0.7
  max_tokens: 500
```

### Create Image Template

**ComfyUI Workflow:**
```json
{
  "name": "Product Hero Image",
  "description": "Professional product photography style",
  "workflow": {
    "nodes": [
      {
        "id": 1,
        "type": "CheckpointLoaderSimple",
        "inputs": {
          "ckpt_name": "flux-dev.safetensors"
        }
      },
      {
        "id": 2,
        "type": "CLIPTextEncode",
        "inputs": {
          "text": "{{prompt}}, professional product photography, clean background, soft lighting"
        }
      },
      {
        "id": 3,
        "type": "KSampler",
        "inputs": {
          "steps": 30,
          "cfg": 7.5,
          "width": 1024,
          "height": 1024
        }
      }
    ]
  },
  "variables": {
    "prompt": "Product description"
  }
}
```

## Asset Management

### Upload Assets

**Methods:**
1. **Drag & Drop** - Arrastra archivos al área de upload
2. **File Browser** - Click para seleccionar
3. **Bulk Upload** - Múltiples archivos simultáneos
4. **API Upload** - Programático

**Validation:**
- Max file size: 50MB (configurable)
- Allowed types: images, videos, documents
- Malware scan (ClamAV)
- Duplicate detection

### Metadata Management

**Automatic:**
- File type, size, dimensions
- Upload date, uploader
- Checksum (MD5)

**Manual:**
- Title and description
- Tags
- Category
- Copyright info
- Alt text (accessibility)

### Search & Filter

**Search by:**
- Filename
- Tags
- Description
- File type
- Upload date
- Uploader

**Full-text search:**
```typescript
GET /api/assets/search?q=product+launch&type=image&tags=hero

Response:
{
  "results": [
    {
      "id": "uuid",
      "filename": "product-hero-v2.png",
      "tags": ["hero", "product", "launch"],
      "url": "https://cdn.example.com/..."
    }
  ],
  "total": 15,
  "page": 1
}
```

### Collections

**Purpose:** Agrupar assets relacionados

**Use Cases:**
- Brand kit (logos, colors, fonts)
- Campaign assets (specific project)
- Stock photos (generic)
- Templates (reusable)

**Features:**
- Public/Private visibility
- Share links
- Bulk download
- Permissions (view/edit/download)

## Automation

### Scheduled Generation

**Use Case:** Generate content at specific times

```typescript
POST /api/automation/schedule

{
  "name": "Daily social post",
  "template_id": "social-media-post",
  "schedule": "0 9 * * *",  // Cron: Every day at 9 AM
  "variables": {
    "topic": "Daily tip",
    "platform": "twitter"
  },
  "auto_publish": false  // Save as draft
}
```

### Webhooks

**Trigger on events:**
- Asset uploaded
- Generation completed
- Campaign launched
- Analytics threshold reached

**Example:**
```typescript
POST /api/webhooks

{
  "url": "https://your-app.com/webhook",
  "events": ["generation.completed", "asset.uploaded"],
  "secret": "webhook_secret"
}

// Webhook payload
{
  "event": "generation.completed",
  "timestamp": "2025-12-12T10:00:00Z",
  "data": {
    "job_id": "uuid",
    "type": "image",
    "status": "completed",
    "result_url": "https://..."
  }
}
```

### Batch Operations

**Apply actions to multiple items:**
- Bulk tag
- Bulk delete
- Bulk move to collection
- Bulk download
- Batch generation

## Analytics & Reporting

### Metrics Tracked

**Asset Performance:**
- Views
- Downloads
- Shares
- Usage in campaigns

**Generation Stats:**
- Jobs completed
- Success rate
- Average generation time
- Cost (API usage)

**Campaign Performance:**
- Impressions
- Clicks
- Conversions
- ROI

### Reports

**Available Reports:**
1. **Asset Usage Report** - Most/least used assets
2. **Generation Report** - AI usage statistics
3. **Campaign Performance** - Campaign metrics
4. **Team Activity** - User activity logs

**Export Formats:**
- CSV
- PDF
- JSON

## Best Practices

### Content Organization

1. **Use consistent naming:**
   - `project-name_asset-type_version.ext`
   - Example: `summer-sale_hero-banner_v2.png`

2. **Tag systematically:**
   - Type: `image`, `video`, `document`
   - Category: `hero`, `thumbnail`, `icon`
   - Project: `summer-sale`, `product-launch`

3. **Create collections for:**
   - Brand assets
   - Evergreen content
   - Seasonal campaigns

### Generation Tips

**Text:**
- Be specific in prompts
- Use examples for style
- Iterate on temperature
- Review and edit outputs

**Images:**
- Use descriptive prompts
- Include style keywords
- Generate multiple variations
- Use negative prompts

### Performance

1. **Optimize asset uploads:**
   - Compress before upload
   - Use appropriate formats (WebP for web)
   - Delete unused assets

2. **Batch operations:**
   - Generate multiple items at once
   - Use batch endpoints for efficiency

3. **Cache management:**
   - Clear old generations
   - Archive completed projects

## Troubleshooting

### Generation Failed

**Possible causes:**
- Invalid prompt
- Model timeout
- API quota exceeded
- ComfyUI error

**Solution:**
1. Check job error message
2. Retry with adjusted parameters
3. Contact support if persists

### Slow Upload

**Possible causes:**
- Large file size
- Network issues
- Server load

**Solution:**
1. Compress files before upload
2. Use batch upload for multiple files
3. Check internet connection

### Asset Not Found

**Possible causes:**
- Deleted asset
- Incorrect permissions
- Expired share link

**Solution:**
1. Verify asset exists in library
2. Check permissions
3. Generate new share link

## API Reference

See full API documentation: [API.md](./API.md)

**Quick Reference:**

```typescript
// Upload asset
POST /api/assets/upload
Content-Type: multipart/form-data

// Generate text
POST /api/generation/text
{
  "template_id": "uuid",
  "variables": {...}
}

// Generate image
POST /api/generation/image
{
  "workflow_id": "uuid",
  "prompt": "...",
  "settings": {...}
}

// Get generation status
GET /api/generation/jobs/:jobId

// List assets
GET /api/assets?project_id=uuid&tags=hero&page=1&limit=20
```

## Support & Resources

- **Documentation:** [/docs](../docs/)
- **API Docs:** [API.md](./API.md)
- **Architecture:** [ARCHITECTURE.md](./ARCHITECTURE.md)
- **Issues:** GitHub Issues
- **Discord:** Community support (future)

## Glossary

- **Asset:** Digital file (image, video, document)
- **Campaign:** Marketing initiative with content and schedule
- **Collection:** Grouped set of related assets
- **Generation Job:** Async AI content generation task
- **Project:** Container for campaigns and assets
- **Template:** Reusable content generation blueprint
- **Workflow:** ComfyUI image generation pipeline
