Actualizar server.js
This commit is contained in:
166
server.js
166
server.js
@@ -3,7 +3,6 @@ import cors from "cors";
|
||||
import bcrypt from "bcryptjs";
|
||||
import jwt from "jsonwebtoken";
|
||||
import pg from "pg";
|
||||
import fetch from "node-fetch";
|
||||
|
||||
const { Pool } = pg;
|
||||
const app = express();
|
||||
@@ -37,7 +36,7 @@ async function autoUpdateDB() {
|
||||
try {
|
||||
console.log("🔄 Verificando estructura DB...");
|
||||
|
||||
// 1. TABLAS PRINCIPALES
|
||||
// 1. ESTRUCTURA BÁSICA
|
||||
await client.query(`
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id SERIAL PRIMARY KEY,
|
||||
@@ -77,6 +76,10 @@ async function autoUpdateDB() {
|
||||
id SERIAL PRIMARY KEY,
|
||||
owner_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
cif TEXT,
|
||||
email TEXT,
|
||||
phone TEXT,
|
||||
address TEXT,
|
||||
created_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS clients (
|
||||
@@ -100,37 +103,33 @@ async function autoUpdateDB() {
|
||||
);
|
||||
`);
|
||||
|
||||
// 2. TABLAS GEOGRÁFICAS (NUEVO MODELO)
|
||||
// 2. TABLAS GEOGRÁFICAS
|
||||
await client.query(`
|
||||
CREATE TABLE IF NOT EXISTS provinces (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name TEXT UNIQUE NOT NULL
|
||||
);
|
||||
|
||||
-- TABLA DE POBLACIONES (Se llenará externamente)
|
||||
CREATE TABLE IF NOT EXISTS towns (
|
||||
id SERIAL PRIMARY KEY,
|
||||
province_id INT REFERENCES provinces(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL
|
||||
);
|
||||
|
||||
-- ZONAS PERSONALIZADAS (Agrupaciones de pueblos)
|
||||
CREATE TABLE IF NOT EXISTS zones (
|
||||
id SERIAL PRIMARY KEY,
|
||||
province_id INT REFERENCES provinces(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL, -- Ej: "Ruta Sierra", "Capital y Alrededores"
|
||||
name TEXT NOT NULL,
|
||||
owner_id INT,
|
||||
created_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- RELACIÓN ZONA <-> PUEBLOS (Qué pueblos componen una zona)
|
||||
CREATE TABLE IF NOT EXISTS zone_towns (
|
||||
zone_id INT REFERENCES zones(id) ON DELETE CASCADE,
|
||||
town_id INT REFERENCES towns(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (zone_id, town_id)
|
||||
);
|
||||
|
||||
-- RELACIÓN OPERARIO <-> ZONAS (Dónde trabaja el operario)
|
||||
CREATE TABLE IF NOT EXISTS user_zones (
|
||||
user_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||||
zone_id INT REFERENCES zones(id) ON DELETE CASCADE,
|
||||
@@ -138,7 +137,7 @@ async function autoUpdateDB() {
|
||||
);
|
||||
`);
|
||||
|
||||
// 3. TABLA SERVICIOS
|
||||
// 3. SERVICIOS Y LOGS
|
||||
await client.query(`
|
||||
CREATE TABLE IF NOT EXISTS services (
|
||||
id SERIAL PRIMARY KEY,
|
||||
@@ -176,10 +175,7 @@ async function autoUpdateDB() {
|
||||
);
|
||||
`);
|
||||
|
||||
// 4. SEEDING (CARGA DE DATOS INE)
|
||||
await seedSpainData(client);
|
||||
|
||||
// 5. PARCHE DE REPARACIÓN DE COLUMNAS
|
||||
// 4. PARCHE DE REPARACIÓN
|
||||
await client.query(`
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='client_id') THEN ALTER TABLE services ADD COLUMN client_id INT REFERENCES clients(id) ON DELETE SET NULL; END IF;
|
||||
@@ -207,77 +203,79 @@ async function autoUpdateDB() {
|
||||
END $$;
|
||||
`);
|
||||
|
||||
// 5. CARGA MASIVA INE (AHORA SÍ)
|
||||
await seedSpainData(client);
|
||||
|
||||
console.log("✅ DB Sincronizada.");
|
||||
} catch (e) { console.error("❌ Error DB:", e); } finally { client.release(); }
|
||||
}
|
||||
|
||||
// 🌍 CARGA MASIVA INE
|
||||
// 🌍 CARGA MASIVA INE (LÓGICA MEJORADA)
|
||||
async function seedSpainData(client) {
|
||||
try {
|
||||
const count = await client.query("SELECT COUNT(*) FROM provinces");
|
||||
if (parseInt(count.rows[0].count) > 0) return;
|
||||
// Comprobamos si hay PUEBLOS (no provincias), porque provincias puede haber alguna suelta
|
||||
const count = await client.query("SELECT COUNT(*) FROM towns");
|
||||
if (parseInt(count.rows[0].count) > 100) return; // Si hay más de 100 pueblos, asumimos que está cargada
|
||||
|
||||
console.log("📥 Detectada DB vacía de poblaciones. Descargando datos del INE...");
|
||||
|
||||
console.log("📥 Descargando datos del INE...");
|
||||
// JSON fiable con Provincias y Poblaciones
|
||||
const response = await fetch("https://raw.githubusercontent.com/frontid/comunidades-provincias-poblaciones/master/poblaciones.json");
|
||||
const listFull = await response.json();
|
||||
|
||||
console.log(`🇪🇸 Insertando ${listFull.length} registros... (Esto puede tardar un poco)`);
|
||||
|
||||
await client.query("BEGIN");
|
||||
|
||||
// 1. Extraer y crear Provincias (Evitando duplicados con ON CONFLICT)
|
||||
const provincesSet = new Set();
|
||||
listFull.forEach(item => provincesSet.add(item.parent_op));
|
||||
|
||||
// Mapa para guardar el ID real de cada provincia
|
||||
const provinceMap = new Map();
|
||||
|
||||
for (const provName of provincesSet) {
|
||||
const res = await client.query("INSERT INTO provinces (name) VALUES ($1) RETURNING id", [provName]);
|
||||
// Insertamos si no existe, y recuperamos el ID (incluso si ya existía)
|
||||
await client.query("INSERT INTO provinces (name) VALUES ($1) ON CONFLICT (name) DO NOTHING", [provName]);
|
||||
const res = await client.query("SELECT id FROM provinces WHERE name=$1", [provName]);
|
||||
provinceMap.set(provName, res.rows[0].id);
|
||||
}
|
||||
|
||||
// 2. Insertar Pueblos
|
||||
for (const item of listFull) {
|
||||
const pid = provinceMap.get(item.parent_op);
|
||||
if (pid) await client.query("INSERT INTO towns (province_id, name) VALUES ($1, $2)", [pid, item.label]);
|
||||
}
|
||||
await client.query("COMMIT");
|
||||
console.log("✅ Datos de España cargados.");
|
||||
} catch (e) {
|
||||
await client.query("ROLLBACK");
|
||||
console.error("❌ Error Seeding:", e);
|
||||
// Fallback en caso de error
|
||||
await client.query("INSERT INTO provinces (name) VALUES ('Cádiz') ON CONFLICT DO NOTHING");
|
||||
if (pid) {
|
||||
// Insertamos pueblo asociado a la provincia encontrada
|
||||
await client.query("INSERT INTO towns (province_id, name) VALUES ($1, $2)", [pid, item.label]);
|
||||
}
|
||||
}
|
||||
|
||||
// HELPERS (Igual que siempre)
|
||||
await client.query("COMMIT");
|
||||
console.log("✅ Datos de España cargados correctamente.");
|
||||
|
||||
} catch (e) {
|
||||
await client.query("ROLLBACK");
|
||||
console.error("❌ Error Seeding:", e);
|
||||
}
|
||||
}
|
||||
|
||||
// HELPERS
|
||||
function normalizePhone(phone) { let p = String(phone || "").trim().replace(/\s+/g, "").replace(/-/g, ""); if (!p) return ""; if (!p.startsWith("+") && /^[6789]\d{8}$/.test(p)) return "+34" + p; return p; }
|
||||
function genCode6() { return String(Math.floor(100000 + Math.random() * 900000)); }
|
||||
function signToken(user) { const accountId = user.owner_id || user.id; return jwt.sign({ sub: user.id, email: user.email, phone: user.phone, role: user.role || 'operario', accountId }, JWT_SECRET, { expiresIn: "30d" }); }
|
||||
function authMiddleware(req, res, next) { const h = req.headers.authorization || ""; const token = h.startsWith("Bearer ") ? h.slice(7) : ""; if (!token) return res.status(401).json({ ok: false, error: "No token" }); try { req.user = jwt.verify(token, JWT_SECRET); next(); } catch { return res.status(401).json({ ok: false, error: "Token inválido" }); } }
|
||||
async function sendWhatsAppCode(phone, code) { if (!EVOLUTION_BASE_URL || !EVOLUTION_API_KEY) return; const url = `${EVOLUTION_BASE_URL.replace(/\/$/, "")}/message/sendText/${EVOLUTION_INSTANCE}`; await fetch(url, { method: "POST", headers: { "Content-Type": "application/json", "apikey": EVOLUTION_API_KEY }, body: JSON.stringify({ number: phone.replace("+", ""), text: `🔐 Código: *${code}*` }) }).catch(console.error); }
|
||||
|
||||
// RUTAS AUTH (Igual que siempre)
|
||||
// RUTAS AUTH
|
||||
app.post("/auth/register", async (req, res) => { const client = await pool.connect(); try { const { fullName, phone, address, dni, email, password } = req.body; const p = normalizePhone(phone); if (!fullName || !p || !email || !password) return res.status(400).json({ ok: false }); const passwordHash = await bcrypt.hash(password, 10); await client.query('BEGIN'); const insert = await client.query("INSERT INTO users (full_name, phone, address, dni, email, password_hash, role, owner_id) VALUES ($1, $2, $3, $4, $5, $6, 'admin', NULL) RETURNING id", [fullName, p, address, dni, email, passwordHash]); const userId = insert.rows[0].id; const code = genCode6(); const codeHash = await bcrypt.hash(code, 10); const expiresAt = new Date(Date.now() + 10 * 60 * 1000); await client.query("INSERT INTO login_codes (user_id, phone, code_hash, expires_at) VALUES ($1, $2, $3, $4)", [userId, p, codeHash, expiresAt]); await sendWhatsAppCode(p, code); await client.query('COMMIT'); res.json({ ok: true, phone: p }); } catch (e) { await client.query('ROLLBACK'); res.status(500).json({ ok: false }); } finally { client.release(); } });
|
||||
app.post("/auth/verify", async (req, res) => { try { const { phone, code } = req.body; const p = normalizePhone(phone); const q = await pool.query(`SELECT lc.*, u.id as uid, u.email, u.role, u.owner_id FROM login_codes lc JOIN users u ON lc.user_id = u.id WHERE lc.phone=$1 AND lc.consumed_at IS NULL AND lc.expires_at > NOW() ORDER BY lc.created_at DESC LIMIT 1`, [p]); if (q.rowCount === 0) return res.status(400).json({ ok: false }); const row = q.rows[0]; if (!(await bcrypt.compare(String(code), row.code_hash))) return res.status(400).json({ ok: false }); await pool.query("UPDATE login_codes SET consumed_at=NOW() WHERE id=$1", [row.id]); await pool.query("UPDATE users SET is_verified=TRUE WHERE id=$1", [row.uid]); res.json({ ok: true, token: signToken({ id: row.uid, email: row.email, phone: p, role: row.role, owner_id: row.owner_id }) }); } catch (e) { res.status(500).json({ ok: false }); } });
|
||||
app.post("/auth/login", async (req, res) => { try { const { email, password } = req.body; const q = await pool.query("SELECT * FROM users WHERE email=$1", [email]); if (q.rowCount === 0) return res.status(401).json({ ok: false }); let user = null; for (const u of q.rows) { if (await bcrypt.compare(password, u.password_hash)) { user = u; break; } } if (!user) return res.status(401).json({ ok: false }); res.json({ ok: true, token: signToken(user) }); } catch(e) { res.status(500).json({ ok: false }); } });
|
||||
app.post("/auth/forgot-password", async (req, res) => { try { const { dni, phone } = req.body; const p = normalizePhone(phone); const q = await pool.query("SELECT id FROM users WHERE dni=$1 AND phone=$2", [dni, p]); if (q.rowCount === 0) return res.status(404).json({ ok: false }); const uid = q.rows[0].id; const code = genCode6(); const hash = await bcrypt.hash(code, 10); await pool.query("INSERT INTO login_codes (user_id, phone, code_hash, purpose, expires_at) VALUES ($1, $2, $3, 'password_reset', $4)", [uid, p, hash, new Date(Date.now()+600000)]); await sendWhatsAppCode(p, code); res.json({ ok: true }); } catch (e) { res.status(500).json({ ok: false }); } });
|
||||
app.post("/auth/reset-password", async (req, res) => { const client = await pool.connect(); try { const { phone, code, newPassword } = req.body; const p = normalizePhone(phone); const q = await client.query(`SELECT lc.*, u.id as uid FROM login_codes lc JOIN users u ON lc.user_id=u.id WHERE lc.phone=$1 AND lc.purpose='password_reset' AND lc.consumed_at IS NULL AND lc.expires_at>NOW() ORDER BY lc.created_at DESC LIMIT 1`, [p]); if(q.rowCount===0) return res.status(400).json({ok:false}); const row=q.rows[0]; if(!(await bcrypt.compare(String(code), row.code_hash))) return res.status(400).json({ok:false}); const hash=await bcrypt.hash(newPassword, 10); await client.query('BEGIN'); await client.query("UPDATE users SET password_hash=$1 WHERE id=$2",[hash, row.uid]); await client.query("UPDATE login_codes SET consumed_at=NOW() WHERE id=$1",[row.id]); await client.query('COMMIT'); res.json({ok:true}); } catch(e){await client.query('ROLLBACK'); res.status(500).json({ok:false});} finally{client.release();} });
|
||||
|
||||
// =========================
|
||||
// API GEOGRÁFICA (ZONAS Y PUEBLOS)
|
||||
// =========================
|
||||
// APIS GEOGRÁFICAS
|
||||
app.get("/provinces", authMiddleware, async (req, res) => { try { const q = await pool.query("SELECT * FROM provinces ORDER BY name ASC"); res.json({ ok: true, provinces: q.rows }); } catch (e) { res.status(500).json({ ok: false }); } });
|
||||
app.get("/provinces/:id/towns", authMiddleware, async (req, res) => { try { const q = await pool.query("SELECT * FROM towns WHERE province_id=$1 ORDER BY name ASC", [req.params.id]); res.json({ ok: true, towns: q.rows }); } catch (e) { res.status(500).json({ ok: false }); } });
|
||||
|
||||
// 1. Obtener Provincias
|
||||
app.get("/provinces", authMiddleware, async (req, res) => {
|
||||
try { const q = await pool.query("SELECT * FROM provinces ORDER BY name ASC"); res.json({ ok: true, provinces: q.rows }); } catch (e) { res.status(500).json({ ok: false }); }
|
||||
});
|
||||
|
||||
// 2. Obtener Pueblos de una Provincia
|
||||
app.get("/provinces/:id/towns", authMiddleware, async (req, res) => {
|
||||
try {
|
||||
const q = await pool.query("SELECT * FROM towns WHERE province_id=$1 ORDER BY name ASC", [req.params.id]);
|
||||
res.json({ ok: true, towns: q.rows });
|
||||
} catch (e) { res.status(500).json({ ok: false }); }
|
||||
});
|
||||
|
||||
// 3. Crear/Listar Zonas (Con pueblos asociados)
|
||||
app.get("/zones", authMiddleware, async (req, res) => {
|
||||
try {
|
||||
const { province_id } = req.query;
|
||||
@@ -286,11 +284,9 @@ app.get("/zones", authMiddleware, async (req, res) => {
|
||||
(SELECT json_agg(t.name) FROM zone_towns zt JOIN towns t ON zt.town_id = t.id WHERE zt.zone_id = z.id) as towns_names
|
||||
FROM zones z
|
||||
WHERE (owner_id IS NULL OR owner_id=$1)`;
|
||||
|
||||
const params = [req.user.accountId];
|
||||
if(province_id) { query += " AND province_id=$2"; params.push(province_id); }
|
||||
query += " ORDER BY name ASC";
|
||||
|
||||
const q = await pool.query(query, params);
|
||||
res.json({ ok: true, zones: q.rows });
|
||||
} catch (e) { res.status(500).json({ ok: false }); }
|
||||
@@ -299,99 +295,57 @@ app.get("/zones", authMiddleware, async (req, res) => {
|
||||
app.post("/zones", authMiddleware, async (req, res) => {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
const { province_id, name, town_ids } = req.body; // town_ids es un array [1, 2, 5]
|
||||
const { province_id, name, town_ids } = req.body;
|
||||
if (!province_id || !name) return res.status(400).json({ ok: false });
|
||||
|
||||
await client.query('BEGIN');
|
||||
|
||||
// Crear Zona
|
||||
const q = await client.query("INSERT INTO zones (province_id, name, owner_id) VALUES ($1, $2, $3) RETURNING id", [province_id, name, req.user.accountId]);
|
||||
const zoneId = q.rows[0].id;
|
||||
|
||||
// Asociar Pueblos
|
||||
if (town_ids && Array.isArray(town_ids)) {
|
||||
for (const tid of town_ids) {
|
||||
await client.query("INSERT INTO zone_towns (zone_id, town_id) VALUES ($1, $2)", [zoneId, tid]);
|
||||
for (const tid of town_ids) await client.query("INSERT INTO zone_towns (zone_id, town_id) VALUES ($1, $2)", [zoneId, tid]);
|
||||
}
|
||||
}
|
||||
|
||||
await client.query('COMMIT');
|
||||
res.json({ ok: true });
|
||||
await client.query('COMMIT'); res.json({ ok: true });
|
||||
} catch (e) { await client.query('ROLLBACK'); res.status(500).json({ ok: false }); } finally { client.release(); }
|
||||
});
|
||||
|
||||
app.delete("/zones/:id", authMiddleware, async (req, res) => {
|
||||
try { await pool.query("DELETE FROM zones WHERE id=$1 AND owner_id=$2", [req.params.id, req.user.accountId]); res.json({ ok: true }); } catch (e) { res.status(500).json({ ok: false }); }
|
||||
});
|
||||
|
||||
// 4. Asignación Operarios <-> Zonas
|
||||
app.get("/zones/:id/operators", authMiddleware, async (req, res) => {
|
||||
try {
|
||||
const q = await pool.query("SELECT user_id FROM user_zones WHERE zone_id=$1", [req.params.id]);
|
||||
const assignedIds = q.rows.map(r => r.user_id);
|
||||
res.json({ ok: true, assignedIds });
|
||||
} catch (e) { res.status(500).json({ ok: false }); }
|
||||
});
|
||||
app.delete("/zones/:id", authMiddleware, async (req, res) => { try { await pool.query("DELETE FROM zones WHERE id=$1 AND owner_id=$2", [req.params.id, req.user.accountId]); res.json({ ok: true }); } catch (e) { res.status(500).json({ ok: false }); } });
|
||||
|
||||
app.get("/zones/:id/operators", authMiddleware, async (req, res) => { try { const q = await pool.query("SELECT user_id FROM user_zones WHERE zone_id=$1", [req.params.id]); const assignedIds = q.rows.map(r => r.user_id); res.json({ ok: true, assignedIds }); } catch (e) { res.status(500).json({ ok: false }); } });
|
||||
app.post("/zones/:id/assign", authMiddleware, async (req, res) => {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
const { operator_ids } = req.body;
|
||||
const zoneId = req.params.id;
|
||||
const { operator_ids } = req.body; const zoneId = req.params.id;
|
||||
await client.query('BEGIN');
|
||||
// Limpiamos solo para mis usuarios en esa zona
|
||||
await client.query("DELETE FROM user_zones WHERE zone_id=$1 AND user_id IN (SELECT id FROM users WHERE owner_id=$2)", [zoneId, req.user.accountId]);
|
||||
if (operator_ids && Array.isArray(operator_ids)) {
|
||||
for (const uid of operator_ids) {
|
||||
const check = await client.query("SELECT id FROM users WHERE id=$1 AND owner_id=$2", [uid, req.user.accountId]);
|
||||
if (check.rowCount > 0) {
|
||||
await client.query("INSERT INTO user_zones (user_id, zone_id) VALUES ($1, $2)", [uid, zoneId]);
|
||||
if (check.rowCount > 0) await client.query("INSERT INTO user_zones (user_id, zone_id) VALUES ($1, $2)", [uid, zoneId]);
|
||||
}
|
||||
}
|
||||
}
|
||||
await client.query('COMMIT');
|
||||
res.json({ ok: true });
|
||||
await client.query('COMMIT'); res.json({ ok: true });
|
||||
} catch (e) { await client.query('ROLLBACK'); res.status(500).json({ ok: false }); } finally { client.release(); }
|
||||
});
|
||||
|
||||
// ==========================================
|
||||
// 🚀 EL ENDPOINT MÁGICO (AUTO-ASIGNACIÓN)
|
||||
// ==========================================
|
||||
// AUTO-ASIGNACIÓN
|
||||
app.get("/towns/:id/auto-assign", authMiddleware, async (req, res) => {
|
||||
try {
|
||||
// 1. Averiguar la Zona de este pueblo (perteneciente a esta empresa o zona pública)
|
||||
const qZone = await pool.query(`
|
||||
SELECT z.id, z.name
|
||||
FROM zone_towns zt
|
||||
SELECT z.id, z.name FROM zone_towns zt
|
||||
JOIN zones z ON zt.zone_id = z.id
|
||||
WHERE zt.town_id = $1 AND (z.owner_id = $2 OR z.owner_id IS NULL)
|
||||
LIMIT 1
|
||||
`, [req.params.id, req.user.accountId]);
|
||||
|
||||
if (qZone.rowCount === 0) {
|
||||
return res.json({ ok: true, found: false }); // No hay zona para este pueblo
|
||||
}
|
||||
|
||||
if (qZone.rowCount === 0) return res.json({ ok: true, found: false });
|
||||
const zone = qZone.rows[0];
|
||||
|
||||
// 2. Averiguar qué operarios cubren esa zona
|
||||
const qOps = await pool.query(`
|
||||
SELECT u.id, u.full_name
|
||||
FROM user_zones uz
|
||||
JOIN users u ON uz.user_id = u.id
|
||||
WHERE uz.zone_id = $1
|
||||
SELECT u.id, u.full_name FROM user_zones uz
|
||||
JOIN users u ON uz.user_id = u.id WHERE uz.zone_id = $1
|
||||
`, [zone.id]);
|
||||
|
||||
res.json({
|
||||
ok: true,
|
||||
found: true,
|
||||
zone_name: zone.name,
|
||||
operators: qOps.rows
|
||||
});
|
||||
|
||||
} catch (e) {
|
||||
res.status(500).json({ ok: false, error: e.message });
|
||||
}
|
||||
res.json({ ok: true, found: true, zone_name: zone.name, operators: qOps.rows });
|
||||
} catch (e) { res.status(500).json({ ok: false, error: e.message }); }
|
||||
});
|
||||
|
||||
// OBTENER OPERARIOS
|
||||
|
||||
Reference in New Issue
Block a user