# Guía de Instalación - CampaignHub

## 📋 Requisitos del Sistema

### Servidor
- **PHP**: 8.3 o superior
- **Composer**: 2.6+
- **Node.js**: 20.x LTS
- **NPM**: 10.x
- **PostgreSQL**: 16.x
- **Redis**: 7.x
- **Git**

### Extensiones PHP Requeridas
```bash
php -m | grep -E 'mbstring|dom|fileinfo|pgsql|redis|gd|zip|bcmath|pdo'
```

---

## 🚀 Instalación Rápida (Desarrollo Local)

### 1. Clonar el Repositorio

```bash
git clone https://github.com/tu-org/campaignhub.git
cd campaignhub
```

### 2. Instalar Dependencias Backend

```bash
composer install
```

### 3. Configurar Ambiente

```bash
cp .env.example .env
php artisan key:generate
```

Edita `.env` con tus credenciales:

```env
APP_NAME="CampaignHub"
APP_ENV=local
APP_DEBUG=true
APP_URL=http://localhost:8000

DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=campaignhub
DB_USERNAME=postgres
DB_PASSWORD=tu_password

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
```

### 4. Crear Base de Datos

```bash
# PostgreSQL
createdb campaignhub

# O usando psql
psql -U postgres
CREATE DATABASE campaignhub;
\q
```

### 5. Ejecutar Migraciones

```bash
# Migración central (campaigns, domains)
php artisan migrate

# Crear tenant de prueba
php artisan tinker
>>> $campaign = \App\Models\Campaign::create([
...   'name' => 'Campaña Demo',
...   'slug' => 'demo',
...   'email' => 'demo@campaignhub.com',
...   'candidate_name' => 'Juan Demo',
...   'level' => 'municipal',
...   'jurisdiction' => 'Bogotá',
...   'status' => 'active',
...   'plan' => 'pro',
...   'trial_ends_at' => now()->addDays(30),
... ]);
>>> $campaign->domains()->create(['domain' => 'demo.campaignhub.test']);
>>> exit

# Migrar tenant
php artisan tenants:migrate
```

### 6. Seeders (Datos de Prueba)

```bash
php artisan db:seed --class=TenantSeeder
```

### 7. Instalar Dependencias Frontend

```bash
npm install
```

### 8. Compilar Assets

```bash
# Desarrollo
npm run dev

# Producción
npm run build
```

### 9. Iniciar Servidor

```bash
# Terminal 1: Laravel
php artisan serve

# Terminal 2: Vite (hot reload)
npm run dev

# Terminal 3: Queue Worker
php artisan queue:work

# Terminal 4: Horizon (opcional)
php artisan horizon
```

Accede a: **http://localhost:8000**

---

## 🐳 Instalación con Docker

### 1. Clonar y Configurar

```bash
git clone https://github.com/tu-org/campaignhub.git
cd campaignhub
cp .env.example .env
```

### 2. Levantar Contenedores

```bash
docker-compose up -d
```

### 3. Instalar Dependencias

```bash
docker-compose exec app composer install
docker-compose exec app php artisan key:generate
docker-compose exec app php artisan migrate --seed
```

### 4. Instalar Frontend

```bash
npm install
npm run build
```

Accede a: **http://localhost:8000**

---

## ⚙️ Configuración Avanzada

### Multi-Tenancy

Edita `config/tenancy.php`:

```php
'central_domains' => [
    env('CENTRAL_DOMAIN', 'campaignhub.test'),
],

'tenant_suffix' => env('TENANT_SUFFIX', '.campaignhub.test'),
```

Para desarrollo local, configura hosts:

```bash
# /etc/hosts (Linux/Mac) o C:\Windows\System32\drivers\etc\hosts (Windows)
127.0.0.1 campaignhub.test
127.0.0.1 demo.campaignhub.test
```

### Permisos

```bash
# Linux/Mac
sudo chown -R www-data:www-data storage bootstrap/cache
chmod -R 775 storage bootstrap/cache

# Docker
docker-compose exec app chown -R www-data:www-data storage bootstrap/cache
```

### Colas (Queues)

En producción, usa Supervisor:

```bash
# /etc/supervisor/conf.d/campaignhub-worker.conf
[program:campaignhub-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/html/artisan queue:work redis --sleep=3 --tries=3 --max-time=3600
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
user=www-data
numprocs=2
redirect_stderr=true
stdout_logfile=/var/www/html/storage/logs/worker.log
stopwaitsecs=3600

sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start campaignhub-worker:*
```

### Tareas Programadas (Cron)

```bash
# Agregar a crontab
* * * * * cd /ruta/campaignhub && php artisan schedule:run >> /dev/null 2>&1
```

---

## 🧪 Testing

### Backend Tests

```bash
# Todos los tests
php artisan test

# Con cobertura
php artisan test --coverage

# Solo unitarios
php artisan test --testsuite=Unit

# Solo features
php artisan test --testsuite=Feature
```

### Frontend Tests

```bash
# Linter
npm run lint

# Type Check
npm run type-check

# E2E (cuando estén configurados)
npm run test:e2e
```

---

## 📦 Producción

### 1. Optimizaciones

```bash
composer install --optimize-autoloader --no-dev
php artisan config:cache
php artisan route:cache
php artisan view:cache
npm run build
```

### 2. Servidor Web (Nginx)

```nginx
server {
    listen 80;
    server_name campaignhub.com *.campaignhub.com;
    root /var/www/campaignhub/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";

    index index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.3-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}
```

### 3. SSL con Let's Encrypt

```bash
sudo certbot --nginx -d campaignhub.com -d *.campaignhub.com
```

### 4. Variables de Entorno Producción

```env
APP_ENV=production
APP_DEBUG=false
APP_URL=https://campaignhub.com

DB_CONNECTION=pgsql
DB_HOST=db.production.com
DB_PORT=5432
DB_DATABASE=campaignhub_prod
DB_USERNAME=campaignhub
DB_PASSWORD=STRONG_PASSWORD_HERE

REDIS_HOST=redis.production.com

CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_CONNECTION=redis

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=campaignhub-assets
```

---

## 🔐 Seguridad

### Firewall

```bash
# UFW (Ubuntu)
sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
```

### PostgreSQL

```bash
# /etc/postgresql/16/main/pg_hba.conf
host    all    all    127.0.0.1/32    scram-sha-256

sudo systemctl restart postgresql
```

### Redis

```bash
# /etc/redis/redis.conf
bind 127.0.0.1
requirepass REDIS_STRONG_PASSWORD
```

---

## 📊 Monitoreo

### Logs

```bash
tail -f storage/logs/laravel.log
```

### Performance

- **Laravel Telescope**: Para debugging en desarrollo
- **New Relic / DataDog**: Para producción
- **Sentry**: Para errores

---

## 🆘 Solución de Problemas

### Error: "No application encryption key"

```bash
php artisan key:generate
```

### Error: Permisos en storage/

```bash
chmod -R 775 storage bootstrap/cache
chown -R www-data:www-data storage bootstrap/cache
```

### Error: "SQLSTATE[08006] Connection refused"

Verifica que PostgreSQL esté corriendo:

```bash
sudo systemctl status postgresql
sudo systemctl start postgresql
```

### Limpiar caché

```bash
php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear
```

---

## 📞 Soporte

- **Docs**: https://docs.campaignhub.com
- **Email**: support@campaignhub.com
- **GitHub Issues**: https://github.com/tu-org/campaignhub/issues

---

**¡Listo!** 🎉 Ya puedes comenzar a usar CampaignHub.








