# Guía de Setup del Proyecto

**Versión:** 1.0.0
**Fecha:** 2025-12-08
**Proyecto:** Platform Marketing Content

---

## Requisitos Previos

### Software Requerido

| Software | Versión Mínima | Propósito |
|----------|----------------|-----------|
| Node.js | 18.x | Runtime |
| npm/pnpm | 9.x/8.x | Package manager |
| PostgreSQL | 15.x | Base de datos |
| Redis | 7.x | Cache y colas |
| Docker | 24.x | Contenedores |
| Docker Compose | 2.x | Orquestación local |

### Hardware Recomendado (Desarrollo)

| Componente | Mínimo | Recomendado |
|------------|--------|-------------|
| RAM | 8 GB | 16 GB |
| CPU | 4 cores | 8 cores |
| Storage | 20 GB libre | SSD 50 GB |
| GPU (para ComfyUI) | - | NVIDIA 8GB VRAM |

---

## Instalación Rápida con Docker

### 1. Clonar Repositorio

```bash
git clone <repo-url> platform_marketing_content
cd platform_marketing_content
```

### 2. Configurar Variables de Entorno

```bash
cp .env.example .env
# Editar .env con valores apropiados
```

### 3. Levantar Servicios con Docker Compose

```bash
docker-compose up -d
```

Esto levanta:
- PostgreSQL en puerto 5432
- Redis en puerto 6379
- MinIO (S3) en puerto 9000
- n8n en puerto 5678

### 4. Verificar Servicios

```bash
docker-compose ps
```

---

## Instalación Manual (Desarrollo)

### 1. Base de Datos

```bash
# Crear base de datos
createdb pmc

# Crear usuario
psql -c "CREATE USER pmc_user WITH PASSWORD 'secret';"
psql -c "GRANT ALL PRIVILEGES ON DATABASE pmc TO pmc_user;"

# Crear schemas
psql -d pmc -f scripts/init-schemas.sql
```

### 2. Backend

```bash
cd apps/backend

# Instalar dependencias
npm install

# Copiar configuración
cp .env.example .env

# Ejecutar migraciones
npm run migration:run

# Ejecutar seeds (datos iniciales)
npm run seed

# Iniciar en modo desarrollo
npm run start:dev
```

### 3. Frontend

```bash
cd apps/frontend

# Instalar dependencias
npm install

# Copiar configuración
cp .env.example .env

# Iniciar en modo desarrollo
npm run dev
```

### 4. ComfyUI (Opcional)

```bash
# Clonar ComfyUI
git clone https://github.com/comfyanonymous/ComfyUI.git
cd ComfyUI

# Instalar dependencias
pip install -r requirements.txt

# Descargar modelos (SDXL)
# Seguir instrucciones de ComfyUI para modelos

# Iniciar ComfyUI
python main.py --listen 0.0.0.0
```

---

## Estructura de Variables de Entorno

### Backend (.env)

```bash
# ===================
# APPLICATION
# ===================
NODE_ENV=development
PORT=3000
API_PREFIX=api/v1
CORS_ORIGINS=http://localhost:5173

# ===================
# DATABASE
# ===================
DATABASE_HOST=localhost
DATABASE_PORT=5432
DATABASE_NAME=pmc
DATABASE_USER=pmc_user
DATABASE_PASSWORD=secret
DATABASE_SSL=false
DATABASE_LOGGING=true

# ===================
# REDIS
# ===================
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=

# ===================
# AUTHENTICATION
# ===================
JWT_SECRET=your-super-secret-key-change-in-production
JWT_EXPIRES_IN=1d
JWT_REFRESH_EXPIRES_IN=7d

# ===================
# STORAGE (S3/MinIO)
# ===================
S3_ENDPOINT=http://localhost:9000
S3_ACCESS_KEY=minioadmin
S3_SECRET_KEY=minioadmin
S3_BUCKET=pmc-assets
S3_REGION=us-east-1
S3_USE_SSL=false

# ===================
# COMFYUI
# ===================
COMFYUI_URL=http://localhost:8188
COMFYUI_WEBHOOK_URL=http://localhost:3000/api/v1/generation/webhook
COMFYUI_WEBHOOK_SECRET=comfyui-webhook-secret

# ===================
# AI SERVICES
# ===================
OPENAI_API_KEY=sk-your-api-key
OPENAI_MODEL=gpt-4

# ===================
# N8N
# ===================
N8N_URL=http://localhost:5678
N8N_API_KEY=your-n8n-api-key

# ===================
# EMAIL
# ===================
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_USER=
SMTP_PASSWORD=
SMTP_FROM=noreply@example.com
```

### Frontend (.env)

