F4 schema-per-tenant: edge functions roteiam pro schema do tenant
- _shared/tenant.ts: helper (adminClient, tenantDbForId, schemaForTenant, listTenantSchemas, resolveTenantByChannel, tenantSchemaName) - _shared/whatsapp-hooks.ts: hooks de tabela tenant recebem tdb; RPCs de credito (deduct/add_whatsapp_credits) e tenant_members seguem em supa+p_tenant_id - inbound (twilio/evolution): tenant_id da URL -> tdb pra conversation_messages e notification_channels - crons de fila (process-notification/email/sms/whatsapp-queue): varrem listTenantSchemas e drenam a fila de cada schema (Q3: filas sao per-tenant); modo single-tenant se body.tenant_id vier - crons reminders/checks (send-session-reminders, conversation-sla-check, whatsapp-heartbeat-check, convert-abandoned-intakes, sync-email-templates): loop por tenant - routing por tenant_id (send-whatsapp-message, send-session-reminder-manual, twilio-provision, de/reactivate-channel, twilio-webhook): tenantDbForId; channel-actions sem tenant_id varrem schemas por channel_id - asaas-*: tenant_id do body -> tdb; asaas-webhook fica global (whatsapp_credit_purchases) - notification-webhook (Meta): resolve tenant via channel_routing por phone_number_id, fan-out por message_id quando nao resolve - caller send-session-reminder-manual passa tenant_id (evento vive no schema) Pendente: save-intake-progress e fluxos anon por token (decisao de roteamento) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -13,7 +13,7 @@
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
|
||||
import { adminClient, listTenantSchemas } from '../_shared/tenant.ts'
|
||||
|
||||
const corsHeaders = {
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
@@ -37,48 +37,56 @@ Deno.serve(async (req: Request) => {
|
||||
const body = await req.json().catch(() => ({})) as { idle_minutes?: number }
|
||||
const idleMinutes = Math.max(5, Math.min(1440, Number(body.idle_minutes) || DEFAULT_IDLE_MINUTES))
|
||||
|
||||
const supa = createClient(
|
||||
Deno.env.get('SUPABASE_URL')!,
|
||||
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!
|
||||
)
|
||||
const admin = adminClient()
|
||||
|
||||
const cutoff = new Date(Date.now() - idleMinutes * 60 * 1000).toISOString()
|
||||
|
||||
// Busca candidatos: in_progress, last_progress_at antigo, tem minimo nome OU telefone
|
||||
const { data: candidates, error: fetchErr } = await supa
|
||||
.from('patient_intake_requests')
|
||||
.select('id, nome_completo, telefone, email_principal')
|
||||
.eq('status', 'in_progress')
|
||||
.lt('last_progress_at', cutoff)
|
||||
|
||||
if (fetchErr) return json({ error: fetchErr.message }, 500)
|
||||
|
||||
const eligible = (candidates || []).filter((c) => c.nome_completo || c.telefone)
|
||||
|
||||
if (eligible.length === 0) {
|
||||
return json({ checked: candidates?.length || 0, converted: 0, errors: 0 })
|
||||
}
|
||||
|
||||
let checked = 0
|
||||
let eligibleCount = 0
|
||||
let converted = 0
|
||||
let errors = 0
|
||||
const results: Array<{ intake_id: string; ok: boolean; error?: string }> = []
|
||||
const results: Array<{ tenant_id: string; intake_id: string; ok: boolean; error?: string }> = []
|
||||
|
||||
for (const row of eligible) {
|
||||
const { error: rpcErr } = await supa.rpc('convert_abandoned_intake_to_lead', {
|
||||
p_intake_id: row.id
|
||||
})
|
||||
if (rpcErr) {
|
||||
errors++
|
||||
results.push({ intake_id: row.id, ok: false, error: rpcErr.message })
|
||||
} else {
|
||||
converted++
|
||||
results.push({ intake_id: row.id, ok: true })
|
||||
// Varre todos os tenants; patient_intake_requests é tenant → tdb
|
||||
for (const t of await listTenantSchemas(admin)) {
|
||||
const tdb = admin.schema(t.schema)
|
||||
|
||||
// Busca candidatos: in_progress, last_progress_at antigo, tem minimo nome OU telefone
|
||||
const { data: candidates, error: fetchErr } = await tdb
|
||||
.from('patient_intake_requests')
|
||||
.select('id, nome_completo, telefone, email_principal')
|
||||
.eq('status', 'in_progress')
|
||||
.lt('last_progress_at', cutoff)
|
||||
|
||||
if (fetchErr) {
|
||||
console.error(`[convert-abandoned-intakes] fetch error (tenant ${t.tenantId}):`, fetchErr.message)
|
||||
continue
|
||||
}
|
||||
|
||||
checked += candidates?.length || 0
|
||||
|
||||
const eligible = (candidates || []).filter((c) => c.nome_completo || c.telefone)
|
||||
eligibleCount += eligible.length
|
||||
|
||||
for (const row of eligible) {
|
||||
// RPC opera no schema do tenant → tdb.rpc (assinatura só com p_intake_id).
|
||||
// TODO(F6): se a RPC passar a exigir p_tenant_id, adicionar t.tenantId aqui.
|
||||
const { error: rpcErr } = await tdb.rpc('convert_abandoned_intake_to_lead', {
|
||||
p_intake_id: row.id
|
||||
})
|
||||
if (rpcErr) {
|
||||
errors++
|
||||
results.push({ tenant_id: t.tenantId, intake_id: row.id, ok: false, error: rpcErr.message })
|
||||
} else {
|
||||
converted++
|
||||
results.push({ tenant_id: t.tenantId, intake_id: row.id, ok: true })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return json({
|
||||
checked: candidates?.length || 0,
|
||||
eligible: eligible.length,
|
||||
checked,
|
||||
eligible: eligibleCount,
|
||||
converted,
|
||||
errors,
|
||||
idle_minutes: idleMinutes,
|
||||
|
||||
Reference in New Issue
Block a user