37 Commits

Author SHA1 Message Date
29fd339398 WhatsApp de Claude: pausa temporal de la IA (30 min) que se quita sola
Sustituye los endpoints /services/:id/whatsapp e /services/:id/ia de este PR: en vez de pausar la IA indefinidamente, la pausa durante 30 min (ia_paused_until) y se reactiva sola. Nuevo /services/:id/ia/resume. Los mensajes de Claude no activan el escudo humano de 120 min. El emoji 🟢 también quita la pausa temporal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WWFY3ABzJiRZVLaqum8Fg1
2026-11-25 15:03:39 +00:00
9cb0bc7d21 Conector: enviar_whatsapp (pausa 30 min) y reactivar_asistente
Sustituye enviar_whatsapp_cliente y pausar_ia_expediente.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WWFY3ABzJiRZVLaqum8Fg1
2026-11-25 15:03:06 +00:00
3471f2102e MCP: herramientas enviar_whatsapp_cliente y pausar_ia_expediente 2026-11-25 08:13:04 +00:00
c94ab7e054 WhatsApp: enviar texto libre al cliente y pausar/reactivar la IA por expediente 2026-11-25 08:13:02 +00:00
689e029f00 Presupuestos: archivar el expediente PRE-xxx al rechazarse
Cuando el cliente rechaza un presupuesto (portal o cambio de estado desde el panel/MCP), su expediente PRE-<id> se archiva en estado Anulado y se le quita budget_mode, para que no quede abierto ni el asistente de WhatsApp lo trate como pendiente. Si después se acepta, se reabre (solo si se archivó por rechazo). No toca servicios de compañías.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WWFY37srpxpPcZiSR6ekwB
2026-11-24 18:26:42 +00:00
a935b7cbb0 WhatsApp: no pedir disponibilidad si el servicio ya tiene cita
Al asignar tecnico en la edicion de servicio: sin fecha/hora -> wa_evt_assigned; con fecha/hora -> wa_evt_date; si ademas pasa a Citado no se duplica el aviso.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WWFY39s3XeGu7Zwr8YWyjm
2026-11-23 22:16:08 +00:00
541c5ba5e8 WhatsApp IA: anteponer "ASISTENTE IA:" a los mensajes automáticos de la IA
- Nuevo helper conPrefijoIA() (no duplica el prefijo si la IA ya lo puso).
- Se aplica a la respuesta de la IA al cliente y al mensaje de apertura del comando de admin.
- El historial del panel se sigue guardando sin prefijo (ya figura como Asistente IA).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WWFY395YKdGaAzwkwy3St4
2026-11-22 18:51:33 +00:00
44947367fd OAuth MCP: permitir volver a la app que conecta (Claude) en form-action 2026-11-22 09:20:03 +00:00
318af7b330 Actualizar integra-mcp/oauth.mjs 2026-11-08 21:03:32 +00:00
7c7419aa7d Subir archivos a "/" 2026-11-08 20:50:25 +00:00
85a32244af Subir archivos a "integra-mcp" 2026-11-08 20:41:53 +00:00
ea7792d642 Actualizar integra-mcp/oauth.mjs 2026-11-08 20:05:13 +00:00
365e6a68f9 Subir archivos a "integra-mcp" 2026-11-08 19:39:38 +00:00
988b06b196 Actualizar package.json 2026-11-08 19:06:48 +00:00
6f2798b3ab Subir archivos a "integra-mcp" 2026-11-08 18:58:22 +00:00
716f1f6bc7 Subir archivos a "integra-mcp" 2026-11-08 18:57:59 +00:00
aa3d296160 Actualizar package.json 2026-11-08 18:52:09 +00:00
0f899850be Actualizar server.js 2026-11-08 18:51:15 +00:00
38b1d925f3 Actualizar server.js 2026-10-13 07:14:48 +00:00
13c258bda5 Actualizar server.js 2026-10-04 21:51:44 +00:00
e749b58f97 Permite CORS desde marsalva.es para el nuevo formulario de la landing de ahorro de luz 2026-10-04 18:43:39 +00:00
0520fc915e Corrige la posicion de las lineas separadoras de la tabla de factura en el PDF (cortaban el texto de la fila siguiente) 2026-10-04 16:27:51 +00:00
545a0d17cb Añade el logo real de Marsalva (desde la configuración de la web) para el PDF de comparativa de luz 2026-10-04 16:00:28 +00:00
8469b3931d Reaplica mejoras de lectura de IA (precios llano/valle con detail:high, suma de lineas de descuento) que se habian quedado fuera al reconstruir server.js sobre una base limpia 2026-10-04 15:49:26 +00:00
ca9dc95232 Reconstruye el PDF de comparativa de luz sobre una base limpia (corrige corrupcion de codificacion UTF-8 introducida por commits anteriores de hoy) y sanea los textos de la factura en origen 2026-10-04 15:47:00 +00:00
e1b8f8c8b5 Aplica tambien el saneado de texto en wrapText (otro punto donde fallaba WinAnsi) 2026-10-04 15:33:37 +00:00
2494573452 Corrige caracteres mal codificados en datos de factura que rompian la generacion del PDF (WinAnsi 0x82) 2026-10-04 15:29:29 +00:00
5bb09e3f80 Cambia el envio de PDF por enlace de descarga permanente en el portal del cliente 2026-10-04 15:23:19 +00:00
5dcd20a76b Corrige comentario SQL inválido (// -> --) que rompía la migración de la base de datos 2026-10-04 14:59:42 +00:00
8c8fb375b7 Añade dependencia pdf-lib (generación de PDFs de la comparativa de luz) 2026-10-04 14:30:42 +00:00
8070af11d8 Añade generación y envío por WhatsApp del PDF detallado de la comparativa de luz (logo Marsalva + Repsol) 2026-10-04 14:30:32 +00:00
8ee1277eac Añade logo de Repsol para generar PDFs de comparativa de luz 2026-10-04 14:19:15 +00:00
5c18541ebb Mejora: pedir a la IA que sume todas las lineas de descuento de la factura (p.ej. fidelidad + promocional) en vez de quedarse solo con la primera 2026-10-04 13:46:11 +00:00
e668036fb9 Mejora: pedir a la IA que busque con más atención los precios de energia llano/valle en facturas con discriminacion horaria, y usar detail:high en la lectura de imagenes 2026-10-04 13:38:50 +00:00
e8a9d73057 Fix: usar instancia Evolution real (cliente_$ownerId) para aviso WhatsApp de leads de luz, en vez de la instancia inexistente ADMIN 2026-10-04 13:23:24 +00:00
fee46a8f67 Actualizar server.js 2026-10-04 12:50:18 +00:00
4230d41071 Merge pull request 'Comparador de facturas de luz (Fase 1): endpoint público, tablas y panel admin' (#3) from feature/comparador-luz into main
Reviewed-on: #3
2026-10-03 21:37:00 +00:00
11 changed files with 1456 additions and 18 deletions

BIN
assets/logos/marsalva.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

BIN
assets/logos/repsol.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

73
integra-mcp/bridge.mjs Normal file
View File

@@ -0,0 +1,73 @@
import { tools, validateBusiness } from './tools.mjs';
import { redact } from './security.mjs';
const ownership = {
service:['scraped_services','owner_id'],block:['scraped_services','owner_id'],
client:['clients','owner_id'],budget:['budgets','owner_id'],article:['articles','owner_id'],
user:['users','owner_id'],guild:['guilds','owner_id'],status:['service_statuses','owner_id'],
company:['companies','owner_id'],zone:['zones','owner_id'],report:['work_reports','owner_id'],
plan:['protection_plans','company_id'],subscription:['protection_subscriptions','company_id'],
tariff:['energy_tariffs','owner_id'],lead:['energy_quote_leads','owner_id']
};
export function makeBridge({ pool, signToken, backendUrl, checkAvailability, fetchImpl=fetch }) {
const base = new URL(backendUrl);
if (base.protocol!=='http:' || base.hostname!=='127.0.0.1' || base.pathname!=='/' || base.search || base.hash || base.username || base.password)
throw new Error('El puente interno solo permite http://127.0.0.1:PUERTO');
async function own(kind,value,user) {
const [table,column]=ownership[kind]; // Fixed identifiers; user input is always parameterized.
const extra=kind==='block'?" AND provider='SYSTEM_BLOCK'":'';
const q=await pool.query(`SELECT id FROM ${table} WHERE id=$1 AND ${column}=$2${extra}`,[value,user.accountId]);
if (!q.rows.length) throw new Error('Registro no encontrado en tu empresa.');
}
return async (name,input,user,scopes) => {
const tool=tools.find(t=>t.name===name);
if (!tool) throw new Error('Herramienta desconocida.');
if (!scopes.includes('integra:read') || (!tool.readOnly && !scopes.includes('integra:write')))
throw new Error('La conexión no tiene permiso para esta operación.');
const args=tool.schema.parse(input);
validateBusiness(tool,args);
if (tool.owner) await own(tool.owner,args.id,user);
for (const [field,kind] of Object.entries(tool.refs)) {
for (const value of [args[field]].flat().filter(v=>v!==undefined&&v!==null)) await own(kind,value,user);
}
for (const value of args.portal_settings?.visible_guilds||[]) await own('guild',value,user);
if (name==='eliminar_usuario' && [user.id,user.accountId].includes(args.id)) throw new Error('No se puede eliminar al usuario conectado ni al propietario.');
if (name==='cambiar_estado_usuario' && args.status!=='active' && [user.id,user.accountId].includes(args.id))
throw new Error('No se puede bloquear al usuario conectado ni al propietario desde el complemento.');
if (['actualizar_expediente','cambiar_cita_estado'].includes(name)) {
const q=await pool.query('SELECT assigned_to,raw_data FROM scraped_services WHERE id=$1 AND owner_id=$2',[args.id,user.accountId]);
const s=q.rows[0]; if (!s) throw new Error('Expediente no encontrado.');
const raw=s.raw_data||{}, worker=args.assigned_to===undefined?s.assigned_to:args.assigned_to;
const day=args.scheduled_date||args.date||raw.scheduled_date;
const hour=args.scheduled_time||args.time||raw.scheduled_time;
if (worker&&day&&hour) {
if (!checkAvailability) throw new Error('Falta conectar comprobarDisponibilidad en el servidor.');
const result=await checkAvailability(user.accountId,worker,day,hour,raw.duration_minutes||60,args.id);
if (result.choca) throw new Error('El horario coincide con otro servicio del técnico.');
}
}
let route=tool.route;
const payload={...args};
for (const match of tool.route.matchAll(/:([A-Za-z_]+)/g)) {
route=route.replace(`:${match[1]}`,encodeURIComponent(String(payload[match[1]])));
delete payload[match[1]];
}
const url=new URL(route,base);
if (tool.query) for (const [k,v] of Object.entries(payload)) if (v!==undefined) url.searchParams.set(k,String(v));
const response=await fetchImpl(url,{
method:tool.method,redirect:'error',signal:AbortSignal.timeout(45000),
headers:{'Content-Type':'application/json',Authorization:`Bearer ${signToken(user)}`},
...(!['GET','DELETE'].includes(tool.method)?{body:JSON.stringify(payload)}:{})
});
// Never propagate upstream error bodies: some supplied routes include stack traces.
if (!response.ok) throw new Error(`IntegraRepara devolvió HTTP ${response.status}; revisa el registro en la web antes de reintentar.`);
const raw=await response.text();
if (raw.length>3000000) throw new Error('Respuesta demasiado grande. Usa buscar_expedientes con filtros.');
let data;try { data=JSON.parse(raw); } catch { throw new Error('La API no ha devuelto JSON.'); }
if (data.ok===false) throw new Error('La API no confirmó la operación. Revisa su estado en la web.');
data=redact(data);
// The API's unpaginated lists can exceed model context. Do not silently omit rows.
if (JSON.stringify(data).length>180000) throw new Error('Resultado demasiado amplio para el chat. Usa una búsqueda con texto o fechas en la web o en buscar_expedientes.');
return data;
};
}

89
integra-mcp/mount.mjs Normal file
View File

@@ -0,0 +1,89 @@
import express from 'express';
import rateLimit from 'integra-mcp-rate-limit';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
import { PgStore, hash } from './store.mjs';
import { oauthRouter, accountAccess } from './oauth.mjs';
import { normalizeOrigin } from './security.mjs';
import { tools } from './tools.mjs';
import { makeBridge } from './bridge.mjs';
export async function mountIntegraMcp({app,pool,signToken,checkAvailability,store:providedStore,
publicOrigin=process.env.INTEGRA_MCP_PUBLIC_ORIGIN,
redirectUris=String(process.env.INTEGRA_MCP_REDIRECT_URIS||'').split(',').map(s=>s.trim()).filter(Boolean),
backendUrl=`http://127.0.0.1:${process.env.PORT||3000}`,
access:providedAccess,bridge:providedBridge,audit:providedAudit
}) {
const origin=normalizeOrigin(publicOrigin),store=providedStore||new PgStore(pool);
await store.init();
const access=providedAccess||accountAccess(pool);
const bridge=providedBridge||makeBridge({pool,signToken,backendUrl,checkAvailability});
if (!providedAudit) await pool.query(`CREATE TABLE IF NOT EXISTS integra_mcp_audit (
id BIGSERIAL PRIMARY KEY, user_id INT NOT NULL, owner_id INT NOT NULL,
tool TEXT NOT NULL, target_id INT, success BOOLEAN NOT NULL, created_at TIMESTAMPTZ DEFAULT now()
)`);
const audit=providedAudit||((user,name,args,success)=>pool.query(
'INSERT INTO integra_mcp_audit(user_id,owner_id,tool,target_id,success) VALUES ($1,$2,$3,$4,$5)',
[user.id,user.accountId,name,Number.isInteger(args.id)?args.id:null,success]));
const router=express.Router();
const allowedOrigins=new Set([origin,...String(process.env.INTEGRA_MCP_ALLOWED_ORIGINS||'').split(',').filter(Boolean)]);
router.use((req,res,next)=>{
if (req.headers.origin&&!allowedOrigins.has(req.headers.origin)) return res.status(403).json({error:'origin_not_allowed'});
next();
});
router.use(oauthRouter({store,origin,...access,redirectUris}));
router.get('/mcp-connect/status',(req,res)=>res.json({
name:'IntegraRepara',version:'0.1.1',mcp:`${origin}/mcp`,authentication:'oauth',
oauthConfigured:redirectUris.length>0,toolCount:tools.length
}));
const mcpLimit=rateLimit({windowMs:60000,limit:120,standardHeaders:'draft-8',legacyHeaders:false});
router.all('/mcp',mcpLimit,express.json({limit:'10mb'}),async(req,res,next)=>{
try {
res.set('Cache-Control','no-store');
const bearer=String(req.headers.authorization||'').match(/^Bearer ([A-Za-z0-9_-]{43})$/)?.[1];
const auth=bearer?await store.get('access',hash(bearer)):null;
const user=auth?await access.currentUser(auth.userId):null;
if (!auth || auth.resource!==`${origin}/mcp` || !user || !await store.get('grant',auth.grantId)) {
res.set('WWW-Authenticate',`Bearer resource_metadata="${origin}/.well-known/oauth-protected-resource/mcp", scope="integra:read integra:write"`);
return res.status(401).json({error:'unauthorized'});
}
if (req.method!=='POST') return res.status(405).set('Allow','POST').json({error:'method_not_allowed'});
const server=new McpServer({name:'integrarepara',version:'0.1.1'});
for (const tool of tools) {
if (!tool.readOnly&&!auth.scopes.includes('integra:write')) continue;
server.registerTool(tool.name,{
description:tool.description,inputSchema:tool.schema,
annotations:{readOnlyHint:tool.readOnly,destructiveHint:!tool.readOnly,idempotentHint:tool.readOnly,openWorldHint:!tool.readOnly}
},async(args)=>{
let success=false;
try {
// Re-read account access per call, including long-running batches.
const fresh=await access.currentUser(user.id);
if (!fresh||fresh.accountId!==user.accountId||!await store.get('grant',auth.grantId)) throw new Error('La autorización ha caducado.');
const data=await bridge(tool.name,args,fresh,auth.scopes);success=true;
return {content:[{type:'text',text:JSON.stringify(data)}]};
} catch(err) {
const known=err.name==='ZodError'?'Parámetros inválidos.':err.name==='AbortError'||err.name==='TimeoutError'?
'Tiempo agotado. La operación puede haberse realizado; comprueba el estado antes de reintentar.':err.message;
return {isError:true,content:[{type:'text',text:known}]};
} finally {
try {await audit(user,tool.name,args,success);} catch { console.error('[Integra MCP] No se pudo registrar auditoría.'); }
}
});
}
const transport=new StreamableHTTPServerTransport({sessionIdGenerator:undefined,enableJsonResponse:true});
res.on('close',()=>{void transport.close();void server.close();});
await server.connect(transport);
await transport.handleRequest(req,res,req.body);
} catch(err) {next(err);}
});
router.use((err,req,res,next)=>{
if (res.headersSent) return next(err);
console.error('[Integra MCP]',err.name);
res.status(500).json({error:'server_error'});
});
app.use(router);
const timer=setInterval(()=>{store.cleanup().catch(()=>console.error('[Integra MCP] Falló limpieza OAuth.'));},3600000);
timer.unref();
return {stopCleanup:()=>clearInterval(timer),toolCount:tools.length};
}

192
integra-mcp/oauth.mjs Normal file
View File

@@ -0,0 +1,192 @@
import { randomBytes, createHash, timingSafeEqual } from 'node:crypto';
import express from 'express';
import bcrypt from 'bcryptjs';
import rateLimit from 'integra-mcp-rate-limit';
import { hash } from './store.mjs';
import { safeRedirect, redirectAllowed } from './security.mjs';
const random = () => randomBytes(32).toString('base64url');
const equal = (a,b) => typeof a === 'string' && typeof b === 'string' && a.length === b.length &&
timingSafeEqual(Buffer.from(a),Buffer.from(b));
const esc = s => String(s).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
const scopesAllowed = ['integra:read','integra:write'];
const fail = (res,error='invalid_request',status=400) => res.status(status).json({error});
const wrap = fn => (req,res,next) => Promise.resolve(fn(req,res)).catch(next);
const denialMessages = Object.freeze({
invalid_origin:'El formulario no se ha enviado desde el origen de IntegraRepara.',
invalid_form:'Falta el identificador del formulario. Abre una conexión nueva.',
flow_missing_or_expired:'La conexión ha caducado o ya se ha utilizado. Abre una conexión nueva.',
cookie_missing:'El navegador no ha enviado la cookie de esta conexión.',
cookie_mismatch:'La cookie corresponde a otro formulario. Cierra los anteriores y abre una conexión nueva.',
callback_not_allowed:'El callback de esta conexión ya no está permitido en el servidor.',
invalid_credentials:'No se ha podido validar el email o teléfono y la contraseña.',
user_not_found:'La cuenta validada ya no existe.',
user_inactive:'La cuenta está inactiva o bloqueada.',
user_not_verified:'La cuenta no tiene la verificación requerida por el conector.',
role_not_admin:'La cuenta validada no tiene rol admin ni superadmin.',
owner_not_found:'No existe el propietario de la empresa asociado a esta cuenta.',
owner_inactive:'El propietario de la empresa está inactivo o bloqueado.',
owner_not_verified:'El propietario de la empresa no tiene la verificación requerida por el conector.',
flow_already_used:'Otra solicitud ya ha utilizado este formulario. Abre una conexión nueva.',
account_rejected:'La cuenta ha sido rechazada por el proveedor de acceso.'
});
function deny(res, reason) {
const safeReason=Object.hasOwn(denialMessages,reason)?reason:'account_rejected';
// Fixed reason codes only. Never log identity, form bodies, credentials or cookies.
console.warn('[Integra MCP OAuth] access_denied:',safeReason);
return res.status(403).json({error:'access_denied',reason:safeReason,error_description:denialMessages[safeReason]});
}
export function oauthRouter({ store, origin, authenticate, currentUser, redirectUris }) {
if (!redirectUris.every(safeRedirect)) throw new Error('Los callbacks deben usar HTTPS o HTTP local en 127.0.0.1.');
const resource = `${origin}/mcp`;
const router = express.Router();
router.use(express.json({limit:'16kb'}),express.urlencoded({extended:false,limit:'16kb'}));
router.use((req,res,next)=>{res.set('Cache-Control','no-store');next();});
const strictLimit = rateLimit({windowMs:15*60000,limit:20,standardHeaders:'draft-8',legacyHeaders:false});
router.get('/.well-known/oauth-authorization-server', (req,res)=>res.json({
issuer:origin,authorization_endpoint:`${origin}/mcp-connect/authorize`,token_endpoint:`${origin}/mcp-connect/token`,
registration_endpoint:`${origin}/mcp-connect/register`,revocation_endpoint:`${origin}/mcp-connect/revoke`,
response_types_supported:['code'],grant_types_supported:['authorization_code','refresh_token'],
code_challenge_methods_supported:['S256'],token_endpoint_auth_methods_supported:['none'],
authorization_response_iss_parameter_supported:true,
scopes_supported:scopesAllowed
}));
for (const route of ['/.well-known/oauth-protected-resource','/.well-known/oauth-protected-resource/mcp']) {
router.get(route,(req,res)=>res.json({resource,authorization_servers:[origin],scopes_supported:scopesAllowed,resource_name:'IntegraRepara'}));
}
router.post('/mcp-connect/register',strictLimit,wrap(async(req,res)=>{
const b=req.body;
if (!Array.isArray(b.redirect_uris) || !b.redirect_uris.length || b.redirect_uris.length>10 ||
!b.redirect_uris.every(u=>redirectAllowed(u,redirectUris)) ||
(b.token_endpoint_auth_method && b.token_endpoint_auth_method!=='none') ||
(b.grant_types && (!Array.isArray(b.grant_types) || !b.grant_types.every(g=>['authorization_code','refresh_token'].includes(g)))) ||
(b.response_types && (!Array.isArray(b.response_types) || b.response_types.some(t=>t!=='code'))))
return fail(res,'invalid_client_metadata');
const client={client_id:random(),client_name:String(b.client_name||'Cliente MCP').slice(0,100),
redirect_uris:b.redirect_uris,token_endpoint_auth_method:'none',grant_types:['authorization_code','refresh_token'],response_types:['code']};
await store.set('client',client.client_id,client,365*86400);
res.status(201).json(client);
}));
router.get('/mcp-connect/authorize',strictLimit,wrap(async(req,res)=>{
const p=req.query;
if (Object.values(p).some(v=>typeof v!=='string')) return fail(res);
const client=await store.get('client',p.client_id);
const scopes=[...new Set(String(p.scope||'integra:read').split(' ').filter(Boolean))];
if (!client || !redirectAllowed(p.redirect_uri,client.redirect_uris) || !redirectAllowed(p.redirect_uri,redirectUris) ||
p.response_type!=='code' || p.code_challenge_method!=='S256' || !/^[A-Za-z0-9_-]{43}$/.test(p.code_challenge||'') ||
p.resource!==resource || !scopes.includes('integra:read') || scopes.some(s=>!scopesAllowed.includes(s)) || (p.state||'').length>2048)
return fail(res);
const requestId=random(),browserSecret=random();
await store.set('flow',hash(requestId),{...p,scopes,browserHash:hash(browserSecret)},600);
res.set({
'Content-Security-Policy':`default-src 'none'; style-src 'unsafe-inline'; form-action 'self' ${new URL(p.redirect_uri).origin} http://127.0.0.1:*; frame-ancestors 'none'; base-uri 'none'`, 'X-Frame-Options':'DENY','Referrer-Policy':'strict-origin','X-Content-Type-Options':'nosniff'
});
res.cookie('integra_mcp_flow',browserSecret,{httpOnly:true,secure:true,sameSite:'lax',path:'/mcp-connect',maxAge:600000});
res.type('html').send(`<!doctype html><html lang="es"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Conectar IntegraRepara</title>
<style>body{font:16px system-ui;background:#f1f5f9;color:#0f172a;padding:24px}main{max-width:480px;margin:6vh auto;background:white;padding:32px;border-radius:16px}label{display:block;margin:16px 0}input,button{box-sizing:border-box;width:100%;padding:12px;font:inherit}button{background:#1e3a8a;color:white;border:0;border-radius:6px}small{overflow-wrap:anywhere}</style>
<main><h1>Conectar IntegraRepara</h1><p>Vas a autorizar a <strong>${esc(client.client_name)}</strong>.</p>
<p>Permisos: consultar datos de tu empresa${scopes.includes('integra:write')?', crear y modificar registros, eliminar registros y activar acciones con WhatsApp según lo que solicites':''}.</p>
<small>Aplicación de destino: ${esc(new URL(p.redirect_uri).origin)}</small>
<form method="post" action="/mcp-connect/consent"><input type="hidden" name="request_id" value="${requestId}">
<label>Email o teléfono<input name="email" autocomplete="username" required maxlength="254"></label>
<label>Contraseña<input type="password" name="password" autocomplete="current-password" required maxlength="1024"></label>
<p>Usa una cuenta administradora de IntegraRepara. La contraseña se comprueba aquí y no se entrega al complemento.</p>
<button>Iniciar sesión y autorizar</button></form><p>Para cancelar, cierra esta ventana.</p></main></html>`);
}));
router.post('/mcp-connect/consent',strictLimit,wrap(async(req,res)=>{
if (req.headers.origin!==origin) return deny(res,'invalid_origin');
if (typeof req.body.request_id!=='string') return deny(res,'invalid_form');
const flow=await store.get('flow',hash(req.body.request_id));
const cookie=String(req.headers.cookie||'').split(';').map(s=>s.trim()).find(s=>s.startsWith('integra_mcp_flow='))?.slice('integra_mcp_flow='.length);
if (!flow) return deny(res,'flow_missing_or_expired');
if (!cookie) return deny(res,'cookie_missing');
if (!equal(flow.browserHash,hash(cookie))) return deny(res,'cookie_mismatch');
if (!redirectAllowed(flow.redirect_uri,redirectUris)) return deny(res,'callback_not_allowed');
let reason='account_rejected';
const user=await authenticate(req.body.email,req.body.password,code=>{if(Object.hasOwn(denialMessages,code))reason=code;});
if (!user) return deny(res,reason);
if (!await store.take('flow',hash(req.body.request_id))) return deny(res,'flow_already_used');
const code=random();
await store.set('code',hash(code),{...flow,userId:user.id},120);
res.clearCookie('integra_mcp_flow',{httpOnly:true,secure:true,sameSite:'lax',path:'/mcp-connect'});
const callback=new URL(flow.redirect_uri);callback.searchParams.set('code',code);
callback.searchParams.set('iss',origin);
if (flow.state) callback.searchParams.set('state',flow.state);
res.redirect(303,callback.href);
}));
async function issue(record,grantId) {
const access=random(),refresh=random();
const data={userId:record.userId,clientId:record.client_id,scopes:record.scopes,resource,grantId};
await store.set('access',hash(access),data,3600);
await store.set('refresh',hash(refresh),data,30*86400);
return {access_token:access,refresh_token:refresh,token_type:'Bearer',expires_in:3600,scope:data.scopes.join(' ')};
}
router.post('/mcp-connect/token',strictLimit,wrap(async(req,res)=>{
const b=req.body;
if (b.resource!==resource || typeof b.client_id!=='string' || !await store.get('client',b.client_id)) return fail(res,'invalid_client');
if (b.grant_type==='authorization_code') {
if (typeof b.code!=='string' || !/^[A-Za-z0-9._~-]{43,128}$/.test(b.code_verifier||'')) return fail(res,'invalid_grant');
const record=await store.get('code',hash(b.code));
const challenge=createHash('sha256').update(b.code_verifier).digest('base64url');
if (!record || record.client_id!==b.client_id || record.redirect_uri!==b.redirect_uri || record.resource!==resource ||
!equal(record.code_challenge,challenge) || !redirectAllowed(record.redirect_uri,redirectUris) || !await currentUser(record.userId))
return fail(res,'invalid_grant');
if (!await store.take('code',hash(b.code))) return fail(res,'invalid_grant');
const grantId=random();await store.set('grant',grantId,{userId:record.userId,clientId:b.client_id},30*86400);
return res.json(await issue(record,grantId));
}
if (b.grant_type==='refresh_token') {
if (typeof b.refresh_token!=='string') return fail(res,'invalid_grant');
const record=await store.get('refresh',hash(b.refresh_token));
if (!record || record.clientId!==b.client_id || record.resource!==resource || !await store.get('grant',record.grantId) || !await currentUser(record.userId))
return fail(res,'invalid_grant');
const scopes=b.scope===undefined?record.scopes:String(b.scope).split(' ').filter(Boolean);
if (!scopes.includes('integra:read') || scopes.some(s=>!record.scopes.includes(s))) return fail(res,'invalid_scope');
if (!await store.take('refresh',hash(b.refresh_token))) return fail(res,'invalid_grant');
return res.json(await issue({userId:record.userId,client_id:b.client_id,scopes},record.grantId));
}
return fail(res,'unsupported_grant_type');
}));
router.post('/mcp-connect/revoke',strictLimit,wrap(async(req,res)=>{
const b=req.body;
if (typeof b.token!=='string' || typeof b.client_id!=='string') return fail(res);
for (const kind of ['access','refresh']) {
const record=await store.get(kind,hash(b.token));
if (record?.clientId===b.client_id) await store.delete('grant',record.grantId);
}
res.status(200).end();
}));
router.use((err,req,res,next)=>{
if (res.headersSent) return next(err);
console.error('[Integra MCP OAuth]',err.name);
res.status(500).json({error:'server_error'});
});
return router;
}
export function accountAccess(pool) {
const rejected = (report,reason) => { if(typeof report==='function')report(reason);return null; };
async function currentUser(userId,report) {
const q=await pool.query('SELECT id,owner_id,role,status,is_verified FROM users WHERE id=$1',[userId]);
const u=q.rows[0];
if (!u) return rejected(report,'user_not_found');
if (u.status!=='active') return rejected(report,'user_inactive');
if (u.is_verified!==true) return rejected(report,'user_not_verified');
if (!['admin','superadmin'].includes(String(u.role).trim().toLowerCase())) return rejected(report,'role_not_admin');
const accountId=u.owner_id||u.id;
const owner=await pool.query('SELECT status,is_verified FROM users WHERE id=$1',[accountId]);
if (!owner.rows[0]) return rejected(report,'owner_not_found');
if (owner.rows[0].status!=='active') return rejected(report,'owner_inactive');
if (owner.rows[0].is_verified!==true) return rejected(report,'owner_not_verified');
return {...u,accountId,role:String(u.role).trim().toLowerCase()};
}
return {currentUser,async authenticate(email,password,report) {
if (typeof email!=='string' || typeof password!=='string' || email.length>254 || password.length>1024) return rejected(report,'invalid_credentials');
const q=await pool.query('SELECT id,password_hash FROM users WHERE email=$1 OR phone=$1 ORDER BY id LIMIT 1',[email]);
const u=q.rows[0];
// A valid dummy bcrypt hash keeps unknown-account failures expensive as well.
const valid=await bcrypt.compare(password,u?.password_hash||'$2b$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy');
return valid&&u?currentUser(u.id,report):rejected(report,'invalid_credentials');
}};
}

49
integra-mcp/security.mjs Normal file
View File

@@ -0,0 +1,49 @@
export function publicBillingSettings(value = {}) {
// Safe for the PUBLIC customer portal. Never return stripe_sk or other keys.
return Object.fromEntries(['iban', 'bank_name', 'account_holder', 'observations', 'stripe_enabled']
.filter(k => Object.hasOwn(value, k)).map(k => [k, value[k]]));
}
const secretKey = /password|secret|token|api[_-]?key|stripe[_-]?[sp]k|signature|pdf_base64|contract_pdf_url|pdf_raw_data/i;
export function redact(value) {
if (Array.isArray(value)) return value.map(redact);
if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value)
.filter(([key]) => !secretKey.test(key)).map(([key, val]) => [key, redact(val)]));
return value;
}
export function normalizeOrigin(value) {
const url = new URL(value);
if (url.protocol !== 'https:' || url.username || url.password || url.pathname !== '/' || url.search || url.hash)
throw new Error('INTEGRA_MCP_PUBLIC_ORIGIN debe ser un origen HTTPS sin ruta, por ejemplo https://tu-backend.es');
return url.origin;
}
export function safeRedirect(value) {
try {
if (typeof value !== 'string') return false;
const u = new URL(value);
return !u.username && !u.password && !u.hash && (u.protocol === 'https:' || isLoopbackRedirect(value));
} catch { return false; }
}
export function isLoopbackRedirect(value) {
try {
if (typeof value !== 'string' || !/^http:\/\/127\.0\.0\.1(?::[0-9]+)?(?:\/|$)/.test(value)) return false;
const u = new URL(value);
return u.protocol === 'http:' && u.hostname === '127.0.0.1' && !u.username && !u.password && !u.hash;
} catch { return false; }
}
export function redirectAllowed(requested, registeredUris) {
if (!safeRedirect(requested)) return false;
return registeredUris.some(registered => {
if (!safeRedirect(registered)) return false;
if (requested === registered) return true;
if (!isLoopbackRedirect(requested) || !isLoopbackRedirect(registered)) return false;
const a = new URL(requested), b = new URL(registered);
// RFC 8252: a native client chooses a free local port at login. Only that
// port may vary; the registered host, path and query must still match.
return a.pathname === b.pathname && a.search === b.search;
});
}

