diff --git a/server.js b/server.js index 465f969..adc63d8 100644 --- a/server.js +++ b/server.js @@ -36,7 +36,7 @@ async function autoUpdateDB() { try { console.log("🔄 Verificando estructura DB..."); - // 1. TABLAS PRINCIPALES + // TABLAS PRINCIPALES (Usuarios, Clientes, Gremios...) await client.query(` CREATE TABLE IF NOT EXISTS users ( id SERIAL PRIMARY KEY, @@ -103,29 +103,14 @@ async function autoUpdateDB() { ); `); - // 2. TABLAS GEOGRÁFICAS (Mantenemos la estructura por si acaso, pero vacías) + // TABLAS DE ZONAS (Versión simplificada, sin pueblos) await client.query(` - CREATE TABLE IF NOT EXISTS provinces ( - id SERIAL PRIMARY KEY, - name TEXT UNIQUE NOT NULL - ); - CREATE TABLE IF NOT EXISTS towns ( - id SERIAL PRIMARY KEY, - province_id INT REFERENCES provinces(id) ON DELETE CASCADE, - name TEXT NOT NULL - ); CREATE TABLE IF NOT EXISTS zones ( id SERIAL PRIMARY KEY, - province_id INT REFERENCES provinces(id) ON DELETE CASCADE, name TEXT NOT NULL, owner_id INT, created_at TIMESTAMP DEFAULT NOW() ); - 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) - ); 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, @@ -133,7 +118,7 @@ async function autoUpdateDB() { ); `); - // 3. TABLA SERVICIOS + // TABLA SERVICIOS await client.query(` CREATE TABLE IF NOT EXISTS services ( id SERIAL PRIMARY KEY, @@ -171,7 +156,7 @@ async function autoUpdateDB() { ); `); - // 4. PARCHE DE REPARACIÓN (Asegura columnas) + // PARCHE DE REPARACIÓN (Mantenido por seguridad) 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; @@ -217,10 +202,14 @@ app.post("/auth/login", async (req, res) => { try { const { email, password } = 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();} }); -// DATOS MAESTROS + +// ========================================== +// 🛠️ GESTIÓN DE ESTADOS (CRUD COMPLETO) +// ========================================== 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]); + // Si no hay estados, crea los default 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]); @@ -229,11 +218,32 @@ app.get("/statuses", authMiddleware, async (req, res) => { res.json({ ok: true, statuses: q.rows }); } catch (e) { res.status(500).json({ ok: false }); } }); + +// NUEVO: CREAR ESTADO +app.post("/statuses", authMiddleware, async (req, res) => { + try { + const { name, color } = req.body; + if(!name) return res.status(400).json({ok:false, error: "Nombre requerido"}); + await pool.query("INSERT INTO service_statuses (owner_id, name, color) VALUES ($1, $2, $3)", [req.user.accountId, name, color || 'gray']); + res.json({ ok: true }); + } catch(e) { res.status(500).json({ ok: false }); } +}); + +// NUEVO: BORRAR ESTADO +app.delete("/statuses/:id", authMiddleware, async (req, res) => { + try { + await pool.query("DELETE FROM service_statuses 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 }); } +}); + +// CLIENTES, COMPAÑIAS, GREMIOS 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 }); } }); +app.delete("/companies/:id", authMiddleware, async (req, res) => { try { await pool.query("DELETE FROM companies 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 }); } }); // OBTENER OPERARIOS POR GREMIO app.get("/operators", authMiddleware, async (req, res) => { @@ -248,6 +258,13 @@ app.get("/operators", authMiddleware, async (req, res) => { } catch (e) { res.status(500).json({ ok: false, error: e.message }); } }); +// ZONAS (MANUAL) +app.get("/zones", authMiddleware, async (req, res) => { try { const q = await pool.query("SELECT * FROM zones WHERE owner_id=$1 ORDER BY name ASC", [req.user.accountId]); res.json({ ok: true, zones: q.rows }); } catch (e) { res.status(500).json({ ok: false }); } }); +app.post("/zones", authMiddleware, async (req, res) => { try { const { name } = req.body; await pool.query("INSERT INTO zones (name, owner_id) VALUES ($1, $2)", [name, req.user.accountId]); res.json({ ok: true }); } 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]); res.json({ ok: true, assignedIds: q.rows.map(r=>r.user_id) }); } 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; await client.query('BEGIN'); await client.query("DELETE FROM user_zones WHERE zone_id=$1", [req.params.id]); if(operator_ids) for(const uid of operator_ids) await client.query("INSERT INTO user_zones (user_id, zone_id) VALUES ($1, $2)", [uid, req.params.id]); await client.query('COMMIT'); res.json({ok:true}); } catch(e){ await client.query('ROLLBACK'); res.status(500).json({ok:false}); } finally { client.release(); } }); + // SERVICIOS CRUD app.get("/services", authMiddleware, async (req, res) => { try { @@ -287,27 +304,21 @@ app.put("/services/:id/status", authMiddleware, async (req, res) => { } catch (e) { await client.query('ROLLBACK'); res.status(500).json({ ok: false }); } finally { client.release(); } }); -// CREAR SERVICIO (SANITIZADO) app.post("/services", authMiddleware, async (req, res) => { const client = await pool.connect(); try { const { phone, name, address, email, description, scheduled_date, scheduled_time, duration, is_urgent, is_company, company_id, company_ref, internal_notes, client_notes, status_id, guild_id, assigned_to } = req.body; const p = normalizePhone(phone); - - // SANITIZAR ENTEROS (Evitar error invalid input syntax for type integer: "") const safeDuration = (duration === "" || duration === null) ? 30 : duration; const safeCompanyId = (company_id === "" || company_id === null) ? null : company_id; const safeGuildId = (guild_id === "" || guild_id === null) ? null : guild_id; const safeAssignedTo = (assigned_to === "" || assigned_to === null) ? null : assigned_to; - await client.query('BEGIN'); - let finalStatus = status_id; if (!finalStatus) { const def = await client.query("SELECT id FROM service_statuses WHERE owner_id=$1 AND is_default=TRUE LIMIT 1", [req.user.accountId]); finalStatus = def.rows[0]?.id; } - let clientId; const cCheck = await client.query("SELECT id, addresses FROM clients WHERE phone=$1 AND owner_id=$2", [p, req.user.accountId]); if (cCheck.rowCount > 0) { @@ -318,103 +329,35 @@ app.post("/services", authMiddleware, async (req, res) => { const newC = await client.query("INSERT INTO clients (owner_id, full_name, phone, email, addresses) VALUES ($1, $2, $3, $4, $5) RETURNING id", [req.user.accountId, name, p, email, JSON.stringify([address])]); clientId = newC.rows[0].id; } - - const insert = await client.query(` - INSERT INTO services ( - owner_id, client_id, status_id, contact_phone, contact_name, address, email, - description, scheduled_date, scheduled_time, duration_minutes, is_urgent, - is_company, company_id, company_ref, internal_notes, client_notes, title, - guild_id, assigned_to - ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20) - RETURNING id - `, [ - req.user.accountId, clientId, finalStatus, p, name, address, email, - description, scheduled_date || 'NOW()', scheduled_time || 'NOW()', safeDuration, is_urgent || false, - is_company || false, safeCompanyId, company_ref, internal_notes, client_notes, name + " - Svc", - safeGuildId, safeAssignedTo - ]); - + const insert = await client.query(`INSERT INTO services (owner_id, client_id, status_id, contact_phone, contact_name, address, email, description, scheduled_date, scheduled_time, duration_minutes, is_urgent, is_company, company_id, company_ref, internal_notes, client_notes, title, guild_id, assigned_to) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20) RETURNING id`, [req.user.accountId, clientId, finalStatus, p, name, address, email, description, scheduled_date || 'NOW()', scheduled_time || 'NOW()', safeDuration, is_urgent || false, is_company || false, safeCompanyId, company_ref, internal_notes, client_notes, name + " - Svc", safeGuildId, safeAssignedTo]); await client.query("INSERT INTO service_logs (service_id, user_id, new_status_id, comment) VALUES ($1, $2, $3, 'Servicio Creado')", [insert.rows[0].id, req.user.sub, finalStatus]); - - await client.query('COMMIT'); - res.json({ ok: true }); + await client.query('COMMIT'); res.json({ ok: true }); } catch (e) { await client.query('ROLLBACK'); console.error(e); res.status(500).json({ ok: false, error: e.message }); } finally { client.release(); } }); -// EDITAR SERVICIO (SANITIZADO) app.put("/services/:id", authMiddleware, async (req, res) => { const client = await pool.connect(); try { - const { - name, address, email, description, - scheduled_date, scheduled_time, duration, is_urgent, - is_company, company_id, company_ref, - internal_notes, client_notes, - guild_id, assigned_to - } = req.body; - + const { name, address, email, description, scheduled_date, scheduled_time, duration, is_urgent, is_company, company_id, company_ref, internal_notes, client_notes, guild_id, assigned_to } = req.body; const safeDuration = (duration === "" || duration === null) ? 30 : duration; const safeCompanyId = (company_id === "" || company_id === null) ? null : company_id; const safeGuildId = (guild_id === "" || guild_id === null) ? null : guild_id; const safeAssignedTo = (assigned_to === "" || assigned_to === null) ? null : assigned_to; - await client.query('BEGIN'); - await client.query(` - UPDATE services SET - contact_name=$1, address=$2, email=$3, description=$4, - scheduled_date=$5, scheduled_time=$6, duration_minutes=$7, is_urgent=$8, - is_company=$9, company_id=$10, company_ref=$11, - internal_notes=$12, client_notes=$13, - guild_id=$14, assigned_to=$15 - WHERE id=$16 AND owner_id=$17 - `, [ - name, address, email, description, - scheduled_date, scheduled_time, safeDuration, is_urgent, - is_company, safeCompanyId, company_ref, - internal_notes, client_notes, - safeGuildId, safeAssignedTo, - req.params.id, req.user.accountId - ]); - + await client.query(`UPDATE services SET contact_name=$1, address=$2, email=$3, description=$4, scheduled_date=$5, scheduled_time=$6, duration_minutes=$7, is_urgent=$8, is_company=$9, company_id=$10, company_ref=$11, internal_notes=$12, client_notes=$13, guild_id=$14, assigned_to=$15 WHERE id=$16 AND owner_id=$17`, [name, address, email, description, scheduled_date, scheduled_time, safeDuration, is_urgent, is_company, safeCompanyId, company_ref, internal_notes, client_notes, safeGuildId, safeAssignedTo, req.params.id, req.user.accountId]); await client.query("INSERT INTO service_logs (service_id, user_id, new_status_id, comment) VALUES ($1, $2, (SELECT status_id FROM services WHERE id=$1), 'Datos editados')", [req.params.id, req.user.sub]); await client.query('COMMIT'); res.json({ ok: true }); } catch (e) { await client.query('ROLLBACK'); console.error(e); res.status(500).json({ ok: false }); } finally { client.release(); } }); - app.delete("/services/:id", authMiddleware, async (req, res) => { try { await pool.query("DELETE FROM services 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 }); } }); // RUTAS USERS/GREMIOS app.get("/guilds", authMiddleware, async (req, res) => { try { const q = await pool.query("SELECT * FROM guilds WHERE owner_id=$1 ORDER BY name ASC", [req.user.accountId]); res.json({ ok: true, guilds: q.rows }); } catch (e) { res.status(500).json({ ok: false }); } }); app.post("/guilds", authMiddleware, async (req, res) => { try { const { name } = req.body; await pool.query("INSERT INTO guilds (name, owner_id) VALUES ($1, $2)", [name, req.user.accountId]); res.json({ ok: true }); } catch (e) { res.status(500).json({ ok: false }); } }); app.delete("/guilds/:id", authMiddleware, async (req, res) => { try { await pool.query("DELETE FROM guilds 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("/admin/users", authMiddleware, async (req, res) => { try { const q = await pool.query(`SELECT u.id, u.full_name, u.email, u.phone, u.role, COALESCE(json_agg(g.id) FILTER (WHERE g.id IS NOT NULL), '[]') as guilds FROM users u LEFT JOIN user_guilds ug ON u.id=ug.user_id LEFT JOIN guilds g ON ug.guild_id=g.id WHERE u.owner_id=$1 GROUP BY u.id ORDER BY u.id DESC`, [req.user.accountId]); res.json({ ok: true, users: q.rows }); } catch (e) { res.status(500).json({ ok: false }); } }); -app.post("/admin/users", authMiddleware, async (req, res) => { - const client = await pool.connect(); - try { - const { fullName, email, password, role, guilds, phone } = req.body; - if (!email || !password || !fullName || !phone) return res.status(400).json({ ok: false }); - const p = normalizePhone(phone); const hash = await bcrypt.hash(password, 10); - const check = await client.query("SELECT id FROM users WHERE (phone=$1 OR email=$2) AND owner_id=$3", [p, email, req.user.accountId]); - if (check.rowCount > 0) return res.status(400).json({ ok: false, error: "Duplicado" }); - await client.query('BEGIN'); - const insert = await client.query("INSERT INTO users (full_name, email, password_hash, role, phone, is_verified, owner_id) VALUES ($1, $2, $3, $4, $5, TRUE, $6) RETURNING id", [fullName, email, hash, role || 'operario', p, req.user.accountId]); - const uid = insert.rows[0].id; - if (guilds) for (const gid of guilds) await client.query("INSERT INTO user_guilds (user_id, guild_id) VALUES ($1, $2)", [uid, gid]); - await client.query('COMMIT'); res.json({ ok: true }); - } catch (e) { await client.query('ROLLBACK'); res.status(500).json({ ok: false }); } finally { client.release(); } -}); -app.put("/admin/users/:id", authMiddleware, async (req, res) => { - const client = await pool.connect(); - try { - const userId = req.params.id; const { fullName, email, phone, role, guilds, password } = req.body; const p = normalizePhone(phone); - await client.query('BEGIN'); - if(password) { const hash = await bcrypt.hash(password, 10); await client.query("UPDATE users SET full_name=$1, email=$2, phone=$3, role=$4, password_hash=$5 WHERE id=$6", [fullName, email, p, role, hash, userId]); } - else { await client.query("UPDATE users SET full_name=$1, email=$2, phone=$3, role=$4 WHERE id=$5", [fullName, email, p, role, userId]); } - if (guilds && Array.isArray(guilds)) { await client.query("DELETE FROM user_guilds WHERE user_id=$1", [userId]); for (const gid of guilds) await client.query("INSERT INTO user_guilds (user_id, guild_id) VALUES ($1, $2)", [userId, gid]); } - await client.query('COMMIT'); res.json({ ok: true }); - } catch (e) { await client.query('ROLLBACK'); res.status(500).json({ ok: false }); } finally { client.release(); } -}); +app.post("/admin/users", authMiddleware, async (req, res) => { const client = await pool.connect(); try { const { fullName, email, password, role, guilds, phone } = req.body; if (!email || !password || !fullName || !phone) return res.status(400).json({ ok: false }); const p = normalizePhone(phone); const hash = await bcrypt.hash(password, 10); const check = await client.query("SELECT id FROM users WHERE (phone=$1 OR email=$2) AND owner_id=$3", [p, email, req.user.accountId]); if (check.rowCount > 0) return res.status(400).json({ ok: false, error: "Duplicado" }); await client.query('BEGIN'); const insert = await client.query("INSERT INTO users (full_name, email, password_hash, role, phone, is_verified, owner_id) VALUES ($1, $2, $3, $4, $5, TRUE, $6) RETURNING id", [fullName, email, hash, role || 'operario', p, req.user.accountId]); const uid = insert.rows[0].id; if (guilds) for (const gid of guilds) await client.query("INSERT INTO user_guilds (user_id, guild_id) VALUES ($1, $2)", [uid, gid]); await client.query('COMMIT'); res.json({ ok: true }); } catch (e) { await client.query('ROLLBACK'); res.status(500).json({ ok: false }); } finally { client.release(); } }); +app.put("/admin/users/:id", authMiddleware, async (req, res) => { const client = await pool.connect(); try { const userId = req.params.id; const { fullName, email, phone, role, guilds, password } = req.body; const p = normalizePhone(phone); await client.query('BEGIN'); if(password) { const hash = await bcrypt.hash(password, 10); await client.query("UPDATE users SET full_name=$1, email=$2, phone=$3, role=$4, password_hash=$5 WHERE id=$6", [fullName, email, p, role, hash, userId]); } else { await client.query("UPDATE users SET full_name=$1, email=$2, phone=$3, role=$4 WHERE id=$5", [fullName, email, p, role, userId]); } if (guilds && Array.isArray(guilds)) { await client.query("DELETE FROM user_guilds WHERE user_id=$1", [userId]); for (const gid of guilds) await client.query("INSERT INTO user_guilds (user_id, guild_id) VALUES ($1, $2)", [userId, gid]); } 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("/admin/users/:id", authMiddleware, async (req, res) => { try { await pool.query("DELETE FROM users 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 }); } }); const port = process.env.PORT || 3000;