Actualizar server.js
This commit is contained in:
548
server.js
548
server.js
@@ -36,6 +36,7 @@ async function autoUpdateDB() {
|
|||||||
try {
|
try {
|
||||||
console.log("🔄 Verificando estructura DB...");
|
console.log("🔄 Verificando estructura DB...");
|
||||||
|
|
||||||
|
// TABLAS PRINCIPALES
|
||||||
await client.query(`
|
await client.query(`
|
||||||
CREATE TABLE IF NOT EXISTS users (
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
id SERIAL PRIMARY KEY,
|
id SERIAL PRIMARY KEY,
|
||||||
@@ -101,6 +102,17 @@ async function autoUpdateDB() {
|
|||||||
created_at TIMESTAMP DEFAULT NOW()
|
created_at TIMESTAMP DEFAULT NOW()
|
||||||
);
|
);
|
||||||
|
|
||||||
|
-- TABLA DE PLANTILLAS (NUEVO)
|
||||||
|
CREATE TABLE IF NOT EXISTS message_templates (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
owner_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
type TEXT NOT NULL, -- 'welcome', 'no_contact', 'appointment', 'update', 'on_way', 'survey'
|
||||||
|
content TEXT,
|
||||||
|
created_at TIMESTAMP DEFAULT NOW(),
|
||||||
|
UNIQUE(owner_id, type)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Zonas
|
||||||
CREATE TABLE IF NOT EXISTS zones (
|
CREATE TABLE IF NOT EXISTS zones (
|
||||||
id SERIAL PRIMARY KEY,
|
id SERIAL PRIMARY KEY,
|
||||||
name TEXT NOT NULL,
|
name TEXT NOT NULL,
|
||||||
@@ -183,9 +195,9 @@ async function autoUpdateDB() {
|
|||||||
|
|
||||||
// HELPERS
|
// 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 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 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" }); } }
|
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" }); } }
|
||||||
|
function genCode6() { return String(Math.floor(100000 + Math.random() * 900000)); }
|
||||||
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); }
|
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
|
// RUTAS AUTH
|
||||||
@@ -195,10 +207,7 @@ 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/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();} });
|
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();} });
|
||||||
|
|
||||||
|
// GESTIÓN DE ESTADOS
|
||||||
// ==========================================
|
|
||||||
// 🛠️ GESTIÓN DE ESTADOS (CRUD SEGURO)
|
|
||||||
// ==========================================
|
|
||||||
app.get("/statuses", authMiddleware, async (req, res) => {
|
app.get("/statuses", authMiddleware, async (req, res) => {
|
||||||
try {
|
try {
|
||||||
let q = await pool.query("SELECT * FROM service_statuses WHERE owner_id=$1 ORDER BY id ASC", [req.user.accountId]);
|
let q = await pool.query("SELECT * FROM service_statuses WHERE owner_id=$1 ORDER BY id ASC", [req.user.accountId]);
|
||||||
@@ -210,7 +219,6 @@ app.get("/statuses", authMiddleware, async (req, res) => {
|
|||||||
res.json({ ok: true, statuses: q.rows });
|
res.json({ ok: true, statuses: q.rows });
|
||||||
} catch (e) { res.status(500).json({ ok: false }); }
|
} catch (e) { res.status(500).json({ ok: false }); }
|
||||||
});
|
});
|
||||||
|
|
||||||
app.post("/statuses", authMiddleware, async (req, res) => {
|
app.post("/statuses", authMiddleware, async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { name, color } = req.body;
|
const { name, color } = req.body;
|
||||||
@@ -219,157 +227,64 @@ app.post("/statuses", authMiddleware, async (req, res) => {
|
|||||||
res.json({ ok: true });
|
res.json({ ok: true });
|
||||||
} catch(e) { res.status(500).json({ ok: false }); }
|
} catch(e) { res.status(500).json({ ok: false }); }
|
||||||
});
|
});
|
||||||
|
|
||||||
// 🔥 BORRADO SEGURO DE ESTADOS 🔥
|
|
||||||
app.delete("/statuses/:id", authMiddleware, async (req, res) => {
|
app.delete("/statuses/:id", authMiddleware, async (req, res) => {
|
||||||
const client = await pool.connect();
|
const client = await pool.connect();
|
||||||
try {
|
try {
|
||||||
const statusId = req.params.id;
|
const statusId = req.params.id; const accountId = req.user.accountId;
|
||||||
const accountId = req.user.accountId;
|
|
||||||
|
|
||||||
// 1. Comprobar si hay servicios usando este estado
|
|
||||||
const check = await client.query("SELECT COUNT(*) FROM services WHERE status_id = $1 AND owner_id = $2", [statusId, accountId]);
|
const check = await client.query("SELECT COUNT(*) FROM services WHERE status_id = $1 AND owner_id = $2", [statusId, accountId]);
|
||||||
const usageCount = parseInt(check.rows[0].count);
|
const usageCount = parseInt(check.rows[0].count);
|
||||||
|
if (usageCount > 0) return res.status(400).json({ ok: false, error: `No se puede borrar: Este estado se usa en ${usageCount} servicios.` });
|
||||||
if (usageCount > 0) {
|
|
||||||
// Devolvemos 400 Bad Request con un mensaje claro
|
|
||||||
return res.status(400).json({
|
|
||||||
ok: false,
|
|
||||||
error: `No se puede borrar: Este estado se usa en ${usageCount} servicios.`
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. Si no se usa, lo borramos tranquilamente
|
|
||||||
const del = await client.query("DELETE FROM service_statuses WHERE id=$1 AND owner_id=$2", [statusId, accountId]);
|
const del = await client.query("DELETE FROM service_statuses WHERE id=$1 AND owner_id=$2", [statusId, accountId]);
|
||||||
|
if (del.rowCount === 0) return res.status(404).json({ ok: false, error: "Estado no encontrado" });
|
||||||
if (del.rowCount === 0) {
|
|
||||||
return res.status(404).json({ ok: false, error: "Estado no encontrado" });
|
|
||||||
}
|
|
||||||
|
|
||||||
res.json({ ok: true });
|
res.json({ ok: true });
|
||||||
} catch(e) {
|
} catch(e) { res.status(500).json({ ok: false, error: "Error interno" }); } finally { client.release(); }
|
||||||
console.error("Error borrando estado:", e);
|
|
||||||
res.status(500).json({ ok: false, error: "Error interno del servidor" });
|
|
||||||
} finally {
|
|
||||||
client.release();
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// CLIENTES, COMPAÑIAS, GREMIOS
|
// ==========================================
|
||||||
app.get("/clients/search", authMiddleware, async (req, res) => {
|
// 📄 GESTIÓN DE PLANTILLAS (NUEVO)
|
||||||
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("/templates", authMiddleware, async (req, res) => {
|
||||||
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
|
|
||||||
app.get("/operators", authMiddleware, async (req, res) => {
|
|
||||||
try {
|
try {
|
||||||
const { guild_id } = req.query;
|
const q = await pool.query("SELECT * FROM message_templates WHERE owner_id=$1", [req.user.accountId]);
|
||||||
let query = `SELECT u.id, u.full_name FROM users u JOIN user_guilds ug ON u.id = ug.user_id WHERE u.owner_id = $1 AND u.role = 'operario'`;
|
res.json({ ok: true, templates: q.rows });
|
||||||
const params = [req.user.accountId];
|
} catch (e) { res.status(500).json({ ok: false }); }
|
||||||
if (guild_id) { query += ` AND ug.guild_id = $2`; params.push(guild_id); }
|
|
||||||
query += ` GROUP BY u.id ORDER BY u.full_name ASC`;
|
|
||||||
const q = await pool.query(query, params);
|
|
||||||
res.json({ ok: true, operators: q.rows });
|
|
||||||
} catch (e) { res.status(500).json({ ok: false, error: e.message }); }
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// ZONAS (MANUAL)
|
app.post("/templates", authMiddleware, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { type, content } = req.body;
|
||||||
|
// Upsert: Si existe actualiza, si no crea
|
||||||
|
await pool.query(`
|
||||||
|
INSERT INTO message_templates (owner_id, type, content)
|
||||||
|
VALUES ($1, $2, $3)
|
||||||
|
ON CONFLICT (owner_id, type)
|
||||||
|
DO UPDATE SET content = EXCLUDED.content
|
||||||
|
`, [req.user.accountId, type, content]);
|
||||||
|
res.json({ ok: true });
|
||||||
|
} catch (e) { console.error(e); res.status(500).json({ ok: false }); }
|
||||||
|
});
|
||||||
|
|
||||||
|
// ZONAS Y OTROS
|
||||||
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.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.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.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.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(); } });
|
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(); } });
|
||||||
|
|
||||||
|
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 }); } });
|
||||||
|
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 }); } });
|
||||||
|
|
||||||
// SERVICIOS CRUD
|
// SERVICIOS CRUD
|
||||||
app.get("/services", authMiddleware, async (req, res) => {
|
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 }); } });
|
||||||
try {
|
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 }); } });
|
||||||
const q = await pool.query(`
|
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 }); } });
|
||||||
SELECT s.*, st.name as status_name, st.color as status_color, c.name as company_name,
|
app.put("/services/:id/status", authMiddleware, async (req, res) => { const client = await pool.connect(); try { const { status_id, comment } = req.body; await client.query('BEGIN'); const curr = await client.query("SELECT status_id FROM services WHERE id=$1", [req.params.id]); const old = curr.rows[0].status_id; await client.query("UPDATE services SET status_id=$1 WHERE id=$2", [status_id, req.params.id]); await client.query("INSERT INTO service_logs (service_id, user_id, old_status_id, new_status_id, comment) VALUES ($1, $2, $3, $4, $5)", [req.params.id, req.user.sub, old, status_id, comment]); await client.query('COMMIT'); res.json({ ok: true }); } catch (e) { await client.query('ROLLBACK'); res.status(500).json({ ok: false }); } finally { client.release(); } });
|
||||||
g.name as guild_name, u.full_name as assigned_name
|
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); 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) { clientId = cCheck.rows[0].id; let addrs = cCheck.rows[0].addresses || []; if(!addrs.includes(address)) { addrs.push(address); await client.query("UPDATE clients SET addresses=$1 WHERE id=$2", [JSON.stringify(addrs), clientId]); } } else { 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]); 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 }); } catch (e) { await client.query('ROLLBACK'); console.error(e); res.status(500).json({ ok: false, error: e.message }); } finally { client.release(); } });
|
||||||
FROM services s
|
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 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("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(); } });
|
||||||
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 }); }
|
|
||||||
});
|
|
||||||
|
|
||||||
app.put("/services/:id/status", authMiddleware, async (req, res) => {
|
|
||||||
const client = await pool.connect();
|
|
||||||
try {
|
|
||||||
const { status_id, comment } = req.body;
|
|
||||||
await client.query('BEGIN');
|
|
||||||
const curr = await client.query("SELECT status_id FROM services WHERE id=$1", [req.params.id]);
|
|
||||||
const old = curr.rows[0].status_id;
|
|
||||||
await client.query("UPDATE services SET status_id=$1 WHERE id=$2", [status_id, req.params.id]);
|
|
||||||
await client.query("INSERT INTO service_logs (service_id, user_id, old_status_id, new_status_id, comment) VALUES ($1, $2, $3, $4, $5)", [req.params.id, req.user.sub, old, status_id, comment]);
|
|
||||||
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("/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);
|
|
||||||
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) {
|
|
||||||
clientId = cCheck.rows[0].id;
|
|
||||||
let addrs = cCheck.rows[0].addresses || [];
|
|
||||||
if(!addrs.includes(address)) { addrs.push(address); await client.query("UPDATE clients SET addresses=$1 WHERE id=$2", [JSON.stringify(addrs), clientId]); }
|
|
||||||
} else {
|
|
||||||
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]);
|
|
||||||
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 });
|
|
||||||
} catch (e) { await client.query('ROLLBACK'); console.error(e); res.status(500).json({ ok: false, error: e.message }); } finally { client.release(); }
|
|
||||||
});
|
|
||||||
|
|
||||||
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 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("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 }); } });
|
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.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.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.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 }); } });
|
||||||
@@ -380,3 +295,362 @@ app.delete("/admin/users/:id", authMiddleware, async (req, res) => { try { await
|
|||||||
|
|
||||||
const port = process.env.PORT || 3000;
|
const port = process.env.PORT || 3000;
|
||||||
autoUpdateDB().then(() => { app.listen(port, "0.0.0.0", () => console.log(`🚀 Server OK en puerto ${port}`)); });
|
autoUpdateDB().then(() => { app.listen(port, "0.0.0.0", () => console.log(`🚀 Server OK en puerto ${port}`)); });
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### PASO 2: Actualizar `configuracion.html` (Frontend)
|
||||||
|
|
||||||
|
Aquí tienes el archivo completo con el **Editor de Plantillas** totalmente funcional.
|
||||||
|
|
||||||
|
Copia y reemplaza tu `configuracion.html`:
|
||||||
|
|
||||||
|
```html
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="es">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Configuración - IntegraRepara</title>
|
||||||
|
<script src="[https://cdn.tailwindcss.com](https://cdn.tailwindcss.com)"></script>
|
||||||
|
<script src="[https://unpkg.com/lucide@latest](https://unpkg.com/lucide@latest)"></script>
|
||||||
|
<style>
|
||||||
|
.fade-in { animation: fadeIn 0.3s ease-in-out; }
|
||||||
|
.scroller::-webkit-scrollbar { width: 6px; }
|
||||||
|
.scroller::-webkit-scrollbar-thumb { background-color: #cbd5e1; border-radius: 4px; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body class="bg-gray-50 text-gray-800 font-sans h-screen overflow-hidden flex">
|
||||||
|
|
||||||
|
<div id="sidebar-container" class="h-full shrink-0"></div>
|
||||||
|
|
||||||
|
<div class="flex-1 flex flex-col h-full relative min-w-0">
|
||||||
|
<div id="header-container"></div>
|
||||||
|
|
||||||
|
<main class="flex-1 flex flex-col overflow-hidden relative">
|
||||||
|
|
||||||
|
<div class="bg-gray-50 p-6 pb-0 z-20 shrink-0">
|
||||||
|
<h2 class="text-2xl font-bold text-gray-800 mb-6 flex items-center gap-2">
|
||||||
|
<i data-lucide="settings" class="text-blue-600"></i> Configuración Avanzada
|
||||||
|
</h2>
|
||||||
|
|
||||||
|
<div class="flex border-b border-gray-200 overflow-x-auto no-scrollbar">
|
||||||
|
<button onclick="showTab('templates')" id="tab-templates" class="tab-btn px-6 py-3 text-sm font-bold text-blue-600 border-b-2 border-blue-600 hover:bg-gray-100 transition whitespace-nowrap">
|
||||||
|
<i data-lucide="file-text" class="inline w-4 h-4 mr-1"></i> Plantillas
|
||||||
|
</button>
|
||||||
|
<button onclick="showTab('whatsapp')" id="tab-whatsapp" class="tab-btn px-6 py-3 text-sm font-medium text-gray-500 hover:text-blue-600 hover:bg-gray-100 transition whitespace-nowrap">
|
||||||
|
<i data-lucide="message-circle" class="inline w-4 h-4 mr-1"></i> WhatsApp
|
||||||
|
</button>
|
||||||
|
<button onclick="showTab('providers')" id="tab-providers" class="tab-btn px-6 py-3 text-sm font-medium text-gray-500 hover:text-blue-600 hover:bg-gray-100 transition whitespace-nowrap">
|
||||||
|
<i data-lucide="truck" class="inline w-4 h-4 mr-1"></i> Proveedores
|
||||||
|
</button>
|
||||||
|
<button onclick="showTab('portal')" id="tab-portal" class="tab-btn px-6 py-3 text-sm font-medium text-gray-500 hover:text-blue-600 hover:bg-gray-100 transition whitespace-nowrap">
|
||||||
|
<i data-lucide="globe" class="inline w-4 h-4 mr-1"></i> Portal Cliente
|
||||||
|
</button>
|
||||||
|
<button onclick="showTab('others')" id="tab-others" class="tab-btn px-6 py-3 text-sm font-medium text-gray-500 hover:text-blue-600 hover:bg-gray-100 transition whitespace-nowrap">
|
||||||
|
<i data-lucide="sliders" class="inline w-4 h-4 mr-1"></i> Otras Configuraciones
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex-1 overflow-hidden p-6 bg-gray-50">
|
||||||
|
|
||||||
|
<div id="view-templates" class="tab-content h-full fade-in flex gap-6">
|
||||||
|
<div class="w-1/3 bg-white rounded-xl shadow border border-gray-100 overflow-hidden flex flex-col">
|
||||||
|
<div class="p-4 bg-gray-50 border-b font-bold text-gray-700">Tipos de Mensaje</div>
|
||||||
|
<div class="flex-1 overflow-y-auto p-2 space-y-1">
|
||||||
|
<button onclick="selectTemplate('welcome', this)" class="tpl-btn w-full text-left p-3 rounded-lg hover:bg-blue-50 text-sm font-medium text-gray-600 transition-colors flex items-center gap-2">
|
||||||
|
<i data-lucide="hand" class="w-4 h-4"></i> Bienvenida
|
||||||
|
</button>
|
||||||
|
<button onclick="selectTemplate('no_contact', this)" class="tpl-btn w-full text-left p-3 rounded-lg hover:bg-blue-50 text-sm font-medium text-gray-600 transition-colors flex items-center gap-2">
|
||||||
|
<i data-lucide="phone-off" class="w-4 h-4"></i> Cliente no localizado
|
||||||
|
</button>
|
||||||
|
<button onclick="selectTemplate('appointment', this)" class="tpl-btn w-full text-left p-3 rounded-lg hover:bg-blue-50 text-sm font-medium text-gray-600 transition-colors flex items-center gap-2">
|
||||||
|
<i data-lucide="calendar-check" class="w-4 h-4"></i> Cita creada
|
||||||
|
</button>
|
||||||
|
<button onclick="selectTemplate('update', this)" class="tpl-btn w-full text-left p-3 rounded-lg hover:bg-blue-50 text-sm font-medium text-gray-600 transition-colors flex items-center gap-2">
|
||||||
|
<i data-lucide="refresh-cw" class="w-4 h-4"></i> Modificación servicio
|
||||||
|
</button>
|
||||||
|
<button onclick="selectTemplate('on_way', this)" class="tpl-btn w-full text-left p-3 rounded-lg hover:bg-blue-50 text-sm font-medium text-gray-600 transition-colors flex items-center gap-2">
|
||||||
|
<i data-lucide="truck" class="w-4 h-4"></i> De camino
|
||||||
|
</button>
|
||||||
|
<button onclick="selectTemplate('survey', this)" class="tpl-btn w-full text-left p-3 rounded-lg hover:bg-blue-50 text-sm font-medium text-gray-600 transition-colors flex items-center gap-2">
|
||||||
|
<i data-lucide="star" class="w-4 h-4"></i> Encuesta calidad
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex-1 bg-white rounded-xl shadow border border-gray-100 flex flex-col">
|
||||||
|
<div class="p-4 border-b bg-gray-50 flex justify-between items-center">
|
||||||
|
<span class="font-bold text-gray-700" id="editorTitle">Selecciona una plantilla</span>
|
||||||
|
<button onclick="saveTemplate()" class="bg-blue-600 text-white px-4 py-2 rounded-lg text-sm font-bold shadow hover:bg-blue-700 transition-colors">Guardar Cambios</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="p-3 border-b bg-gray-50 flex flex-wrap gap-2">
|
||||||
|
<span class="text-xs font-bold text-gray-400 uppercase tracking-wide py-1">Insertar:</span>
|
||||||
|
<button onclick="insertVar('{{NOMBRE}}')" class="px-2 py-1 bg-white border rounded text-xs font-mono hover:border-blue-400 text-gray-600 transition">{{NOMBRE}}</button>
|
||||||
|
<button onclick="insertVar('{{DIRECCION}}')" class="px-2 py-1 bg-white border rounded text-xs font-mono hover:border-blue-400 text-gray-600 transition">{{DIRECCION}}</button>
|
||||||
|
<button onclick="insertVar('{{FECHA}}')" class="px-2 py-1 bg-white border rounded text-xs font-mono hover:border-blue-400 text-gray-600 transition">{{FECHA}}</button>
|
||||||
|
<button onclick="insertVar('{{HORA}}')" class="px-2 py-1 bg-white border rounded text-xs font-mono hover:border-blue-400 text-gray-600 transition">{{HORA}}</button>
|
||||||
|
<button onclick="insertVar('{{COMPANIA}}')" class="px-2 py-1 bg-white border rounded text-xs font-mono hover:border-blue-400 text-gray-600 transition">{{COMPANIA}}</button>
|
||||||
|
<button onclick="insertVar('{{REFERENCIA}}')" class="px-2 py-1 bg-white border rounded text-xs font-mono hover:border-blue-400 text-gray-600 transition">{{REFERENCIA}}</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<textarea id="tplContent" class="flex-1 p-4 outline-none resize-none text-sm leading-relaxed" placeholder="Escribe aquí el texto del mensaje..."></textarea>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="view-whatsapp" class="tab-content hidden h-full fade-in">
|
||||||
|
<div class="bg-white rounded-xl shadow p-10 text-center border border-gray-100">
|
||||||
|
<i data-lucide="message-circle" class="w-16 h-16 text-green-100 mx-auto mb-4 text-green-500"></i>
|
||||||
|
<h3 class="text-xl font-bold text-gray-700">Conexión WhatsApp</h3>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="view-providers" class="tab-content hidden h-full fade-in">
|
||||||
|
<div class="bg-white rounded-xl shadow p-10 text-center border border-gray-100">
|
||||||
|
<i data-lucide="truck" class="w-16 h-16 text-gray-200 mx-auto mb-4"></i>
|
||||||
|
<h3 class="text-xl font-bold text-gray-700">Proveedores</h3>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="view-portal" class="tab-content hidden h-full fade-in">
|
||||||
|
<div class="bg-white rounded-xl shadow p-10 text-center border border-gray-100">
|
||||||
|
<i data-lucide="globe" class="w-16 h-16 text-blue-200 mx-auto mb-4"></i>
|
||||||
|
<h3 class="text-xl font-bold text-gray-700">Portal del Cliente</h3>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="view-others" class="tab-content hidden h-full fade-in flex flex-col">
|
||||||
|
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||||
|
<div class="bg-white rounded-xl shadow border border-gray-100 flex flex-col h-[500px]">
|
||||||
|
<div class="p-4 bg-gray-50 border-b border-gray-200 shrink-0">
|
||||||
|
<h3 class="font-bold text-gray-700 flex items-center gap-2">
|
||||||
|
<i data-lucide="shield" class="w-4 h-4 text-blue-600"></i> Compañías de Seguros
|
||||||
|
</h3>
|
||||||
|
</div>
|
||||||
|
<div class="p-4 border-b border-gray-100 bg-white">
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<input type="text" id="newCompanyInput" placeholder="Nombre de la compañía..." class="flex-1 border rounded-lg px-3 py-2 text-sm outline-none focus:border-blue-500">
|
||||||
|
<button onclick="addCompany()" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-xs font-bold transition-colors">Añadir</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div id="listCompanies" class="flex-1 overflow-y-auto scroller p-2 space-y-1">
|
||||||
|
<p class="text-center text-xs text-gray-400 mt-10">Cargando...</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="bg-white rounded-xl shadow border border-gray-100 flex flex-col h-[500px]">
|
||||||
|
<div class="p-4 bg-gray-50 border-b border-gray-200 shrink-0">
|
||||||
|
<h3 class="font-bold text-gray-700 flex items-center gap-2">
|
||||||
|
<i data-lucide="activity" class="w-4 h-4 text-blue-600"></i> Estados del Servicio
|
||||||
|
</h3>
|
||||||
|
</div>
|
||||||
|
<div class="p-4 border-b border-gray-100 bg-white">
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<input type="text" id="newStatusInput" placeholder="Nuevo estado..." class="flex-1 border rounded-lg px-3 py-2 text-sm outline-none focus:border-blue-500">
|
||||||
|
<select id="newStatusColor" class="border rounded-lg px-2 text-sm text-gray-600 outline-none focus:border-blue-500 bg-gray-50">
|
||||||
|
<option value="gray">Gris</option>
|
||||||
|
<option value="blue">Azul</option>
|
||||||
|
<option value="green">Verde</option>
|
||||||
|
<option value="red">Rojo</option>
|
||||||
|
<option value="yellow">Amarillo</option>
|
||||||
|
<option value="purple">Morado</option>
|
||||||
|
</select>
|
||||||
|
<button onclick="addStatus()" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-xs font-bold transition-colors">Añadir</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div id="listStatuses" class="flex-1 overflow-y-auto scroller p-2 space-y-1">
|
||||||
|
<p class="text-center text-xs text-gray-400 mt-10">Cargando...</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="toast" class="fixed bottom-5 right-5 bg-slate-800 text-white px-6 py-3 rounded-lg shadow-2xl transform translate-y-20 opacity-0 transition-all duration-300 z-50 flex items-center gap-3"><span id="toastMsg">Msg</span></div>
|
||||||
|
|
||||||
|
<script src="js/layout.js"></script>
|
||||||
|
<script>
|
||||||
|
let cachedTemplates = {};
|
||||||
|
let currentTemplateType = null;
|
||||||
|
|
||||||
|
document.addEventListener("DOMContentLoaded", () => {
|
||||||
|
if (!localStorage.getItem("token")) window.location.href = "index.html";
|
||||||
|
showTab('templates');
|
||||||
|
loadTemplates(); // Cargar plantillas al inicio
|
||||||
|
});
|
||||||
|
|
||||||
|
function showTab(tabId) {
|
||||||
|
document.querySelectorAll('.tab-content').forEach(el => el.classList.add('hidden'));
|
||||||
|
document.getElementById(`view-${tabId}`).classList.remove('hidden');
|
||||||
|
|
||||||
|
document.querySelectorAll('.tab-btn').forEach(el => {
|
||||||
|
el.classList.remove('text-blue-600', 'border-b-2', 'border-blue-600', 'font-bold');
|
||||||
|
el.classList.add('text-gray-500', 'font-medium');
|
||||||
|
});
|
||||||
|
const btn = document.getElementById(`tab-${tabId}`);
|
||||||
|
btn.classList.add('text-blue-600', 'border-b-2', 'border-blue-600', 'font-bold');
|
||||||
|
btn.classList.remove('text-gray-500', 'font-medium');
|
||||||
|
|
||||||
|
if(tabId === 'others') {
|
||||||
|
loadCompanies();
|
||||||
|
loadStatusesConfig();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- GESTIÓN DE PLANTILLAS ---
|
||||||
|
async function loadTemplates() {
|
||||||
|
try {
|
||||||
|
const res = await fetch(`${API_URL}/templates`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
|
||||||
|
const data = await res.json();
|
||||||
|
if(data.ok) {
|
||||||
|
data.templates.forEach(t => {
|
||||||
|
cachedTemplates[t.type] = t.content;
|
||||||
|
});
|
||||||
|
// Seleccionar la primera por defecto si no hay seleccionada
|
||||||
|
if (!currentTemplateType) {
|
||||||
|
document.querySelector('.tpl-btn').click();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch(e) { console.error("Error cargando plantillas"); }
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectTemplate(type, btn) {
|
||||||
|
currentTemplateType = type;
|
||||||
|
// Visual feedback
|
||||||
|
document.querySelectorAll('.tpl-btn').forEach(b => b.classList.remove('bg-blue-50', 'text-blue-700', 'font-bold'));
|
||||||
|
btn.classList.add('bg-blue-50', 'text-blue-700', 'font-bold');
|
||||||
|
|
||||||
|
// Cargar contenido
|
||||||
|
document.getElementById('editorTitle').innerText = btn.innerText.trim();
|
||||||
|
document.getElementById('tplContent').value = cachedTemplates[type] || "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function insertVar(text) {
|
||||||
|
const textarea = document.getElementById('tplContent');
|
||||||
|
const start = textarea.selectionStart;
|
||||||
|
const end = textarea.selectionEnd;
|
||||||
|
const val = textarea.value;
|
||||||
|
textarea.value = val.substring(0, start) + text + val.substring(end);
|
||||||
|
textarea.focus();
|
||||||
|
textarea.selectionStart = textarea.selectionEnd = start + text.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveTemplate() {
|
||||||
|
if(!currentTemplateType) return;
|
||||||
|
const content = document.getElementById('tplContent').value;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch(`${API_URL}/templates`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
|
||||||
|
body: JSON.stringify({ type: currentTemplateType, content: content })
|
||||||
|
});
|
||||||
|
|
||||||
|
if(res.ok) {
|
||||||
|
cachedTemplates[currentTemplateType] = content;
|
||||||
|
showToast("Plantilla guardada");
|
||||||
|
} else {
|
||||||
|
showToast("Error al guardar", true);
|
||||||
|
}
|
||||||
|
} catch(e) { showToast("Error conexión", true); }
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- GESTIÓN DE COMPAÑÍAS ---
|
||||||
|
async function loadCompanies() {
|
||||||
|
const list = document.getElementById('listCompanies');
|
||||||
|
list.innerHTML = '<p class="text-center text-xs text-gray-400 mt-10">Cargando...</p>';
|
||||||
|
try {
|
||||||
|
const res = await fetch(`${API_URL}/companies`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
|
||||||
|
const data = await res.json();
|
||||||
|
list.innerHTML = "";
|
||||||
|
if(data.companies.length === 0) { list.innerHTML = '<p class="text-center text-xs text-gray-400 mt-4">Sin compañías.</p>'; return; }
|
||||||
|
data.companies.forEach(c => {
|
||||||
|
const div = document.createElement('div');
|
||||||
|
div.className = "p-3 border border-gray-100 rounded-lg bg-gray-50 flex justify-between items-center group hover:border-blue-200 transition-colors";
|
||||||
|
div.innerHTML = `<span class="font-bold text-gray-700 text-sm">${c.name}</span><button onclick="deleteCompany(${c.id})" class="text-gray-300 hover:text-red-500"><i data-lucide="trash-2" class="w-4 h-4"></i></button>`;
|
||||||
|
list.appendChild(div);
|
||||||
|
});
|
||||||
|
lucide.createIcons();
|
||||||
|
} catch(e) { list.innerHTML = '<p class="text-red-500 text-xs text-center">Error</p>'; }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function addCompany() {
|
||||||
|
const input = document.getElementById('newCompanyInput');
|
||||||
|
const name = input.value.trim();
|
||||||
|
if(!name) return;
|
||||||
|
try {
|
||||||
|
const res = await fetch(`${API_URL}/companies`, {
|
||||||
|
method: 'POST', headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
|
||||||
|
body: JSON.stringify({ name: name })
|
||||||
|
});
|
||||||
|
if(res.ok) { showToast("Compañía añadida"); input.value = ""; loadCompanies(); }
|
||||||
|
} catch(e) { showToast("Error", true); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteCompany(id) {
|
||||||
|
if(!confirm("¿Borrar compañía?")) return;
|
||||||
|
await fetch(`${API_URL}/companies/${id}`, { method: 'DELETE', headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
|
||||||
|
loadCompanies();
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- GESTIÓN DE ESTADOS ---
|
||||||
|
async function loadStatusesConfig() {
|
||||||
|
const list = document.getElementById('listStatuses');
|
||||||
|
list.innerHTML = '<p class="text-center text-xs text-gray-400 mt-10">Cargando...</p>';
|
||||||
|
try {
|
||||||
|
const res = await fetch(`${API_URL}/statuses`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
|
||||||
|
const data = await res.json();
|
||||||
|
list.innerHTML = "";
|
||||||
|
data.statuses.forEach(s => {
|
||||||
|
const div = document.createElement('div');
|
||||||
|
div.className = "p-3 border border-gray-100 rounded-lg bg-gray-50 flex justify-between items-center group hover:border-blue-200 transition-colors";
|
||||||
|
div.innerHTML = `
|
||||||
|
<div class="flex items-center gap-3">
|
||||||
|
<div class="w-3 h-3 rounded-full bg-${s.color}-500"></div>
|
||||||
|
<span class="font-bold text-gray-700 text-sm">${s.name}</span>
|
||||||
|
</div>
|
||||||
|
<button onclick="deleteStatus(${s.id})" class="text-gray-300 hover:text-red-500"><i data-lucide="trash-2" class="w-4 h-4"></i></button>
|
||||||
|
`;
|
||||||
|
list.appendChild(div);
|
||||||
|
});
|
||||||
|
lucide.createIcons();
|
||||||
|
} catch(e) { list.innerHTML = '<p class="text-red-500 text-xs text-center">Error</p>'; }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function addStatus() {
|
||||||
|
const input = document.getElementById('newStatusInput');
|
||||||
|
const color = document.getElementById('newStatusColor').value;
|
||||||
|
const name = input.value.trim();
|
||||||
|
if(!name) return;
|
||||||
|
try {
|
||||||
|
const res = await fetch(`${API_URL}/statuses`, {
|
||||||
|
method: 'POST', headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
|
||||||
|
body: JSON.stringify({ name: name, color: color })
|
||||||
|
});
|
||||||
|
if(res.ok) { showToast("Estado añadido"); input.value = ""; loadStatusesConfig(); }
|
||||||
|
} catch(e) { showToast("Error", true); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteStatus(id) {
|
||||||
|
if(!confirm("¿Borrar estado?")) return;
|
||||||
|
try {
|
||||||
|
const res = await fetch(`${API_URL}/statuses/${id}`, { method: 'DELETE', headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
|
||||||
|
const json = await res.json();
|
||||||
|
if(res.ok) { showToast("Estado eliminado"); loadStatusesConfig(); }
|
||||||
|
else { showToast(json.error || "No se pudo borrar", true); }
|
||||||
|
} catch(e) { showToast("Error conexión", true); }
|
||||||
|
}
|
||||||
|
|
||||||
|
function showToast(msg, isError = false) {
|
||||||
|
const t = document.getElementById('toast'), m = document.getElementById('toastMsg');
|
||||||
|
t.className = `fixed bottom-5 right-5 px-6 py-3 rounded-lg shadow-xl transition-all duration-300 z-50 flex items-center gap-3 ${isError ? 'bg-red-600' : 'bg-slate-800'} text-white font-medium`;
|
||||||
|
m.innerText = msg; t.classList.remove('translate-y-20', 'opacity-0');
|
||||||
|
setTimeout(() => t.classList.add('translate-y-20', 'opacity-0'), 3000);
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Reference in New Issue
Block a user