34
integra-mcp/store.mjs Normal file
View File

@@ -0,0 +1,34 @@
import { createHash } from 'node:crypto';
export const hash = value => createHash('sha256').update(value).digest('hex');
// Shared by all Coolify replicas. Only digests of bearer tokens, codes and browser
// transaction secrets are stored. No user passwords or IntegraRepara JWTs.
export class PgStore {
constructor(pool) { this.pool = pool; }
async init() {
await this.pool.query(`CREATE TABLE IF NOT EXISTS integra_mcp_oauth (
kind TEXT NOT NULL, key TEXT NOT NULL, data JSONB NOT NULL,
expires_at TIMESTAMPTZ NOT NULL, PRIMARY KEY (kind, key)
)`);
await this.pool.query('CREATE INDEX IF NOT EXISTS integra_mcp_oauth_expiry ON integra_mcp_oauth(expires_at)');
}
async set(kind, key, data, seconds) {
await this.pool.query(`INSERT INTO integra_mcp_oauth(kind,key,data,expires_at)
VALUES ($1,$2,$3,now()+$4*interval '1 second')
ON CONFLICT(kind,key) DO UPDATE SET data=EXCLUDED.data,expires_at=EXCLUDED.expires_at`,
[kind, key, JSON.stringify(data), seconds]);
}
async get(kind, key) {
const q = await this.pool.query('SELECT data FROM integra_mcp_oauth WHERE kind=$1 AND key=$2 AND expires_at>now()', [kind,key]);
return q.rows[0]?.data;
}
async take(kind, key) {
const q = await this.pool.query('DELETE FROM integra_mcp_oauth WHERE kind=$1 AND key=$2 AND expires_at>now() RETURNING data', [kind,key]);
return q.rows[0]?.data;
}
async delete(kind, key) {
await this.pool.query('DELETE FROM integra_mcp_oauth WHERE kind=$1 AND key=$2', [kind,key]);
}
async cleanup() { await this.pool.query('DELETE FROM integra_mcp_oauth WHERE expires_at<=now()'); }
}

