diff --git a/supabase/functions/railway-webhook/index.ts b/supabase/functions/railway-webhook/index.ts index 6943cfb..840669e 100644 --- a/supabase/functions/railway-webhook/index.ts +++ b/supabase/functions/railway-webhook/index.ts @@ -81,7 +81,7 @@ Deno.serve(async (req) => { const { data: agent } = await supabase .from("agent_instances") - .select("id, status") + .select("id, status, user_id, telegram_bot_username, railway_service_id") .eq("railway_service_id", serviceId) .maybeSingle(); @@ -92,6 +92,17 @@ Deno.serve(async (req) => { const now = new Date().toISOString(); const upper = status.toUpperCase(); + const wasProvisioning = agent.status === "provisioning"; + + // Carrega nome do cliente para a notificação (best-effort) + async function loadFullName(): Promise { + const { data } = await supabase + .from("profiles") + .select("full_name") + .eq("id", agent.user_id) + .maybeSingle(); + return (data?.full_name as string | undefined) || "—"; + } if (upper === "SUCCESS" || upper === "ACTIVE" || upper === "DEPLOYED") { await supabase @@ -110,6 +121,19 @@ Deno.serve(async (req) => { .in("status", ["running", "retrying", "pending"]); console.log(`railway-webhook: agent ${agent.id} marcado como active (status=${upper})`); + + // Notifica admin somente se era um auto-provisionamento (status anterior=provisioning) + if (wasProvisioning) { + const fullName = await loadFullName(); + await notifyAdmin( + `✅ Agente provisionado automaticamente!\n\n` + + `👤 Cliente: ${fullName}\n` + + `🤖 Bot: @${agent.telegram_bot_username || "—"}\n` + + `🚀 Railway: ${agent.railway_service_id}\n\n` + + `O cliente já pode conversar com a Mika no Telegram.`, + ); + } + return jsonResponse(200, { ok: true, agent_id: agent.id, new_status: "active" }); } @@ -130,6 +154,18 @@ Deno.serve(async (req) => { .in("status", ["running", "retrying", "pending"]); console.log(`railway-webhook: agent ${agent.id} marcado como error (status=${upper})`); + + if (wasProvisioning) { + const fullName = await loadFullName(); + await notifyAdmin( + `❌ Falha no deploy do agente\n\n` + + `👤 Cliente: ${fullName}\n` + + `🚀 Railway: ${agent.railway_service_id}\n` + + `❗ Status: ${upper}\n\n` + + `➡️ Investigar`, + ); + } + return jsonResponse(200, { ok: true, agent_id: agent.id, new_status: "error" }); }