```bash
VITE_API_URL=http://localhost:3000/api/v1
VITE_WS_URL=ws://localhost:3000
VITE_APP_NAME=Platform Marketing Content
```

---

## Docker Compose

### docker-compose.yml

```yaml
version: '3.8'

services:
  postgres:
    image: postgres:15
    container_name: pmc-postgres
    environment:
      POSTGRES_DB: pmc
      POSTGRES_USER: pmc_user
      POSTGRES_PASSWORD: secret
    ports:
      - "5432:5432"
    volumes:
      - postgres_data:/var/lib/postgresql/data
      - ./scripts/init-schemas.sql:/docker-entrypoint-initdb.d/01-schemas.sql

  redis:
    image: redis:7-alpine
    container_name: pmc-redis
    ports:
      - "6379:6379"
    volumes:
      - redis_data:/data

  minio:
    image: minio/minio
    container_name: pmc-minio
    command: server /data --console-address ":9001"
    environment:
      MINIO_ROOT_USER: minioadmin
      MINIO_ROOT_PASSWORD: minioadmin
    ports:
      - "9000:9000"
      - "9001:9001"
    volumes:
      - minio_data:/data

  n8n:
    image: n8nio/n8n
    container_name: pmc-n8n
    environment:
      - N8N_BASIC_AUTH_ACTIVE=true
      - N8N_BASIC_AUTH_USER=admin
      - N8N_BASIC_AUTH_PASSWORD=admin
    ports:
      - "5678:5678"
    volumes:
      - n8n_data:/home/node/.n8n

volumes:
  postgres_data:
  redis_data:
  minio_data:
  n8n_data:
```

---

## Scripts Útiles

### Package.json (Backend)

```json
{
  "scripts": {
    "start": "node dist/main",
    "start:dev": "nest start --watch",
    "start:debug": "nest start --debug --watch",
    "build": "nest build",
    "test": "jest",
    "test:watch": "jest --watch",
    "test:cov": "jest --coverage",
    "test:e2e": "jest --config ./test/jest-e2e.json",
    "migration:generate": "typeorm migration:generate -d src/config/data-source.ts",
    "migration:run": "typeorm migration:run -d src/config/data-source.ts",
    "migration:revert": "typeorm migration:revert -d src/config/data-source.ts",
    "seed": "ts-node src/seeds/run-seeds.ts",
    "lint": "eslint \"{src,test}/**/*.ts\" --fix",
    "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\""
  }
}
```

---

## Verificación de Instalación

### 1. Verificar Backend

```bash
curl http://localhost:3000/api/v1/health
# Response: { "status": "ok", "timestamp": "..." }
```

### 2. Verificar Frontend

```bash
# Abrir navegador en http://localhost:5173
# Debería mostrar página de login
```

### 3. Verificar PostgreSQL

```bash
psql -h localhost -U pmc_user -d pmc -c "SELECT 1;"
```

### 4. Verificar Redis

```bash
redis-cli ping
# Response: PONG
```

### 5. Verificar MinIO

```bash
# Abrir navegador en http://localhost:9001
# Login: minioadmin / minioadmin
```

---

## Datos Iniciales (Seeds)

El comando `npm run seed` crea:

1. **Plan "Internal"** - Sin límites para uso interno
2. **Tenant inicial** - "Agencia Demo"
3. **Usuario Super Admin** - admin@example.com / Admin123!
4. **Roles de sistema** - super_admin, tenant_admin, creative, analyst, viewer
5. **Workflows de generación** - product_photo, social_post, variations

---

## Troubleshooting

### Error: "ECONNREFUSED" a PostgreSQL

```bash
# Verificar que PostgreSQL está corriendo
docker-compose ps postgres
# O si es local
pg_isready -h localhost -p 5432
```

### Error: "Redis connection refused"

```bash
# Verificar Redis
docker-compose logs redis
redis-cli ping
```

### Error: "Cannot find module"

```bash
# Reinstalar dependencias
rm -rf node_modules
npm install
```

### Error: Migraciones fallan

```bash
# Verificar conexión a BD
npm run typeorm query "SELECT 1"

# Ejecutar migraciones paso a paso
npm run migration:run -- --verbose
```

---

## Referencias

- [GUIA-CONVENCIONES.md](./GUIA-CONVENCIONES.md)
- [ARQUITECTURA-TECNICA.md](../00-vision-general/ARQUITECTURA-TECNICA.md)
- [Docker Documentation](https://docs.docker.com/)
- [NestJS CLI](https://docs.nestjs.com/cli/overview)

---

**Documento generado por:** Requirements-Analyst
**Fecha:** 2025-12-08