202
integra-mcp/tools.mjs Normal file
View File

@@ -0,0 +1,202 @@
import { z } from 'zod';
const id = z.number().int().positive();
const text = z.string().trim().min(1).max(4000);
const optional = z.string().max(4000).optional();
const date = z.iso.date();
const time = z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/);
const money = z.number().finite().nonnegative().max(10000000);
const duration = z.number().int().min(1).max(1440);
const phone = z.string().regex(/^\+?[0-9 ()-]{9,20}$/);
const ids = z.array(id).max(100);
const item = z.object({ qty: z.number().positive(), concept: text, price: money }).strict();
const budget = { client_phone: phone, client_name: text, client_address: text,
items: z.array(item).min(1).max(100), subtotal: money, tax: money, total: money };
const tariff = { tipo: z.enum(['propia','repsol','mercado']), nombre: text, comercializadora: optional,
precioPotenciaP1: money, precioPotenciaP2: money, precioEnergiaPunta: money,
precioEnergiaLlano: money, precioEnergiaValle: money,
descuentoPct: z.number().min(0).max(100), bonoSocialDia: money, alquilerContadorDia: money,
notas: optional, activa: z.boolean() };
export const tools = [];
function add(name, description, method, route, shape = {}, options = {}) {
const { query = false, owner, refs = {}, sideEffect = false } = options;
tools.push({ name, description, method, route, query, owner, refs,
readOnly: method === 'GET' && !sideEffect, schema: z.object(shape).strict() });
}
const service = { owner: 'service' }, client = { owner: 'client' }, bud = { owner: 'budget' };
const notify = ' Puede enviar WhatsApp al cliente y activar robots; explicar estos efectos antes de ejecutarla.';
add('consultar_sesion','Consultar usuario conectado.','GET','/auth/me');
add('buscar_expedientes','Buscar por texto o fechas; incluye histórico. Requiere texto o al menos una fecha.','GET','/services/search',{
q: optional, date_field: z.enum(['created_at','scheduled_date']).optional(), date_from: date.optional(), date_to: date.optional(),
company: optional, limit: z.number().int().min(1).max(100).default(30), offset: z.number().int().nonnegative().default(0)
}, {query:true});
add('listar_expedientes','Listar expedientes del panel, incluidos archivados.','GET','/services/active');
add('listar_buzon','Consultar servicios de proveedores y bolsa.','GET','/providers/scraped');
add('comprobar_referencia','Comprobar si existe una referencia.','GET','/services/check-ref',{ref:text},{query:true});
add('crear_expediente','Crear expediente manual.'+notify,'POST','/services/manual-high',{
phone,name:text,address:text,description:text,guild_id:id,assigned_to:id.optional(),duration_minutes:duration.default(60),
mode:z.enum(['manual','auto']).default('manual'),is_company:z.boolean().default(false),company_name:optional,company_ref:optional
},{refs:{guild_id:'guild',assigned_to:'user'}});
add('actualizar_expediente','Actualizar los campos indicados sin sustituir el resto.'+notify,'PUT','/providers/scraped/:id',{
id,name:optional,phone:phone.optional(),address:optional,cp:z.string().regex(/^\d{5}$/).optional(),description:optional,
guild_id:id.optional(),assigned_to:id.nullable().optional(),assigned_to_name:optional,internal_notes:optional,client_notes:optional,
is_urgent:z.boolean().optional(),scheduled_date:date.optional(),scheduled_time:time.optional(),status_operativo:id.optional()
},{...service,refs:{guild_id:'guild',assigned_to:'user',status_operativo:'status'}});
add('cambiar_cita_estado','Cambiar fecha, hora o estado.'+notify,'PUT','/services/set-appointment/:id',{
id,date:date.optional(),time:time.optional(),status_operativo:id.optional(),skip_survey:z.boolean().default(false)
},{...service,refs:{status_operativo:'status'}});
add('registrar_no_localizado','Registrar intento de contacto.'+notify,'POST','/services/not-found/:id',{id},service);
add('traspasar_del_buzon','Validar y traspasar al panel operativo.','POST','/providers/import/:id',{id},service);
add('enviar_a_bolsa','Activar asignación automática; avisa por WhatsApp a técnicos.','POST','/providers/automate/:id',{
id,guild_id:id,cp:z.string().regex(/^\d{5}$/)
},{...service,refs:{guild_id:'guild'}});
add('consultar_historial_expediente','Leer trazabilidad.','GET','/services/:id/logs',{id},service);
add('anotar_evento','Añadir un evento a la trazabilidad.','POST','/services/:id/log',{id,action:text,details:optional},service);
add('leer_chat','Leer conversaciones y notas internas de la cuenta.','GET','/services/:id/chat',{id},service);
add('escribir_chat','Guardar mensaje en el chat interno del panel. Este endpoint no envía WhatsApp.','POST','/services/:id/chat',{
id,message:text,is_internal:z.boolean().default(true)
},service);
add('enviar_whatsapp','Enviar un WhatsApp de texto al cliente del expediente (a su móvil o al teléfono indicado) y guardarlo en el chat como «Marsalva (Claude)». Pausa la IA de esa conversación pause_minutes minutos (30 por defecto) y se reactiva sola. Usar SOLO con el texto exacto confirmado por el usuario.','POST','/services/:id/whatsapp',{
id,message:text,phone:phone.optional(),pause_minutes:z.number().int().min(0).max(720).default(30)
},service);
add('reactivar_asistente','Quitar la pausa temporal de la IA de WhatsApp de un expediente al terminar de hablar con el cliente. No anula una pausa manual con 🔴.','POST','/services/:id/ia/resume',{id},service);
add('enviar_instagram','Enviar al cliente el mensaje promocional de Instagram por WhatsApp.','POST','/services/:id/send-instagram',{id},service);
add('listar_solicitudes_cita','Consultar citas pendientes de aprobación.','GET','/agenda/requests');
add('aprobar_cita','Aprobar o ajustar cita solicitada.'+notify,'POST','/agenda/requests/:id/approve',{
id,duration:duration.default(60),date:date.optional(),time:time.optional()
},service);
add('rechazar_cita','Rechazar solicitud y enviar WhatsApp al cliente.','POST','/agenda/requests/:id/reject',{id},service);
add('listar_bloqueos','Consultar bloqueos de agenda.','GET','/agenda/blocks');
add('crear_bloqueo','Bloquear un tramo de agenda para un técnico.','POST','/agenda/blocks',{
worker_id:id,date,time,duration,reason:text,guild_id:id.optional(),guild_name:optional
},{refs:{worker_id:'user',guild_id:'guild'}});
add('eliminar_bloqueo','Eliminar un bloqueo de agenda.','DELETE','/agenda/blocks/:id',{id},{owner:'block'});
add('buscar_cliente','Buscar cliente por teléfono.','GET','/clients/search',{phone},{query:true});
add('crear_o_recuperar_cliente','Crear o recuperar ficha de cliente. No devuelve el token privado de su portal.','POST','/clients/ensure',{
phone,name:text,address:optional
});
add('historial_cliente','Consultar ficha e historial.','GET','/clients/:id/history',{id},client);
add('leer_notas_cliente','Leer notas del equipo.','GET','/clients/:id/notes',{id},client);
add('anotar_cliente','Añadir nota a la ficha.','POST','/clients/:id/notes',{id,note:text},client);
add('listar_presupuestos','Consultar presupuestos y sus estados.','GET','/budgets');
add('crear_presupuesto','Crear presupuesto; envía automáticamente WhatsApp con el enlace al cliente.','POST','/budgets',budget);
add('editar_presupuesto','Modificar presupuesto; envía automáticamente WhatsApp con el importe actualizado.','PUT','/budgets/:id',{id,...budget},bud);
add('cambiar_estado_presupuesto','Cambiar estado administrativo. No acredita firma del cliente ni confirma un cobro de Stripe.','PATCH','/budgets/:id/status',{
id,status:z.enum(['pending','accepted','rejected'])
},bud);
add('eliminar_presupuesto','Borrar presupuesto conforme a las reglas del backend.','DELETE','/budgets/:id',{id},bud);
add('convertir_presupuesto','Convertir presupuesto en servicio.'+notify,'POST','/budgets/:id/convert',{
id,date:date.optional(),time:time.optional(),guild_id:id.optional(),assigned_to:id.optional(),use_automation:z.boolean().default(false)
},{...bud,refs:{guild_id:'guild',assigned_to:'user'}});
add('listar_articulos','Consultar catálogo.','GET','/articles');
add('crear_articulo','Añadir artículo.','POST','/articles',{name:text,price:money});
add('editar_articulo','Modificar artículo.','PUT','/articles/:id',{id,name:text,price:money},{owner:'article'});
// GET /financials and /statuses perform writes in the supplied backend.
add('consultar_contabilidad','Consultar contabilidad; el backend crea las fichas financieras que falten.','GET','/financials',{}, {sideEffect:true});
add('registrar_cobro','Registrar importe y método. Cualquier método distinto de Pendiente marca el servicio como pagado.','PUT','/financials/:id',{
id,amount:money,payment_method:text
},service);
add('listar_partes','Consultar partes guardados sin descargar sus PDF.','GET','/services/:id/work-reports',{id},service);
add('mejorar_texto_parte','Reescribir notas con el motor IA del servidor; puede consumir crédito de su API.','POST','/work-reports/improve',{text});
add('guardar_parte','Guardar parte y PDF aportado. No inventar ni generar una firma del cliente.','POST','/services/:id/work-report',{
id,raw_text:optional,final_text:text,pdf_base64:z.string().min(8).max(8000000),signature_data:z.string().max(1000000).optional()
},service);
add('enviar_parte','Enviar PDF existente por WhatsApp a los teléfonos indicados o al cliente del parte.','POST','/work-reports/:id/send',{
id,phones:z.array(phone).min(1).max(10).optional()
},{owner:'report'});
add('listar_operarios','Consultar operarios activos, opcionalmente por gremio.','GET','/operators',{guild_id:id.optional()},{query:true,refs:{guild_id:'guild'}});
add('listar_equipo','Consultar usuarios de la empresa.','GET','/admin/users');
// Creating accounts and setting their passwords is kept in the existing website.
add('cambiar_estado_usuario','Activar o bloquear un usuario de esta empresa.','PATCH','/admin/users/:id/status',{
id,status:z.enum(['active','blocked','inactive'])
},{owner:'user'});
add('eliminar_usuario','Eliminar usuario de esta empresa. No permite eliminar al propietario ni al usuario conectado.','DELETE','/admin/users/:id',{id},{owner:'user'});
add('listar_gremios','Consultar gremios; el backend crea los predeterminados si no existen.','GET','/guilds',{}, {sideEffect:true});
add('crear_gremio','Crear gremio.','POST','/guilds',{name:text});
add('eliminar_gremio','Eliminar gremio.','DELETE','/guilds/:id',{id},{owner:'guild'});
add('editar_palabras_gremio','Definir palabras para la clasificación automática.','PUT','/guilds/:id/ia-rules',{
id,keywords:z.array(text).max(100)
},{owner:'guild'});
add('listar_estados','Consultar estados; sincroniza estados y migra el antiguo Pendiente de Cita.','GET','/statuses',{}, {sideEffect:true});
add('listar_companias','Consultar compañías.','GET','/companies');
add('crear_compania','Crear compañía.','POST','/companies',{name:text});
add('eliminar_compania','Eliminar compañía.','DELETE','/companies/:id',{id},{owner:'company'});
add('listar_zonas','Consultar zonas.','GET','/zones');
add('crear_zona','Crear zona.','POST','/zones',{name:text});
add('eliminar_zona','Eliminar zona.','DELETE','/zones/:id',{id},{owner:'zone'});
add('operarios_zona','Consultar asignados a zona.','GET','/zones/:id/operators',{id},{owner:'zone'});
add('asignar_zona','Sustituir los operarios asignados a una zona.','POST','/zones/:id/assign',{
id,operator_ids:ids
},{owner:'zone',refs:{operator_ids:'user'}});
add('consultar_municipios','Consultar municipios y CP de una provincia.','GET','/api/geo/municipios/:provincia',{provincia:text});
add('listar_plantillas','Consultar plantillas de WhatsApp.','GET','/templates');
add('guardar_plantilla','Crear o actualizar plantilla.','POST','/templates',{type:text,content:z.string().max(10000)});
add('consultar_automatizaciones','Consultar recordatorios; crea ajustes predeterminados si faltan.','GET','/automations/settings',{}, {sideEffect:true});
add('configurar_recordatorio','Configurar recordatorios del servidor. Activarlo puede enviar WhatsApp automáticamente.','POST','/automations/settings',{
automation_type:z.enum(['sin_citar','espera_cliente','dia_antes']),enabled:z.boolean(),test_mode:z.boolean().default(true),
dias_espera_inicial:z.number().int().min(1).max(365),dias_repeticion:z.number().int().min(1).max(365),hora_envio:time
});
add('historial_recordatorios','Consultar seguimiento de recordatorios.','GET','/automations/history');
add('consultar_proveedores','Consultar conexiones sin contraseñas.','GET','/providers/credentials');
add('consultar_mapeo','Consultar claves y mapeo de un proveedor.','GET','/discovery/keys/:provider',{provider:text});
add('consultar_empresa','Consultar configuración; se eliminan claves secretas de la respuesta.','GET','/config/company');
add('configurar_empresa','Actualizar nombre, enlace público, colores y horario. Las claves de Stripe se gestionan en la web.','POST','/config/company',{
slug:z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/).optional(),company_name:optional,
app_settings:z.object({primary:z.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),secondary:z.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),bg:z.string().regex(/^#[0-9a-fA-F]{6}$/).optional()}).strict().optional(),
portal_settings:z.object({m_start:time.optional(),m_end:time.optional(),a_start:time.optional(),a_end:time.optional(),visible_guilds:ids.optional()}).strict().optional()
});
add('consultar_ajustes_whatsapp','Consultar ajustes de WhatsApp e IA sin secretos.','GET','/whatsapp/settings');
add('configurar_whatsapp','Modificar IA y avisos; activar opciones puede causar envíos automáticos.','POST','/whatsapp/settings',{
wa_ai_enabled:z.boolean().optional(),wa_delay_enabled:z.boolean().optional(),wa_evt_welcome:z.boolean().optional(),wa_evt_assigned:z.boolean().optional(),
wa_evt_date:z.boolean().optional(),wa_evt_onway:z.boolean().optional(),wa_evt_survey:z.boolean().optional(),ai_custom_prompt:optional,instagram_promo_message:optional
});
add('resumen_proteccion','Consultar estadísticas de planes.','GET','/protection/dashboard');
add('listar_planes','Consultar planes de protección.','GET','/protection/plans');
add('crear_plan','Crear plan de protección.','POST','/protection/plans',{
name:text,type:text,price:money,renewal:money,urgencies:z.number().int().nonnegative(),bricos:z.number().int().nonnegative(),coverages:text
});
add('listar_suscriptores','Consultar suscripciones de protección.','GET','/protection/subscribers');
add('crear_suscripcion','Registrar suscripción administrativa. No crea ni confirma un cargo de Stripe.','POST','/protection/subscribers',{
plan_id:id,name:text,dni:optional,phone,payment_status:z.enum(['pagado','impagado']),status:z.enum(['pendiente_pago','activo','suspendido','cancelado']),
renewal_date:date.optional(),bricos_used:z.number().int().nonnegative().default(0),urgencies_used:z.number().int().nonnegative().default(0)
},{refs:{plan_id:'plan'}});
add('cambiar_suscripcion','Actualizar estado administrativo; no cancela ni cobra una suscripción de Stripe.','PUT','/protection/subscribers/:id/toggle',{
id,field:z.enum(['payment_status','status']),value:text
},{owner:'subscription'});
add('consultar_config_proteccion','Consultar configuración de protección.','GET','/protection/config');
add('configurar_proteccion','Actualizar condiciones y ajustes de protección.','POST','/protection/config',{
name:text,email:z.email(),phone,auto_renew:z.boolean(),pre_notice:z.boolean(),billing_method:z.enum(['stripe','manual']),contract_text:text
});
add('listar_tarifas_luz','Consultar tarifas del comparador.','GET','/energy-tariffs');
add('crear_tarifa_luz','Crear tarifa del comparador.','POST','/energy-tariffs',tariff);
add('editar_tarifa_luz','Modificar tarifa del comparador.','PUT','/energy-tariffs/:id',{id,...tariff},{owner:'tariff'});
add('eliminar_tarifa_luz','Eliminar tarifa del comparador.','DELETE','/energy-tariffs/:id',{id},{owner:'tariff'});
add('listar_leads_luz','Consultar hasta 200 solicitudes del comparador.','GET','/energy-leads');
add('cambiar_lead_luz','Actualizar seguimiento de un lead.','PATCH','/energy-leads/:id',{
id,estado:z.enum(['nuevo','revisado','contactado','descartado'])
},{owner:'lead'});
add('enviar_estudio_luz','Enviar enlace al estudio por WhatsApp al cliente.','POST','/energy-leads/:id/send-pdf',{id},{owner:'lead'});
add('consultar_ajustes_luz','Consultar ajustes del comparador.','GET','/energy-settings');
add('configurar_comparador_luz','Configurar cálculo y avisos del comparador.','PUT','/energy-settings',{
ieePct:z.number().min(0).max(100),ivaPct:z.number().min(0).max(100),openaiModel:optional,cnmcEnabled:z.boolean(),adminWhatsapp:phone.optional()
});
export function validateBusiness(tool, args) {
if (tool.name === 'buscar_expedientes' && !args.q?.trim() && !args.date_from && !args.date_to)
throw new Error('Indica texto de búsqueda o una fecha.');
if (args.date_from && args.date_to && args.date_from > args.date_to) throw new Error('Rango de fechas invertido.');
if (tool.name === 'crear_expediente' && args.is_company && (!args.company_name || !args.company_ref))
throw new Error('Indica compañía y referencia.');
if (['crear_presupuesto','editar_presupuesto'].includes(tool.name)) {
const subtotal = Math.round(args.items.reduce((s,i)=>s+i.qty*i.price,0)*100)/100;
if (Math.abs(subtotal-args.subtotal)>0.011 || Math.abs(args.subtotal+args.tax-args.total)>0.011)
throw new Error('Los importes no cuadran: tax es el importe de impuestos, no el porcentaje.');
}
if (tool.name === 'cambiar_suscripcion') {
const allowed = args.field === 'status' ? ['pendiente_pago','activo','suspendido','cancelado'] : ['pagado','impagado'];
if (!allowed.includes(args.value)) throw new Error('Valor de suscripción inválido.');
}
}

