72 lines
2.1 KiB
JavaScript
72 lines
2.1 KiB
JavaScript
import crypto from "crypto";
|
|
import { parseEvolutionWebhook } from "../services/evolutionParser.js";
|
|
import { resolveTenantId, processMessage } from "../../2-identity/services/pipeline.js";
|
|
import { debug as dbg } from "../../shared/debug.js";
|
|
|
|
export async function handleEvolutionWebhook(body) {
|
|
const t0 = Date.now();
|
|
const parsed = parseEvolutionWebhook(body);
|
|
// #region agent log
|
|
fetch("http://127.0.0.1:7242/ingest/86c7b1cd-c414-4eae-852c-08e57e562b3b", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({
|
|
sessionId: "debug-session",
|
|
runId: "pre-fix",
|
|
hypothesisId: "H1",
|
|
location: "evolution.js:9",
|
|
message: "parsed_webhook",
|
|
data: {
|
|
ok: parsed?.ok,
|
|
reason: parsed?.reason || null,
|
|
has_text: Boolean(parsed?.text),
|
|
source: parsed?.source || null,
|
|
},
|
|
timestamp: Date.now(),
|
|
}),
|
|
}).catch(() => {});
|
|
// #endregion
|
|
if (!parsed.ok) {
|
|
return { status: 200, payload: { ok: true, ignored: parsed.reason } };
|
|
}
|
|
|
|
if (dbg.perf || dbg.evolution) {
|
|
console.log("[perf] evolution.webhook.start", {
|
|
tenant_key: parsed.tenant_key || null,
|
|
chat_id: parsed.chat_id,
|
|
message_id: parsed.message_id || null,
|
|
ts: parsed.ts || null,
|
|
});
|
|
}
|
|
|
|
const tenantId = await resolveTenantId({
|
|
chat_id: parsed.chat_id,
|
|
tenant_key: parsed.tenant_key,
|
|
to_phone: null,
|
|
});
|
|
|
|
const pm = await processMessage({
|
|
tenantId,
|
|
chat_id: parsed.chat_id,
|
|
from: parsed.chat_id.replace("@s.whatsapp.net", ""),
|
|
displayName: parsed.from_name || null,
|
|
text: parsed.text,
|
|
provider: "evolution",
|
|
message_id: parsed.message_id || crypto.randomUUID(),
|
|
meta: { pushName: parsed.from_name, ts: parsed.ts, instance: parsed.tenant_key, source: parsed.source },
|
|
});
|
|
|
|
if (dbg.perf || dbg.evolution) {
|
|
console.log("[perf] evolution.webhook.end", {
|
|
tenantId,
|
|
chat_id: parsed.chat_id,
|
|
message_id: parsed.message_id || null,
|
|
run_id: pm?.run_id || null,
|
|
webhook_ms: Date.now() - t0,
|
|
});
|
|
}
|
|
|
|
return { status: 200, payload: { ok: true } };
|
|
}
|
|
|