Actualizar servicios.html
This commit is contained in:
868
servicios.html
868
servicios.html
@@ -1,543 +1,387 @@
|
|||||||
<!DOCTYPE html>
|
import express from "express";
|
||||||
<html lang="es">
|
import cors from "cors";
|
||||||
<head>
|
import bcrypt from "bcryptjs";
|
||||||
<meta charset="UTF-8">
|
import jwt from "jsonwebtoken";
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
import pg from "pg";
|
||||||
<title>Servicios - IntegraRepara</title>
|
|
||||||
<script src="https://cdn.tailwindcss.com"></script>
|
|
||||||
<script src="https://unpkg.com/lucide@latest"></script>
|
|
||||||
<style>
|
|
||||||
.fade-in { animation: fadeIn 0.3s ease-in-out; }
|
|
||||||
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
|
|
||||||
.slide-in { animation: slideIn 0.3s ease-out forwards; }
|
|
||||||
@keyframes slideIn { from { transform: translateX(100%); } to { transform: translateX(0); } }
|
|
||||||
/* Ocultar scrollbar en panel lateral pero permitir scroll */
|
|
||||||
.no-scrollbar::-webkit-scrollbar { display: none; }
|
|
||||||
.no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
<body class="bg-gray-50 text-gray-800 font-sans antialiased overflow-hidden">
|
|
||||||
|
|
||||||
<div class="flex h-screen overflow-hidden">
|
const { Pool } = pg;
|
||||||
<div id="sidebar-container" class="h-full"></div>
|
const app = express();
|
||||||
|
|
||||||
<div class="flex-1 flex flex-col overflow-hidden relative">
|
app.use(cors());
|
||||||
<div id="header-container"></div>
|
app.use(express.json());
|
||||||
|
|
||||||
<main class="flex-1 overflow-x-hidden overflow-y-auto bg-gray-50 p-6 relative">
|
const {
|
||||||
|
DATABASE_URL,
|
||||||
|
JWT_SECRET,
|
||||||
|
EVOLUTION_BASE_URL,
|
||||||
|
EVOLUTION_API_KEY,
|
||||||
|
EVOLUTION_INSTANCE,
|
||||||
|
} = process.env;
|
||||||
|
|
||||||
<div id="servicesListView" class="fade-in">
|
if (!DATABASE_URL || !JWT_SECRET) {
|
||||||
<div class="flex justify-between items-center mb-6">
|
console.error("❌ ERROR FATAL: Faltan variables de entorno");
|
||||||
<div>
|
process.exit(1);
|
||||||
<h2 class="text-2xl font-bold text-gray-800 flex items-center gap-2">
|
}
|
||||||
<i data-lucide="briefcase" class="text-blue-600"></i> Servicios Activos
|
|
||||||
</h2>
|
|
||||||
<p class="text-sm text-gray-500 mt-1">Gestiona las reparaciones y sus estados.</p>
|
|
||||||
</div>
|
|
||||||
<button onclick="toggleView('create')" class="bg-blue-600 hover:bg-blue-700 text-white px-5 py-2.5 rounded-xl shadow-lg flex items-center gap-2 font-medium transition-all transform hover:scale-105">
|
|
||||||
<i data-lucide="plus-circle" class="w-5 h-5"></i> Nuevo Servicio
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
|
const pool = new Pool({
|
||||||
<table class="w-full text-left border-collapse">
|
connectionString: DATABASE_URL,
|
||||||
<thead class="bg-gray-50 text-gray-500 text-xs uppercase tracking-wider border-b">
|
ssl: false
|
||||||
<tr>
|
});
|
||||||
<th class="p-4 font-semibold">Fecha</th>
|
|
||||||
<th class="p-4 font-semibold">Cliente / Dirección</th>
|
|
||||||
<th class="p-4 font-semibold">Detalle</th>
|
|
||||||
<th class="p-4 font-semibold">Estado</th>
|
|
||||||
<th class="p-4 text-right"></th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody id="servicesTableBody" class="divide-y divide-gray-100 text-sm text-gray-600">
|
|
||||||
<tr><td colspan="5" class="p-8 text-center text-gray-400">Cargando servicios...</td></tr>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div id="createServiceView" class="hidden fade-in max-w-5xl mx-auto pb-10">
|
// ==========================================
|
||||||
<button onclick="toggleView('list')" class="mb-6 text-gray-500 hover:text-gray-800 flex items-center gap-2 transition-colors">
|
// 🧠 AUTO-ACTUALIZACIÓN DB (ESTADOS Y LOGS)
|
||||||
<i data-lucide="arrow-left" class="w-5 h-5"></i> Volver al listado
|
// ==========================================
|
||||||
</button>
|
async function autoUpdateDB() {
|
||||||
|
const client = await pool.connect();
|
||||||
|
try {
|
||||||
|
console.log("🔄 Revisando estructura de base de datos...");
|
||||||
|
|
||||||
<h2 class="text-2xl font-bold text-gray-800 mb-6 flex items-center gap-2">
|
// 1. Tablas Base
|
||||||
<i data-lucide="file-plus" class="text-green-600"></i> Alta de Nuevo Servicio
|
await client.query(`
|
||||||
</h2>
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
full_name TEXT NOT NULL,
|
||||||
|
phone TEXT NOT NULL,
|
||||||
|
email TEXT NOT NULL,
|
||||||
|
dni TEXT,
|
||||||
|
address TEXT,
|
||||||
|
password_hash TEXT NOT NULL,
|
||||||
|
is_verified BOOLEAN DEFAULT FALSE,
|
||||||
|
owner_id INT,
|
||||||
|
role TEXT DEFAULT 'operario',
|
||||||
|
created_at TIMESTAMP DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
<form onsubmit="createService(event)" class="space-y-6">
|
CREATE TABLE IF NOT EXISTS login_codes (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
user_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
phone TEXT NOT NULL,
|
||||||
|
code_hash TEXT NOT NULL,
|
||||||
|
purpose TEXT DEFAULT 'register_verify',
|
||||||
|
consumed_at TIMESTAMP,
|
||||||
|
expires_at TIMESTAMP NOT NULL,
|
||||||
|
created_at TIMESTAMP DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
<div class="bg-white p-6 rounded-xl shadow-sm border border-gray-100">
|
CREATE TABLE IF NOT EXISTS guilds (
|
||||||
<h3 class="text-lg font-bold text-gray-700 mb-4 border-b pb-2 flex items-center gap-2">
|
id SERIAL PRIMARY KEY,
|
||||||
<i data-lucide="user" class="w-5 h-5 text-gray-400"></i> Datos del Cliente
|
owner_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||||||
</h3>
|
name TEXT NOT NULL,
|
||||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-5">
|
created_at TIMESTAMP DEFAULT NOW()
|
||||||
<div>
|
);
|
||||||
<label class="block text-xs font-bold text-gray-600 mb-1">Teléfono (Obligatorio) *</label>
|
|
||||||
<div class="relative">
|
|
||||||
<input type="tel" id="sPhone" required placeholder="600123456"
|
|
||||||
class="w-full pl-10 pr-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none font-medium text-gray-700"
|
|
||||||
onblur="searchClientByPhone()">
|
|
||||||
<i data-lucide="phone" class="absolute left-3 top-2.5 w-4 h-4 text-gray-400"></i>
|
|
||||||
</div>
|
|
||||||
<p class="text-xs text-green-600 mt-1 hidden font-bold" id="clientFoundMsg">✓ Cliente encontrado</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
CREATE TABLE IF NOT EXISTS user_guilds (
|
||||||
<label class="block text-xs font-bold text-gray-600 mb-1">Nombre Completo *</label>
|
user_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||||||
<input type="text" id="sName" required class="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none">
|
guild_id INT REFERENCES guilds(id) ON DELETE CASCADE,
|
||||||
</div>
|
PRIMARY KEY (user_id, guild_id)
|
||||||
|
);
|
||||||
|
|
||||||
<div class="md:col-span-2">
|
CREATE TABLE IF NOT EXISTS companies (
|
||||||
<label class="block text-xs font-bold text-gray-600 mb-1">Dirección y Población *</label>
|
id SERIAL PRIMARY KEY,
|
||||||
<div class="flex gap-2">
|
owner_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||||||
<input type="text" id="sAddress" required placeholder="Calle Mayor 1, Madrid" class="flex-1 px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none">
|
name TEXT NOT NULL,
|
||||||
<select id="sAddressSelect" class="hidden w-1/3 border rounded-lg text-sm bg-gray-50 focus:ring-2 focus:ring-blue-500" onchange="selectAddress(this.value)">
|
cif TEXT,
|
||||||
<option value="">Otras direcciones...</option>
|
email TEXT,
|
||||||
</select>
|
phone TEXT,
|
||||||
</div>
|
address TEXT,
|
||||||
</div>
|
created_at TIMESTAMP DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
<div>
|
CREATE TABLE IF NOT EXISTS clients (
|
||||||
<label class="block text-xs font-bold text-gray-600 mb-1">Email (Opcional)</label>
|
id SERIAL PRIMARY KEY,
|
||||||
<input type="email" id="sEmail" class="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none">
|
owner_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||||||
</div>
|
full_name TEXT NOT NULL,
|
||||||
</div>
|
phone TEXT NOT NULL,
|
||||||
</div>
|
email TEXT,
|
||||||
|
addresses JSONB DEFAULT '[]',
|
||||||
|
notes TEXT,
|
||||||
|
created_at TIMESTAMP DEFAULT NOW()
|
||||||
|
);
|
||||||
|
`);
|
||||||
|
|
||||||
<div class="bg-white p-6 rounded-xl shadow-sm border border-gray-100">
|
// 2. NUEVO: TABLA DE ESTADOS DE SERVICIO
|
||||||
<h3 class="text-lg font-bold text-gray-700 mb-4 border-b pb-2 flex items-center gap-2">
|
await client.query(`
|
||||||
<i data-lucide="clipboard" class="w-5 h-5 text-gray-400"></i> Detalles del Trabajo
|
CREATE TABLE IF NOT EXISTS service_statuses (
|
||||||
</h3>
|
id SERIAL PRIMARY KEY,
|
||||||
|
owner_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
name TEXT NOT NULL, -- Ej: Pendiente, En Proceso, Completado
|
||||||
|
color TEXT DEFAULT 'gray', -- gray, blue, green, red, yellow
|
||||||
|
is_default BOOLEAN DEFAULT FALSE, -- Estado inicial al crear servicio
|
||||||
|
is_final BOOLEAN DEFAULT FALSE, -- Si es estado final (cierra el servicio)
|
||||||
|
created_at TIMESTAMP DEFAULT NOW()
|
||||||
|
);
|
||||||
|
`);
|
||||||
|
|
||||||
<div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-4">
|
// 3. TABLA SERVICIOS (Con FK a status)
|
||||||
<div>
|
await client.query(`
|
||||||
<label class="block text-xs font-bold text-gray-600 mb-1">Fecha Prevista</label>
|
CREATE TABLE IF NOT EXISTS services (
|
||||||
<input type="date" id="sDate" class="w-full px-3 py-2 border rounded-lg outline-none focus:border-blue-500">
|
id SERIAL PRIMARY KEY,
|
||||||
</div>
|
owner_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||||||
<div>
|
client_id INT REFERENCES clients(id) ON DELETE SET NULL,
|
||||||
<label class="block text-xs font-bold text-gray-600 mb-1">Hora</label>
|
status_id INT REFERENCES service_statuses(id) ON DELETE SET NULL, -- NUEVO: ID del estado
|
||||||
<input type="time" id="sTime" class="w-full px-3 py-2 border rounded-lg outline-none focus:border-blue-500">
|
title TEXT,
|
||||||
</div>
|
description TEXT,
|
||||||
<div>
|
contact_phone TEXT NOT NULL,
|
||||||
<label class="block text-xs font-bold text-gray-600 mb-1">Duración Est.</label>
|
contact_name TEXT NOT NULL,
|
||||||
<select id="sDuration" class="w-full px-3 py-2 border rounded-lg bg-white outline-none focus:border-blue-500">
|
address TEXT NOT NULL,
|
||||||
<option value="15">15 min</option>
|
email TEXT,
|
||||||
<option value="30" selected>30 min</option>
|
scheduled_date DATE DEFAULT CURRENT_DATE,
|
||||||
<option value="45">45 min</option>
|
scheduled_time TIME DEFAULT CURRENT_TIME,
|
||||||
<option value="60">1 hora</option>
|
duration_minutes INT DEFAULT 30,
|
||||||
<option value="90">1h 30m</option>
|
is_urgent BOOLEAN DEFAULT FALSE,
|
||||||
<option value="120">2 horas</option>
|
is_company BOOLEAN DEFAULT FALSE,
|
||||||
</select>
|
company_id INT REFERENCES companies(id) ON DELETE SET NULL,
|
||||||
</div>
|
company_ref TEXT,
|
||||||
<div class="flex items-end pb-1">
|
internal_notes TEXT,
|
||||||
<label class="flex items-center justify-center space-x-2 cursor-pointer bg-red-50 px-4 py-2 rounded-lg border border-red-100 w-full hover:bg-red-100 transition h-[42px]">
|
client_notes TEXT,
|
||||||
<input type="checkbox" id="sUrgent" class="form-checkbox text-red-600 w-5 h-5 rounded focus:ring-red-500">
|
closed_at TIMESTAMP,
|
||||||
<span class="text-sm font-bold text-red-700">¡ES URGENTE!</span>
|
created_at TIMESTAMP DEFAULT NOW()
|
||||||
</label>
|
);
|
||||||
</div>
|
`);
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="mb-4">
|
// 4. NUEVO: TABLA LOGS DE ESTADOS (TRAZABILIDAD)
|
||||||
<label class="block text-xs font-bold text-gray-600 mb-1">Descripción / Avería</label>
|
await client.query(`
|
||||||
<textarea id="sDesc" rows="3" class="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none transition-shadow" placeholder="Describe qué hay que hacer..."></textarea>
|
CREATE TABLE IF NOT EXISTS service_logs (
|
||||||
</div>
|
id SERIAL PRIMARY KEY,
|
||||||
|
service_id INT REFERENCES services(id) ON DELETE CASCADE,
|
||||||
|
user_id INT REFERENCES users(id) ON DELETE SET NULL, -- Quién hizo el cambio
|
||||||
|
old_status_id INT REFERENCES service_statuses(id),
|
||||||
|
new_status_id INT REFERENCES service_statuses(id),
|
||||||
|
comment TEXT, -- Comentario del cambio (ej: "Cliente no estaba")
|
||||||
|
created_at TIMESTAMP DEFAULT NOW()
|
||||||
|
);
|
||||||
|
`);
|
||||||
|
|
||||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
// 5. PARCHES Y DATOS POR DEFECTO
|
||||||
<div>
|
try { await client.query(`ALTER TABLE users DROP CONSTRAINT IF EXISTS users_phone_key`); } catch (e) {}
|
||||||
<label class="block text-xs font-bold text-gray-600 mb-1 flex justify-between">
|
try { await client.query(`ALTER TABLE users DROP CONSTRAINT IF EXISTS users_email_key`); } catch (e) {}
|
||||||
<span>Notas Internas</span>
|
|
||||||
<span class="text-gray-400 font-normal text-[10px] uppercase">Solo Oficina</span>
|
|
||||||
</label>
|
|
||||||
<textarea id="sNotesInternal" rows="2" class="w-full px-3 py-2 border bg-yellow-50 border-yellow-200 rounded-lg outline-none text-sm placeholder-yellow-700/50" placeholder="Código alarma, llaves en portería..."></textarea>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label class="block text-xs font-bold text-gray-600 mb-1 flex justify-between">
|
|
||||||
<span>Notas para Cliente</span>
|
|
||||||
<span class="text-gray-400 font-normal text-[10px] uppercase">Visible en Parte</span>
|
|
||||||
</label>
|
|
||||||
<textarea id="sNotesClient" rows="2" class="w-full px-3 py-2 border rounded-lg outline-none text-sm" placeholder="Recomendaciones, observaciones..."></textarea>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="bg-white p-6 rounded-xl shadow-sm border border-gray-100">
|
await client.query(`
|
||||||
<div class="flex items-center justify-between">
|
DO $$ BEGIN
|
||||||
<h3 class="text-lg font-bold text-gray-700 flex items-center gap-2">
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='status_id') THEN
|
||||||
<i data-lucide="shield" class="w-5 h-5 text-gray-400"></i> Compañía / Seguro
|
ALTER TABLE services ADD COLUMN status_id INT REFERENCES service_statuses(id) ON DELETE SET NULL;
|
||||||
</h3>
|
END IF;
|
||||||
<label class="flex items-center space-x-2 cursor-pointer select-none">
|
END $$;
|
||||||
<span class="text-sm font-medium text-gray-600">¿Es un servicio de compañía?</span>
|
`);
|
||||||
<div class="relative">
|
|
||||||
<input type="checkbox" id="sIsCompany" class="peer sr-only" onchange="toggleCompanyFields()">
|
|
||||||
<div class="w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
|
|
||||||
</div>
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div id="companyFields" class="hidden mt-4 pt-4 border-t border-gray-100 grid grid-cols-1 md:grid-cols-2 gap-4 animate-slide-in">
|
console.log("✅ DB Sincronizada (Estados y Logs listos).");
|
||||||
<div>
|
} catch (e) { console.error("❌ Error DB:", e); } finally { client.release(); }
|
||||||
<label class="block text-xs font-bold text-gray-600 mb-1">Seleccionar Compañía</label>
|
}
|
||||||
<div class="flex gap-2">
|
|
||||||
<select id="sCompanyId" class="flex-1 px-3 py-2 border rounded-lg bg-white outline-none focus:border-blue-500">
|
|
||||||
<option value="">-- Seleccionar --</option>
|
|
||||||
</select>
|
|
||||||
<button type="button" onclick="quickAddCompany()" class="bg-slate-800 text-white px-3 rounded-lg hover:bg-slate-700 transition-colors" title="Añadir nueva compañía">
|
|
||||||
<i data-lucide="plus" class="w-4 h-4"></i>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label class="block text-xs font-bold text-gray-600 mb-1">Nº Expediente / Referencia</label>
|
|
||||||
<input type="text" id="sCompanyRef" class="w-full px-3 py-2 border rounded-lg outline-none focus:border-blue-500" placeholder="Ej: SIN-2024-8892">
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="pt-2 pb-6">
|
// HELPERS
|
||||||
<button type="submit" id="btnSave" class="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-4 rounded-xl shadow-lg shadow-blue-500/30 text-lg transition-all flex justify-center items-center gap-3 transform active:scale-95">
|
function normalizePhone(phone) {
|
||||||
<i data-lucide="save" class="w-6 h-6"></i> CREAR SERVICIO
|
let p = String(phone || "").trim().replace(/\s+/g, "").replace(/-/g, "");
|
||||||
</button>
|
if (!p) return "";
|
||||||
</div>
|
if (!p.startsWith("+") && /^[6789]\d{8}$/.test(p)) return "+34" + p;
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
function genCode6() { return String(Math.floor(100000 + Math.random() * 900000)); }
|
||||||
|
function signToken(user) {
|
||||||
|
const accountId = user.owner_id || user.id;
|
||||||
|
return jwt.sign({ sub: user.id, email: user.email, phone: user.phone, role: user.role || 'operario', accountId }, JWT_SECRET, { expiresIn: "30d" });
|
||||||
|
}
|
||||||
|
function authMiddleware(req, res, next) {
|
||||||
|
const h = req.headers.authorization || "";
|
||||||
|
const token = h.startsWith("Bearer ") ? h.slice(7) : "";
|
||||||
|
if (!token) return res.status(401).json({ ok: false, error: "No token" });
|
||||||
|
try { req.user = jwt.verify(token, JWT_SECRET); next(); }
|
||||||
|
catch { return res.status(401).json({ ok: false, error: "Token inválido" }); }
|
||||||
|
}
|
||||||
|
async function sendWhatsAppCode(phone, code) {
|
||||||
|
if (!EVOLUTION_BASE_URL || !EVOLUTION_API_KEY) {
|
||||||
|
console.log("⚠️ Evolution no configurado. Código:", code);
|
||||||
|
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 IntegraRepara: *${code}*` })
|
||||||
|
}).catch(console.error);
|
||||||
|
}
|
||||||
|
|
||||||
</form>
|
// =========================
|
||||||
</div>
|
// RUTAS AUTH (Standard)
|
||||||
|
// =========================
|
||||||
|
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, error: "Faltan datos" });
|
||||||
|
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, error: "Error server" }); } finally { client.release(); }
|
||||||
|
});
|
||||||
|
|
||||||
<div id="serviceDetailPanel" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden flex justify-end transition-opacity duration-300">
|
app.post("/auth/verify", async (req, res) => {
|
||||||
<div class="w-full max-w-md bg-white h-full shadow-2xl p-6 overflow-y-auto slide-in flex flex-col">
|
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, error: "Inválido" }); const row = q.rows[0]; if (!(await bcrypt.compare(String(code), row.code_hash))) return res.status(400).json({ ok: false, error: "Incorrecto" }); 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 }); }
|
||||||
|
});
|
||||||
|
|
||||||
<div class="flex justify-between items-start mb-6">
|
app.post("/auth/login", async (req, res) => {
|
||||||
<h2 class="text-xl font-bold text-gray-900">Detalle del Servicio</h2>
|
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, error: "Datos incorrectos" }); 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, error: "Datos incorrectos" }); res.json({ ok: true, token: signToken(user) }); } catch(e) { res.status(500).json({ ok: false }); }
|
||||||
<button onclick="closeDetailPanel()" class="text-gray-400 hover:text-gray-800 transition-colors">
|
});
|
||||||
<i data-lucide="x" class="w-6 h-6"></i>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="bg-gray-50 p-4 rounded-xl border border-gray-200 mb-6 shadow-sm">
|
// =========================
|
||||||
<div class="flex justify-between items-start mb-2">
|
// API ESTADOS (STATUSES)
|
||||||
<span id="detailStatusBadge" class="px-2 py-1 rounded text-[10px] font-bold bg-gray-200 text-gray-700 uppercase tracking-wide">ESTADO</span>
|
// =========================
|
||||||
<span id="detailId" class="text-xs font-mono text-gray-400">#000</span>
|
app.get("/statuses", authMiddleware, async (req, res) => {
|
||||||
</div>
|
try {
|
||||||
<h3 class="text-lg font-bold text-gray-800 leading-tight mb-1" id="detailTitle">Título</h3>
|
let q = await pool.query("SELECT * FROM service_statuses WHERE owner_id=$1 ORDER BY id ASC", [req.user.accountId]);
|
||||||
<p class="text-sm text-gray-500 mb-2" id="detailClient">Cliente</p>
|
// Si no existen estados, creamos los DEFAULT
|
||||||
<div class="flex items-center text-xs text-gray-400 gap-2">
|
if (q.rowCount === 0) {
|
||||||
<i data-lucide="calendar" class="w-3 h-3"></i> <span id="detailDate">Fecha</span>
|
const defaults = [
|
||||||
</div>
|
{ name: 'Pendiente', color: 'gray', def: true, fin: false },
|
||||||
</div>
|
{ name: 'En Proceso', color: 'blue', def: false, fin: false },
|
||||||
|
{ name: 'Completado', color: 'green', def: false, fin: true },
|
||||||
<div class="mb-8">
|
{ name: 'Cancelado', color: 'red', def: false, fin: true }
|
||||||
<label class="block text-xs font-bold text-gray-500 uppercase mb-2 tracking-wider">Actualizar Estado</label>
|
];
|
||||||
<div class="flex gap-2">
|
for (const s of defaults) {
|
||||||
<select id="newStatusSelect" class="flex-1 border border-gray-300 rounded-lg px-3 py-2 text-sm outline-none focus:border-blue-500 bg-white shadow-sm"></select>
|
await pool.query("INSERT INTO service_statuses (owner_id, name, color, is_default, is_final) VALUES ($1, $2, $3, $4, $5)",
|
||||||
<button onclick="updateStatus()" class="bg-slate-800 text-white px-4 py-2 rounded-lg text-sm hover:bg-slate-700 font-bold shadow-md transition-colors">
|
[req.user.accountId, s.name, s.color, s.def, s.fin]);
|
||||||
Guardar
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="flex-1">
|
|
||||||
<h3 class="font-bold text-gray-800 mb-6 flex items-center gap-2 border-b pb-2">
|
|
||||||
<i data-lucide="history" class="w-4 h-4 text-gray-400"></i> Historial de Cambios
|
|
||||||
</h3>
|
|
||||||
<div class="relative border-l-2 border-gray-200 ml-3 space-y-8 pb-8 pl-6" id="statusTimeline">
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
</main>
|
|
||||||
</div>
|
|
||||||
</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 allStatuses = [];
|
|
||||||
let currentServiceId = null;
|
|
||||||
|
|
||||||
document.addEventListener("DOMContentLoaded", () => {
|
|
||||||
const token = localStorage.getItem("token");
|
|
||||||
if (!token) window.location.href = "index.html";
|
|
||||||
|
|
||||||
// Valores por defecto
|
|
||||||
document.getElementById('sDate').valueAsDate = new Date();
|
|
||||||
const now = new Date();
|
|
||||||
document.getElementById('sTime').value = now.toTimeString().slice(0,5);
|
|
||||||
|
|
||||||
fetchStatuses();
|
|
||||||
fetchServices();
|
|
||||||
loadCompanies();
|
|
||||||
});
|
|
||||||
|
|
||||||
// --- NAVEGACIÓN ---
|
|
||||||
function toggleView(view) {
|
|
||||||
document.getElementById('servicesListView').classList.add('hidden');
|
|
||||||
document.getElementById('createServiceView').classList.add('hidden');
|
|
||||||
|
|
||||||
if(view === 'list') {
|
|
||||||
document.getElementById('servicesListView').classList.remove('hidden');
|
|
||||||
fetchServices(); // Recargar lista al volver
|
|
||||||
} else {
|
|
||||||
document.getElementById('createServiceView').classList.remove('hidden');
|
|
||||||
window.scrollTo(0,0);
|
|
||||||
}
|
}
|
||||||
|
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, error: e.message }); }
|
||||||
|
});
|
||||||
|
|
||||||
|
// =========================
|
||||||
|
// API CLIENTES & COMPAÑIAS
|
||||||
|
// =========================
|
||||||
|
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 }); }
|
||||||
|
});
|
||||||
|
|
||||||
|
// =========================
|
||||||
|
// API SERVICIOS (CON LOGS)
|
||||||
|
// =========================
|
||||||
|
|
||||||
|
// LISTAR
|
||||||
|
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
|
||||||
|
FROM services s
|
||||||
|
LEFT JOIN service_statuses st ON s.status_id = st.id
|
||||||
|
LEFT JOIN companies c ON s.company_id = c.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 }); }
|
||||||
|
});
|
||||||
|
|
||||||
|
// HISTORIAL / LOGS
|
||||||
|
app.get("/services/:id/logs", authMiddleware, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const q = await pool.query(`
|
||||||
|
SELECT l.*, u.full_name as user_name, s1.name as old_status, 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 s1 ON l.old_status_id = s1.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 }); }
|
||||||
|
});
|
||||||
|
|
||||||
|
// CAMBIAR ESTADO
|
||||||
|
app.put("/services/:id/status", authMiddleware, async (req, res) => {
|
||||||
|
const client = await pool.connect();
|
||||||
|
try {
|
||||||
|
const { status_id, comment } = req.body;
|
||||||
|
const serviceId = req.params.id;
|
||||||
|
await client.query('BEGIN');
|
||||||
|
|
||||||
|
const current = await client.query("SELECT status_id FROM services WHERE id=$1", [serviceId]);
|
||||||
|
const oldStatus = current.rows[0].status_id;
|
||||||
|
|
||||||
|
await client.query("UPDATE services SET status_id=$1 WHERE id=$2", [status_id, serviceId]);
|
||||||
|
await client.query("INSERT INTO service_logs (service_id, user_id, old_status_id, new_status_id, comment) VALUES ($1, $2, $3, $4, $5)",
|
||||||
|
[serviceId, req.user.sub, oldStatus, status_id, comment || "Cambio manual"]);
|
||||||
|
|
||||||
|
await client.query('COMMIT');
|
||||||
|
res.json({ ok: true });
|
||||||
|
} catch (e) { await client.query('ROLLBACK'); res.status(500).json({ ok: false }); } finally { client.release(); }
|
||||||
|
});
|
||||||
|
|
||||||
|
// CREAR SERVICIO
|
||||||
|
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 // <--- NUEVO: Recibimos el estado manual
|
||||||
|
} = req.body;
|
||||||
|
|
||||||
|
const p = normalizePhone(phone);
|
||||||
|
|
||||||
|
await client.query('BEGIN');
|
||||||
|
|
||||||
|
// 1. GESTIÓN DEL ESTADO
|
||||||
|
let finalStatusId = status_id;
|
||||||
|
|
||||||
|
// Si no nos envían estado, buscamos el "por defecto" (Pendiente)
|
||||||
|
if (!finalStatusId) {
|
||||||
|
const defStatus = await client.query("SELECT id FROM service_statuses WHERE owner_id=$1 AND is_default=TRUE LIMIT 1", [req.user.accountId]);
|
||||||
|
finalStatusId = defStatus.rows[0]?.id;
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- DATOS MAESTROS ---
|
// 2. GESTIÓN CLIENTE
|
||||||
async function fetchStatuses() {
|
let clientId;
|
||||||
try {
|
const clientCheck = await client.query("SELECT id, addresses FROM clients WHERE phone=$1 AND owner_id=$2", [p, req.user.accountId]);
|
||||||
const res = await fetch(`${API_URL}/statuses`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
|
if (clientCheck.rowCount > 0) {
|
||||||
const data = await res.json();
|
clientId = clientCheck.rows[0].id;
|
||||||
if(data.ok) allStatuses = data.statuses;
|
let addrs = clientCheck.rows[0].addresses || [];
|
||||||
} catch(e) {}
|
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loadCompanies() {
|
// 3. INSERTAR SERVICIO
|
||||||
try {
|
const insert = await client.query(`
|
||||||
const res = await fetch(`${API_URL}/companies`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
|
INSERT INTO services (
|
||||||
const data = await res.json();
|
owner_id, client_id, status_id, contact_phone, contact_name, address, email,
|
||||||
if (data.ok) {
|
description, scheduled_date, scheduled_time, duration_minutes, is_urgent,
|
||||||
const sel = document.getElementById('sCompanyId');
|
is_company, company_id, company_ref, internal_notes, client_notes, title
|
||||||
sel.innerHTML = '<option value="">-- Seleccionar --</option>';
|
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18)
|
||||||
data.companies.forEach(c => sel.innerHTML += `<option value="${c.id}">${c.name}</option>`);
|
RETURNING id
|
||||||
}
|
`, [
|
||||||
} catch (e) {}
|
req.user.accountId, clientId, finalStatusId, p, name, address, email,
|
||||||
}
|
description, scheduled_date || 'NOW()', scheduled_time || 'NOW()', duration || 30, is_urgent || false,
|
||||||
|
is_company || false, company_id || null, company_ref, internal_notes, client_notes, name + " - Svc"
|
||||||
|
]);
|
||||||
|
|
||||||
async function quickAddCompany() {
|
// 4. LOG INICIAL
|
||||||
const name = prompt("Nombre de la nueva compañía:");
|
await client.query("INSERT INTO service_logs (service_id, user_id, new_status_id, comment) VALUES ($1, $2, $3, 'Servicio Creado')",
|
||||||
if(!name) return;
|
[insert.rows[0].id, req.user.sub, finalStatusId]);
|
||||||
try {
|
|
||||||
const res = await fetch(`${API_URL}/companies`, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
|
|
||||||
body: JSON.stringify({ name })
|
|
||||||
});
|
|
||||||
if(res.ok) { showToast("Compañía añadida"); loadCompanies(); }
|
|
||||||
} catch(e) { alert("Error"); }
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- LÓGICA DE SERVICIOS (LISTAR) ---
|
await client.query('COMMIT');
|
||||||
async function fetchServices() {
|
res.json({ ok: true });
|
||||||
try {
|
} catch (e) { await client.query('ROLLBACK'); console.error(e); res.status(500).json({ ok: false, error: e.message }); } finally { client.release(); }
|
||||||
const res = await fetch(`${API_URL}/services`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
|
});
|
||||||
const data = await res.json();
|
|
||||||
const tbody = document.getElementById('servicesTableBody');
|
|
||||||
tbody.innerHTML = "";
|
|
||||||
|
|
||||||
if(!data.ok || data.services.length === 0) {
|
const port = process.env.PORT || 3000;
|
||||||
tbody.innerHTML = `<tr><td colspan="5" class="p-8 text-center text-gray-400 bg-white">No hay servicios registrados. <button onclick="toggleView('create')" class="text-blue-600 font-bold hover:underline">Crear el primero</button></td></tr>`;
|
autoUpdateDB().then(() => { app.listen(port, "0.0.0.0", () => console.log(`🚀 Server OK en puerto ${port}`)); });
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
data.services.forEach(s => {
|
|
||||||
const color = s.status_color || 'gray';
|
|
||||||
// Parse fecha
|
|
||||||
const date = new Date(s.created_at);
|
|
||||||
const formattedDate = date.toLocaleDateString('es-ES', { day: '2-digit', month: 'short' });
|
|
||||||
|
|
||||||
tbody.innerHTML += `
|
|
||||||
<tr class="hover:bg-blue-50 cursor-pointer transition border-b last:border-0 bg-white"
|
|
||||||
onclick="openDetail(${s.id}, '${s.contact_name}', '${s.title}', '${s.status_name}', '${color}', '${formattedDate}')">
|
|
||||||
<td class="p-4 text-gray-500 whitespace-nowrap font-mono text-xs">${formattedDate}</td>
|
|
||||||
<td class="p-4">
|
|
||||||
<p class="font-bold text-gray-900">${s.contact_name}</p>
|
|
||||||
<p class="text-xs text-gray-500 truncate max-w-[200px] flex items-center gap-1"><i data-lucide="map-pin" class="w-3 h-3"></i> ${s.address}</p>
|
|
||||||
</td>
|
|
||||||
<td class="p-4">
|
|
||||||
<p class="text-sm text-gray-700 truncate max-w-[250px]">${s.description || 'Sin detalles'}</p>
|
|
||||||
${s.is_urgent ? '<span class="text-[10px] font-bold text-red-600 bg-red-100 px-1 rounded uppercase">Urgente</span>' : ''}
|
|
||||||
${s.is_company ? `<span class="text-[10px] font-bold text-blue-600 bg-blue-100 px-1 rounded uppercase ml-1">${s.company_name || 'Compañía'}</span>` : ''}
|
|
||||||
</td>
|
|
||||||
<td class="p-4">
|
|
||||||
<span class="px-3 py-1 rounded-full text-xs font-bold text-white shadow-sm bg-${color}-500 whitespace-nowrap">
|
|
||||||
${s.status_name || 'Nuevo'}
|
|
||||||
</span>
|
|
||||||
</td>
|
|
||||||
<td class="p-4 text-right"><i data-lucide="chevron-right" class="w-5 h-5 text-gray-300"></i></td>
|
|
||||||
</tr>
|
|
||||||
`;
|
|
||||||
});
|
|
||||||
lucide.createIcons();
|
|
||||||
} catch (e) { console.error(e); }
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- LÓGICA DE CREAR ---
|
|
||||||
function toggleCompanyFields() {
|
|
||||||
const isChecked = document.getElementById('sIsCompany').checked;
|
|
||||||
const div = document.getElementById('companyFields');
|
|
||||||
if(isChecked) {
|
|
||||||
div.classList.remove('hidden');
|
|
||||||
loadCompanies();
|
|
||||||
} else {
|
|
||||||
div.classList.add('hidden');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function searchClientByPhone() {
|
|
||||||
const phone = document.getElementById('sPhone').value;
|
|
||||||
if(phone.length < 8) return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const res = await fetch(`${API_URL}/clients/search?phone=${phone}`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
|
|
||||||
const data = await res.json();
|
|
||||||
|
|
||||||
if (data.ok && data.client) {
|
|
||||||
const c = data.client;
|
|
||||||
document.getElementById('sName').value = c.full_name;
|
|
||||||
document.getElementById('sEmail').value = c.email || "";
|
|
||||||
document.getElementById('clientFoundMsg').classList.remove('hidden');
|
|
||||||
|
|
||||||
const addresses = c.addresses || [];
|
|
||||||
if (addresses.length > 0) {
|
|
||||||
document.getElementById('sAddress').value = addresses[addresses.length - 1];
|
|
||||||
const select = document.getElementById('sAddressSelect');
|
|
||||||
select.innerHTML = '<option value="">Otras direcciones...</option>';
|
|
||||||
addresses.forEach(addr => select.innerHTML += `<option value="${addr}">${addr}</option>`);
|
|
||||||
if (addresses.length > 1) select.classList.remove('hidden');
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
document.getElementById('clientFoundMsg').classList.add('hidden');
|
|
||||||
document.getElementById('sAddressSelect').classList.add('hidden');
|
|
||||||
}
|
|
||||||
} catch (e) { console.error(e); }
|
|
||||||
}
|
|
||||||
|
|
||||||
function selectAddress(val) { if(val) document.getElementById('sAddress').value = val; }
|
|
||||||
|
|
||||||
async function createService(e) {
|
|
||||||
e.preventDefault();
|
|
||||||
const btn = document.getElementById('btnSave');
|
|
||||||
btn.disabled = true; btn.innerText = "Guardando...";
|
|
||||||
|
|
||||||
const data = {
|
|
||||||
phone: document.getElementById('sPhone').value,
|
|
||||||
name: document.getElementById('sName').value,
|
|
||||||
address: document.getElementById('sAddress').value,
|
|
||||||
email: document.getElementById('sEmail').value,
|
|
||||||
description: document.getElementById('sDesc').value,
|
|
||||||
scheduled_date: document.getElementById('sDate').value,
|
|
||||||
scheduled_time: document.getElementById('sTime').value,
|
|
||||||
duration: document.getElementById('sDuration').value,
|
|
||||||
is_urgent: document.getElementById('sUrgent').checked,
|
|
||||||
is_company: document.getElementById('sIsCompany').checked,
|
|
||||||
company_id: document.getElementById('sCompanyId').value || null,
|
|
||||||
company_ref: document.getElementById('sCompanyRef').value,
|
|
||||||
internal_notes: document.getElementById('sNotesInternal').value,
|
|
||||||
client_notes: document.getElementById('sNotesClient').value
|
|
||||||
};
|
|
||||||
|
|
||||||
try {
|
|
||||||
const res = await fetch(`${API_URL}/services`, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
|
|
||||||
body: JSON.stringify(data)
|
|
||||||
});
|
|
||||||
const json = await res.json();
|
|
||||||
|
|
||||||
if (json.ok) {
|
|
||||||
showToast("✅ Servicio Creado");
|
|
||||||
document.querySelector('form').reset(); // Limpiar
|
|
||||||
toggleView('list'); // Volver
|
|
||||||
} else {
|
|
||||||
showToast("❌ " + json.error, true);
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
showToast("Error de conexión", true);
|
|
||||||
} finally {
|
|
||||||
btn.disabled = false; btn.innerHTML = '<i data-lucide="save" class="w-6 h-6"></i> CREAR SERVICIO'; lucide.createIcons();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- LÓGICA DE DETALLE Y ESTADOS ---
|
|
||||||
async function openDetail(id, client, title, statusName, statusColor, date) {
|
|
||||||
currentServiceId = id;
|
|
||||||
document.getElementById('serviceDetailPanel').classList.remove('hidden');
|
|
||||||
|
|
||||||
// Llenar datos cabecera
|
|
||||||
document.getElementById('detailTitle').innerText = title || 'Servicio General';
|
|
||||||
document.getElementById('detailClient').innerText = client;
|
|
||||||
document.getElementById('detailId').innerText = `#${id}`;
|
|
||||||
document.getElementById('detailDate').innerText = date;
|
|
||||||
|
|
||||||
const badge = document.getElementById('detailStatusBadge');
|
|
||||||
badge.innerText = statusName;
|
|
||||||
// Limpiar clases previas de color
|
|
||||||
badge.className = `px-2 py-1 rounded text-[10px] font-bold text-white uppercase tracking-wide bg-${statusColor}-500`;
|
|
||||||
|
|
||||||
// Llenar selector de estados
|
|
||||||
const sel = document.getElementById('newStatusSelect');
|
|
||||||
sel.innerHTML = "";
|
|
||||||
allStatuses.forEach(s => {
|
|
||||||
sel.innerHTML += `<option value="${s.id}">${s.name}</option>`;
|
|
||||||
});
|
|
||||||
|
|
||||||
// Cargar Historial
|
|
||||||
loadTimeline(id);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function loadTimeline(id) {
|
|
||||||
const timeline = document.getElementById('statusTimeline');
|
|
||||||
timeline.innerHTML = '<p class="text-xs text-gray-400">Cargando...</p>';
|
|
||||||
|
|
||||||
const res = await fetch(`${API_URL}/services/${id}/logs`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
|
|
||||||
const data = await res.json();
|
|
||||||
|
|
||||||
timeline.innerHTML = "";
|
|
||||||
if(data.logs.length === 0) { timeline.innerHTML = '<p class="text-sm text-gray-400">Sin historial registrado.</p>'; return; }
|
|
||||||
|
|
||||||
data.logs.forEach(log => {
|
|
||||||
const color = log.new_color || 'gray';
|
|
||||||
const date = new Date(log.created_at);
|
|
||||||
|
|
||||||
timeline.innerHTML += `
|
|
||||||
<div class="mb-6 relative group">
|
|
||||||
<span class="absolute -left-[33px] flex items-center justify-center w-6 h-6 bg-${color}-100 rounded-full ring-4 ring-white group-hover:scale-110 transition-transform">
|
|
||||||
<div class="w-2 h-2 bg-${color}-600 rounded-full"></div>
|
|
||||||
</span>
|
|
||||||
<div class="flex justify-between items-center mb-1">
|
|
||||||
<h3 class="text-sm font-bold text-gray-800">${log.new_status}</h3>
|
|
||||||
<time class="text-[10px] font-medium text-gray-400 uppercase">${date.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})} · ${date.toLocaleDateString()}</time>
|
|
||||||
</div>
|
|
||||||
<div class="bg-gray-50 p-3 rounded-lg border border-gray-100 text-sm text-gray-600 hover:bg-white hover:shadow-sm transition-all">
|
|
||||||
<p>${log.comment || 'Cambio de estado'}</p>
|
|
||||||
<p class="text-[10px] text-gray-400 mt-2 text-right italic border-t border-gray-100 pt-1">
|
|
||||||
Usuario: ${log.user_name || 'Sistema'}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
`;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async function updateStatus() {
|
|
||||||
const statusId = document.getElementById('newStatusSelect').value;
|
|
||||||
if(!statusId) return;
|
|
||||||
const comment = prompt("Añade un comentario sobre este cambio (opcional):");
|
|
||||||
|
|
||||||
try {
|
|
||||||
await fetch(`${API_URL}/services/${currentServiceId}/status`, {
|
|
||||||
method: 'PUT',
|
|
||||||
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
|
|
||||||
body: JSON.stringify({ status_id: statusId, comment: comment })
|
|
||||||
});
|
|
||||||
showToast("Estado actualizado");
|
|
||||||
loadTimeline(currentServiceId); // Recargar logs
|
|
||||||
fetchServices(); // Recargar lista fondo
|
|
||||||
} catch(e) { showToast("Error al actualizar", true); }
|
|
||||||
}
|
|
||||||
|
|
||||||
function closeDetailPanel() { document.getElementById('serviceDetailPanel').classList.add('hidden'); }
|
|
||||||
|
|
||||||
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-2xl transition-all duration-300 z-50 flex items-center gap-3 ${isError ? 'bg-red-600' : 'bg-slate-800'} text-white`;
|
|
||||||
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