193
oauth.mjs Normal file
View File

@@ -0,0 +1,193 @@
import { randomBytes, createHash, timingSafeEqual } from 'node:crypto';
import express from 'express';
import bcrypt from 'bcryptjs';
import rateLimit from 'integra-mcp-rate-limit';
import { hash } from './store.mjs';
import { safeRedirect, redirectAllowed } from './security.mjs';
const random = () => randomBytes(32).toString('base64url');
const equal = (a,b) => typeof a === 'string' && typeof b === 'string' && a.length === b.length &&
timingSafeEqual(Buffer.from(a),Buffer.from(b));
const esc = s => String(s).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
const scopesAllowed = ['integra:read','integra:write'];
const fail = (res,error='invalid_request',status=400) => res.status(status).json({error});
const wrap = fn => (req,res,next) => Promise.resolve(fn(req,res)).catch(next);
const denialMessages = Object.freeze({
invalid_origin:'El formulario no se ha enviado desde el origen de IntegraRepara.',
invalid_form:'Falta el identificador del formulario. Abre una conexión nueva.',
flow_missing_or_expired:'La conexión ha caducado o ya se ha utilizado. Abre una conexión nueva.',
cookie_missing:'El navegador no ha enviado la cookie de esta conexión.',
cookie_mismatch:'La cookie corresponde a otro formulario. Cierra los anteriores y abre una conexión nueva.',
callback_not_allowed:'El callback de esta conexión ya no está permitido en el servidor.',
invalid_credentials:'No se ha podido validar el email o teléfono y la contraseña.',
user_not_found:'La cuenta validada ya no existe.',
user_inactive:'La cuenta está inactiva o bloqueada.',
user_not_verified:'La cuenta no tiene la verificación requerida por el conector.',
role_not_admin:'La cuenta validada no tiene rol admin ni superadmin.',
owner_not_found:'No existe el propietario de la empresa asociado a esta cuenta.',
owner_inactive:'El propietario de la empresa está inactivo o bloqueado.',
owner_not_verified:'El propietario de la empresa no tiene la verificación requerida por el conector.',
flow_already_used:'Otra solicitud ya ha utilizado este formulario. Abre una conexión nueva.',
account_rejected:'La cuenta ha sido rechazada por el proveedor de acceso.'
});
function deny(res, reason) {
const safeReason=Object.hasOwn(denialMessages,reason)?reason:'account_rejected';
// Fixed reason codes only. Never log identity, form bodies, credentials or cookies.
console.warn('[Integra MCP OAuth] access_denied:',safeReason);
return res.status(403).json({error:'access_denied',reason:safeReason,error_description:denialMessages[safeReason]});
}
export function oauthRouter({ store, origin, authenticate, currentUser, redirectUris }) {
if (!redirectUris.every(safeRedirect)) throw new Error('Los callbacks deben usar HTTPS o HTTP local en 127.0.0.1.');
const resource = `${origin}/mcp`;
const router = express.Router();
router.use(express.json({limit:'16kb'}),express.urlencoded({extended:false,limit:'16kb'}));
router.use((req,res,next)=>{res.set('Cache-Control','no-store');next();});
const strictLimit = rateLimit({windowMs:15*60000,limit:20,standardHeaders:'draft-8',legacyHeaders:false});
router.get('/.well-known/oauth-authorization-server', (req,res)=>res.json({
issuer:origin,authorization_endpoint:`${origin}/mcp-connect/authorize`,token_endpoint:`${origin}/mcp-connect/token`,
registration_endpoint:`${origin}/mcp-connect/register`,revocation_endpoint:`${origin}/mcp-connect/revoke`,
response_types_supported:['code'],grant_types_supported:['authorization_code','refresh_token'],
code_challenge_methods_supported:['S256'],token_endpoint_auth_methods_supported:['none'],
authorization_response_iss_parameter_supported:true,
scopes_supported:scopesAllowed
}));
for (const route of ['/.well-known/oauth-protected-resource','/.well-known/oauth-protected-resource/mcp']) {
router.get(route,(req,res)=>res.json({resource,authorization_servers:[origin],scopes_supported:scopesAllowed,resource_name:'IntegraRepara'}));
}
router.post('/mcp-connect/register',strictLimit,wrap(async(req,res)=>{
const b=req.body;
if (!Array.isArray(b.redirect_uris) || !b.redirect_uris.length || b.redirect_uris.length>10 ||
!b.redirect_uris.every(u=>redirectAllowed(u,redirectUris)) ||
(b.token_endpoint_auth_method && b.token_endpoint_auth_method!=='none') ||
(b.grant_types && (!Array.isArray(b.grant_types) || !b.grant_types.every(g=>['authorization_code','refresh_token'].includes(g)))) ||
(b.response_types && (!Array.isArray(b.response_types) || b.response_types.some(t=>t!=='code'))))
return fail(res,'invalid_client_metadata');
const client={client_id:random(),client_name:String(b.client_name||'Cliente MCP').slice(0,100),
redirect_uris:b.redirect_uris,token_endpoint_auth_method:'none',grant_types:['authorization_code','refresh_token'],response_types:['code']};
await store.set('client',client.client_id,client,365*86400);
res.status(201).json(client);
}));
router.get('/mcp-connect/authorize',strictLimit,wrap(async(req,res)=>{
const p=req.query;
if (Object.values(p).some(v=>typeof v!=='string')) return fail(res);
const client=await store.get('client',p.client_id);
const scopes=[...new Set(String(p.scope||'integra:read').split(' ').filter(Boolean))];
if (!client || !redirectAllowed(p.redirect_uri,client.redirect_uris) || !redirectAllowed(p.redirect_uri,redirectUris) ||
p.response_type!=='code' || p.code_challenge_method!=='S256' || !/^[A-Za-z0-9_-]{43}$/.test(p.code_challenge||'') ||
p.resource!==resource || !scopes.includes('integra:read') || scopes.some(s=>!scopesAllowed.includes(s)) || (p.state||'').length>2048)
return fail(res);
const requestId=random(),browserSecret=random();
await store.set('flow',hash(requestId),{...p,scopes,browserHash:hash(browserSecret)},600);
res.set({
'Content-Security-Policy':"default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'",
'X-Frame-Options':'DENY','Referrer-Policy':'strict-origin','X-Content-Type-Options':'nosniff'
});
res.cookie('integra_mcp_flow',browserSecret,{httpOnly:true,secure:true,sameSite:'lax',path:'/mcp-connect',maxAge:600000});
res.type('html').send(`<!doctype html><html lang="es"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Conectar IntegraRepara</title>
<style>body{font:16px system-ui;background:#f1f5f9;color:#0f172a;padding:24px}main{max-width:480px;margin:6vh auto;background:white;padding:32px;border-radius:16px}label{display:block;margin:16px 0}input,button{box-sizing:border-box;width:100%;padding:12px;font:inherit}button{background:#1e3a8a;color:white;border:0;border-radius:6px}small{overflow-wrap:anywhere}</style>
<main><h1>Conectar IntegraRepara</h1><p>Vas a autorizar a <strong>${esc(client.client_name)}</strong>.</p>
<p>Permisos: consultar datos de tu empresa${scopes.includes('integra:write')?', crear y modificar registros, eliminar registros y activar acciones con WhatsApp según lo que solicites':''}.</p>
<small>Aplicación de destino: ${esc(new URL(p.redirect_uri).origin)}</small>
<form method="post" action="/mcp-connect/consent"><input type="hidden" name="request_id" value="${requestId}">
<label>Email o teléfono<input name="email" autocomplete="username" required maxlength="254"></label>
<label>Contraseña<input type="password" name="password" autocomplete="current-password" required maxlength="1024"></label>
<p>Usa una cuenta administradora de IntegraRepara. La contraseña se comprueba aquí y no se entrega al complemento.</p>
<button>Iniciar sesión y autorizar</button></form><p>Para cancelar, cierra esta ventana.</p></main></html>`);
}));
router.post('/mcp-connect/consent',strictLimit,wrap(async(req,res)=>{
if (req.headers.origin!==origin) return deny(res,'invalid_origin');
if (typeof req.body.request_id!=='string') return deny(res,'invalid_form');
const flow=await store.get('flow',hash(req.body.request_id));
const cookie=String(req.headers.cookie||'').split(';').map(s=>s.trim()).find(s=>s.startsWith('integra_mcp_flow='))?.slice('integra_mcp_flow='.length);
if (!flow) return deny(res,'flow_missing_or_expired');
if (!cookie) return deny(res,'cookie_missing');
if (!equal(flow.browserHash,hash(cookie))) return deny(res,'cookie_mismatch');
if (!redirectAllowed(flow.redirect_uri,redirectUris)) return deny(res,'callback_not_allowed');
let reason='account_rejected';
const user=await authenticate(req.body.email,req.body.password,code=>{if(Object.hasOwn(denialMessages,code))reason=code;});
if (!user) return deny(res,reason);
if (!await store.take('flow',hash(req.body.request_id))) return deny(res,'flow_already_used');
const code=random();
await store.set('code',hash(code),{...flow,userId:user.id},120);
res.clearCookie('integra_mcp_flow',{httpOnly:true,secure:true,sameSite:'lax',path:'/mcp-connect'});
const callback=new URL(flow.redirect_uri);callback.searchParams.set('code',code);
callback.searchParams.set('iss',origin);
if (flow.state) callback.searchParams.set('state',flow.state);
res.redirect(303,callback.href);
}));
async function issue(record,grantId) {
const access=random(),refresh=random();
const data={userId:record.userId,clientId:record.client_id,scopes:record.scopes,resource,grantId};
await store.set('access',hash(access),data,3600);
await store.set('refresh',hash(refresh),data,30*86400);
return {access_token:access,refresh_token:refresh,token_type:'Bearer',expires_in:3600,scope:data.scopes.join(' ')};
}
router.post('/mcp-connect/token',strictLimit,wrap(async(req,res)=>{
const b=req.body;
if (b.resource!==resource || typeof b.client_id!=='string' || !await store.get('client',b.client_id)) return fail(res,'invalid_client');
if (b.grant_type==='authorization_code') {
if (typeof b.code!=='string' || !/^[A-Za-z0-9._~-]{43,128}$/.test(b.code_verifier||'')) return fail(res,'invalid_grant');
const record=await store.get('code',hash(b.code));
const challenge=createHash('sha256').update(b.code_verifier).digest('base64url');
if (!record || record.client_id!==b.client_id || record.redirect_uri!==b.redirect_uri || record.resource!==resource ||
!equal(record.code_challenge,challenge) || !redirectAllowed(record.redirect_uri,redirectUris) || !await currentUser(record.userId))
return fail(res,'invalid_grant');
if (!await store.take('code',hash(b.code))) return fail(res,'invalid_grant');
const grantId=random();await store.set('grant',grantId,{userId:record.userId,clientId:b.client_id},30*86400);
return res.json(await issue(record,grantId));
}
if (b.grant_type==='refresh_token') {
if (typeof b.refresh_token!=='string') return fail(res,'invalid_grant');
const record=await store.get('refresh',hash(b.refresh_token));
if (!record || record.clientId!==b.client_id || record.resource!==resource || !await store.get('grant',record.grantId) || !await currentUser(record.userId))
return fail(res,'invalid_grant');
const scopes=b.scope===undefined?record.scopes:String(b.scope).split(' ').filter(Boolean);
if (!scopes.includes('integra:read') || scopes.some(s=>!record.scopes.includes(s))) return fail(res,'invalid_scope');
if (!await store.take('refresh',hash(b.refresh_token))) return fail(res,'invalid_grant');
return res.json(await issue({userId:record.userId,client_id:b.client_id,scopes},record.grantId));
}
return fail(res,'unsupported_grant_type');
}));
router.post('/mcp-connect/revoke',strictLimit,wrap(async(req,res)=>{
const b=req.body;
if (typeof b.token!=='string' || typeof b.client_id!=='string') return fail(res);
for (const kind of ['access','refresh']) {
const record=await store.get(kind,hash(b.token));
if (record?.clientId===b.client_id) await store.delete('grant',record.grantId);
}
res.status(200).end();
}));
router.use((err,req,res,next)=>{
if (res.headersSent) return next(err);
console.error('[Integra MCP OAuth]',err.name);
res.status(500).json({error:'server_error'});
});
return router;
}
export function accountAccess(pool) {
const rejected = (report,reason) => { if(typeof report==='function')report(reason);return null; };
async function currentUser(userId,report) {
const q=await pool.query('SELECT id,owner_id,role,status,is_verified FROM users WHERE id=$1',[userId]);
const u=q.rows[0];
if (!u) return rejected(report,'user_not_found');
if (u.status!=='active') return rejected(report,'user_inactive');
if (u.is_verified!==true) return rejected(report,'user_not_verified');
if (!['admin','superadmin'].includes(String(u.role).trim().toLowerCase())) return rejected(report,'role_not_admin');
const accountId=u.owner_id||u.id;
const owner=await pool.query('SELECT status,is_verified FROM users WHERE id=$1',[accountId]);
if (!owner.rows[0]) return rejected(report,'owner_not_found');
if (owner.rows[0].status!=='active') return rejected(report,'owner_inactive');
if (owner.rows[0].is_verified!==true) return rejected(report,'owner_not_verified');
return {...u,accountId,role:String(u.role).trim().toLowerCase()};
}
return {currentUser,async authenticate(email,password,report) {
if (typeof email!=='string' || typeof password!=='string' || email.length>254 || password.length>1024) return rejected(report,'invalid_credentials');
const q=await pool.query('SELECT id,password_hash FROM users WHERE email=$1 OR phone=$1 ORDER BY id LIMIT 1',[email]);
const u=q.rows[0];
// A valid dummy bcrypt hash keeps unknown-account failures expensive as well.
const valid=await bcrypt.compare(password,u?.password_hash||'$2b$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy');
return valid&&u?currentUser(u.id,report):rejected(report,'invalid_credentials');
}};
}

