Actualizar server.js
This commit is contained in:
129
server.js
129
server.js
@@ -3,6 +3,7 @@ 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();
|
||||
@@ -175,27 +176,8 @@ async function autoUpdateDB() {
|
||||
);
|
||||
`);
|
||||
|
||||
// 4. POBLAR DATOS GEOGRÁFICOS BÁSICOS (EJEMPLO)
|
||||
const provCheck = await client.query("SELECT COUNT(*) FROM provinces");
|
||||
if (parseInt(provCheck.rows[0].count) === 0) {
|
||||
console.log("🇪🇸 Inicializando Provincias y Poblaciones de ejemplo...");
|
||||
|
||||
// Insertamos un par de provincias para probar
|
||||
const cadizRes = await client.query("INSERT INTO provinces (name) VALUES ('Cádiz') RETURNING id");
|
||||
const madridRes = await client.query("INSERT INTO provinces (name) VALUES ('Madrid') RETURNING id");
|
||||
|
||||
const cadizId = cadizRes.rows[0].id;
|
||||
const madridId = madridRes.rows[0].id;
|
||||
|
||||
// Insertamos algunas poblaciones de ejemplo (EN PRODUCCIÓN ESTO SE HACE CON SQL MASIVO)
|
||||
const townsCadiz = ["Cádiz Capital", "Jerez de la Frontera", "Algeciras", "San Fernando", "El Puerto de Santa María", "Chiclana", "Sanlúcar", "La Línea", "Puerto Real", "Rota", "Tarifa", "Conil"];
|
||||
const townsMadrid = ["Madrid Capital", "Móstoles", "Alcalá de Henares", "Fuenlabrada", "Leganés", "Getafe"];
|
||||
|
||||
for (const t of townsCadiz) await client.query("INSERT INTO towns (province_id, name) VALUES ($1, $2)", [cadizId, t]);
|
||||
for (const t of townsMadrid) await client.query("INSERT INTO towns (province_id, name) VALUES ($1, $2)", [madridId, t]);
|
||||
|
||||
console.log("✅ Datos geográficos de ejemplo cargados.");
|
||||
}
|
||||
// 4. SEEDING (CARGA DE DATOS INE)
|
||||
await seedSpainData(client);
|
||||
|
||||
// 5. PARCHE DE REPARACIÓN DE COLUMNAS
|
||||
await client.query(`
|
||||
@@ -204,7 +186,22 @@ async function autoUpdateDB() {
|
||||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='status_id') THEN ALTER TABLE services ADD COLUMN status_id INT REFERENCES service_statuses(id) ON DELETE SET NULL; END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='guild_id') THEN ALTER TABLE services ADD COLUMN guild_id INT REFERENCES guilds(id) ON DELETE SET NULL; END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='assigned_to') THEN ALTER TABLE services ADD COLUMN assigned_to INT REFERENCES users(id) ON DELETE SET NULL; END IF;
|
||||
-- (Resto de columnas omitidas por brevedad, el bloque anterior ya las reparó, pero mantenemos limpieza constraints)
|
||||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='contact_phone') THEN ALTER TABLE services ADD COLUMN contact_phone TEXT; END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='contact_name') THEN ALTER TABLE services ADD COLUMN contact_name TEXT; END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='address') THEN ALTER TABLE services ADD COLUMN address TEXT; END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='email') THEN ALTER TABLE services ADD COLUMN email TEXT; END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='title') THEN ALTER TABLE services ADD COLUMN title TEXT; END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='description') THEN ALTER TABLE services ADD COLUMN description TEXT; END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='scheduled_date') THEN ALTER TABLE services ADD COLUMN scheduled_date DATE DEFAULT CURRENT_DATE; END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='scheduled_time') THEN ALTER TABLE services ADD COLUMN scheduled_time TIME DEFAULT CURRENT_TIME; END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='duration_minutes') THEN ALTER TABLE services ADD COLUMN duration_minutes INT DEFAULT 30; END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='is_urgent') THEN ALTER TABLE services ADD COLUMN is_urgent BOOLEAN DEFAULT FALSE; END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='company_id') THEN ALTER TABLE services ADD COLUMN company_id INT REFERENCES companies(id) ON DELETE SET NULL; END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='is_company') THEN ALTER TABLE services ADD COLUMN is_company BOOLEAN DEFAULT FALSE; END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='company_ref') THEN ALTER TABLE services ADD COLUMN company_ref TEXT; END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='internal_notes') THEN ALTER TABLE services ADD COLUMN internal_notes TEXT; END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='client_notes') THEN ALTER TABLE services ADD COLUMN client_notes TEXT; END IF;
|
||||
|
||||
BEGIN ALTER TABLE users DROP CONSTRAINT IF EXISTS users_phone_key; EXCEPTION WHEN OTHERS THEN NULL; END;
|
||||
BEGIN ALTER TABLE users DROP CONSTRAINT IF EXISTS users_email_key; EXCEPTION WHEN OTHERS THEN NULL; END;
|
||||
END $$;
|
||||
@@ -214,6 +211,41 @@ async function autoUpdateDB() {
|
||||
} catch (e) { console.error("❌ Error DB:", e); } finally { client.release(); }
|
||||
}
|
||||
|
||||
// 🌍 CARGA MASIVA INE
|
||||
async function seedSpainData(client) {
|
||||
try {
|
||||
const count = await client.query("SELECT COUNT(*) FROM provinces");
|
||||
if (parseInt(count.rows[0].count) > 0) return;
|
||||
|
||||
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();
|
||||
|
||||
await client.query("BEGIN");
|
||||
const provincesSet = new Set();
|
||||
listFull.forEach(item => provincesSet.add(item.parent_op));
|
||||
const provinceMap = new Map();
|
||||
|
||||
for (const provName of provincesSet) {
|
||||
const res = await client.query("INSERT INTO provinces (name) VALUES ($1) RETURNING id", [provName]);
|
||||
provinceMap.set(provName, res.rows[0].id);
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
// HELPERS (Igual que siempre)
|
||||
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)); }
|
||||
@@ -225,6 +257,8 @@ async function sendWhatsAppCode(phone, code) { if (!EVOLUTION_BASE_URL || !EVOLU
|
||||
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)
|
||||
@@ -320,19 +354,50 @@ app.post("/zones/:id/assign", authMiddleware, async (req, res) => {
|
||||
} catch (e) { await client.query('ROLLBACK'); res.status(500).json({ ok: false }); } finally { client.release(); }
|
||||
});
|
||||
|
||||
// OBTENER OPERARIOS (Sin filtro gremio para esta vista, o con filtro)
|
||||
app.get("/operators", authMiddleware, async (req, res) => {
|
||||
// ==========================================
|
||||
// 🚀 EL ENDPOINT MÁGICO (AUTO-ASIGNACIÓN)
|
||||
// ==========================================
|
||||
app.get("/towns/:id/auto-assign", authMiddleware, async (req, res) => {
|
||||
try {
|
||||
const q = await pool.query("SELECT id, full_name FROM users WHERE owner_id=$1 AND role='operario' ORDER BY full_name ASC", [req.user.accountId]);
|
||||
res.json({ ok: true, operators: q.rows });
|
||||
} catch (e) { res.status(500).json({ ok: false }); }
|
||||
// 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
|
||||
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
|
||||
}
|
||||
|
||||
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
|
||||
`, [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 });
|
||||
}
|
||||
});
|
||||
|
||||
// --- RESTO DE APIS (SERVICIOS, ESTADOS, ETC - MANTENIDOS IGUAL) ---
|
||||
app.get("/statuses", authMiddleware, async (req, res) => { try { let q = await pool.query("SELECT * FROM service_statuses WHERE owner_id=$1 ORDER BY id ASC", [req.user.accountId]); if (q.rowCount === 0) { const defaults = [{name:'Pendiente',c:'gray',d:true,f:false},{name:'En Proceso',c:'blue',d:false,f:false},{name:'Terminado',c:'green',d:false,f:true},{name:'Cancelado',c:'red',d:false,f:true}]; for (const s of defaults) await pool.query("INSERT INTO service_statuses (owner_id,name,color,is_default,is_final) VALUES ($1,$2,$3,$4,$5)", [req.user.accountId,s.name,s.c,s.d,s.f]); q = await pool.query("SELECT * FROM service_statuses WHERE owner_id=$1 ORDER BY id ASC", [req.user.accountId]); } res.json({ ok: true, statuses: q.rows }); } catch (e) { res.status(500).json({ ok: false }); } });
|
||||
app.get("/clients/search", authMiddleware, async (req, res) => { try { const { phone } = req.query; const p = normalizePhone(phone); if(!p) return res.json({ok:true,client:null}); const q = await pool.query("SELECT * FROM clients WHERE phone=$1 AND owner_id=$2 LIMIT 1", [p, req.user.accountId]); res.json({ ok: true, client: q.rows[0] || null }); } catch (e) { res.status(500).json({ ok: false }); } });
|
||||
app.get("/companies", authMiddleware, async (req, res) => { try { const q = await pool.query("SELECT * FROM companies WHERE owner_id=$1 ORDER BY name ASC", [req.user.accountId]); res.json({ ok: true, companies: q.rows }); } catch (e) { res.status(500).json({ ok: false }); } });
|
||||
app.post("/companies", authMiddleware, async (req, res) => { try { const { name } = req.body; await pool.query("INSERT INTO companies (name, owner_id) VALUES ($1, $2)", [name, req.user.accountId]); res.json({ ok: true }); } catch (e) { res.status(500).json({ ok: false }); } });
|
||||
// OBTENER OPERARIOS
|
||||
app.get("/operators", authMiddleware, async (req, res) => { try { const q = await pool.query("SELECT id, full_name FROM users WHERE owner_id=$1 AND role='operario' ORDER BY full_name ASC", [req.user.accountId]); res.json({ ok: true, operators: q.rows }); } catch (e) { res.status(500).json({ ok: false }); } });
|
||||
|
||||
// SERVICIOS CRUD
|
||||
app.get("/services", authMiddleware, async (req, res) => { try { const q = await pool.query(`SELECT s.*, st.name as status_name, st.color as status_color, c.name as company_name, g.name as guild_name, u.full_name as assigned_name FROM services s LEFT JOIN service_statuses st ON s.status_id = st.id LEFT JOIN companies c ON s.company_id = c.id LEFT JOIN guilds g ON s.guild_id = g.id LEFT JOIN users u ON s.assigned_to = u.id WHERE s.owner_id=$1 ORDER BY s.created_at DESC`, [req.user.accountId]); res.json({ ok: true, services: q.rows }); } catch (e) { res.status(500).json({ ok: false }); } });
|
||||
app.get("/services/:id", authMiddleware, async (req, res) => { try { const q = await pool.query(`SELECT * FROM services WHERE id=$1 AND owner_id=$2`, [req.params.id, req.user.accountId]); res.json({ ok: true, service: q.rows[0] }); } catch (e) { res.status(500).json({ ok: false }); } });
|
||||
app.get("/services/:id/logs", authMiddleware, async (req, res) => { try { const q = await pool.query(`SELECT l.*, u.full_name as user_name, s2.name as new_status, s2.color as new_color FROM service_logs l LEFT JOIN users u ON l.user_id=u.id LEFT JOIN service_statuses s2 ON l.new_status_id=s2.id WHERE l.service_id=$1 ORDER BY l.created_at DESC`, [req.params.id]); res.json({ ok: true, logs: q.rows }); } catch (e) { res.status(500).json({ ok: false }); } });
|
||||
|
||||
Reference in New Issue
Block a user