Reflect current project state across all 8 docs: ADMIN/ORGANISMO_OPERADOR/OPERATOR role hierarchy, scope filtering, organismos_operadores table, Histórico de Tomas page, new SQL migrations, and updated API endpoints with auth requirements. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
395 lines
8.0 KiB
Markdown
395 lines
8.0 KiB
Markdown
# Guia de Instalacion
|
|
|
|
## Requisitos Previos
|
|
|
|
### Software Requerido
|
|
- **Node.js** 18.x o superior
|
|
- **npm** 9.x o superior
|
|
- **PostgreSQL** 14.x o superior
|
|
- **Git**
|
|
|
|
### Puertos Utilizados
|
|
| Servicio | Puerto |
|
|
|----------|--------|
|
|
| Frontend Principal | 5173 |
|
|
| Panel de Carga CSV | 5174 |
|
|
| Backend API | 3000 |
|
|
| PostgreSQL | 5432 |
|
|
|
|
---
|
|
|
|
## Instalacion del Backend (water-api)
|
|
|
|
### 1. Clonar el Repositorio
|
|
```bash
|
|
git clone https://git.consultoria-as.com/consultoria-as/water-project.git
|
|
cd water-project
|
|
```
|
|
|
|
### 2. Configurar la Base de Datos
|
|
|
|
#### Crear la base de datos:
|
|
```bash
|
|
sudo -u postgres psql
|
|
```
|
|
|
|
```sql
|
|
CREATE DATABASE water_project;
|
|
CREATE USER water_user WITH PASSWORD 'tu_password_seguro';
|
|
GRANT ALL PRIVILEGES ON DATABASE water_project TO water_user;
|
|
\q
|
|
```
|
|
|
|
#### Ejecutar los scripts SQL:
|
|
```bash
|
|
cd water-api/sql
|
|
psql -U water_user -d water_project -f schema.sql
|
|
psql -U water_user -d water_project -f add_audit_logs.sql
|
|
psql -U water_user -d water_project -f add_notifications.sql
|
|
psql -U water_user -d water_project -f add_meter_extended_fields.sql
|
|
psql -U water_user -d water_project -f add_meter_project_relation.sql
|
|
psql -U water_user -d water_project -f add_meter_types.sql
|
|
psql -U water_user -d water_project -f add_organismos_operadores.sql
|
|
psql -U water_user -d water_project -f add_user_meter_fields.sql
|
|
```
|
|
|
|
**Nota:** `add_organismos_operadores.sql` crea la tabla `organismos_operadores`, agrega columnas FK en `projects` y `users`, y agrega el rol `ORGANISMO_OPERADOR`. `add_user_meter_fields.sql` agrega campos como `cespt_account` y `cadastral_key`.
|
|
|
|
### 3. Configurar Variables de Entorno
|
|
|
|
```bash
|
|
cd water-api
|
|
cp .env.example .env
|
|
```
|
|
|
|
Editar `.env`:
|
|
```env
|
|
# Server
|
|
PORT=3000
|
|
NODE_ENV=production
|
|
|
|
# Database
|
|
DB_HOST=localhost
|
|
DB_PORT=5432
|
|
DB_NAME=water_project
|
|
DB_USER=water_user
|
|
DB_PASSWORD=tu_password_seguro
|
|
|
|
# JWT (generar claves seguras)
|
|
JWT_ACCESS_SECRET=clave_secreta_acceso_minimo_32_caracteres
|
|
JWT_REFRESH_SECRET=clave_secreta_refresh_minimo_32_caracteres
|
|
JWT_ACCESS_EXPIRES_IN=15m
|
|
JWT_REFRESH_EXPIRES_IN=7d
|
|
|
|
# CORS (URLs del frontend separadas por coma)
|
|
CORS_ORIGIN=http://localhost:5173,http://localhost:5174,https://sistema.gestionrecursoshidricos.com,https://panel.gestionrecursoshidricos.com
|
|
|
|
# TTS (The Things Stack) - Opcional
|
|
TTS_ENABLED=false
|
|
TTS_BASE_URL=https://your-tts-server.com
|
|
TTS_APPLICATION_ID=your-app-id
|
|
TTS_API_KEY=your-api-key
|
|
TTS_WEBHOOK_SECRET=your-webhook-secret
|
|
```
|
|
|
|
### 4. Instalar Dependencias y Ejecutar
|
|
|
|
```bash
|
|
npm install
|
|
npm run dev # Desarrollo con hot-reload
|
|
# o
|
|
npm run build # Compilar para produccion
|
|
npm start # Ejecutar version compilada
|
|
```
|
|
|
|
### 5. Verificar Instalacion
|
|
```bash
|
|
curl http://localhost:3000/health
|
|
```
|
|
|
|
Respuesta esperada:
|
|
```json
|
|
{
|
|
"status": "ok",
|
|
"timestamp": "2024-01-20T10:30:00.000Z",
|
|
"environment": "production"
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## Instalacion del Frontend Principal
|
|
|
|
### 1. Configurar Variables de Entorno
|
|
|
|
```bash
|
|
cd /path/to/water-project
|
|
cp .env.example .env
|
|
```
|
|
|
|
Editar `.env`:
|
|
```env
|
|
VITE_API_BASE_URL=http://localhost:3000
|
|
```
|
|
|
|
Para produccion:
|
|
```env
|
|
VITE_API_BASE_URL=https://api.gestionrecursoshidricos.com
|
|
```
|
|
|
|
### 2. Instalar Dependencias y Ejecutar
|
|
|
|
```bash
|
|
npm install
|
|
npm run dev # Desarrollo
|
|
# o
|
|
npm run build # Compilar para produccion
|
|
npm run preview # Vista previa de produccion
|
|
```
|
|
|
|
### 3. Verificar Instalacion
|
|
Abrir en el navegador: http://localhost:5173
|
|
|
|
---
|
|
|
|
## Instalacion del Panel de Carga CSV
|
|
|
|
### 1. Configurar Variables de Entorno
|
|
|
|
```bash
|
|
cd upload-panel
|
|
cp .env.example .env # Si existe, o crear manualmente
|
|
```
|
|
|
|
Crear `.env`:
|
|
```env
|
|
VITE_API_URL=http://localhost:3000/api
|
|
```
|
|
|
|
Para produccion:
|
|
```env
|
|
VITE_API_URL=https://api.gestionrecursoshidricos.com/api
|
|
```
|
|
|
|
### 2. Instalar Dependencias y Ejecutar
|
|
|
|
```bash
|
|
npm install
|
|
npm run dev # Desarrollo (puerto 5174)
|
|
# o
|
|
npm run build # Compilar para produccion
|
|
```
|
|
|
|
### 3. Verificar Instalacion
|
|
Abrir en el navegador: http://localhost:5174
|
|
|
|
---
|
|
|
|
## Despliegue en Produccion
|
|
|
|
### Opcion 1: PM2 (Recomendado)
|
|
|
|
#### Instalar PM2:
|
|
```bash
|
|
npm install -g pm2
|
|
```
|
|
|
|
#### Configurar ecosystem.config.js:
|
|
```javascript
|
|
module.exports = {
|
|
apps: [
|
|
{
|
|
name: 'water-api',
|
|
cwd: '/path/to/water-project/water-api',
|
|
script: 'npm',
|
|
args: 'start',
|
|
env: {
|
|
NODE_ENV: 'production',
|
|
PORT: 3000
|
|
}
|
|
}
|
|
]
|
|
};
|
|
```
|
|
|
|
#### Iniciar con PM2:
|
|
```bash
|
|
pm2 start ecosystem.config.js
|
|
pm2 save
|
|
pm2 startup # Configurar inicio automatico
|
|
```
|
|
|
|
### Opcion 2: Systemd Service
|
|
|
|
Crear `/etc/systemd/system/water-api.service`:
|
|
```ini
|
|
[Unit]
|
|
Description=Water API Server
|
|
After=network.target postgresql.service
|
|
|
|
[Service]
|
|
Type=simple
|
|
User=www-data
|
|
WorkingDirectory=/path/to/water-project/water-api
|
|
ExecStart=/usr/bin/node dist/index.js
|
|
Restart=on-failure
|
|
Environment=NODE_ENV=production
|
|
|
|
[Install]
|
|
WantedBy=multi-user.target
|
|
```
|
|
|
|
```bash
|
|
sudo systemctl enable water-api
|
|
sudo systemctl start water-api
|
|
```
|
|
|
|
### Configurar Nginx (Reverse Proxy)
|
|
|
|
```nginx
|
|
# /etc/nginx/sites-available/water-project
|
|
|
|
# API
|
|
server {
|
|
listen 443 ssl;
|
|
server_name api.gestionrecursoshidricos.com;
|
|
|
|
ssl_certificate /path/to/cert.pem;
|
|
ssl_certificate_key /path/to/key.pem;
|
|
|
|
location / {
|
|
proxy_pass http://localhost:3000;
|
|
proxy_http_version 1.1;
|
|
proxy_set_header Upgrade $http_upgrade;
|
|
proxy_set_header Connection 'upgrade';
|
|
proxy_set_header Host $host;
|
|
proxy_set_header X-Real-IP $remote_addr;
|
|
proxy_cache_bypass $http_upgrade;
|
|
}
|
|
}
|
|
|
|
# Frontend Principal
|
|
server {
|
|
listen 443 ssl;
|
|
server_name sistema.gestionrecursoshidricos.com;
|
|
|
|
ssl_certificate /path/to/cert.pem;
|
|
ssl_certificate_key /path/to/key.pem;
|
|
|
|
root /path/to/water-project/dist;
|
|
index index.html;
|
|
|
|
location / {
|
|
try_files $uri $uri/ /index.html;
|
|
}
|
|
}
|
|
|
|
# Panel de Carga
|
|
server {
|
|
listen 443 ssl;
|
|
server_name panel.gestionrecursoshidricos.com;
|
|
|
|
ssl_certificate /path/to/cert.pem;
|
|
ssl_certificate_key /path/to/key.pem;
|
|
|
|
root /path/to/water-project/upload-panel/dist;
|
|
index index.html;
|
|
|
|
location / {
|
|
try_files $uri $uri/ /index.html;
|
|
}
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## Crear Usuario Administrador Inicial
|
|
|
|
### Via SQL:
|
|
```sql
|
|
-- Primero obtener el ID del rol ADMIN
|
|
SELECT id FROM roles WHERE name = 'ADMIN';
|
|
|
|
-- Crear usuario (password debe ser hash bcrypt)
|
|
-- Puedes usar: https://bcrypt-generator.com/ para generar el hash
|
|
INSERT INTO users (email, password_hash, name, role_id, is_active)
|
|
VALUES (
|
|
'admin@ejemplo.com',
|
|
'$2b$10$xxxxx...', -- Hash bcrypt de la contraseña
|
|
'Administrador',
|
|
'uuid-del-rol-admin',
|
|
true
|
|
);
|
|
```
|
|
|
|
### Via API (si ya tienes un admin):
|
|
```bash
|
|
curl -X POST http://localhost:3000/api/users \
|
|
-H "Authorization: Bearer {token}" \
|
|
-H "Content-Type: application/json" \
|
|
-d '{
|
|
"email": "nuevo@ejemplo.com",
|
|
"password": "password123",
|
|
"name": "Nuevo Admin",
|
|
"role_id": "uuid-rol-admin"
|
|
}'
|
|
```
|
|
|
|
---
|
|
|
|
## Configuracion de The Things Stack (TTS)
|
|
|
|
### 1. Configurar Variables de Entorno
|
|
|
|
```env
|
|
TTS_ENABLED=true
|
|
TTS_BASE_URL=https://tu-servidor-tts.com
|
|
TTS_APPLICATION_ID=tu-aplicacion
|
|
TTS_API_KEY=tu-api-key
|
|
TTS_WEBHOOK_SECRET=tu-webhook-secret
|
|
```
|
|
|
|
### 2. Configurar Webhook en TTS
|
|
|
|
En la consola de TTS, configurar webhook apuntando a:
|
|
- **URL Base**: `https://api.gestionrecursoshidricos.com/api/webhooks/tts`
|
|
- **Eventos**:
|
|
- Uplink: `/uplink`
|
|
- Join: `/join`
|
|
- Downlink ACK: `/downlink/ack`
|
|
|
|
### 3. Configurar Header de Autenticacion
|
|
- **Header**: `X-Downlink-Apikey`
|
|
- **Valor**: El mismo que `TTS_WEBHOOK_SECRET`
|
|
|
|
---
|
|
|
|
## Solucion de Problemas
|
|
|
|
### Error de conexion a la base de datos
|
|
```
|
|
Error: connect ECONNREFUSED 127.0.0.1:5432
|
|
```
|
|
- Verificar que PostgreSQL esta corriendo: `sudo systemctl status postgresql`
|
|
- Verificar credenciales en `.env`
|
|
|
|
### Error CORS
|
|
```
|
|
Access-Control-Allow-Origin
|
|
```
|
|
- Verificar que la URL del frontend esta en `CORS_ORIGIN`
|
|
|
|
### Puerto en uso
|
|
```
|
|
Error: listen EADDRINUSE :::3000
|
|
```
|
|
- Verificar si hay otro proceso: `lsof -i :3000`
|
|
- Terminar proceso: `kill -9 <PID>`
|
|
|
|
### Permisos de archivo
|
|
```
|
|
EACCES: permission denied
|
|
```
|
|
- Verificar permisos del directorio
|
|
- Ejecutar: `chown -R $USER:$USER /path/to/water-project`
|