View File

@@ -21,8 +21,16 @@
"stripe": "^14.20.0", "stripe": "^14.20.0",
"playwright": "^1.42.1", "playwright": "^1.42.1",
"openai": "^4.28.0", "openai": "^4.28.0",
"express-rate-limit": "^7.4.0" "express-rate-limit": "^7.4.0",
"pdf-lib": "^1.17.1",
"@modelcontextprotocol/sdk": "1.32.2",
"zod": "4.6.7",
"integra-mcp-rate-limit": "npm:express-rate-limit@^8.2.1"
},
"overrides": {
"openai": {
"zod": "$zod"
}
}, },
"engines": { "engines": {
"node": ">=18.0.0" "node": ">=18.0.0"

630
server.js
View File

@@ -1,10 +1,19 @@
import { mountIntegraMcp } from './integra-mcp/mount.mjs';
import { publicBillingSettings } from './integra-mcp/security.mjs';
import express from "express"; import express from "express";
import cors from "cors"; import cors from "cors";
import bcrypt from "bcryptjs"; import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken"; import jwt from "jsonwebtoken";
import pg from "pg"; import pg from "pg";
import crypto from "crypto"; import crypto from "crypto";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { PDFDocument, StandardFonts, rgb } from "pdf-lib";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
import OpenAI from "openai"; import OpenAI from "openai";
import Stripe from "stripe"; import Stripe from "stripe";
import rateLimit from "express-rate-limit"; import rateLimit from "express-rate-limit";
@@ -34,11 +43,14 @@ const corsOptions = {
'https://web.integrarepara.es', 'https://web.integrarepara.es',
'https://portal.integrarepara.es', 'https://portal.integrarepara.es',
'https://app.integrarepara.es', 'https://app.integrarepara.es',
'https://marsalva.es',
'https://www.marsalva.es',
'http://localhost:3000', 'http://localhost:3000',
'http://127.0.0.1:3000' 'http://127.0.0.1:3000'
], ],
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'], allowedHeaders: ['Content-Type', 'Authorization', 'MCP-Protocol-Version'],
exposedHeaders: ['WWW-Authenticate'],
credentials: true, credentials: true,
optionsSuccessStatus: 200 optionsSuccessStatus: 200
}; };
@@ -1024,6 +1036,15 @@ ALTER TABLE protection_subscriptions ALTER COLUMN status SET DEFAULT 'pendiente_
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='users' AND column_name='portal_settings') THEN 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"}'; 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; END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='energy_quote_leads' AND column_name='pdf_enviado') THEN
-- AÑADIDO: Marca si ya se envió el enlace del PDF de la comparativa de luz al cliente
ALTER TABLE energy_quote_leads ADD COLUMN pdf_enviado BOOLEAN DEFAULT FALSE;
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 -- 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 IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='scraped_services' AND column_name='assigned_to') THEN
@@ -1614,6 +1635,22 @@ Máximo 2 frases por mensaje: sé claro y directo.
No te presentes de nuevo si ya habéis hablado antes. No te presentes de nuevo si ya habéis hablado antes.
No uses la muletilla "¿En qué más te puedo ayudar?".`; No uses la muletilla "¿En qué más te puedo ayudar?".`;
// 📸 Texto por defecto del mensaje de WhatsApp para promocionar Instagram al pulsar
// el botón "Enviar Instagram" de un servicio. Se personaliza desde Configuración en la App;
// si la empresa no ha guardado nunca uno propio, se usa este texto.
const DEFAULT_INSTAGRAM_PROMO_MSG = `⚡ ¡Ya que hemos conectado, no perdamos el contacto! 😂 Sígueme en Instagram: averías, consejos y humor de electricista. ¡Seguirme no sube la factura de la luz! 😉
👉 https://www.instagram.com/marsalva_algeciras/`;
// 🤖 Prefijo en los mensajes que escribe la IA por WhatsApp, para que el cliente
// sepa claramente que no le está escribiendo Marco sino el asistente automático.
// (En el historial del panel se guarda sin prefijo: ya sale como "Asistente IA".)
const PREFIJO_IA = "ASISTENTE IA: ";
function conPrefijoIA(texto) {
const limpio = String(texto || "").trim();
return /^asistente ia\s*:/i.test(limpio) ? limpio : PREFIJO_IA + limpio;
}
async function procesarConIA(ownerId, mensajeCliente, datosExpediente) { async function procesarConIA(ownerId, mensajeCliente, datosExpediente) {
try { try {
const userQ = await pool.query( const userQ = await pool.query(
@@ -2685,7 +2722,7 @@ app.get("/public/portal/:token", async (req, res) => {
name: qConfig.rows[0]?.full_name || "IntegraRepara", name: qConfig.rows[0]?.full_name || "IntegraRepara",
logo: qConfig.rows[0]?.company_logo || null, logo: qConfig.rows[0]?.company_logo || null,
ad: qConfig.rows[0]?.company_ad || null, ad: qConfig.rows[0]?.company_ad || null,
billing_settings: qConfig.rows[0]?.billing_settings || null // AQUÍ VIAJA EL IBAN Y LAS OBSERVACIONES billing_settings: publicBillingSettings(qConfig.rows[0]?.billing_settings || {}) // AQUÍ VIAJA EL IBAN Y LAS OBSERVACIONES
}; };
// 3. CONSULTA SEGURA (Con o sin ID) // 3. CONSULTA SEGURA (Con o sin ID)
@@ -3322,7 +3359,11 @@ app.get("/whatsapp/settings", authMiddleware, async (req, res) => {
// 🗣️ Texto que usa la IA por defecto para el bloque de estilo/reglas de negocio // 🗣️ 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 // 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. // precargar el cuadro de texto la primera vez, para que se vea lo que hace hoy.
default_ai_rules: DEFAULT_REGLAS_NEGOCIO_IA default_ai_rules: DEFAULT_REGLAS_NEGOCIO_IA,
// 📸 Mensaje de Instagram ya resuelto (el guardado por la empresa, o si no,
// el texto por defecto) + el texto por defecto aparte, para poder "restaurar".
instagram_promo_message: (q.rows[0]?.wa_settings?.instagram_promo_message) || DEFAULT_INSTAGRAM_PROMO_MSG,
default_instagram_promo_message: DEFAULT_INSTAGRAM_PROMO_MSG
}); });
} catch (e) { res.status(500).json({ ok: false }); } } catch (e) { res.status(500).json({ ok: false }); }
}); });
@@ -3344,6 +3385,30 @@ app.post("/whatsapp/settings", authMiddleware, async (req, res) => {
} }
}); });
// 📸 Enviar al cliente de un servicio el mensaje promocional de Instagram por WhatsApp
app.post("/services/:id/send-instagram", 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, error: "Servicio no encontrado" });
const raw = current.rows[0].raw_data || {};
const phone = raw["Teléfono"] || raw["TELEFONO"] || raw["TELEFONOS"] || "";
if (!phone) return res.status(400).json({ ok: false, error: "Este servicio no tiene un teléfono guardado" });
const settingsQ = await pool.query("SELECT wa_settings FROM users WHERE id=$1", [req.user.accountId]);
const mensaje = settingsQ.rows[0]?.wa_settings?.instagram_promo_message || DEFAULT_INSTAGRAM_PROMO_MSG;
const enviado = await sendWhatsAppAuto(phone, mensaje, `cliente_${req.user.accountId}`, false);
if (!enviado) return res.status(500).json({ ok: false, error: "No se pudo enviar el WhatsApp (revisa la conexión con Evolution)" });
res.json({ ok: true });
} catch (e) {
console.error("Error enviando promo de Instagram:", e);
res.status(500).json({ ok: false, error: "Error de servidor" });
}
});
// ========================================== // ==========================================
// 💬 NÚCLEO DE ENVÍO WHATSAPP (EVOLUTION API - MODO HUMANO DINÁMICO) // 💬 NÚCLEO DE ENVÍO WHATSAPP (EVOLUTION API - MODO HUMANO DINÁMICO)
// ========================================== // ==========================================
@@ -3401,7 +3466,7 @@ async function sendWhatsAppAuto(phone, message, instanceName, useDelay = false)
// 📎 Envía un documento (PDF) por WhatsApp vía Evolution API. Devuelve {ok, detail} // 📎 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). // para poder ver el motivo exacto de un fallo (útil para depurar en caliente).
async function sendWhatsAppMedia(phone, base64Pdf, fileName, caption, instanceName) { async function sendWhatsAppMedia(phone, base64Pdf, fileName, caption, instanceName, mimeType = "application/pdf") {
if (!EVOLUTION_BASE_URL || !EVOLUTION_API_KEY) { if (!EVOLUTION_BASE_URL || !EVOLUTION_API_KEY) {
console.error("⚠️ WhatsApp omitido: Servidor Evolution no configurado."); console.error("⚠️ WhatsApp omitido: Servidor Evolution no configurado.");
return { ok: false, detail: "Evolution no configurado" }; return { ok: false, detail: "Evolution no configurado" };
@@ -3421,8 +3486,8 @@ async function sendWhatsAppMedia(phone, base64Pdf, fileName, caption, instanceNa
}, },
body: JSON.stringify({ body: JSON.stringify({
number: phone, number: phone,
mediatype: "document", mediatype: mimeType.startsWith("image/") ? "image" : "document",
mimetype: "application/pdf", mimetype: mimeType,
fileName: fileName, fileName: fileName,
caption: caption, caption: caption,
media: cleanBase64 media: cleanBase64
@@ -3860,8 +3925,17 @@ app.put('/providers/scraped/:id', authMiddleware, async (req, res) => {
const isNoLocalizado = stName.includes('no localizado') || stName.includes('buzon') || stName.includes('contesta'); const isNoLocalizado = stName.includes('no localizado') || stName.includes('buzon') || stName.includes('contesta');
// --- DISPARADORES WHATSAPP --- // --- DISPARADORES WHATSAPP ---
const yaTieneCita = newDate && newDate !== "null" && newTime && newTime !== "null";
const vaASalirAvisoCita = isCitado && (statusChanged || dateChanged || timeChanged);
if ((statusChanged && isAsignado && finalAssignedTo) || workerNewlyAssigned) { if ((statusChanged && isAsignado && finalAssignedTo) || workerNewlyAssigned) {
triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_assigned').catch(console.error); if (!yaTieneCita) {
// Sin fecha/hora: pedir disponibilidad
triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_assigned').catch(console.error);
} else if (!vaASalirAvisoCita) {
// Ya tiene cita: mandar "Cita creada" en vez de pedir disponibilidad
triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_date').catch(console.error);
}
// Si ademas pasa a Citado, el bloque de abajo ya manda el aviso de cita (sin duplicar)
} }
// 🔔 Se dispara si cambia el estado a citado, si cambia el día o si cambia la hora // 🔔 Se dispara si cambia el estado a citado, si cambia el día o si cambia la hora
if (isCitado && (statusChanged || dateChanged || timeChanged)) { if (isCitado && (statusChanged || dateChanged || timeChanged)) {
@@ -5630,7 +5704,8 @@ app.put("/budgets/:id", authMiddleware, async (req, res) => {
app.patch("/budgets/:id/status", authMiddleware, async (req, res) => { app.patch("/budgets/:id/status", authMiddleware, async (req, res) => {
try { 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]); const upd = await pool.query("UPDATE budgets SET status=$1 WHERE id=$2 AND owner_id=$3", [req.body.status, req.params.id, req.user.accountId]);
if (upd.rowCount > 0) await sincronizarExpedientePresupuesto(req.params.id, req.user.accountId, req.body.status, "Panel");
res.json({ ok: true }); res.json({ ok: true });
} catch(e) { res.status(500).json({ok: false}); } } catch(e) { res.status(500).json({ok: false}); }
}); });
@@ -5769,6 +5844,96 @@ app.post("/services/:id/chat", authMiddleware, async (req, res) => {
} }
}); });
// ==========================================
// 🤖 CLAUDE: ENVIAR WHATSAPP AL CLIENTE DE UN EXPEDIENTE
// ==========================================
// Lo usa el conector de IA (herramienta enviar_whatsapp). Envía el texto tal cual,
// lo guarda en el chat como "Marsalva (Claude)" y pausa la IA de esa conversación
// durante pause_minutes (30 por defecto). La pausa se quita sola al vencer.
const CLAUDE_SENDER_NAME = "Marsalva (Claude)";
app.post("/services/:id/whatsapp", authMiddleware, async (req, res) => {
try {
if (req.user.role === 'operario' || req.user.role === 'operario_cerrado') {
return res.status(403).json({ ok: false, error: "Solo administración puede enviar desde aquí" });
}
const { id } = req.params;
const message = (req.body?.message ?? "").toString().trim();
if (!message) return res.status(400).json({ ok: false, error: "El mensaje está vacío" });
if (message.length > 4000) return res.status(400).json({ ok: false, error: "Mensaje demasiado largo" });
let pauseMin = parseInt(req.body?.pause_minutes ?? 30, 10);
if (!Number.isFinite(pauseMin)) pauseMin = 30;
pauseMin = Math.min(Math.max(pauseMin, 0), 720);
const svcQ = await pool.query("SELECT raw_data 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 nueve = req.body?.phone ? extractValidPhone(String(req.body.phone)) : extractBestMobile(raw);
if (!/^[67]\d{8}$/.test(nueve || "")) return res.status(400).json({ ok: false, error: "El expediente no tiene un móvil válido" });
const destino = "34" + nueve;
// Pausamos ANTES de enviar, para que la IA no conteste a la vez que nosotros
let hasta = null;
if (pauseMin > 0) {
hasta = new Date(Date.now() + pauseMin * 60000).toISOString();
await pool.query(
"UPDATE scraped_services SET raw_data = COALESCE(raw_data, '{}'::jsonb) || jsonb_build_object('ia_paused_until', $2::text) WHERE id=$1 AND owner_id=$3",
[id, hasta, req.user.accountId]
);
}
const enviado = await sendWhatsAppAuto(destino, message, `cliente_${req.user.accountId}`, false);
if (!enviado) return res.status(502).json({ ok: false, error: "No se pudo enviar el WhatsApp (revisa la conexión con Evolution)" });
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, 'admin', $5, false)
RETURNING id, sender_name, message, created_at`,
[id, req.user.accountId, req.user.sub, CLAUDE_SENDER_NAME, message]
);
await pool.query(
"INSERT INTO scraped_service_logs (scraped_id, user_name, action, details) VALUES ($1, $2, $3, $4)",
[id, CLAUDE_SENDER_NAME, "WhatsApp enviado al cliente", "Al " + nueve + ": " + message.slice(0, 500)]
).catch(e => console.error("⚠️ Log WhatsApp de Claude:", e.message));
console.log(`🤖 [CLAUDE WA] Enviado a ${destino} (servicio ${id}). IA pausada hasta ${hasta || 'sin pausa'}`);
res.json({ ok: true, sent_to: destino, ia_paused_until: hasta, message: insertQ.rows[0] });
} catch (e) {
console.error("Error enviando WhatsApp de Claude:", e);
res.status(500).json({ ok: false });
}
});
// 🟢 Quitar la pausa temporal de la IA (no toca la pausa manual con 🔴)
app.post("/services/:id/ia/resume", authMiddleware, async (req, res) => {
try {
if (req.user.role === 'operario' || req.user.role === 'operario_cerrado') {
return res.status(403).json({ ok: false, error: "Solo administración" });
}
const { id } = req.params;
const q = await pool.query(
`UPDATE scraped_services SET raw_data = COALESCE(raw_data, '{}'::jsonb) - 'ia_paused_until'
WHERE id=$1 AND owner_id=$2
RETURNING LOWER(COALESCE(raw_data->>'ia_paused', 'false')) IN ('true', 't', '1') AS pausa_manual`,
[id, req.user.accountId]
);
if (q.rowCount === 0) return res.status(404).json({ ok: false, error: "Servicio no encontrado" });
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)`,
[id, req.user.accountId, "🟢 IA reactivada al terminar la conversación de Claude."]
);
res.json({ ok: true, manual_pause_still_active: q.rows[0].pausa_manual === true });
} catch (e) {
console.error("Error reactivando IA:", e);
res.status(500).json({ ok: false });
}
});
// ========================================== // ==========================================
// 🧾 PARTES DE TRABAJO (texto con IA + firma + PDF + envío WhatsApp) // 🧾 PARTES DE TRABAJO (texto con IA + firma + PDF + envío WhatsApp)
// ========================================== // ==========================================
@@ -5910,12 +6075,25 @@ async function procesarTurnoIA({ ownerId, service, mensajeTexto, telefonoCliente
return; return;
} }
// ⏸️ Pausa temporal (p. ej. cuando Claude escribe al cliente): se quita sola al vencer
try {
const pausaQ = await pool.query("SELECT raw_data->>'ia_paused_until' AS hasta FROM scraped_services WHERE id = $1", [service.id]);
const hasta = pausaQ.rows[0]?.hasta ? new Date(pausaQ.rows[0].hasta) : null;
if (hasta && !isNaN(hasta.getTime()) && hasta.getTime() > Date.now()) {
console.log(`⏸️ [IA EN PAUSA] ${service.service_ref} hasta ${hasta.toISOString()}`);
return;
}
} catch (ePausa) {
console.error("Error comprobando pausa temporal de IA:", ePausa.message);
}
// 🛡️ Escudo humano: si alguien habló hace menos de 120 min, la IA se calla // 🛡️ Escudo humano: si alguien habló hace menos de 120 min, la IA se calla
const checkHumanQ = await pool.query(` const checkHumanQ = await pool.query(`
SELECT sender_role, created_at SELECT sender_role, created_at
FROM service_communications FROM service_communications
WHERE scraped_id = $1 WHERE scraped_id = $1
AND sender_role IN ('admin', 'superadmin', 'operario') AND sender_role IN ('admin', 'superadmin', 'operario')
AND COALESCE(sender_name, '') <> 'Marsalva (Claude)'
ORDER BY created_at DESC ORDER BY created_at DESC
LIMIT 1 LIMIT 1
`, [service.id]); `, [service.id]);
@@ -6022,7 +6200,7 @@ async function procesarTurnoIA({ ownerId, service, mensajeTexto, telefonoCliente
if (!textoLimpio) return; if (!textoLimpio) return;
await sendWhatsAppAuto(telefonoCliente, textoLimpio, instanceName, true); await sendWhatsAppAuto(telefonoCliente, conPrefijoIA(textoLimpio), instanceName, true);
await pool.query(` await pool.query(`
INSERT INTO service_communications INSERT INTO service_communications
@@ -6083,7 +6261,7 @@ async function manejarComandoAdmin({ ownerId, mensajeTexto, esAudioSinTexto, tel
const finalPhone = "34" + pending.targetPhone; 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?`; 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 sendWhatsAppAuto(finalPhone, conPrefijoIA(mensajeApertura), instanceName, false);
await pool.query(` await pool.query(`
INSERT INTO service_communications INSERT INTO service_communications
@@ -6374,7 +6552,7 @@ app.post("/webhook/evolution", async (req, res) => {
try { try {
await pool.query(` await pool.query(`
UPDATE scraped_services UPDATE scraped_services
SET raw_data = raw_data - 'ia_paused' SET raw_data = raw_data - 'ia_paused' - 'ia_paused_until'
WHERE id = $1 WHERE id = $1
`, [service.id]); `, [service.id]);
@@ -6438,6 +6616,60 @@ app.post("/webhook/evolution", async (req, res) => {
} }
}); });
// ==========================================
// 🗄️ ARCHIVO AUTOMÁTICO DEL EXPEDIENTE DE UN PRESUPUESTO
// ==========================================
// Cuando el cliente RECHAZA un presupuesto, su expediente propio (service_ref "PRE-<id>") se archiva
// en estado Anulado y se le quita el modo presupuesto, para que no quede abierto ni el asistente de
// WhatsApp lo siga tratando como pendiente. Si más tarde se ACEPTA, se reabre (solo si lo archivó esto).
// Nunca toca servicios de compañías (HomeServe, Multi...): solo el expediente PRE-<id> del presupuesto.
async function sincronizarExpedientePresupuesto(budgetId, ownerId, nuevoEstado, origen = "Sistema") {
try {
if (!budgetId || !ownerId) return;
if (nuevoEstado !== "rejected" && nuevoEstado !== "accepted") return;
const sq = await pool.query(
"SELECT id, status, raw_data FROM scraped_services WHERE owner_id = $1 AND service_ref = $2 ORDER BY id DESC LIMIT 1",
[ownerId, `PRE-${budgetId}`]
);
if (sq.rowCount === 0) return;
const exp = sq.rows[0];
const raw = exp.raw_data || {};
if (nuevoEstado === "rejected") {
if (exp.status === "archived") return;
const stQ = await pool.query(
"SELECT id FROM service_statuses WHERE owner_id = $1 AND LOWER(TRIM(name)) = 'anulado' ORDER BY id LIMIT 1",
[ownerId]
);
raw.budget_mode = false;
raw.archived_at = new Date().toISOString();
raw.archivado_por_rechazo = true;
raw.estado_operativo_previo = raw.status_operativo ?? null;
if (stQ.rowCount > 0) raw.status_operativo = stQ.rows[0].id;
await pool.query("UPDATE scraped_services SET status = 'archived', raw_data = $1 WHERE id = $2", [JSON.stringify(raw), exp.id]);
await pool.query(
"INSERT INTO scraped_service_logs (scraped_id, user_name, action, details) VALUES ($1, $2, $3, $4)",
[exp.id, origen, "Presupuesto Rechazado", `El cliente ha rechazado el presupuesto PRE-${budgetId}. Expediente archivado automáticamente.`]
).catch(() => {});
console.log(`🗄️ [PRESUPUESTOS] PRE-${budgetId} rechazado → expediente ${exp.id} archivado`);
} else if (exp.status === "archived" && raw.archivado_por_rechazo) {
delete raw.archived_at;
delete raw.archivado_por_rechazo;
raw.status_operativo = raw.estado_operativo_previo ?? "";
delete raw.estado_operativo_previo;
raw.budget_mode = true;
await pool.query("UPDATE scraped_services SET status = 'pending', raw_data = $1 WHERE id = $2", [JSON.stringify(raw), exp.id]);
await pool.query(
"INSERT INTO scraped_service_logs (scraped_id, user_name, action, details) VALUES ($1, $2, $3, $4)",
[exp.id, origen, "Presupuesto Aceptado", `El presupuesto PRE-${budgetId} se ha aceptado tras haberse rechazado. Expediente reabierto.`]
).catch(() => {});
console.log(`♻️ [PRESUPUESTOS] PRE-${budgetId} aceptado → expediente ${exp.id} reabierto`);
}
} catch (e) {
console.error("⚠️ Error sincronizando expediente del presupuesto:", e.message);
}
}
// ========================================== // ==========================================
// ✍️ 5. RUTA PARA ACEPTAR/RECHAZAR Y FIRMAR PRESUPUESTOS // ✍️ 5. RUTA PARA ACEPTAR/RECHAZAR Y FIRMAR PRESUPUESTOS
// ========================================== // ==========================================
@@ -6457,6 +6689,8 @@ app.post("/public/portal/:token/budget/:id/respond", async (req, res) => {
"UPDATE budgets SET status = $1, signature = $2 WHERE id = $3 AND owner_id = $4", "UPDATE budgets SET status = $1, signature = $2 WHERE id = $3 AND owner_id = $4",
[newStatus, signature || null, id, ownerId] [newStatus, signature || null, id, ownerId]
); );
// 🗄️ Rechazado → archivar su expediente PRE-xxx. Aceptado → reabrirlo si se había archivado por rechazo.
await sincronizarExpedientePresupuesto(id, ownerId, newStatus, "Cliente (portal)");
const ownerData = await pool.query("SELECT phone FROM users WHERE id = $1", [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]); const bQ = await pool.query("SELECT client_name, total FROM budgets WHERE id = $1", [id]);
@@ -7352,6 +7586,14 @@ 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_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, precio_energia_llano, precio_energia_valle, descuento_pct, descuento_aplica_a,
alquiler_contador_dia, bono_social_dia, total_factura, permanencia, permanencia_fecha_fin. 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 SOBRE FORMATO NUMERICO: las facturas españolas usan la coma como separador decimal
(por ejemplo "4,600 kW" significa 4.6, no 4600; "0,115155 Eur/kWh" significa 0.115155, no 115155).
Todos los valores numéricos del JSON deben ir en formato JSON estándar (con punto decimal, sin
comas, sin separador de miles y sin unidades ni símbolos como "kW", "kWh" o "€"). Convierte
siempre la coma decimal española a punto antes de responder.
IMPORTANTE: NUNCA extraigas ni menciones nombre, DNI, dirección, IBAN ni CUPS, aunque aparezcan 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.`; en la factura. No incluyas esas claves en el JSON bajo ningún concepto.`;
@@ -7366,7 +7608,7 @@ en la factura. No incluyas esas claves en el JSON bajo ningún concepto.`;
] ]
: [ : [
{ type: "text", text: "Extrae los datos de esta factura (foto) según las instrucciones." }, { type: "text", text: "Extrae los datos de esta factura (foto) según las instrucciones." },
{ type: "image_url", image_url: { url: dataUrl } }, { type: "image_url", image_url: { url: dataUrl, detail: "high" } },
]; ];
const completion = await openai.chat.completions.create({ const completion = await openai.chat.completions.create({
@@ -7490,11 +7732,17 @@ app.post("/public/energy-quote", energyQuoteLimiter, async (req, res) => {
// 6) Avisar a Marco por WhatsApp (reutilizando la integración Evolution ya existente) // 6) Avisar a Marco por WhatsApp (reutilizando la integración Evolution ya existente)
const adminPhoneRaw = settings.admin_whatsapp || process.env.ENERGY_ADMIN_WHATSAPP || ""; const adminPhoneRaw = settings.admin_whatsapp || process.env.ENERGY_ADMIN_WHATSAPP || "";
const adminPhone = adminPhoneRaw.replace("+", ""); const adminPhone = adminPhoneRaw.replace("+", "");
if (adminPhone && process.env.EVOLUTION_INSTANCE) { if (adminPhone) {
const instanciaEvolution = `cliente_${ownerId}`;
const aviso = revisarManualmente 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 (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)`; : `💡 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, process.env.EVOLUTION_INSTANCE, false).catch(console.error); sendWhatsAppAuto(adminPhone, aviso, instanciaEvolution, false).catch(console.error);
// 📎 Enviamos también el archivo original de la factura (PDF o foto) para que Marco la vea directamente
const extFactura = archivoMime === "application/pdf" ? "pdf" : (archivoMime === "image/png" ? "png" : "jpg");
const nombreFactura = `factura_${telefono || "sin_telefono"}.${extFactura}`;
sendWhatsAppMedia(adminPhone, archivoBase64, nombreFactura, "📎 Factura subida por el cliente", instanciaEvolution, archivoMime).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 }); res.json({ ok: true, message: "Hemos recibido tu factura, te enviamos el estudio en menos de 24h.", leadId: leadQ.rows[0].id });
@@ -7554,6 +7802,280 @@ app.delete("/energy-tariffs/:id", authMiddleware, async (req, res) => {
} catch (e) { res.status(500).json({ ok: false }); } } catch (e) { res.status(500).json({ ok: false }); }
}); });
// --- Generación del PDF detallado de la comparativa de factura de luz (logo Marsalva + Repsol) ---
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);
const MARSALVA_LOGO_PATH = path.join(__dirname, "assets", "logos", "marsalva.png");
const REPSOL_LOGO_PATH = path.join(__dirname, "assets", "logos", "repsol.png");
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);
}
function __cp1252ControlMap(code) {
const map = {
128: "€", 130: "‚", 131: "ƒ", 132: "„",
133: "…", 134: "†", 135: "‡", 136: "ˆ",
137: "‰", 138: "Š", 139: "‹", 140: "Œ",
142: "Ž", 145: "‘", 146: "’", 147: "“",
148: "”", 149: "•", 150: "–", 151: "—",
152: "˜", 153: "™", 154: "š", 155: "›",
156: "œ", 158: "ž", 159: "Ÿ",
};
return map[code] || "";
}
function sanitizeMojibake(input) {
if (input === null || input === undefined) return input;
const s = String(input);
let out = "";
for (let i = 0; i < s.length; i++) {
const code = s.charCodeAt(i);
if (code >= 128 && code <= 159) {
out += __cp1252ControlMap(code);
} else if (code <= 8 || code === 11 || code === 12 || (code >= 14 && code <= 31) || code === 127) {
// caracter de control sin uso, se elimina
} else {
out += s[i];
}
}
return out;
}
function sanitizeDeepStrings(value) {
if (typeof value === "string") return sanitizeMojibake(value);
if (Array.isArray(value)) return value.map(sanitizeDeepStrings);
if (value && typeof value === "object") {
const out = {};
for (const k in value) out[k] = sanitizeDeepStrings(value[k]);
return out;
}
return value;
}
async function embedLogoIfExists(doc, 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 doc.embedJpg(bytes);
}
return await doc.embedPng(bytes);
} catch (e) {
console.error("No se pudo incrustar el logo", logoPath, e.message);
return null;
}
}
async function generarPdfComparativaLuz(leadOriginal, opts) {
opts = opts || {};
const lead = sanitizeDeepStrings(leadOriginal);
const fj = lead.factura_json || {};
const comparativa = Array.isArray(lead.comparativa_json) ? lead.comparativa_json : [];
const mejor = comparativa[0] || null;
const doc = await PDFDocument.create();
const PAGE_W = 595.28, PAGE_H = 841.89; // A4
const MARGIN = 42;
let page = doc.addPage([PAGE_W, PAGE_H]);
const font = await doc.embedFont(StandardFonts.Helvetica);
const fontBold = await doc.embedFont(StandardFonts.HelveticaBold);
const marsalvaLogo = await embedLogoIfExists(doc, opts.marsalvaLogoPath || MARSALVA_LOGO_PATH);
const repsolLogo = await embedLogoIfExists(doc, opts.repsolLogoPath || REPSOL_LOGO_PATH);
let y = PAGE_H - MARGIN;
function ensureSpace(h) {
if (y - h < MARGIN + 30) {
page = doc.addPage([PAGE_W, PAGE_H]);
y = PAGE_H - MARGIN;
}
}
function drawText(text, x, yy, o) {
o = o || {};
const size = o.size != null ? o.size : 10;
const bold = !!o.bold;
const color = o.color || PDF_COLOR_DARK;
const align = o.align || "left";
const maxWidth = o.maxWidth != null ? o.maxWidth : null;
text = sanitizeMojibake(text);
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: size, font: f, color: color });
}
function wrapText(text, maxWidth, size, f) {
text = sanitizeMojibake(text);
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: y }, end: { x: PAGE_W - MARGIN, y: 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 != null ? 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 + 11 }, end: { x: PAGE_W - MARGIN, y: y + 11 }, 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(function (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: y }, end: { x: PAGE_W - MARGIN, y: 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(function (line) {
drawText(line, MARGIN, y, { size: 7.5, color: PDF_COLOR_GRAY });
y -= 10;
});
const bytes = await doc.save();
return Buffer.from(bytes);
}
// --- Panel admin: leads del comparador --- // --- Panel admin: leads del comparador ---
app.get("/energy-leads", authMiddleware, async (req, res) => { app.get("/energy-leads", authMiddleware, async (req, res) => {
try { try {
@@ -7570,6 +8092,66 @@ app.patch("/energy-leads/:id", authMiddleware, async (req, res) => {
} catch (e) { res.status(500).json({ ok: false }); } } catch (e) { res.status(500).json({ ok: false }); }
}); });
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 mejorTarifa = Array.isArray(lead.comparativa_json) ? lead.comparativa_json[0] : null;
const tieneAhorroMsg = mejorTarifa && Number(lead.ahorro_estimado_factura) > 0;
const mensaje = tieneAhorroMsg
? ("Hola! Ya tenemos listo tu estudio comparativo de la factura de luz. Con " + mejorTarifa.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) --- // --- Panel admin: ajustes (IEE, IVA, modelo IA, WhatsApp de aviso, activar/desactivar CNMC) ---
app.get("/energy-settings", authMiddleware, async (req, res) => { app.get("/energy-settings", authMiddleware, async (req, res) => {
try { try {
@@ -7594,4 +8176,20 @@ app.put("/energy-settings", authMiddleware, async (req, res) => {
const port = process.env.PORT || 3000; const port = process.env.PORT || 3000;
autoUpdateDB().then(() => { app.listen(port, "0.0.0.0", () => console.log(`🚀 Server OK en puerto ${port}`)); }); autoUpdateDB().then(async () => {
if (process.env.INTEGRA_MCP_ENABLED === 'true') {
await mountIntegraMcp({
app, pool,
// Token interno efímero; nunca se entrega al cliente MCP.
signToken: user => jwt.sign(
{ sub: user.id, role: user.role, accountId: user.accountId },
JWT_SECRET, { expiresIn: '60s' }
),
checkAvailability: comprobarDisponibilidad
});
}
app.listen(port, "0.0.0.0", () => console.log(`🚀 Server OK en puerto ${port}`));
}).catch(error => {
console.error('No se pudo iniciar IntegraRepara:', error.message);
process.exit(1);
});