7914 lines
384 KiB
JavaScript
7914 lines
384 KiB
JavaScript
import express from "express";
|
||
import cors from "cors";
|
||
import bcrypt from "bcryptjs";
|
||
import jwt from "jsonwebtoken";
|
||
|
||
import pg from "pg";
|
||
import crypto from "crypto";
|
||
import OpenAI from "openai";
|
||
import Stripe from "stripe";
|
||
import rateLimit from "express-rate-limit";
|
||
import fs from "fs";
|
||
import path from "path";
|
||
import { fileURLToPath } from "url";
|
||
import { PDFDocument, StandardFonts, rgb } from "pdf-lib";
|
||
|
||
const { Pool } = pg;
|
||
const __filename = fileURLToPath(import.meta.url);
|
||
const __dirname = path.dirname(__filename);
|
||
const app = express();
|
||
app.set("trust proxy", 1); // Necesario para express-rate-limit detrás del proxy de Coolify
|
||
|
||
|
||
// ð SEMÃFORO IA: Guarda los IDs de los servicios que están siendo procesados
|
||
const candadosIA = new Set();
|
||
|
||
// ð DEBOUNCE IA: si el cliente manda varios WhatsApps seguidos, esperamos a que pare
|
||
// de escribir para contestar una sola vez (evita respuestas fragmentadas o duplicadas)
|
||
const debounceTimersIA = new Map();
|
||
const IA_DEBOUNCE_MS = 8000;
|
||
|
||
// ð ESTADO DEL MINI-DIÃLOGO DE COMANDOS DE ADMIN (por owner): cuando el admin escribe
|
||
// "escribe a [teléfono]" desde su móvil personal, guardamos aquà que estamos esperando
|
||
// que nos diga el motivo, antes de contactar al cliente. Es en memoria (si el servidor
|
||
// reinicia a mitad, el admin simplemente tiene que repetir el comando).
|
||
const adminIntakeState = new Map();
|
||
|
||
// Configuración de CORS Profesional
|
||
const corsOptions = {
|
||
origin: [
|
||
'https://web.integrarepara.es',
|
||
'https://portal.integrarepara.es',
|
||
'https://app.integrarepara.es',
|
||
'http://localhost:3000',
|
||
'http://127.0.0.1:3000'
|
||
],
|
||
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
|
||
allowedHeaders: ['Content-Type', 'Authorization'],
|
||
credentials: true,
|
||
optionsSuccessStatus: 200
|
||
};
|
||
|
||
app.use(cors(corsOptions));
|
||
// Habilitar pre-flight para todas las rutas
|
||
app.options('*', cors(corsOptions));
|
||
|
||
// ==========================================
|
||
// ð³ WEBHOOK STRIPE (DEBE IR ANTES DE express.json)
|
||
// ==========================================
|
||
app.post("/webhook/stripe", express.raw({ type: "application/json" }), async (req, res) => {
|
||
let event;
|
||
|
||
try {
|
||
if (!STRIPE_WEBHOOK_SECRET) {
|
||
console.error("â STRIPE_WEBHOOK_SECRET no configurado.");
|
||
return res.status(500).send("Webhook secret no configurado");
|
||
}
|
||
|
||
const signature = req.headers["stripe-signature"];
|
||
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY || "sk_test_dummy", { apiVersion: "2023-10-16" });
|
||
|
||
event = stripe.webhooks.constructEvent(req.body, signature, STRIPE_WEBHOOK_SECRET);
|
||
} catch (err) {
|
||
console.error("â Firma webhook Stripe inválida:", err.message);
|
||
return res.status(400).send(`Webhook Error: ${err.message}`);
|
||
}
|
||
|
||
const insertarEventoPago = async ({
|
||
subscriptionId = null,
|
||
companyId = null,
|
||
stripeInvoiceId = null,
|
||
stripePaymentIntentId = null,
|
||
stripeCheckoutSessionId = null,
|
||
stripeEventId = null,
|
||
amount = 0,
|
||
currency = "eur",
|
||
status = "pendiente",
|
||
eventType = null,
|
||
paidAt = null
|
||
}) => {
|
||
try {
|
||
await pool.query(`
|
||
INSERT INTO protection_payment_events (
|
||
subscription_id,
|
||
company_id,
|
||
stripe_invoice_id,
|
||
stripe_payment_intent_id,
|
||
stripe_checkout_session_id,
|
||
stripe_event_id,
|
||
amount,
|
||
currency,
|
||
status,
|
||
event_type,
|
||
paid_at
|
||
)
|
||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)
|
||
`, [
|
||
subscriptionId,
|
||
companyId,
|
||
stripeInvoiceId,
|
||
stripePaymentIntentId,
|
||
stripeCheckoutSessionId,
|
||
stripeEventId,
|
||
amount,
|
||
currency,
|
||
status,
|
||
eventType,
|
||
paidAt
|
||
]);
|
||
} catch (e) {
|
||
console.error("â ï¸ Error insertando protection_payment_events:", e.message);
|
||
}
|
||
};
|
||
|
||
try {
|
||
switch (event.type) {
|
||
// =====================================================
|
||
// 1. CHECKOUT COMPLETADO
|
||
// =====================================================
|
||
case "checkout.session.completed": {
|
||
const session = event.data.object;
|
||
const metadata = session.metadata || {};
|
||
const paymentType = metadata.type;
|
||
|
||
// ð¢ PLAN DE PROTECCIÃN
|
||
if (paymentType === "protection_plan") {
|
||
const subscriptionId = parseInt(metadata.subscription_id, 10);
|
||
const ownerId = parseInt(metadata.owner_id, 10);
|
||
|
||
if (!subscriptionId || !ownerId) {
|
||
console.warn("â ï¸ checkout.session.completed sin metadata válida para protection_plan");
|
||
break;
|
||
}
|
||
|
||
await pool.query(`
|
||
UPDATE protection_subscriptions
|
||
SET
|
||
payment_status = 'pagado',
|
||
status = 'activo',
|
||
stripe_customer_id = COALESCE($1, stripe_customer_id),
|
||
stripe_subscription_id = COALESCE($2, stripe_subscription_id),
|
||
started_at = COALESCE(started_at, NOW()),
|
||
last_payment_at = NOW(),
|
||
updated_at = NOW()
|
||
WHERE id = $3 AND company_id = $4
|
||
`, [
|
||
session.customer ? String(session.customer) : null,
|
||
session.subscription ? String(session.subscription) : null,
|
||
subscriptionId,
|
||
ownerId
|
||
]);
|
||
|
||
await pool.query(`
|
||
INSERT INTO protection_activity (company_id, type, description)
|
||
VALUES ($1, 'cobro', $2)
|
||
`, [
|
||
ownerId,
|
||
`Alta confirmada por Stripe. Suscripción #${subscriptionId} activada correctamente.`
|
||
]);
|
||
|
||
await insertarEventoPago({
|
||
subscriptionId,
|
||
companyId: ownerId,
|
||
stripeCheckoutSessionId: session.id || null,
|
||
stripePaymentIntentId: session.payment_intent || null,
|
||
stripeEventId: event.id,
|
||
amount: ((session.amount_total || 0) / 100),
|
||
currency: session.currency || "eur",
|
||
status: "paid",
|
||
eventType: event.type,
|
||
paidAt: new Date()
|
||
});
|
||
|
||
console.log(`â
[STRIPE] Alta plan activada. Sub ID ${subscriptionId}`);
|
||
}
|
||
// ðµ PRESUPUESTO NORMAL
|
||
else {
|
||
const budgetId = session.metadata?.budget_id;
|
||
const ownerId = session.metadata?.owner_id;
|
||
const amountTotal = ((session.amount_total || 0) / 100).toFixed(2);
|
||
|
||
if (!budgetId || !ownerId) {
|
||
console.warn("â ï¸ checkout.session.completed de presupuesto sin metadata suficiente");
|
||
break;
|
||
}
|
||
|
||
await pool.query(
|
||
"UPDATE budgets SET status = 'paid' WHERE id = $1 AND owner_id = $2",
|
||
[budgetId, ownerId]
|
||
);
|
||
|
||
const sq = await pool.query(`
|
||
SELECT id, raw_data
|
||
FROM scraped_services
|
||
WHERE service_ref = $1 AND owner_id = $2
|
||
`, [`PRE-${budgetId}`, ownerId]);
|
||
|
||
if (sq.rowCount > 0) {
|
||
const serviceId = sq.rows[0].id;
|
||
let rawData = sq.rows[0].raw_data || {};
|
||
rawData.is_paid = true;
|
||
|
||
await pool.query(
|
||
"UPDATE scraped_services SET raw_data = $1 WHERE id = $2",
|
||
[JSON.stringify(rawData), serviceId]
|
||
);
|
||
|
||
await pool.query(`
|
||
INSERT INTO service_financials (scraped_id, amount, payment_method, is_paid)
|
||
VALUES ($1, $2, 'Tarjeta (Stripe)', true)
|
||
ON CONFLICT (scraped_id)
|
||
DO UPDATE SET
|
||
amount = EXCLUDED.amount,
|
||
is_paid = true,
|
||
payment_method = 'Tarjeta (Stripe)',
|
||
updated_at = NOW()
|
||
`, [serviceId, amountTotal]);
|
||
|
||
await pool.query(`
|
||
INSERT INTO scraped_service_logs (scraped_id, user_name, action, details)
|
||
VALUES ($1, $2, $3, $4)
|
||
`, [
|
||
serviceId,
|
||
"Stripe API",
|
||
"Pago Confirmado",
|
||
`El cliente ha abonado ${amountTotal}⬠por pasarela segura.`
|
||
]);
|
||
}
|
||
|
||
const ownerQ = await pool.query("SELECT phone FROM users WHERE id = $1", [ownerId]);
|
||
if (ownerQ.rowCount > 0) {
|
||
const msgWa = `ð° *¡PAGO RECIBIDO (STRIPE)!*\n\nSe acaba de confirmar el pago con tarjeta del presupuesto *PRE-${budgetId}* por un importe de *${amountTotal}â¬*.\n\nEl sistema lo ha marcado como pagado automáticamente.`;
|
||
sendWhatsAppAuto(ownerQ.rows[0].phone, msgWa, `cliente_${ownerId}`, false).catch(console.error);
|
||
}
|
||
|
||
console.log(`â
[STRIPE] Presupuesto PRE-${budgetId} pagado`);
|
||
}
|
||
|
||
break;
|
||
}
|
||
|
||
// =====================================================
|
||
// 2. FACTURA PAGADA (RENOVACIONES Y COBROS REALES)
|
||
// =====================================================
|
||
case "invoice.paid": {
|
||
const invoice = event.data.object;
|
||
const stripeSubscriptionId = invoice.subscription ? String(invoice.subscription) : null;
|
||
if (!stripeSubscriptionId) break;
|
||
|
||
const subQ = await pool.query(`
|
||
SELECT id, company_id
|
||
FROM protection_subscriptions
|
||
WHERE stripe_subscription_id = $1
|
||
ORDER BY created_at DESC
|
||
LIMIT 1
|
||
`, [stripeSubscriptionId]);
|
||
|
||
if (subQ.rowCount === 0) {
|
||
console.warn(`â ï¸ invoice.paid sin subscription local para ${stripeSubscriptionId}`);
|
||
break;
|
||
}
|
||
|
||
const localSub = subQ.rows[0];
|
||
|
||
const periodStartUnix =
|
||
invoice.lines?.data?.[0]?.period?.start || null;
|
||
const periodEndUnix =
|
||
invoice.lines?.data?.[0]?.period?.end || null;
|
||
|
||
await pool.query(`
|
||
UPDATE protection_subscriptions
|
||
SET
|
||
payment_status = 'pagado',
|
||
status = 'activo',
|
||
stripe_customer_id = COALESCE($1, stripe_customer_id),
|
||
current_period_start = COALESCE(to_timestamp($2), current_period_start),
|
||
current_period_end = COALESCE(to_timestamp($3), current_period_end),
|
||
renewal_date = CASE
|
||
WHEN $3 IS NOT NULL THEN to_timestamp($3)::date
|
||
ELSE renewal_date
|
||
END,
|
||
last_payment_at = NOW(),
|
||
updated_at = NOW()
|
||
WHERE id = $4
|
||
`, [
|
||
invoice.customer ? String(invoice.customer) : null,
|
||
periodStartUnix,
|
||
periodEndUnix,
|
||
localSub.id
|
||
]);
|
||
|
||
await pool.query(`
|
||
INSERT INTO protection_activity (company_id, type, description)
|
||
VALUES ($1, 'cobro', $2)
|
||
`, [
|
||
localSub.company_id,
|
||
`Cobro mensual confirmado por Stripe para la suscripción #${localSub.id}.`
|
||
]);
|
||
|
||
await insertarEventoPago({
|
||
subscriptionId: localSub.id,
|
||
companyId: localSub.company_id,
|
||
stripeInvoiceId: invoice.id || null,
|
||
stripePaymentIntentId: invoice.payment_intent || null,
|
||
stripeEventId: event.id,
|
||
amount: ((invoice.amount_paid || 0) / 100),
|
||
currency: invoice.currency || "eur",
|
||
status: "paid",
|
||
eventType: event.type,
|
||
paidAt: new Date()
|
||
});
|
||
|
||
console.log(`â
[STRIPE] invoice.paid procesado para sub local ${localSub.id}`);
|
||
break;
|
||
}
|
||
|
||
// =====================================================
|
||
// 3. FACTURA FALLIDA
|
||
// =====================================================
|
||
case "invoice.payment_failed": {
|
||
const invoice = event.data.object;
|
||
const stripeSubscriptionId = invoice.subscription ? String(invoice.subscription) : null;
|
||
if (!stripeSubscriptionId) break;
|
||
|
||
const subQ = await pool.query(`
|
||
SELECT id, company_id
|
||
FROM protection_subscriptions
|
||
WHERE stripe_subscription_id = $1
|
||
ORDER BY created_at DESC
|
||
LIMIT 1
|
||
`, [stripeSubscriptionId]);
|
||
|
||
if (subQ.rowCount === 0) break;
|
||
|
||
const localSub = subQ.rows[0];
|
||
|
||
await pool.query(`
|
||
UPDATE protection_subscriptions
|
||
SET
|
||
payment_status = 'impagado',
|
||
status = 'suspendido',
|
||
updated_at = NOW()
|
||
WHERE id = $1
|
||
`, [localSub.id]);
|
||
|
||
await pool.query(`
|
||
INSERT INTO protection_activity (company_id, type, description)
|
||
VALUES ($1, 'cobro', $2)
|
||
`, [
|
||
localSub.company_id,
|
||
`Pago fallido detectado por Stripe en la suscripción #${localSub.id}.`
|
||
]);
|
||
|
||
await insertarEventoPago({
|
||
subscriptionId: localSub.id,
|
||
companyId: localSub.company_id,
|
||
stripeInvoiceId: invoice.id || null,
|
||
stripePaymentIntentId: invoice.payment_intent || null,
|
||
stripeEventId: event.id,
|
||
amount: ((invoice.amount_due || 0) / 100),
|
||
currency: invoice.currency || "eur",
|
||
status: "failed",
|
||
eventType: event.type,
|
||
paidAt: null
|
||
});
|
||
|
||
console.log(`â ï¸ [STRIPE] invoice.payment_failed para sub local ${localSub.id}`);
|
||
break;
|
||
}
|
||
|
||
// =====================================================
|
||
// 4. SUSCRIPCIÃN ACTUALIZADA
|
||
// =====================================================
|
||
case "customer.subscription.updated": {
|
||
const subscription = event.data.object;
|
||
const stripeSubscriptionId = subscription.id ? String(subscription.id) : null;
|
||
if (!stripeSubscriptionId) break;
|
||
|
||
await pool.query(`
|
||
UPDATE protection_subscriptions
|
||
SET
|
||
stripe_customer_id = COALESCE($1, stripe_customer_id),
|
||
current_period_start = COALESCE(to_timestamp($2), current_period_start),
|
||
current_period_end = COALESCE(to_timestamp($3), current_period_end),
|
||
renewal_date = CASE
|
||
WHEN $3 IS NOT NULL THEN to_timestamp($3)::date
|
||
ELSE renewal_date
|
||
END,
|
||
cancel_at_period_end = COALESCE($4, cancel_at_period_end),
|
||
status = CASE
|
||
WHEN $5 = 'active' THEN 'activo'
|
||
WHEN $5 IN ('past_due', 'unpaid') THEN 'suspendido'
|
||
WHEN $5 IN ('canceled', 'incomplete_expired') THEN 'cancelado'
|
||
ELSE status
|
||
END,
|
||
payment_status = CASE
|
||
WHEN $5 = 'active' THEN 'pagado'
|
||
WHEN $5 IN ('past_due', 'unpaid') THEN 'impagado'
|
||
ELSE payment_status
|
||
END,
|
||
updated_at = NOW()
|
||
WHERE stripe_subscription_id = $6
|
||
`, [
|
||
subscription.customer ? String(subscription.customer) : null,
|
||
subscription.current_period_start || null,
|
||
subscription.current_period_end || null,
|
||
subscription.cancel_at_period_end ?? false,
|
||
subscription.status || null,
|
||
stripeSubscriptionId
|
||
]);
|
||
|
||
console.log(`ð [STRIPE] customer.subscription.updated ${stripeSubscriptionId}`);
|
||
break;
|
||
}
|
||
|
||
// =====================================================
|
||
// 5. SUSCRIPCIÃN CANCELADA / TERMINADA
|
||
// =====================================================
|
||
case "customer.subscription.deleted": {
|
||
const subscription = event.data.object;
|
||
const stripeSubscriptionId = subscription.id ? String(subscription.id) : null;
|
||
if (!stripeSubscriptionId) break;
|
||
|
||
await pool.query(`
|
||
UPDATE protection_subscriptions
|
||
SET
|
||
status = 'cancelado',
|
||
cancel_at_period_end = false,
|
||
cancelled_at = NOW(),
|
||
ended_at = NOW(),
|
||
updated_at = NOW()
|
||
WHERE stripe_subscription_id = $1
|
||
`, [stripeSubscriptionId]);
|
||
|
||
console.log(`ð [STRIPE] customer.subscription.deleted ${stripeSubscriptionId}`);
|
||
break;
|
||
}
|
||
|
||
default:
|
||
console.log(`Evento Stripe ignorado: ${event.type}`);
|
||
break;
|
||
}
|
||
|
||
return res.json({ received: true });
|
||
|
||
} catch (e) {
|
||
console.error("â Error grave procesando Webhook de Stripe:", e.message);
|
||
return res.status(500).send(`Webhook Error: ${e.message}`);
|
||
}
|
||
});
|
||
|
||
// LÃmites de subida para logotipos en Base64
|
||
app.use(express.json({ limit: '10mb' }));
|
||
app.use(express.urlencoded({ limit: '10mb', extended: true }));
|
||
|
||
// VARIABLES DE ENTORNO
|
||
// --- 1. VARIABLES DE ENTORNO ---
|
||
const {
|
||
DATABASE_URL,
|
||
JWT_SECRET,
|
||
EVOLUTION_BASE_URL,
|
||
EVOLUTION_API_KEY,
|
||
EVOLUTION_INSTANCE,
|
||
OPENAI_API_KEY, // ð LEER LLAVE
|
||
OPENAI_MODEL, // ð LEER MODELO
|
||
STRIPE_WEBHOOK_SECRET
|
||
|
||
} = process.env;
|
||
|
||
// --- 2. INICIALIZACIÃN GLOBAL DEL MOTOR IA (ESTO ES LO QUE TE FALTABA) ---
|
||
const openai = new OpenAI({
|
||
apiKey: OPENAI_API_KEY,
|
||
});
|
||
|
||
// --- 3. DIAGNÃSTICO DE INICIO ---
|
||
console.log("------------------------------------------------");
|
||
console.log("ð VERSIÃN COMPLETA - INTEGRA REPARA SAAS");
|
||
console.log("------------------------------------------------");
|
||
|
||
if (!STRIPE_WEBHOOK_SECRET) {
|
||
console.error("â ï¸ AVISO: Falta STRIPE_WEBHOOK_SECRET en variables de entorno.");
|
||
} else {
|
||
console.log("â
Stripe Webhook Secret detectado.");
|
||
}
|
||
|
||
if (!OPENAI_API_KEY) {
|
||
console.error("â ï¸ AVISO: Falta OPENAI_API_KEY en variables de entorno.");
|
||
} else {
|
||
console.log("â
OpenAI API Key detectada. IA lista para operar.");
|
||
}
|
||
|
||
if (!EVOLUTION_BASE_URL) console.error("â ï¸ AVISO: Falta EVOLUTION_BASE_URL");
|
||
else console.log("â
Evolution URL:", EVOLUTION_BASE_URL);
|
||
|
||
if (!EVOLUTION_INSTANCE) console.error("â ï¸ AVISO: Falta EVOLUTION_INSTANCE");
|
||
else console.log("â
Instancia Notificaciones:", EVOLUTION_INSTANCE);
|
||
|
||
console.log("------------------------------------------------");
|
||
|
||
if (!DATABASE_URL || !JWT_SECRET) process.exit(1);
|
||
|
||
const pool = new Pool({ connectionString: DATABASE_URL, ssl: false });
|
||
|
||
// ==========================================
|
||
// ð° CONFIGURACIÃN DE PLANES (SAAS)
|
||
// ==========================================
|
||
const PLAN_LIMITS = {
|
||
'free': { name: 'Básico Gratuito', whatsapp_enabled: false, templates_enabled: false, automation_enabled: false },
|
||
'standard': { name: 'Estándar', whatsapp_enabled: true, templates_enabled: true, automation_enabled: false },
|
||
'pro': { name: 'Profesional', whatsapp_enabled: true, templates_enabled: true, automation_enabled: true }
|
||
};
|
||
|
||
// ==========================================
|
||
// ð§ AUTO-ACTUALIZACIÃN DB
|
||
// ==========================================
|
||
async function autoUpdateDB() {
|
||
const client = await pool.connect();
|
||
try {
|
||
console.log("ð Verificando estructura DB...");
|
||
|
||
await client.query(`
|
||
-- USUARIOS
|
||
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',
|
||
company_slug TEXT UNIQUE,
|
||
plan_tier TEXT DEFAULT 'free',
|
||
subscription_status TEXT DEFAULT 'active',
|
||
paid_providers_count INT DEFAULT 0,
|
||
zones JSONB DEFAULT '[]',
|
||
status TEXT DEFAULT 'active',
|
||
created_at TIMESTAMP DEFAULT NOW()
|
||
);
|
||
|
||
-- COLA DEL ROBOT
|
||
CREATE TABLE IF NOT EXISTS robot_queue (
|
||
id SERIAL PRIMARY KEY,
|
||
owner_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||
provider TEXT DEFAULT 'homeserve',
|
||
service_number TEXT NOT NULL,
|
||
new_status TEXT NOT NULL,
|
||
appointment_date TEXT,
|
||
observation TEXT,
|
||
inform_client BOOLEAN DEFAULT FALSE,
|
||
status TEXT DEFAULT 'PENDING', -- PENDING, RUNNING, DONE, FAILED
|
||
error_msg TEXT,
|
||
created_at TIMESTAMP DEFAULT NOW(),
|
||
updated_at TIMESTAMP DEFAULT NOW()
|
||
|
||
);
|
||
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()
|
||
);
|
||
|
||
-- CONFIGURACIÃN NEGOCIO
|
||
CREATE TABLE IF NOT EXISTS guilds (
|
||
id SERIAL PRIMARY KEY,
|
||
owner_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||
name TEXT NOT NULL,
|
||
created_at TIMESTAMP DEFAULT NOW()
|
||
);
|
||
CREATE TABLE IF NOT EXISTS user_guilds (
|
||
user_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||
guild_id INT REFERENCES guilds(id) ON DELETE CASCADE,
|
||
PRIMARY KEY (user_id, guild_id)
|
||
);
|
||
CREATE TABLE IF NOT EXISTS companies (
|
||
id SERIAL PRIMARY KEY,
|
||
owner_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||
name TEXT NOT NULL,
|
||
cif TEXT,
|
||
email TEXT,
|
||
phone TEXT,
|
||
address TEXT,
|
||
created_at TIMESTAMP DEFAULT NOW()
|
||
);
|
||
|
||
-- CLIENTES (CRM)
|
||
CREATE TABLE IF NOT EXISTS clients (
|
||
id SERIAL PRIMARY KEY,
|
||
owner_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||
full_name TEXT NOT NULL,
|
||
phone TEXT NOT NULL,
|
||
email TEXT,
|
||
addresses JSONB DEFAULT '[]',
|
||
notes TEXT,
|
||
created_at TIMESTAMP DEFAULT NOW()
|
||
);
|
||
|
||
-- ESTADOS Y PLANTILLAS
|
||
CREATE TABLE IF NOT EXISTS service_statuses (
|
||
id SERIAL PRIMARY KEY,
|
||
owner_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||
name TEXT NOT NULL,
|
||
color TEXT DEFAULT 'gray',
|
||
is_default BOOLEAN DEFAULT FALSE,
|
||
is_final BOOLEAN DEFAULT FALSE,
|
||
is_system BOOLEAN DEFAULT FALSE, -- AÃADIDO: Identificador de estados imborrables
|
||
created_at TIMESTAMP DEFAULT NOW()
|
||
);
|
||
CREATE TABLE IF NOT EXISTS message_templates (
|
||
id SERIAL PRIMARY KEY,
|
||
owner_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||
type TEXT NOT NULL,
|
||
content TEXT,
|
||
created_at TIMESTAMP DEFAULT NOW(),
|
||
UNIQUE(owner_id, type)
|
||
);
|
||
|
||
-- ZONAS
|
||
CREATE TABLE IF NOT EXISTS zones (
|
||
id SERIAL PRIMARY KEY,
|
||
name TEXT NOT NULL,
|
||
owner_id INT,
|
||
created_at TIMESTAMP DEFAULT NOW()
|
||
);
|
||
CREATE TABLE IF NOT EXISTS user_zones (
|
||
user_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||
zone_id INT REFERENCES zones(id) ON DELETE CASCADE,
|
||
PRIMARY KEY (user_id, zone_id)
|
||
);
|
||
|
||
|
||
-- ð¤ ROBOTS / PROVEEDORES
|
||
CREATE TABLE IF NOT EXISTS provider_credentials (
|
||
id SERIAL PRIMARY KEY,
|
||
owner_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||
provider TEXT NOT NULL,
|
||
username TEXT NOT NULL,
|
||
password_hash TEXT NOT NULL,
|
||
last_sync TIMESTAMP,
|
||
status TEXT DEFAULT 'active',
|
||
UNIQUE(owner_id, provider)
|
||
);
|
||
CREATE TABLE IF NOT EXISTS scraped_services (
|
||
id SERIAL PRIMARY KEY,
|
||
owner_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||
provider TEXT NOT NULL,
|
||
service_ref TEXT NOT NULL,
|
||
raw_data JSONB,
|
||
status TEXT DEFAULT 'pending',
|
||
automation_status TEXT DEFAULT 'manual',
|
||
created_at TIMESTAMP DEFAULT NOW(),
|
||
UNIQUE(owner_id, provider, service_ref)
|
||
);
|
||
|
||
-- ðºï¸ TABLA DE MAPEO DE VARIABLES
|
||
CREATE TABLE IF NOT EXISTS variable_mappings (
|
||
id SERIAL PRIMARY KEY,
|
||
owner_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||
provider TEXT NOT NULL,
|
||
original_key TEXT NOT NULL,
|
||
target_key TEXT,
|
||
is_ignored BOOLEAN DEFAULT FALSE,
|
||
created_at TIMESTAMP DEFAULT NOW(),
|
||
UNIQUE(owner_id, provider, original_key)
|
||
);
|
||
|
||
-- SERVICIOS (PRINCIPAL)
|
||
CREATE TABLE IF NOT EXISTS services (
|
||
id SERIAL PRIMARY KEY,
|
||
owner_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||
client_id INT REFERENCES clients(id) ON DELETE SET NULL,
|
||
status_id INT REFERENCES service_statuses(id) ON DELETE SET NULL,
|
||
guild_id INT REFERENCES guilds(id) ON DELETE SET NULL,
|
||
assigned_to INT REFERENCES users(id) ON DELETE SET NULL,
|
||
title TEXT,
|
||
description TEXT,
|
||
contact_phone TEXT,
|
||
contact_name TEXT,
|
||
address TEXT,
|
||
email TEXT,
|
||
scheduled_date DATE DEFAULT CURRENT_DATE,
|
||
scheduled_time TIME DEFAULT CURRENT_TIME,
|
||
duration_minutes INT DEFAULT 30,
|
||
is_urgent BOOLEAN DEFAULT FALSE,
|
||
is_company BOOLEAN DEFAULT FALSE,
|
||
company_id INT REFERENCES companies(id) ON DELETE SET NULL,
|
||
company_ref TEXT,
|
||
internal_notes TEXT,
|
||
client_notes TEXT,
|
||
import_source TEXT,
|
||
provider_data JSONB DEFAULT '{}',
|
||
closed_at TIMESTAMP,
|
||
created_at TIMESTAMP DEFAULT NOW()
|
||
);
|
||
CREATE TABLE IF NOT EXISTS service_logs (
|
||
id SERIAL PRIMARY KEY,
|
||
service_id INT REFERENCES services(id) ON DELETE CASCADE,
|
||
user_id INT REFERENCES users(id) ON DELETE SET NULL,
|
||
old_status_id INT REFERENCES service_statuses(id),
|
||
new_status_id INT REFERENCES service_statuses(id),
|
||
comment TEXT,
|
||
created_at TIMESTAMP DEFAULT NOW()
|
||
);
|
||
|
||
-- TABLA PARA ASIGNACIÃN AUTOMÃTICA
|
||
CREATE TABLE IF NOT EXISTS assignment_pings (
|
||
id SERIAL PRIMARY KEY,
|
||
scraped_id INT NOT NULL,
|
||
user_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||
token TEXT UNIQUE NOT NULL,
|
||
status TEXT DEFAULT 'pending',
|
||
expires_at TIMESTAMP NOT NULL,
|
||
created_at TIMESTAMP DEFAULT NOW()
|
||
);
|
||
|
||
-- ==========================================
|
||
-- ð¡ï¸ MÃDULO SAAS: PLANES DE PROTECCIÃN
|
||
-- ==========================================
|
||
CREATE TABLE IF NOT EXISTS protection_config (
|
||
company_id INT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
|
||
name TEXT,
|
||
email TEXT,
|
||
phone TEXT,
|
||
auto_renew BOOLEAN DEFAULT TRUE,
|
||
pre_notice BOOLEAN DEFAULT TRUE,
|
||
billing_method TEXT DEFAULT 'stripe',
|
||
contract_text TEXT,
|
||
updated_at TIMESTAMP DEFAULT NOW()
|
||
);
|
||
|
||
CREATE TABLE IF NOT EXISTS protection_plans (
|
||
id SERIAL PRIMARY KEY,
|
||
company_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||
name TEXT NOT NULL,
|
||
type TEXT NOT NULL,
|
||
price DECIMAL(10,2) DEFAULT 0.00,
|
||
renewal_price DECIMAL(10,2) DEFAULT 0.00,
|
||
urgencies_limit INT DEFAULT 0,
|
||
bricos_limit INT DEFAULT 0,
|
||
coverages TEXT,
|
||
|
||
billing_interval TEXT DEFAULT 'month',
|
||
billing_interval_count INT DEFAULT 1,
|
||
stripe_price_id TEXT,
|
||
is_active BOOLEAN DEFAULT TRUE,
|
||
updated_at TIMESTAMP DEFAULT NOW(),
|
||
|
||
created_at TIMESTAMP DEFAULT NOW()
|
||
);
|
||
|
||
CREATE TABLE IF NOT EXISTS protection_subscriptions (
|
||
id SERIAL PRIMARY KEY,
|
||
company_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||
plan_id INT REFERENCES protection_plans(id) ON DELETE RESTRICT,
|
||
client_name TEXT NOT NULL,
|
||
client_dni TEXT,
|
||
client_phone TEXT,
|
||
|
||
payment_status TEXT DEFAULT 'impagado',
|
||
status TEXT DEFAULT 'pendiente_pago',
|
||
|
||
custom_discount INT DEFAULT 0,
|
||
bricos_used INT DEFAULT 0,
|
||
urgencies_used INT DEFAULT 0,
|
||
|
||
renewal_date DATE,
|
||
contract_pdf_url TEXT,
|
||
|
||
stripe_session_id TEXT,
|
||
stripe_subscription_id TEXT,
|
||
stripe_customer_id TEXT,
|
||
stripe_price_id TEXT,
|
||
|
||
started_at TIMESTAMP,
|
||
current_period_start TIMESTAMP,
|
||
current_period_end TIMESTAMP,
|
||
last_payment_at TIMESTAMP,
|
||
cancel_at_period_end BOOLEAN DEFAULT FALSE,
|
||
cancelled_at TIMESTAMP,
|
||
ended_at TIMESTAMP,
|
||
updated_at TIMESTAMP DEFAULT NOW(),
|
||
|
||
created_at TIMESTAMP DEFAULT NOW()
|
||
);
|
||
|
||
CREATE TABLE IF NOT EXISTS protection_payment_events (
|
||
id SERIAL PRIMARY KEY,
|
||
subscription_id INT REFERENCES protection_subscriptions(id) ON DELETE CASCADE,
|
||
company_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||
stripe_invoice_id TEXT,
|
||
stripe_payment_intent_id TEXT,
|
||
stripe_checkout_session_id TEXT,
|
||
stripe_event_id TEXT,
|
||
amount DECIMAL(10,2) DEFAULT 0.00,
|
||
currency TEXT DEFAULT 'eur',
|
||
status TEXT NOT NULL,
|
||
event_type TEXT,
|
||
paid_at TIMESTAMP,
|
||
created_at TIMESTAMP DEFAULT NOW()
|
||
);
|
||
|
||
|
||
-- ð¬ CHAT Y NOTAS INTERNAS
|
||
CREATE TABLE IF NOT EXISTS service_communications (
|
||
id SERIAL PRIMARY KEY,
|
||
scraped_id INT REFERENCES scraped_services(id) ON DELETE CASCADE,
|
||
owner_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||
sender_id INT REFERENCES users(id) ON DELETE SET NULL,
|
||
sender_name TEXT NOT NULL,
|
||
sender_role TEXT,
|
||
message TEXT NOT NULL,
|
||
is_internal BOOLEAN DEFAULT FALSE,
|
||
created_at TIMESTAMP DEFAULT NOW()
|
||
);
|
||
|
||
-- ð§¾ PARTES DE TRABAJO (texto redactado con IA + firma del cliente + PDF)
|
||
CREATE TABLE IF NOT EXISTS work_reports (
|
||
id SERIAL PRIMARY KEY,
|
||
scraped_id INT REFERENCES scraped_services(id) ON DELETE CASCADE,
|
||
owner_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||
operator_id INT REFERENCES users(id) ON DELETE SET NULL,
|
||
operator_name TEXT,
|
||
client_name TEXT,
|
||
client_phone TEXT,
|
||
raw_text TEXT,
|
||
final_text TEXT NOT NULL,
|
||
signature_data TEXT,
|
||
pdf_base64 TEXT,
|
||
sent_to JSONB DEFAULT '[]',
|
||
created_at TIMESTAMP DEFAULT NOW()
|
||
);
|
||
|
||
-- ð AUTOMATIZACIONES DE RECORDATORIOS (SIN CITAR / ESPERA CLIENTE / DÃA ANTES)
|
||
CREATE TABLE IF NOT EXISTS automation_settings (
|
||
id SERIAL PRIMARY KEY,
|
||
owner_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||
automation_type TEXT NOT NULL,
|
||
enabled BOOLEAN DEFAULT FALSE,
|
||
test_mode BOOLEAN DEFAULT TRUE,
|
||
dias_espera_inicial INT DEFAULT 1,
|
||
dias_repeticion INT DEFAULT 3,
|
||
hora_envio TEXT DEFAULT '09:00',
|
||
created_at TIMESTAMP DEFAULT NOW(),
|
||
UNIQUE(owner_id, automation_type)
|
||
);
|
||
|
||
-- ð Seguimiento de cuándo entró cada servicio en el estado vigilado (para contar los dÃas de espera)
|
||
CREATE TABLE IF NOT EXISTS automation_tracking (
|
||
id SERIAL PRIMARY KEY,
|
||
owner_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||
service_id INT REFERENCES scraped_services(id) ON DELETE CASCADE,
|
||
automation_type TEXT NOT NULL,
|
||
first_seen_at TIMESTAMP DEFAULT NOW(),
|
||
UNIQUE(service_id, automation_type)
|
||
);
|
||
|
||
-- ð Historial de cada recordatorio automático enviado
|
||
CREATE TABLE IF NOT EXISTS automation_log (
|
||
id SERIAL PRIMARY KEY,
|
||
owner_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||
service_id INT REFERENCES scraped_services(id) ON DELETE CASCADE,
|
||
automation_type TEXT NOT NULL,
|
||
sent_at TIMESTAMP DEFAULT NOW()
|
||
);
|
||
`);
|
||
|
||
// PARCHE DE ACTUALIZACIÃN
|
||
await client.query(`
|
||
DO $$ BEGIN
|
||
|
||
-- ==========================================
|
||
-- ð¡ï¸ PARCHES MÃDULO PROTECCIÃN
|
||
-- ==========================================
|
||
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='protection_plans' AND column_name='billing_interval') THEN
|
||
ALTER TABLE protection_plans ADD COLUMN billing_interval TEXT DEFAULT 'month';
|
||
END IF;
|
||
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='protection_plans' AND column_name='billing_interval_count') THEN
|
||
ALTER TABLE protection_plans ADD COLUMN billing_interval_count INT DEFAULT 1;
|
||
END IF;
|
||
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='protection_plans' AND column_name='stripe_price_id') THEN
|
||
ALTER TABLE protection_plans ADD COLUMN stripe_price_id TEXT;
|
||
END IF;
|
||
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='protection_plans' AND column_name='is_active') THEN
|
||
ALTER TABLE protection_plans ADD COLUMN is_active BOOLEAN DEFAULT TRUE;
|
||
END IF;
|
||
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='protection_plans' AND column_name='updated_at') THEN
|
||
ALTER TABLE protection_plans ADD COLUMN updated_at TIMESTAMP DEFAULT NOW();
|
||
END IF;
|
||
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='protection_subscriptions' AND column_name='stripe_session_id') THEN
|
||
ALTER TABLE protection_subscriptions ADD COLUMN stripe_session_id TEXT;
|
||
END IF;
|
||
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='protection_subscriptions' AND column_name='stripe_subscription_id') THEN
|
||
ALTER TABLE protection_subscriptions ADD COLUMN stripe_subscription_id TEXT;
|
||
END IF;
|
||
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='protection_subscriptions' AND column_name='stripe_customer_id') THEN
|
||
ALTER TABLE protection_subscriptions ADD COLUMN stripe_customer_id TEXT;
|
||
END IF;
|
||
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='protection_subscriptions' AND column_name='stripe_price_id') THEN
|
||
ALTER TABLE protection_subscriptions ADD COLUMN stripe_price_id TEXT;
|
||
END IF;
|
||
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='protection_subscriptions' AND column_name='started_at') THEN
|
||
ALTER TABLE protection_subscriptions ADD COLUMN started_at TIMESTAMP;
|
||
END IF;
|
||
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='protection_subscriptions' AND column_name='current_period_start') THEN
|
||
ALTER TABLE protection_subscriptions ADD COLUMN current_period_start TIMESTAMP;
|
||
END IF;
|
||
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='protection_subscriptions' AND column_name='current_period_end') THEN
|
||
ALTER TABLE protection_subscriptions ADD COLUMN current_period_end TIMESTAMP;
|
||
END IF;
|
||
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='protection_subscriptions' AND column_name='last_payment_at') THEN
|
||
ALTER TABLE protection_subscriptions ADD COLUMN last_payment_at TIMESTAMP;
|
||
END IF;
|
||
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='protection_subscriptions' AND column_name='cancel_at_period_end') THEN
|
||
ALTER TABLE protection_subscriptions ADD COLUMN cancel_at_period_end BOOLEAN DEFAULT FALSE;
|
||
END IF;
|
||
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='protection_subscriptions' AND column_name='cancelled_at') THEN
|
||
ALTER TABLE protection_subscriptions ADD COLUMN cancelled_at TIMESTAMP;
|
||
END IF;
|
||
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='protection_subscriptions' AND column_name='ended_at') THEN
|
||
ALTER TABLE protection_subscriptions ADD COLUMN ended_at TIMESTAMP;
|
||
END IF;
|
||
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='protection_subscriptions' AND column_name='updated_at') THEN
|
||
ALTER TABLE protection_subscriptions ADD COLUMN updated_at TIMESTAMP DEFAULT NOW();
|
||
END IF;
|
||
|
||
CREATE TABLE IF NOT EXISTS protection_payment_events (
|
||
id SERIAL PRIMARY KEY,
|
||
subscription_id INT REFERENCES protection_subscriptions(id) ON DELETE CASCADE,
|
||
company_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||
stripe_invoice_id TEXT,
|
||
stripe_payment_intent_id TEXT,
|
||
stripe_checkout_session_id TEXT,
|
||
stripe_event_id TEXT,
|
||
amount DECIMAL(10,2) DEFAULT 0.00,
|
||
currency TEXT DEFAULT 'eur',
|
||
status TEXT NOT NULL,
|
||
event_type TEXT,
|
||
paid_at TIMESTAMP,
|
||
created_at TIMESTAMP DEFAULT NOW()
|
||
);
|
||
|
||
UPDATE protection_subscriptions
|
||
SET payment_status = 'impagado'
|
||
WHERE payment_status IS NULL OR payment_status = '';
|
||
|
||
UPDATE protection_subscriptions
|
||
SET status = 'pendiente_pago'
|
||
WHERE status IS NULL OR status = '';
|
||
|
||
ALTER TABLE protection_subscriptions ALTER COLUMN payment_status SET DEFAULT 'impagado';
|
||
ALTER TABLE protection_subscriptions ALTER COLUMN status SET DEFAULT 'pendiente_pago';
|
||
|
||
-- ð¢ AÃADIDO: Fecha de última lectura del chat por el operario
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='scraped_services' AND column_name='last_chat_read_worker') THEN
|
||
ALTER TABLE scraped_services ADD COLUMN last_chat_read_worker TIMESTAMP DEFAULT '2000-01-01';
|
||
END IF;
|
||
|
||
-- AÃADIDO: Control de envÃos automáticos de urgencias por proveedor
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='provider_credentials' AND column_name='auto_dispatch') THEN
|
||
ALTER TABLE provider_credentials ADD COLUMN auto_dispatch BOOLEAN DEFAULT FALSE;
|
||
END IF;
|
||
|
||
|
||
-- AÃADIDO: Token mágico para el Portal del Cliente
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='clients' AND column_name='portal_token') THEN
|
||
ALTER TABLE clients ADD COLUMN portal_token TEXT UNIQUE;
|
||
UPDATE clients SET portal_token = substr(md5(random()::text || id::text), 1, 12) WHERE portal_token IS NULL;
|
||
ALTER TABLE clients ALTER COLUMN portal_token SET DEFAULT substr(md5(random()::text || clock_timestamp()::text), 1, 12);
|
||
END IF;
|
||
|
||
-- AÃADIDO: Motor de Ranking
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='users' AND column_name='ranking_score') THEN
|
||
ALTER TABLE users ADD COLUMN ranking_score NUMERIC DEFAULT 50.0;
|
||
ALTER TABLE users ADD COLUMN ranking_data JSONB DEFAULT '{}'::jsonb;
|
||
END IF;
|
||
|
||
|
||
-- NUEVO: Columna para colores personalizados de la App
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='users' AND column_name='app_settings') THEN
|
||
ALTER TABLE users ADD COLUMN app_settings JSONB DEFAULT '{"primary": "#1e3a8a", "secondary": "#2563eb", "bg": "#f8fafc"}';
|
||
END IF;
|
||
|
||
-- AÃADIDO: Permiso para coger servicios libres de la bolsa
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='users' AND column_name='can_claim_services') THEN
|
||
ALTER TABLE users ADD COLUMN can_claim_services BOOLEAN DEFAULT TRUE;
|
||
END IF;
|
||
|
||
-- AÃADIDO: Columna para guardar la configuración de WhatsApp
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='users' AND column_name='wa_settings') THEN
|
||
ALTER TABLE users ADD COLUMN wa_settings JSONB DEFAULT '{}';
|
||
END IF;
|
||
|
||
-- AÃADIDO: Configuración del Portal del Cliente
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='users' AND column_name='company_logo') THEN
|
||
ALTER TABLE users ADD COLUMN company_logo TEXT;
|
||
END IF;
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='users' AND column_name='portal_settings') THEN
|
||
ALTER TABLE users ADD COLUMN portal_settings JSONB DEFAULT '{"m_start":"09:00", "m_end":"14:00", "a_start":"16:00", "a_end":"19:00"}';
|
||
END IF;
|
||
|
||
-- AÃADIDO: Guarda si ya se envió el PDF de la comparativa de luz al cliente
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='energy_quote_leads' AND column_name='pdf_enviado') THEN
|
||
ALTER TABLE energy_quote_leads ADD COLUMN pdf_enviado BOOLEAN DEFAULT FALSE;
|
||
END IF;
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='energy_quote_leads' AND column_name='pdf_enviado_at') THEN
|
||
ALTER TABLE energy_quote_leads ADD COLUMN pdf_enviado_at TIMESTAMP;
|
||
END IF;
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='energy_quote_leads' AND column_name='pdf_token') THEN
|
||
-- AÑADIDO: Token único para el enlace público permanente del PDF de comparativa de luz
|
||
ALTER TABLE energy_quote_leads ADD COLUMN pdf_token TEXT UNIQUE;
|
||
END IF;
|
||
|
||
-- AÃADIDO: Columna fÃsica de operario para el panel operativo
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='scraped_services' AND column_name='assigned_to') THEN
|
||
ALTER TABLE scraped_services ADD COLUMN assigned_to INT REFERENCES users(id);
|
||
END IF;
|
||
|
||
-- ASEGURAR COLUMNA URGENTE EN SCRAPED
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='scraped_services' AND column_name='is_urgent') THEN
|
||
ALTER TABLE scraped_services ADD COLUMN is_urgent BOOLEAN DEFAULT FALSE;
|
||
END IF;
|
||
|
||
-- AÃADIDO: Columna de palabras clave IA para los gremios
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='guilds' AND column_name='ia_keywords') THEN
|
||
ALTER TABLE guilds ADD COLUMN ia_keywords JSONB DEFAULT '[]';
|
||
END IF;
|
||
|
||
-- AÃADIDO: Columna para marcar estados imborrables del sistema
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='service_statuses' AND column_name='is_system') THEN
|
||
ALTER TABLE service_statuses ADD COLUMN is_system BOOLEAN DEFAULT FALSE;
|
||
END IF;
|
||
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='client_id') THEN ALTER TABLE services ADD COLUMN client_id INT REFERENCES clients(id) ON DELETE SET NULL; END IF;
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='status_id') THEN ALTER TABLE services ADD COLUMN status_id INT REFERENCES service_statuses(id) ON DELETE SET NULL; END IF;
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='contact_phone') THEN ALTER TABLE services ADD COLUMN contact_phone TEXT; END IF;
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='contact_name') THEN ALTER TABLE services ADD COLUMN contact_name TEXT; END IF;
|
||
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='users' AND column_name='plan_tier') THEN ALTER TABLE users ADD COLUMN plan_tier TEXT DEFAULT 'free'; END IF;
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='users' AND column_name='company_slug') THEN ALTER TABLE users ADD COLUMN company_slug TEXT UNIQUE; END IF;
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='users' AND column_name='zones') THEN ALTER TABLE users ADD COLUMN zones JSONB DEFAULT '[]'; END IF;
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='users' AND column_name='status') THEN ALTER TABLE users ADD COLUMN status TEXT DEFAULT 'active'; END IF;
|
||
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='provider_data') THEN ALTER TABLE services ADD COLUMN provider_data JSONB DEFAULT '{}'; END IF;
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='import_source') THEN ALTER TABLE services ADD COLUMN import_source TEXT; END IF;
|
||
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='scraped_services' AND column_name='automation_status') THEN ALTER TABLE scraped_services ADD COLUMN automation_status TEXT DEFAULT 'manual'; END IF;
|
||
|
||
-- AÃADIDO: Token mágico para el Portal del Cliente
|
||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='clients' AND column_name='portal_token') THEN
|
||
ALTER TABLE clients ADD COLUMN portal_token TEXT UNIQUE;
|
||
UPDATE clients SET portal_token = substr(md5(random()::text || id::text), 1, 12) WHERE portal_token IS NULL;
|
||
ALTER TABLE clients ALTER COLUMN portal_token SET DEFAULT substr(md5(random()::text || clock_timestamp()::text), 1, 12);
|
||
END IF;
|
||
|
||
BEGIN ALTER TABLE users DROP CONSTRAINT IF EXISTS users_phone_key; EXCEPTION WHEN OTHERS THEN NULL; END;
|
||
BEGIN ALTER TABLE users DROP CONSTRAINT IF EXISTS users_email_key; EXCEPTION WHEN OTHERS THEN NULL; END;
|
||
END $$;
|
||
`);
|
||
|
||
console.log("â
DB Sincronizada.");
|
||
} catch (e) { console.error("â Error DB:", e); } finally { client.release(); }
|
||
}
|
||
|
||
// ==========================================
|
||
// ð HELPERS (UNIFICACIÃN TOTAL DE TELÃFONOS)
|
||
// ==========================================
|
||
|
||
// 1. Extrae SIEMPRE exactamente 9 dÃgitos (Formato Nacional: 600123456)
|
||
function extractValidPhone(rawPhone) {
|
||
if (!rawPhone) return "";
|
||
let str = String(rawPhone).replace(/\D/g, ""); // Borra todo lo que no sea número (espacios, letras, +, -)
|
||
if (str.startsWith("0034")) str = str.slice(4);
|
||
if (str.startsWith("34") && str.length >= 11) str = str.slice(2);
|
||
|
||
const match = str.match(/[6789]\d{8}/);
|
||
return match ? match[0] : (str.length >= 9 ? str.slice(-9) : str);
|
||
}
|
||
|
||
// ð Un servicio puede traer VARIOS teléfonos mezclados en el mismo campo (tÃpico de HomeServe:
|
||
// "629046101 de 09:00 a 20:00\n659153929 de 09:00 a 20:00..."), fijos y móviles sin ningún orden.
|
||
// Esto extrae TODOS los números válidos que encuentre (de "Teléfono"/"TELEFONO"/"TELEFONOS"),
|
||
// sin duplicados, y los devuelve con los MÃVILES (6xx/7xx) siempre primero.
|
||
function extractAllPhones(raw) {
|
||
if (!raw) return [];
|
||
const sources = [raw['TELEFONOS'], raw['Teléfonos'], raw['Teléfono'], raw['TELEFONO']].filter(Boolean);
|
||
const seen = new Set();
|
||
const result = [];
|
||
|
||
for (const src of sources) {
|
||
const lines = String(src).split(/\n+/);
|
||
for (const line of lines) {
|
||
const matches = line.match(/[6789]\d{8}/g) || [];
|
||
for (const number of matches) {
|
||
if (seen.has(number)) continue;
|
||
seen.add(number);
|
||
const horario = line.match(/de\s*\d{1,2}:\d{2}\s*a\s*\d{1,2}:\d{2}/i)?.[0] || '';
|
||
const contactoMatch = line.match(/Persona de Contacto:\s*([^\n]*?)(?:\s*Observaciones:|$)/i);
|
||
const contacto = contactoMatch ? contactoMatch[1].trim() : '';
|
||
result.push({ number, isMobile: /^[67]/.test(number), horario, contacto });
|
||
}
|
||
}
|
||
}
|
||
|
||
result.sort((a, b) => (b.isMobile - a.isMobile));
|
||
return result;
|
||
}
|
||
|
||
// Igual que extractValidPhone, pero PRIORIZANDO MÃVILES: para automatizaciones de WhatsApp/SMS,
|
||
// que solo pueden llegar de verdad a un número móvil, no a un fijo.
|
||
function extractBestMobile(raw) {
|
||
const phones = extractAllPhones(raw);
|
||
if (phones.length > 0) return phones[0].number;
|
||
// Red de seguridad: si no detectamos ningún número con el patrón habitual, mantenemos
|
||
// el comportamiento anterior para no perder del todo la posibilidad de contactar.
|
||
const fallbackRaw = (raw && (raw["Teléfono"] || raw["TELEFONO"] || raw["TELEFONOS"])) || "";
|
||
return extractValidPhone(fallbackRaw);
|
||
}
|
||
|
||
// 2. Normaliza SIEMPRE a Formato Internacional para la Base de Datos (+34600123456)
|
||
function normalizePhone(phone) {
|
||
const clean = extractValidPhone(phone);
|
||
return clean ? "+34" + clean : "";
|
||
}
|
||
|
||
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 genCode6() { return String(Math.floor(100000 + Math.random() * 900000)); }
|
||
|
||
|
||
// ==========================================
|
||
// ð¡ï¸ ESCUDO DE TITANIO: ANTI-SOLAPAMIENTOS BBDD
|
||
// ==========================================
|
||
async function comprobarDisponibilidad(ownerId, workerId, date, time, durationMin, excludeId = null) {
|
||
try {
|
||
if (!ownerId || !workerId || !date || !time) {
|
||
return { choca: false };
|
||
}
|
||
|
||
const parseTimeToMinutes = (value) => {
|
||
if (!value) return null;
|
||
const parts = String(value).trim().split(":");
|
||
if (parts.length < 2) return null;
|
||
const hh = parseInt(parts[0], 10);
|
||
const mm = parseInt(parts[1], 10);
|
||
if (Number.isNaN(hh) || Number.isNaN(mm)) return null;
|
||
return (hh * 60) + mm;
|
||
};
|
||
|
||
const requestedStart = parseTimeToMinutes(time);
|
||
const requestedDuration = Math.max(parseInt(durationMin, 10) || 60, 1);
|
||
|
||
if (requestedStart === null) {
|
||
return { choca: false };
|
||
}
|
||
|
||
const requestedEnd = requestedStart + requestedDuration;
|
||
|
||
let query = `
|
||
SELECT
|
||
id,
|
||
service_ref,
|
||
COALESCE(
|
||
NULLIF(raw_data->>'scheduled_time', ''),
|
||
CASE
|
||
WHEN raw_data->>'appointment_status' = 'pending' THEN NULLIF(raw_data->>'requested_time', '')
|
||
ELSE NULL
|
||
END
|
||
) as effective_time,
|
||
COALESCE(
|
||
NULLIF(raw_data->>'duration_minutes', ''),
|
||
'60'
|
||
) as effective_duration
|
||
FROM scraped_services
|
||
WHERE owner_id = $1
|
||
AND assigned_to = $2
|
||
AND status != 'archived'
|
||
AND (
|
||
raw_data->>'scheduled_date' = $3
|
||
OR (
|
||
raw_data->>'appointment_status' = 'pending'
|
||
AND raw_data->>'requested_date' = $3
|
||
)
|
||
)
|
||
`;
|
||
|
||
const params = [ownerId, workerId, date];
|
||
|
||
if (excludeId) {
|
||
query += ` AND id != $4`;
|
||
params.push(excludeId);
|
||
}
|
||
|
||
const q = await pool.query(query, params);
|
||
|
||
for (const row of q.rows) {
|
||
const start = parseTimeToMinutes(row.effective_time);
|
||
if (start === null) continue;
|
||
|
||
const duration = Math.max(parseInt(row.effective_duration, 10) || 60, 1);
|
||
const end = start + duration;
|
||
|
||
if (requestedStart < end && requestedEnd > start) {
|
||
return {
|
||
choca: true,
|
||
ref: row.service_ref || `ID-${row.id}`,
|
||
time: row.effective_time
|
||
};
|
||
}
|
||
}
|
||
|
||
return { choca: false };
|
||
} catch (e) {
|
||
console.error("â Error en comprobarDisponibilidad:", e.message);
|
||
return { choca: false };
|
||
}
|
||
}
|
||
|
||
// ==========================================
|
||
// ð SISTEMA DE AUTENTICACIÃN (LOGIN Y SESIÃN)
|
||
// ==========================================
|
||
app.post("/auth/login", async (req, res) => {
|
||
try {
|
||
const { email, password } = req.body;
|
||
if (!email || !password) return res.status(400).json({ ok: false, error: "Faltan datos" });
|
||
|
||
const q = await pool.query("SELECT * FROM users WHERE email = $1 OR phone = $1 LIMIT 1", [email]);
|
||
if (q.rowCount === 0) return res.status(401).json({ ok: false, error: "Credenciales incorrectas" });
|
||
|
||
const user = q.rows[0];
|
||
|
||
if (user.is_verified === false) {
|
||
return res.status(403).json({
|
||
ok: false,
|
||
error: "Cuenta no verificada. Por favor, revisa tu WhatsApp o contacta con soporte.",
|
||
require_verification: true
|
||
});
|
||
}
|
||
|
||
if (user.status !== 'active') return res.status(403).json({ ok: false, error: "Cuenta inactiva o bloqueada" });
|
||
|
||
const valid = await bcrypt.compare(password, user.password_hash);
|
||
if (!valid) return res.status(401).json({ ok: false, error: "Credenciales incorrectas" });
|
||
|
||
// ð¡ï¸ DEVOLVEMOS LA NORMALIDAD: Leemos el rol real de la base de datos
|
||
// (Si por algún casual estuviera vacÃo, le ponemos operario por seguridad)
|
||
const safeRole = user.role ? String(user.role).trim().toLowerCase() : 'operario';
|
||
user.role = safeRole;
|
||
|
||
const token = signToken(user);
|
||
|
||
res.json({
|
||
ok: true,
|
||
token,
|
||
user: {
|
||
id: user.id,
|
||
full_name: user.full_name,
|
||
role: safeRole, // Enviamos si es admin u operario correctamente
|
||
accountId: user.owner_id || user.id
|
||
}
|
||
});
|
||
} catch (e) {
|
||
console.error("Error en Login:", e);
|
||
res.status(500).json({ ok: false, error: "Error interno del servidor" });
|
||
}
|
||
});
|
||
|
||
// ð¢ RUTA RESUCITADA: VERIFICACIÃN DE SESIÃN (AUTH ME) ð¢
|
||
app.get("/auth/me", authMiddleware, async (req, res) => {
|
||
try {
|
||
const q = await pool.query("SELECT id, full_name, email, phone, role, company_slug, plan_tier FROM users WHERE id = $1", [req.user.sub]);
|
||
if (q.rowCount === 0) return res.status(404).json({ ok: false });
|
||
|
||
const userData = q.rows[0];
|
||
|
||
// ð¡ï¸ EL EXORCISMO DEL ROL: Por si entra con sesión guardada
|
||
let safeRole = userData.role ? String(userData.role).trim().toLowerCase() : 'operario';
|
||
if (safeRole === '' || safeRole === 'null') safeRole = 'operario';
|
||
userData.role = safeRole;
|
||
|
||
res.json({ ok: true, user: userData });
|
||
} catch (e) {
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
// ==========================================
|
||
// ð REGISTRO DE NUEVAS EMPRESAS (SAAS)
|
||
// ==========================================
|
||
app.post("/auth/register", async (req, res) => {
|
||
try {
|
||
const { fullName, email, phone, password, dni, address } = req.body;
|
||
|
||
if (!email || !password || !fullName || !phone) {
|
||
return res.status(400).json({ ok: false, error: "Faltan datos obligatorios" });
|
||
}
|
||
|
||
const p = normalizePhone(phone);
|
||
|
||
// 1. Verificamos si el email o teléfono ya están en uso
|
||
const check = await pool.query("SELECT id FROM users WHERE email = $1 OR phone = $2", [email, p]);
|
||
if (check.rowCount > 0) {
|
||
return res.status(400).json({ ok: false, error: "El email o teléfono ya están registrados" });
|
||
}
|
||
|
||
const hash = await bcrypt.hash(password, 10);
|
||
|
||
// 2. Creamos al usuario como ADMIN (dueño de su propia empresa/instancia)
|
||
// Lo creamos como NO verificado hasta que ponga el código
|
||
const insert = await pool.query(`
|
||
INSERT INTO users (full_name, email, phone, password_hash, dni, address, role, status, is_verified)
|
||
VALUES ($1, $2, $3, $4, $5, $6, 'admin', 'active', FALSE)
|
||
RETURNING id
|
||
`, [fullName, email, p, hash, dni || null, address || null]);
|
||
|
||
const newUserId = insert.rows[0].id;
|
||
|
||
// 3. Le asignamos su propio ID como owner_id (es el jefe de su panel)
|
||
await pool.query("UPDATE users SET owner_id = $1 WHERE id = $2", [newUserId, newUserId]);
|
||
|
||
// 4. Generamos el código de 6 dÃgitos para el WhatsApp
|
||
const code = genCode6();
|
||
const codeHash = await bcrypt.hash(code, 10);
|
||
|
||
await pool.query(`
|
||
INSERT INTO login_codes (user_id, phone, code_hash, purpose, expires_at)
|
||
VALUES ($1, $2, $3, 'register_verify', NOW() + INTERVAL '15 minutes')
|
||
`, [newUserId, p, codeHash]);
|
||
|
||
console.log(`ð [SISTEMA] Código de verificación para ${p}: ${code}`);
|
||
|
||
// 5. Enviamos el WhatsApp usando la instancia principal
|
||
// ð NUEVO: Le quitamos el sÃmbolo "+" para que Evolution no dé error
|
||
const phoneForEvolution = p.replace('+', '');
|
||
const msg = `ð *¡Bienvenido a IntegraRepara!*\n\nTu código de verificación es: *${code}*\n\nTiene una validez de 15 minutos.`;
|
||
|
||
if (process.env.EVOLUTION_INSTANCE) {
|
||
sendWhatsAppAuto(phoneForEvolution, msg, process.env.EVOLUTION_INSTANCE, false).catch(console.error);
|
||
} else {
|
||
console.warn("â ï¸ No se pudo enviar el WhatsApp: Falta la variable EVOLUTION_INSTANCE en Coolify.");
|
||
}
|
||
|
||
res.json({ ok: true, message: "Código enviado" });
|
||
} catch (e) {
|
||
console.error("Error en Registro:", e);
|
||
res.status(500).json({ ok: false, error: "Error interno del servidor" });
|
||
}
|
||
});
|
||
|
||
// ==========================================
|
||
// â
VERIFICACIÃN DEL CÃDIGO (OTP)
|
||
// ==========================================
|
||
app.post("/auth/verify", async (req, res) => {
|
||
try {
|
||
const { phone, code } = req.body;
|
||
const p = normalizePhone(phone);
|
||
|
||
// Buscamos códigos pendientes para ese teléfono
|
||
const q = await pool.query(`
|
||
SELECT c.*, u.id as u_id, u.full_name, u.role, u.owner_id
|
||
FROM login_codes c
|
||
JOIN users u ON c.user_id = u.id
|
||
WHERE c.phone = $1 AND c.consumed_at IS NULL AND c.expires_at > NOW()
|
||
ORDER BY c.created_at DESC LIMIT 1
|
||
`, [p]);
|
||
|
||
if (q.rowCount === 0) return res.status(400).json({ ok: false, error: "Código inválido o caducado" });
|
||
|
||
const codeRecord = q.rows[0];
|
||
const valid = await bcrypt.compare(code, codeRecord.code_hash);
|
||
|
||
if (!valid) return res.status(400).json({ ok: false, error: "Código incorrecto" });
|
||
|
||
// Marcamos código como usado y usuario como verificado
|
||
await pool.query("UPDATE login_codes SET consumed_at = NOW() WHERE id = $1", [codeRecord.id]);
|
||
await pool.query("UPDATE users SET is_verified = TRUE WHERE id = $1", [codeRecord.u_id]);
|
||
|
||
// Generamos su token de sesión para que entre directo
|
||
const token = signToken({
|
||
id: codeRecord.u_id,
|
||
email: codeRecord.email, // Aquà si usaras email en el token
|
||
phone: codeRecord.phone,
|
||
role: codeRecord.role,
|
||
owner_id: codeRecord.owner_id
|
||
});
|
||
|
||
res.json({ ok: true, token, user: { id: codeRecord.u_id, full_name: codeRecord.full_name, role: codeRecord.role } });
|
||
} catch (e) {
|
||
console.error("Error en Verificación:", e);
|
||
res.status(500).json({ ok: false, error: "Error en el servidor" });
|
||
}
|
||
});
|
||
|
||
// ==========================================
|
||
// ð¤ PUENTE AUTOMÃTICO HACIA HOMESERVE
|
||
// ==========================================
|
||
async function triggerHomeServeRobot(ownerId, serviceId, eventType) {
|
||
try {
|
||
// 1. Obtener la configuración del robot y los datos del servicio
|
||
const userQ = await pool.query("SELECT wa_settings FROM users WHERE id=$1", [ownerId]);
|
||
const settings = userQ.rows[0]?.wa_settings?.robot_homeserve || {};
|
||
|
||
const rule = settings[eventType];
|
||
if (!rule || !rule.enabled) {
|
||
console.log(`ð¤ [ROBOT HS] Regla '${eventType}' desactivada. Omitiendo.`);
|
||
return;
|
||
}
|
||
|
||
const svcQ = await pool.query(`
|
||
SELECT s.service_ref, s.raw_data, u.full_name as worker_name
|
||
FROM scraped_services s
|
||
LEFT JOIN users u ON s.assigned_to = u.id
|
||
WHERE s.id = $1
|
||
`, [serviceId]);
|
||
if (svcQ.rowCount === 0) return;
|
||
|
||
const s = svcQ.rows[0];
|
||
const raw = s.raw_data || {};
|
||
|
||
// 2. Calcular la fecha de Siguiente Acción (Formato exacto HomeServe DD/MM/YYYY)
|
||
let targetDate = new Date();
|
||
let formattedDate = "";
|
||
|
||
if (eventType === 'date' && raw.scheduled_date) {
|
||
// ð¯ SI ES "CITA", usamos estrictamente la fecha en la que se ha agendado
|
||
const [y, m, d] = raw.scheduled_date.split('-');
|
||
formattedDate = `${d.padStart(2, '0')}/${m.padStart(2, '0')}/${y}`;
|
||
} else {
|
||
// ð
SI ES "ASIGNAR" o "NO LOCALIZADO", sumamos los dÃas a partir de HOY
|
||
const daysToAdd = parseInt(rule.days_next) || 0;
|
||
targetDate.setDate(targetDate.getDate() + daysToAdd);
|
||
|
||
// Blindaje: Si la fecha resultante cae en fin de semana, la movemos al Lunes
|
||
if (targetDate.getDay() === 6) targetDate.setDate(targetDate.getDate() + 2); // Si es Sábado -> Suma 2 dÃas (Lunes)
|
||
else if (targetDate.getDay() === 0) targetDate.setDate(targetDate.getDate() + 1); // Si es Domingo -> Suma 1 dÃa (Lunes)
|
||
|
||
const dd = String(targetDate.getDate()).padStart(2, '0');
|
||
const mm = String(targetDate.getMonth() + 1).padStart(2, '0');
|
||
const yyyy = targetDate.getFullYear();
|
||
formattedDate = `${dd}/${mm}/${yyyy}`;
|
||
}
|
||
|
||
// 3. Traducir variables personalizadas
|
||
let text = rule.obs || "";
|
||
const clientName = raw["Nombre Cliente"] || raw["CLIENTE"] || "Cliente";
|
||
let clientPhone = extractBestMobile(raw);
|
||
|
||
// Formateo humano de la fecha para el texto de observaciones
|
||
let textoFechaCita = "hoy";
|
||
if (raw.scheduled_date) {
|
||
const [y, m, d] = raw.scheduled_date.split('-');
|
||
textoFechaCita = `${d.padStart(2, '0')}/${m.padStart(2, '0')}/${y}`;
|
||
} else {
|
||
// Si no hay cita agendada (Ej: No localizado), usamos la fecha de hoy para el texto
|
||
const hoy = new Date();
|
||
textoFechaCita = `${String(hoy.getDate()).padStart(2, '0')}/${String(hoy.getMonth() + 1).padStart(2, '0')}/${hoy.getFullYear()}`;
|
||
}
|
||
|
||
text = text.replace(/{{NOMBRE}}/g, clientName);
|
||
text = text.replace(/{{FECHA}}/g, textoFechaCita);
|
||
|
||
// Si no hay hora (ej: No localizado), ponemos la hora actual
|
||
const horaActual = `${String(new Date().getHours()).padStart(2, '0')}:${String(new Date().getMinutes()).padStart(2, '0')}`;
|
||
text = text.replace(/{{HORA}}/g, raw["scheduled_time"] || horaActual);
|
||
|
||
text = text.replace(/{{TELEFONO}}/g, clientPhone);
|
||
text = text.replace(/{{REFERENCIA}}/g, s.service_ref);
|
||
text = text.replace(/{{NOMBRE_OPERARIO}}/g, s.worker_name || "el técnico");
|
||
|
||
// 4. ESCUDO ANTI-POPUP HOMESERVE (MÃnimo 20 caracteres)
|
||
if (text.length < 25) {
|
||
text += " - Actualizado por el sistema.";
|
||
}
|
||
|
||
// 5. Mandar la orden definitiva al Robot
|
||
await pool.query(`
|
||
INSERT INTO robot_queue (owner_id, provider, service_number, new_status, appointment_date, observation, inform_client)
|
||
VALUES ($1, 'homeserve', $2, $3, $4, $5, $6)
|
||
`, [ownerId, s.service_ref, rule.status, formattedDate, text, rule.check_inform]);
|
||
|
||
console.log(`ð¤ [ROBOT HS] Orden enviada a la cola para exp ${s.service_ref} (Regla: ${eventType}) | Fecha: ${formattedDate} | Obs: "${text}"`);
|
||
|
||
} catch(e) {
|
||
console.error("â Error en puente HomeServe:", e);
|
||
}
|
||
}
|
||
|
||
// ==========================================
|
||
// ð¤ PUENTE AUTOMÃTICO HACIA MULTIASISTENCIA
|
||
// ==========================================
|
||
async function triggerMultiRobot(ownerId, serviceId, eventType) {
|
||
try {
|
||
const userQ = await pool.query("SELECT wa_settings FROM users WHERE id=$1", [ownerId]);
|
||
const settings = userQ.rows[0]?.wa_settings?.robot_multi || {};
|
||
|
||
const rule = settings[eventType];
|
||
if (!rule || !rule.enabled) {
|
||
console.log(`ð¤ [ROBOT MULTI] Regla '${eventType}' desactivada. Omitiendo.`);
|
||
return;
|
||
}
|
||
|
||
const svcQ = await pool.query(`
|
||
SELECT s.service_ref, s.raw_data, u.full_name as worker_name
|
||
FROM scraped_services s
|
||
LEFT JOIN users u ON s.assigned_to = u.id
|
||
WHERE s.id = $1
|
||
`, [serviceId]);
|
||
if (svcQ.rowCount === 0) return;
|
||
|
||
const s = svcQ.rows[0];
|
||
const raw = s.raw_data || {};
|
||
|
||
let targetDate = new Date();
|
||
let formattedDate = "";
|
||
let formattedTime = "";
|
||
|
||
if (eventType === 'date' && raw.scheduled_date) {
|
||
const [y, m, d] = raw.scheduled_date.split('-');
|
||
formattedDate = `${d.padStart(2, '0')}/${m.padStart(2, '0')}/${y}`;
|
||
formattedTime = raw.scheduled_time || "";
|
||
} else {
|
||
const daysToAdd = parseInt(rule.days_next) || 0;
|
||
targetDate.setDate(targetDate.getDate() + daysToAdd);
|
||
|
||
if (targetDate.getDay() === 6) targetDate.setDate(targetDate.getDate() + 2);
|
||
else if (targetDate.getDay() === 0) targetDate.setDate(targetDate.getDate() + 1);
|
||
|
||
const dd = String(targetDate.getDate()).padStart(2, '0');
|
||
const mm = String(targetDate.getMonth() + 1).padStart(2, '0');
|
||
const yyyy = targetDate.getFullYear();
|
||
formattedDate = `${dd}/${mm}/${yyyy}`;
|
||
|
||
const horaActual = `${String(new Date().getHours()).padStart(2, '0')}:${String(new Date().getMinutes()).padStart(2, '0')}`;
|
||
formattedTime = raw.scheduled_time || horaActual;
|
||
}
|
||
|
||
let text = rule.obs || "";
|
||
const clientName = raw["Nombre Cliente"] || raw["CLIENTE"] || "Cliente";
|
||
let clientPhone = extractBestMobile(raw);
|
||
|
||
let textoFechaCita = "hoy";
|
||
if (raw.scheduled_date) {
|
||
const [y, m, d] = raw.scheduled_date.split('-');
|
||
textoFechaCita = `${d.padStart(2, '0')}/${m.padStart(2, '0')}/${y}`;
|
||
} else {
|
||
const hoy = new Date();
|
||
textoFechaCita = `${String(hoy.getDate()).padStart(2, '0')}/${String(hoy.getMonth() + 1).padStart(2, '0')}/${hoy.getFullYear()}`;
|
||
}
|
||
|
||
text = text.replace(/{{NOMBRE}}/g, clientName);
|
||
text = text.replace(/{{FECHA}}/g, textoFechaCita);
|
||
text = text.replace(/{{HORA}}/g, formattedTime);
|
||
text = text.replace(/{{TELEFONO}}/g, clientPhone);
|
||
text = text.replace(/{{REFERENCIA}}/g, s.service_ref);
|
||
text = text.replace(/{{NOMBRE_OPERARIO}}/g, s.worker_name || "el técnico");
|
||
|
||
// Añadimos columna si no existe por si acaso
|
||
await pool.query(`ALTER TABLE robot_queue ADD COLUMN IF NOT EXISTS appointment_time TEXT;`).catch(() => {});
|
||
|
||
await pool.query(`
|
||
INSERT INTO robot_queue (owner_id, provider, service_number, new_status, appointment_date, appointment_time, observation, inform_client)
|
||
VALUES ($1, 'multiasistencia', $2, $3, $4, $5, $6, false)
|
||
`, [ownerId, s.service_ref, rule.status, formattedDate, formattedTime, text]);
|
||
|
||
console.log(`ð¤ [ROBOT MULTI] Orden enviada a la cola para exp ${s.service_ref} (Regla: ${eventType}) | Fecha: ${formattedDate} | Hora: ${formattedTime}`);
|
||
|
||
} catch(e) {
|
||
console.error("â Error en puente Multiasistencia:", e);
|
||
}
|
||
}
|
||
|
||
|
||
// ==========================================
|
||
// ðµï¸ ROBOT NOTARIO (TRAZABILIDAD TOTAL)
|
||
// ==========================================
|
||
async function registrarMovimiento(serviceId, userId, action, details) {
|
||
try {
|
||
let userName = "Sistema Robot";
|
||
if (userId) {
|
||
const u = await pool.query("SELECT full_name FROM users WHERE id=$1", [userId]);
|
||
if (u.rowCount > 0) userName = u.rows[0].full_name;
|
||
}
|
||
await pool.query(
|
||
"INSERT INTO scraped_service_logs (scraped_id, user_name, action, details) VALUES ($1, $2, $3, $4)",
|
||
[serviceId, userName, action, details || ""]
|
||
);
|
||
} catch (e) { console.error("Error Robot Notario:", e); }
|
||
}
|
||
|
||
// ==========================================
|
||
// ð§ CEREBRO IA (WHATSAPP)
|
||
// ==========================================
|
||
// ð£ï¸ Texto por defecto del bloque "Estilo e instrucciones de la empresa" que se ve y se
|
||
// edita desde el cuadro de "Instrucciones y estilo de la IA" en Configuración Avanzada.
|
||
// Si la empresa no ha guardado nunca nada en ese cuadro, se usa este texto (que es
|
||
// exactamente el comportamiento que la IA tenÃa antes de poder editarse desde el panel).
|
||
const DEFAULT_REGLAS_NEGOCIO_IA = `Habla de tú, de forma natural, clara, cercana y profesional.
|
||
Los fines de semana solo se ofrecen citas si es una urgencia.
|
||
Máximo 2 frases por mensaje: sé claro y directo.
|
||
No te presentes de nuevo si ya habéis hablado antes.
|
||
No uses la muletilla "¿En qué más te puedo ayudar?".`;
|
||
|
||
async function procesarConIA(ownerId, mensajeCliente, datosExpediente) {
|
||
try {
|
||
const userQ = await pool.query(
|
||
"SELECT wa_settings, full_name, portal_settings FROM users WHERE id=$1",
|
||
[ownerId]
|
||
);
|
||
|
||
if (userQ.rowCount === 0) return null;
|
||
|
||
const userData = userQ.rows[0];
|
||
const settings = userData?.wa_settings || {};
|
||
// ð£ï¸ Estilo e instrucciones de la empresa: editable desde el panel web
|
||
// (Configuración Avanzada â cuadro "Instrucciones y estilo de la IA"). Si la
|
||
// empresa nunca ha guardado nada ahÃ, usamos el texto por defecto de siempre.
|
||
const reglasNegocioIA = (settings.ai_custom_prompt && settings.ai_custom_prompt.trim())
|
||
? settings.ai_custom_prompt.trim()
|
||
: DEFAULT_REGLAS_NEGOCIO_IA;
|
||
const empresaNombre = userData?.full_name || "nuestra empresa";
|
||
|
||
// ð§¾ Condiciones de cobertura por compañÃa y/o gremio: cada regla puede llevar una
|
||
// "keyword" corta (ej. "santander") que buscamos DENTRO del campo CompañÃa del
|
||
// expediente, sin mayúsculas ni tildes (asà da igual si el texto viene envuelto en
|
||
// cosas de Multiasistencia/HomeServe, ej. "MULTI - Siniestros - Santander Generales
|
||
// proyecto Gesca" â con que contenga la palabra clave, coincide), y/o un "gremio_id"
|
||
// (el id del gremio tal cual está en la tabla guilds) para que las condiciones
|
||
// cambien según sea manitas, electricista, fontanerÃa, etc. Una regla necesita al
|
||
// menos uno de los dos criterios; si solo lleva uno, ese criterio se ignora (aplica
|
||
// a "todas las compañÃas" o "todos los gremios" según cuál falte). Si varias reglas
|
||
// coinciden a la vez, gana la más especÃfica (la que combina compañÃa + gremio).
|
||
const normalizarTexto = (str) => String(str || "").toLowerCase().normalize("NFD").replace(/[Ì-ͯ]/g, "");
|
||
const coverageRules = Array.isArray(settings.coverage_rules) ? settings.coverage_rules : [];
|
||
const companiaNormalizada = normalizarTexto(datosExpediente.compania);
|
||
const gremioIdActual = String(datosExpediente.guild_id || "");
|
||
const reglasCoincidentes = coverageRules.filter(r => {
|
||
if (!r.keyword && !r.gremio_id) return false;
|
||
const matchCompania = r.keyword ? companiaNormalizada.includes(normalizarTexto(r.keyword)) : true;
|
||
const matchGremio = r.gremio_id ? String(r.gremio_id) === gremioIdActual : true;
|
||
return matchCompania && matchGremio;
|
||
});
|
||
const especificidad = (r) => (r.keyword ? 1 : 0) + (r.gremio_id ? 1 : 0);
|
||
const reglaCobertura = reglasCoincidentes.sort((a, b) => especificidad(b) - especificidad(a))[0];
|
||
|
||
if (!settings.wa_ai_enabled) return null;
|
||
|
||
const pSettings = userData?.portal_settings || {};
|
||
const horarios = {
|
||
m_start: pSettings.m_start || "09:00",
|
||
m_end: pSettings.m_end || "14:00",
|
||
a_start: pSettings.a_start || "16:00",
|
||
a_end: pSettings.a_end || "19:00"
|
||
};
|
||
|
||
const fechaHoyTexto = new Intl.DateTimeFormat("es-ES", {
|
||
timeZone: "Europe/Madrid",
|
||
weekday: "long",
|
||
year: "numeric",
|
||
month: "long",
|
||
day: "numeric"
|
||
}).format(new Date());
|
||
|
||
// =========================================================
|
||
// HELPERS INTERNOS (AUTOCONTENIDOS, PARA NO ROMPER TU SERVER)
|
||
// =========================================================
|
||
const parseTimeToMinutes = (value) => {
|
||
if (!value) return null;
|
||
const parts = String(value).trim().split(":");
|
||
if (parts.length < 2) return null;
|
||
const hh = parseInt(parts[0], 10);
|
||
const mm = parseInt(parts[1], 10);
|
||
if (Number.isNaN(hh) || Number.isNaN(mm)) return null;
|
||
return (hh * 60) + mm;
|
||
};
|
||
|
||
const minutesToHHMM = (mins) => {
|
||
const safe = Math.max(0, mins);
|
||
const hh = String(Math.floor(safe / 60)).padStart(2, "0");
|
||
const mm = String(safe % 60).padStart(2, "0");
|
||
return `${hh}:${mm}`;
|
||
};
|
||
|
||
const roundUpTo30 = (mins) => Math.ceil(mins / 30) * 30;
|
||
const roundDownTo30 = (mins) => Math.floor(mins / 30) * 30;
|
||
|
||
const mergeIntervals = (intervals) => {
|
||
if (!Array.isArray(intervals) || intervals.length === 0) return [];
|
||
const sorted = [...intervals].sort((a, b) => a[0] - b[0]);
|
||
const merged = [sorted[0]];
|
||
|
||
for (let i = 1; i < sorted.length; i++) {
|
||
const [curStart, curEnd] = sorted[i];
|
||
const last = merged[merged.length - 1];
|
||
|
||
if (curStart <= last[1]) {
|
||
last[1] = Math.max(last[1], curEnd);
|
||
} else {
|
||
merged.push([curStart, curEnd]);
|
||
}
|
||
}
|
||
|
||
return merged;
|
||
};
|
||
|
||
const getMadridNowInfo = () => {
|
||
const fmt = new Intl.DateTimeFormat("en-CA", {
|
||
timeZone: "Europe/Madrid",
|
||
year: "numeric",
|
||
month: "2-digit",
|
||
day: "2-digit",
|
||
hour: "2-digit",
|
||
minute: "2-digit",
|
||
hour12: false
|
||
});
|
||
|
||
const parts = fmt.formatToParts(new Date());
|
||
const map = {};
|
||
for (const p of parts) {
|
||
if (p.type !== "literal") map[p.type] = p.value;
|
||
}
|
||
|
||
return {
|
||
todayISO: `${map.year}-${map.month}-${map.day}`,
|
||
currentMinutes: (parseInt(map.hour, 10) * 60) + parseInt(map.minute, 10)
|
||
};
|
||
};
|
||
|
||
const addDaysISO = (isoDate, daysToAdd) => {
|
||
const [y, m, d] = isoDate.split("-").map(Number);
|
||
const dt = new Date(Date.UTC(y, m - 1, d));
|
||
dt.setUTCDate(dt.getUTCDate() + daysToAdd);
|
||
return dt.toISOString().slice(0, 10);
|
||
};
|
||
|
||
const isWeekendISO = (isoDate) => {
|
||
const [y, m, d] = isoDate.split("-").map(Number);
|
||
const dt = new Date(Date.UTC(y, m - 1, d));
|
||
const day = dt.getUTCDay();
|
||
return day === 0 || day === 6;
|
||
};
|
||
|
||
const formatDisplayDateES = (isoDate) => {
|
||
const [y, m, d] = isoDate.split("-").map(Number);
|
||
return new Date(y, m - 1, d, 12, 0, 0).toLocaleDateString("es-ES", {
|
||
weekday: "long",
|
||
day: "numeric",
|
||
month: "long"
|
||
});
|
||
};
|
||
|
||
const calcularHuecosDisponiblesExactos = async () => {
|
||
if (!datosExpediente.worker_id) return [];
|
||
|
||
// ð§ Ciudad del cliente actual (misma lógica de zonas que usa el portal público)
|
||
const workerZonesQ = await pool.query("SELECT zones FROM users WHERE id = $1", [datosExpediente.worker_id]);
|
||
const workerZones = workerZonesQ.rows[0]?.zones || [];
|
||
const targetGuildId = datosExpediente.guild_id || null;
|
||
|
||
function getCityForCP(cp, fallbackPop) {
|
||
const cleanCP = String(cp || "").trim();
|
||
const zone = Array.isArray(workerZones) ? workerZones.find(z => z.cps === cleanCP) : null;
|
||
if (zone && zone.city) return zone.city.toUpperCase().trim();
|
||
return String(fallbackPop || "").toUpperCase().trim();
|
||
}
|
||
|
||
const targetCity = getCityForCP(datosExpediente.cp, datosExpediente.poblacion);
|
||
|
||
const agendaQ = await pool.query(`
|
||
SELECT
|
||
COALESCE(
|
||
NULLIF(raw_data->>'scheduled_date', ''),
|
||
CASE
|
||
WHEN raw_data->>'appointment_status' = 'pending' THEN NULLIF(raw_data->>'requested_date', '')
|
||
ELSE NULL
|
||
END
|
||
) as effective_date,
|
||
COALESCE(
|
||
NULLIF(raw_data->>'scheduled_time', ''),
|
||
CASE
|
||
WHEN raw_data->>'appointment_status' = 'pending' THEN NULLIF(raw_data->>'requested_time', '')
|
||
ELSE NULL
|
||
END
|
||
) as effective_time,
|
||
COALESCE(NULLIF(raw_data->>'duration_minutes', ''), '60') as effective_duration,
|
||
raw_data->>'Población' as poblacion,
|
||
COALESCE(raw_data->>'Código Postal', raw_data->>'C.P.') as cp,
|
||
provider,
|
||
raw_data->>'blocked_guild_id' as blocked_guild_id
|
||
FROM scraped_services
|
||
WHERE owner_id = $1
|
||
AND assigned_to = $2
|
||
AND status != 'archived'
|
||
AND id != $3
|
||
AND (
|
||
(raw_data->>'scheduled_date' IS NOT NULL AND raw_data->>'scheduled_date' >= CURRENT_DATE::text)
|
||
OR
|
||
(raw_data->>'appointment_status' = 'pending' AND raw_data->>'requested_date' >= CURRENT_DATE::text)
|
||
)
|
||
ORDER BY effective_date ASC, effective_time ASC
|
||
`, [ownerId, datosExpediente.worker_id, datosExpediente.dbId]);
|
||
|
||
const ocupacionesPorDia = {};
|
||
const ciudadPorDia = {};
|
||
const afternoonStartMin = parseTimeToMinutes(horarios.a_start);
|
||
|
||
for (const row of agendaQ.rows) {
|
||
const isoDate = row.effective_date;
|
||
const startMin = parseTimeToMinutes(row.effective_time);
|
||
const duration = Math.max(parseInt(row.effective_duration, 10) || 60, 1);
|
||
|
||
if (!isoDate) continue;
|
||
|
||
// ð Un bloqueo manual reservado para OTRO gremio no cuenta para nada (igual que en el portal)
|
||
if (row.provider === 'SYSTEM_BLOCK' && row.blocked_guild_id && String(row.blocked_guild_id) !== String(targetGuildId)) {
|
||
continue;
|
||
}
|
||
|
||
// ð REGLA CRÃTICA DE TURNOS: anotamos la ciudad de la mañana/tarde de ese dÃa
|
||
if (row.provider !== 'SYSTEM_BLOCK' && startMin !== null && afternoonStartMin !== null) {
|
||
const city = getCityForCP(row.cp, row.poblacion);
|
||
if (!ciudadPorDia[isoDate]) ciudadPorDia[isoDate] = { morningCity: null, afternoonCity: null };
|
||
if (startMin < afternoonStartMin) {
|
||
if (!ciudadPorDia[isoDate].morningCity) ciudadPorDia[isoDate].morningCity = city;
|
||
} else {
|
||
if (!ciudadPorDia[isoDate].afternoonCity) ciudadPorDia[isoDate].afternoonCity = city;
|
||
}
|
||
}
|
||
|
||
if (startMin === null) continue;
|
||
if (!ocupacionesPorDia[isoDate]) ocupacionesPorDia[isoDate] = [];
|
||
ocupacionesPorDia[isoDate].push([startMin, startMin + duration]);
|
||
}
|
||
|
||
const sesionesTrabajo = [
|
||
[parseTimeToMinutes(horarios.m_start), parseTimeToMinutes(horarios.m_end)],
|
||
[parseTimeToMinutes(horarios.a_start), parseTimeToMinutes(horarios.a_end)]
|
||
].filter(([ini, fin]) => ini !== null && fin !== null && fin > ini);
|
||
|
||
const { todayISO } = getMadridNowInfo();
|
||
const diasDisponibles = [];
|
||
|
||
// â ï¸ Igual que el portal público: no se ofrece el mismo dÃa, se empieza a partir de mañana
|
||
for (let offset = 1; offset < 22 && diasDisponibles.length < 10; offset++) {
|
||
const isoDate = addDaysISO(todayISO, offset);
|
||
if (isWeekendISO(isoDate)) continue;
|
||
|
||
const ocupadas = mergeIntervals(ocupacionesPorDia[isoDate] || []);
|
||
const dayCity = ciudadPorDia[isoDate];
|
||
const ventanas = [];
|
||
|
||
for (const [sesionStartBase, sesionEndBase] of sesionesTrabajo) {
|
||
// ð Si esa mañana/tarde ya está anclada a otra ciudad, no la ofrecemos (evita saltos de zona)
|
||
if (dayCity && afternoonStartMin !== null) {
|
||
const esSesionManana = sesionStartBase < afternoonStartMin;
|
||
if (esSesionManana && dayCity.morningCity && dayCity.morningCity !== targetCity) continue;
|
||
if (!esSesionManana && dayCity.afternoonCity && dayCity.afternoonCity !== targetCity) continue;
|
||
}
|
||
|
||
let sesionStart = sesionStartBase;
|
||
const sesionEnd = sesionEndBase;
|
||
|
||
if ((sesionEnd - sesionStart) < 60) continue;
|
||
|
||
let cursor = sesionStart;
|
||
|
||
for (const [occStart, occEnd] of ocupadas) {
|
||
if (occEnd <= sesionStart) continue;
|
||
if (occStart >= sesionEnd) break;
|
||
|
||
const gapStart = roundUpTo30(cursor);
|
||
const gapEnd = roundDownTo30(Math.min(occStart, sesionEnd));
|
||
|
||
if ((gapEnd - gapStart) >= 60) {
|
||
ventanas.push({
|
||
start: minutesToHHMM(gapStart),
|
||
end: minutesToHHMM(gapEnd),
|
||
startMin: gapStart,
|
||
endMin: gapEnd
|
||
});
|
||
}
|
||
|
||
cursor = Math.max(cursor, occEnd);
|
||
if (cursor >= sesionEnd) break;
|
||
}
|
||
|
||
const tailStart = roundUpTo30(cursor);
|
||
const tailEnd = roundDownTo30(sesionEnd);
|
||
|
||
if ((tailEnd - tailStart) >= 60) {
|
||
ventanas.push({
|
||
start: minutesToHHMM(tailStart),
|
||
end: minutesToHHMM(tailEnd),
|
||
startMin: tailStart,
|
||
endMin: tailEnd
|
||
});
|
||
}
|
||
}
|
||
|
||
if (ventanas.length > 0) {
|
||
diasDisponibles.push({
|
||
date: isoDate,
|
||
displayDate: formatDisplayDateES(isoDate),
|
||
windows: ventanas
|
||
});
|
||
}
|
||
}
|
||
|
||
return diasDisponibles;
|
||
};
|
||
|
||
// =========================================================
|
||
// HISTORIAL REAL DEL CHAT
|
||
// =========================================================
|
||
const historyQ = await pool.query(`
|
||
SELECT sender_role, message
|
||
FROM service_communications
|
||
WHERE scraped_id = $1
|
||
AND sender_role <> 'system'
|
||
ORDER BY created_at DESC
|
||
LIMIT 12
|
||
`, [datosExpediente.dbId]);
|
||
|
||
const historialRows = historyQ.rows.reverse();
|
||
|
||
const historialChat = historialRows.map(row => ({
|
||
role: row.sender_role === 'user' ? 'user' : 'assistant',
|
||
content: row.message
|
||
}));
|
||
|
||
const esPrimerMensaje = historialRows.length <= 1;
|
||
|
||
// =========================================================
|
||
// ð MODO CAPTACIÃN: expedientes creados con el comando de admin
|
||
// "escribe a [teléfono]" (todavÃa sin nombre/dirección/averÃa). Aquà extraemos
|
||
// lo que el cliente acaba de aportar y, en cuanto tengamos nombre + dirección +
|
||
// descripción, intentamos detectar el gremio y asignar técnico automáticamente
|
||
// para que el resto de la conversación siga el flujo normal de agenda de siempre.
|
||
// =========================================================
|
||
if (datosExpediente.intake_mode) {
|
||
try {
|
||
const extraccionCompletion = await openai.chat.completions.create({
|
||
model: OPENAI_MODEL || "gpt-4o-mini",
|
||
messages: [
|
||
{
|
||
role: "system",
|
||
content: "Extrae de esta conversación con un posible cliente los datos que haya dado HASTA AHORA (incluyendo su último mensaje). Responde SOLO un JSON con las claves: nombre, direccion, codigo_postal, poblacion, descripcion. Usa cadena vacÃa \"\" en cualquier clave que no conste explÃcitamente en la conversación. No inventes ni deduzcas nada."
|
||
},
|
||
...historialChat,
|
||
{ role: "user", content: mensajeCliente }
|
||
],
|
||
response_format: { type: "json_object" },
|
||
temperature: 0
|
||
});
|
||
|
||
let extraido = {};
|
||
try {
|
||
extraido = JSON.parse(extraccionCompletion.choices?.[0]?.message?.content || "{}");
|
||
} catch (eParse) {
|
||
extraido = {};
|
||
}
|
||
|
||
const patch = {};
|
||
if (typeof extraido.nombre === 'string' && extraido.nombre.trim()) patch["Nombre Cliente"] = extraido.nombre.trim();
|
||
if (typeof extraido.direccion === 'string' && extraido.direccion.trim()) patch["Dirección"] = extraido.direccion.trim();
|
||
if (typeof extraido.codigo_postal === 'string' && extraido.codigo_postal.trim()) patch["Código Postal"] = extraido.codigo_postal.trim();
|
||
if (typeof extraido.poblacion === 'string' && extraido.poblacion.trim()) patch["Población"] = extraido.poblacion.trim();
|
||
if (typeof extraido.descripcion === 'string' && extraido.descripcion.trim()) patch["Descripción"] = extraido.descripcion.trim();
|
||
|
||
const nombreActual = patch["Nombre Cliente"] || datosExpediente.nombre_cliente || "";
|
||
const direccionActual = patch["Dirección"] || datosExpediente.direccion || "";
|
||
const descripcionActual = patch["Descripción"] || datosExpediente.averia || "";
|
||
const capturaCompleta = !!(nombreActual && direccionActual && descripcionActual);
|
||
|
||
// ð® FALLBACK CP: si la IA no separó el código postal como campo propio (p.ej.
|
||
// el cliente escribió "Calle Mayor 5, 28013 Madrid" todo junto), lo buscamos
|
||
// nosotros mismos en la dirección/población para no dejar el aviso sin CP â
|
||
// sin CP, el aviso NO aparece en "Solicitar Servicios" (Bolsa) para operarios
|
||
// con zonas configuradas, aunque esté correctamente sin gremio/operario.
|
||
if (!patch["Código Postal"] && !datosExpediente.cp) {
|
||
const poblacionActual = patch["Población"] || datosExpediente.poblacion || "";
|
||
const cpMatch = `${direccionActual} ${poblacionActual}`.match(/\b\d{5}\b/);
|
||
if (cpMatch) patch["Código Postal"] = cpMatch[0];
|
||
}
|
||
|
||
let workerAsignado = null;
|
||
let guildAsignado = null;
|
||
|
||
if (capturaCompleta) {
|
||
// ð Detección de gremio por palabras clave (misma lógica que la
|
||
// asignación automática de servicios importados de proveedores).
|
||
const textoLimpio = descripcionActual.toLowerCase().normalize("NFD").replace(/[Ì-ͯ]/g, "");
|
||
const allGuildsQ = await pool.query("SELECT id, name, ia_keywords FROM guilds WHERE owner_id = $1", [ownerId]);
|
||
for (const g of allGuildsQ.rows) {
|
||
const keywords = Array.isArray(g.ia_keywords) ? g.ia_keywords : [];
|
||
if (keywords.some(kw => textoLimpio.includes(String(kw).toLowerCase()))) {
|
||
guildAsignado = g.id;
|
||
break;
|
||
}
|
||
}
|
||
|
||
// ð· Solo asignamos técnico si hemos podido detectar el gremio; si no,
|
||
// se queda sin gremio y sin operario para que el admin lo revise a mano.
|
||
if (guildAsignado) {
|
||
// ð¡ TEMPORAL (a petición del cliente, mientras se prueba el flujo de
|
||
// "escribe a un número"): en vez de repartir al azar entre los técnicos
|
||
// del gremio detectado, asignamos siempre al mismo técnico (Marco Rincón).
|
||
// Para quitar esto y volver al reparto aleatorio de siempre, basta con
|
||
// borrar este bloque "if (workerQ.rowCount === 0)" de aquà abajo.
|
||
const TECNICO_FIJO_TEMPORAL_PHONE = "+34687845940"; // Marco Rincón
|
||
let workerQ = await pool.query(
|
||
"SELECT id FROM users WHERE owner_id = $1 AND status = 'active' AND phone = $2 LIMIT 1",
|
||
[ownerId, TECNICO_FIJO_TEMPORAL_PHONE]
|
||
);
|
||
if (workerQ.rowCount === 0) {
|
||
// Si no está en esta cuenta (p.ej. otra empresa), reparto normal por gremio.
|
||
workerQ = await pool.query(`
|
||
SELECT u.id FROM users u
|
||
JOIN user_guilds ug ON u.id = ug.user_id
|
||
WHERE u.owner_id = $1 AND u.status = 'active' AND ug.guild_id = $2
|
||
ORDER BY RANDOM() LIMIT 1
|
||
`, [ownerId, guildAsignado]);
|
||
}
|
||
if (workerQ.rowCount === 0) {
|
||
workerQ = await pool.query("SELECT id FROM users WHERE owner_id = $1 AND status = 'active' ORDER BY RANDOM() LIMIT 1", [ownerId]);
|
||
}
|
||
if (workerQ.rowCount > 0) workerAsignado = workerQ.rows[0].id;
|
||
}
|
||
|
||
patch["intake_mode"] = false;
|
||
if (guildAsignado) patch["guild_id"] = guildAsignado;
|
||
}
|
||
|
||
if (Object.keys(patch).length > 0) {
|
||
if (workerAsignado) {
|
||
const statusAsignadoQ = await pool.query("SELECT id FROM service_statuses WHERE owner_id=$1 AND name = 'Asignado' LIMIT 1", [ownerId]);
|
||
if (statusAsignadoQ.rowCount > 0) patch["status_operativo"] = String(statusAsignadoQ.rows[0].id);
|
||
|
||
await pool.query(
|
||
`UPDATE scraped_services SET raw_data = COALESCE(raw_data,'{}'::jsonb) || $1::jsonb, assigned_to = $2 WHERE id = $3`,
|
||
[JSON.stringify(patch), workerAsignado, datosExpediente.dbId]
|
||
);
|
||
} else {
|
||
await pool.query(
|
||
`UPDATE scraped_services SET raw_data = COALESCE(raw_data,'{}'::jsonb) || $1::jsonb WHERE id = $2`,
|
||
[JSON.stringify(patch), datosExpediente.dbId]
|
||
);
|
||
}
|
||
}
|
||
|
||
// Reflejamos los cambios en el objeto en memoria para que el resto de
|
||
// esta misma llamada (directiva, huecos de agenda) ya vea los datos frescos.
|
||
if (patch["Nombre Cliente"]) datosExpediente.nombre_cliente = patch["Nombre Cliente"];
|
||
if (patch["Dirección"]) datosExpediente.direccion = patch["Dirección"];
|
||
if (patch["Código Postal"]) datosExpediente.cp = patch["Código Postal"];
|
||
if (patch["Población"]) datosExpediente.poblacion = patch["Población"];
|
||
if (patch["Descripción"]) datosExpediente.averia = patch["Descripción"];
|
||
if (workerAsignado) datosExpediente.worker_id = workerAsignado;
|
||
if (guildAsignado) datosExpediente.guild_id = guildAsignado;
|
||
datosExpediente.intake_mode = !capturaCompleta;
|
||
} catch (eIntake) {
|
||
console.error("â Error en captación de datos (modo intake):", eIntake.message);
|
||
}
|
||
}
|
||
|
||
// =========================================================
|
||
// ð° MODO PRESUPUESTO: expedientes abiertos automáticamente porque el
|
||
// cliente escribió y tenÃa un presupuesto (budgets) nuestro sin convertir.
|
||
// Mientras no esté aceptado, la IA solo puede resolver dudas sobre su
|
||
// contenido â nunca ofrecer cita. En cuanto el presupuesto pasa a
|
||
// aceptado/pagado (por el cliente en el portal o por ti a mano), detectamos
|
||
// gremio por palabras clave y asignamos técnico automáticamente (igual que
|
||
// en el alta por WhatsApp), y el resto de la conversación sigue el flujo
|
||
// normal de agenda de siempre.
|
||
// =========================================================
|
||
let datosPresupuestoTexto = "";
|
||
if (datosExpediente.budget_id) {
|
||
try {
|
||
const budgetQ = await pool.query("SELECT * FROM budgets WHERE id = $1 AND owner_id = $2", [datosExpediente.budget_id, ownerId]);
|
||
if (budgetQ.rowCount > 0) {
|
||
const budget = budgetQ.rows[0];
|
||
const itemsTexto = Array.isArray(budget.items)
|
||
? budget.items.map(i => `- ${i.qty || 1}x ${i.concept || ''}${i.price ? ` (${i.price}â¬/ud)` : ''}`).join("\n")
|
||
: "";
|
||
|
||
datosPresupuestoTexto = `
|
||
--- ð° DATOS DEL PRESUPUESTO PRE-${budget.id} (fijos, no editables desde el panel) ---
|
||
Conceptos:
|
||
${itemsTexto || "(sin detalle de conceptos)"}
|
||
Subtotal: ${budget.subtotal}⬠· Impuestos: ${budget.tax}⬠· TOTAL: ${budget.total}â¬
|
||
Estado actual del presupuesto: ${String(budget.status || '').toUpperCase()}
|
||
Usa estos datos para responder con naturalidad las dudas del cliente sobre el presupuesto (qué incluye, precios, etc.).`;
|
||
|
||
const yaEstaAceptado = budget.status === 'accepted' || budget.status === 'paid';
|
||
|
||
if (datosExpediente.budget_mode && yaEstaAceptado) {
|
||
// ð Detección de gremio por palabras clave (misma lógica que el resto
|
||
// del sistema), buscando en los conceptos del propio presupuesto.
|
||
const textoParaGremio = `${itemsTexto} ${datosExpediente.averia || ''}`.toLowerCase().normalize("NFD").replace(/[Ì-ͯ]/g, "");
|
||
let guildAsignado = null;
|
||
const allGuildsQ = await pool.query("SELECT id, name, ia_keywords FROM guilds WHERE owner_id = $1", [ownerId]);
|
||
for (const g of allGuildsQ.rows) {
|
||
const keywords = Array.isArray(g.ia_keywords) ? g.ia_keywords : [];
|
||
if (keywords.some(kw => textoParaGremio.includes(String(kw).toLowerCase()))) {
|
||
guildAsignado = g.id;
|
||
break;
|
||
}
|
||
}
|
||
|
||
// ð¡ TEMPORAL (mismo criterio que el alta por WhatsApp): si no hay
|
||
// técnico en el gremio detectado, caemos siempre en Marco Rincón.
|
||
const TECNICO_FIJO_TEMPORAL_PHONE = "+34687845940"; // Marco Rincón
|
||
let workerAsignado = null;
|
||
let workerQ = await pool.query(
|
||
"SELECT id FROM users WHERE owner_id = $1 AND status = 'active' AND phone = $2 LIMIT 1",
|
||
[ownerId, TECNICO_FIJO_TEMPORAL_PHONE]
|
||
);
|
||
if (guildAsignado) {
|
||
const workerGremioQ = await pool.query(`
|
||
SELECT u.id FROM users u
|
||
JOIN user_guilds ug ON u.id = ug.user_id
|
||
WHERE u.owner_id = $1 AND u.status = 'active' AND ug.guild_id = $2
|
||
ORDER BY RANDOM() LIMIT 1
|
||
`, [ownerId, guildAsignado]);
|
||
if (workerGremioQ.rowCount > 0) workerQ = workerGremioQ;
|
||
}
|
||
if (workerQ.rowCount === 0) {
|
||
workerQ = await pool.query("SELECT id FROM users WHERE owner_id = $1 AND status = 'active' ORDER BY RANDOM() LIMIT 1", [ownerId]);
|
||
}
|
||
if (workerQ.rowCount > 0) workerAsignado = workerQ.rows[0].id;
|
||
|
||
const patch = { "budget_mode": false };
|
||
if (guildAsignado) patch["guild_id"] = guildAsignado;
|
||
if (workerAsignado) {
|
||
const statusAsignadoQ = await pool.query("SELECT id FROM service_statuses WHERE owner_id=$1 AND name = 'Asignado' LIMIT 1", [ownerId]);
|
||
if (statusAsignadoQ.rowCount > 0) patch["status_operativo"] = String(statusAsignadoQ.rows[0].id);
|
||
}
|
||
|
||
if (workerAsignado) {
|
||
await pool.query(
|
||
`UPDATE scraped_services SET raw_data = COALESCE(raw_data,'{}'::jsonb) || $1::jsonb, assigned_to = $2 WHERE id = $3`,
|
||
[JSON.stringify(patch), workerAsignado, datosExpediente.dbId]
|
||
);
|
||
} else {
|
||
await pool.query(
|
||
`UPDATE scraped_services SET raw_data = COALESCE(raw_data,'{}'::jsonb) || $1::jsonb WHERE id = $2`,
|
||
[JSON.stringify(patch), datosExpediente.dbId]
|
||
);
|
||
}
|
||
|
||
if (budget.status !== 'converted') {
|
||
await pool.query("UPDATE budgets SET status = 'converted' WHERE id = $1", [budget.id]);
|
||
}
|
||
|
||
datosExpediente.budget_mode = false;
|
||
if (guildAsignado) datosExpediente.guild_id = guildAsignado;
|
||
if (workerAsignado) datosExpediente.worker_id = workerAsignado;
|
||
}
|
||
}
|
||
} catch (eBudgetMode) {
|
||
console.error("â Error en modo presupuesto:", eBudgetMode.message);
|
||
}
|
||
}
|
||
|
||
// =========================================================
|
||
// HUECOS EXACTOS CALCULADOS POR BACKEND
|
||
// =========================================================
|
||
let huecosExactos = [];
|
||
let agendaDisponibleTexto = "â Ahora mismo no hay huecos exactos calculados por el sistema.";
|
||
|
||
if (datosExpediente.worker_id) {
|
||
huecosExactos = await calcularHuecosDisponiblesExactos();
|
||
|
||
if (huecosExactos.length > 0) {
|
||
agendaDisponibleTexto = huecosExactos.map(dia => {
|
||
const tramos = dia.windows
|
||
.map(w => `entre las ${w.start} y las ${w.end} aprox`)
|
||
.join(" | ");
|
||
|
||
return `- ${dia.displayDate} (${dia.date}): ${tramos}`;
|
||
}).join("\n");
|
||
} else {
|
||
agendaDisponibleTexto = "â No hay huecos exactos libres en los próximos dÃas laborables calculados por el sistema.";
|
||
}
|
||
}
|
||
|
||
const hayCitaPendiente =
|
||
datosExpediente.appointment_status === 'pending' &&
|
||
datosExpediente.cita_pendiente_fecha;
|
||
|
||
const tieneCitaConfirmada =
|
||
datosExpediente.cita &&
|
||
datosExpediente.cita !== 'Ninguna';
|
||
|
||
const esUrgencia = datosExpediente.is_urgent;
|
||
|
||
let tramoPendiente = datosExpediente.cita_pendiente_hora || "";
|
||
if (tramoPendiente && tramoPendiente.includes(":")) {
|
||
const [h, m] = tramoPendiente.split(':');
|
||
const hEnd = String((parseInt(h, 10) + 1) % 24).padStart(2, '0');
|
||
tramoPendiente = `entre las ${h}:${m} y las ${hEnd}:${m} aprox`;
|
||
}
|
||
|
||
let tramoConfirmado = datosExpediente.hora_cita || "";
|
||
if (tramoConfirmado && tramoConfirmado.includes(":")) {
|
||
const [h, m] = tramoConfirmado.split(':');
|
||
const hEnd = String((parseInt(h, 10) + 1) % 24).padStart(2, '0');
|
||
tramoConfirmado = `entre las ${h}:${m} y las ${hEnd}:${m} aprox`;
|
||
} else {
|
||
tramoConfirmado = 'una hora por confirmar';
|
||
}
|
||
|
||
let citaYaPaso = false;
|
||
if (tieneCitaConfirmada && datosExpediente.cita) {
|
||
const ahora = new Date();
|
||
const [y, m, d] = datosExpediente.cita.split('-');
|
||
// Si no hay hora concreta, solo se considera "pasada" al cambiar de dia (fin del dia)
|
||
let horaFin = 23, minFin = 59;
|
||
if (datosExpediente.hora_cita && datosExpediente.hora_cita.includes(':')) {
|
||
const [hh, mm] = datosExpediente.hora_cita.split(':');
|
||
horaFin = parseInt(hh, 10) + 1; // margen aprox. de duracion del servicio
|
||
minFin = parseInt(mm, 10);
|
||
}
|
||
const finVentanaCita = new Date(y, m - 1, d, horaFin, minFin);
|
||
if (finVentanaCita < ahora) citaYaPaso = true;
|
||
}
|
||
|
||
const esEstadoFinal =
|
||
datosExpediente.estado &&
|
||
(
|
||
datosExpediente.estado.toLowerCase().includes('finalizado') ||
|
||
datosExpediente.estado.toLowerCase().includes('terminado') ||
|
||
datosExpediente.estado.toLowerCase().includes('anulado')
|
||
);
|
||
|
||
const noTieneTecnico = !datosExpediente.worker_id;
|
||
|
||
let directivaEstricta = "";
|
||
|
||
if (datosExpediente.budget_mode) {
|
||
directivaEstricta = `ð¡ ESTADO ACTUAL: PRESUPUESTO PENDIENTE DE ACEPTAR (PRE-${datosExpediente.budget_id}). Continúa la conversación ya iniciada sobre este presupuesto.
|
||
Puedes resolver dudas sobre su contenido usando los datos de la sección "DATOS DEL PRESUPUESTO" de más abajo (qué incluye, precios, plazos, etc.).
|
||
â NO ofrezcas fecha ni hora de visita bajo ningún concepto: el presupuesto TODAVÃA NO está aceptado.
|
||
Si el cliente pide cita, pregunta cuándo puede ir el técnico, o quiere que empecéis el trabajo, explÃcale con amabilidad que primero tiene que aceptar el presupuesto desde su portal: pulsando el enlace que se le envió, entrando en el presupuesto y pulsando "Aceptar Presupuesto". En cuanto lo acepte, podréis concretar la visita.`;
|
||
} else if (datosExpediente.intake_mode) {
|
||
const faltantes = [];
|
||
if (!datosExpediente.nombre_cliente) faltantes.push("su nombre completo");
|
||
if (!datosExpediente.direccion) faltantes.push("la dirección exacta de la visita (calle, número, código postal y población)");
|
||
if (!datosExpediente.averia) faltantes.push(`una breve descripción de lo que necesita${datosExpediente.intake_purpose ? ` (motivo indicado: ${datosExpediente.intake_purpose})` : ''}`);
|
||
|
||
directivaEstricta = `ð¡ ESTADO ACTUAL: RECOGIDA INICIAL DE DATOS. Esto es una primera toma de contacto (todavÃa no hay expediente completo), continúa la conversación ya iniciada.
|
||
TU OBJETIVO: en un solo mensaje corto, pide de forma natural los datos que aún faltan: ${faltantes.join(", ")}.
|
||
â NO ofrezcas fecha ni hora de cita en este mensaje, NO agendes nada todavÃa: primero necesitamos estos datos básicos.`;
|
||
} else if (esEstadoFinal) {
|
||
directivaEstricta = `ð ESTADO ACTUAL: SERVICIO CERRADO. Informa al cliente que el servicio por su averÃa (${datosExpediente.averia}) está finalizado. NO AGENDES NADA.`;
|
||
} else if (noTieneTecnico) {
|
||
directivaEstricta = `ð ESTADO ACTUAL: SIN TÃCNICO ASIGNADO.
|
||
TU ÃNICO OBJETIVO: Informar al cliente que hemos recibido el aviso de su averÃa (${datosExpediente.averia}) y que estamos coordinando para asignarle un técnico en su zona.
|
||
â PROHIBICIÃN ABSOLUTA: NO ofrezcas citas, NO des horas, NO agendes nada hasta que se le asigne un técnico.`;
|
||
} else if (citaYaPaso) {
|
||
directivaEstricta = `ð ESTADO ACTUAL: LA CITA (${datosExpediente.cita} ${tramoConfirmado}) YA DEBERÃA HABER PASADO, pero el servicio sigue en estado "citado" (no consta que se haya cerrado el parte de trabajo).
|
||
â ï¸ NO afirmes que el técnico ya fue ni que el servicio está hecho. NO digas tampoco que la cita sigue por llegar, como si no hubiera pasado ya la hora.
|
||
TU OBJETIVO: Exprésate con duda de forma natural. Dile que según tus datos tenÃa cita a esa hora para su averÃa (${datosExpediente.averia}) y pregúntale directamente si el técnico ya pasó por su domicilio o si sigue esperando, para poder ayudarle mejor. NO AGENDES NADA hasta saberlo.`;
|
||
} else if (esUrgencia) {
|
||
directivaEstricta = `ð ESTADO ACTUAL: URGENCIA. Tranquiliza al cliente sobre su averÃa (${datosExpediente.averia}) y dile que el técnico está avisado. NO PROPONGAS HORAS.`;
|
||
} else if (hayCitaPendiente) {
|
||
directivaEstricta = `ð ESTADO ACTUAL: CITA PENDIENTE DE APROBACIÃN.
|
||
ð
Propuesta actual: El dÃa ${datosExpediente.cita_pendiente_fecha} ${tramoPendiente}.
|
||
TU OBJETIVO: Informar que esperamos confirmación del técnico para reparar su averÃa (${datosExpediente.averia}).
|
||
â ï¸ EXCEPCIÃN: Si el cliente pide CAMBIAR o CANCELAR, ofrécele un hueco nuevo usando SOLO los huecos exactos calculados por el sistema.`;
|
||
} else if (tieneCitaConfirmada) {
|
||
directivaEstricta = `ð ESTADO ACTUAL: CITA CONFIRMADA para el ${datosExpediente.cita} ${tramoConfirmado}. Recuerda la cita para su averÃa (${datosExpediente.averia}).
|
||
â ï¸ EXCEPCIÃN: Si el cliente pide CAMBIARLA o CANCELARLA, ofrécele un hueco nuevo usando SOLO los huecos exactos calculados por el sistema.`;
|
||
} else {
|
||
directivaEstricta = `ð¢ ESTADO ACTUAL: PENDIENTE DE AGENDAR CITA.
|
||
TU OBJETIVO: Acordar fecha y hora para reparar su averÃa (${datosExpediente.averia}) usando SOLO los huecos exactos calculados por el sistema.
|
||
â ï¸ MUY IMPORTANTE: Cuando el cliente elija un hueco, NO le digas que la cita está confirmada. Dile que le pasas la nota al técnico para que él lo valide.`;
|
||
}
|
||
|
||
const promptSistema = `
|
||
Eres el coordinador humano de "${empresaNombre}", hablando por WhatsApp.
|
||
|
||
--- ð CONTEXTO BÃSICO ---
|
||
- Hoy es: ${fechaHoyTexto}.
|
||
- Horario de la empresa: L-V de ${horarios.m_start} a ${horarios.m_end} y de ${horarios.a_start} a ${horarios.a_end}.
|
||
- â REGLA DE ORO DEL HORARIO: NUNCA propongas horas fuera de ese horario ni cruces el tramo de comer.
|
||
- Localidad del cliente actual: ${datosExpediente.poblacion || 'Localidad no especificada'}.
|
||
${reglaCobertura ? `
|
||
--- ð§¾ CONDICIONES DE COBERTURA PARA ESTE SERVICIO (CompañÃa: ${datosExpediente.compania || 'no especificada'} · Gremio: ${datosExpediente.gremio || 'no especificado'}) ---
|
||
${reglaCobertura.text}
|
||
Menciona esto SOLO si el cliente pregunta por costes, materiales, o qué cubre el seguro. No lo repitas si no viene a cuento.` : ''}
|
||
${datosPresupuestoTexto}
|
||
|
||
--- â
HUECOS EXACTOS CALCULADOS POR EL SISTEMA ---
|
||
${agendaDisponibleTexto}
|
||
|
||
--- ð¨ NORMA ABSOLUTA DE AGENDA (fija, no editable desde el panel) ---
|
||
Los huecos anteriores son la ÃNICA verdad.
|
||
NO puedes inventar horas.
|
||
NO puedes deducir huecos por tu cuenta.
|
||
NO puedes reinterpretar horarios ocupados.
|
||
SOLO puedes ofrecer horas que estén dentro de esos huecos exactos calculados por el sistema.
|
||
Si el cliente pide una hora concreta y esa hora cae dentro de uno de esos huecos, puedes aceptarla tentativamente.
|
||
Si cae fuera, debes decir que no la ves libre y ofrecer una alternativa de la lista exacta.
|
||
Si el cliente pide disponibilidad general, resume las opciones reales sin inventar nada.
|
||
|
||
--- ð¯ DIRECTIVA ESTRICTA PARA ESTE MENSAJE (fija, no editable desde el panel) ---
|
||
${directivaEstricta}
|
||
|
||
--- â¡ REGLA CRÃTICA DE AGENDA (COMANDO SECRETO, fija, no editable desde el panel) ---
|
||
Si (y solo si) el cliente ACEPTA claramente un hueco concreto, DEBES añadir AL FINAL ABSOLUTO de tu respuesta este texto literal:
|
||
[PROPUESTA:YYYY-MM-DD HH:mm]
|
||
|
||
Ejemplo:
|
||
"Perfecto, le paso la nota al técnico para que te confirme el miércoles entre las 12:00 y las 13:00 aprox. ¡Te decimos algo pronto! [PROPUESTA:2026-03-25 12:00]"
|
||
|
||
â PROHIBICIONES (fijas, no editables desde el panel):
|
||
- NUNCA digas "te agendo".
|
||
- NUNCA digas "cita confirmada".
|
||
- NUNCA menciones las palabras "código" o "etiqueta".
|
||
- NUNCA ofrezcas huecos distintos a los calculados.
|
||
- Si el cliente pregunta por "la semana que viene", responde usando solo los huecos de esa semana.
|
||
${esPrimerMensaje && !datosExpediente.budget_id ? `
|
||
--- ð NOTA ---
|
||
Este es el primer mensaje: preséntate y menciona el aviso (#${datosExpediente.ref}).` : ''}
|
||
|
||
--- ð£ï¸ ESTILO E INSTRUCCIONES DE LA EMPRESA (editable desde el panel web, Configuración Avanzada) ---
|
||
${reglasNegocioIA}
|
||
`;
|
||
|
||
const completion = await openai.chat.completions.create({
|
||
model: OPENAI_MODEL || "gpt-4o-mini",
|
||
messages: [
|
||
{ role: "system", content: promptSistema },
|
||
...historialChat
|
||
],
|
||
temperature: 0.1
|
||
});
|
||
|
||
return completion.choices?.[0]?.message?.content || null;
|
||
} catch (e) {
|
||
console.error("â Error OpenAI:", e.message);
|
||
return null;
|
||
}
|
||
}
|
||
|
||
// ==========================================
|
||
// ð± OTP PARA PORTAL DEL CLIENTE (ACCESO WEB)
|
||
// ==========================================
|
||
app.post("/public/auth/request-otp", async (req, res) => {
|
||
try {
|
||
const { phone, owner_id } = req.body;
|
||
if (!phone || !owner_id) return res.status(400).json({ ok: false, error: "Faltan datos" });
|
||
|
||
const p = normalizePhone(phone);
|
||
// Generamos un código aleatorio de 4 dÃgitos
|
||
const code = String(Math.floor(1000 + Math.random() * 9000));
|
||
const codeHash = await bcrypt.hash(code, 10);
|
||
|
||
// Lo guardamos en la tabla de login_codes (ponemos user_id NULL porque es un cliente, no un operario)
|
||
await pool.query(`
|
||
INSERT INTO login_codes (user_id, phone, code_hash, purpose, expires_at)
|
||
VALUES (NULL, $1, $2, 'client_portal', NOW() + INTERVAL '15 minutes')
|
||
`, [p, codeHash]);
|
||
|
||
const msg = `ð *Asistencia Técnica*\n\nTu código seguro de acceso al portal es: *${code}*\n\nCaduca en 15 minutos.`;
|
||
|
||
// Enviamos el WhatsApp usando la instancia de la empresa correspondiente
|
||
sendWhatsAppAuto(p, msg, `cliente_${owner_id}`, false).catch(console.error);
|
||
|
||
res.json({ ok: true });
|
||
} catch (e) {
|
||
console.error("Error solicitando OTP cliente:", e);
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
app.post("/public/auth/verify-otp", async (req, res) => {
|
||
try {
|
||
const { phone, code, owner_id } = req.body;
|
||
const p = normalizePhone(phone);
|
||
|
||
// 1. Buscamos si el código existe, es de cliente, y no está caducado
|
||
const q = await pool.query(`
|
||
SELECT id, code_hash FROM login_codes
|
||
WHERE phone = $1 AND purpose = 'client_portal' AND consumed_at IS NULL AND expires_at > NOW()
|
||
ORDER BY created_at DESC LIMIT 1
|
||
`, [p]);
|
||
|
||
if (q.rowCount === 0) return res.status(400).json({ ok: false, error: "Código inválido o caducado" });
|
||
|
||
// 2. Comprobamos que el código de 4 dÃgitos coincide
|
||
const valid = await bcrypt.compare(String(code), q.rows[0].code_hash);
|
||
if (!valid) return res.status(400).json({ ok: false, error: "Código incorrecto" });
|
||
|
||
// 3. Quemamos el código para que no se pueda usar 2 veces
|
||
await pool.query("UPDATE login_codes SET consumed_at = NOW() WHERE id = $1", [q.rows[0].id]);
|
||
|
||
// 4. Magia: Buscamos si este cliente ya nos ha llamado antes para pre-rellenar su formulario
|
||
const cleanPhoneForSearch = String(phone).replace(/\D/g, "");
|
||
const clientQ = await pool.query(
|
||
"SELECT full_name, addresses FROM clients WHERE phone LIKE $1 AND owner_id = $2 LIMIT 1",
|
||
[`%${cleanPhoneForSearch}%`, owner_id]
|
||
);
|
||
|
||
let clientData = null;
|
||
let exists = false;
|
||
if (clientQ.rowCount > 0) {
|
||
clientData = clientQ.rows[0];
|
||
exists = true;
|
||
}
|
||
|
||
res.json({ ok: true, exists, client: clientData });
|
||
} catch (e) {
|
||
console.error("Error verificando OTP cliente:", e);
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
// ==========================================
|
||
// ð EMBUDO PÃBLICO DE ENTRADA DE CLIENTES
|
||
// ==========================================
|
||
app.post("/public/new-request", async (req, res) => {
|
||
const clientDb = await pool.connect();
|
||
try {
|
||
const { phone, name, address, guild_id, description, is_urgent, owner_id } = req.body;
|
||
|
||
// ð¨ CAMBIO SAAS: Obligamos a que venga el owner_id sà o sÃ
|
||
if (!phone || !guild_id || !owner_id) return res.status(400).json({ ok: false, error: "Faltan datos clave de la empresa" });
|
||
|
||
// ð¡ï¸ CONVERSIÃN ESTRICTA DE DATOS (Para que PostgreSQL no lance Error 500)
|
||
const targetOwnerId = parseInt(owner_id); // Quitamos el "|| 1" para que no asigne a la Empresa 1 por error
|
||
const safeGuildId = parseInt(guild_id) || 0;
|
||
const isUrgentBool = is_urgent === true || is_urgent === 'true';
|
||
const cleanPhone = String(phone).replace(/\D/g, "");
|
||
|
||
if (cleanPhone.length < 9) return res.status(400).json({ ok: false, error: "Teléfono inválido" });
|
||
|
||
await clientDb.query('BEGIN');
|
||
|
||
// 1. BUSCAR O CREAR CLIENTE
|
||
let clientId, clientToken;
|
||
const qClient = await clientDb.query("SELECT id, portal_token FROM clients WHERE phone LIKE $1 AND owner_id = $2 LIMIT 1", [`%${cleanPhone}%`, targetOwnerId]);
|
||
|
||
if (qClient.rowCount > 0) {
|
||
clientId = qClient.rows[0].id;
|
||
clientToken = qClient.rows[0].portal_token;
|
||
} else {
|
||
clientToken = crypto.randomBytes(6).toString('hex');
|
||
const newClient = await clientDb.query(
|
||
"INSERT INTO clients (owner_id, full_name, phone, addresses, portal_token) VALUES ($1, $2, $3, $4, $5) RETURNING id",
|
||
[targetOwnerId, name || "Cliente Web", phone, JSON.stringify([address || ""]), clientToken]
|
||
);
|
||
clientId = newClient.rows[0].id;
|
||
}
|
||
|
||
// 2. BUSCAR OPERARIO AL AZAR (Si es NORMAL)
|
||
let assignedWorkerId = null;
|
||
if (!isUrgentBool) {
|
||
let qWorker = await clientDb.query(`
|
||
SELECT u.id FROM users u
|
||
JOIN user_guilds ug ON u.id = ug.user_id
|
||
WHERE u.owner_id = $1 AND u.status = 'active' AND ug.guild_id = $2
|
||
ORDER BY RANDOM() LIMIT 1
|
||
`, [targetOwnerId, safeGuildId]);
|
||
|
||
// ð¡ï¸ FALLBACK: Si nadie tiene ese gremio, coge a CUALQUIERA activo
|
||
if (qWorker.rowCount === 0) {
|
||
qWorker = await clientDb.query("SELECT id FROM users WHERE owner_id = $1 AND status = 'active' ORDER BY RANDOM() LIMIT 1", [targetOwnerId]);
|
||
}
|
||
|
||
if (qWorker.rowCount > 0) {
|
||
assignedWorkerId = qWorker.rows[0].id;
|
||
} else {
|
||
await clientDb.query('ROLLBACK'); // â ï¸ VITAL para no bloquear la BD
|
||
return res.status(400).json({ ok: false, error: "No hay técnicos disponibles. Llama a la oficina." });
|
||
}
|
||
}
|
||
|
||
// 3. CREAR EL SERVICIO
|
||
const rawData = {
|
||
"Nombre Cliente": name || "Cliente Web",
|
||
"Teléfono": phone,
|
||
"Dirección": address || "",
|
||
"Descripción": description || "Aviso desde Web",
|
||
"guild_id": safeGuildId,
|
||
"CompañÃa": "Particular",
|
||
"Origen": "Web Público"
|
||
};
|
||
|
||
const ref = `WEB-${Date.now().toString().slice(-6)}`;
|
||
|
||
const qSvc = await clientDb.query(`
|
||
INSERT INTO scraped_services (owner_id, provider, service_ref, status, automation_status, assigned_to, is_urgent, raw_data)
|
||
VALUES ($1, 'particular', $2, 'pending', $3, $4, $5, $6) RETURNING id
|
||
`, [
|
||
targetOwnerId,
|
||
ref,
|
||
isUrgentBool ? 'in_progress' : 'manual',
|
||
assignedWorkerId,
|
||
isUrgentBool,
|
||
JSON.stringify(rawData)
|
||
]);
|
||
|
||
const newServiceId = qSvc.rows[0].id;
|
||
|
||
// 4. SI ES URGENTE, DISPARAMOS EL WHATSAPP DIRECTAMENTE
|
||
if (isUrgentBool) {
|
||
// Buscamos un operario activo de ese gremio
|
||
let workersQ = await clientDb.query(`
|
||
SELECT u.id, u.full_name, u.phone FROM users u
|
||
JOIN user_guilds ug ON u.id = ug.user_id
|
||
WHERE u.owner_id = $1 AND u.status = 'active' AND ug.guild_id = $2
|
||
ORDER BY RANDOM() LIMIT 1
|
||
`, [targetOwnerId, safeGuildId]);
|
||
|
||
// ð¡ï¸ FALLBACK URGENCIA: Si nadie tiene ese gremio, coge a CUALQUIERA activo
|
||
if (workersQ.rowCount === 0) {
|
||
workersQ = await clientDb.query(`
|
||
SELECT id, full_name, phone FROM users
|
||
WHERE owner_id = $1 AND status = 'active'
|
||
ORDER BY RANDOM() LIMIT 1
|
||
`, [targetOwnerId]);
|
||
}
|
||
|
||
if (workersQ.rowCount > 0) {
|
||
const worker = workersQ.rows[0];
|
||
const token = crypto.randomBytes(16).toString('hex');
|
||
|
||
// Creamos la alerta
|
||
await clientDb.query(`
|
||
INSERT INTO assignment_pings (scraped_id, user_id, token, expires_at)
|
||
VALUES ($1, $2, $3, CURRENT_TIMESTAMP + INTERVAL '5 minutes')
|
||
`, [newServiceId, worker.id, token]);
|
||
|
||
// ð EXTRAEMOS LA CALLE OCULTA (Sin números)
|
||
let calleOculta = "Zona asignada";
|
||
if (address) {
|
||
calleOculta = address.replace(/\s*,?\s*(\d+|s\/n).*$/i, '').trim();
|
||
}
|
||
|
||
// Enviamos el WA al operario
|
||
const msg = `ð¨ *URGENCIA PARTICULAR (WEB)*\nð Calle: ${calleOculta}\nð https://web.integrarepara.es/aceptar.html?t=${token}`;
|
||
sendWhatsAppAuto(worker.phone, msg, `cliente_${targetOwnerId}`, false).catch(console.error);
|
||
|
||
await clientDb.query(
|
||
"INSERT INTO scraped_service_logs (scraped_id, user_name, action, details) VALUES ($1, 'Sistema Automático', 'Bolsa de Urgencias', $2)",
|
||
[newServiceId, `Notificación enviada a: ${worker.full_name}`]
|
||
);
|
||
} else {
|
||
await clientDb.query("UPDATE scraped_services SET automation_status = 'failed' WHERE id = $1", [newServiceId]);
|
||
}
|
||
|
||
await clientDb.query('COMMIT');
|
||
return res.json({ ok: true, action: 'queued', message: "Aviso urgente en cola." });
|
||
} else {
|
||
await clientDb.query('COMMIT');
|
||
// Devolvemos el token del cliente para llevarlo a pedir Cita Normal
|
||
return res.json({
|
||
ok: true,
|
||
action: 'calendar',
|
||
redirectUrl: `https://portal.integrarepara.es/?token=${clientToken}&service=${newServiceId}`
|
||
});
|
||
}
|
||
|
||
} catch (e) {
|
||
await clientDb.query('ROLLBACK');
|
||
console.error("ð¨ CRASH EN WEB PÃBLICA (NUEVO AVISO):", e.message);
|
||
res.status(500).json({ ok: false, error: "Error procesando solicitud" });
|
||
} finally {
|
||
clientDb.release();
|
||
}
|
||
});
|
||
|
||
// ==========================================
|
||
// ð¯ RUTA PARA CUANDO EL CLIENTE PULSA "ME INTERESA" EN PUBLICIDAD
|
||
// ==========================================
|
||
app.post("/public/portal/:token/interest", async (req, res) => {
|
||
try {
|
||
const { token } = req.params;
|
||
|
||
// 1. Buscamos quién es el cliente usando su token
|
||
const clientQ = await pool.query("SELECT owner_id, full_name, phone FROM clients WHERE portal_token = $1 LIMIT 1", [token]);
|
||
if (clientQ.rowCount === 0) return res.status(404).json({ ok: false, error: "Token inválido" });
|
||
|
||
const client = clientQ.rows[0];
|
||
const ownerId = client.owner_id;
|
||
|
||
// 2. Buscamos el teléfono del administrador (tú) para avisarte
|
||
const ownerQ = await pool.query("SELECT phone FROM users WHERE id = $1", [ownerId]);
|
||
if (ownerQ.rowCount === 0) return res.status(404).json({ ok: false, error: "Empresa no encontrada" });
|
||
|
||
const adminPhone = ownerQ.rows[0].phone;
|
||
|
||
// 3. Montamos el mensaje de WhatsApp para el jefe
|
||
const msgWa = `ð *¡NUEVO LEAD DE PUBLICIDAD!* ð\n\nEl cliente *${client.full_name}* ha pulsado el botón "Me interesa" en el banner de publicidad de su portal web.\n\nð *Teléfono:* ${client.phone}\n\n¡Llámale cuanto antes para informarle!`;
|
||
|
||
// 4. Enviamos el mensaje
|
||
await sendWhatsAppAuto(adminPhone, msgWa, `cliente_${ownerId}`, false);
|
||
|
||
res.json({ ok: true });
|
||
} catch (e) {
|
||
console.error("Error al registrar interés en publicidad:", e);
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
// ==========================================
|
||
// ð PORTAL PÃBLICO DEL CLIENTE
|
||
// ==========================================
|
||
// ð§½ LIMPIEZA DE AVERÃA PARA EL CLIENTE (con IA + caché en raw_data)
|
||
// El campo "Descripción" va acumulando avisos automáticos, cambios de cita, códigos internos, etc.
|
||
// Aquà lo convertimos en una frase breve y sin ruido para que la vea el cliente en el Portal.
|
||
async function getClientFriendlyDescription(service) {
|
||
const rawDesc = (service.raw_data?.["Descripción"] || service.raw_data?.["DESCRIPCION"] || "").toString().trim();
|
||
if (!rawDesc) return "Aviso de reparación";
|
||
|
||
const rawHash = crypto.createHash('md5').update(rawDesc).digest('hex');
|
||
|
||
// Si ya la limpiamos antes y el texto original no ha cambiado, reutilizamos la versión guardada
|
||
if (service.raw_data?.portal_desc_hash === rawHash && service.raw_data?.portal_desc_clean) {
|
||
return service.raw_data.portal_desc_clean;
|
||
}
|
||
|
||
try {
|
||
const completion = await openai.chat.completions.create({
|
||
model: OPENAI_MODEL || "gpt-4o-mini",
|
||
messages: [
|
||
{
|
||
role: "system",
|
||
content: "Redactas, para el CLIENTE de una empresa de reparaciones del hogar, una frase muy breve (máximo 18 palabras) que describa SOLO el problema técnico o averÃa en su domicilio. No menciones fechas, horas, citas, cambios de cita, nombres de operarios o agentes, teléfonos, códigos de expediente, aseguradoras, ni el estado del trámite administrativo. Si el texto no describe ningún problema técnico claro, responde exactamente: \"Revisión técnica en el domicilio.\". Responde en español, en una sola frase, sin comillas ni markdown."
|
||
},
|
||
{ role: "user", content: rawDesc.slice(0, 2000) }
|
||
],
|
||
temperature: 0.2,
|
||
max_tokens: 60
|
||
});
|
||
|
||
const clean = completion.choices?.[0]?.message?.content?.trim();
|
||
if (!clean) throw new Error("La IA no devolvió texto");
|
||
|
||
// Guardamos en caché de forma asÃncrona (no bloqueamos la respuesta al cliente ni si falla)
|
||
pool.query(`
|
||
UPDATE scraped_services
|
||
SET raw_data = jsonb_set(jsonb_set(COALESCE(raw_data, '{}'::jsonb), '{portal_desc_clean}', $1::jsonb), '{portal_desc_hash}', $2::jsonb)
|
||
WHERE id = $3
|
||
`, [JSON.stringify(clean), JSON.stringify(rawHash), service.id]).catch(e => console.error("â ï¸ No se pudo cachear la averÃa limpia:", e.message));
|
||
|
||
return clean;
|
||
} catch (e) {
|
||
console.error("â Error limpiando averÃa con IA:", e.message);
|
||
// Si la IA falla, devolvemos algo razonable en lugar del volcado crudo completo
|
||
return rawDesc.length > 150 ? rawDesc.slice(0, 150).trim() + "..." : rawDesc;
|
||
}
|
||
}
|
||
|
||
app.get("/public/portal/:token", async (req, res) => {
|
||
try {
|
||
const { token } = req.params;
|
||
const serviceId = req.query.service;
|
||
|
||
// 1. Buscamos al cliente por su token
|
||
const qClient = await pool.query("SELECT * FROM clients WHERE portal_token = $1 LIMIT 1", [token]);
|
||
if (qClient.rowCount === 0) return res.status(404).json({ ok: false, error: "Enlace no válido" });
|
||
|
||
const client = qClient.rows[0];
|
||
const ownerId = client.owner_id;
|
||
|
||
// 2. ð FIX CRÃTICO: PEDIMOS BILLING_SETTINGS Y PUBLICIDAD A LA BBDD
|
||
const qConfig = await pool.query("SELECT full_name, company_logo, company_ad, billing_settings FROM users WHERE id = $1", [ownerId]);
|
||
const company = {
|
||
name: qConfig.rows[0]?.full_name || "IntegraRepara",
|
||
logo: qConfig.rows[0]?.company_logo || null,
|
||
ad: qConfig.rows[0]?.company_ad || null,
|
||
billing_settings: qConfig.rows[0]?.billing_settings || null // AQUÃ VIAJA EL IBAN Y LAS OBSERVACIONES
|
||
};
|
||
|
||
// 3. CONSULTA SEGURA (Con o sin ID)
|
||
let qServices;
|
||
if (serviceId && !isNaN(parseInt(serviceId))) {
|
||
qServices = await pool.query(`
|
||
SELECT s.id, s.service_ref, s.is_urgent, s.raw_data, s.created_at,
|
||
st.name as real_status_name, st.is_final as is_status_final,
|
||
u.full_name as worker_name, u.phone as worker_phone
|
||
FROM scraped_services s
|
||
LEFT JOIN users u ON u.id = s.assigned_to
|
||
LEFT JOIN service_statuses st ON st.id::text = (s.raw_data->>'status_operativo')::text
|
||
WHERE s.id = $1 AND s.owner_id = $2 AND s.provider != 'SYSTEM_BLOCK'
|
||
`, [parseInt(serviceId), ownerId]);
|
||
} else {
|
||
let phoneMatch = String(client.phone || "").replace(/[^0-9]/g, "");
|
||
if (phoneMatch.length > 9) phoneMatch = phoneMatch.slice(-9);
|
||
if (phoneMatch.length < 6) phoneMatch = "TELEFONO_FALSO_123";
|
||
|
||
qServices = await pool.query(`
|
||
SELECT s.id, s.service_ref, s.is_urgent, s.raw_data, s.created_at,
|
||
st.name as real_status_name, st.is_final as is_status_final,
|
||
u.full_name as worker_name, u.phone as worker_phone
|
||
FROM scraped_services s
|
||
LEFT JOIN users u ON u.id = s.assigned_to
|
||
LEFT JOIN service_statuses st ON st.id::text = (s.raw_data->>'status_operativo')::text
|
||
WHERE s.owner_id = $1 AND s.provider != 'SYSTEM_BLOCK'
|
||
AND s.raw_data::text ILIKE $2
|
||
ORDER BY s.created_at DESC
|
||
`, [ownerId, `%${phoneMatch}%`]);
|
||
}
|
||
|
||
const formattedServices = await Promise.all(qServices.rows.map(async s => {
|
||
return {
|
||
id: s.id,
|
||
title: s.is_urgent ? `ð¨ URGENTE: #${s.service_ref}` : `Expediente #${s.service_ref}`,
|
||
description: s.raw_data?.["Descripción"] || s.raw_data?.["DESCRIPCION"] || "Aviso de reparación",
|
||
description_clean: await getClientFriendlyDescription(s),
|
||
status_name: s.real_status_name || "En gestión",
|
||
is_final: s.is_status_final || false,
|
||
scheduled_date: s.raw_data?.scheduled_date || "",
|
||
scheduled_time: s.raw_data?.scheduled_time || "",
|
||
assigned_worker: s.worker_name || null,
|
||
worker_phone: s.worker_phone || null,
|
||
raw_data: s.raw_data
|
||
};
|
||
}));
|
||
|
||
// 4. BUSCAR PRESUPUESTOS CON SUS ARTÃCULOS
|
||
let cleanPhoneSearch = String(client.phone || "").replace(/[^0-9]/g, "");
|
||
if (cleanPhoneSearch.length > 9) cleanPhoneSearch = cleanPhoneSearch.slice(-9);
|
||
|
||
let formattedQuotes = [];
|
||
if (cleanPhoneSearch.length >= 9) {
|
||
const qBudgets = await pool.query(`
|
||
SELECT id, client_name, client_phone, client_address, items, subtotal, tax, total, status, created_at
|
||
FROM budgets
|
||
WHERE owner_id = $1
|
||
AND client_phone LIKE $2
|
||
ORDER BY created_at DESC
|
||
`, [ownerId, `%${cleanPhoneSearch}%`]);
|
||
|
||
formattedQuotes = qBudgets.rows.map(b => ({
|
||
id: b.id,
|
||
quote_ref: `PRE-${b.id}`,
|
||
title: "Presupuesto de Reparación",
|
||
amount: parseFloat(b.total).toFixed(2),
|
||
created_at: b.created_at,
|
||
items: b.items,
|
||
subtotal: b.subtotal,
|
||
tax: b.tax,
|
||
client_name: b.client_name,
|
||
client_phone: b.client_phone,
|
||
client_address: b.client_address,
|
||
status: b.status
|
||
}));
|
||
}
|
||
|
||
// ð 5. NUEVO: BUSCAR SI TIENE PLAN DE PROTECCIÃN ACTIVO
|
||
let activeSubscription = null;
|
||
if (cleanPhoneSearch.length >= 9) {
|
||
const subQ = await pool.query(`
|
||
SELECT s.status, s.payment_status, s.bricos_used, s.urgencies_used, s.renewal_date,
|
||
p.name as plan_name, p.bricos_limit, p.urgencies_limit
|
||
FROM protection_subscriptions s
|
||
JOIN protection_plans p ON s.plan_id = p.id
|
||
WHERE s.company_id = $1 AND s.client_phone LIKE $2 AND s.status = 'activo' AND s.payment_status = 'pagado'
|
||
ORDER BY s.created_at DESC LIMIT 1
|
||
`, [ownerId, `%${cleanPhoneSearch}%`]);
|
||
|
||
if (subQ.rowCount > 0) {
|
||
activeSubscription = subQ.rows[0];
|
||
}
|
||
}
|
||
|
||
res.json({
|
||
ok: true,
|
||
client: { name: client.full_name },
|
||
company,
|
||
services: formattedServices,
|
||
quotes: formattedQuotes,
|
||
subscription: activeSubscription // <-- ð¢ Lo pasamos al frontend del cliente
|
||
});
|
||
|
||
} catch (e) {
|
||
console.error("ð¥ ERROR EN PORTAL:", e.message);
|
||
res.status(500).json({ ok: false, error: e.message });
|
||
}
|
||
});
|
||
|
||
// 2. Obtener huecos disponibles inteligentes (CON ENRUTAMIENTO POR TURNOS: Mañana y Tarde)
|
||
app.get("/public/portal/:token/slots", async (req, res) => {
|
||
try {
|
||
const { token } = req.params;
|
||
const { serviceId } = req.query;
|
||
|
||
const clientQ = await pool.query("SELECT id, owner_id FROM clients WHERE portal_token = $1", [token]);
|
||
if (clientQ.rowCount === 0) return res.status(404).json({ ok: false, error: "Token inválido" });
|
||
const ownerId = clientQ.rows[0].owner_id;
|
||
|
||
// EXTRAEMOS LA CONFIGURACIÃN DE HORARIOS DEL PORTAL
|
||
const userQ = await pool.query("SELECT portal_settings FROM users WHERE id = $1", [ownerId]);
|
||
const pSet = userQ.rows[0]?.portal_settings || { m_start:"09:00", m_end:"14:00", a_start:"16:00", a_end:"19:00" };
|
||
|
||
function genSlots(start, end) {
|
||
if(!start || !end) return [];
|
||
let s = [];
|
||
let [sh, sm] = start.split(':').map(Number);
|
||
let [eh, em] = end.split(':').map(Number);
|
||
let cur = sh * 60 + sm;
|
||
let limit = eh * 60 + em;
|
||
|
||
while(cur + 60 <= limit) {
|
||
s.push(`${String(Math.floor(cur/60)).padStart(2,'0')}:${String(cur%60).padStart(2,'0')}`);
|
||
cur += 60;
|
||
}
|
||
return s;
|
||
}
|
||
|
||
const morningBase = genSlots(pSet.m_start, pSet.m_end);
|
||
const afternoonBase = genSlots(pSet.a_start, pSet.a_end);
|
||
|
||
const serviceQ = await pool.query("SELECT * FROM scraped_services WHERE id=$1", [serviceId]);
|
||
if (serviceQ.rowCount === 0) return res.status(404).json({ ok: false, error: "Servicio no encontrado" });
|
||
|
||
const service = serviceQ.rows[0];
|
||
const assignedTo = service.assigned_to;
|
||
if (!assignedTo) return res.status(400).json({ ok: false, error: "No hay operario asignado" });
|
||
|
||
const raw = service.raw_data || {};
|
||
const targetGuildId = raw["guild_id"];
|
||
|
||
// ð§ 1. EXTRAER LAS ZONAS DEL OPERARIO
|
||
const workerQ = await pool.query("SELECT zones FROM users WHERE id = $1", [assignedTo]);
|
||
const workerZones = workerQ.rows[0]?.zones || [];
|
||
|
||
function getCityForCP(cp, fallbackPop) {
|
||
let cleanCP = String(cp || "").trim();
|
||
const zone = workerZones.find(z => z.cps === cleanCP);
|
||
if (zone && zone.city) return zone.city.toUpperCase().trim();
|
||
return String(fallbackPop || "").toUpperCase().trim();
|
||
}
|
||
|
||
// Bautizamos al cliente actual
|
||
const targetCity = getCityForCP(raw["Código Postal"] || raw["C.P."], raw["Población"] || raw["POBLACION-PROVINCIA"]);
|
||
|
||
// ð§ 2. EXTRAER LA AGENDA TOTAL
|
||
const agendaQ = await pool.query(`
|
||
SELECT raw_data->>'scheduled_date' as date,
|
||
raw_data->>'scheduled_time' as time,
|
||
raw_data->>'requested_date' as req_date,
|
||
raw_data->>'requested_time' as req_time,
|
||
raw_data->>'appointment_status' as appt_status,
|
||
raw_data->>'duration_minutes' as duration,
|
||
raw_data->>'Población' as poblacion,
|
||
raw_data->>'Código Postal' as cp,
|
||
provider,
|
||
raw_data->>'blocked_guild_id' as blocked_guild_id
|
||
FROM scraped_services
|
||
WHERE assigned_to = $1
|
||
AND status != 'archived'
|
||
AND id != $2
|
||
`, [assignedTo, serviceId]);
|
||
|
||
const agendaMap = {};
|
||
|
||
agendaQ.rows.forEach(row => {
|
||
let effectiveDate = row.date;
|
||
let effectiveTime = row.time;
|
||
|
||
if (row.appt_status === 'pending' && row.req_date && row.req_time) {
|
||
effectiveDate = row.req_date;
|
||
effectiveTime = row.req_time;
|
||
}
|
||
|
||
if (!effectiveDate || new Date(effectiveDate) < new Date(new Date().toISOString().split('T')[0])) return;
|
||
|
||
if (row.provider === 'SYSTEM_BLOCK' && row.blocked_guild_id && String(row.blocked_guild_id) !== String(targetGuildId)) {
|
||
return;
|
||
}
|
||
|
||
// ð NUEVO: Ahora guardamos la ciudad de la MAÃANA y de la TARDE por separado
|
||
if (!agendaMap[effectiveDate]) agendaMap[effectiveDate] = { times: [], morningCity: null, afternoonCity: null };
|
||
|
||
if (row.provider !== 'SYSTEM_BLOCK' && effectiveTime) {
|
||
const city = getCityForCP(row.cp, row.poblacion);
|
||
let [th, tm] = effectiveTime.split(':').map(Number);
|
||
let [afternoonStartH, afternoonStartM] = pSet.a_start.split(':').map(Number); // Ej: 16:00
|
||
|
||
// Si la cita empieza antes del turno de tarde, bautiza la mañana. Si no, la tarde.
|
||
if (th < afternoonStartH) {
|
||
if (!agendaMap[effectiveDate].morningCity) agendaMap[effectiveDate].morningCity = city;
|
||
} else {
|
||
if (!agendaMap[effectiveDate].afternoonCity) agendaMap[effectiveDate].afternoonCity = city;
|
||
}
|
||
}
|
||
|
||
const dur = parseInt(row.duration || 60);
|
||
if (effectiveTime) {
|
||
let [th, tm] = effectiveTime.split(':').map(Number);
|
||
let startMin = th * 60 + tm;
|
||
let endMin = startMin + dur;
|
||
|
||
const blockSlots = (base) => {
|
||
base.forEach(slot => {
|
||
let [sh, sm] = slot.split(':').map(Number);
|
||
let slotStart = sh * 60 + sm;
|
||
let slotEnd = slotStart + 60;
|
||
if(slotStart < endMin && slotEnd > startMin) {
|
||
agendaMap[effectiveDate].times.push(slot);
|
||
}
|
||
});
|
||
};
|
||
blockSlots(morningBase);
|
||
blockSlots(afternoonBase);
|
||
}
|
||
});
|
||
|
||
// ð§ 3. GENERAR LOS DÃAS DISPONIBLES (CON CORTAFUEGOS POR TURNOS)
|
||
const availableDays = [];
|
||
let d = new Date();
|
||
d.setDate(d.getDate() + 1);
|
||
|
||
let daysAdded = 0;
|
||
while(daysAdded < 5) {
|
||
if (d.getDay() !== 0 && d.getDay() !== 6) {
|
||
const dateStr = d.toISOString().split('T')[0];
|
||
const dayData = agendaMap[dateStr];
|
||
|
||
const takenTimes = dayData ? dayData.times : [];
|
||
let availMorning = morningBase.filter(t => !takenTimes.includes(t));
|
||
let availAfternoon = afternoonBase.filter(t => !takenTimes.includes(t));
|
||
|
||
// ð REGLA CRÃTICA DE TURNOS: Bloqueamos de forma independiente
|
||
if (dayData) {
|
||
if (dayData.morningCity && dayData.morningCity !== targetCity) {
|
||
availMorning = []; // Mañana ocupada en otra ciudad
|
||
}
|
||
if (dayData.afternoonCity && dayData.afternoonCity !== targetCity) {
|
||
availAfternoon = []; // Tarde ocupada en otra ciudad
|
||
}
|
||
}
|
||
|
||
if (availMorning.length > 0 || availAfternoon.length > 0) {
|
||
availableDays.push({
|
||
date: dateStr,
|
||
displayDate: d.toLocaleDateString('es-ES', { weekday: 'long', day: 'numeric', month: 'long' }),
|
||
morning: availMorning,
|
||
afternoon: availAfternoon
|
||
});
|
||
daysAdded++;
|
||
}
|
||
}
|
||
d.setDate(d.getDate() + 1);
|
||
}
|
||
res.json({ ok: true, days: availableDays });
|
||
} catch (e) {
|
||
console.error("Error Slots:", e);
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
|
||
// 3. Obtener los Gremios Visibles, Logo y Nombre para el Portal Público
|
||
app.get("/public/company/:id/guilds", async (req, res) => {
|
||
try {
|
||
const ownerId = parseInt(req.params.id) || 1;
|
||
|
||
// 1. Leemos la configuración de esta empresa (INCLUYENDO LOGO Y NOMBRE)
|
||
const userQ = await pool.query("SELECT full_name, company_logo, portal_settings FROM users WHERE id = $1", [ownerId]);
|
||
if(userQ.rowCount === 0) return res.status(404).json({ok: false});
|
||
|
||
const company = userQ.rows[0];
|
||
const settings = company.portal_settings || {};
|
||
const visibleIds = settings.visible_guilds || [];
|
||
|
||
let guilds = [];
|
||
// 2. Buscamos los gremios seleccionados
|
||
if (visibleIds.length > 0) {
|
||
const guildsQ = await pool.query("SELECT id, name FROM guilds WHERE id = ANY($1::int[]) AND owner_id = $2 ORDER BY name ASC", [visibleIds, ownerId]);
|
||
guilds = guildsQ.rows;
|
||
}
|
||
|
||
// Devolvemos TODO empaquetado al frontend
|
||
res.json({
|
||
ok: true,
|
||
name: company.full_name,
|
||
logo: company.company_logo,
|
||
guilds: guilds
|
||
});
|
||
} catch(e) {
|
||
res.status(500).json({ok: false});
|
||
}
|
||
});
|
||
|
||
|
||
// --- RUTA PARA GUARDAR LA CITA SOLICITADA POR EL CLIENTE ---
|
||
app.post("/public/portal/:token/book", async (req, res) => {
|
||
try {
|
||
const { token } = req.params;
|
||
const { serviceId, date, time } = req.body;
|
||
|
||
if (!serviceId || !date || !time) return res.status(400).json({ ok: false, error: "Faltan datos" });
|
||
|
||
// Verificamos quién es el dueño del portal usando el token
|
||
const clientQ = await pool.query("SELECT id, owner_id FROM clients WHERE portal_token = $1", [token]);
|
||
if (clientQ.rowCount === 0) return res.status(404).json({ ok: false, error: "Token inválido" });
|
||
const ownerId = clientQ.rows[0].owner_id;
|
||
|
||
// ð¨ CAMBIO AQUÃ: Recuperamos los datos crudos Y TAMBIÃN a quién está asignado
|
||
const serviceQ = await pool.query("SELECT raw_data, assigned_to, service_ref FROM scraped_services WHERE id=$1 AND owner_id=$2", [serviceId, ownerId]);
|
||
if (serviceQ.rowCount === 0) return res.status(404).json({ ok: false, error: "Servicio no encontrado" });
|
||
|
||
const srv = serviceQ.rows[0];
|
||
const raw = srv.raw_data || {};
|
||
|
||
// ð¡ï¸ ESCUDO: Verificamos que el hueco siga libre (Por si 2 clientes hacen clic en el mismo milisegundo)
|
||
if (srv.assigned_to) {
|
||
const solapamiento = await comprobarDisponibilidad(ownerId, srv.assigned_to, date, time, 60, serviceId);
|
||
if (solapamiento.choca) {
|
||
return res.status(400).json({ ok: false, error: "Lo sentimos, alguien acaba de reservar ese mismo hueco hace unos instantes. Por favor, elige otro horario." });
|
||
}
|
||
}
|
||
|
||
// Grabamos la solicitud en el jsonb para que el admin la vea en agenda.html
|
||
raw.requested_date = date;
|
||
raw.requested_time = time;
|
||
raw.appointment_status = 'pending';
|
||
|
||
await pool.query("UPDATE scraped_services SET raw_data = $1 WHERE id = $2", [JSON.stringify(raw), serviceId]);
|
||
|
||
// =========================================================
|
||
// ð¨ MAGIA: AVISAR AL OPERARIO POR WHATSAPP AL INSTANTE
|
||
// =========================================================
|
||
if (srv.assigned_to) {
|
||
const workerQ = await pool.query("SELECT full_name, phone FROM users WHERE id=$1", [srv.assigned_to]);
|
||
if (workerQ.rowCount > 0) {
|
||
const w = workerQ.rows[0];
|
||
const ref = srv.service_ref || raw["Referencia"] || serviceId;
|
||
const clientName = raw["Nombre Cliente"] || raw["CLIENTE"] || "El cliente";
|
||
|
||
// Formateamos la fecha para que se lea bonita en WhatsApp
|
||
const [y, m, d] = date.split('-');
|
||
const dateFormatted = `${d}/${m}/${y}`;
|
||
|
||
const msg = `ð *¡NUEVA CITA SOLICITADA!*\n\nHola ${w.full_name}, ${clientName} acaba de elegir un hueco para el expediente *#${ref}*.\n\nð
*Fecha:* ${dateFormatted}\nâ° *Hora aprox:* ${time}\n\nEntra en tu App (Agenda) para confirmarla o rechazarla.`;
|
||
|
||
// Enviamos el WA de aviso al trabajador
|
||
sendWhatsAppAuto(w.phone, msg, `cliente_${ownerId}`, false).catch(console.error);
|
||
}
|
||
}
|
||
|
||
res.json({ ok: true });
|
||
} catch (e) {
|
||
console.error("Error agendando cita (book):", e);
|
||
res.status(500).json({ ok: false, error: "Error interno" });
|
||
}
|
||
});
|
||
|
||
// 3. OBTENER SOLICITUDES PARA EL PANEL DEL ADMIN Y APP OPERARIO
|
||
app.get("/agenda/requests", authMiddleware, async (req, res) => {
|
||
try {
|
||
let query = `
|
||
SELECT s.id, s.service_ref, s.raw_data, u.full_name as assigned_name
|
||
FROM scraped_services s
|
||
LEFT JOIN users u ON s.assigned_to = u.id
|
||
WHERE s.owner_id = $1
|
||
AND s.raw_data->>'appointment_status' = 'pending'
|
||
`;
|
||
const params = [req.user.accountId];
|
||
|
||
// Si es operario, solo ve sus propias solicitudes
|
||
if (req.user.role === 'operario' || req.user.role === 'operario_cerrado') {
|
||
query += ` AND s.assigned_to = $2`;
|
||
params.push(req.user.sub);
|
||
}
|
||
|
||
query += ` ORDER BY s.created_at ASC`;
|
||
|
||
const q = await pool.query(query, params);
|
||
res.json({ ok: true, requests: q.rows });
|
||
} catch (e) { res.status(500).json({ ok: false }); }
|
||
});
|
||
|
||
app.post("/agenda/requests/:id/approve", authMiddleware, async (req, res) => {
|
||
try {
|
||
const { id } = req.params;
|
||
// ð NUEVO: Recibimos date y time desde la App
|
||
const { duration, date, time } = req.body;
|
||
|
||
const current = await pool.query('SELECT raw_data, assigned_to FROM scraped_services WHERE id=$1 AND owner_id=$2', [id, req.user.accountId]);
|
||
if (current.rowCount === 0) return res.status(404).json({ok: false});
|
||
|
||
const raw = current.rows[0].raw_data;
|
||
const assignedTo = current.rows[0].assigned_to;
|
||
// ð NUEVO: Si el técnico ha cambiado la fecha/hora en la App, usamos esa. Si no, la que pidió el cliente.
|
||
const reqDate = date || raw.requested_date;
|
||
const reqTime = time || raw.requested_time;
|
||
|
||
// ð¡ï¸ ESCUDO: Verificamos que el hueco siga libre antes de confirmar (evita solapamientos)
|
||
if (assignedTo && reqDate && reqTime) {
|
||
const solapamiento = await comprobarDisponibilidad(req.user.accountId, assignedTo, reqDate, reqTime, duration || 60, id);
|
||
if (solapamiento.choca) {
|
||
return res.status(400).json({ ok: false, error: `Ese hueco ya no está libre (choca con ${solapamiento.ref} a las ${solapamiento.time}). Elige otra hora.` });
|
||
}
|
||
}
|
||
|
||
const statusQ = await pool.query("SELECT id FROM service_statuses WHERE owner_id=$1 AND name ILIKE '%citado%' LIMIT 1", [req.user.accountId]);
|
||
const idCitado = statusQ.rows[0]?.id || raw.status_operativo;
|
||
|
||
const updatedRaw = {
|
||
...raw,
|
||
scheduled_date: reqDate,
|
||
scheduled_time: reqTime,
|
||
duration_minutes: duration,
|
||
appointment_status: 'approved',
|
||
status_operativo: idCitado
|
||
};
|
||
delete updatedRaw.requested_date;
|
||
delete updatedRaw.requested_time;
|
||
|
||
// 1. Guardamos en Base de Datos
|
||
await pool.query("UPDATE scraped_services SET raw_data=$1 WHERE id=$2", [JSON.stringify(updatedRaw), id]);
|
||
|
||
console.log(`ð¤ [PORTAL-CITA] Cita aprobada para ${reqDate}. Disparando eventos...`);
|
||
|
||
// ð 2. RESPONDEMOS AL NAVEGADOR INMEDIATAMENTE (La ventana se cierra al instante)
|
||
res.json({ok: true});
|
||
|
||
// ð» 3. TAREAS EN SEGUNDO PLANO (El WA tarda 10 segs, pero el usuario ya no espera)
|
||
(async () => {
|
||
try {
|
||
// Disparamos WhatsApp oficial de cita confirmada
|
||
await triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_date');
|
||
|
||
// Disparamos ROBOTS SEGÃN PROVEEDOR
|
||
const checkProv = await pool.query("SELECT provider FROM scraped_services WHERE id=$1", [id]);
|
||
const providerName = checkProv.rows[0]?.provider;
|
||
|
||
if (providerName === 'homeserve') {
|
||
console.log(`â
[PORTAL-CITA] Disparando robot HS: CITA (${reqDate})`);
|
||
triggerHomeServeRobot(req.user.accountId, id, 'date').catch(console.error);
|
||
} else if (providerName === 'multiasistencia') {
|
||
console.log(`â
[PORTAL-CITA] Disparando robot MULTI: CITA (${reqDate})`);
|
||
triggerMultiRobot(req.user.accountId, id, 'date').catch(console.error);
|
||
}
|
||
} catch (errBckg) {
|
||
console.error("Error en tareas de fondo de aprobar cita:", errBckg);
|
||
}
|
||
})();
|
||
|
||
} catch (e) {
|
||
console.error("Error al aprobar cita:", e);
|
||
if (!res.headersSent) res.status(500).json({ok: false});
|
||
}
|
||
});
|
||
|
||
// 5. RECHAZAR CITA
|
||
app.post("/agenda/requests/:id/reject", authMiddleware, async (req, res) => {
|
||
try {
|
||
const { id } = req.params;
|
||
const current = await pool.query('SELECT raw_data FROM scraped_services WHERE id=$1 AND owner_id=$2', [id, req.user.accountId]);
|
||
if (current.rowCount === 0) return res.status(404).json({ok: false});
|
||
|
||
const raw = current.rows[0].raw_data;
|
||
const updatedRaw = { ...raw, appointment_status: 'rejected' };
|
||
delete updatedRaw.requested_date;
|
||
delete updatedRaw.requested_time;
|
||
|
||
await pool.query("UPDATE scraped_services SET raw_data=$1 WHERE id=$2", [JSON.stringify(updatedRaw), id]);
|
||
|
||
// Enviar WA de rechazo con el enlace para que elija otra
|
||
const phone = raw["Teléfono"] || raw["TELEFONO"] || "";
|
||
if (phone) {
|
||
const clientQ = await pool.query("SELECT portal_token FROM clients WHERE phone LIKE $1 AND owner_id=$2 LIMIT 1", [`%${phone.replace('+34', '').trim()}%`, req.user.accountId]);
|
||
const token = clientQ.rows[0]?.portal_token;
|
||
const link = `https://portal.integrarepara.es/?token=${token}&service=${id}`;
|
||
|
||
const finalMsg = `â ï¸ *CITA NO CONFIRMADA*\n\nHola ${raw["Nombre Cliente"] || "Cliente"}. Lamentamos informarte que el técnico no podrá acudir en el horario que solicitaste por un problema de ruta.\n\nPor favor, entra de nuevo en tu portal y elige otro hueco disponible:\nð ${link}`;
|
||
|
||
await sendWhatsAppAuto(phone, finalMsg, `cliente_${req.user.accountId}`, false);
|
||
}
|
||
res.json({ok: true});
|
||
} catch (e) { res.status(500).json({ok: false}); }
|
||
});
|
||
|
||
|
||
// 6. RUTAS DE BLOQUEOS (AGENDA) CON SOPORTE PARA GREMIOS
|
||
app.post("/agenda/blocks", authMiddleware, async (req, res) => {
|
||
try {
|
||
const { worker_id, date, time, duration, reason, guild_id, guild_name } = req.body;
|
||
|
||
const raw = {
|
||
"Nombre Cliente": "BLOQUEO DE AGENDA",
|
||
"Descripción": reason,
|
||
scheduled_date: date,
|
||
scheduled_time: time,
|
||
duration_minutes: duration,
|
||
blocked_guild_id: guild_id || null, // Guardamos el gremio
|
||
blocked_guild_name: guild_name || null
|
||
};
|
||
|
||
await pool.query(`
|
||
INSERT INTO scraped_services (owner_id, provider, service_ref, status, assigned_to, raw_data)
|
||
VALUES ($1, 'SYSTEM_BLOCK', 'BLOCK-' || extract(epoch from now())::int, 'pending', $2, $3)
|
||
`, [req.user.accountId, worker_id, JSON.stringify(raw)]);
|
||
|
||
res.json({ ok: true });
|
||
} catch(e) { res.status(500).json({ ok: false }); }
|
||
});
|
||
|
||
app.get("/agenda/blocks", authMiddleware, async (req, res) => {
|
||
try {
|
||
const q = await pool.query(`
|
||
SELECT s.id, u.full_name as worker_name,
|
||
s.raw_data->>'scheduled_date' as date,
|
||
s.raw_data->>'scheduled_time' as time,
|
||
s.raw_data->>'duration_minutes' as duration,
|
||
s.raw_data->>'Descripción' as reason,
|
||
s.raw_data->>'blocked_guild_name' as guild_name
|
||
FROM scraped_services s
|
||
JOIN users u ON s.assigned_to = u.id
|
||
WHERE s.owner_id = $1 AND s.provider = 'SYSTEM_BLOCK'
|
||
ORDER BY s.raw_data->>'scheduled_date' DESC
|
||
`, [req.user.accountId]);
|
||
|
||
res.json({ ok: true, blocks: q.rows });
|
||
} catch(e) { res.status(500).json({ ok: false }); }
|
||
});
|
||
|
||
app.delete("/agenda/blocks/:id", authMiddleware, async (req, res) => {
|
||
try {
|
||
await pool.query("DELETE FROM scraped_services WHERE id=$1 AND owner_id=$2 AND provider='SYSTEM_BLOCK'", [req.params.id, req.user.accountId]);
|
||
res.json({ ok: true });
|
||
} catch(e) { res.status(500).json({ ok: false }); }
|
||
});
|
||
|
||
// ==========================================
|
||
// ð¥ TRASPASO MANUAL (BUZÃN -> PANEL)
|
||
// ==========================================
|
||
app.post('/providers/import/:id', authMiddleware, async (req, res) => {
|
||
try {
|
||
const { id } = req.params;
|
||
|
||
// 1. Cambiamos el estado principal a 'imported' para que el buzón lo marque en azul
|
||
// y detenemos cualquier automatismo pendiente ('completed')
|
||
await pool.query(
|
||
"UPDATE scraped_services SET status = 'imported', automation_status = 'completed' WHERE id = $1 AND owner_id = $2",
|
||
[id, req.user.accountId]
|
||
);
|
||
|
||
// 2. Dejamos constancia en la trazabilidad (Historial)
|
||
await pool.query(
|
||
"INSERT INTO scraped_service_logs (scraped_id, user_name, action, details) VALUES ($1, $2, $3, $4)",
|
||
[id, "Admin", "Traspaso Manual", "El expediente ha sido validado y asignado desde el buzón."]
|
||
);
|
||
|
||
res.json({ ok: true });
|
||
} catch (e) {
|
||
console.error("Error en traspaso manual:", e);
|
||
res.status(500).json({ ok: false, error: "Error en el servidor" });
|
||
}
|
||
});
|
||
|
||
// ==========================================
|
||
// âï¸ MOTOR AUTOMÃTICO DE WHATSAPP Y APP SETTINGS (AÃADIDO PARA SOLUCIONAR ERROR 404)
|
||
// ==========================================
|
||
app.get("/whatsapp/status", authMiddleware, async (req, res) => {
|
||
try {
|
||
const instanceName = `cliente_${req.user.accountId}`;
|
||
if (!EVOLUTION_BASE_URL || !EVOLUTION_API_KEY) return res.json({ ok: false, error: "Servidor Evolution no configurado" });
|
||
|
||
const baseUrl = EVOLUTION_BASE_URL.replace(/\/$/, "");
|
||
const headers = { "Content-Type": "application/json", "apikey": EVOLUTION_API_KEY.trim() };
|
||
|
||
// 1. Verificamos si la instancia existe en Evolution
|
||
let statusRes = await fetch(`${baseUrl}/instance/connectionState/${instanceName}`, { headers });
|
||
|
||
// 2. Si da 404, significa que nunca se ha creado. La creamos y pedimos el QR
|
||
if (statusRes.status === 404) {
|
||
await fetch(`${baseUrl}/instance/create`, {
|
||
method: 'POST', headers,
|
||
body: JSON.stringify({ instanceName: instanceName, qrcode: true, integration: "WHATSAPP-BAILEYS" })
|
||
});
|
||
// Esperamos un poco y volvemos a consultar
|
||
await new Promise(r => setTimeout(r, 2000));
|
||
statusRes = await fetch(`${baseUrl}/instance/connectionState/${instanceName}`, { headers });
|
||
}
|
||
|
||
const data = await statusRes.json();
|
||
|
||
// 3. Devolvemos el estado
|
||
if (data.instance?.state === 'open') {
|
||
return res.json({ ok: true, state: 'open', instanceName });
|
||
} else {
|
||
// Buscamos el QR
|
||
const qrRes = await fetch(`${baseUrl}/instance/connect/${instanceName}`, { headers });
|
||
const qrData = await qrRes.json();
|
||
return res.json({ ok: true, state: 'connecting', qr: qrData.base64 || qrData.code });
|
||
}
|
||
} catch (e) {
|
||
console.error("Error consultando estado WA:", e);
|
||
res.status(500).json({ ok: false, error: "Error de conexión con el motor WA" });
|
||
}
|
||
});
|
||
|
||
|
||
app.get("/whatsapp/settings", authMiddleware, async (req, res) => {
|
||
try {
|
||
const q = await pool.query("SELECT wa_settings FROM users WHERE id=$1", [req.user.accountId]);
|
||
res.json({
|
||
ok: true,
|
||
settings: q.rows[0]?.wa_settings || {},
|
||
// ð£ï¸ Texto que usa la IA por defecto para el bloque de estilo/reglas de negocio
|
||
// cuando la empresa aún no ha guardado nada personalizado. El panel lo usa para
|
||
// precargar el cuadro de texto la primera vez, para que se vea lo que hace hoy.
|
||
default_ai_rules: DEFAULT_REGLAS_NEGOCIO_IA
|
||
});
|
||
} catch (e) { res.status(500).json({ ok: false }); }
|
||
});
|
||
|
||
app.post("/whatsapp/settings", authMiddleware, async (req, res) => {
|
||
try {
|
||
// ð MAGIA: Usamos COALESCE y el operador || de PostgreSQL para FUSIONAR los JSON.
|
||
// AsÃ, si guardas la IA, no borra el Robot, y si guardas el Robot, no borra la IA.
|
||
await pool.query(`
|
||
UPDATE users
|
||
SET wa_settings = COALESCE(wa_settings, '{}'::jsonb) || $1::jsonb
|
||
WHERE id=$2
|
||
`, [JSON.stringify(req.body), req.user.accountId]);
|
||
|
||
res.json({ ok: true });
|
||
} catch (e) {
|
||
console.error("Error guardando settings:", e);
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
// ==========================================
|
||
// ð¬ NÃCLEO DE ENVÃO WHATSAPP (EVOLUTION API - MODO HUMANO DINÃMICO)
|
||
// ==========================================
|
||
async function sendWhatsAppAuto(phone, message, instanceName, useDelay = false) {
|
||
if (!EVOLUTION_BASE_URL || !EVOLUTION_API_KEY) {
|
||
console.error("â ï¸ WhatsApp omitido: Servidor Evolution no configurado.");
|
||
return false;
|
||
}
|
||
|
||
// ð§ Lógica de escritura "Modo Humano"
|
||
let timeToType = 0;
|
||
if (useDelay) {
|
||
// Calcula 50ms por cada carácter del mensaje
|
||
let baseTime = message.length * 50;
|
||
|
||
// Nos aseguramos de que tarde entre 1.5 segundos (mÃnimo) y 10 segundos (máximo)
|
||
baseTime = Math.min(Math.max(baseTime, 1500), 10000);
|
||
|
||
// Sumamos un margen aleatorio (entre 0 y 1.5 segundos) para que nunca tarde exactamente lo mismo
|
||
const factorAleatorio = Math.floor(Math.random() * 1500);
|
||
timeToType = baseTime + factorAleatorio;
|
||
|
||
console.log(`[WA] Modo Humano: Simulando escritura durante ${Math.round(timeToType/1000)} segundos para un texto de ${message.length} letras.`);
|
||
}
|
||
|
||
try {
|
||
const baseUrl = EVOLUTION_BASE_URL.replace(/\/$/, "");
|
||
const url = `${baseUrl}/message/sendText/${instanceName}`;
|
||
|
||
const response = await fetch(url, {
|
||
method: 'POST',
|
||
headers: {
|
||
"Content-Type": "application/json",
|
||
"apikey": EVOLUTION_API_KEY.trim()
|
||
},
|
||
body: JSON.stringify({
|
||
number: phone,
|
||
text: message,
|
||
delay: timeToType, // Usamos el tiempo dinámico que acabamos de calcular
|
||
linkPreview: true // Muestra la vista previa del enlace (imagen/tÃtulo) en WhatsApp
|
||
})
|
||
});
|
||
|
||
if (!response.ok) {
|
||
const errText = await response.text().catch(() => "");
|
||
console.error("â Fallo enviando WhatsApp. Estado Evolution:", response.status, "Tel:", phone, "Detalle:", errText.substring(0, 300));
|
||
return false;
|
||
}
|
||
return true;
|
||
} catch (error) {
|
||
console.error("â Error de red conectando con Evolution API:", error.message);
|
||
return false;
|
||
}
|
||
}
|
||
|
||
// ð EnvÃa un documento (PDF) por WhatsApp vÃa Evolution API. Devuelve {ok, detail}
|
||
// para poder ver el motivo exacto de un fallo (útil para depurar en caliente).
|
||
async function sendWhatsAppMedia(phone, base64Pdf, fileName, caption, instanceName) {
|
||
if (!EVOLUTION_BASE_URL || !EVOLUTION_API_KEY) {
|
||
console.error("â ï¸ WhatsApp omitido: Servidor Evolution no configurado.");
|
||
return { ok: false, detail: "Evolution no configurado" };
|
||
}
|
||
if (!base64Pdf) return { ok: false, detail: "Sin PDF" };
|
||
|
||
try {
|
||
const baseUrl = EVOLUTION_BASE_URL.replace(/\/$/, "");
|
||
const url = `${baseUrl}/message/sendMedia/${instanceName}`;
|
||
const cleanBase64 = base64Pdf.includes(',') ? base64Pdf.split(',').pop() : base64Pdf;
|
||
|
||
const response = await fetch(url, {
|
||
method: 'POST',
|
||
headers: {
|
||
"Content-Type": "application/json",
|
||
"apikey": EVOLUTION_API_KEY.trim()
|
||
},
|
||
body: JSON.stringify({
|
||
number: phone,
|
||
mediatype: "document",
|
||
mimetype: "application/pdf",
|
||
fileName: fileName,
|
||
caption: caption,
|
||
media: cleanBase64
|
||
})
|
||
});
|
||
|
||
if (!response.ok) {
|
||
const errText = await response.text().catch(() => "");
|
||
console.error("â Fallo enviando documento WhatsApp. Estado Evolution:", response.status, errText);
|
||
return { ok: false, detail: `HTTP ${response.status}: ${errText.substring(0, 300)}` };
|
||
}
|
||
return { ok: true };
|
||
} catch (error) {
|
||
console.error("â Error de red enviando documento WhatsApp:", error.message);
|
||
return { ok: false, detail: error.message };
|
||
}
|
||
}
|
||
|
||
// ==========================================
|
||
// ð DISPARADOR DE EVENTOS DE WHATSAPP (CON MODO SEGURO)
|
||
// ==========================================
|
||
async function triggerWhatsAppEvent(ownerId, serviceId, eventType) {
|
||
try {
|
||
const userQ = await pool.query("SELECT wa_settings FROM users WHERE id=$1", [ownerId]);
|
||
const settings = userQ.rows[0]?.wa_settings || {};
|
||
const checkSwitch = eventType === 'wa_evt_update' ? 'wa_evt_date' : eventType;
|
||
if (!settings[checkSwitch]) return false; // Botón apagado = No enviado
|
||
|
||
const tplTypeMap = {
|
||
'wa_evt_welcome': 'welcome',
|
||
'wa_evt_assigned': 'assigned',
|
||
'wa_evt_date': 'appointment',
|
||
'wa_evt_update': 'update',
|
||
'wa_evt_onway': 'on_way',
|
||
'wa_evt_survey': 'survey'
|
||
};
|
||
const tplQ = await pool.query("SELECT content FROM message_templates WHERE owner_id=$1 AND type=$2", [ownerId, tplTypeMap[eventType]]);
|
||
if (tplQ.rowCount === 0 || !tplQ.rows[0].content) return false;
|
||
let text = tplQ.rows[0].content;
|
||
|
||
const svcQ = await pool.query("SELECT * FROM scraped_services WHERE id=$1", [serviceId]);
|
||
if (svcQ.rowCount === 0) return false;
|
||
const s = svcQ.rows[0];
|
||
const raw = s.raw_data || {};
|
||
|
||
// 1. EXTRAER TELÃFONO DEL CLIENTE LIMPIO (prioriza móvil sobre fijo)
|
||
let cleanPhoneToMatch = extractBestMobile(raw);
|
||
if (cleanPhoneToMatch.length < 9) return false; // Si no hay teléfono válido, cancelamos
|
||
|
||
const finalPhoneToSend = "34" + cleanPhoneToMatch;
|
||
|
||
// 2. Buscamos el token del portal cliente (o lo creamos si no existe)
|
||
let token = "ERROR";
|
||
const clientQ = await pool.query("SELECT portal_token FROM clients WHERE phone LIKE $1 AND owner_id=$2 LIMIT 1", [`%${cleanPhoneToMatch}%`, ownerId]);
|
||
|
||
if (clientQ.rowCount > 0) {
|
||
token = clientQ.rows[0].portal_token;
|
||
} else {
|
||
const cName = raw["Nombre Cliente"] || raw["CLIENTE"] || "Asegurado";
|
||
const cAddr = raw["Dirección"] || raw["DOMICILIO"] || "";
|
||
const insertC = await pool.query(
|
||
"INSERT INTO clients (owner_id, full_name, phone, addresses) VALUES ($1, $2, $3, $4) RETURNING portal_token",
|
||
[ownerId, cName, finalPhoneToSend, JSON.stringify([cAddr])]
|
||
);
|
||
token = insertC.rows[0].portal_token;
|
||
}
|
||
|
||
const linkMagico = `https://portal.integrarepara.es/?token=${token}&service=${serviceId}`;
|
||
|
||
let fechaLimpia = raw["scheduled_date"] || "la fecha acordada";
|
||
if (fechaLimpia.includes("-")) {
|
||
const partes = fechaLimpia.split("-");
|
||
if (partes.length === 3) {
|
||
const fechaObj = new Date(partes[0], partes[1] - 1, partes[2], 12, 0, 0);
|
||
const diaSemana = fechaObj.toLocaleDateString('es-ES', { weekday: 'long' });
|
||
fechaLimpia = `(${diaSemana}) ${partes[2]}/${partes[1]}/${partes[0]}`;
|
||
}
|
||
}
|
||
|
||
text = text.replace(/{{NOMBRE}}/g, raw["Nombre Cliente"] || raw["CLIENTE"] || "Cliente");
|
||
text = text.replace(/{{DIRECCION}}/g, raw["Dirección"] || raw["DOMICILIO"] || "su domicilio");
|
||
text = text.replace(/{{FECHA}}/g, fechaLimpia);
|
||
text = text.replace(/{{HORA}}/g, raw["scheduled_time"] || "la hora acordada");
|
||
text = text.replace(/{{COMPANIA}}/g, raw["CompañÃa"] || raw["COMPAÃIA"] || "su Aseguradora");
|
||
text = text.replace(/{{REFERENCIA}}/g, s.service_ref || raw["Referencia"] || raw["Nº Siniestro"] || serviceId);
|
||
text = text.replace(/{{ENLACE}}/g, linkMagico);
|
||
|
||
const useDelay = settings.wa_delay_enabled !== false;
|
||
const instanceName = `cliente_${ownerId}`;
|
||
|
||
// ====================================================
|
||
// ð MODO PRUEBAS (DesvÃa los mensajes a tu móvil)
|
||
// ====================================================
|
||
const MODO_PRUEBAS = false; // Cambia esto a 'false' para enviar a clientes reales
|
||
const MI_TELEFONO = "34667248132"; // <--- TU NÃMERO DE MÃVIL YA CONFIGURADO
|
||
|
||
if (MODO_PRUEBAS) {
|
||
console.log(`ð¡ï¸ [MODO PRUEBAS] Enviando WA al admin (${MI_TELEFONO}) en lugar de al cliente (${finalPhoneToSend})`);
|
||
const textoPrueba = `*(SIMULACIÃN PARA CLIENTE: ${finalPhoneToSend})*\n\n` + text;
|
||
return await sendWhatsAppAuto(MI_TELEFONO, textoPrueba, instanceName, useDelay);
|
||
} else {
|
||
console.log(`[WA] Enviando mensaje real al cliente: ${finalPhoneToSend}`);
|
||
return await sendWhatsAppAuto(finalPhoneToSend, text, instanceName, useDelay);
|
||
}
|
||
|
||
} catch (e) {
|
||
console.error("Error Motor WA:", e.message);
|
||
return false;
|
||
}
|
||
}
|
||
|
||
// ==========================================
|
||
// ð CREDENCIALES DE PROVEEDORES
|
||
// ==========================================
|
||
app.get("/providers/credentials", authMiddleware, async (req, res) => {
|
||
try {
|
||
// ð ï¸ FIX 1: Añadimos 'auto_dispatch' a la consulta para que el botón "recuerde" si está encendido
|
||
const q = await pool.query("SELECT provider, username, last_sync, status, auto_dispatch FROM provider_credentials WHERE owner_id=$1", [req.user.accountId]);
|
||
res.json({ ok: true, credentials: q.rows });
|
||
} catch (e) {
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
app.post("/providers/credentials", authMiddleware, async (req, res) => {
|
||
try {
|
||
const { provider, username, password, auto_dispatch } = req.body;
|
||
|
||
// Si no hay contraseña, pasamos null
|
||
const passwordSafe = (password && password.trim() !== "") ? Buffer.from(password).toString('base64') : null;
|
||
|
||
const autoDispatchBool = auto_dispatch === true;
|
||
|
||
// ð ï¸ FIX 2: Usamos COALESCE($4, '') en el INSERT.
|
||
// Si es la primera vez y no pones clave, guarda un texto vacÃo ('') en vez de null para que la base de datos no explote con error 500.
|
||
await pool.query(`
|
||
INSERT INTO provider_credentials (owner_id, provider, username, password_hash, auto_dispatch)
|
||
VALUES ($1, $2, $3, COALESCE($4, ''), $5)
|
||
ON CONFLICT (owner_id, provider) DO UPDATE SET
|
||
username = EXCLUDED.username,
|
||
password_hash = COALESCE($4, provider_credentials.password_hash),
|
||
auto_dispatch = EXCLUDED.auto_dispatch,
|
||
status = 'active'
|
||
`, [req.user.accountId, provider, username, passwordSafe, autoDispatchBool]);
|
||
|
||
res.json({ ok: true });
|
||
} catch (e) {
|
||
console.error("Error guardando credenciales:", e.message);
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
// ==========================================
|
||
// ð MOTOR DE AUTO-ASIGNACIÃN (BOLSA INTERNA)
|
||
// ==========================================
|
||
async function dispatchToBolsa(serviceId, guildId, cp, accountId, userId) {
|
||
try {
|
||
let workersQ = await pool.query(`
|
||
SELECT u.id, u.full_name, u.phone FROM users u
|
||
JOIN user_guilds ug ON u.id = ug.user_id
|
||
WHERE u.owner_id = $1 AND u.role = 'operario' AND u.status = 'active'
|
||
AND ug.guild_id = $2 AND u.zones::jsonb @> $3::jsonb
|
||
`, [accountId, guildId, JSON.stringify([{ cps: (cp || "00000").toString() }])]);
|
||
|
||
// ð¥ Se ha ELIMINADO el bloque fallback. Si nadie tiene el CP, abortamos misión y se queda en el buzón.
|
||
if (workersQ.rowCount === 0) {
|
||
console.log(`â ï¸ [AUTO-DISPATCH] Abortado: No hay operarios de ese gremio dados de alta en el CP ${cp}.`);
|
||
return { ok: false, error: "No hay operarios con este código postal asignado." };
|
||
}
|
||
|
||
await pool.query("UPDATE scraped_services SET automation_status = 'in_progress' WHERE id = $1", [serviceId]);
|
||
const worker = workersQ.rows[Math.floor(Math.random() * workersQ.rows.length)];
|
||
const token = crypto.randomBytes(16).toString('hex');
|
||
|
||
await pool.query(`INSERT INTO assignment_pings (scraped_id, user_id, token, expires_at) VALUES ($1, $2, $3, CURRENT_TIMESTAMP + INTERVAL '5 minutes')`, [serviceId, worker.id, token]);
|
||
|
||
// ð§ Buscamos el nombre del gremio para el WhatsApp
|
||
let nombreGremio = "URGENCIA";
|
||
const gQ = await pool.query("SELECT name FROM guilds WHERE id = $1", [guildId]);
|
||
if(gQ.rowCount > 0) nombreGremio = gQ.rows[0].name.toUpperCase();
|
||
|
||
const msg = `ð¨ *NUEVO AVISO: ${nombreGremio}*\nð Código Postal: ${(cp && cp !== "00000") ? cp : "Zona Asignada"}\n\nTienes un aviso urgente pendiente. Entra aquà para ver la averÃa y aceptarlo antes de que caduque el turno:\nð https://web.integrarepara.es/aceptar.html?t=${token}`;
|
||
|
||
sendWhatsAppAuto(worker.phone, msg, `cliente_${accountId}`, false).catch(console.error);
|
||
|
||
await registrarMovimiento(serviceId, userId, "Bolsa Automática", `Notificación enviada a: ${worker.full_name}`);
|
||
console.log(`â
[AUTO-DISPATCH] Urgencia enviada con éxito a ${worker.full_name}`);
|
||
|
||
return { ok: true };
|
||
} catch (e) {
|
||
console.error("â Error en dispatchToBolsa:", e);
|
||
return { ok: false, error: "Error interno" };
|
||
}
|
||
}
|
||
|
||
// ==========================================
|
||
// ð¥ RECEPCIÃN DE SERVICIOS (EL MOTOR DEFINITIVO)
|
||
// ==========================================
|
||
app.post("/providers/scraped", authMiddleware, async (req, res) => {
|
||
try {
|
||
const { provider, services } = req.body;
|
||
if (!provider || !Array.isArray(services)) return res.status(400).json({ ok: false });
|
||
|
||
// 1. Cargamos el interruptor (siendo flexibles con 1 o true)
|
||
const credsQ = await pool.query(
|
||
"SELECT auto_dispatch FROM provider_credentials WHERE owner_id = $1 AND provider = $2",
|
||
[req.user.accountId, provider]
|
||
);
|
||
const autoDispatchEnabled = credsQ.rowCount > 0 &&
|
||
(credsQ.rows[0].auto_dispatch === true || credsQ.rows[0].auto_dispatch === 1 || credsQ.rows[0].auto_dispatch === '1');
|
||
|
||
// 2. Cargamos los gremios y sus palabras clave para detectar el gremio si falta
|
||
const allGuilds = await pool.query("SELECT id, name, ia_keywords FROM guilds WHERE owner_id = $1", [req.user.accountId]);
|
||
|
||
let count = 0;
|
||
for (const svc of services) {
|
||
const ref = svc['service_ref'] || svc['SERVICIO'] || svc['Referencia'] || svc['Expediente'] ||
|
||
(svc.raw_data && (svc.raw_data['SERVICIO'] || svc.raw_data['Referencia']));
|
||
|
||
if (!ref) continue;
|
||
|
||
// DETECCIÃN DE URGENCIA
|
||
let esUrgente = false;
|
||
const textoLimpio = JSON.stringify(svc).toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
|
||
if (textoLimpio.includes("urgencia") || textoLimpio.includes("urgente") || textoLimpio.includes("por atencion")) {
|
||
esUrgente = true;
|
||
}
|
||
|
||
// DETECCIÃN DE GREMIO (Si no viene, lo buscamos nosotros)
|
||
let guildId = svc.guild_id || svc['guild_id'] || (svc.raw_data && svc.raw_data.guild_id);
|
||
|
||
if (!guildId) {
|
||
for (const g of allGuilds.rows) {
|
||
const keywords = Array.isArray(g.ia_keywords) ? g.ia_keywords : [];
|
||
if (keywords.some(kw => textoLimpio.includes(kw.toLowerCase()))) {
|
||
guildId = g.id;
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
|
||
// ð¨ SOLUCIÃN DEFINITIVA PARA ARCHIVADOS:
|
||
let scraperStatus = (svc.status === 'archived') ? 'archived' : 'pending';
|
||
|
||
// ð NUEVO: ESCUDO DETECTOR DE NOVEDADES (100% Fiable)
|
||
const checkExist = await pool.query("SELECT id FROM scraped_services WHERE owner_id=$1 AND provider=$2 AND service_ref=$3", [req.user.accountId, provider, ref]);
|
||
const isNewRecord = (checkExist.rowCount === 0);
|
||
|
||
// GUARDAR EN BD
|
||
const insertRes = await pool.query(`
|
||
INSERT INTO scraped_services (owner_id, provider, service_ref, status, raw_data, is_urgent)
|
||
VALUES ($1, $2, $3, $4, $5, $6)
|
||
ON CONFLICT (owner_id, provider, service_ref)
|
||
DO UPDATE SET
|
||
status = CASE
|
||
WHEN EXCLUDED.status = 'archived' THEN 'archived'
|
||
ELSE scraped_services.status
|
||
END,
|
||
raw_data = scraped_services.raw_data || EXCLUDED.raw_data
|
||
RETURNING id, automation_status
|
||
`, [req.user.accountId, provider, ref, scraperStatus, JSON.stringify(svc), esUrgente]);
|
||
|
||
const newSvcId = insertRes.rows[0].id;
|
||
const autoStatus = insertRes.rows[0].automation_status;
|
||
|
||
// 𢠡CHIVATO DE CONSOLA!
|
||
console.log(`[DETECTOR-PRO] Ref: ${ref} | Urgente: ${esUrgente} | Gremio: ${guildId} | Es Nuevo: ${isNewRecord}`);
|
||
|
||
// ð 1. DISPARADOR DEL MENSAJE DE BIENVENIDA
|
||
if (isNewRecord) {
|
||
console.log(`ð [BIENVENIDA] Expediente #${ref} acaba de nacer. Disparando WhatsApp...`);
|
||
triggerWhatsAppEvent(req.user.accountId, newSvcId, 'wa_evt_welcome').catch(console.error);
|
||
}
|
||
|
||
// ð¥ 2. LANZAMIENTO AUTOMÃTICO A LA BOLSA ð¥
|
||
if (esUrgente && guildId && autoDispatchEnabled && (autoStatus === 'manual' || autoStatus === 'pending')) {
|
||
console.log(`â¡ [AUTO-DISPATCH] Lanzando a la bolsa: ${ref}`);
|
||
const cpMatch = textoLimpio.match(/\b\d{5}\b/);
|
||
dispatchToBolsa(newSvcId, guildId, cpMatch ? cpMatch[0] : "00000", req.user.accountId, req.user.sub).catch(console.error);
|
||
}
|
||
count++;
|
||
}
|
||
res.json({ ok: true, inserted: count });
|
||
} catch (error) {
|
||
console.error("â Error grave en recepción:", error);
|
||
res.status(500).json({ ok: false, error: error.message });
|
||
}
|
||
});
|
||
|
||
// ==========================================
|
||
// ð¤ OBTENER SERVICIOS PARA EL BUZÃN (Y BOLSA DE LA APP)
|
||
// ==========================================
|
||
app.get("/providers/scraped", authMiddleware, async (req, res) => {
|
||
try {
|
||
let query = `
|
||
SELECT s.*, ap.token as active_token,
|
||
EXTRACT(EPOCH FROM (ap.expires_at - CURRENT_TIMESTAMP)) as seconds_left,
|
||
u.full_name as current_worker_name,
|
||
(SELECT json_agg(json_build_object('name', u2.full_name, 'phone', u2.phone))
|
||
FROM assignment_pings ap2 JOIN users u2 ON ap2.user_id = u2.id
|
||
WHERE ap2.scraped_id = s.id AND ap2.status IN ('expired', 'rejected')) as attempted_workers_data
|
||
FROM scraped_services s
|
||
LEFT JOIN assignment_pings ap ON s.id = ap.scraped_id AND ap.status = 'pending'
|
||
LEFT JOIN users u ON ap.user_id = u.id
|
||
WHERE s.owner_id = $1
|
||
`;
|
||
const params = [req.user.accountId];
|
||
|
||
// ð¡ï¸ ESCUDO DE ZONA: Si es operario, aplicamos filtros de gremio y CP obligatorios
|
||
if (req.user.role === 'operario') {
|
||
query += ` AND s.assigned_to IS NULL AND s.status != 'archived'`;
|
||
|
||
// ð¨ FIX: Usamos NULLIF para evitar que un guild_id vacÃo ("") rompa el casting a número
|
||
query += ` AND (NULLIF(s.raw_data->>'guild_id', '') IS NULL OR NULLIF(s.raw_data->>'guild_id', '')::int IN (SELECT guild_id FROM user_guilds WHERE user_id = $2))`;
|
||
|
||
// 2. El CP de la averÃa tiene que coincidir SÃ o SÃ con los del operario
|
||
// Buscamos el CP en varios campos del JSON para asegurarnos de que no se escapa
|
||
query += ` AND EXISTS (
|
||
SELECT 1 FROM jsonb_array_elements((SELECT zones FROM users WHERE id = $2)) as z
|
||
WHERE z->>'cps' = COALESCE(s.raw_data->>'Código Postal', s.raw_data->>'C.P.', substring(s.raw_data::text from '\\y[0-9]{5}\\y'), '00000')
|
||
)`;
|
||
params.push(req.user.sub);
|
||
}
|
||
|
||
query += ` ORDER BY s.created_at DESC`;
|
||
|
||
const q = await pool.query(query, params);
|
||
const services = q.rows.map(row => {
|
||
if (row.seconds_left && row.seconds_left > 0) row.token_expires_at = new Date(Date.now() + (row.seconds_left * 1000));
|
||
return row;
|
||
});
|
||
res.json({ ok: true, services });
|
||
} catch (e) {
|
||
console.error("Error buzón/bolsa:", e.message);
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
// ==========================================
|
||
// ð¤ RUTA DE AUTOMATIZACIÃN (BOTÃN DEL RAYO)
|
||
// ==========================================
|
||
app.post("/providers/automate/:id", authMiddleware, async (req, res) => {
|
||
try {
|
||
const { guild_id, cp } = req.body;
|
||
const result = await dispatchToBolsa(req.params.id, guild_id, cp, req.user.accountId, req.user.sub);
|
||
if (result.ok) res.json({ ok: true });
|
||
else res.status(404).json(result);
|
||
} catch (e) { res.status(500).json({ ok: false }); }
|
||
});
|
||
|
||
// [EL RESTO DEL CÃDIGO PERMANECE IGUAL DESDE app.put('/providers/scraped/:id'...]
|
||
|
||
app.put('/providers/scraped/:id', authMiddleware, async (req, res) => {
|
||
const { id } = req.params;
|
||
// Extraemos todos los datos que vienen del frontend
|
||
let { automation_status, status, name, phone, address, cp, description, guild_id, assigned_to, assigned_to_name, internal_notes, client_notes, is_urgent, scheduled_date, scheduled_time, status_operativo, ...extra } = req.body;
|
||
|
||
try {
|
||
if (automation_status) {
|
||
await pool.query(`UPDATE scraped_services SET automation_status = $1 WHERE id = $2 AND owner_id = $3`, [automation_status, id, req.user.accountId]);
|
||
return res.json({ ok: true });
|
||
}
|
||
|
||
const current = await pool.query('SELECT raw_data, assigned_to, status, is_urgent FROM scraped_services WHERE id = $1 AND owner_id = $2', [id, req.user.accountId]);
|
||
if (current.rows.length === 0) return res.status(404).json({ error: 'No encontrado' });
|
||
|
||
let rawActual = current.rows[0].raw_data || {};
|
||
|
||
let oldStatus = String(rawActual.status_operativo || "");
|
||
let newStatus = String(status_operativo !== undefined ? status_operativo : oldStatus);
|
||
|
||
const oldDate = String(rawActual.scheduled_date || "");
|
||
const newDate = String(scheduled_date !== undefined ? scheduled_date : oldDate);
|
||
|
||
const oldTime = String(rawActual.scheduled_time || "");
|
||
const newTime = String(scheduled_time !== undefined ? scheduled_time : oldTime);
|
||
|
||
const statusChanged = (newStatus !== oldStatus && newStatus !== "" && newStatus !== "null");
|
||
const dateChanged = (newDate !== oldDate && newDate !== "" && newDate !== "null");
|
||
const timeChanged = (newTime !== oldTime && newTime !== "" && newTime !== "null");
|
||
|
||
const oldWorkerId = current.rows[0].assigned_to || rawActual.assigned_to;
|
||
let finalAssignedTo = assigned_to !== undefined ? (assigned_to === "" ? null : assigned_to) : oldWorkerId;
|
||
|
||
// ð¨ NUEVO: Detectar si le acabamos de asignar un técnico (de la nada a alguien, o de un técnico a otro distinto)
|
||
const workerNewlyAssigned = finalAssignedTo && (String(finalAssignedTo) !== String(oldWorkerId));
|
||
|
||
let stName = "";
|
||
if (newStatus && newStatus !== "null") {
|
||
const statusQ = await pool.query("SELECT name FROM service_statuses WHERE id=$1", [newStatus]);
|
||
stName = (statusQ.rows[0]?.name || "").toLowerCase();
|
||
}
|
||
|
||
// ð¨ EL EXORCISMO: Si pasa a Pendiente o Desasignado, forzamos la limpieza del operario
|
||
if (stName.includes('pendiente') || stName.includes('desasignado')) {
|
||
finalAssignedTo = null;
|
||
assigned_to_name = "";
|
||
}
|
||
|
||
console.log(`ð¤ [DEBUG ADMIN-PANEL] Exp: ${id} | Estado: '${stName}' | statusChanged: ${statusChanged} | dateChanged: ${dateChanged} | timeChanged: ${timeChanged}`);
|
||
|
||
// ð¨ AQUà ESTABA EL BUG: AHORA RE-INYECTAMOS TODOS LOS CAMPOS AL JSON ð¨
|
||
const updatedRawData = {
|
||
...rawActual, ...extra,
|
||
"Nombre Cliente": name !== undefined ? name : rawActual["Nombre Cliente"],
|
||
"Teléfono": phone !== undefined ? phone : rawActual["Teléfono"],
|
||
"Dirección": address !== undefined ? address : rawActual["Dirección"],
|
||
"Código Postal": cp !== undefined ? cp : (rawActual["Código Postal"] || rawActual["C.P."]),
|
||
"Descripción": description !== undefined ? description : rawActual["Descripción"],
|
||
"guild_id": guild_id !== undefined ? guild_id : rawActual.guild_id,
|
||
"internal_notes": internal_notes !== undefined ? internal_notes : rawActual.internal_notes,
|
||
"client_notes": client_notes !== undefined ? client_notes : rawActual.client_notes,
|
||
"assigned_to": finalAssignedTo, // ð§ EL REMATE AL ZOMBIE
|
||
"assigned_to_name": assigned_to_name !== undefined ? assigned_to_name : rawActual.assigned_to_name,
|
||
"scheduled_date": newDate,
|
||
"scheduled_time": newTime,
|
||
"status_operativo": newStatus === "null" ? null : newStatus
|
||
};
|
||
|
||
// Rescatamos si es urgente (es una columna fÃsica en tu base de datos)
|
||
const isUrgentFinal = is_urgent !== undefined ? is_urgent : current.rows[0].is_urgent;
|
||
|
||
// 𧹠AUTO-ARCHIVO: Si es finalizado o anulado, lo quitamos del buzón de proveedores
|
||
const isFinal = stName.includes('finalizado') || stName.includes('terminado') || stName.includes('anulado');
|
||
const mainStatus = isFinal ? 'archived' : 'imported';
|
||
|
||
await pool.query(
|
||
`UPDATE scraped_services SET raw_data = $1, assigned_to = $2, is_urgent = $3, status = $6 WHERE id = $4 AND owner_id = $5`,
|
||
[JSON.stringify(updatedRawData), finalAssignedTo, isUrgentFinal, id, req.user.accountId, mainStatus]
|
||
);
|
||
|
||
// BANDERAS INTELIGENTES
|
||
const isAsignado = stName.includes('asignado');
|
||
const isCitado = stName.includes('citado') || stName.includes('cita') || stName.includes('agendado');
|
||
const isNoLocalizado = stName.includes('no localizado') || stName.includes('buzon') || stName.includes('contesta');
|
||
|
||
// --- DISPARADORES WHATSAPP ---
|
||
if ((statusChanged && isAsignado && finalAssignedTo) || workerNewlyAssigned) {
|
||
triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_assigned').catch(console.error);
|
||
}
|
||
// ð Se dispara si cambia el estado a citado, si cambia el dÃa o si cambia la hora
|
||
if (isCitado && (statusChanged || dateChanged || timeChanged)) {
|
||
if (oldDate === "" || oldDate === "null") triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_date').catch(console.error);
|
||
else triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_update').catch(console.error);
|
||
}
|
||
|
||
// ð DISPARAR ROBOTS SEGÃN PROVEEDOR
|
||
const checkProvider = await pool.query("SELECT provider FROM scraped_services WHERE id=$1", [id]);
|
||
const providerName = checkProvider.rows[0]?.provider;
|
||
|
||
if (providerName === 'homeserve') {
|
||
if ((statusChanged && isAsignado && finalAssignedTo) || workerNewlyAssigned) {
|
||
console.log("â
[ADMIN] Disparando robot HS: ASIGNACIÃN");
|
||
triggerHomeServeRobot(req.user.accountId, id, 'assign').catch(console.error);
|
||
}
|
||
if (isCitado && (statusChanged || dateChanged || timeChanged) && newDate !== "" && newDate !== "null") {
|
||
console.log(`â
[ADMIN] Disparando robot HS: CITA (${newDate} ${newTime})`);
|
||
triggerHomeServeRobot(req.user.accountId, id, 'date').catch(console.error);
|
||
}
|
||
if (isNoLocalizado && statusChanged) {
|
||
console.log(`â
[ADMIN] Disparando robot HS: NO LOCALIZADO`);
|
||
triggerHomeServeRobot(req.user.accountId, id, 'notfound').catch(console.error);
|
||
}
|
||
}
|
||
else if (providerName === 'multiasistencia') {
|
||
if ((statusChanged && isAsignado && finalAssignedTo) || workerNewlyAssigned) {
|
||
console.log("â
[ADMIN] Disparando robot MULTI: ASIGNACIÃN");
|
||
triggerMultiRobot(req.user.accountId, id, 'assign').catch(console.error);
|
||
}
|
||
if (isCitado && (statusChanged || dateChanged || timeChanged) && newDate !== "" && newDate !== "null") {
|
||
console.log(`â
[ADMIN] Disparando robot MULTI: CITA (${newDate} ${newTime})`);
|
||
triggerMultiRobot(req.user.accountId, id, 'date').catch(console.error);
|
||
}
|
||
if (isNoLocalizado && statusChanged) {
|
||
console.log(`â
[ADMIN] Disparando robot MULTI: NO LOCALIZADO`);
|
||
triggerMultiRobot(req.user.accountId, id, 'notfound').catch(console.error);
|
||
}
|
||
}
|
||
|
||
res.json({ ok: true });
|
||
} catch (error) {
|
||
console.error("â ERROR EN ACTUALIZACIÃN:", error);
|
||
res.status(500).json({ ok: false, error: error.message });
|
||
}
|
||
});
|
||
|
||
// Validar si una referencia ya existe
|
||
app.get("/services/check-ref", authMiddleware, async (req, res) => {
|
||
try {
|
||
const { ref } = req.query;
|
||
const q = await pool.query("SELECT id FROM scraped_services WHERE service_ref = $1 AND owner_id = $2", [ref, req.user.accountId]);
|
||
res.json({ exists: q.rowCount > 0 });
|
||
} catch (e) { res.status(500).json({ ok: false }); }
|
||
});
|
||
|
||
app.get("/discovery/keys/:provider", authMiddleware, async (req, res) => {
|
||
try {
|
||
const { provider } = req.params;
|
||
const rawServices = await pool.query("SELECT raw_data FROM scraped_services WHERE owner_id=$1 AND provider=$2 ORDER BY id DESC LIMIT 1", [req.user.accountId, provider]);
|
||
const mappings = await pool.query("SELECT original_key, target_key, is_ignored FROM variable_mappings WHERE owner_id=$1 AND provider=$2", [req.user.accountId, provider]);
|
||
const mapDict = {}; mappings.rows.forEach(m => { mapDict[m.original_key] = m; });
|
||
const discoverySet = new Set(); const samples = {};
|
||
rawServices.rows.forEach(row => { const data = row.raw_data; if (data && typeof data === 'object') { Object.keys(data).forEach(k => { discoverySet.add(k); if (!samples[k]) samples[k] = data[k]; }); } });
|
||
const result = Array.from(discoverySet).map(key => ({ original: key, sample: samples[key] || "(VacÃo)", mappedTo: mapDict[key]?.target_key || "", ignored: mapDict[key]?.is_ignored || false })).sort((a, b) => a.original.localeCompare(b.original));
|
||
res.json({ ok: true, keys: result });
|
||
} catch (e) { res.status(500).json({ ok: false }); }
|
||
});
|
||
|
||
|
||
// RUTA PARA EL PANEL OPERATIVO (ADMIN VE TODO, OPERARIO VE LO SUYO)
|
||
app.get("/services/active", authMiddleware, async (req, res) => {
|
||
try {
|
||
let query = `
|
||
SELECT
|
||
s.*,
|
||
u.full_name as assigned_name
|
||
FROM scraped_services s
|
||
LEFT JOIN users u ON s.assigned_to = u.id
|
||
WHERE s.owner_id = $1
|
||
`;
|
||
// ð¨ MAGIA: Ya no ocultamos los archivados en la consulta general.
|
||
// AsÃ, tú como Admin, Sà los verás en la pantalla de Servicios (Kanban).
|
||
|
||
const params = [req.user.accountId];
|
||
|
||
// SI ES OPERARIO: Ve solo lo suyo.
|
||
// ð» FANTASMAS: Enviamos los archivados de los últimos 15 dÃas para que salgan translúcidos
|
||
if (req.user.role === 'operario' || req.user.role === 'operario_cerrado') {
|
||
query += ` AND s.assigned_to = $2 AND (s.status != 'archived' OR (s.status = 'archived' AND COALESCE((s.raw_data->>'archived_at')::timestamptz, s.created_at) >= NOW() - INTERVAL '15 days'))`;
|
||
params.push(req.user.sub);
|
||
}
|
||
|
||
query += ` ORDER BY s.created_at DESC`;
|
||
|
||
const q = await pool.query(query, params);
|
||
const servicesWithPhones = q.rows.map(s => ({ ...s, phones: extractAllPhones(s.raw_data) }));
|
||
res.json({ ok: true, services: servicesWithPhones });
|
||
} catch (e) {
|
||
console.error("Error al cargar /services/active:", e);
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
// ==========================================
|
||
// ð BUSCADOR GLOBAL (App): cualquier servicio de la empresa, cualquier estado, filtrando por fechas
|
||
// ==========================================
|
||
// A diferencia de /services/active (que para un operario solo enseña lo suyo, y solo lo archivado
|
||
// de los últimos 15 dÃas), este endpoint busca en TODO el histórico de la cuenta âcualquier técnico,
|
||
// cualquier estado (citado, anulado, finalizado...)â pero exige un filtro (fecha o texto) para no
|
||
// volcar la base de datos entera de golpe.
|
||
app.get("/services/search", authMiddleware, async (req, res) => {
|
||
try {
|
||
const ownerId = req.user.accountId;
|
||
const { q, date_field, date_from, date_to, company } = req.query;
|
||
const limit = Math.min(parseInt(req.query.limit) || 30, 100);
|
||
const offset = Math.max(parseInt(req.query.offset) || 0, 0);
|
||
|
||
const useCitaDate = date_field === 'scheduled_date';
|
||
const conditions = ["s.owner_id = $1", "s.provider != 'SYSTEM_BLOCK'"];
|
||
const params = [ownerId];
|
||
let idx = 2;
|
||
|
||
if (useCitaDate) {
|
||
if (date_from) { conditions.push(`(s.raw_data->>'scheduled_date') >= $${idx++}`); params.push(date_from); }
|
||
if (date_to) { conditions.push(`(s.raw_data->>'scheduled_date') <= $${idx++}`); params.push(date_to); }
|
||
} else {
|
||
if (date_from) { conditions.push(`s.created_at >= $${idx++}::date`); params.push(date_from); }
|
||
if (date_to) { conditions.push(`s.created_at < ($${idx++}::date + INTERVAL '1 day')`); params.push(date_to); }
|
||
}
|
||
|
||
if (company) {
|
||
conditions.push(`COALESCE(s.raw_data->>'CompañÃa', s.raw_data->>'COMPAÃIA', s.raw_data->>'Procedencia', '') ILIKE $${idx++}`);
|
||
params.push(company);
|
||
}
|
||
|
||
const hasDateRange = !!(date_from || date_to);
|
||
const term = (q || "").trim();
|
||
if (term !== "") {
|
||
conditions.push(`(
|
||
s.service_ref ILIKE $${idx} OR
|
||
COALESCE(s.raw_data->>'Nombre Cliente', s.raw_data->>'CLIENTE', '') ILIKE $${idx} OR
|
||
COALESCE(s.raw_data->>'Dirección', s.raw_data->>'DOMICILIO', '') ILIKE $${idx} OR
|
||
COALESCE(s.raw_data->>'Población', s.raw_data->>'POBLACION-PROVINCIA', '') ILIKE $${idx} OR
|
||
COALESCE(s.raw_data->>'Teléfono', s.raw_data->>'TELEFONO', s.raw_data->>'TELEFONOS', '') ILIKE $${idx} OR
|
||
COALESCE(s.raw_data->>'CompañÃa', s.raw_data->>'COMPAÃIA', '') ILIKE $${idx}
|
||
)`);
|
||
params.push(`%${term}%`);
|
||
idx++;
|
||
} else if (!hasDateRange) {
|
||
// Ni fecha ni texto: no devolvemos nada para no volcar el histórico entero.
|
||
return res.json({ ok: true, services: [], hasMore: false, needsFilter: true });
|
||
}
|
||
|
||
params.push(limit, offset);
|
||
const query = `
|
||
SELECT s.*, u.full_name as assigned_name
|
||
FROM scraped_services s
|
||
LEFT JOIN users u ON s.assigned_to = u.id
|
||
WHERE ${conditions.join(' AND ')}
|
||
ORDER BY s.created_at DESC
|
||
LIMIT $${idx++} OFFSET $${idx}
|
||
`;
|
||
|
||
const result = await pool.query(query, params);
|
||
const servicesWithPhones = result.rows.map(s => ({ ...s, phones: extractAllPhones(s.raw_data) }));
|
||
res.json({ ok: true, services: servicesWithPhones, hasMore: result.rows.length === limit });
|
||
} catch (e) {
|
||
console.error("Error en /services/search:", e);
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
app.put("/services/set-appointment/:id", authMiddleware, async (req, res) => {
|
||
try {
|
||
const { id } = req.params;
|
||
let { date, time, status_operativo, skip_survey, ...extra } = req.body;
|
||
|
||
const current = await pool.query('SELECT raw_data, assigned_to FROM scraped_services WHERE id = $1 AND owner_id = $2', [id, req.user.accountId]);
|
||
if (current.rowCount === 0) return res.status(404).json({ ok: false, error: 'No encontrado' });
|
||
|
||
const rawActual = current.rows[0].raw_data || {};
|
||
|
||
// FIX CRÃTICO: Si la app no envÃa estado, mantenemos el que tenÃa el expediente para no borrarlo
|
||
if (status_operativo === undefined || status_operativo === "") {
|
||
status_operativo = rawActual.status_operativo || null;
|
||
}
|
||
|
||
let newDate = (date !== undefined) ? date : (rawActual.scheduled_date || "");
|
||
let newTime = (time !== undefined) ? time : (rawActual.scheduled_time || "");
|
||
let finalAssignedTo = current.rows[0].assigned_to;
|
||
|
||
let stName = "";
|
||
if (status_operativo) {
|
||
const statusQ = await pool.query("SELECT name FROM service_statuses WHERE id=$1", [status_operativo]);
|
||
stName = (statusQ.rows[0]?.name || "").toLowerCase();
|
||
}
|
||
|
||
if (stName.includes('pendiente') || stName.includes('desasignado')) {
|
||
newDate = "";
|
||
newTime = "";
|
||
}
|
||
|
||
// GUARDAR EN BBDD
|
||
const updatedRawData = {
|
||
...rawActual, ...extra,
|
||
"scheduled_date": newDate,
|
||
"scheduled_time": newTime,
|
||
"status_operativo": status_operativo
|
||
};
|
||
|
||
// 𧹠AUTO-ARCHIVO DESDE LA APP: Si finaliza, lo quitamos del buzón de proveedores
|
||
const isFinalApp = stName.includes('finalizado') || stName.includes('terminado') || stName.includes('anulado');
|
||
if (isFinalApp) updatedRawData.archived_at = new Date().toISOString();
|
||
const mainStatusApp = isFinalApp ? 'archived' : 'imported';
|
||
|
||
await pool.query('UPDATE scraped_services SET raw_data = $1, assigned_to = $2, status = $5 WHERE id = $3 AND owner_id = $4',
|
||
[JSON.stringify(updatedRawData), finalAssignedTo, id, req.user.accountId, mainStatusApp]
|
||
);
|
||
|
||
let logDetalle = `Estado modificado a: ${stName.toUpperCase() || 'MODIFICADO'}.`;
|
||
if (newDate) logDetalle += ` Cita para el ${newDate} a las ${newTime}.`;
|
||
await registrarMovimiento(id, req.user.sub, "Actualización desde App", logDetalle);
|
||
|
||
res.json({ ok: true });
|
||
|
||
// TAREAS EN SEGUNDO PLANO
|
||
(async () => {
|
||
try {
|
||
const statusChanged = String(status_operativo) !== String(rawActual.status_operativo);
|
||
const oldDate = rawActual.scheduled_date || "";
|
||
const dateChanged = newDate !== "" && newDate !== oldDate;
|
||
|
||
console.log(`ð¤ [DEBUG APP-OP] Exp: ${id} | Estado: '${stName}' | statusChanged: ${statusChanged} | dateChanged: ${dateChanged}`);
|
||
|
||
// ð LEER PROVEEDOR REAL (HOME SERVE O MULTIASISTENCIA)
|
||
const checkProv = await pool.query("SELECT provider FROM scraped_services WHERE id=$1", [id]);
|
||
const providerName = checkProv.rows[0]?.provider;
|
||
|
||
// BANDERAS INTELIGENTES
|
||
const isAsignado = stName.includes('asignado');
|
||
const isCitado = stName.includes('citado') || stName.includes('cita') || stName.includes('agendado');
|
||
const isNoLocalizado = stName.includes('no localizado') || stName.includes('buzon') || stName.includes('contesta');
|
||
|
||
// --- ASIGNADO ---
|
||
if (statusChanged && isAsignado) {
|
||
|
||
// Disparar Robot Inteligente
|
||
if (providerName === 'homeserve') triggerHomeServeRobot(req.user.accountId, id, 'assign').catch(console.error);
|
||
else if (providerName === 'multiasistencia') triggerMultiRobot(req.user.accountId, id, 'assign').catch(console.error);
|
||
|
||
// Notificar por WhatsApp y cambiar a Esperando al Cliente si tiene éxito
|
||
const waEnviadoExito = await triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_assigned');
|
||
if (waEnviadoExito) {
|
||
const estadoEsperando = await pool.query("SELECT id FROM service_statuses WHERE owner_id=$1 AND name='Esperando al Cliente' LIMIT 1", [req.user.accountId]);
|
||
if (estadoEsperando.rowCount > 0) {
|
||
updatedRawData.status_operativo = estadoEsperando.rows[0].id;
|
||
await pool.query('UPDATE scraped_services SET raw_data = $1 WHERE id = $2 AND owner_id = $3', [JSON.stringify(updatedRawData), id, req.user.accountId]);
|
||
}
|
||
}
|
||
}
|
||
// --- CITADO (CONFIRMAR CITA) ---
|
||
else if (isCitado && (statusChanged || dateChanged)) {
|
||
|
||
if (newDate !== "") {
|
||
// Disparar Robot Inteligente
|
||
if (providerName === 'homeserve') {
|
||
console.log(`â
[APP-OP] Disparando robot HS: CITA (${newDate})`);
|
||
triggerHomeServeRobot(req.user.accountId, id, 'date').catch(console.error);
|
||
} else if (providerName === 'multiasistencia') {
|
||
console.log(`â
[APP-OP] Disparando robot MULTI: CITA (${newDate})`);
|
||
triggerMultiRobot(req.user.accountId, id, 'date').catch(console.error);
|
||
}
|
||
}
|
||
|
||
// Notificar por WhatsApp
|
||
if (oldDate === "") await triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_date');
|
||
else if (oldDate !== newDate) await triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_update');
|
||
}
|
||
// --- NO LOCALIZADO ---
|
||
else if (isNoLocalizado && statusChanged) {
|
||
if (providerName === 'homeserve') {
|
||
console.log(`â
[APP-OP] Disparando robot HS: NO LOCALIZADO`);
|
||
triggerHomeServeRobot(req.user.accountId, id, 'notfound').catch(console.error);
|
||
} else if (providerName === 'multiasistencia') {
|
||
console.log(`â
[APP-OP] Disparando robot MULTI: NO LOCALIZADO`);
|
||
triggerMultiRobot(req.user.accountId, id, 'notfound').catch(console.error);
|
||
}
|
||
}
|
||
// --- CAMINO / FINALIZADO ---
|
||
else if (stName.includes('camino')) {
|
||
await triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_onway');
|
||
} else if (stName.includes('finalizado') || stName.includes('terminado')) {
|
||
if (!skip_survey) await triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_survey');
|
||
}
|
||
} catch (errBckg) {
|
||
console.error("Error en tareas de fondo:", errBckg);
|
||
}
|
||
})();
|
||
|
||
} catch (e) {
|
||
console.error("â ERROR EXACTO AL CAMBIAR ESTADO/CITA:", e.stack);
|
||
if (!res.headersSent) res.status(500).json({ ok: false, error: e.message, stack: e.stack });
|
||
}
|
||
});
|
||
|
||
|
||
// ==========================================
|
||
// ð RUTA PARA CLIENTE NO LOCALIZADO
|
||
// ==========================================
|
||
app.post("/services/not-found/:id", authMiddleware, async (req, res) => {
|
||
try {
|
||
const { id } = req.params;
|
||
const current = await pool.query('SELECT raw_data, provider, owner_id FROM scraped_services WHERE id=$1 AND owner_id=$2', [id, req.user.accountId]);
|
||
|
||
if (current.rowCount === 0) return res.status(404).json({ok: false});
|
||
|
||
const raw = current.rows[0].raw_data || {};
|
||
|
||
// Sumamos 1 al contador de llamadas
|
||
const currentCalls = parseInt(raw.called_times || 0) + 1;
|
||
raw.called_times = currentCalls;
|
||
|
||
// Guardamos en la base de datos
|
||
await pool.query("UPDATE scraped_services SET raw_data=$1 WHERE id=$2", [JSON.stringify(raw), id]);
|
||
|
||
// Intentamos enviar el WhatsApp usando la plantilla (prioriza móvil sobre fijo)
|
||
let cleanPhoneToMatch = extractBestMobile(raw);
|
||
|
||
if (cleanPhoneToMatch.length >= 9) { // Solo intentamos enviar si hay un número válido
|
||
|
||
// ð¨ Búsqueda flexible por si la plantilla se guardó con otro nombre interno
|
||
const tplQ = await pool.query("SELECT content FROM message_templates WHERE owner_id=$1 AND type IN ('not_found', 'unreachable', 'no_reply') LIMIT 1", [req.user.accountId]);
|
||
let text = tplQ.rowCount > 0 && tplQ.rows[0].content
|
||
? tplQ.rows[0].content
|
||
: `Hola {{NOMBRE}}, soy el técnico de {{COMPANIA}}. He intentado contactar contigo para agendar tu reparación (Exp. {{REFERENCIA}}), pero no ha sido posible. Por favor, pulsa aquà para elegir tu cita: {{ENLACE}}`;
|
||
|
||
const finalPhoneToSend = "34" + cleanPhoneToMatch;
|
||
let token = "ERROR";
|
||
const clientQ = await pool.query("SELECT portal_token FROM clients WHERE phone LIKE $1 AND owner_id=$2 LIMIT 1", [`%${cleanPhoneToMatch}%`, req.user.accountId]);
|
||
|
||
if (clientQ.rowCount > 0) {
|
||
token = clientQ.rows[0].portal_token;
|
||
} else {
|
||
const newToken = crypto.randomBytes(6).toString('hex');
|
||
const insertC = await pool.query(
|
||
"INSERT INTO clients (owner_id, full_name, phone, addresses, portal_token) VALUES ($1, $2, $3, '[]', $4) RETURNING portal_token",
|
||
[req.user.accountId, raw["Nombre Cliente"] || "Cliente", finalPhoneToSend, newToken]
|
||
);
|
||
token = insertC.rows[0].portal_token;
|
||
}
|
||
|
||
const linkMagico = `https://portal.integrarepara.es/?token=${token}&service=${id}`;
|
||
|
||
let fechaLimpia = raw["scheduled_date"] || "la fecha acordada";
|
||
if (fechaLimpia.includes("-")) {
|
||
const partes = fechaLimpia.split("-");
|
||
if (partes.length === 3) {
|
||
const fechaObj = new Date(partes[0], partes[1] - 1, partes[2], 12, 0, 0);
|
||
const diaSemana = fechaObj.toLocaleDateString('es-ES', { weekday: 'long' });
|
||
fechaLimpia = `(${diaSemana}) ${partes[2]}/${partes[1]}/${partes[0]}`;
|
||
}
|
||
}
|
||
|
||
// REEMPLAZO DE TODAS LAS VARIABLES (Como en la foto)
|
||
text = text.replace(/{{NOMBRE}}/g, raw["Nombre Cliente"] || raw["CLIENTE"] || "Cliente");
|
||
text = text.replace(/{{DIRECCION}}/g, raw["Dirección"] || raw["DOMICILIO"] || "su domicilio");
|
||
text = text.replace(/{{FECHA}}/g, fechaLimpia);
|
||
text = text.replace(/{{HORA}}/g, raw["scheduled_time"] || "la hora acordada");
|
||
text = text.replace(/{{COMPANIA}}/g, raw["CompañÃa"] || raw["COMPAÃIA"] || "su Aseguradora");
|
||
text = text.replace(/{{REFERENCIA}}/g, current.rows[0].service_ref || id);
|
||
text = text.replace(/{{ENLACE}}/g, linkMagico);
|
||
|
||
const userQ = await pool.query("SELECT wa_settings FROM users WHERE id=$1", [req.user.accountId]);
|
||
const settings = userQ.rows[0]?.wa_settings || {};
|
||
const useDelay = settings.wa_delay_enabled !== false;
|
||
|
||
// MODO PRUEBAS: Redirigir el mensaje a tu móvil
|
||
const MODO_PRUEBAS = false;
|
||
const MI_TELEFONO = "34667248132";
|
||
|
||
if (MODO_PRUEBAS) {
|
||
console.log(`ð¡ï¸ [MODO PRUEBAS NO LOCALIZADO] DesvÃo a tu móvil (${MI_TELEFONO})`);
|
||
const textoPrueba = `*(SIMULACIÃN NO LOCALIZADO PARA: ${finalPhoneToSend})*\n\n` + text;
|
||
await sendWhatsAppAuto(MI_TELEFONO, textoPrueba, `cliente_${req.user.accountId}`, useDelay);
|
||
} else {
|
||
await sendWhatsAppAuto(finalPhoneToSend, text, `cliente_${req.user.accountId}`, useDelay);
|
||
}
|
||
}
|
||
|
||
// --- INICIO TRAZABILIDAD ---
|
||
await registrarMovimiento(id, req.user.sub, "Intento de Contacto", `El operario reporta que el cliente no contesta. Total intentos: ${currentCalls}`);
|
||
|
||
// ð DISPARAR ROBOTS SEGÃN PROVEEDOR
|
||
const providerName = current.rows[0].provider;
|
||
if (providerName === 'homeserve') {
|
||
console.log(`â
[NO-LOCALIZADO] Disparando robot HS`);
|
||
triggerHomeServeRobot(req.user.accountId, id, 'notfound').catch(console.error);
|
||
} else if (providerName === 'multiasistencia') {
|
||
console.log(`â
[NO-LOCALIZADO] Disparando robot MULTI`);
|
||
triggerMultiRobot(req.user.accountId, id, 'notfound').catch(console.error);
|
||
}
|
||
// --- FIN TRAZABILIDAD ---
|
||
|
||
res.json({ ok: true, called_times: currentCalls });
|
||
} catch (e) {
|
||
console.error("Error No Localizado:", e);
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
// ==========================================
|
||
// ð RUTAS DE PLANTILLAS DE MENSAJES
|
||
// ==========================================
|
||
app.get("/templates", authMiddleware, async (req, res) => {
|
||
try {
|
||
const q = await pool.query("SELECT type, content FROM message_templates WHERE owner_id=$1", [req.user.accountId]);
|
||
res.json({ ok: true, templates: q.rows });
|
||
} catch (e) {
|
||
res.status(500).json({ ok: false, error: e.message });
|
||
}
|
||
});
|
||
|
||
app.post("/templates", authMiddleware, async (req, res) => {
|
||
try {
|
||
const { type, content } = req.body;
|
||
if (!type) return res.status(400).json({ ok: false, error: "Falta el tipo de plantilla" });
|
||
|
||
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("Error guardando plantilla:", e);
|
||
res.status(500).json({ ok: false, error: e.message });
|
||
}
|
||
});
|
||
|
||
// ==========================================
|
||
// ð RUTAS DE AUTOMATIZACIONES (RECORDATORIOS)
|
||
// ==========================================
|
||
const AUTOMATION_TYPES = ['sin_citar', 'espera_cliente', 'dia_antes'];
|
||
|
||
app.get("/automations/settings", authMiddleware, async (req, res) => {
|
||
try {
|
||
for (const tipo of AUTOMATION_TYPES) {
|
||
await pool.query(
|
||
"INSERT INTO automation_settings (owner_id, automation_type) VALUES ($1,$2) ON CONFLICT (owner_id, automation_type) DO NOTHING",
|
||
[req.user.accountId, tipo]
|
||
);
|
||
}
|
||
const q = await pool.query("SELECT * FROM automation_settings WHERE owner_id=$1", [req.user.accountId]);
|
||
res.json({ ok: true, settings: q.rows });
|
||
} catch (e) {
|
||
console.error("Error obteniendo settings de automatizaciones:", e);
|
||
res.status(500).json({ ok: false, error: e.message });
|
||
}
|
||
});
|
||
|
||
app.post("/automations/settings", authMiddleware, async (req, res) => {
|
||
try {
|
||
const { automation_type, enabled, test_mode, dias_espera_inicial, dias_repeticion, hora_envio } = req.body;
|
||
if (!AUTOMATION_TYPES.includes(automation_type)) {
|
||
return res.status(400).json({ ok: false, error: "Tipo de automatización no válido" });
|
||
}
|
||
await pool.query(`
|
||
INSERT INTO automation_settings (owner_id, automation_type, enabled, test_mode, dias_espera_inicial, dias_repeticion, hora_envio)
|
||
VALUES ($1,$2,$3,$4,$5,$6,$7)
|
||
ON CONFLICT (owner_id, automation_type) DO UPDATE SET
|
||
enabled = EXCLUDED.enabled,
|
||
test_mode = EXCLUDED.test_mode,
|
||
dias_espera_inicial = EXCLUDED.dias_espera_inicial,
|
||
dias_repeticion = EXCLUDED.dias_repeticion,
|
||
hora_envio = EXCLUDED.hora_envio
|
||
`, [
|
||
req.user.accountId,
|
||
automation_type,
|
||
!!enabled,
|
||
test_mode !== false,
|
||
parseInt(dias_espera_inicial) || 1,
|
||
parseInt(dias_repeticion) || 3,
|
||
hora_envio || '09:00'
|
||
]);
|
||
res.json({ ok: true });
|
||
} catch (e) {
|
||
console.error("Error guardando settings de automatizaciones:", e);
|
||
res.status(500).json({ ok: false, error: e.message });
|
||
}
|
||
});
|
||
|
||
app.get("/automations/history", authMiddleware, async (req, res) => {
|
||
try {
|
||
const q = await pool.query(`
|
||
SELECT at.service_id, s.service_ref, s.raw_data, at.automation_type, at.first_seen_at,
|
||
(SELECT COUNT(*) FROM automation_log al WHERE al.service_id = at.service_id AND al.automation_type = at.automation_type) as veces_enviado
|
||
FROM automation_tracking at
|
||
JOIN scraped_services s ON s.id = at.service_id
|
||
WHERE at.owner_id = $1
|
||
ORDER BY at.first_seen_at ASC
|
||
`, [req.user.accountId]);
|
||
res.json({ ok: true, history: q.rows });
|
||
} catch (e) {
|
||
console.error("Error obteniendo historial de automatizaciones:", e);
|
||
res.status(500).json({ ok: false, error: e.message });
|
||
}
|
||
});
|
||
|
||
// ==========================================
|
||
// ð¨ RUTAS DE ESTADOS DEL SISTEMA (SAAS COMPLETO)
|
||
// ==========================================
|
||
app.get("/statuses", authMiddleware, async (req, res) => {
|
||
try {
|
||
// 1. FORZAMOS LA INYECCIÃN/ACTUALIZACIÃN SIEMPRE
|
||
const defaults = [
|
||
{name:'Pendiente de Asignar', c:'gray', d:true, f:false, sys:true},
|
||
{name:'Asignado', c:'blue', d:false, f:false, sys:true},
|
||
{name:'Esperando al Cliente', c:'amber', d:false, f:false, sys:true},
|
||
{name:'Citado', c:'emerald', d:false, f:false, sys:true},
|
||
{name:'En espera de CompañÃa / Perito', c:'blue', d:false, f:false, sys:true}, // <--- NUEVO
|
||
{name:'De Camino', c:'indigo', d:false, f:false, sys:true},
|
||
{name:'Trabajando', c:'orange', d:false, f:false, sys:true},
|
||
{name:'Incidencia', c:'red', d:false, f:false, sys:true},
|
||
{name:'Desasignado', c:'rose', d:false, f:false, sys:true},
|
||
{name:'Finalizado', c:'purple', d:false, f:true, sys:true},
|
||
{name:'Anulado', c:'gray', d:false, f:true, sys:true}
|
||
];
|
||
|
||
for (const s of defaults) {
|
||
const check = await pool.query("SELECT id FROM service_statuses WHERE owner_id=$1 AND name=$2", [req.user.accountId, s.name]);
|
||
if(check.rowCount === 0){
|
||
await pool.query("INSERT INTO service_statuses (owner_id,name,color,is_default,is_final,is_system) VALUES ($1,$2,$3,$4,$5,$6)", [req.user.accountId,s.name,s.c,s.d,s.f,s.sys]);
|
||
} else {
|
||
await pool.query("UPDATE service_statuses SET is_system=true, color=$2, is_final=$3 WHERE id=$1", [check.rows[0].id, s.c, s.f]);
|
||
}
|
||
}
|
||
|
||
// ð§¹ Limpiamos el candado a los viejos (Asegura que esta parte se mantiene igual)
|
||
const nombresOficiales = defaults.map(d => d.name);
|
||
await pool.query("UPDATE service_statuses SET is_system=false WHERE owner_id=$1 AND name != ALL($2::text[])", [req.user.accountId, nombresOficiales]);
|
||
|
||
// ð FUSIÃN AUTOMÃTICA: Movemos todo lo viejo al nuevo y borramos el fantasma
|
||
let currentDb = await pool.query("SELECT * FROM service_statuses WHERE owner_id=$1", [req.user.accountId]);
|
||
const idEsperando = currentDb.rows.find(s => s.name === 'Esperando al Cliente')?.id;
|
||
const idPendiente = currentDb.rows.find(s => s.name === 'Pendiente de Cita')?.id;
|
||
|
||
if (idEsperando && idPendiente) {
|
||
// Pasamos los servicios normales
|
||
await pool.query("UPDATE services SET status_id = $1 WHERE status_id = $2 AND owner_id = $3", [idEsperando, idPendiente, req.user.accountId]);
|
||
// Pasamos los servicios del panel operativo (JSON)
|
||
await pool.query(`UPDATE scraped_services SET raw_data = jsonb_set(COALESCE(raw_data, '{}'::jsonb), '{status_operativo}', to_jsonb($1::text)) WHERE raw_data->>'status_operativo' = $2 AND owner_id = $3`, [String(idEsperando), String(idPendiente), req.user.accountId]);
|
||
// Exterminamos "Pendiente de Cita"
|
||
await pool.query("DELETE FROM service_statuses WHERE id = $1 AND owner_id = $2", [idPendiente, req.user.accountId]);
|
||
}
|
||
|
||
// 2. RECUPERAMOS LOS ESTADOS LIMPIOS
|
||
let q = await pool.query("SELECT * FROM service_statuses WHERE owner_id=$1", [req.user.accountId]);
|
||
|
||
// ORDENAMOS
|
||
let sortedStatuses = q.rows.sort((a, b) => {
|
||
let idxA = nombresOficiales.indexOf(a.name);
|
||
let idxB = nombresOficiales.indexOf(b.name);
|
||
if(idxA === -1) idxA = 99;
|
||
if(idxB === -1) idxB = 99;
|
||
return idxA - idxB;
|
||
});
|
||
|
||
res.json({ ok: true, statuses: sortedStatuses });
|
||
} catch (e) { res.status(500).json({ ok: false }); }
|
||
});
|
||
|
||
// 𩹠FIX: antes SOLO buscaba en la tabla "clients" y exigÃa coincidencia EXACTA con el
|
||
// formato de teléfono "+34XXXXXXXXX". Muchos clientes reales nunca llegan a crearse en esa
|
||
// tabla (solo tienen presupuestos o servicios previos), o quedan guardados con otro formato
|
||
// de teléfono (p.ej. sin el "+"), asà que la búsqueda fallaba aunque el cliente "ya existiera".
|
||
// Ahora comparamos solo los dÃgitos del teléfono (sea cual sea el formato guardado) y, si no
|
||
// se encuentra en "clients", buscamos también en sus presupuestos y servicios anteriores,
|
||
// sea cual sea su estado.
|
||
app.get("/clients/search", authMiddleware, async (req, res) => {
|
||
try {
|
||
const { phone } = req.query;
|
||
const bare = extractValidPhone(phone);
|
||
if (!bare) return res.json({ ok: true, client: null });
|
||
const ownerId = req.user.accountId;
|
||
|
||
const q = await pool.query(
|
||
`SELECT * FROM clients WHERE owner_id=$1 AND regexp_replace(phone, '\\D', '', 'g') LIKE '%' || $2 || '%' ORDER BY id DESC LIMIT 1`,
|
||
[ownerId, bare]
|
||
);
|
||
if (q.rowCount > 0) return res.json({ ok: true, client: q.rows[0] });
|
||
|
||
const bq = await pool.query(
|
||
`SELECT client_name, client_phone, client_address FROM budgets
|
||
WHERE owner_id=$1 AND regexp_replace(COALESCE(client_phone,''), '\\D', '', 'g') LIKE '%' || $2 || '%'
|
||
ORDER BY created_at DESC LIMIT 1`,
|
||
[ownerId, bare]
|
||
);
|
||
if (bq.rowCount > 0) {
|
||
const b = bq.rows[0];
|
||
return res.json({ ok: true, client: { full_name: b.client_name, phone: b.client_phone, addresses: [b.client_address].filter(Boolean) } });
|
||
}
|
||
|
||
const sq = await pool.query(
|
||
`SELECT raw_data FROM scraped_services
|
||
WHERE owner_id=$1 AND regexp_replace(COALESCE(raw_data->>'Teléfono', raw_data->>'TELEFONO', raw_data->>'TELEFONOS', ''), '\\D', '', 'g') LIKE '%' || $2 || '%'
|
||
ORDER BY created_at DESC LIMIT 1`,
|
||
[ownerId, bare]
|
||
);
|
||
if (sq.rowCount > 0) {
|
||
const raw = sq.rows[0].raw_data || {};
|
||
const name = raw['Nombre Cliente'] || raw['NOMBRE'] || raw['Nombre'] || '';
|
||
const addr = raw['Dirección'] || raw['DIRECCION'] || raw['Direccion'] || '';
|
||
return res.json({ ok: true, client: { full_name: name, phone, addresses: [addr].filter(Boolean) } });
|
||
}
|
||
|
||
res.json({ ok: true, client: null });
|
||
} catch (e) { res.status(500).json({ ok: false }); }
|
||
});
|
||
|
||
// --- ENDPOINT PARA GENERAR ENLACE AL PORTAL DEL CLIENTE DESDE LA APP ---
|
||
app.post('/clients/ensure', authMiddleware, async (req, res) => {
|
||
try {
|
||
const { phone, name, address } = req.body;
|
||
if (!phone) return res.status(400).json({ ok: false, error: "Teléfono obligatorio" });
|
||
|
||
const cleanPhone = phone.replace('+34', '').replace(/\s+/g, '').trim();
|
||
const ownerId = req.user.accountId;
|
||
|
||
const q = await pool.query("SELECT * FROM clients WHERE phone LIKE $1 AND owner_id = $2 LIMIT 1", [`%${cleanPhone}%`, ownerId]);
|
||
|
||
if (q.rowCount > 0) {
|
||
let client = q.rows[0];
|
||
// PARCHE: Si el cliente existe pero no tiene token (porque es antiguo), se lo creamos
|
||
if (!client.portal_token) {
|
||
client.portal_token = crypto.randomBytes(6).toString('hex');
|
||
await pool.query("UPDATE clients SET portal_token = $1 WHERE id = $2", [client.portal_token, client.id]);
|
||
}
|
||
res.json({ ok: true, client });
|
||
} else {
|
||
const newToken = crypto.randomBytes(6).toString('hex');
|
||
const insert = await pool.query(
|
||
"INSERT INTO clients (owner_id, full_name, phone, addresses, portal_token) VALUES ($1, $2, $3, $4, $5) RETURNING *",
|
||
[ownerId, name || "Cliente", phone, JSON.stringify([address || ""]), newToken]
|
||
);
|
||
// ð Devolvemos la fila completa (antes solo el portal_token), porque ahora la
|
||
// Ficha del Cliente de la App necesita el id del cliente recién creado.
|
||
res.json({ ok: true, client: insert.rows[0] });
|
||
}
|
||
} catch (e) {
|
||
res.status(500).json({ ok: false, error: "Error interno del servidor" });
|
||
}
|
||
});
|
||
|
||
|
||
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 }); } });
|
||
|
||
// AÃADIDO: Filtro estricto para que solo devuelva operarios que estén en estado 'active'
|
||
app.get("/operators", authMiddleware, async (req, res) => {
|
||
try {
|
||
const guildId = req.query.guild_id;
|
||
let query = `SELECT u.id, u.full_name, u.zones FROM users u WHERE u.owner_id=$1 AND u.role='operario' AND u.status='active'`;
|
||
const params = [req.user.accountId];
|
||
if (guildId) { query = `SELECT u.id, u.full_name, u.zones FROM users u JOIN user_guilds ug ON u.id = ug.user_id WHERE u.owner_id=$1 AND u.role='operario' AND u.status='active' AND ug.guild_id=$2`; params.push(guildId); }
|
||
query += ` 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 }); }
|
||
});
|
||
|
||
app.get("/zones", authMiddleware, async (req, res) => { try { const q = await pool.query("SELECT * FROM zones WHERE owner_id=$1 ORDER BY name ASC", [req.user.accountId]); res.json({ ok: true, zones: q.rows }); } catch (e) { res.status(500).json({ ok: false }); } });
|
||
app.post("/zones", authMiddleware, async (req, res) => { try { const { name } = req.body; await pool.query("INSERT INTO zones (name, owner_id) VALUES ($1, $2)", [name, req.user.accountId]); res.json({ ok: true }); } catch (e) { res.status(500).json({ ok: false }); } });
|
||
app.delete("/zones/:id", authMiddleware, async (req, res) => { try { await pool.query("DELETE FROM zones WHERE id=$1 AND owner_id=$2", [req.params.id, req.user.accountId]); res.json({ ok: true }); } catch (e) { res.status(500).json({ ok: false }); } });
|
||
app.get("/zones/:id/operators", authMiddleware, async (req, res) => { try { const q = await pool.query("SELECT user_id FROM user_zones WHERE zone_id=$1", [req.params.id]); res.json({ ok: true, assignedIds: q.rows.map(r=>r.user_id) }); } catch (e) { res.status(500).json({ ok: false }); } });
|
||
app.post("/zones/:id/assign", authMiddleware, async (req, res) => { const client = await pool.connect(); try { const { operator_ids } = req.body; await client.query('BEGIN'); await client.query("DELETE FROM user_zones WHERE zone_id=$1", [req.params.id]); if(operator_ids) for(const uid of operator_ids) await client.query("INSERT INTO user_zones (user_id, zone_id) VALUES ($1, $2)", [uid, req.params.id]); await client.query('COMMIT'); res.json({ok:true}); } catch(e){ await client.query('ROLLBACK'); res.status(500).json({ok:false}); } finally { client.release(); } });
|
||
|
||
app.get("/api/geo/municipios/:provincia", authMiddleware, async (req, res) => { try { let { provincia } = req.params; const provClean = provincia.toUpperCase().normalize("NFD").replace(/[\u0300-\u036f]/g, ""); const q = await pool.query("SELECT municipio, codigo_postal FROM master_geo_es WHERE provincia = $1 ORDER BY municipio ASC", [provClean]); res.json({ ok: true, municipios: q.rows }); } catch (e) { res.status(500).json({ ok: false }); } });
|
||
app.patch("/admin/users/:id/status", authMiddleware, async (req, res) => { try { const { status } = req.body; await pool.query("UPDATE users SET status = $1 WHERE id = $2 AND owner_id = $3", [status, req.params.id, req.user.accountId]); res.json({ ok: true }); } catch (e) { res.status(500).json({ ok: false }); } });
|
||
app.get("/admin/users", authMiddleware, async (req, res) => { try { const q = await pool.query(`SELECT u.id, u.full_name, u.email, u.phone, u.role, u.zones, u.status, COALESCE(json_agg(g.id) FILTER (WHERE g.id IS NOT NULL), '[]') as guilds FROM users u LEFT JOIN user_guilds ug ON u.id=ug.user_id LEFT JOIN guilds g ON ug.guild_id=g.id WHERE u.owner_id=$1 GROUP BY u.id ORDER BY u.id DESC`, [req.user.accountId]); res.json({ ok: true, users: q.rows }); } catch (e) { res.status(500).json({ ok: false }); } });
|
||
app.post("/admin/users", authMiddleware, async (req, res) => { const client = await pool.connect(); try { const { fullName, email, password, role, guilds, phone, zones } = req.body; if (!email || !password || !fullName || !phone) return res.status(400).json({ ok: false }); const p = normalizePhone(phone); const hash = await bcrypt.hash(password, 10); const check = await client.query("SELECT id FROM users WHERE (phone=$1 OR email=$2) AND owner_id=$3", [p, email, req.user.accountId]); if (check.rowCount > 0) return res.status(400).json({ ok: false, error: "Duplicado" }); await client.query('BEGIN'); const insert = await client.query("INSERT INTO users (full_name, email, password_hash, role, phone, is_verified, owner_id, zones, status) VALUES ($1, $2, $3, $4, $5, TRUE, $6, $7, 'active') RETURNING id", [fullName, email, hash, role || 'operario', p, req.user.accountId, JSON.stringify(zones || [])]); const uid = insert.rows[0].id; if (guilds) for (const gid of guilds) await client.query("INSERT INTO user_guilds (user_id, guild_id) VALUES ($1, $2)", [uid, gid]); await client.query('COMMIT'); res.json({ ok: true }); } catch (e) { await client.query('ROLLBACK'); res.status(500).json({ ok: false }); } finally { client.release(); } });
|
||
app.put("/admin/users/:id", authMiddleware, async (req, res) => { const client = await pool.connect(); try { const userId = req.params.id; const { fullName, email, phone, role, guilds, password, zones } = req.body; const p = normalizePhone(phone); await client.query('BEGIN'); if(password) { const hash = await bcrypt.hash(password, 10); await client.query("UPDATE users SET full_name=$1, email=$2, phone=$3, role=$4, password_hash=$5, zones=$6 WHERE id=$7", [fullName, email, p, role, hash, JSON.stringify(zones || []), userId]); } else { await client.query("UPDATE users SET full_name=$1, email=$2, phone=$3, role=$4, zones=$5 WHERE id=$6", [fullName, email, p, role, JSON.stringify(zones || []), userId]); } if (guilds && Array.isArray(guilds)) { await client.query("DELETE FROM user_guilds WHERE user_id=$1", [userId]); for (const gid of guilds) await client.query("INSERT INTO user_guilds (user_id, guild_id) VALUES ($1, $2)", [userId, gid]); } await client.query('COMMIT'); res.json({ ok: true }); } catch (e) { await client.query('ROLLBACK'); res.status(500).json({ ok: false }); } finally { client.release(); } });
|
||
app.delete("/admin/users/:id", authMiddleware, async (req, res) => { try { await pool.query("DELETE FROM users WHERE id=$1 AND owner_id=$2", [req.params.id, req.user.accountId]); res.json({ ok: true }); } catch (e) { res.status(500).json({ ok: false }); } });
|
||
|
||
// ==========================================
|
||
// ð¢ CONFIGURACIÃN EMPRESA (COLORES, LOGO, PUBLICIDAD, PORTAL)
|
||
// ==========================================
|
||
|
||
app.post("/config/company", authMiddleware, async (req, res) => {
|
||
const client = await pool.connect();
|
||
try {
|
||
// AÃADIDO: Recogemos company_ad del frontend
|
||
const { slug, company_name, company_logo, company_ad, portal_settings, app_settings, billing_settings } = req.body;
|
||
|
||
// 1. Manejo del Slug (Enlace)
|
||
let cleanSlug = null;
|
||
if (slug) {
|
||
cleanSlug = slug.toLowerCase().replace(/[^a-z0-9-]/g, "");
|
||
const check = await client.query("SELECT id FROM users WHERE company_slug=$1 AND id != $2", [cleanSlug, req.user.accountId]);
|
||
if (check.rowCount > 0) return res.status(400).json({ ok: false, error: "Enlace en uso" });
|
||
}
|
||
|
||
// 2. Asegurar que existe la columna de facturación y publicidad en la tabla users
|
||
await client.query(`ALTER TABLE users ADD COLUMN IF NOT EXISTS billing_settings JSONB DEFAULT '{}'`);
|
||
await client.query(`ALTER TABLE users ADD COLUMN IF NOT EXISTS company_ad TEXT`);
|
||
|
||
// 3. UPDATE Inteligente: Añadido company_ad a la base de datos
|
||
await client.query(`
|
||
UPDATE users
|
||
SET company_slug = COALESCE($1, company_slug),
|
||
full_name = COALESCE($2, full_name),
|
||
company_logo = COALESCE($3, company_logo),
|
||
company_ad = COALESCE($4, company_ad),
|
||
portal_settings = COALESCE(portal_settings, '{}'::jsonb) || COALESCE($5, '{}'::jsonb),
|
||
app_settings = COALESCE(app_settings, '{}'::jsonb) || COALESCE($6, '{}'::jsonb),
|
||
billing_settings = COALESCE(billing_settings, '{}'::jsonb) || COALESCE($7, '{}'::jsonb)
|
||
WHERE id = $8
|
||
`, [
|
||
cleanSlug,
|
||
company_name ?? null,
|
||
company_logo ?? null,
|
||
company_ad ?? null,
|
||
portal_settings ? JSON.stringify(portal_settings) : null,
|
||
app_settings ? JSON.stringify(app_settings) : null,
|
||
billing_settings ? JSON.stringify(billing_settings) : null,
|
||
req.user.accountId
|
||
]);
|
||
|
||
res.json({ ok: true });
|
||
} catch (e) {
|
||
console.error("â Error guardando config:", e);
|
||
res.status(500).json({ ok: false });
|
||
} finally { client.release(); }
|
||
});
|
||
|
||
app.get("/config/company", authMiddleware, async (req, res) => {
|
||
try {
|
||
// 4. Modificamos el GET para que devuelva la columna company_ad
|
||
const q = await pool.query("SELECT company_slug, full_name, plan_tier, company_logo, company_ad, portal_settings, app_settings, billing_settings FROM users WHERE id=$1", [req.user.accountId]);
|
||
res.json({ ok: true, config: q.rows[0] || {} });
|
||
} catch (e) {
|
||
try {
|
||
const fallback = await pool.query("SELECT company_slug, full_name, plan_tier, company_logo, portal_settings, app_settings FROM users WHERE id=$1", [req.user.accountId]);
|
||
res.json({ ok: true, config: fallback.rows[0] || {} });
|
||
} catch(fallbackError) {
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
}
|
||
});
|
||
|
||
// RUTA: Logo de la empresa en formato ligero (solo el campo logo), pensada para
|
||
// que la App técnica pueda pintar dinámicamente su icono/favicon sin exponer
|
||
// el resto de la configuración de la empresa (facturación, ajustes, etc.)
|
||
app.get("/branding", authMiddleware, async (req, res) => {
|
||
try {
|
||
const q = await pool.query("SELECT company_logo, full_name FROM users WHERE id=$1", [req.user.accountId]);
|
||
const row = q.rows[0] || {};
|
||
res.json({ ok: true, logo: row.company_logo || null, full_name: row.full_name || null });
|
||
} catch (e) {
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
// RUTA: Alta de expediente manual con validación de cliente
|
||
app.post("/services/manual-high", authMiddleware, async (req, res) => {
|
||
try {
|
||
const { phone, name, address, description, guild_id, assigned_to, duration_minutes, mode, is_company, company_name, company_ref } = req.body;
|
||
const ownerId = req.user.accountId;
|
||
|
||
// 1. Manejo del Cliente (Buscamos si existe por teléfono)
|
||
const cleanPhone = phone.replace(/\D/g, "");
|
||
let clientQ = await pool.query("SELECT id, addresses FROM clients WHERE phone LIKE $1 AND owner_id = $2", [`%${cleanPhone}%`, ownerId]);
|
||
|
||
let clientId;
|
||
if (clientQ.rowCount > 0) {
|
||
clientId = clientQ.rows[0].id;
|
||
let currentAddrs = clientQ.rows[0].addresses || [];
|
||
// Si la dirección es nueva, la añadimos a su ficha
|
||
if (!currentAddrs.includes(address)) {
|
||
currentAddrs.push(address);
|
||
await pool.query("UPDATE clients SET addresses = $1 WHERE id = $2", [JSON.stringify(currentAddrs), clientId]);
|
||
}
|
||
} else {
|
||
// Si no existe, creamos cliente nuevo
|
||
const token = crypto.randomBytes(6).toString('hex');
|
||
const newClient = await pool.query(
|
||
"INSERT INTO clients (owner_id, full_name, phone, addresses, portal_token) VALUES ($1, $2, $3, $4, $5) RETURNING id",
|
||
[ownerId, name, phone, JSON.stringify([address]), token]
|
||
);
|
||
clientId = newClient.rows[0].id;
|
||
}
|
||
|
||
// 2. Crear el Expediente
|
||
// 𩹠FIX: extraemos el Código Postal de la dirección en texto libre. Antes este campo
|
||
// nunca se guardaba en las altas manuales, asà que la asignación automática (que exige
|
||
// que el CP coincida exactamente con una zona del operario) siempre fallaba al usar "00000".
|
||
const cpMatchAlta = (address || "").match(/\b\d{5}\b/);
|
||
const cpDetectado = cpMatchAlta ? cpMatchAlta[0] : "00000";
|
||
|
||
// 𩹠FIX: si al crear el servicio ya se elige un operario a mano, habÃa que guardar
|
||
// también el status_operativo como "Asignado". Si se dejaba vacÃo (como pasaba antes),
|
||
// la ficha de detalle caÃa en systemStatuses[0] ("Pendiente de Asignar") al no encontrar
|
||
// el estado, y como ese nombre contiene la palabra "asignar" el panel de detalle mostraba
|
||
// "Sin Asignar" aunque el operario SÃ estuviera guardado correctamente en la base de datos.
|
||
let statusOperativoAlta = null;
|
||
if (assigned_to) {
|
||
const statusAsignadoQ = await pool.query("SELECT id FROM service_statuses WHERE owner_id=$1 AND name = 'Asignado' LIMIT 1", [ownerId]);
|
||
if (statusAsignadoQ.rowCount > 0) statusOperativoAlta = String(statusAsignadoQ.rows[0].id);
|
||
}
|
||
|
||
const rawData = {
|
||
"Nombre Cliente": name,
|
||
"Teléfono": phone,
|
||
"Dirección": address,
|
||
"Código Postal": cpDetectado,
|
||
"Descripción": description,
|
||
"guild_id": guild_id,
|
||
"scheduled_date": "",
|
||
"scheduled_time": "",
|
||
"duration_minutes": duration_minutes || 60,
|
||
"CompañÃa": is_company ? company_name : "Particular",
|
||
"status_operativo": statusOperativoAlta
|
||
};
|
||
|
||
const serviceReference = is_company ? company_ref : `M-${Date.now().toString().slice(-6)}`;
|
||
|
||
const insertSvc = await pool.query(
|
||
`INSERT INTO scraped_services (owner_id, provider, service_ref, status, automation_status, assigned_to, raw_data)
|
||
VALUES ($1, 'MANUAL', $2, 'pending', $3, $4, $5) RETURNING id`,
|
||
[
|
||
ownerId,
|
||
serviceReference,
|
||
mode === 'auto' ? 'in_progress' : 'manual',
|
||
assigned_to || null,
|
||
JSON.stringify(rawData)
|
||
]
|
||
);
|
||
|
||
const newId = insertSvc.rows[0].id;
|
||
|
||
// 3. Si se eligió "Mandar a la bolsa", llamamos internamente al robot
|
||
if (mode === 'auto' && guild_id) {
|
||
const port = process.env.PORT || 3000;
|
||
fetch(`http://127.0.0.1:${port}/providers/automate/${newId}`, {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json', 'Authorization': req.headers.authorization },
|
||
body: JSON.stringify({ guild_id, cp: cpDetectado })
|
||
}).catch(e => console.error("Error lanzando bolsa:", e));
|
||
}
|
||
|
||
// --- TRAZABILIDAD ---
|
||
await registrarMovimiento(newId, req.user.sub, "Alta Manual", `Servicio creado manualmente (${rawData["CompañÃa"]}).`);
|
||
|
||
res.json({ ok: true, id: newId });
|
||
} catch (e) {
|
||
console.error("Error Alta Manual:", e);
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
// ==========================================
|
||
// ð ï¸ RUTAS DE GREMIOS E INTELIGENCIA ARTIFICIAL
|
||
// ==========================================
|
||
app.get("/guilds", authMiddleware, async (req, res) => {
|
||
try {
|
||
let q = await pool.query("SELECT id, name, ia_keywords FROM guilds WHERE owner_id=$1 ORDER BY name ASC", [req.user.accountId]);
|
||
if (q.rowCount === 0) {
|
||
const defaults = [
|
||
{ n: "ELECTRICISTA", kw: '["electric", "cortocircuito", "cuadro electrico", "salto de plomos", "apagon", "diferencial", "icp", "magnetotermico", "chispazo", "sin luz", "cableado", "derivacion", "no hay luz", "salta el termico"]' },
|
||
{ n: "FONTANERIA", kw: '["fontaner", "fuga de agua", "tuberia", "atasco", "desatasco", "bote sifonico", "llave de paso", "calentador", "termo", "radiador", "caldera", "gotera", "inundacion", "filtracion", "bajante", "humedad"]' },
|
||
{ n: "CRISTALERIA", kw: '["cristal", "vidrio", "ventana rota", "escaparate", "luna", "espejo", "climalit", "doble acristalamiento", "velux", "rotura"]' },
|
||
{ n: "PERSIANAS", kw: '["motor persiana", "eje persiana", "persianista", "persiana atascada", "rotura de persiana", "domotica persiana"]' },
|
||
{ n: "CARPINTERIA", kw: '["carpinter", "puerta de madera", "bisagra", "marco", "rodapie", "tarima", "armario", "cepillar puerta", "cajon", "encimera", "madera hinchada"]' },
|
||
{ n: "ALBAÃILERIA", kw: '["albañil", "cemento", "yeso", "ladrillo", "azulejo", "desconchado", "grieta", "muro", "alicatado"]' },
|
||
{ n: "MANITAS ELECTRICISTA", kw: '["manitas electric", "cambiar bombilla", "colgar lampara", "instalar foco", "fluorescente", "casquillo", "lampara del dormitorio", "cambiar enchufe", "embellecedor"]' },
|
||
{ n: "MANITAS FONTANERIA", kw: '["manitas fontaner", "cambiar grifo", "sellar bañera", "silicona", "latiguillo", "alcachofa", "tapon", "cambiar cisterna", "descargador"]' },
|
||
{ n: "MANITAS PERSIANAS", kw: '["manitas persian", "cambiar cinta", "cuerda persiana", "recogedor", "atasco persiana", "lamas rotas", "persiana descolgada"]' },
|
||
{ n: "MANITAS GENERAL", kw: '["bombin", "colgar cuadro", "soporte tv", "estanteria", "montar mueble", "ikea", "cortina", "riel", "estor", "agujero", "taladro", "picaporte", "colgar espejo"]' }
|
||
];
|
||
for (const g of defaults) { await pool.query("INSERT INTO guilds (owner_id, name, ia_keywords) VALUES ($1, $2, $3::jsonb)", [req.user.accountId, g.n, g.kw]); }
|
||
q = await pool.query("SELECT id, name, ia_keywords FROM guilds WHERE owner_id=$1 ORDER BY name ASC", [req.user.accountId]);
|
||
}
|
||
res.json({ ok: true, guilds: q.rows });
|
||
} catch (e) { res.status(500).json({ ok: false }); }
|
||
});
|
||
|
||
app.post("/guilds", authMiddleware, async (req, res) => { try { const { name } = req.body; await pool.query("INSERT INTO guilds (name, owner_id) VALUES ($1, $2)", [name, req.user.accountId]); res.json({ ok: true }); } catch (e) { res.status(500).json({ ok: false }); } });
|
||
app.delete("/guilds/:id", authMiddleware, async (req, res) => { try { await pool.query("DELETE FROM guilds WHERE id=$1 AND owner_id=$2", [req.params.id, req.user.accountId]); res.json({ ok: true }); } catch (e) { res.status(500).json({ ok: false }); } });
|
||
|
||
app.put("/guilds/:id/ia-rules", authMiddleware, async (req, res) => {
|
||
try {
|
||
const { keywords } = req.body;
|
||
const guildId = req.params.id;
|
||
const safeKeywords = Array.isArray(keywords) ? keywords : [];
|
||
await pool.query("UPDATE guilds SET ia_keywords = $1 WHERE id = $2 AND owner_id = $3", [JSON.stringify(safeKeywords), guildId, req.user.accountId]);
|
||
res.json({ ok: true });
|
||
} catch (e) { res.status(500).json({ ok: false, error: e.message }); }
|
||
});
|
||
|
||
// ==========================================
|
||
// ð MOTOR DE RANKING Y ESTADÃSTICAS
|
||
// ==========================================
|
||
|
||
function calculateScore(services) {
|
||
let score = 0;
|
||
const now = new Date();
|
||
const thirtyDaysAgo = new Date(now.getTime() - (30 * 24 * 60 * 60 * 1000));
|
||
|
||
// Separar servicios (usamos created_at para medir el último mes)
|
||
const openServices = services.filter(s => !s.is_final);
|
||
const closedLast30Days = services.filter(s => s.is_final && new Date(s.created_at) >= thirtyDaysAgo);
|
||
|
||
// --- 1. VELOCIDAD DE CIERRE (Max 30 Puntos) ---
|
||
let scoreCierre = 0;
|
||
if (closedLast30Days.length > 0) {
|
||
let totalDaysToClose = 0;
|
||
closedLast30Days.forEach(s => {
|
||
const created = new Date(s.created_at);
|
||
const closed = new Date(); // Estimamos el cierre en el ciclo actual
|
||
totalDaysToClose += Math.max(1, (closed - created) / (1000 * 60 * 60 * 24));
|
||
});
|
||
const avgCloseDays = totalDaysToClose / closedLast30Days.length;
|
||
|
||
if (avgCloseDays <= 2) scoreCierre = 30;
|
||
else if (avgCloseDays >= 14) scoreCierre = 0;
|
||
else scoreCierre = 30 - ((avgCloseDays - 2) * (30 / 12));
|
||
}
|
||
|
||
// --- 2. CITA RÃPIDA < 24h (Max 30 Puntos) ---
|
||
let scoreCita = 0;
|
||
let validSchedules = 0;
|
||
let fastSchedules = 0;
|
||
|
||
const recentServices = services.filter(s => new Date(s.created_at) >= thirtyDaysAgo);
|
||
recentServices.forEach(s => {
|
||
const raw = s.raw_data || {};
|
||
if (raw.scheduled_date) {
|
||
validSchedules++;
|
||
const created = new Date(s.created_at);
|
||
const [y, m, d] = raw.scheduled_date.split('-');
|
||
const schedDate = new Date(y, m - 1, d);
|
||
|
||
const diffDays = (schedDate - created) / (1000 * 60 * 60 * 24);
|
||
if (diffDays <= 1.5) fastSchedules++;
|
||
}
|
||
});
|
||
|
||
if (validSchedules > 0) {
|
||
const fastRatio = fastSchedules / validSchedules;
|
||
scoreCita = fastRatio * 30;
|
||
}
|
||
|
||
// --- 3. VOLUMEN DE TRABAJO AL DÃA (Max 20 Puntos) ---
|
||
let scoreVolumen = 0;
|
||
const closedPerDay = closedLast30Days.length / 22;
|
||
|
||
if (closedPerDay >= 3) scoreVolumen = 20;
|
||
else scoreVolumen = (closedPerDay / 3) * 20;
|
||
|
||
// --- 4. PENALIZACIÃN POR RE-CITAS (Max 20 Puntos) ---
|
||
let scoreRecitas = 20;
|
||
let totalCalled = 0;
|
||
recentServices.forEach(s => {
|
||
const raw = s.raw_data || {};
|
||
const calls = parseInt(raw.called_times || 0);
|
||
if (calls > 1) totalCalled += (calls - 1);
|
||
});
|
||
|
||
scoreRecitas = Math.max(0, 20 - (totalCalled * 2));
|
||
|
||
// --- SUMA BASE ---
|
||
let totalScore = scoreCierre + scoreCita + scoreVolumen + scoreRecitas;
|
||
|
||
// --- 5. PENALIZACIÃN POR ACUMULACIÃN DE ABIERTOS ---
|
||
let penalizacionAbiertos = 0;
|
||
if (openServices.length > 15) {
|
||
penalizacionAbiertos = (openServices.length - 15) * 1.5;
|
||
}
|
||
|
||
totalScore -= penalizacionAbiertos;
|
||
totalScore = Math.min(100, Math.max(0, totalScore));
|
||
|
||
return {
|
||
score: Math.round(totalScore),
|
||
details: {
|
||
cierre: Math.round(scoreCierre),
|
||
cita: Math.round(scoreCita),
|
||
volumen: Math.round(scoreVolumen),
|
||
recitas: Math.round(scoreRecitas),
|
||
penalizacion: Math.round(penalizacionAbiertos),
|
||
abiertos: openServices.length,
|
||
cerrados_mes: closedLast30Days.length
|
||
}
|
||
};
|
||
}
|
||
|
||
// RUTA GET PARA EL RANKING
|
||
app.get("/ranking", authMiddleware, async (req, res) => {
|
||
try {
|
||
// CORRECCIÃN: Hemos quitado "updated_at" de aquà para evitar que la base de datos se queje
|
||
const q = await pool.query(`
|
||
SELECT id, created_at, raw_data,
|
||
(SELECT is_final FROM service_statuses WHERE id::text = raw_data->>'status_operativo') as is_final
|
||
FROM scraped_services
|
||
WHERE assigned_to = $1
|
||
`, [req.user.sub]);
|
||
|
||
const rankingData = calculateScore(q.rows);
|
||
|
||
await pool.query(
|
||
"UPDATE users SET ranking_score = $1, ranking_data = $2 WHERE id = $3",
|
||
[rankingData.score, rankingData.details, req.user.sub]
|
||
);
|
||
|
||
res.json({ ok: true, ranking: rankingData });
|
||
|
||
} catch (error) {
|
||
console.error("Error en ranking:", error);
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
|
||
// ==========================================
|
||
// ð MOTOR GPS: RASTREO EN TIEMPO REAL
|
||
// ==========================================
|
||
|
||
// El operario envÃa su ubicación
|
||
app.post("/services/:id/location", authMiddleware, async (req, res) => {
|
||
try {
|
||
const { lat, lng } = req.body;
|
||
if (!lat || !lng) return res.status(400).json({ ok: false });
|
||
|
||
const locData = { lat, lng, updated_at: new Date().toISOString() };
|
||
|
||
// CORRECCIÃN: Ahora usa owner_id para que funcione aunque el admin esté haciendo la prueba
|
||
await pool.query(`
|
||
UPDATE scraped_services
|
||
SET raw_data = jsonb_set(COALESCE(raw_data, '{}'::jsonb), '{worker_location}', $1::jsonb)
|
||
WHERE id = $2 AND owner_id = $3
|
||
`, [JSON.stringify(locData), req.params.id, req.user.accountId]);
|
||
|
||
res.json({ ok: true });
|
||
} catch (e) {
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
// El cliente consulta la ubicación
|
||
app.get("/public/portal/:token/location/:serviceId", async (req, res) => {
|
||
try {
|
||
const { token, serviceId } = req.params;
|
||
const clientQ = await pool.query("SELECT owner_id FROM clients WHERE portal_token = $1", [token]);
|
||
if (clientQ.rowCount === 0) return res.status(404).json({ ok: false });
|
||
|
||
const serviceQ = await pool.query("SELECT raw_data FROM scraped_services WHERE id = $1 AND owner_id = $2", [serviceId, clientQ.rows[0].owner_id]);
|
||
if (serviceQ.rowCount === 0) return res.status(404).json({ ok: false });
|
||
|
||
const loc = serviceQ.rows[0].raw_data.worker_location || null;
|
||
res.json({ ok: true, location: loc });
|
||
} catch (e) {
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
|
||
// ==========================================
|
||
// ð RUTAS PARA ACEPTAR/RECHAZAR AVISOS (PANTALLA OPERARIOS)
|
||
// ==========================================
|
||
|
||
app.get("/public/assignment/:token", async (req, res) => {
|
||
try {
|
||
const { token } = req.params;
|
||
// ð§ AÃADIDO: Subconsulta mágica para sacar el nombre real del Gremio
|
||
const q = await pool.query(`
|
||
SELECT ap.*, s.raw_data, s.service_ref, s.is_urgent, u.full_name,
|
||
(SELECT name FROM guilds WHERE id::text = s.raw_data->>'guild_id' LIMIT 1) as real_guild_name
|
||
FROM assignment_pings ap
|
||
JOIN scraped_services s ON ap.scraped_id = s.id
|
||
JOIN users u ON ap.user_id = u.id
|
||
WHERE ap.token = $1
|
||
`, [token]);
|
||
|
||
if (q.rowCount === 0) return res.status(404).json({ ok: false, error: "Asignación no encontrada" });
|
||
|
||
const assign = q.rows[0];
|
||
|
||
if (assign.status !== 'pending') {
|
||
return res.json({ ok: false, error: "Este aviso ya fue " + (assign.status === 'accepted' ? 'aceptado' : 'rechazado o ha caducado.') });
|
||
}
|
||
|
||
if (new Date() > new Date(assign.expires_at)) {
|
||
await pool.query("UPDATE assignment_pings SET status = 'expired' WHERE id = $1", [assign.id]);
|
||
return res.json({ ok: false, error: "El tiempo para aceptar este aviso ha caducado." });
|
||
}
|
||
|
||
// Parsear datos para enviarlos bonitos a la pantalla de aceptar.html
|
||
const raw = assign.raw_data || {};
|
||
const serviceData = {
|
||
"Gremio": assign.real_guild_name || raw["Gremio"] || raw.guild_name || "Servicio General",
|
||
"Expediente": assign.service_ref || raw["Referencia"] || "Sin Ref",
|
||
"Dirección": raw["Dirección"] || raw["DOMICILIO"] || "",
|
||
"Población": raw["Población"] || raw["POBLACION-PROVINCIA"] || "",
|
||
"Código Postal": raw["Código Postal"] || "",
|
||
"Descripción": raw["Descripción"] || raw["DESCRIPCION"] || "Revisar en el lugar."
|
||
};
|
||
|
||
res.json({ ok: true, service: serviceData, debug: { hora_limite_bd: assign.expires_at } });
|
||
} catch (e) {
|
||
console.error("Error al obtener asignación:", e);
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
app.post("/public/assignment/respond", async (req, res) => {
|
||
const client = await pool.connect();
|
||
try {
|
||
const { token, action } = req.body;
|
||
|
||
if (!token || !action) return res.status(400).json({ ok: false, error: "Faltan datos" });
|
||
|
||
await client.query('BEGIN');
|
||
|
||
// 1. Validar ping bloqueando la fila
|
||
const qPing = await client.query("SELECT * FROM assignment_pings WHERE token = $1 AND status = 'pending' FOR UPDATE", [token]);
|
||
if (qPing.rowCount === 0) {
|
||
await client.query('ROLLBACK');
|
||
return res.status(400).json({ ok: false, error: "Este aviso ya no está disponible." });
|
||
}
|
||
|
||
const ping = qPing.rows[0];
|
||
|
||
if (action === 'reject') {
|
||
await client.query("UPDATE assignment_pings SET status = 'rejected' WHERE id = $1", [ping.id]);
|
||
await client.query('COMMIT');
|
||
|
||
// --- INICIO TRAZABILIDAD ---
|
||
await registrarMovimiento(ping.scraped_id, ping.user_id, "Servicio Aceptado", "El operario ha aceptado el aviso desde su teléfono móvil.");
|
||
// --- FIN TRAZABILIDAD ---
|
||
|
||
|
||
return res.json({ ok: true });
|
||
}
|
||
|
||
if (action === 'accept') {
|
||
// 2. Marcar ping como aceptado
|
||
await client.query("UPDATE assignment_pings SET status = 'accepted' WHERE id = $1", [ping.id]);
|
||
|
||
// 3. Sacar datos del servicio
|
||
const sQ = await client.query("SELECT owner_id, raw_data FROM scraped_services WHERE id = $1", [ping.scraped_id]);
|
||
const ownerId = sQ.rows[0].owner_id;
|
||
let rawData = sQ.rows[0].raw_data || {};
|
||
|
||
// 4. Poner el estado en "Asignado" si existe
|
||
const statusQ = await client.query("SELECT id, name FROM service_statuses WHERE owner_id=$1 AND name ILIKE '%asignado%' LIMIT 1", [ownerId]);
|
||
const statusAsignadoId = statusQ.rows[0]?.id || null;
|
||
|
||
if (statusAsignadoId) {
|
||
rawData.status_operativo = statusAsignadoId;
|
||
}
|
||
|
||
// 5. Actualizar el expediente oficial con el técnico y BLINDARLO contra el robot
|
||
await client.query(`
|
||
UPDATE scraped_services
|
||
SET assigned_to = $1, automation_status = 'completed', status = 'imported', raw_data = $2
|
||
WHERE id = $3
|
||
`, [ping.user_id, JSON.stringify(rawData), ping.scraped_id]);
|
||
|
||
await client.query('COMMIT');
|
||
|
||
// 6. ¡Magia! Le enviamos un WhatsApp automático al cliente diciendo que ya tiene técnico
|
||
triggerWhatsAppEvent(ownerId, ping.scraped_id, 'wa_evt_assigned').catch(e => console.error(e));
|
||
|
||
return res.json({ ok: true });
|
||
}
|
||
|
||
await client.query('ROLLBACK');
|
||
res.status(400).json({ ok: false, error: "Acción no válida" });
|
||
|
||
} catch (e) {
|
||
await client.query('ROLLBACK');
|
||
console.error("Error respondiendo asignación:", e);
|
||
res.status(500).json({ ok: false, error: "Error interno del servidor" });
|
||
} finally {
|
||
client.release();
|
||
}
|
||
});
|
||
|
||
app.post("/public/assignment/:token/reject", async (req, res) => {
|
||
try {
|
||
const { token } = req.params;
|
||
// Si lo rechaza, el reloj (setInterval) se encargará de buscar al siguiente técnico libre al instante
|
||
await pool.query("UPDATE assignment_pings SET status = 'rejected' WHERE token = $1 AND status = 'pending'", [token]);
|
||
res.json({ ok: true });
|
||
} catch (e) {
|
||
console.error("Error rechazando asignación:", e);
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
// ==========================================
|
||
// ð MOTOR DE PRESUPUESTOS Y CATÃLOGO DE ARTÃCULOS
|
||
// ==========================================
|
||
pool.query(`
|
||
CREATE TABLE IF NOT EXISTS articles (
|
||
id SERIAL PRIMARY KEY,
|
||
owner_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||
name TEXT NOT NULL,
|
||
price DECIMAL(10,2) DEFAULT 0.00,
|
||
created_at TIMESTAMP DEFAULT NOW()
|
||
);
|
||
|
||
CREATE TABLE IF NOT EXISTS budgets (
|
||
id SERIAL PRIMARY KEY,
|
||
owner_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||
client_phone TEXT,
|
||
client_name TEXT,
|
||
client_address TEXT,
|
||
items JSONB DEFAULT '[]',
|
||
subtotal DECIMAL(10,2) DEFAULT 0.00,
|
||
tax DECIMAL(10,2) DEFAULT 0.00,
|
||
total DECIMAL(10,2) DEFAULT 0.00,
|
||
status TEXT DEFAULT 'pending', -- pending, accepted, rejected, converted
|
||
created_at TIMESTAMP DEFAULT NOW()
|
||
);
|
||
`).catch(console.error);
|
||
|
||
// --- CATÃLOGO DE ARTÃCULOS ---
|
||
app.get("/articles", authMiddleware, async (req, res) => {
|
||
try {
|
||
const q = await pool.query("SELECT * FROM articles WHERE owner_id=$1 ORDER BY name ASC", [req.user.accountId]);
|
||
res.json({ ok: true, articles: q.rows });
|
||
} catch(e) { res.status(500).json({ok: false}); }
|
||
});
|
||
|
||
app.post("/articles", authMiddleware, async (req, res) => {
|
||
try {
|
||
const { name, price } = req.body;
|
||
await pool.query("INSERT INTO articles (owner_id, name, price) VALUES ($1, $2, $3)", [req.user.accountId, name, price]);
|
||
res.json({ ok: true });
|
||
} catch(e) { res.status(500).json({ok: false}); }
|
||
});
|
||
|
||
app.put("/articles/:id", authMiddleware, async (req, res) => {
|
||
try {
|
||
const { name, price } = req.body;
|
||
await pool.query("UPDATE articles SET name=$1, price=$2 WHERE id=$3 AND owner_id=$4", [name, price, req.params.id, req.user.accountId]);
|
||
res.json({ ok: true });
|
||
} catch(e) { res.status(500).json({ok: false}); }
|
||
});
|
||
|
||
// --- PRESUPUESTOS ---
|
||
app.get("/budgets", authMiddleware, async (req, res) => {
|
||
try {
|
||
// MAGIA: Cruzamos los datos con scraped_services y service_statuses para saber
|
||
// exactamente en qué estado se encuentra el servicio que nació de este presupuesto.
|
||
const q = await pool.query(`
|
||
SELECT b.*,
|
||
s.status as linked_service_status,
|
||
st.name as linked_service_status_name
|
||
FROM budgets b
|
||
LEFT JOIN scraped_services s ON s.service_ref = 'PRE-' || b.id AND s.owner_id = b.owner_id
|
||
LEFT JOIN service_statuses st ON st.id::text = (s.raw_data->>'status_operativo')::text
|
||
WHERE b.owner_id=$1
|
||
ORDER BY b.created_at DESC
|
||
`, [req.user.accountId]);
|
||
const seen = new Map();
|
||
for (const row of q.rows) {
|
||
const isAnulado = (row.linked_service_status_name || '').toLowerCase().includes('anulado');
|
||
const prev = seen.get(row.id);
|
||
if (!prev) {
|
||
seen.set(row.id, { row, isAnulado });
|
||
} else if (prev.isAnulado && !isAnulado) {
|
||
seen.set(row.id, { row, isAnulado });
|
||
}
|
||
}
|
||
const dedupedBudgets = Array.from(seen.values()).map(v => v.row);
|
||
res.json({ ok: true, budgets: dedupedBudgets });
|
||
} catch(e) { res.status(500).json({ok: false}); }
|
||
});
|
||
|
||
// Borrar Presupuesto
|
||
app.delete("/budgets/:id", authMiddleware, async (req, res) => {
|
||
try {
|
||
const q = await pool.query("SELECT status FROM budgets WHERE id=$1 AND owner_id=$2", [req.params.id, req.user.accountId]);
|
||
if (q.rowCount === 0) return res.status(404).json({ok: false, error: "No encontrado"});
|
||
|
||
const status = q.rows[0].status;
|
||
|
||
// Comprobamos si el servicio vinculado está anulado
|
||
const sq = await pool.query(`
|
||
SELECT st.name as status_name
|
||
FROM scraped_services s
|
||
LEFT JOIN service_statuses st ON st.id::text = (s.raw_data->>'status_operativo')::text
|
||
WHERE s.service_ref = $1 AND s.owner_id = $2
|
||
`, [`PRE-${req.params.id}`, req.user.accountId]);
|
||
|
||
let isAnulado = false;
|
||
if (sq.rowCount > 0 && sq.rows[0].status_name && sq.rows[0].status_name.toLowerCase().includes('anulado')) {
|
||
isAnulado = true;
|
||
}
|
||
|
||
// REGLA DE NEGOCIO: No se puede borrar si está aceptado o convertido (Y NO ESTà ANULADO)
|
||
if ((status === 'accepted' || status === 'converted') && !isAnulado) {
|
||
return res.status(400).json({ok: false, error: "Para poder borrar un presupuesto, el servicio primero debe estar anulado."});
|
||
}
|
||
|
||
await pool.query("DELETE FROM budgets 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, error: "Error interno"});
|
||
}
|
||
});
|
||
|
||
// Convertir Presupuesto en Servicio Activo (CON SOPORTE RED INTERNA Y TRAZABILIDAD)
|
||
app.post("/budgets/:id/convert", authMiddleware, async (req, res) => {
|
||
try {
|
||
const { date, time, guild_id, assigned_to, use_automation } = req.body;
|
||
const bq = await pool.query("SELECT * FROM budgets WHERE id=$1 AND owner_id=$2", [req.params.id, req.user.accountId]);
|
||
if (bq.rowCount === 0) return res.status(404).json({ok: false});
|
||
const budget = bq.rows[0];
|
||
|
||
// ð Evitar conversiones duplicadas: si este presupuesto ya se convirtió antes en un servicio, no crear otro
|
||
if (budget.status === 'converted' || budget.status === 'paid') {
|
||
return res.status(409).json({ ok: false, error: "Este presupuesto ya fue convertido en un servicio anteriormente." });
|
||
}
|
||
|
||
// ð¢ Saber si ya estaba pagado antes de convertirlo
|
||
const isAlreadyPaid = budget.status === 'paid';
|
||
|
||
// 1. Montamos el Raw Data para el servicio
|
||
const rawData = {
|
||
"Nombre Cliente": budget.client_name,
|
||
"Teléfono": budget.client_phone,
|
||
"Dirección": budget.client_address,
|
||
"CompañÃa": "Particular",
|
||
"Descripción": "PRESUPUESTO ACEPTADO.\n" + budget.items.map(i => `${i.qty}x ${i.concept}`).join("\n"),
|
||
"guild_id": guild_id || null,
|
||
"assigned_to": assigned_to || null,
|
||
"scheduled_date": date || "",
|
||
"scheduled_time": time || "",
|
||
"is_paid": isAlreadyPaid // ð¢ Inyección limpia estructural
|
||
};
|
||
|
||
// 2. Insertamos en el Panel Operativo (Buzón) empezando en manual
|
||
const insertSvc = await pool.query(
|
||
"INSERT INTO scraped_services (owner_id, provider, service_ref, status, automation_status, assigned_to, raw_data) VALUES ($1, 'particular', $2, 'pending', 'manual', $3, $4) RETURNING id",
|
||
[
|
||
req.user.accountId,
|
||
`PRE-${budget.id}`,
|
||
assigned_to || null,
|
||
JSON.stringify(rawData)
|
||
]
|
||
);
|
||
|
||
const newServiceId = insertSvc.rows[0].id;
|
||
|
||
// 3. Marcamos presupuesto y enlazamos ficha financiera
|
||
const finalBudgetStatus = isAlreadyPaid ? 'paid' : 'converted';
|
||
await pool.query("UPDATE budgets SET status=$1 WHERE id=$2", [finalBudgetStatus, budget.id]);
|
||
|
||
await pool.query(
|
||
"INSERT INTO service_financials (scraped_id, amount, payment_method, is_paid) VALUES ($1, $2, $3, $4)",
|
||
[newServiceId, budget.total, isAlreadyPaid ? 'Tarjeta (Stripe)' : 'Pendiente', isAlreadyPaid]
|
||
);
|
||
|
||
// 4. Si pide automatización, la disparamos internamente llamando a nuestra propia IP (127.0.0.1)
|
||
if (use_automation && guild_id) {
|
||
const cpMatch = budget.client_address ? budget.client_address.match(/\b\d{5}\b/) : null;
|
||
const cp = cpMatch ? cpMatch[0] : "00000";
|
||
|
||
const port = process.env.PORT || 3000;
|
||
const autoUrl = `http://127.0.0.1:${port}/providers/automate/${newServiceId}`;
|
||
|
||
fetch(autoUrl, {
|
||
method: 'POST',
|
||
headers: {
|
||
'Content-Type': 'application/json',
|
||
'Authorization': req.headers.authorization
|
||
},
|
||
body: JSON.stringify({ guild_id, cp, useDelay: false })
|
||
}).catch(e => console.error("Error lanzando automatización interna:", e));
|
||
}
|
||
|
||
if (budget.client_phone && date && time) {
|
||
// Cita ya agendada (fecha y técnico asignados): usamos la plantilla "Cita Creada" configurada en Configuración > Plantillas
|
||
triggerWhatsAppEvent(req.user.accountId, newServiceId, 'wa_evt_date').catch(console.error);
|
||
|
||
if (assigned_to) {
|
||
const statusQ = await pool.query("SELECT id FROM service_statuses WHERE owner_id=$1 AND name ILIKE '%asignado%' LIMIT 1", [req.user.accountId]);
|
||
if (statusQ.rowCount > 0) {
|
||
rawData.status_operativo = statusQ.rows[0].id;
|
||
await pool.query("UPDATE scraped_services SET raw_data = $1 WHERE id = $2", [JSON.stringify(rawData), newServiceId]);
|
||
}
|
||
}
|
||
} else if (budget.client_phone) {
|
||
|
||
const msg = `â
*PRESUPUESTO ACEPTADO*\n\nHola ${budget.client_name}, confirmamos la aceptación del presupuesto por un total de *${budget.total}â¬*.\n\nEn breve un técnico se pondrá en contacto contigo para agendar la cita. ¡Gracias por confiar en nosotros!`;
|
||
sendWhatsAppAuto(budget.client_phone, msg, `cliente_${req.user.accountId}`, false).catch(console.error);
|
||
}
|
||
|
||
// --- INICIO TRAZABILIDAD ---
|
||
await registrarMovimiento(newServiceId, req.user.sub, "Aviso Creado", `Servicio generado a raÃz del presupuesto aceptado #PRE-${budget.id}.`);
|
||
// --- FIN TRAZABILIDAD ---
|
||
|
||
res.json({ ok: true });
|
||
} catch(e) {
|
||
console.error("Error convirtiendo presupuesto:", e);
|
||
res.status(500).json({ok: false});
|
||
}
|
||
});
|
||
|
||
|
||
|
||
// ==========================================
|
||
// ð° MOTOR FINANCIERO Y CONTABILIDAD (PREPARADO PARA ROBOT PDF)
|
||
// ==========================================
|
||
// Creamos la tabla financiera preparada para facturas y robots
|
||
pool.query(`
|
||
CREATE TABLE IF NOT EXISTS service_financials (
|
||
id SERIAL PRIMARY KEY,
|
||
scraped_id INT REFERENCES scraped_services(id) ON DELETE CASCADE UNIQUE,
|
||
amount DECIMAL(10,2) DEFAULT 0.00,
|
||
payment_method TEXT,
|
||
is_paid BOOLEAN DEFAULT false,
|
||
invoice_ref TEXT,
|
||
pdf_raw_data JSONB,
|
||
created_at TIMESTAMP DEFAULT NOW(),
|
||
updated_at TIMESTAMP DEFAULT NOW()
|
||
);
|
||
`).catch(console.error);
|
||
|
||
// Obtener toda la contabilidad
|
||
app.get("/financials", authMiddleware, async (req, res) => {
|
||
try {
|
||
// 1. Truco de magia: Si hay servicios que no tienen ficha financiera, se la creamos automáticamente.
|
||
// Si tiene compañÃa asignada, le ponemos "Cobro Banco" por defecto. Si no, "Pendiente".
|
||
await pool.query(`
|
||
INSERT INTO service_financials (scraped_id, payment_method)
|
||
SELECT id,
|
||
CASE WHEN raw_data->>'CompañÃa' IS NOT NULL AND raw_data->>'CompañÃa' != '' AND raw_data->>'CompañÃa' != 'Particular'
|
||
THEN 'Cobro Banco'
|
||
ELSE 'Pendiente' END
|
||
FROM scraped_services
|
||
WHERE owner_id = $1 AND id NOT IN (SELECT scraped_id FROM service_financials)
|
||
`, [req.user.accountId]);
|
||
|
||
// 2. Devolvemos la lista cruzando las finanzas con los datos del servicio
|
||
const q = await pool.query(`
|
||
SELECT f.*, s.service_ref, s.raw_data, s.status
|
||
FROM service_financials f
|
||
JOIN scraped_services s ON f.scraped_id = s.id
|
||
WHERE s.owner_id = $1
|
||
ORDER BY f.updated_at DESC
|
||
`, [req.user.accountId]);
|
||
|
||
res.json({ ok: true, financials: q.rows });
|
||
} catch(e) {
|
||
console.error("Error financiero:", e);
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
// Guardar un cobro/pago
|
||
app.put("/financials/:id", authMiddleware, async (req, res) => {
|
||
try {
|
||
const { amount, payment_method } = req.body;
|
||
const parsedAmount = parseFloat(amount) || 0;
|
||
|
||
// NUEVA REGLA: Si el método de pago es "Pendiente", NO está pagado,
|
||
// independientemente del importe que tenga apuntado (Ej: Presupuestos).
|
||
const isPaid = payment_method !== 'Pendiente';
|
||
|
||
await pool.query(`
|
||
UPDATE service_financials
|
||
SET amount = $1, payment_method = $2, is_paid = $3, updated_at = NOW()
|
||
WHERE scraped_id = $4
|
||
`, [parsedAmount, payment_method, isPaid, req.params.id]);
|
||
|
||
// LOG AUTOMÃTICO DE TRAZABILIDAD
|
||
const userQ = await pool.query("SELECT full_name FROM users WHERE id=$1", [req.user.sub]);
|
||
const userName = userQ.rows[0]?.full_name || "Sistema";
|
||
await pool.query(
|
||
"INSERT INTO scraped_service_logs (scraped_id, user_name, action, details) VALUES ($1, $2, $3, $4)",
|
||
[req.params.id, userName, "Cobro Actualizado", `Importe: ${parsedAmount}⬠| Método: ${payment_method}`]
|
||
);
|
||
|
||
res.json({ ok: true, is_paid: isPaid });
|
||
} catch(e) {
|
||
console.error(e);
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
// ==========================================
|
||
// ð MOTOR DE TRAZABILIDAD (LOGS)
|
||
// ==========================================
|
||
// Creamos la tabla automáticamente si no existe
|
||
pool.query(`
|
||
CREATE TABLE IF NOT EXISTS scraped_service_logs (
|
||
id SERIAL PRIMARY KEY,
|
||
scraped_id INT REFERENCES scraped_services(id) ON DELETE CASCADE,
|
||
user_name TEXT,
|
||
action TEXT NOT NULL,
|
||
details TEXT,
|
||
created_at TIMESTAMP DEFAULT NOW()
|
||
);
|
||
`).catch(console.error);
|
||
|
||
// Ruta para GUARDAR un evento en el log
|
||
app.post("/services/:id/log", authMiddleware, async (req, res) => {
|
||
try {
|
||
const { action, details } = req.body;
|
||
const serviceId = req.params.id;
|
||
|
||
// Verificamos propiedad antes de insertar
|
||
const check = await pool.query("SELECT id FROM scraped_services WHERE id=$1 AND owner_id=$2", [serviceId, req.user.accountId]);
|
||
if (check.rowCount === 0) return res.status(403).json({ ok: false, error: "No autorizado" });
|
||
|
||
const userQ = await pool.query("SELECT full_name FROM users WHERE id=$1", [req.user.sub]);
|
||
const userName = userQ.rows[0]?.full_name || "Sistema";
|
||
|
||
await pool.query(
|
||
"INSERT INTO scraped_service_logs (scraped_id, user_name, action, details) VALUES ($1, $2, $3, $4)",
|
||
[serviceId, userName, action, details || ""]
|
||
);
|
||
res.json({ ok: true });
|
||
} catch(e) {
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
// Ruta para LEER el historial de un servicio
|
||
app.get("/services/:id/logs", authMiddleware, async (req, res) => {
|
||
try {
|
||
// Cruce con la tabla principal para verificar el dueño (owner_id)
|
||
const q = await pool.query(`
|
||
SELECT l.* FROM scraped_service_logs l
|
||
JOIN scraped_services s ON l.scraped_id = s.id
|
||
WHERE l.scraped_id = $1
|
||
AND s.owner_id = $2
|
||
ORDER BY l.created_at DESC
|
||
`, [req.params.id, req.user.accountId]);
|
||
|
||
res.json({ ok: true, logs: q.rows });
|
||
} catch(e) {
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
// ==========================================
|
||
// ð§âð§ FICHA DEL CLIENTE (App): historial de servicios + notas propias del equipo
|
||
// ==========================================
|
||
pool.query(`
|
||
CREATE TABLE IF NOT EXISTS client_notes (
|
||
id SERIAL PRIMARY KEY,
|
||
client_id INT REFERENCES clients(id) ON DELETE CASCADE,
|
||
owner_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||
user_name TEXT,
|
||
note TEXT NOT NULL,
|
||
created_at TIMESTAMP DEFAULT NOW()
|
||
);
|
||
`).catch(console.error);
|
||
|
||
// Ficha completa: datos del cliente + todos sus servicios anteriores (de cualquier compañÃa),
|
||
// buscados por teléfono igual que hace /clients/search.
|
||
app.get("/clients/:id/history", authMiddleware, async (req, res) => {
|
||
try {
|
||
const ownerId = req.user.accountId;
|
||
const clientQ = await pool.query("SELECT * FROM clients WHERE id=$1 AND owner_id=$2", [req.params.id, ownerId]);
|
||
if (clientQ.rowCount === 0) return res.status(404).json({ ok: false, error: "Cliente no encontrado" });
|
||
const client = clientQ.rows[0];
|
||
|
||
const bare = extractValidPhone(client.phone);
|
||
const servicesQ = await pool.query(`
|
||
SELECT s.id, s.provider, s.service_ref, s.status, s.raw_data, s.created_at,
|
||
st.name as status_name, st.color as status_color, st.is_final as status_is_final
|
||
FROM scraped_services s
|
||
LEFT JOIN service_statuses st ON st.id::text = (s.raw_data->>'status_operativo')::text
|
||
WHERE s.owner_id=$1
|
||
AND regexp_replace(COALESCE(s.raw_data->>'Teléfono', s.raw_data->>'TELEFONO', s.raw_data->>'TELEFONOS', ''), '\\D', '', 'g') LIKE '%' || $2 || '%'
|
||
ORDER BY s.created_at DESC
|
||
LIMIT 100
|
||
`, [ownerId, bare]);
|
||
|
||
res.json({ ok: true, client, services: servicesQ.rows });
|
||
} catch (e) {
|
||
console.error("Error cargando ficha de cliente:", e);
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
// Notas del equipo sobre este cliente (visibles para toda la cuenta, no solo quien las escribe)
|
||
app.get("/clients/:id/notes", authMiddleware, async (req, res) => {
|
||
try {
|
||
const q = await pool.query(`
|
||
SELECT n.* FROM client_notes n
|
||
JOIN clients c ON n.client_id = c.id
|
||
WHERE n.client_id = $1 AND c.owner_id = $2
|
||
ORDER BY n.created_at DESC
|
||
`, [req.params.id, req.user.accountId]);
|
||
res.json({ ok: true, notes: q.rows });
|
||
} catch (e) {
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
app.post("/clients/:id/notes", authMiddleware, async (req, res) => {
|
||
try {
|
||
const { note } = req.body;
|
||
if (!note || !note.trim()) return res.status(400).json({ ok: false, error: "La nota está vacÃa" });
|
||
|
||
const check = await pool.query("SELECT id FROM clients WHERE id=$1 AND owner_id=$2", [req.params.id, req.user.accountId]);
|
||
if (check.rowCount === 0) return res.status(403).json({ ok: false, error: "No autorizado" });
|
||
|
||
const userQ = await pool.query("SELECT full_name FROM users WHERE id=$1", [req.user.sub]);
|
||
const userName = userQ.rows[0]?.full_name || "Usuario";
|
||
|
||
const insert = await pool.query(
|
||
"INSERT INTO client_notes (client_id, owner_id, user_name, note) VALUES ($1, $2, $3, $4) RETURNING *",
|
||
[req.params.id, req.user.accountId, userName, note.trim()]
|
||
);
|
||
res.json({ ok: true, note: insert.rows[0] });
|
||
} catch (e) {
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
// ==========================================
|
||
// ð MOTOR DE PRESUPUESTOS (continuación) â POST/PUT/PATCH de /budgets
|
||
// 𩹠FIX: este bloque duplicaba por completo la creación de tablas y las rutas
|
||
// GET/POST/PUT /articles, GET /budgets y DELETE /budgets/:id que ya se registran
|
||
// arriba (Express siempre usaba la primera copia; la segunda era código muerto).
|
||
// Se ha fusionado en un único bloque, dejando solo las rutas que eran nuevas aquÃ.
|
||
// ==========================================
|
||
app.post("/budgets", authMiddleware, async (req, res) => {
|
||
try {
|
||
const { client_phone, client_name, client_address, items, subtotal, tax, total } = req.body;
|
||
|
||
// 1. Guardamos el presupuesto en la BBDD
|
||
await pool.query(
|
||
"INSERT INTO budgets (owner_id, client_phone, client_name, client_address, items, subtotal, tax, total) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
|
||
[req.user.accountId, client_phone, client_name, client_address, JSON.stringify(items), subtotal, tax, total]
|
||
);
|
||
|
||
// Respondemos a la App rápido para que no se quede pensando
|
||
res.json({ ok: true });
|
||
|
||
// 2. TAREAS EN SEGUNDO PLANO (EnvÃo del WhatsApp)
|
||
(async () => {
|
||
try {
|
||
let rawPhone = client_phone || "";
|
||
let cleanPhoneToMatch = extractValidPhone(rawPhone);
|
||
|
||
if (cleanPhoneToMatch.length >= 9) {
|
||
const finalPhoneToSend = "34" + cleanPhoneToMatch;
|
||
let token = null;
|
||
|
||
// Buscamos si el cliente ya tiene un token
|
||
const clientQ = await pool.query("SELECT portal_token FROM clients WHERE phone LIKE $1 AND owner_id=$2 LIMIT 1", [`%${cleanPhoneToMatch}%`, req.user.accountId]);
|
||
|
||
if (clientQ.rowCount > 0) {
|
||
token = clientQ.rows[0].portal_token;
|
||
} else {
|
||
// Si es un cliente totalmente nuevo, lo registramos y le creamos un token seguro
|
||
const newToken = crypto.randomBytes(32).toString('hex');
|
||
const insertC = await pool.query(
|
||
"INSERT INTO clients (owner_id, full_name, phone, addresses, portal_token) VALUES ($1, $2, $3, $4, $5) RETURNING portal_token",
|
||
[req.user.accountId, client_name || "Cliente", finalPhoneToSend, JSON.stringify([client_address || ""]), newToken]
|
||
);
|
||
token = insertC.rows[0].portal_token;
|
||
}
|
||
|
||
if (token) {
|
||
const linkMagico = `https://portal.integrarepara.es/?token=${token}`;
|
||
const msg = `ð Hola ${client_name || "Cliente"},\n\nAcabamos de generar un *nuevo presupuesto* para tu reparación por un total de *${total}â¬*.\n\nð Puedes revisarlo al detalle y descargarlo en PDF directamente desde tu portal privado:\nð ${linkMagico}`;
|
||
|
||
// MODO PRUEBAS: Si quieres probarlo a tu número primero, cambia MODO_PRUEBAS a true
|
||
const MODO_PRUEBAS = false;
|
||
const MI_TELEFONO = "34667248132";
|
||
|
||
if (MODO_PRUEBAS) {
|
||
console.log(`ð¡ï¸ [MODO PRUEBAS] Enviando WA presupuesto a (${MI_TELEFONO}) en lugar de al cliente`);
|
||
await sendWhatsAppAuto(MI_TELEFONO, `*(SIMULACIÃN PRESUPUESTO PARA: ${finalPhoneToSend})*\n\n${msg}`, `cliente_${req.user.accountId}`, false);
|
||
} else {
|
||
console.log(`â
Enviando WA de nuevo presupuesto al cliente: ${finalPhoneToSend}`);
|
||
await sendWhatsAppAuto(finalPhoneToSend, msg, `cliente_${req.user.accountId}`, false);
|
||
}
|
||
}
|
||
}
|
||
} catch(errWA) {
|
||
console.error("â Error enviando WA de presupuesto:", errWA);
|
||
}
|
||
})();
|
||
|
||
} catch(e) {
|
||
res.status(500).json({ok: false});
|
||
}
|
||
});
|
||
|
||
// Actualizar Presupuesto Existente
|
||
app.put("/budgets/:id", authMiddleware, async (req, res) => {
|
||
try {
|
||
const { client_phone, client_name, client_address, items, subtotal, tax, total } = req.body;
|
||
|
||
const q = await pool.query(
|
||
"UPDATE budgets SET client_phone=$1, client_name=$2, client_address=$3, items=$4, subtotal=$5, tax=$6, total=$7 WHERE id=$8 AND owner_id=$9",
|
||
[client_phone, client_name, client_address, JSON.stringify(items), subtotal, tax, total, req.params.id, req.user.accountId]
|
||
);
|
||
|
||
if (q.rowCount === 0) return res.status(404).json({ ok: false, error: "Presupuesto no encontrado" });
|
||
|
||
// Respondemos rápido a la App y avisamos al cliente en segundo plano
|
||
res.json({ ok: true });
|
||
|
||
// AVISO AL CLIENTE DE PRESUPUESTO MODIFICADO (con reenvÃo del enlace del portal)
|
||
(async () => {
|
||
try {
|
||
let rawPhone = client_phone || "";
|
||
let cleanPhoneToMatch = extractValidPhone(rawPhone);
|
||
|
||
if (cleanPhoneToMatch.length >= 9) {
|
||
const finalPhoneToSend = "34" + cleanPhoneToMatch;
|
||
let token = null;
|
||
|
||
const clientQ = await pool.query("SELECT portal_token FROM clients WHERE phone LIKE $1 AND owner_id=$2 LIMIT 1", [`%${cleanPhoneToMatch}%`, req.user.accountId]);
|
||
|
||
if (clientQ.rowCount > 0) {
|
||
token = clientQ.rows[0].portal_token;
|
||
} else {
|
||
const newToken = crypto.randomBytes(32).toString('hex');
|
||
const insertC = await pool.query(
|
||
"INSERT INTO clients (owner_id, full_name, phone, addresses, portal_token) VALUES ($1, $2, $3, $4, $5) RETURNING portal_token",
|
||
[req.user.accountId, client_name || "Cliente", finalPhoneToSend, JSON.stringify([client_address || ""]), newToken]
|
||
);
|
||
token = insertC.rows[0].portal_token;
|
||
}
|
||
|
||
if (token) {
|
||
const linkMagico = `https://portal.integrarepara.es/?token=${token}`;
|
||
const msg = `âï¸ Hola ${client_name || "Cliente"},\n\nHemos *actualizado tu presupuesto*. El nuevo importe total es *${total}â¬*.\n\nð Puedes revisar los cambios y descargarlo de nuevo en PDF desde tu portal privado:\nð ${linkMagico}`;
|
||
|
||
const MODO_PRUEBAS = false;
|
||
const MI_TELEFONO = "34667248132";
|
||
|
||
if (MODO_PRUEBAS) {
|
||
console.log(`ð¡ï¸ [MODO PRUEBAS] Enviando WA de presupuesto modificado a (${MI_TELEFONO}) en lugar de al cliente`);
|
||
await sendWhatsAppAuto(MI_TELEFONO, `*(SIMULACIÃN PRESUPUESTO MODIFICADO PARA: ${finalPhoneToSend})*\n\n${msg}`, `cliente_${req.user.accountId}`, false);
|
||
} else {
|
||
console.log(`â
Enviando WA de presupuesto modificado al cliente: ${finalPhoneToSend}`);
|
||
await sendWhatsAppAuto(finalPhoneToSend, msg, `cliente_${req.user.accountId}`, false);
|
||
}
|
||
}
|
||
}
|
||
} catch (errWA) {
|
||
console.error("â Error enviando WA de presupuesto modificado:", errWA);
|
||
}
|
||
})();
|
||
} catch(e) {
|
||
console.error("Error al actualizar presupuesto:", e);
|
||
res.status(500).json({ ok: false, error: "Error en el servidor al actualizar" });
|
||
}
|
||
});
|
||
|
||
app.patch("/budgets/:id/status", authMiddleware, async (req, res) => {
|
||
try {
|
||
await pool.query("UPDATE budgets SET status=$1 WHERE id=$2 AND owner_id=$3", [req.body.status, req.params.id, req.user.accountId]);
|
||
res.json({ ok: true });
|
||
} catch(e) { res.status(500).json({ok: false}); }
|
||
});
|
||
// (DELETE /budgets/:id ya está registrado más arriba, junto con GET/POST/PUT /articles y GET /budgets â no se repite aquÃ)
|
||
|
||
// ==========================================
|
||
// ð¤ API COLA DEL ROBOT (REEMPLAZO FIREBASE)
|
||
// ==========================================
|
||
|
||
// 1. Enviar una orden al Robot
|
||
app.post("/robot/queue", authMiddleware, async (req, res) => {
|
||
try {
|
||
// AÃADIDO: Recogemos el provider y el appointment_time
|
||
const { provider, service_number, new_status, appointment_date, appointment_time, observation, inform_client } = req.body;
|
||
|
||
// Si no mandan provider (ej: App vieja), asumimos homeserve por retrocompatibilidad
|
||
const finalProvider = provider || 'homeserve';
|
||
|
||
// IMPORTANTE: Nos aseguramos de que la tabla tiene la columna de la hora para Multiasistencia
|
||
await pool.query(`ALTER TABLE robot_queue ADD COLUMN IF NOT EXISTS appointment_time TEXT;`).catch(() => {});
|
||
|
||
const q = await pool.query(`
|
||
INSERT INTO robot_queue (owner_id, provider, service_number, new_status, appointment_date, appointment_time, observation, inform_client)
|
||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING id
|
||
`, [
|
||
req.user.accountId,
|
||
finalProvider,
|
||
service_number,
|
||
new_status,
|
||
appointment_date || "",
|
||
appointment_time || "", // Nueva variable de hora
|
||
observation || "",
|
||
inform_client || false
|
||
]);
|
||
|
||
res.json({ ok: true, jobId: q.rows[0].id });
|
||
} catch (e) {
|
||
console.error("Error guardando en cola:", e);
|
||
res.status(500).json({ ok: false, error: e.message });
|
||
}
|
||
});
|
||
|
||
|
||
// 3. Obtener resumen de mensajes nuevos para el operario (Globo de Notificación)
|
||
app.get("/worker/notifications", authMiddleware, async (req, res) => {
|
||
try {
|
||
// Buscamos expedientes donde la fecha del último mensaje de ADMIN sea más reciente que la última lectura del operario
|
||
const q = await pool.query(`
|
||
SELECT DISTINCT s.id
|
||
FROM scraped_services s
|
||
JOIN service_communications c ON s.id = c.scraped_id
|
||
WHERE s.assigned_to = $1
|
||
AND c.sender_role IN ('admin', 'superadmin')
|
||
AND c.is_internal = FALSE
|
||
AND c.created_at > COALESCE(s.last_chat_read_worker, '2000-01-01')
|
||
`, [req.user.sub]);
|
||
|
||
res.json({ ok: true, unreadCount: q.rowCount, serviceIds: q.rows.map(r => r.id) });
|
||
} catch (e) {
|
||
console.error("Error notificaciones:", e);
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
// 4. Marcar chat como leÃdo por el operario
|
||
app.post("/services/:id/chat/read", authMiddleware, async (req, res) => {
|
||
try {
|
||
await pool.query(
|
||
"UPDATE scraped_services SET last_chat_read_worker = NOW() WHERE id = $1 AND assigned_to = $2",
|
||
[req.params.id, req.user.sub]
|
||
);
|
||
res.json({ ok: true });
|
||
} catch (e) {
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
// ==========================================
|
||
// ð¬ CHAT Y COMUNICACIÃN INTERNA (TIPO iTRAMIT)
|
||
// ==========================================
|
||
|
||
app.get("/services/:id/chat", authMiddleware, async (req, res) => {
|
||
try {
|
||
const { id } = req.params;
|
||
const isOperario = req.user.role === 'operario';
|
||
|
||
let query = `
|
||
SELECT id, sender_id, sender_name, sender_role, message, is_internal, created_at
|
||
FROM service_communications
|
||
WHERE scraped_id = $1 AND owner_id = $2
|
||
`;
|
||
|
||
if (isOperario) query += ` AND is_internal = FALSE`;
|
||
query += ` ORDER BY created_at ASC`;
|
||
|
||
const q = await pool.query(query, [id, req.user.accountId]);
|
||
res.json({ ok: true, messages: q.rows });
|
||
} catch (e) {
|
||
console.error("Error cargando chat:", e);
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
// 𩹠FIX: faltaba el endpoint para ENVIAR mensajes desde el panel (solo existÃa el de leer historial)
|
||
app.post("/services/:id/chat", authMiddleware, async (req, res) => {
|
||
try {
|
||
const { id } = req.params;
|
||
const { message, is_internal } = req.body;
|
||
|
||
if (!message || !message.toString().trim()) {
|
||
return res.status(400).json({ ok: false, error: "El mensaje está vacÃo" });
|
||
}
|
||
|
||
// Verificamos que el servicio pertenece a esta cuenta antes de escribir
|
||
const svcQ = await pool.query("SELECT id FROM scraped_services WHERE id=$1 AND owner_id=$2", [id, req.user.accountId]);
|
||
if (svcQ.rowCount === 0) return res.status(404).json({ ok: false, error: "Servicio no encontrado" });
|
||
|
||
const isOperario = req.user.role === 'operario' || req.user.role === 'operario_cerrado';
|
||
// Las notas internas son solo cosa de admin: un operario nunca puede marcar su mensaje como interno
|
||
const finalIsInternal = isOperario ? false : (is_internal === true || is_internal === 'true');
|
||
|
||
const userQ = await pool.query("SELECT full_name FROM users WHERE id=$1", [req.user.sub]);
|
||
const senderName = userQ.rows[0]?.full_name || (isOperario ? 'Operario' : 'Admin');
|
||
|
||
const insertQ = await pool.query(
|
||
`INSERT INTO service_communications (scraped_id, owner_id, sender_id, sender_name, sender_role, message, is_internal)
|
||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||
RETURNING id, sender_id, sender_name, sender_role, message, is_internal, created_at`,
|
||
[id, req.user.accountId, req.user.sub, senderName, req.user.role, message.toString().trim(), finalIsInternal]
|
||
);
|
||
|
||
res.json({ ok: true, message: insertQ.rows[0] });
|
||
} catch (e) {
|
||
console.error("Error enviando mensaje de chat:", e);
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
// ==========================================
|
||
// ð§¾ PARTES DE TRABAJO (texto con IA + firma + PDF + envÃo WhatsApp)
|
||
// ==========================================
|
||
|
||
// 1. Reescribe con IA el texto que escribe el operario, en un tono profesional
|
||
app.post("/work-reports/improve", authMiddleware, async (req, res) => {
|
||
try {
|
||
const { text } = req.body;
|
||
if (!text || !text.toString().trim()) return res.status(400).json({ ok: false, error: "Falta el texto" });
|
||
|
||
const completion = await openai.chat.completions.create({
|
||
model: OPENAI_MODEL || "gpt-4o-mini",
|
||
messages: [
|
||
{ role: "system", content: "Eres un técnico administrativo que redacta partes de trabajo profesionales para una empresa de reparaciones y mantenimiento del hogar. Reescribe las notas que te da el operario en un texto claro, profesional, ordenado y objetivo, en español, describiendo el diagnóstico y el trabajo realizado. No inventes datos que no te den. No uses markdown, ni asteriscos, ni listas con guiones. Máximo 120 palabras." },
|
||
{ role: "user", content: text.toString().trim() }
|
||
],
|
||
temperature: 0.4
|
||
});
|
||
|
||
const improved = completion.choices?.[0]?.message?.content?.trim();
|
||
if (!improved) return res.status(500).json({ ok: false, error: "La IA no ha devuelto ningún texto" });
|
||
res.json({ ok: true, text: improved });
|
||
} catch (e) {
|
||
console.error("â Error mejorando parte de trabajo con IA:", e.message);
|
||
res.status(500).json({ ok: false, error: "Error al contactar con la IA" });
|
||
}
|
||
});
|
||
|
||
// 2. Guarda un parte de trabajo ya generado (texto final + firma + PDF en base64)
|
||
app.post("/services/:id/work-report", authMiddleware, async (req, res) => {
|
||
try {
|
||
const { id } = req.params;
|
||
const { raw_text, final_text, signature_data, pdf_base64 } = req.body;
|
||
|
||
if (!final_text || !final_text.toString().trim()) return res.status(400).json({ ok: false, error: "Falta el texto del parte" });
|
||
if (!pdf_base64) return res.status(400).json({ ok: false, error: "Falta el PDF generado" });
|
||
|
||
const svcQ = await pool.query("SELECT * FROM scraped_services WHERE id=$1 AND owner_id=$2", [id, req.user.accountId]);
|
||
if (svcQ.rowCount === 0) return res.status(404).json({ ok: false, error: "Servicio no encontrado" });
|
||
const raw = svcQ.rows[0].raw_data || {};
|
||
|
||
const userQ = await pool.query("SELECT full_name FROM users WHERE id=$1", [req.user.sub]);
|
||
const operatorName = userQ.rows[0]?.full_name || "Operario";
|
||
|
||
const clientName = raw["Nombre Cliente"] || raw["CLIENTE"] || "";
|
||
const clientPhone = extractBestMobile(raw);
|
||
|
||
const insert = await pool.query(
|
||
`INSERT INTO work_reports (scraped_id, owner_id, operator_id, operator_name, client_name, client_phone, raw_text, final_text, signature_data, pdf_base64)
|
||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10) RETURNING id, created_at`,
|
||
[id, req.user.accountId, req.user.sub, operatorName, clientName, clientPhone, (raw_text || "").toString(), final_text.toString().trim(), signature_data || null, pdf_base64]
|
||
);
|
||
|
||
res.json({ ok: true, report: { id: insert.rows[0].id, created_at: insert.rows[0].created_at, client_phone: clientPhone, client_name: clientName } });
|
||
} catch (e) {
|
||
console.error("â Error guardando parte de trabajo:", e);
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
// 3. Lista el historial de partes de trabajo de un servicio (sin el PDF pesado)
|
||
app.get("/services/:id/work-reports", authMiddleware, async (req, res) => {
|
||
try {
|
||
const { id } = req.params;
|
||
const q = await pool.query(
|
||
`SELECT id, operator_name, final_text, client_phone, sent_to, created_at
|
||
FROM work_reports WHERE scraped_id=$1 AND owner_id=$2 ORDER BY created_at DESC`,
|
||
[id, req.user.accountId]
|
||
);
|
||
res.json({ ok: true, reports: q.rows });
|
||
} catch (e) {
|
||
console.error("â Error listando partes de trabajo:", e);
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
// 4. Devuelve el PDF en base64 de un parte concreto (para verlo o reenviarlo)
|
||
app.get("/work-reports/:id/pdf", authMiddleware, async (req, res) => {
|
||
try {
|
||
const q = await pool.query("SELECT pdf_base64, client_name FROM work_reports WHERE id=$1 AND owner_id=$2", [req.params.id, req.user.accountId]);
|
||
if (q.rowCount === 0) return res.status(404).json({ ok: false });
|
||
res.json({ ok: true, pdf_base64: q.rows[0].pdf_base64, client_name: q.rows[0].client_name });
|
||
} catch (e) {
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
// 5. EnvÃa por WhatsApp el PDF de un parte ya guardado. Si no se pasan teléfonos,
|
||
// se envÃa automáticamente al teléfono del cliente guardado en el parte.
|
||
app.post("/work-reports/:id/send", authMiddleware, async (req, res) => {
|
||
try {
|
||
const { id } = req.params;
|
||
let { phones } = req.body;
|
||
|
||
const q = await pool.query("SELECT * FROM work_reports WHERE id=$1 AND owner_id=$2", [id, req.user.accountId]);
|
||
if (q.rowCount === 0) return res.status(404).json({ ok: false, error: "Parte no encontrado" });
|
||
const report = q.rows[0];
|
||
|
||
if (!phones || !Array.isArray(phones) || phones.length === 0) {
|
||
phones = report.client_phone ? [report.client_phone] : [];
|
||
}
|
||
phones = phones.map(p => extractValidPhone(p)).filter(p => p && p.length >= 9);
|
||
if (phones.length === 0) return res.status(400).json({ ok: false, error: "No hay ningún teléfono válido al que enviar" });
|
||
|
||
const fileName = `Parte_Trabajo_${report.scraped_id}.pdf`;
|
||
const caption = `ð Parte de trabajo${report.client_name ? ` - ${report.client_name}` : ''}`;
|
||
|
||
const results = [];
|
||
for (const p of phones) {
|
||
const finalPhone = "34" + p;
|
||
const sendRes = await sendWhatsAppMedia(finalPhone, report.pdf_base64, fileName, caption, `cliente_${req.user.accountId}`);
|
||
results.push({ phone: finalPhone, ok: sendRes.ok, detail: sendRes.ok ? undefined : sendRes.detail });
|
||
}
|
||
|
||
const sentOk = results.filter(r => r.ok).map(r => r.phone);
|
||
if (sentOk.length > 0) {
|
||
const prevSent = Array.isArray(report.sent_to) ? report.sent_to : [];
|
||
const newSentTo = Array.from(new Set([...prevSent, ...sentOk]));
|
||
await pool.query("UPDATE work_reports SET sent_to=$1 WHERE id=$2", [JSON.stringify(newSentTo), id]);
|
||
}
|
||
|
||
res.json({ ok: sentOk.length > 0, results });
|
||
} catch (e) {
|
||
console.error("â Error enviando parte de trabajo por WhatsApp:", e);
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
// ð¤ WEBHOOK CON ESCUDO HUMANO, MEMORIA Y GESTIÃN DE URGENCIAS
|
||
// ð§ Ejecuta realmente el turno de la IA para un expediente (llamado tras el debounce)
|
||
async function procesarTurnoIA({ ownerId, service, mensajeTexto, telefonoCliente, instanceName }) {
|
||
if (candadosIA.has(service.id)) return;
|
||
candadosIA.add(service.id);
|
||
|
||
try {
|
||
// ð Si está pausada, no contestamos
|
||
if (service.ia_paused === true || service.ia_paused === 'true') {
|
||
console.log(`𤫠[IA MUTEADA] ${service.service_ref}`);
|
||
return;
|
||
}
|
||
|
||
// ð¡ï¸ Escudo humano: si alguien habló hace menos de 120 min, la IA se calla
|
||
const checkHumanQ = await pool.query(`
|
||
SELECT sender_role, created_at
|
||
FROM service_communications
|
||
WHERE scraped_id = $1
|
||
AND sender_role IN ('admin', 'superadmin', 'operario')
|
||
ORDER BY created_at DESC
|
||
LIMIT 1
|
||
`, [service.id]);
|
||
|
||
if (checkHumanQ.rowCount > 0) {
|
||
const lastMsg = checkHumanQ.rows[0];
|
||
const diffMinutos = (Date.now() - new Date(lastMsg.created_at).getTime()) / (1000 * 60);
|
||
|
||
if (diffMinutos >= 0 && diffMinutos < 120) {
|
||
console.log(`ð¡ï¸ [ESCUDO IA] Silenciada porque un humano habló hace ${Math.round(diffMinutos)} minutos.`);
|
||
return;
|
||
}
|
||
}
|
||
|
||
// ð§ LLAMADA A LA IA (el historial ya incluye, en orden, todos los mensajes que el cliente
|
||
// haya mandado seguidos durante la espera del debounce)
|
||
const respuestaIA = await procesarConIA(ownerId, mensajeTexto, {
|
||
dbId: service.id,
|
||
ref: service.service_ref,
|
||
estado: service.status_name || "En proceso",
|
||
operario: service.worker_name,
|
||
worker_id: service.assigned_to,
|
||
cita: service.cita,
|
||
hora_cita: service.hora_cita,
|
||
poblacion: service.poblacion || "",
|
||
cp: service.cp || "",
|
||
guild_id: service.guild_id || "",
|
||
gremio: service.gremio_nombre || "",
|
||
is_urgent: service.is_urgent,
|
||
appointment_status: service.appointment_status,
|
||
cita_pendiente_fecha: service.cita_pendiente_fecha,
|
||
cita_pendiente_hora: service.cita_pendiente_hora,
|
||
compania: service.compania,
|
||
averia: service.averia,
|
||
nombre_cliente: service.nombre_cliente || "",
|
||
direccion: service.direccion || "",
|
||
intake_mode: service.intake_mode || false,
|
||
intake_purpose: service.intake_purpose || "",
|
||
budget_mode: service.budget_mode || false,
|
||
budget_id: service.budget_id || null
|
||
});
|
||
|
||
if (!respuestaIA) return;
|
||
|
||
const matchPropuesta = respuestaIA.match(/\[PROPUESTA:\s*(\d{4}-\d{2}-\d{2})\s+(\d{2}:\d{2})\]/i);
|
||
let textoLimpio = respuestaIA
|
||
.replace(/\[PROPUESTA:.*?\]/gi, "")
|
||
.replace(/\n{3,}/g, "\n\n")
|
||
.trim();
|
||
|
||
// ð Si el técnico se acaba de auto-asignar en este mismo turno (flujo de
|
||
// captación de datos por comando de admin), "service.assigned_to" todavÃa
|
||
// tiene el valor de ANTES de esta llamada â lo refrescamos solo si hace falta.
|
||
let assignedToActual = service.assigned_to;
|
||
if (!assignedToActual) {
|
||
const freshAssignedQ = await pool.query("SELECT assigned_to FROM scraped_services WHERE id=$1", [service.id]);
|
||
assignedToActual = freshAssignedQ.rows[0]?.assigned_to || null;
|
||
}
|
||
|
||
if (matchPropuesta && assignedToActual) {
|
||
const fechaSugerida = matchPropuesta[1];
|
||
const horaSugerida = matchPropuesta[2];
|
||
|
||
const disponibilidad = await comprobarDisponibilidad(
|
||
ownerId,
|
||
assignedToActual,
|
||
fechaSugerida,
|
||
horaSugerida,
|
||
60,
|
||
service.id
|
||
);
|
||
|
||
if (disponibilidad.choca) {
|
||
console.log(`â [DOBLE-BOOKING EVITADO] ${service.service_ref} chocaba con ${disponibilidad.ref}`);
|
||
textoLimpio = "Uy, justo ese hueco ya no lo veo libre en el sistema. Dime otra hora y lo reviso.";
|
||
} else {
|
||
await pool.query(`
|
||
UPDATE scraped_services
|
||
SET raw_data = raw_data || jsonb_build_object(
|
||
'requested_date', $1::text,
|
||
'requested_time', $2::text,
|
||
'appointment_status', 'pending'
|
||
)
|
||
WHERE id = $3
|
||
`, [fechaSugerida, horaSugerida, service.id]);
|
||
|
||
// ð Si este expediente viene del comando de admin ("escribe a..."), le
|
||
// avisamos por WhatsApp en cuanto se cierra la cita con el cliente.
|
||
if (service.intake_purpose) {
|
||
try {
|
||
const adminPhoneQ2 = await pool.query("SELECT phone FROM users WHERE id = $1", [ownerId]);
|
||
const adminPhone = adminPhoneQ2.rows[0]?.phone;
|
||
if (adminPhone) {
|
||
const nombreParaAviso = service.nombre_cliente || "el cliente";
|
||
const avisoAdmin = `â
Cita propuesta con ${nombreParaAviso} (${telefonoCliente}) para el ${fechaSugerida} a las ${horaSugerida}, motivo: ${service.intake_purpose}. Expediente ${service.service_ref}.`;
|
||
sendWhatsAppAuto(adminPhone, avisoAdmin, instanceName, false).catch(console.error);
|
||
}
|
||
} catch (eAvisoAdmin) {
|
||
console.error("â Error avisando al admin de cita cerrada:", eAvisoAdmin.message);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
if (!textoLimpio) return;
|
||
|
||
await sendWhatsAppAuto(telefonoCliente, textoLimpio, instanceName, true);
|
||
|
||
await pool.query(`
|
||
INSERT INTO service_communications
|
||
(scraped_id, owner_id, sender_name, sender_role, message, is_internal)
|
||
VALUES ($1, $2, 'Asistente IA', 'ia', $3, false)
|
||
`, [service.id, ownerId, textoLimpio]);
|
||
|
||
} finally {
|
||
candadosIA.delete(service.id);
|
||
}
|
||
}
|
||
|
||
// ð COMANDOS DE ADMIN POR WHATSAPP: solo se llega aquà si el mensaje viene del móvil
|
||
// personal del dueño de la cuenta (ya comprobado en el webhook). De momento entiende
|
||
// un único comando: "escribe/manda un mensaje a [teléfono]", que arranca una toma de
|
||
// contacto con un cliente nuevo o potencial y va recogiendo sus datos con la IA hasta
|
||
// poder ofrecerle cita, igual que con cualquier otro cliente.
|
||
async function manejarComandoAdmin({ ownerId, mensajeTexto, esAudioSinTexto, telefonoAdmin, instanceName }) {
|
||
if (esAudioSinTexto) {
|
||
sendWhatsAppAuto(telefonoAdmin, "ðï¸ No puedo escuchar audios, escrÃbemelo en un mensaje de texto, por favor.", instanceName, false).catch(console.error);
|
||
return;
|
||
}
|
||
|
||
const texto = (mensajeTexto || "").trim();
|
||
if (!texto) return;
|
||
|
||
const pending = adminIntakeState.get(ownerId);
|
||
|
||
// 2º paso: ya habÃamos preguntado el motivo, asà que este mensaje ES el motivo.
|
||
if (pending && pending.step === 'awaiting_purpose') {
|
||
adminIntakeState.delete(ownerId);
|
||
const purpose = texto;
|
||
|
||
try {
|
||
const empresaQ = await pool.query("SELECT full_name FROM users WHERE id=$1", [ownerId]);
|
||
const empresaNombre = empresaQ.rows[0]?.full_name || "nuestra empresa";
|
||
|
||
const serviceReference = `M-${Date.now().toString().slice(-6)}`;
|
||
const rawData = {
|
||
"Nombre Cliente": "",
|
||
"Teléfono": pending.targetPhone,
|
||
"Dirección": "",
|
||
"Descripción": "",
|
||
"guild_id": null,
|
||
"CompañÃa": "Particular",
|
||
"Origen": "WhatsApp Admin",
|
||
"intake_mode": true,
|
||
"intake_purpose": purpose
|
||
};
|
||
|
||
const insertSvc = await pool.query(
|
||
`INSERT INTO scraped_services (owner_id, provider, service_ref, status, automation_status, raw_data)
|
||
VALUES ($1, 'MANUAL', $2, 'pending', 'manual', $3) RETURNING id`,
|
||
[ownerId, serviceReference, JSON.stringify(rawData)]
|
||
);
|
||
const newServiceId = insertSvc.rows[0].id;
|
||
|
||
const finalPhone = "34" + pending.targetPhone;
|
||
const mensajeApertura = `Hola, soy el asistente virtual (IA) de ${empresaNombre}. Le contactamos para tramitar su solicitud de ${purpose}. Para poder ayudarle, ¿nos indica su nombre completo y la dirección exacta de la visita?`;
|
||
|
||
await sendWhatsAppAuto(finalPhone, mensajeApertura, instanceName, false);
|
||
|
||
await pool.query(`
|
||
INSERT INTO service_communications
|
||
(scraped_id, owner_id, sender_name, sender_role, message, is_internal)
|
||
VALUES ($1, $2, 'Asistente IA', 'ia', $3, false)
|
||
`, [newServiceId, ownerId, mensajeApertura]);
|
||
|
||
await sendWhatsAppAuto(telefonoAdmin, `â
Mensaje enviado a ${pending.targetPhone}. En cuanto conteste, sigo yo recogiendo los datos y te aviso cuando quede la cita.`, instanceName, false);
|
||
} catch (e) {
|
||
console.error("â Error iniciando captación de datos por comando de admin:", e.message);
|
||
sendWhatsAppAuto(telefonoAdmin, "â No he podido iniciar la conversación, revisa el log.", instanceName, false).catch(console.error);
|
||
}
|
||
return;
|
||
}
|
||
|
||
// 1er paso: ¿es un comando para iniciar conversación con un número nuevo?
|
||
const esComandoInicio = /\b(escribe|escr[Ãi]bele|manda|mand[aá]le|env[Ãi]a|env[Ãi]ale|contacta)\b/i.test(texto);
|
||
const telefonoMatch = texto.match(/(\d[\d\s\-]{7,13}\d)/);
|
||
let telefonoExtraido = null;
|
||
if (telefonoMatch) {
|
||
const digits = telefonoMatch[1].replace(/\D/g, "");
|
||
if (digits.length === 9) telefonoExtraido = digits;
|
||
else if (digits.length > 9) telefonoExtraido = digits.slice(-9);
|
||
}
|
||
|
||
if (esComandoInicio && telefonoExtraido) {
|
||
adminIntakeState.set(ownerId, { step: 'awaiting_purpose', targetPhone: telefonoExtraido });
|
||
await sendWhatsAppAuto(telefonoAdmin, `De acuerdo. ¿Cuál es el motivo del contacto con el ${telefonoExtraido}? (por ejemplo: averÃa, presupuesto de visita, u otro)`, instanceName, false);
|
||
return;
|
||
}
|
||
|
||
// No reconocido como comando: no hacemos nada, para no ser un incordio si escribe
|
||
// algo sin relación con esto desde su propio móvil.
|
||
}
|
||
|
||
app.post("/webhook/evolution", async (req, res) => {
|
||
try {
|
||
const data = req.body;
|
||
|
||
if (data.event !== "messages.upsert") {
|
||
return res.sendStatus(200);
|
||
}
|
||
|
||
const remoteJid = data?.data?.key?.remoteJid || "";
|
||
const fromMe = !!data?.data?.key?.fromMe;
|
||
const instanceName = data?.instance || "";
|
||
const mensajeTexto = (
|
||
data?.data?.message?.conversation ||
|
||
data?.data?.message?.extendedTextMessage?.text ||
|
||
""
|
||
).trim();
|
||
|
||
// ðï¸ Notas de voz: no las transcribimos (todavÃa), pero al menos lo detectamos
|
||
// para poder avisar en vez de ignorarlo en silencio como pasaba antes.
|
||
const esAudioSinTexto = !mensajeTexto && !!data?.data?.message?.audioMessage;
|
||
|
||
if ((!mensajeTexto && !esAudioSinTexto) || !remoteJid || !instanceName) {
|
||
return res.sendStatus(200);
|
||
}
|
||
|
||
// Ignorar grupos, estados y cosas raras
|
||
if (!/@s\.whatsapp\.net$/i.test(remoteJid)) {
|
||
return res.sendStatus(200);
|
||
}
|
||
|
||
// Respondemos rápido a Evolution
|
||
res.sendStatus(200);
|
||
|
||
if (!/^cliente_\d+$/.test(instanceName)) {
|
||
console.log(`â ï¸ [WEBHOOK IA] Instancia ignorada: ${instanceName}`);
|
||
return;
|
||
}
|
||
|
||
const ownerId = parseInt(instanceName.replace("cliente_", ""), 10);
|
||
if (!ownerId) return;
|
||
|
||
const telefonoCliente = remoteJid.split("@")[0];
|
||
const cleanPhone = telefonoCliente.replace(/\D/g, "").slice(-9);
|
||
if (!cleanPhone || cleanPhone.length < 9) return;
|
||
|
||
// ð COMANDOS DE ADMINISTRADOR: si quien escribe es el propio dueño de la cuenta
|
||
// desde su móvil personal (no el número de WhatsApp Business, sino un contacto
|
||
// externo que resulta ser su teléfono registrado), lo tratamos aparte y no sigue
|
||
// el flujo normal de cliente/expediente.
|
||
if (!fromMe) {
|
||
try {
|
||
const adminPhoneQ = await pool.query("SELECT phone FROM users WHERE id = $1", [ownerId]);
|
||
const adminPhoneClean = (adminPhoneQ.rows[0]?.phone || "").replace(/\D/g, "").slice(-9);
|
||
if (adminPhoneClean && adminPhoneClean === cleanPhone) {
|
||
const pendingAdmin = adminIntakeState.get(ownerId);
|
||
const pareceComandoNuevo = /\b(escribe|escr[Ãi]bele|manda|mand[aá]le|env[Ãi]a|env[Ãi]ale|contacta)\b/i.test((mensajeTexto || "").trim());
|
||
|
||
// ð Si el admin usa su propio número también como "cliente" (p.ej. para
|
||
// probar el flujo escribiéndose a sà mismo) y ya hay un expediente abierto
|
||
// con ese mismo teléfono, dejamos que el mensaje siga el flujo normal de
|
||
// cliente en vez de tratarlo siempre como comando â si no, cualquier
|
||
// respuesta suya como "cliente" se la comÃa este bloque en silencio.
|
||
// Seguimos tratándolo como comando de admin si está en medio del diálogo
|
||
// de alta (esperando el motivo) o si el texto parece un comando nuevo.
|
||
let hayExpedienteAbierto = false;
|
||
if (!pendingAdmin && !pareceComandoNuevo) {
|
||
const abiertoQ = await pool.query(`
|
||
SELECT 1 FROM scraped_services
|
||
WHERE owner_id = $1 AND status != 'archived'
|
||
AND RIGHT(REGEXP_REPLACE(COALESCE(raw_data->>'Teléfono', raw_data->>'TELEFONO', raw_data->>'TELEFONOS', ''), '\\D', '', 'g'), 9) = $2
|
||
LIMIT 1
|
||
`, [ownerId, cleanPhone]);
|
||
hayExpedienteAbierto = abiertoQ.rowCount > 0;
|
||
}
|
||
|
||
if (pendingAdmin || pareceComandoNuevo || !hayExpedienteAbierto) {
|
||
await manejarComandoAdmin({ ownerId, mensajeTexto, esAudioSinTexto, telefonoAdmin: telefonoCliente, instanceName });
|
||
return;
|
||
}
|
||
// Si no: no hacemos return, dejamos caer al flujo normal de cliente de abajo.
|
||
}
|
||
} catch (eAdmin) {
|
||
console.error("â Error comprobando comando de admin:", eAdmin.message);
|
||
}
|
||
}
|
||
|
||
// ð BUSCAMOS EL EXPEDIENTE ACTIVO MÃS RECIENTE POR TELÃFONO REAL
|
||
const svcQuerySQL = `
|
||
SELECT
|
||
s.id,
|
||
s.service_ref,
|
||
s.assigned_to,
|
||
s.is_urgent,
|
||
u.full_name as worker_name,
|
||
st.name as status_name,
|
||
COALESCE(s.raw_data->>'scheduled_date', '') as cita,
|
||
COALESCE(s.raw_data->>'scheduled_time', '') as hora_cita,
|
||
COALESCE(s.raw_data->>'Población', s.raw_data->>'POBLACION-PROVINCIA', '') as poblacion,
|
||
COALESCE(s.raw_data->>'Código Postal', s.raw_data->>'C.P.', '') as cp,
|
||
COALESCE(s.raw_data->>'guild_id', '') as guild_id,
|
||
COALESCE((SELECT name FROM guilds WHERE id::text = s.raw_data->>'guild_id' LIMIT 1), '') as gremio_nombre,
|
||
COALESCE(s.raw_data->>'appointment_status', '') as appointment_status,
|
||
COALESCE(s.raw_data->>'requested_date', '') as cita_pendiente_fecha,
|
||
COALESCE(s.raw_data->>'requested_time', '') as cita_pendiente_hora,
|
||
COALESCE(s.raw_data->>'CompañÃa', s.raw_data->>'COMPAÃIA', '') as compania,
|
||
COALESCE(s.raw_data->>'Descripción', s.raw_data->>'DESCRIPCION', '') as averia,
|
||
COALESCE(s.raw_data->>'Nombre Cliente', '') as nombre_cliente,
|
||
COALESCE(s.raw_data->>'Dirección', '') as direccion,
|
||
COALESCE(s.raw_data->>'intake_purpose', '') as intake_purpose,
|
||
CASE
|
||
WHEN LOWER(COALESCE(s.raw_data->>'intake_mode', 'false')) IN ('true', 't', '1') THEN true
|
||
ELSE false
|
||
END as intake_mode,
|
||
CASE
|
||
WHEN LOWER(COALESCE(s.raw_data->>'budget_mode', 'false')) IN ('true', 't', '1') THEN true
|
||
ELSE false
|
||
END as budget_mode,
|
||
NULLIF(s.raw_data->>'budget_id', '')::int as budget_id,
|
||
CASE
|
||
WHEN LOWER(COALESCE(s.raw_data->>'ia_paused', 'false')) IN ('true', 't', '1') THEN true
|
||
ELSE false
|
||
END as ia_paused
|
||
FROM scraped_services s
|
||
LEFT JOIN users u ON s.assigned_to = u.id
|
||
LEFT JOIN service_statuses st ON (s.raw_data->>'status_operativo')::text = st.id::text
|
||
WHERE s.owner_id = $1
|
||
AND s.status != 'archived'
|
||
AND RIGHT(
|
||
REGEXP_REPLACE(
|
||
COALESCE(
|
||
s.raw_data->>'Teléfono',
|
||
s.raw_data->>'TELEFONO',
|
||
s.raw_data->>'TELEFONOS',
|
||
''
|
||
),
|
||
'\\D',
|
||
'',
|
||
'g'
|
||
),
|
||
9
|
||
) = $2
|
||
AND (
|
||
st.name IS NULL OR (
|
||
st.name NOT ILIKE '%finalizado%' AND
|
||
st.name NOT ILIKE '%anulado%' AND
|
||
st.name NOT ILIKE '%desasignado%'
|
||
)
|
||
)
|
||
ORDER BY
|
||
(SELECT MAX(sc.created_at) FROM service_communications sc WHERE sc.scraped_id = s.id) DESC NULLS LAST,
|
||
s.created_at DESC
|
||
LIMIT 1
|
||
`;
|
||
|
||
let svcQ = await pool.query(svcQuerySQL, [ownerId, cleanPhone]);
|
||
|
||
if (svcQ.rowCount === 0) {
|
||
// ð° Sin expediente activo: ¿tiene un presupuesto nuestro sin convertir
|
||
// todavÃa con este mismo teléfono? Si es asÃ, le abrimos un expediente
|
||
// "modo presupuesto" para que la IA pueda resolver dudas sobre él (y, en
|
||
// cuanto esté aceptado, asignar técnico y ofrecer cita como cualquier otro).
|
||
let presupuestoCreado = false;
|
||
try {
|
||
const budgetQ = await pool.query(`
|
||
SELECT * FROM budgets
|
||
WHERE owner_id = $1 AND status != 'converted'
|
||
AND RIGHT(REGEXP_REPLACE(COALESCE(client_phone, ''), '\\D', '', 'g'), 9) = $2
|
||
ORDER BY created_at DESC LIMIT 1
|
||
`, [ownerId, cleanPhone]);
|
||
|
||
if (budgetQ.rowCount > 0) {
|
||
if (esAudioSinTexto && !fromMe) {
|
||
// El cliente ha mandado un audio: de momento no lo procesamos, lo ignoramos sin contestar nada.
|
||
return;
|
||
}
|
||
if (!fromMe) {
|
||
const budget = budgetQ.rows[0];
|
||
const itemsTexto = Array.isArray(budget.items)
|
||
? budget.items.map(i => `${i.qty || 1}x ${i.concept || ''}`).join("\n")
|
||
: "";
|
||
const rawDataPresupuesto = {
|
||
"Nombre Cliente": budget.client_name || "",
|
||
"Teléfono": budget.client_phone || telefonoCliente,
|
||
"Dirección": budget.client_address || "",
|
||
"Descripción": `Presupuesto PRE-${budget.id}:\n${itemsTexto}`,
|
||
"CompañÃa": "Particular",
|
||
"Origen": "WhatsApp Presupuesto",
|
||
"budget_mode": true,
|
||
"budget_id": budget.id
|
||
};
|
||
await pool.query(
|
||
`INSERT INTO scraped_services (owner_id, provider, service_ref, status, automation_status, raw_data)
|
||
VALUES ($1, 'MANUAL', $2, 'pending', 'manual', $3)`,
|
||
[ownerId, `PRE-${budget.id}`, JSON.stringify(rawDataPresupuesto)]
|
||
);
|
||
console.log(`ð° [PRESUPUESTO] Expediente placeholder creado para PRE-${budget.id} (owner ${ownerId})`);
|
||
presupuestoCreado = true;
|
||
}
|
||
}
|
||
} catch (eBudgetLookup) {
|
||
console.error("â Error comprobando presupuesto pendiente:", eBudgetLookup.message);
|
||
}
|
||
|
||
if (presupuestoCreado) {
|
||
svcQ = await pool.query(svcQuerySQL, [ownerId, cleanPhone]);
|
||
}
|
||
|
||
if (svcQ.rowCount === 0) {
|
||
console.log(`â ï¸ [WEBHOOK IA] No se encontró expediente activo para ${cleanPhone}`);
|
||
return;
|
||
}
|
||
}
|
||
|
||
const service = svcQ.rows[0];
|
||
|
||
// ðï¸ Si el CLIENTE manda un audio, todavÃa no sabemos transcribirlo: se lo
|
||
// decimos directamente en vez de dejarlo sin respuesta como pasaba antes.
|
||
if (esAudioSinTexto && !fromMe) {
|
||
// El cliente ha mandado un audio: de momento no lo procesamos, lo ignoramos sin contestar nada.
|
||
return;
|
||
}
|
||
|
||
// ==========================================
|
||
// ð§âð§ MENSAJES TUYOS / ADMIN / OFICINA
|
||
// ==========================================
|
||
if (fromMe) {
|
||
const msgCmd = mensajeTexto.trim();
|
||
|
||
// ð´ PAUSAR IA
|
||
if (msgCmd.includes("ð´")) {
|
||
try {
|
||
await pool.query(`
|
||
UPDATE scraped_services
|
||
SET raw_data = COALESCE(raw_data, '{}'::jsonb) || '{"ia_paused": true}'::jsonb
|
||
WHERE id = $1
|
||
`, [service.id]);
|
||
|
||
await pool.query(`
|
||
INSERT INTO service_communications
|
||
(scraped_id, owner_id, sender_name, sender_role, message, is_internal)
|
||
VALUES ($1, $2, 'Sistema', 'system', $3, true)
|
||
`, [service.id, ownerId, "ð´ IA Pausada manualmente con Emoji."]);
|
||
|
||
console.log(`ð´ [IA PAUSADA] ${service.service_ref}`);
|
||
} catch (err) {
|
||
console.error("Error pausando IA:", err);
|
||
}
|
||
return;
|
||
}
|
||
|
||
// ð¢ REACTIVAR IA
|
||
if (msgCmd.includes("ð¢")) {
|
||
try {
|
||
await pool.query(`
|
||
UPDATE scraped_services
|
||
SET raw_data = raw_data - 'ia_paused'
|
||
WHERE id = $1
|
||
`, [service.id]);
|
||
|
||
await pool.query(`
|
||
INSERT INTO service_communications
|
||
(scraped_id, owner_id, sender_name, sender_role, message, is_internal)
|
||
VALUES ($1, $2, 'Sistema', 'system', $3, true)
|
||
`, [service.id, ownerId, "ð¢ IA Reactivada manualmente con Emoji."]);
|
||
|
||
console.log(`ð¢ [IA ACTIVADA] ${service.service_ref}`);
|
||
} catch (err) {
|
||
console.error("Error activando IA:", err);
|
||
}
|
||
return;
|
||
}
|
||
|
||
// Guardamos mensajes humanos salientes
|
||
try {
|
||
await pool.query(`
|
||
INSERT INTO service_communications
|
||
(scraped_id, owner_id, sender_name, sender_role, message, is_internal)
|
||
VALUES ($1, $2, 'Técnico (WhatsApp)', 'operario', $3, false)
|
||
`, [service.id, ownerId, mensajeTexto]);
|
||
} catch (err) {
|
||
console.error("Error guardando mensaje humano saliente:", err);
|
||
}
|
||
|
||
return;
|
||
}
|
||
|
||
// ==========================================
|
||
// ð¤ MENSAJE ENTRANTE DEL CLIENTE
|
||
// ==========================================
|
||
try {
|
||
await pool.query(`
|
||
INSERT INTO service_communications
|
||
(scraped_id, owner_id, sender_name, sender_role, message, is_internal)
|
||
VALUES ($1, $2, 'Cliente', 'user', $3, false)
|
||
`, [service.id, ownerId, mensajeTexto]);
|
||
} catch (err) {
|
||
console.error("Error guardando mensaje del cliente:", err);
|
||
}
|
||
|
||
// ð Debounce: si el cliente manda varios mensajes seguidos, esperamos a que haga
|
||
// una pausa antes de contestar, para no fragmentar ni duplicar respuestas.
|
||
if (debounceTimersIA.has(service.id)) {
|
||
clearTimeout(debounceTimersIA.get(service.id));
|
||
}
|
||
|
||
const timerIA = setTimeout(() => {
|
||
debounceTimersIA.delete(service.id);
|
||
procesarTurnoIA({ ownerId, service, mensajeTexto, telefonoCliente, instanceName })
|
||
.catch(err => console.error("â [WEBHOOK IA DIFERIDA] Error:", err));
|
||
}, IA_DEBOUNCE_MS);
|
||
|
||
debounceTimersIA.set(service.id, timerIA);
|
||
|
||
} catch (e) {
|
||
console.error("â [WEBHOOK ERROR]:", e);
|
||
if (!res.headersSent) return res.sendStatus(200);
|
||
}
|
||
});
|
||
|
||
// ==========================================
|
||
// âï¸ 5. RUTA PARA ACEPTAR/RECHAZAR Y FIRMAR PRESUPUESTOS
|
||
// ==========================================
|
||
app.post("/public/portal/:token/budget/:id/respond", async (req, res) => {
|
||
try {
|
||
const { token, id } = req.params;
|
||
const { action, signature } = req.body;
|
||
|
||
const clientQ = await pool.query("SELECT owner_id, full_name, phone FROM clients WHERE portal_token = $1", [token]);
|
||
if (clientQ.rowCount === 0) return res.status(404).json({ ok: false });
|
||
const ownerId = clientQ.rows[0].owner_id;
|
||
|
||
await pool.query(`ALTER TABLE budgets ADD COLUMN IF NOT EXISTS signature TEXT;`).catch(()=>{});
|
||
|
||
const newStatus = action === 'accept' ? 'accepted' : 'rejected';
|
||
await pool.query(
|
||
"UPDATE budgets SET status = $1, signature = $2 WHERE id = $3 AND owner_id = $4",
|
||
[newStatus, signature || null, id, ownerId]
|
||
);
|
||
|
||
const ownerData = await pool.query("SELECT phone FROM users WHERE id = $1", [ownerId]);
|
||
const bQ = await pool.query("SELECT client_name, total FROM budgets WHERE id = $1", [id]);
|
||
|
||
if (ownerData.rowCount > 0 && bQ.rowCount > 0) {
|
||
const adminPhone = ownerData.rows[0].phone;
|
||
const bInfo = bQ.rows[0];
|
||
|
||
const msgWa = action === 'accept'
|
||
? `ð¢ *PRESUPUESTO ACEPTADO*\nEl cliente ${bInfo.client_name} ha ACEPTADO y firmado el presupuesto PRE-${id} por ${bInfo.total}â¬.`
|
||
: `ð´ *PRESUPUESTO RECHAZADO*\nEl cliente ${bInfo.client_name} ha RECHAZADO el presupuesto PRE-${id}.`;
|
||
|
||
sendWhatsAppAuto(adminPhone, msgWa, `cliente_${ownerId}`, false).catch(console.error);
|
||
}
|
||
|
||
res.json({ ok: true });
|
||
} catch (e) {
|
||
console.error("Error firmando presupuesto:", e);
|
||
res.status(500).json({ ok: false });
|
||
}
|
||
});
|
||
|
||
// ==========================================
|
||
// ð³ 6. MOTOR DE PAGOS (STRIPE) PARA PRESUPUESTOS Y FACTURAS
|
||
// ==========================================
|
||
|
||
app.post("/public/portal/:token/budget/:id/checkout", async (req, res) => {
|
||
try {
|
||
const { token, id } = req.params;
|
||
|
||
// 1. Identificar al cliente y su empresa (dueño)
|
||
const clientQ = await pool.query("SELECT owner_id, full_name, phone FROM clients WHERE portal_token = $1", [token]);
|
||
if (clientQ.rowCount === 0) return res.status(404).json({ ok: false, error: "Token inválido" });
|
||
const ownerId = clientQ.rows[0].owner_id;
|
||
|
||
// 2. Extraer datos del presupuesto
|
||
const bQ = await pool.query("SELECT * FROM budgets WHERE id = $1 AND owner_id = $2", [id, ownerId]);
|
||
if (bQ.rowCount === 0) return res.status(404).json({ ok: false, error: "Presupuesto no encontrado" });
|
||
const budget = bQ.rows[0];
|
||
|
||
// 3. Extraer las claves secretas de Stripe de ESA EMPRESA EN CONCRETO (Modo SaaS)
|
||
const ownerQ = await pool.query("SELECT billing_settings FROM users WHERE id = $1", [ownerId]);
|
||
const billingSettings = ownerQ.rows[0]?.billing_settings || {};
|
||
|
||
if (!billingSettings.stripe_enabled || !billingSettings.stripe_sk) {
|
||
return res.status(400).json({ ok: false, error: "Los pagos con tarjeta no están habilitados para esta empresa." });
|
||
}
|
||
|
||
// 4. Iniciar Stripe de forma dinámica con la llave del cliente
|
||
const stripe = new Stripe(billingSettings.stripe_sk, { apiVersion: "2023-10-16" });
|
||
|
||
// 5. Crear la ventana mágica de pago (Checkout Session)
|
||
const session = await stripe.checkout.sessions.create({
|
||
payment_method_types: ['card'],
|
||
customer_email: budget.client_email || undefined, // Opcional, si tienes su email
|
||
line_items: [
|
||
{
|
||
price_data: {
|
||
currency: 'eur',
|
||
product_data: {
|
||
name: `Presupuesto #PRE-${budget.id}`,
|
||
description: `Servicios de asistencia técnica para ${budget.client_name}`,
|
||
},
|
||
unit_amount: Math.round(budget.total * 100), // Stripe cobra en céntimos (84.70⬠= 8470)
|
||
},
|
||
quantity: 1,
|
||
},
|
||
],
|
||
mode: 'payment',
|
||
// Enviaremos metadatos para saber exactamente qué han pagado cuando Stripe nos avise de vuelta
|
||
metadata: {
|
||
budget_id: budget.id,
|
||
owner_id: ownerId,
|
||
client_phone: budget.client_phone
|
||
},
|
||
// Redirecciones tras el pago
|
||
success_url: `https://portal.integrarepara.es/pago_exito.html?budget_id=${budget.id}`,
|
||
cancel_url: `https://portal.integrarepara.es/?token=${token}`,
|
||
});
|
||
|
||
// 6. Devolvemos el link seguro de Stripe al frontend para que redirija al cliente
|
||
res.json({ ok: true, checkout_url: session.url });
|
||
|
||
} catch (e) {
|
||
console.error("â Error creando sesión de Stripe:", e);
|
||
res.status(500).json({ ok: false, error: e.message });
|
||
}
|
||
});
|
||
|
||
|
||
// ==========================================
|
||
// ð¡ï¸ MÃDULO SAAS: PLANES DE PROTECCIÃN
|
||
// ==========================================
|
||
|
||
// 1. DASHBOARD: EstadÃsticas
|
||
app.get("/protection/dashboard", authMiddleware, async (req, res) => {
|
||
const cid = req.user.accountId;
|
||
try {
|
||
const [statsQ, actQ, topQ] = await Promise.all([
|
||
pool.query(`
|
||
SELECT
|
||
(SELECT COUNT(*) FROM protection_subscriptions WHERE company_id = $1) as total,
|
||
(SELECT COALESCE(SUM(p.price), 0) FROM protection_subscriptions s JOIN protection_plans p ON s.plan_id = p.id WHERE s.company_id = $1 AND s.status = 'activo') as mrr,
|
||
(SELECT COALESCE(SUM(urgencies_used), 0) FROM protection_subscriptions WHERE company_id = $1) as urgUsed,
|
||
(SELECT COALESCE(SUM(bricos_used), 0) FROM protection_subscriptions WHERE company_id = $1) as briUsed,
|
||
(SELECT COUNT(*) FROM protection_subscriptions WHERE company_id = $1 AND payment_status = 'impagado') as unpaid
|
||
`, [cid]),
|
||
pool.query("SELECT * FROM protection_activity WHERE company_id = $1 ORDER BY created_at DESC LIMIT 10", [cid]),
|
||
pool.query(`
|
||
SELECT p.*, COUNT(s.id) as users
|
||
FROM protection_plans p
|
||
LEFT JOIN protection_subscriptions s ON p.id = s.plan_id
|
||
WHERE p.company_id = $1
|
||
GROUP BY p.id
|
||
`, [cid])
|
||
]);
|
||
|
||
res.json({ ok: true, stats: statsQ.rows[0], activity: actQ.rows, topPlans: topQ.rows });
|
||
} catch (e) { res.status(500).json({ ok: false, error: e.message }); }
|
||
});
|
||
|
||
// 2. PLANES
|
||
app.get("/protection/plans", authMiddleware, async (req, res) => {
|
||
try {
|
||
const q = await pool.query("SELECT * FROM protection_plans WHERE company_id = $1 ORDER BY created_at DESC", [req.user.accountId]);
|
||
res.json({ ok: true, plans: q.rows });
|
||
} catch (e) { res.status(500).json({ ok: false, error: e.message }); }
|
||
});
|
||
|
||
app.post("/protection/plans", authMiddleware, async (req, res) => {
|
||
const cid = req.user.accountId;
|
||
const { name, type, price, renewal, urgencies, bricos, coverages } = req.body;
|
||
try {
|
||
await pool.query(
|
||
"INSERT INTO protection_plans (company_id, name, type, price, renewal_price, urgencies_limit, bricos_limit, coverages) VALUES ($1,$2,$3,$4,$5,$6,$7,$8)",
|
||
[cid, name, type, price, renewal, urgencies, bricos, coverages]
|
||
);
|
||
await pool.query("INSERT INTO protection_activity (company_id, type, description) VALUES ($1, 'alta', $2)", [cid, `Nuevo plan creado: ${name}`]);
|
||
res.json({ ok: true });
|
||
} catch (e) { res.status(500).json({ ok: false, error: e.message }); }
|
||
});
|
||
|
||
// 3. SUSCRIPTORES
|
||
app.get("/protection/subscribers", authMiddleware, async (req, res) => {
|
||
try {
|
||
const q = await pool.query(`
|
||
SELECT s.*, p.name as plan_name, p.price as plan_price, p.urgencies_limit, p.bricos_limit
|
||
FROM protection_subscriptions s
|
||
LEFT JOIN protection_plans p ON s.plan_id = p.id
|
||
WHERE s.company_id = $1 ORDER BY s.created_at DESC
|
||
`, [req.user.accountId]);
|
||
res.json({ ok: true, subscribers: q.rows });
|
||
} catch (e) { res.status(500).json({ ok: false, error: e.message }); }
|
||
});
|
||
|
||
app.post("/protection/subscribers", authMiddleware, async (req, res) => {
|
||
const cid = req.user.accountId;
|
||
const { plan_id, name, dni, phone, payment_status, status, renewal_date, bricos_used, urgencies_used } = req.body;
|
||
|
||
try {
|
||
const d = renewal_date ? renewal_date : null;
|
||
await pool.query(
|
||
`INSERT INTO protection_subscriptions
|
||
(company_id, plan_id, client_name, client_dni, client_phone, payment_status, status, renewal_date, bricos_used, urgencies_used)
|
||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`,
|
||
[cid, plan_id, name, dni, phone, payment_status, status, d, bricos_used, urgencies_used]
|
||
);
|
||
await pool.query("INSERT INTO protection_activity (company_id, type, description) VALUES ($1, 'alta', $2)", [cid, `Suscripción creada: ${name}`]);
|
||
res.json({ ok: true });
|
||
} catch (e) { res.status(500).json({ ok: false, error: e.message }); }
|
||
});
|
||
|
||
app.put("/protection/subscribers/:id/toggle", authMiddleware, async (req, res) => {
|
||
const cid = req.user.accountId;
|
||
const { id } = req.params;
|
||
const { field, value } = req.body;
|
||
try {
|
||
if (!['payment_status', 'status'].includes(field)) throw new Error("Invalid field");
|
||
await pool.query(`UPDATE protection_subscriptions SET ${field} = $1 WHERE id = $2 AND company_id = $3`, [value, id, cid]);
|
||
await pool.query("INSERT INTO protection_activity (company_id, type, description) VALUES ($1, 'cobro', $2)", [cid, `Cambiado a ${value} en ID: ${id}`]);
|
||
res.json({ ok: true });
|
||
} catch (e) { res.status(500).json({ ok: false, error: e.message }); }
|
||
});
|
||
|
||
// 4. CONFIGURACIÃN
|
||
app.get("/protection/config", authMiddleware, async (req, res) => {
|
||
try {
|
||
const q = await pool.query("SELECT * FROM protection_config WHERE company_id = $1", [req.user.accountId]);
|
||
res.json({ ok: true, config: q.rows[0] || {} });
|
||
} catch (e) { res.status(500).json({ ok: false, error: e.message }); }
|
||
});
|
||
|
||
app.post("/protection/config", authMiddleware, async (req, res) => {
|
||
const cid = req.user.accountId;
|
||
const { name, email, phone, auto_renew, pre_notice, billing_method, contract_text } = req.body;
|
||
try {
|
||
await pool.query(`
|
||
INSERT INTO protection_config (company_id, name, email, phone, auto_renew, pre_notice, billing_method, contract_text)
|
||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8) ON CONFLICT (company_id) DO UPDATE SET
|
||
name=EXCLUDED.name, email=EXCLUDED.email, phone=EXCLUDED.phone, auto_renew=EXCLUDED.auto_renew,
|
||
pre_notice=EXCLUDED.pre_notice, billing_method=EXCLUDED.billing_method, contract_text=EXCLUDED.contract_text
|
||
`, [cid, name, email, phone, auto_renew, pre_notice, billing_method, contract_text]);
|
||
res.json({ ok: true });
|
||
} catch (e) { res.status(500).json({ ok: false, error: e.message }); }
|
||
});
|
||
|
||
// ==========================================
|
||
// ð¡ï¸ RUTAS PÃBLICAS: CONTRATACIÃN DE PLANES
|
||
// ==========================================
|
||
|
||
// 1. Obtener la información pública de la empresa, planes y comprobar si YA tiene seguro
|
||
app.get("/public/portal/:token/protection", async (req, res) => {
|
||
try {
|
||
const { token } = req.params;
|
||
|
||
// Identificar al cliente y sacar el ID de la empresa dueña
|
||
const clientQ = await pool.query("SELECT id, full_name, phone, owner_id FROM clients WHERE portal_token = $1", [token]);
|
||
if (clientQ.rowCount === 0) return res.status(404).json({ ok: false, error: "Token inválido" });
|
||
|
||
const client = clientQ.rows[0];
|
||
const ownerId = client.owner_id;
|
||
|
||
// Comprobar si el cliente YA tiene un plan activo (Solo si está pagado y activo)
|
||
let cleanPhone = String(client.phone || "").replace(/[^0-9]/g, "");
|
||
if (cleanPhone.length > 9) cleanPhone = cleanPhone.slice(-9);
|
||
|
||
const subQ = await pool.query(`
|
||
SELECT s.status, p.name as plan_name
|
||
FROM protection_subscriptions s
|
||
JOIN protection_plans p ON s.plan_id = p.id
|
||
WHERE s.company_id = $1 AND s.client_phone LIKE $2 AND s.status = 'activo' AND s.payment_status = 'pagado'
|
||
ORDER BY s.created_at DESC LIMIT 1
|
||
`, [ownerId, `%${cleanPhone}%`]);
|
||
|
||
const hasActivePlan = subQ.rowCount > 0;
|
||
const activePlanDetails = hasActivePlan ? subQ.rows[0] : null;
|
||
|
||
// Extraer datos de la empresa, configuración y planes
|
||
const [companyQ, configQ, plansQ] = await Promise.all([
|
||
pool.query("SELECT full_name FROM users WHERE id = $1", [ownerId]),
|
||
pool.query("SELECT contract_text FROM protection_config WHERE company_id = $1", [ownerId]),
|
||
pool.query("SELECT * FROM protection_plans WHERE company_id = $1 ORDER BY price DESC", [ownerId])
|
||
]);
|
||
|
||
res.json({
|
||
ok: true,
|
||
client: { name: client.full_name },
|
||
company: { name: companyQ.rows[0]?.full_name || "Empresa" },
|
||
config: configQ.rows[0] || {},
|
||
plans: plansQ.rows,
|
||
hasActivePlan: hasActivePlan,
|
||
activePlanDetails: activePlanDetails
|
||
});
|
||
|
||
} catch (e) {
|
||
console.error("Error cargando portal protección:", e);
|
||
res.status(500).json({ ok: false, error: "Error interno del servidor" });
|
||
}
|
||
});
|
||
|
||
app.post("/public/portal/:token/protection/subscribe", async (req, res) => {
|
||
try {
|
||
const { token } = req.params;
|
||
const { plan_id, signature, pdf_document, dni } = req.body;
|
||
|
||
const clientQ = await pool.query(
|
||
"SELECT * FROM clients WHERE portal_token = $1",
|
||
[token]
|
||
);
|
||
if (clientQ.rowCount === 0) {
|
||
return res.status(404).json({ ok: false, error: "Token inválido" });
|
||
}
|
||
|
||
const client = clientQ.rows[0];
|
||
const ownerId = client.owner_id;
|
||
|
||
const planQ = await pool.query(
|
||
"SELECT * FROM protection_plans WHERE id = $1 AND company_id = $2",
|
||
[plan_id, ownerId]
|
||
);
|
||
if (planQ.rowCount === 0) {
|
||
return res.status(404).json({ ok: false, error: "El plan seleccionado no existe" });
|
||
}
|
||
|
||
const plan = planQ.rows[0];
|
||
|
||
const ownerConfigQ = await pool.query(
|
||
"SELECT billing_settings FROM users WHERE id = $1",
|
||
[ownerId]
|
||
);
|
||
let billingSettings = ownerConfigQ.rows[0]?.billing_settings || {};
|
||
if (typeof billingSettings === "string") {
|
||
try { billingSettings = JSON.parse(billingSettings); } catch (_) { billingSettings = {}; }
|
||
}
|
||
|
||
if (!billingSettings.stripe_enabled || !billingSettings.stripe_sk) {
|
||
return res.status(400).json({ ok: false, error: "La empresa no tiene habilitados los pagos con tarjeta." });
|
||
}
|
||
|
||
const stripe = new Stripe(billingSettings.stripe_sk, { apiVersion: "2023-10-16" });
|
||
|
||
const interval =
|
||
String(plan.billing_interval || "").toLowerCase() === "year" ||
|
||
String(plan.type || "").toLowerCase().includes("anual")
|
||
? "year"
|
||
: "month";
|
||
|
||
const intervalCount = Number(plan.billing_interval_count || 1);
|
||
|
||
const subInsert = await pool.query(`
|
||
INSERT INTO protection_subscriptions (
|
||
company_id,
|
||
plan_id,
|
||
client_name,
|
||
client_dni,
|
||
client_phone,
|
||
payment_status,
|
||
status,
|
||
contract_pdf_url
|
||
)
|
||
VALUES ($1, $2, $3, $4, $5, 'impagado', 'pendiente_pago', $6)
|
||
RETURNING id
|
||
`, [
|
||
ownerId,
|
||
plan.id,
|
||
client.full_name,
|
||
dni || null,
|
||
client.phone,
|
||
pdf_document || null
|
||
]);
|
||
|
||
const subscriptionId = subInsert.rows[0].id;
|
||
|
||
await pool.query(
|
||
"INSERT INTO protection_activity (company_id, type, description) VALUES ($1, 'alta', $2)",
|
||
[ownerId, `Suscripción iniciada vÃa Web: ${client.full_name} (${plan.name})`]
|
||
);
|
||
|
||
const session = await stripe.checkout.sessions.create({
|
||
payment_method_types: ["card"],
|
||
mode: "subscription",
|
||
line_items: [{
|
||
price_data: {
|
||
currency: "eur",
|
||
product_data: {
|
||
name: `Plan de Protección: ${plan.name}`,
|
||
description: `Suscripción ${plan.type || interval}`
|
||
},
|
||
unit_amount: Math.round(Number(plan.price || 0) * 100),
|
||
recurring: {
|
||
interval,
|
||
interval_count: intervalCount
|
||
}
|
||
},
|
||
quantity: 1
|
||
}],
|
||
metadata: {
|
||
subscription_id: String(subscriptionId),
|
||
owner_id: String(ownerId),
|
||
plan_id: String(plan.id),
|
||
type: "protection_plan"
|
||
},
|
||
customer_email: client.email || undefined,
|
||
success_url: `https://portal.integrarepara.es/pago_exito.html?sub_id=${subscriptionId}`,
|
||
cancel_url: `https://portal.integrarepara.es/plan-tranquilidad.html?token=${token}`,
|
||
});
|
||
|
||
await pool.query(`
|
||
UPDATE protection_subscriptions
|
||
SET stripe_session_id = $1,
|
||
stripe_price_id = $2,
|
||
updated_at = NOW()
|
||
WHERE id = $3
|
||
`, [
|
||
session.id,
|
||
null,
|
||
subscriptionId
|
||
]);
|
||
|
||
res.json({ ok: true, checkout_url: session.url });
|
||
|
||
} catch (e) {
|
||
console.error("Error al procesar firma de plan:", e);
|
||
res.status(500).json({ ok: false, error: "Error al generar la suscripción." });
|
||
}
|
||
});
|
||
|
||
// ==========================================
|
||
// ð HELPERS PARA LAS AUTOMATIZACIONES DE RECORDATORIOS
|
||
// ==========================================
|
||
function getMadridNowInfoAuto() {
|
||
const fmt = new Intl.DateTimeFormat("en-CA", {
|
||
timeZone: "Europe/Madrid",
|
||
year: "numeric", month: "2-digit", day: "2-digit",
|
||
hour: "2-digit", minute: "2-digit", hour12: false
|
||
});
|
||
const parts = fmt.formatToParts(new Date());
|
||
const map = {};
|
||
for (const p of parts) { if (p.type !== "literal") map[p.type] = p.value; }
|
||
return {
|
||
todayISO: `${map.year}-${map.month}-${map.day}`,
|
||
currentMinutes: (parseInt(map.hour, 10) * 60) + parseInt(map.minute, 10)
|
||
};
|
||
}
|
||
|
||
function addDaysISOAuto(isoDate, daysToAdd) {
|
||
const [y, m, d] = isoDate.split("-").map(Number);
|
||
const dt = new Date(Date.UTC(y, m - 1, d));
|
||
dt.setUTCDate(dt.getUTCDate() + daysToAdd);
|
||
return dt.toISOString().slice(0, 10);
|
||
}
|
||
|
||
// EnvÃa el WhatsApp de un recordatorio automático y deja constancia en automation_log.
|
||
// Si test_mode está activo, el mensaje se desvÃa SIEMPRE al móvil de pruebas (667248132),
|
||
// nunca al cliente real, para poder validar el automatismo sin molestar a nadie.
|
||
async function enviarRecordatorioAutomatizacion(client, svc, tipo, testMode) {
|
||
try {
|
||
const raw = svc.raw_data || {};
|
||
const tplTypeMap = {
|
||
sin_citar: 'reminder_sin_citar',
|
||
espera_cliente: 'reminder_espera_cliente',
|
||
dia_antes: 'reminder_dia_antes'
|
||
};
|
||
const tplQ = await client.query("SELECT content FROM message_templates WHERE owner_id=$1 AND type=$2", [svc.owner_id, tplTypeMap[tipo]]);
|
||
if (tplQ.rowCount === 0 || !tplQ.rows[0].content) return;
|
||
let text = tplQ.rows[0].content;
|
||
|
||
const cleanPhone = extractBestMobile(raw);
|
||
|
||
const nombre = raw["Nombre Cliente"] || raw["CLIENTE"] || raw["Nombre"] || "Cliente";
|
||
const direccion = raw["Dirección"] || raw["DOMICILIO"] || "";
|
||
text = text.replace(/{{NOMBRE}}/g, nombre);
|
||
text = text.replace(/{{DIRECCION}}/g, direccion);
|
||
text = text.replace(/{{FECHA}}/g, raw["scheduled_date"] || "");
|
||
text = text.replace(/{{HORA}}/g, raw["scheduled_time"] || "");
|
||
text = text.replace(/{{REFERENCIA}}/g, svc.service_ref || raw["Referencia"] || raw["Nº Siniestro"] || String(svc.id));
|
||
|
||
// ð {{PORTAL}}: enlace mágico al portal del cliente (siempre el real, aunque esté en modo prueba)
|
||
if (text.includes('{{PORTAL}}')) {
|
||
let portalToken = null;
|
||
if (cleanPhone.length >= 9) {
|
||
const clientQ = await client.query(
|
||
"SELECT portal_token FROM clients WHERE phone LIKE $1 AND owner_id=$2 LIMIT 1",
|
||
[`%${cleanPhone}%`, svc.owner_id]
|
||
);
|
||
if (clientQ.rowCount > 0) {
|
||
portalToken = clientQ.rows[0].portal_token;
|
||
} else {
|
||
const insertC = await client.query(
|
||
"INSERT INTO clients (owner_id, full_name, phone, addresses) VALUES ($1, $2, $3, $4) RETURNING portal_token",
|
||
[svc.owner_id, nombre, "34" + cleanPhone, JSON.stringify([direccion])]
|
||
);
|
||
portalToken = insertC.rows[0].portal_token;
|
||
}
|
||
}
|
||
const linkPortal = portalToken ? `https://portal.integrarepara.es/?token=${portalToken}&service=${svc.id}` : "";
|
||
text = text.replace(/{{PORTAL}}/g, linkPortal);
|
||
}
|
||
|
||
let finalPhone;
|
||
if (testMode) {
|
||
finalPhone = "34667248132"; // ð¡ï¸ Modo prueba: siempre al móvil de pruebas, nunca al cliente
|
||
} else {
|
||
if (cleanPhone.length < 9) return; // Sin teléfono válido del cliente, no hay a quién enviar
|
||
finalPhone = "34" + cleanPhone;
|
||
}
|
||
|
||
const instanceName = `cliente_${svc.owner_id}`;
|
||
await sendWhatsAppAuto(finalPhone, text, instanceName, false);
|
||
|
||
await client.query(
|
||
"INSERT INTO automation_log (owner_id, service_id, automation_type, sent_at) VALUES ($1,$2,$3,NOW())",
|
||
[svc.owner_id, svc.id, tipo]
|
||
);
|
||
} catch (e) {
|
||
console.error(`Error enviando recordatorio automatizado (${tipo}) srv#${svc.id}:`, e.message);
|
||
}
|
||
}
|
||
|
||
// ==========================================
|
||
// ð EL RELOJ DEL SISTEMA (Ejecutar cada minuto)
|
||
// ==========================================
|
||
setInterval(async () => {
|
||
const client = await pool.connect(); // <-- Conectamos de forma segura
|
||
try {
|
||
// --- 1. CADUCIDAD DE PINGS (Reasignación si el operario no contesta) ---
|
||
const expiredPings = await client.query(`
|
||
SELECT ap.id, ap.scraped_id, ap.user_id, s.owner_id, s.raw_data
|
||
FROM assignment_pings ap
|
||
JOIN scraped_services s ON ap.scraped_id = s.id
|
||
WHERE ap.status = 'pending'
|
||
AND EXTRACT(EPOCH FROM (ap.expires_at - CURRENT_TIMESTAMP)) <= 0
|
||
AND s.automation_status = 'in_progress'
|
||
`);
|
||
|
||
for (const ping of expiredPings.rows) {
|
||
await client.query("UPDATE assignment_pings SET status = 'expired' WHERE id = $1", [ping.id]);
|
||
|
||
// ð FIX: Extraer Gremio y CP del raw_data para buscar al SIGUIENTE operario CORRECTO
|
||
const raw = ping.raw_data || {};
|
||
const guildId = raw.guild_id || null;
|
||
|
||
// Lógica para extraer CP exactamente igual que al inicio
|
||
const todoElTexto = JSON.stringify(raw).toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
|
||
const cpMatch = todoElTexto.match(/\b\d{5}\b/);
|
||
const cpFinal = cpMatch ? cpMatch[0] : "00000";
|
||
|
||
// Si por algún motivo no hay gremio guardado, abortamos la bolsa para este servicio
|
||
if (!guildId) {
|
||
await client.query("UPDATE scraped_services SET automation_status = 'failed' WHERE id = $1", [ping.scraped_id]);
|
||
continue;
|
||
}
|
||
|
||
const nextWorkerQ = await client.query(`
|
||
SELECT u.id, u.phone, u.full_name
|
||
FROM users u
|
||
JOIN user_guilds ug ON u.id = ug.user_id
|
||
WHERE u.owner_id = $1 AND u.status = 'active'
|
||
AND ug.guild_id = $3 AND u.zones::jsonb @> $4::jsonb
|
||
AND u.id NOT IN (SELECT user_id FROM assignment_pings WHERE scraped_id = $2)
|
||
LIMIT 1
|
||
`, [ping.owner_id, ping.scraped_id, guildId, JSON.stringify([{ cps: cpFinal }])]);
|
||
|
||
if (nextWorkerQ.rowCount > 0) {
|
||
const nextW = nextWorkerQ.rows[0];
|
||
const newToken = crypto.randomBytes(16).toString('hex');
|
||
await client.query(`INSERT INTO assignment_pings (scraped_id, user_id, token, expires_at) VALUES ($1, $2, $3, CURRENT_TIMESTAMP + INTERVAL '5 minutes')`, [ping.scraped_id, nextW.id, newToken]);
|
||
|
||
// ð FIX: URL corregida a web.integrarepara.es
|
||
const mensaje = `ð ï¸ *SERVICIO DISPONIBLE*\nEl anterior compañero no respondió. Es tu turno:\nð https://web.integrarepara.es/aceptar.html?t=${newToken}`;
|
||
const instanceName = `cliente_${ping.owner_id}`;
|
||
sendWhatsAppAuto(nextW.phone, mensaje, instanceName).catch(console.error);
|
||
} else {
|
||
await client.query("UPDATE scraped_services SET automation_status = 'failed' WHERE id = $1", [ping.scraped_id]);
|
||
}
|
||
}
|
||
|
||
// --- 2. ð¨ NUEVO: CAZADOR DE URGENCIAS QUE "ENTRAN SOLAS" ð¨ ---
|
||
// Buscamos servicios que sean urgentes y que sigan atascados en 'manual' o 'pending'
|
||
const pendingUrgent = await client.query(`
|
||
SELECT s.id, s.owner_id, s.raw_data, s.provider, s.service_ref, pc.auto_dispatch
|
||
FROM scraped_services s
|
||
LEFT JOIN provider_credentials pc ON s.owner_id = pc.owner_id AND s.provider = pc.provider
|
||
WHERE s.is_urgent = true
|
||
AND s.automation_status IN ('manual', 'pending')
|
||
AND s.status != 'archived'
|
||
AND s.assigned_to IS NULL -- ð EL ESCUDO: Solo si NO tiene operario asignado
|
||
`);
|
||
|
||
for (const svc of pendingUrgent.rows) {
|
||
// Comprobamos si el interruptor de ese proveedor está encendido (1, '1', 't' o true)
|
||
const isAutoOn = svc.auto_dispatch === true || svc.auto_dispatch === 1 || svc.auto_dispatch === '1' || svc.auto_dispatch === 't';
|
||
|
||
// Sacamos el gremio desde el JSON interno
|
||
const finalGuildId = svc.raw_data && svc.raw_data.guild_id ? svc.raw_data.guild_id : null;
|
||
|
||
if (isAutoOn && finalGuildId) {
|
||
console.log(`⡠[RELOJ] Cazador automático ha encontrado la urgencia #${svc.service_ref}. ¡Lanzando a bolsa!`);
|
||
|
||
// Extraemos el código postal si existe en el raw_data
|
||
const todoElTexto = JSON.stringify(svc.raw_data || {}).toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
|
||
const cpMatch = todoElTexto.match(/\b\d{5}\b/);
|
||
const cpFinal = cpMatch ? cpMatch[0] : "00000";
|
||
|
||
// ð¥ Disparamos la bolsa y guardamos el resultado
|
||
const dispatchResult = await dispatchToBolsa(svc.id, finalGuildId, cpFinal, svc.owner_id, null);
|
||
|
||
// ð ESCUDO ANTI-BUCLE: Si falla porque no hay operarios en ese CP,
|
||
// marcamos la urgencia como "failed" para que el reloj deje de intentarlo eternamente.
|
||
if (!dispatchResult.ok) {
|
||
console.log(`ð [ESCUDO] Abortando bucle para #${svc.service_ref}. Marcado como 'failed'.`);
|
||
await client.query("UPDATE scraped_services SET automation_status = 'failed' WHERE id = $1", [svc.id]);
|
||
}
|
||
}
|
||
}
|
||
|
||
// --- 3. ð AUTOMATIZACIONES DE RECORDATORIOS (SIN CITAR / ESPERA CLIENTE / DÃA ANTES) ---
|
||
const madridInfo = getMadridNowInfoAuto();
|
||
const dentroDeHorario = madridInfo.currentMinutes >= 540 && madridInfo.currentMinutes < 1260; // 9:00 - 21:00 (si no toca ahora, se difiere, nunca se salta)
|
||
|
||
// 3.1 â "Sin citar" (Asignado sin fecha) y "Espera de cliente" (Esperando al Cliente sin fecha)
|
||
const tiposEstado = [
|
||
{ tipo: 'sin_citar', statusName: 'Asignado' },
|
||
{ tipo: 'espera_cliente', statusName: 'Esperando al Cliente' }
|
||
];
|
||
|
||
for (const { tipo, statusName } of tiposEstado) {
|
||
const settingsQ = await client.query(
|
||
"SELECT * FROM automation_settings WHERE automation_type = $1 AND enabled = true",
|
||
[tipo]
|
||
);
|
||
|
||
for (const cfg of settingsQ.rows) {
|
||
// Candidatos actuales: servicios de este owner, en el estado vigilado, sin fecha de cita
|
||
const candidatesQ = await client.query(`
|
||
SELECT s.id, s.owner_id, s.raw_data, s.service_ref
|
||
FROM scraped_services s
|
||
JOIN service_statuses st ON st.id::text = (s.raw_data->>'status_operativo')::text
|
||
WHERE s.owner_id = $1
|
||
AND st.name = $2
|
||
AND (s.raw_data->>'scheduled_date' IS NULL OR s.raw_data->>'scheduled_date' = '')
|
||
AND s.status != 'archived'
|
||
`, [cfg.owner_id, statusName]);
|
||
|
||
const candidateIds = candidatesQ.rows.map(r => r.id);
|
||
|
||
// Damos de alta en el seguimiento a los que son nuevos en este estado
|
||
for (const svc of candidatesQ.rows) {
|
||
await client.query(
|
||
"INSERT INTO automation_tracking (owner_id, service_id, automation_type, first_seen_at) VALUES ($1,$2,$3,NOW()) ON CONFLICT (service_id, automation_type) DO NOTHING",
|
||
[svc.owner_id, svc.id, tipo]
|
||
);
|
||
}
|
||
|
||
// Limpiamos el seguimiento de los que ya no están en ese estado (se citaron, cambiaron, etc.)
|
||
if (candidateIds.length > 0) {
|
||
await client.query(
|
||
"DELETE FROM automation_tracking WHERE owner_id = $1 AND automation_type = $2 AND service_id != ALL($3::int[])",
|
||
[cfg.owner_id, tipo, candidateIds]
|
||
);
|
||
} else {
|
||
await client.query(
|
||
"DELETE FROM automation_tracking WHERE owner_id = $1 AND automation_type = $2",
|
||
[cfg.owner_id, tipo]
|
||
);
|
||
}
|
||
|
||
if (!dentroDeHorario) continue; // Fuera de horario (21h-9h): no enviamos todavÃa, pero el seguimiento ya está al dÃa
|
||
|
||
for (const svc of candidatesQ.rows) {
|
||
const trackQ = await client.query(
|
||
"SELECT first_seen_at FROM automation_tracking WHERE service_id = $1 AND automation_type = $2",
|
||
[svc.id, tipo]
|
||
);
|
||
if (trackQ.rowCount === 0) continue;
|
||
const firstSeenAt = trackQ.rows[0].first_seen_at;
|
||
|
||
const lastSentQ = await client.query(
|
||
"SELECT MAX(sent_at) as last_sent FROM automation_log WHERE service_id = $1 AND automation_type = $2",
|
||
[svc.id, tipo]
|
||
);
|
||
const lastSent = lastSentQ.rows[0].last_sent;
|
||
|
||
let debeEnviar = false;
|
||
if (!lastSent) {
|
||
const diasEspera = (Date.now() - new Date(firstSeenAt).getTime()) / 86400000;
|
||
debeEnviar = diasEspera >= cfg.dias_espera_inicial;
|
||
} else {
|
||
const diasDesdeUltimo = (Date.now() - new Date(lastSent).getTime()) / 86400000;
|
||
debeEnviar = diasDesdeUltimo >= cfg.dias_repeticion;
|
||
}
|
||
|
||
if (debeEnviar) {
|
||
await enviarRecordatorioAutomatizacion(client, svc, tipo, cfg.test_mode);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// 3.2 â "DÃa antes" de la cita: recordatorio al asegurado con dirección, hora y dÃa de la visita
|
||
if (dentroDeHorario) {
|
||
const diaAntesSettingsQ = await client.query(
|
||
"SELECT * FROM automation_settings WHERE automation_type = 'dia_antes' AND enabled = true"
|
||
);
|
||
const mananaISO = addDaysISOAuto(madridInfo.todayISO, 1);
|
||
|
||
for (const cfg of diaAntesSettingsQ.rows) {
|
||
const [hh, mm] = (cfg.hora_envio || '09:00').split(':').map(Number);
|
||
const minutosEnvio = (hh * 60) + (mm || 0);
|
||
if (madridInfo.currentMinutes < minutosEnvio) continue; // Aún no toca su hora configurada de envÃo
|
||
|
||
const candidatesQ = await client.query(`
|
||
SELECT s.id, s.owner_id, s.raw_data, s.service_ref
|
||
FROM scraped_services s
|
||
WHERE s.owner_id = $1
|
||
AND s.raw_data->>'scheduled_date' = $2
|
||
AND s.status != 'archived'
|
||
AND NOT EXISTS (
|
||
SELECT 1 FROM automation_log al
|
||
WHERE al.service_id = s.id AND al.automation_type = 'dia_antes'
|
||
AND al.sent_at::date = CURRENT_DATE
|
||
)
|
||
`, [cfg.owner_id, mananaISO]);
|
||
|
||
for (const svc of candidatesQ.rows) {
|
||
await enviarRecordatorioAutomatizacion(client, svc, 'dia_antes', cfg.test_mode);
|
||
}
|
||
}
|
||
}
|
||
|
||
} catch (e) {
|
||
console.error("Reloj:", e.message);
|
||
} finally {
|
||
client.release(); // <-- Liberamos la conexión SIEMPRE
|
||
}
|
||
}, 60000); // Se ejecuta en bucle cada 60.000 milisegundos (1 minuto)
|
||
|
||
// ============================================
|
||
// ð¡ COMPARADOR DE FACTURAS DE LUZ (marsalva.es)
|
||
// ============================================
|
||
// Fase 1: el cliente sube su factura, nosotros extraemos los datos con IA,
|
||
// recalculamos con nuestras propias fórmulas (la IA NUNCA calcula importes),
|
||
// comparamos contra nuestras tarifas propias y avisamos a Marco por WhatsApp.
|
||
// El archivo subido nunca se guarda en disco: se procesa en memoria y se descarta.
|
||
|
||
pool.query(`
|
||
CREATE TABLE IF NOT EXISTS energy_tariffs (
|
||
id SERIAL PRIMARY KEY,
|
||
owner_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||
tipo TEXT DEFAULT 'propia', -- 'propia' | 'repsol' | 'mercado'
|
||
nombre TEXT NOT NULL,
|
||
comercializadora TEXT,
|
||
precio_potencia_p1 NUMERIC NOT NULL DEFAULT 0, -- â¬/kW·dÃa
|
||
precio_potencia_p2 NUMERIC NOT NULL DEFAULT 0, -- â¬/kW·dÃa
|
||
precio_energia_punta NUMERIC NOT NULL DEFAULT 0, -- â¬/kWh
|
||
precio_energia_llano NUMERIC NOT NULL DEFAULT 0, -- â¬/kWh (si no hay periodos, usar el mismo valor en los 3)
|
||
precio_energia_valle NUMERIC NOT NULL DEFAULT 0, -- â¬/kWh
|
||
descuento_pct NUMERIC NOT NULL DEFAULT 0, -- % único combinado sobre la energÃa
|
||
bono_social_dia NUMERIC NOT NULL DEFAULT 0,
|
||
alquiler_contador_dia NUMERIC NOT NULL DEFAULT 0,
|
||
notas TEXT,
|
||
activa BOOLEAN DEFAULT TRUE,
|
||
created_at TIMESTAMP DEFAULT NOW(),
|
||
updated_at TIMESTAMP DEFAULT NOW()
|
||
);
|
||
|
||
CREATE TABLE IF NOT EXISTS energy_settings (
|
||
owner_id INT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
|
||
iee_pct NUMERIC NOT NULL DEFAULT 5.1126963,
|
||
iva_pct NUMERIC NOT NULL DEFAULT 21,
|
||
openai_model TEXT,
|
||
cnmc_enabled BOOLEAN DEFAULT TRUE,
|
||
admin_whatsapp TEXT,
|
||
updated_at TIMESTAMP DEFAULT NOW()
|
||
);
|
||
|
||
CREATE TABLE IF NOT EXISTS energy_quote_leads (
|
||
id SERIAL PRIMARY KEY,
|
||
owner_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||
email TEXT NOT NULL,
|
||
telefono TEXT NOT NULL,
|
||
codigo_postal TEXT,
|
||
rgpd_aceptado BOOLEAN NOT NULL DEFAULT FALSE,
|
||
rgpd_fecha TIMESTAMP,
|
||
factura_json JSONB, -- datos extraÃdos por la IA (sin PII: sin nombre/DNI/dirección/IBAN/CUPS)
|
||
total_real NUMERIC,
|
||
total_recalculado NUMERIC,
|
||
diferencia NUMERIC,
|
||
revisar_manualmente BOOLEAN DEFAULT FALSE,
|
||
mejor_tarifa_id INT REFERENCES energy_tariffs(id),
|
||
ahorro_estimado_factura NUMERIC,
|
||
ahorro_estimado_anual NUMERIC,
|
||
comparativa_json JSONB, -- resultado completo contra todas las tarifas activas
|
||
mercado_cnmc_json JSONB, -- snapshot informativo del comparador oficial (puede ser null)
|
||
estado TEXT DEFAULT 'nuevo', -- nuevo | revisado | contactado | descartado
|
||
notificado_whatsapp BOOLEAN DEFAULT FALSE,
|
||
created_at TIMESTAMP DEFAULT NOW()
|
||
);
|
||
`).catch((e) => console.error("â Error creando tablas de energy-quote:", e.message));
|
||
|
||
// --- LÃmite de peticiones por IP para el endpoint público (anti-abuso) ---
|
||
const energyQuoteLimiter = rateLimit({
|
||
windowMs: 60 * 60 * 1000, // 1 hora
|
||
max: 5,
|
||
standardHeaders: true,
|
||
legacyHeaders: false,
|
||
message: { ok: false, error: "Demasiadas solicitudes. Inténtalo de nuevo en un rato." },
|
||
});
|
||
|
||
const ENERGY_ALLOWED_MIME = new Set(["application/pdf", "image/jpeg", "image/jpg", "image/png"]);
|
||
const ENERGY_MAX_FILE_BYTES = 6 * 1024 * 1024; // 6MB (con base64 ~8MB, dentro del lÃmite de express.json de 10mb)
|
||
|
||
// --- Motor de cálculo (TODO lo monetario lo hace nuestro código, nunca la IA) ---
|
||
// NOTA sobre "descuentos": el enunciado original decÃa "Base IEE = potencia + energÃa
|
||
// â descuentos + bono social", pero "energÃa" ya lleva el descuento restado una vez
|
||
// (EnergÃa = kWh à precio â descuentos). Validado numéricamente contra la factura de
|
||
// referencia de Endesa (10%+10% = 20% combinado, aplicado UNA sola vez sobre la energÃa
|
||
// bruta): el resultado cuadra con el total real dentro de ±0,05â¬. Restarlo una segunda
|
||
// vez en la Base IEE se desvÃa más de 0,75⬠del total real, asà que NO se resta dos veces.
|
||
function calcularFactura(perfil, precios, ieePct = 5.1126963, ivaPct = 21) {
|
||
const dias = Number(perfil.diasFacturados) || 0;
|
||
const p1 = Number(perfil.potenciaP1Kw) || 0;
|
||
const p2 = Number(perfil.potenciaP2Kw) || 0;
|
||
const kwhPunta = Number(perfil.kwhPunta) || 0;
|
||
const kwhLlano = Number(perfil.kwhLlano) || 0;
|
||
const kwhValle = Number(perfil.kwhValle) || 0;
|
||
|
||
const potencia = p1 * (Number(precios.precioPotenciaP1) || 0) * dias
|
||
+ p2 * (Number(precios.precioPotenciaP2) || 0) * dias;
|
||
|
||
const energiaBruta = kwhPunta * (Number(precios.precioEnergiaPunta) || 0)
|
||
+ kwhLlano * (Number(precios.precioEnergiaLlano) || 0)
|
||
+ kwhValle * (Number(precios.precioEnergiaValle) || 0);
|
||
|
||
const descuentoPct = Number(precios.descuentoPct) || 0;
|
||
const descuento = energiaBruta * (descuentoPct / 100);
|
||
const energia = energiaBruta - descuento;
|
||
|
||
const bonoSocial = dias * (Number(precios.bonoSocialDia) || 0);
|
||
|
||
const baseIEE = potencia + energia + bonoSocial;
|
||
const iee = baseIEE * (Number(ieePct) / 100);
|
||
const alquilerContador = dias * (Number(precios.alquilerContadorDia) || 0);
|
||
|
||
const baseIva = baseIEE + iee + alquilerContador;
|
||
const iva = baseIva * (Number(ivaPct) / 100);
|
||
const total = baseIva + iva;
|
||
|
||
const round2 = (n) => Math.round(n * 100) / 100;
|
||
return {
|
||
potencia: round2(potencia),
|
||
energiaBruta: round2(energiaBruta),
|
||
descuento: round2(descuento),
|
||
energia: round2(energia),
|
||
bonoSocial: round2(bonoSocial),
|
||
baseIEE: round2(baseIEE),
|
||
iee: round2(iee),
|
||
alquilerContador: round2(alquilerContador),
|
||
iva: round2(iva),
|
||
total: round2(total),
|
||
};
|
||
}
|
||
|
||
// --- Consulta best-effort al comparador oficial del CNMC (informativa, nunca bloqueante) ---
|
||
async function consultarOfertasCNMC(perfil, codigoPostal) {
|
||
try {
|
||
const dias = Number(perfil.diasFacturados) || 30;
|
||
const kwhPunta = Number(perfil.kwhPunta) || 0;
|
||
const kwhLlano = Number(perfil.kwhLlano) || 0;
|
||
const kwhValle = Number(perfil.kwhValle) || 0;
|
||
const kwhTotal = kwhPunta + kwhLlano + kwhValle;
|
||
const anual = (n) => Math.round((n / dias) * 365);
|
||
const p1 = Number(perfil.potenciaP1Kw) || 0;
|
||
const p2 = Number(perfil.potenciaP2Kw) || 0;
|
||
|
||
const ahora = Date.now();
|
||
const unAnioMs = 365 * 24 * 60 * 60 * 1000;
|
||
|
||
const params = new URLSearchParams({
|
||
tipoSuministro: "E",
|
||
codigoPostal: String(codigoPostal || ""),
|
||
potencia: String(Math.max(p1, p2)),
|
||
potenciaPrimeraFranja: String(p1),
|
||
potenciaSegundaFranja: String(p2),
|
||
consumoAnualE: String(anual(kwhTotal)),
|
||
consumoPrimeraFranja: String(anual(kwhPunta)),
|
||
consumoSegundaFranja: String(anual(kwhLlano)),
|
||
consumoTerceraFranja: String(anual(kwhValle)),
|
||
tarifa: "4",
|
||
serviciosAdicionales: "2",
|
||
permanencia: "2",
|
||
vivienda: "true",
|
||
factura: "true",
|
||
revisionPrecios: "2",
|
||
dateInicio: String(ahora),
|
||
dateFin: String(ahora + unAnioMs),
|
||
perfilConsumo: "13",
|
||
cups: "0000",
|
||
autoconsumo: "false",
|
||
});
|
||
|
||
const url = `https://comparador.cnmc.gob.es/api/publico/ofertas/electricidad?${params.toString()}`;
|
||
const controller = new AbortController();
|
||
const timeout = setTimeout(() => controller.abort(), 4000);
|
||
const resp = await fetch(url, { signal: controller.signal });
|
||
clearTimeout(timeout);
|
||
if (!resp.ok) return null;
|
||
const data = await resp.json();
|
||
const ofertas = Array.isArray(data.resultadoComparador) ? data.resultadoComparador : [];
|
||
return ofertas
|
||
.slice()
|
||
.sort((a, b) => (a.importePrimerAnio || 0) - (b.importePrimerAnio || 0))
|
||
.slice(0, 5)
|
||
.map((o) => ({
|
||
comercializadora: o.comercializadora,
|
||
oferta: o.oferta,
|
||
importePrimerAnio: o.importePrimerAnio,
|
||
importeSegundoAnio: o.importeSegundoAnio,
|
||
verde: !!o.verde,
|
||
penalizacion: !!o.penalizacion,
|
||
}));
|
||
} catch (e) {
|
||
console.warn("â ï¸ CNMC no disponible (no bloqueante):", e.message);
|
||
return null;
|
||
}
|
||
}
|
||
|
||
// --- Extracción de la factura con OpenAI (visión). NUNCA extrae nombre/DNI/dirección/IBAN/CUPS ---
|
||
async function extraerFacturaConIA(archivoBase64, archivoMime) {
|
||
const systemPrompt = `Eres un extractor de datos de facturas eléctricas españolas. Responde SOLO un JSON con
|
||
estas claves exactas (usa null si un dato no aparece; no inventes ni deduzcas nada):
|
||
comercializadora, tarifa_acceso, dias_facturados, potencia_p1_kw, potencia_p2_kw,
|
||
precio_potencia_p1, precio_potencia_p2, kwh_punta, kwh_llano, kwh_valle, precio_energia_punta,
|
||
precio_energia_llano, precio_energia_valle, descuento_pct, descuento_aplica_a,
|
||
alquiler_contador_dia, bono_social_dia, total_factura, permanencia, permanencia_fecha_fin.
|
||
Si hay consumo en varios periodos horarios (kwh_punta, kwh_llano o kwh_valle con valor distinto de null), busca con atención el precio de la energÃa (euros/kWh) de CADA periodo en la tabla de desglose o detalle de consumo de la factura: suelen venir en una tabla con una fila o columna por periodo, a veces en letra pequeña. No dejes precio_energia_llano o precio_energia_valle en null solo porque cueste más localizarlos; revisa toda la factura, incluidas tablas pequeñas, antes de darlos por ausentes.
|
||
Si en el apartado de Descuentos de la factura aparece más de una lÃnea (por ejemplo "descuento fidelidad" y "descuento promocional", u otros nombres similares), SUMA los porcentajes de TODAS esas lÃneas en un único valor para descuento_pct (dos descuentos del 10% cada uno deben darte descuento_pct: 20, nunca 10). Antes de responder, comprueba que ese descuento_pct aplicado sobre el importe de EnergÃa se aproxime al importe en euros que aparece junto a "Descuentos" en el resumen de la factura; si no cuadra, revisa si te falta alguna lÃnea de descuento.
|
||
IMPORTANTE: NUNCA extraigas ni menciones nombre, DNI, dirección, IBAN ni CUPS, aunque aparezcan
|
||
en la factura. No incluyas esas claves en el JSON bajo ningún concepto.`;
|
||
|
||
const modelo = process.env.OPENAI_MODEL_FACTURAS || process.env.OPENAI_MODEL || "gpt-4o-mini";
|
||
const dataUrl = `data:${archivoMime};base64,${archivoBase64}`;
|
||
const esPdf = archivoMime === "application/pdf";
|
||
|
||
const userContent = esPdf
|
||
? [
|
||
{ type: "text", text: "Extrae los datos de esta factura (PDF) según las instrucciones." },
|
||
{ type: "file", file: { filename: "factura.pdf", file_data: dataUrl } },
|
||
]
|
||
: [
|
||
{ type: "text", text: "Extrae los datos de esta factura (foto) según las instrucciones." },
|
||
{ type: "image_url", image_url: { url: dataUrl, detail: "high" } },
|
||
];
|
||
|
||
const completion = await openai.chat.completions.create({
|
||
model: modelo,
|
||
messages: [
|
||
{ role: "system", content: systemPrompt },
|
||
{ role: "user", content: userContent },
|
||
],
|
||
response_format: { type: "json_object" },
|
||
temperature: 0,
|
||
});
|
||
|
||
try {
|
||
return JSON.parse(completion.choices?.[0]?.message?.content || "{}");
|
||
} catch {
|
||
return {};
|
||
}
|
||
}
|
||
|
||
// --- Endpoint público: el cliente sube su factura desde marsalva.es (Portal con iframe) ---
|
||
app.post("/public/energy-quote", energyQuoteLimiter, async (req, res) => {
|
||
try {
|
||
const { email, telefono, codigoPostal, rgpdAceptado, honeypot, archivoBase64, archivoMime } = req.body || {};
|
||
|
||
// Honeypot: si un bot rellena este campo oculto, respondemos "éxito" genérico sin procesar nada.
|
||
if (honeypot) {
|
||
return res.json({ ok: true, message: "Hemos recibido tu factura, te enviamos el estudio en menos de 24h." });
|
||
}
|
||
|
||
if (!email || !telefono || !rgpdAceptado) {
|
||
return res.status(400).json({ ok: false, error: "Faltan datos obligatorios o no se aceptó la polÃtica de privacidad." });
|
||
}
|
||
if (!archivoBase64 || !archivoMime || !ENERGY_ALLOWED_MIME.has(archivoMime)) {
|
||
return res.status(400).json({ ok: false, error: "Formato de archivo no soportado (solo PDF, JPG o PNG)." });
|
||
}
|
||
|
||
const tamanoBytes = Buffer.byteLength(archivoBase64, "base64");
|
||
if (tamanoBytes > ENERGY_MAX_FILE_BYTES) {
|
||
return res.status(400).json({ ok: false, error: "El archivo es demasiado grande (máximo 6MB)." });
|
||
}
|
||
|
||
const ownerId = Number(process.env.ENERGY_QUOTE_OWNER_ID);
|
||
if (!ownerId) {
|
||
console.error("â ENERGY_QUOTE_OWNER_ID no configurado: el comparador de luz no puede guardar leads.");
|
||
return res.status(503).json({ ok: false, error: "Comparador no disponible temporalmente." });
|
||
}
|
||
|
||
// 1) Extraer con IA (el archivo solo vive en esta variable, nunca se escribe a disco)
|
||
let extraido = await extraerFacturaConIA(archivoBase64, archivoMime);
|
||
// Por si la IA ignora la instrucción: nos aseguramos de no guardar nunca estos campos.
|
||
delete extraido.nombre; delete extraido.dni; delete extraido.direccion; delete extraido.iban; delete extraido.cups;
|
||
|
||
const settingsQ = await pool.query("SELECT * FROM energy_settings WHERE owner_id=$1", [ownerId]);
|
||
const settings = settingsQ.rows[0] || {};
|
||
const ieePct = settings.iee_pct ?? 5.1126963;
|
||
const ivaPct = settings.iva_pct ?? 21;
|
||
|
||
const perfil = {
|
||
diasFacturados: extraido.dias_facturados,
|
||
potenciaP1Kw: extraido.potencia_p1_kw,
|
||
potenciaP2Kw: extraido.potencia_p2_kw,
|
||
kwhPunta: extraido.kwh_punta,
|
||
kwhLlano: extraido.kwh_llano,
|
||
kwhValle: extraido.kwh_valle,
|
||
};
|
||
|
||
// 2) Recalcular la factura actual con sus propios precios extraÃdos, y reconciliar (±1â¬)
|
||
const preciosActuales = {
|
||
precioPotenciaP1: extraido.precio_potencia_p1,
|
||
precioPotenciaP2: extraido.precio_potencia_p2,
|
||
precioEnergiaPunta: extraido.precio_energia_punta,
|
||
precioEnergiaLlano: extraido.precio_energia_llano,
|
||
precioEnergiaValle: extraido.precio_energia_valle,
|
||
descuentoPct: extraido.descuento_pct,
|
||
bonoSocialDia: extraido.bono_social_dia,
|
||
alquilerContadorDia: extraido.alquiler_contador_dia,
|
||
};
|
||
const recalculado = calcularFactura(perfil, preciosActuales, ieePct, ivaPct);
|
||
const totalReal = Number(extraido.total_factura) || null;
|
||
const diferencia = totalReal != null ? Math.round((recalculado.total - totalReal) * 100) / 100 : null;
|
||
const revisarManualmente = totalReal == null || Math.abs(diferencia) > 1;
|
||
|
||
// 3) Comparar contra todas las tarifas activas (propias + Repsol + mercado que haya cargado a mano)
|
||
const tarifasQ = await pool.query("SELECT * FROM energy_tariffs WHERE owner_id=$1 AND activa=TRUE", [ownerId]);
|
||
const comparativa = tarifasQ.rows.map((tarifa) => {
|
||
const calculo = calcularFactura(perfil, {
|
||
precioPotenciaP1: tarifa.precio_potencia_p1,
|
||
precioPotenciaP2: tarifa.precio_potencia_p2,
|
||
precioEnergiaPunta: tarifa.precio_energia_punta,
|
||
precioEnergiaLlano: tarifa.precio_energia_llano,
|
||
precioEnergiaValle: tarifa.precio_energia_valle,
|
||
descuentoPct: tarifa.descuento_pct,
|
||
bonoSocialDia: tarifa.bono_social_dia,
|
||
alquilerContadorDia: tarifa.alquiler_contador_dia,
|
||
}, ieePct, ivaPct);
|
||
const base = totalReal != null ? totalReal : recalculado.total;
|
||
const ahorroFactura = Math.round((base - calculo.total) * 100) / 100;
|
||
const dias = Number(perfil.diasFacturados) || 30;
|
||
const ahorroAnual = Math.round((ahorroFactura / dias) * 365 * 100) / 100;
|
||
return { tarifaId: tarifa.id, nombre: tarifa.nombre, tipo: tarifa.tipo, comercializadora: tarifa.comercializadora, total: calculo.total, ahorroFactura, ahorroAnual };
|
||
}).sort((a, b) => b.ahorroFactura - a.ahorroFactura);
|
||
|
||
const mejor = comparativa[0] || null;
|
||
|
||
// 4) Mercado oficial (CNMC) - informativo, nunca bloquea el estudio si falla
|
||
const mercadoCnmc = settings.cnmc_enabled === false ? null : await consultarOfertasCNMC(perfil, codigoPostal);
|
||
|
||
// 5) Guardar el lead
|
||
const leadQ = await pool.query(
|
||
`INSERT INTO energy_quote_leads
|
||
(owner_id, email, telefono, codigo_postal, rgpd_aceptado, rgpd_fecha, factura_json, total_real,
|
||
total_recalculado, diferencia, revisar_manualmente, mejor_tarifa_id, ahorro_estimado_factura,
|
||
ahorro_estimado_anual, comparativa_json, mercado_cnmc_json)
|
||
VALUES ($1,$2,$3,$4,$5,NOW(),$6,$7,$8,$9,$10,$11,$12,$13,$14,$15)
|
||
RETURNING id`,
|
||
[ownerId, email, telefono, codigoPostal || null, true, JSON.stringify(extraido), totalReal,
|
||
recalculado.total, diferencia, revisarManualmente, mejor?.tarifaId || null, mejor?.ahorroFactura || null,
|
||
mejor?.ahorroAnual || null, JSON.stringify(comparativa), mercadoCnmc ? JSON.stringify(mercadoCnmc) : null]
|
||
);
|
||
|
||
// 6) Avisar a Marco por WhatsApp (reutilizando la integración Evolution ya existente)
|
||
const adminPhoneRaw = settings.admin_whatsapp || process.env.ENERGY_ADMIN_WHATSAPP || "";
|
||
const adminPhone = adminPhoneRaw.replace("+", "");
|
||
if (adminPhone) {
|
||
const instanciaEvolution = `cliente_${ownerId}`;
|
||
const aviso = revisarManualmente
|
||
? `â ï¸ Nuevo lead comparador de luz (REVISAR MANUALMENTE)\nEmail: ${email}\nTel: ${telefono}\nLa factura no cuadra con el recálculo (dif: ${diferencia ?? "N/D"}â¬).`
|
||
: `ð¡ Nuevo lead comparador de luz\nEmail: ${email}\nTel: ${telefono}\nMejor tarifa: ${mejor?.nombre || "N/D"} (ahorro ${mejor?.ahorroFactura ?? "N/D"}â¬/factura, ${mejor?.ahorroAnual ?? "N/D"}â¬/año)`;
|
||
sendWhatsAppAuto(adminPhone, aviso, instanciaEvolution, false).catch(console.error);
|
||
}
|
||
|
||
res.json({ ok: true, message: "Hemos recibido tu factura, te enviamos el estudio en menos de 24h.", leadId: leadQ.rows[0].id });
|
||
} catch (e) {
|
||
console.error("â Error en /public/energy-quote:", e.message);
|
||
res.status(500).json({ ok: false, error: "No hemos podido procesar tu factura. Inténtalo de nuevo." });
|
||
}
|
||
});
|
||
|
||
// --- Panel admin: tarifas propias/Repsol/mercado ---
|
||
app.get("/energy-tariffs", authMiddleware, async (req, res) => {
|
||
try {
|
||
const q = await pool.query("SELECT * FROM energy_tariffs WHERE owner_id=$1 ORDER BY tipo ASC, nombre ASC", [req.user.accountId]);
|
||
res.json({ ok: true, tarifas: q.rows });
|
||
} catch (e) { res.status(500).json({ ok: false }); }
|
||
});
|
||
|
||
app.post("/energy-tariffs", authMiddleware, async (req, res) => {
|
||
try {
|
||
const b = req.body || {};
|
||
const q = await pool.query(
|
||
`INSERT INTO energy_tariffs
|
||
(owner_id, tipo, nombre, comercializadora, precio_potencia_p1, precio_potencia_p2,
|
||
precio_energia_punta, precio_energia_llano, precio_energia_valle, descuento_pct,
|
||
bono_social_dia, alquiler_contador_dia, notas, activa)
|
||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14) RETURNING id`,
|
||
[req.user.accountId, b.tipo || "propia", b.nombre, b.comercializadora || null,
|
||
b.precioPotenciaP1 || 0, b.precioPotenciaP2 || 0, b.precioEnergiaPunta || 0,
|
||
b.precioEnergiaLlano || 0, b.precioEnergiaValle || 0, b.descuentoPct || 0,
|
||
b.bonoSocialDia || 0, b.alquilerContadorDia || 0, b.notas || null, b.activa !== false]
|
||
);
|
||
res.json({ ok: true, id: q.rows[0].id });
|
||
} catch (e) { res.status(500).json({ ok: false }); }
|
||
});
|
||
|
||
app.put("/energy-tariffs/:id", authMiddleware, async (req, res) => {
|
||
try {
|
||
const b = req.body || {};
|
||
await pool.query(
|
||
`UPDATE energy_tariffs SET tipo=$1, nombre=$2, comercializadora=$3, precio_potencia_p1=$4,
|
||
precio_potencia_p2=$5, precio_energia_punta=$6, precio_energia_llano=$7, precio_energia_valle=$8,
|
||
descuento_pct=$9, bono_social_dia=$10, alquiler_contador_dia=$11, notas=$12, activa=$13, updated_at=NOW()
|
||
WHERE id=$14 AND owner_id=$15`,
|
||
[b.tipo || "propia", b.nombre, b.comercializadora || null, b.precioPotenciaP1 || 0, b.precioPotenciaP2 || 0,
|
||
b.precioEnergiaPunta || 0, b.precioEnergiaLlano || 0, b.precioEnergiaValle || 0, b.descuentoPct || 0,
|
||
b.bonoSocialDia || 0, b.alquilerContadorDia || 0, b.notas || null, b.activa !== false,
|
||
req.params.id, req.user.accountId]
|
||
);
|
||
res.json({ ok: true });
|
||
} catch (e) { res.status(500).json({ ok: false }); }
|
||
});
|
||
|
||
app.delete("/energy-tariffs/:id", authMiddleware, async (req, res) => {
|
||
try {
|
||
await pool.query("DELETE FROM energy_tariffs 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 }); }
|
||
});
|
||
|
||
// --- Panel admin: leads del comparador ---
|
||
app.get("/energy-leads", authMiddleware, async (req, res) => {
|
||
try {
|
||
const q = await pool.query("SELECT * FROM energy_quote_leads WHERE owner_id=$1 ORDER BY created_at DESC LIMIT 200", [req.user.accountId]);
|
||
res.json({ ok: true, leads: q.rows });
|
||
} catch (e) { res.status(500).json({ ok: false }); }
|
||
});
|
||
|
||
app.patch("/energy-leads/:id", authMiddleware, async (req, res) => {
|
||
try {
|
||
const { estado } = req.body || {};
|
||
await pool.query("UPDATE energy_quote_leads SET estado=$1 WHERE id=$2 AND owner_id=$3", [estado, req.params.id, req.user.accountId]);
|
||
res.json({ ok: true });
|
||
} catch (e) { res.status(500).json({ ok: false }); }
|
||
});
|
||
|
||
|
||
// =====================================================================
|
||
// Comparador de luz: generación del PDF detallado de la comparativa
|
||
// (con logo de Marsalva y, si la mejor tarifa es de Repsol, su logo)
|
||
// y envÃo por WhatsApp al cliente desde el panel de leads.
|
||
// =====================================================================
|
||
|
||
const MARSALVA_LOGO_PATH = path.join(__dirname, "assets", "logos", "marsalva.png");
|
||
const REPSOL_LOGO_PATH = path.join(__dirname, "assets", "logos", "repsol.png");
|
||
|
||
const PDF_COLOR_DARK = rgb(0x0f / 255, 0x17 / 255, 0x2a / 255);
|
||
const PDF_COLOR_GRAY = rgb(0x64 / 255, 0x74 / 255, 0x8b / 255);
|
||
const PDF_COLOR_LIGHT_GRAY = rgb(0xe2 / 255, 0xe8 / 255, 0xf0 / 255);
|
||
const PDF_COLOR_GREEN = rgb(0x05 / 255, 0x96 / 255, 0x69 / 255);
|
||
const PDF_COLOR_GREEN_BG = rgb(0xec / 255, 0xfd / 255, 0xf5 / 255);
|
||
const PDF_COLOR_AMBER = rgb(0xb4 / 255, 0x53 / 255, 0x09 / 255);
|
||
const PDF_COLOR_AMBER_BG = rgb(0xff / 255, 0xfb / 255, 0xeb / 255);
|
||
|
||
function pdfFmtEuro(n) {
|
||
if (n === null || n === undefined || n === "") return "â";
|
||
return Number(n).toLocaleString("es-ES", { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + " â¬";
|
||
}
|
||
function pdfFmtVal(v) {
|
||
if (v === null || v === undefined || v === "") return "â";
|
||
return String(v);
|
||
}
|
||
|
||
async function embedLogoIfExists(pdfDoc, logoPath) {
|
||
try {
|
||
if (!logoPath || !fs.existsSync(logoPath)) return null;
|
||
const bytes = fs.readFileSync(logoPath);
|
||
if (logoPath.toLowerCase().endsWith(".jpg") || logoPath.toLowerCase().endsWith(".jpeg")) {
|
||
return await pdfDoc.embedJpg(bytes);
|
||
}
|
||
return await pdfDoc.embedPng(bytes);
|
||
} catch (e) {
|
||
console.error("No se pudo incrustar el logo", logoPath, e.message);
|
||
return null;
|
||
}
|
||
}
|
||
|
||
async function generarPdfComparativaLuz(lead) {
|
||
const fj = lead.factura_json || {};
|
||
const comparativa = Array.isArray(lead.comparativa_json) ? lead.comparativa_json : [];
|
||
const mejor = comparativa[0] || null;
|
||
|
||
const pdfDoc = await PDFDocument.create();
|
||
const PAGE_W = 595.28, PAGE_H = 841.89; // A4
|
||
const MARGIN = 42;
|
||
let page = pdfDoc.addPage([PAGE_W, PAGE_H]);
|
||
const font = await pdfDoc.embedFont(StandardFonts.Helvetica);
|
||
const fontBold = await pdfDoc.embedFont(StandardFonts.HelveticaBold);
|
||
|
||
const marsalvaLogo = await embedLogoIfExists(pdfDoc, MARSALVA_LOGO_PATH);
|
||
const repsolLogo = await embedLogoIfExists(pdfDoc, REPSOL_LOGO_PATH);
|
||
|
||
let y = PAGE_H - MARGIN;
|
||
|
||
function ensureSpace(h) {
|
||
if (y - h < MARGIN + 30) {
|
||
page = pdfDoc.addPage([PAGE_W, PAGE_H]);
|
||
y = PAGE_H - MARGIN;
|
||
}
|
||
}
|
||
|
||
function drawText(text, x, yy, opts) {
|
||
opts = opts || {};
|
||
const size = opts.size || 10;
|
||
const bold = !!opts.bold;
|
||
const color = opts.color || PDF_COLOR_DARK;
|
||
const align = opts.align || "left";
|
||
const maxWidth = opts.maxWidth != null ? opts.maxWidth : null;
|
||
const f = bold ? fontBold : font;
|
||
let drawX = x;
|
||
if (align === "right" && maxWidth != null) {
|
||
const w = f.widthOfTextAtSize(text, size);
|
||
drawX = x + maxWidth - w;
|
||
}
|
||
page.drawText(text, { x: drawX, y: yy, size, font: f, color });
|
||
}
|
||
|
||
function wrapText(text, maxWidth, size, f) {
|
||
const words = String(text).split(" ");
|
||
const lines = [];
|
||
let current = "";
|
||
for (const w of words) {
|
||
const test = current ? current + " " + w : w;
|
||
if (f.widthOfTextAtSize(test, size) > maxWidth && current) {
|
||
lines.push(current);
|
||
current = w;
|
||
} else {
|
||
current = test;
|
||
}
|
||
}
|
||
if (current) lines.push(current);
|
||
return lines;
|
||
}
|
||
|
||
// ---------- CABECERA ----------
|
||
const headerH = 54;
|
||
if (marsalvaLogo) {
|
||
const scale = headerH / marsalvaLogo.height;
|
||
const w = marsalvaLogo.width * scale;
|
||
page.drawImage(marsalvaLogo, { x: MARGIN, y: y - headerH, width: w, height: headerH });
|
||
} else {
|
||
drawText("MARSALVA", MARGIN, y - 24, { size: 18, bold: true });
|
||
}
|
||
y -= headerH + 14;
|
||
|
||
page.drawLine({ start: { x: MARGIN, y }, end: { x: PAGE_W - MARGIN, y }, thickness: 1, color: PDF_COLOR_LIGHT_GRAY });
|
||
y -= 24;
|
||
|
||
drawText("Estudio comparativo de tu factura de luz", MARGIN, y, { size: 16, bold: true });
|
||
y -= 16;
|
||
const fecha = new Date().toLocaleDateString("es-ES", { day: "2-digit", month: "long", year: "numeric" });
|
||
drawText(`Fecha del estudio: ${fecha}`, MARGIN, y, { size: 9, color: PDF_COLOR_GRAY });
|
||
y -= 28;
|
||
|
||
// ---------- RESUMEN DESTACADO DE AHORRO ----------
|
||
const ahorroFactura = lead.ahorro_estimado_factura;
|
||
const ahorroAnual = lead.ahorro_estimado_anual;
|
||
const tieneAhorro = mejor && Number(ahorroFactura) > 0;
|
||
|
||
const boxH = 70;
|
||
ensureSpace(boxH + 10);
|
||
page.drawRectangle({
|
||
x: MARGIN, y: y - boxH, width: PAGE_W - MARGIN * 2, height: boxH,
|
||
color: tieneAhorro ? PDF_COLOR_GREEN_BG : PDF_COLOR_AMBER_BG,
|
||
borderColor: tieneAhorro ? PDF_COLOR_GREEN : PDF_COLOR_AMBER,
|
||
borderWidth: 1,
|
||
});
|
||
if (tieneAhorro) {
|
||
drawText(`Mejor opción encontrada: ${mejor.nombre}`, MARGIN + 16, y - 24, { size: 12, bold: true, color: PDF_COLOR_GREEN });
|
||
drawText(`Ahorro estimado: ${pdfFmtEuro(ahorroFactura)} en esta factura ⢠${pdfFmtEuro(ahorroAnual)} al año`, MARGIN + 16, y - 42, { size: 10.5, color: PDF_COLOR_DARK });
|
||
if (repsolLogo && /repsol/i.test(mejor.nombre || "")) {
|
||
const rh = 28;
|
||
const rw = repsolLogo.width * (rh / repsolLogo.height);
|
||
page.drawImage(repsolLogo, { x: PAGE_W - MARGIN - 16 - rw, y: y - boxH / 2 - rh / 2, width: rw, height: rh });
|
||
}
|
||
drawText("Estudio orientativo según los datos de tu factura y las tarifas publicadas a fecha de hoy.", MARGIN + 16, y - 58, { size: 7.5, color: PDF_COLOR_GRAY });
|
||
} else {
|
||
drawText("Con los datos de tu factura actual, hoy no encontramos una tarifa que te suponga un ahorro claro.", MARGIN + 16, y - 24, { size: 10.5, bold: true, color: PDF_COLOR_AMBER });
|
||
drawText("Aun asÃ, aquà tienes el detalle completo de la comparativa realizada.", MARGIN + 16, y - 42, { size: 9.5, color: PDF_COLOR_DARK });
|
||
}
|
||
y -= boxH + 26;
|
||
|
||
// ---------- TABLA: TU FACTURA ACTUAL ----------
|
||
ensureSpace(30);
|
||
drawText("Tu factura actual", MARGIN, y, { size: 12.5, bold: true });
|
||
y -= 18;
|
||
|
||
const filasFactura = [
|
||
["Comercializadora", pdfFmtVal(fj.comercializadora)],
|
||
["Tarifa de acceso", pdfFmtVal(fj.tarifa_acceso)],
|
||
["DÃas facturados", pdfFmtVal(fj.dias_facturados)],
|
||
["Potencia contratada P1 / P2 (kW)", `${pdfFmtVal(fj.potencia_p1_kw)} / ${pdfFmtVal(fj.potencia_p2_kw)}`],
|
||
["Consumo punta / llano / valle (kWh)", `${pdfFmtVal(fj.kwh_punta)} / ${pdfFmtVal(fj.kwh_llano)} / ${pdfFmtVal(fj.kwh_valle)}`],
|
||
["Precio energÃa punta / llano / valle (â¬/kWh)", `${pdfFmtVal(fj.precio_energia_punta)} / ${pdfFmtVal(fj.precio_energia_llano)} / ${pdfFmtVal(fj.precio_energia_valle)}`],
|
||
["Descuento aplicado", `${fj.descuento_pct ?? 0}%${fj.descuento_aplica_a ? " (" + fj.descuento_aplica_a + ")" : ""}`],
|
||
["Permanencia", fj.permanencia ? `${fj.permanencia}${fj.permanencia_fecha_fin ? " hasta " + fj.permanencia_fecha_fin : ""}` : "Sin permanencia"],
|
||
["Total de la factura", pdfFmtEuro(lead.total_real)],
|
||
];
|
||
|
||
const rowH = 18;
|
||
for (const fila of filasFactura) {
|
||
const label = fila[0], value = fila[1];
|
||
ensureSpace(rowH);
|
||
drawText(label, MARGIN, y, { size: 9, color: PDF_COLOR_GRAY });
|
||
drawText(value, MARGIN, y, { size: 9, bold: true, color: PDF_COLOR_DARK, align: "right", maxWidth: PAGE_W - MARGIN * 2 });
|
||
y -= rowH;
|
||
page.drawLine({ start: { x: MARGIN, y: y + 5 }, end: { x: PAGE_W - MARGIN, y: y + 5 }, thickness: 0.5, color: PDF_COLOR_LIGHT_GRAY });
|
||
}
|
||
y -= 16;
|
||
|
||
// ---------- TABLA: COMPARATIVA DE TARIFAS ----------
|
||
ensureSpace(30);
|
||
drawText("Comparativa con tarifas disponibles", MARGIN, y, { size: 12.5, bold: true });
|
||
y -= 20;
|
||
|
||
if (comparativa.length === 0) {
|
||
drawText("No habÃa tarifas activas para comparar en el momento del estudio.", MARGIN, y, { size: 9.5, color: PDF_COLOR_GRAY });
|
||
y -= 20;
|
||
} else {
|
||
const colTarifaW = 205, colTotalW = 95, colAhorroFW = 100, colAhorroAW = 101;
|
||
ensureSpace(20);
|
||
drawText("Tarifa", MARGIN, y, { size: 8.5, bold: true, color: PDF_COLOR_GRAY });
|
||
drawText("Total/factura", MARGIN + colTarifaW, y, { size: 8.5, bold: true, color: PDF_COLOR_GRAY, align: "right", maxWidth: colTotalW });
|
||
drawText("Ahorro/factura", MARGIN + colTarifaW + colTotalW, y, { size: 8.5, bold: true, color: PDF_COLOR_GRAY, align: "right", maxWidth: colAhorroFW });
|
||
drawText("Ahorro/año", MARGIN + colTarifaW + colTotalW + colAhorroFW, y, { size: 8.5, bold: true, color: PDF_COLOR_GRAY, align: "right", maxWidth: colAhorroAW });
|
||
y -= 14;
|
||
page.drawLine({ start: { x: MARGIN, y: y + 6 }, end: { x: PAGE_W - MARGIN, y: y + 6 }, thickness: 0.75, color: PDF_COLOR_DARK });
|
||
y -= 6;
|
||
|
||
comparativa.slice(0, 8).forEach((c, i) => {
|
||
ensureSpace(20);
|
||
const isWinner = i === 0;
|
||
if (isWinner) {
|
||
page.drawRectangle({ x: MARGIN - 4, y: y - 5, width: PAGE_W - MARGIN * 2 + 8, height: 17, color: PDF_COLOR_GREEN_BG });
|
||
}
|
||
const prefijo = isWinner ? "MEJOR: " : "";
|
||
let nombre = prefijo + (c.nombre || "â");
|
||
const fUsada = isWinner ? fontBold : font;
|
||
const maxW = colTarifaW - 4;
|
||
if (fUsada.widthOfTextAtSize(nombre, 9) > maxW) {
|
||
while (nombre.length > prefijo.length + 1 && fUsada.widthOfTextAtSize(nombre + "â¦", 9) > maxW) {
|
||
nombre = nombre.slice(0, -1);
|
||
}
|
||
nombre += "â¦";
|
||
}
|
||
drawText(nombre, MARGIN, y, { size: 9, bold: isWinner, color: isWinner ? PDF_COLOR_GREEN : PDF_COLOR_DARK });
|
||
drawText(pdfFmtEuro(c.total), MARGIN + colTarifaW, y, { size: 9, bold: isWinner, color: isWinner ? PDF_COLOR_GREEN : PDF_COLOR_DARK, align: "right", maxWidth: colTotalW });
|
||
const signoF = Number(c.ahorroFactura) >= 0 ? "+" : "";
|
||
const signoA = Number(c.ahorroAnual) >= 0 ? "+" : "";
|
||
drawText(`${signoF}${pdfFmtEuro(c.ahorroFactura)}`, MARGIN + colTarifaW + colTotalW, y, { size: 9, bold: isWinner, color: isWinner ? PDF_COLOR_GREEN : PDF_COLOR_DARK, align: "right", maxWidth: colAhorroFW });
|
||
drawText(`${signoA}${pdfFmtEuro(c.ahorroAnual)}`, MARGIN + colTarifaW + colTotalW + colAhorroFW, y, { size: 9, bold: isWinner, color: isWinner ? PDF_COLOR_GREEN : PDF_COLOR_DARK, align: "right", maxWidth: colAhorroAW });
|
||
y -= 19;
|
||
});
|
||
y -= 10;
|
||
}
|
||
|
||
// ---------- PIE ----------
|
||
ensureSpace(60);
|
||
page.drawLine({ start: { x: MARGIN, y }, end: { x: PAGE_W - MARGIN, y }, thickness: 1, color: PDF_COLOR_LIGHT_GRAY });
|
||
y -= 16;
|
||
const disclaimer = "Este estudio se ha generado de forma automática a partir de los datos extraÃdos de tu factura y de las tarifas publicadas por las compañÃas comparadas en la fecha indicada. Los importes son orientativos y pueden variar según condiciones particulares del contrato final.";
|
||
const discLines = wrapText(disclaimer, PAGE_W - MARGIN * 2, 7.5, font);
|
||
discLines.forEach((line) => {
|
||
drawText(line, MARGIN, y, { size: 7.5, color: PDF_COLOR_GRAY });
|
||
y -= 10;
|
||
});
|
||
|
||
const bytes = await pdfDoc.save();
|
||
return Buffer.from(bytes);
|
||
}
|
||
|
||
// --- Genera el PDF de la comparativa de un lead y lo envÃa por WhatsApp al cliente ---
|
||
app.post("/energy-leads/:id/send-pdf", authMiddleware, async (req, res) => {
|
||
try {
|
||
const ownerId = req.user.accountId;
|
||
const q = await pool.query("SELECT * FROM energy_quote_leads WHERE id=$1 AND owner_id=$2", [req.params.id, ownerId]);
|
||
const lead = q.rows[0];
|
||
if (!lead) return res.status(404).json({ ok: false, detail: "Lead no encontrado" });
|
||
if (!lead.telefono) return res.status(400).json({ ok: false, detail: "El lead no tiene teléfono guardado" });
|
||
|
||
const telefonoNormalizado = normalizePhone(lead.telefono);
|
||
if (!telefonoNormalizado) {
|
||
return res.status(400).json({ ok: false, detail: "El teléfono del lead no es válido" });
|
||
}
|
||
|
||
let pdfToken = lead.pdf_token;
|
||
if (!pdfToken) {
|
||
pdfToken = crypto.randomUUID();
|
||
await pool.query("UPDATE energy_quote_leads SET pdf_token=$1 WHERE id=$2", [pdfToken, lead.id]);
|
||
}
|
||
|
||
const enlace = `https://portal.integrarepara.es/estudio-luz.html?token=${pdfToken}`;
|
||
|
||
const mejor = Array.isArray(lead.comparativa_json) ? lead.comparativa_json[0] : null;
|
||
const tieneAhorro = mejor && Number(lead.ahorro_estimado_factura) > 0;
|
||
const mensaje = tieneAhorro
|
||
? `Hola! Ya tenemos listo tu estudio comparativo de la factura de luz. Con ${mejor.nombre} podrías ahorrar ${Number(lead.ahorro_estimado_factura).toFixed(2)}€ en esta factura y ${Number(lead.ahorro_estimado_anual || 0).toFixed(2)}€ al año.\n\nConsulta y descarga el estudio completo aquí:\n${enlace}`
|
||
: `Hola! Ya tenemos listo tu estudio comparativo de la factura de luz. Consulta y descarga el estudio completo aquí:\n${enlace}`;
|
||
|
||
const instanciaEvolution = `cliente_${ownerId}`;
|
||
const enviado = await sendWhatsAppAuto(telefonoNormalizado, mensaje, instanciaEvolution, false);
|
||
|
||
if (!enviado) {
|
||
return res.status(502).json({ ok: false, detail: "No se pudo enviar el WhatsApp con el enlace del PDF" });
|
||
}
|
||
|
||
await pool.query("UPDATE energy_quote_leads SET pdf_enviado=true, pdf_enviado_at=NOW() WHERE id=$1 AND owner_id=$2", [req.params.id, ownerId]);
|
||
|
||
res.json({ ok: true, link: enlace });
|
||
} catch (e) {
|
||
console.error("Error enviando enlace del PDF de comparativa de luz:", e);
|
||
res.status(500).json({ ok: false, detail: "Error generando o enviando el enlace del PDF" });
|
||
}
|
||
});
|
||
|
||
// --- Sirve el PDF de la comparativa de luz al cliente mediante su enlace público permanente ---
|
||
app.get("/public/energy-quote/:token/pdf", async (req, res) => {
|
||
try {
|
||
const q = await pool.query("SELECT * FROM energy_quote_leads WHERE pdf_token=$1", [req.params.token]);
|
||
const lead = q.rows[0];
|
||
if (!lead) return res.status(404).send("Estudio no encontrado o enlace caducado.");
|
||
|
||
const pdfBuffer = await generarPdfComparativaLuz(lead);
|
||
res.setHeader("Content-Type", "application/pdf");
|
||
res.setHeader("Content-Disposition", 'inline; filename="estudio-comparativa-luz.pdf"');
|
||
res.send(pdfBuffer);
|
||
} catch (e) {
|
||
console.error("Error sirviendo PDF público de comparativa de luz:", e);
|
||
res.status(500).send("No se pudo generar el PDF.");
|
||
}
|
||
});
|
||
|
||
// --- Panel admin: ajustes (IEE, IVA, modelo IA, WhatsApp de aviso, activar/desactivar CNMC) ---
|
||
app.get("/energy-settings", authMiddleware, async (req, res) => {
|
||
try {
|
||
const q = await pool.query("SELECT * FROM energy_settings WHERE owner_id=$1", [req.user.accountId]);
|
||
res.json({ ok: true, settings: q.rows[0] || null });
|
||
} catch (e) { res.status(500).json({ ok: false }); }
|
||
});
|
||
|
||
app.put("/energy-settings", authMiddleware, async (req, res) => {
|
||
try {
|
||
const b = req.body || {};
|
||
await pool.query(
|
||
`INSERT INTO energy_settings (owner_id, iee_pct, iva_pct, openai_model, cnmc_enabled, admin_whatsapp, updated_at)
|
||
VALUES ($1,$2,$3,$4,$5,$6,NOW())
|
||
ON CONFLICT (owner_id) DO UPDATE SET iee_pct=$2, iva_pct=$3, openai_model=$4, cnmc_enabled=$5, admin_whatsapp=$6, updated_at=NOW()`,
|
||
[req.user.accountId, b.ieePct ?? 5.1126963, b.ivaPct ?? 21, b.openaiModel || null, b.cnmcEnabled !== false, b.adminWhatsapp || null]
|
||
);
|
||
res.json({ ok: true });
|
||
} catch (e) { res.status(500).json({ ok: false }); }
|
||
});
|
||
|
||
|
||
|
||
const port = process.env.PORT || 3000;
|
||
autoUpdateDB().then(() => { app.listen(port, "0.0.0.0", () => console.log(`ð Server OK en puerto ${port}`)); }); |