Files
agenciapsilmno/supabase/functions/convert-abandoned-intakes/index.ts
T
Leonardo f17e9ee786 F1b: 6 tabelas anon-facing ficam em public (decisao roteamento anon)
Fluxos anon identificam tenant por token/slug e nao resolvem o schema fisico.
Decisao (opcao C): manter em public com RLS por token. Volta a global:
patient_intake_requests, patient_invites, patient_invite_attempts,
document_share_links, agendador_configuracoes, agendador_solicitacoes.

- migration 20260613000001_f1b: remove as 6 do _tenant_template (template v2,
  78 tabelas). Smoke: clone gera 78, zero tabelas anon no schema, drop limpo
- frontend: 38 cadeias em 14 arquivos revertidas tenantDb().from() ->
  supabase.from() com tenant_id/owner_id restaurado (via comparacao com main)
- edge: convert-abandoned-intakes restaurada do main (SELECT global)
- save-intake-progress: ja usava public, sem mudanca
- doc F0 atualizado: 78 tenant + 59 global

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-13 09:09:46 -03:00

92 lines
3.3 KiB
TypeScript

/*
|--------------------------------------------------------------------------
| Agência PSI — Edge: convert-abandoned-intakes (8.4)
|--------------------------------------------------------------------------
| Cron que varre patient_intake_requests com status='in_progress' e
| last_progress_at ha mais de IDLE_MINUTES (default 30). Chama a RPC
| convert_abandoned_intake_to_lead pra cada um — RPC cria mensagem
| placeholder + nota interna + marca status='abandoned_lead'.
|
| Body opcional: { idle_minutes?: number } (default 30)
|
| Retorna: { checked, converted, errors }
|--------------------------------------------------------------------------
*/
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
}
function json(body: unknown, status = 200) {
return new Response(JSON.stringify(body), {
status,
headers: { ...corsHeaders, 'Content-Type': 'application/json' }
})
}
const DEFAULT_IDLE_MINUTES = 30
Deno.serve(async (req: Request) => {
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders })
try {
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 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 converted = 0
let errors = 0
const results: Array<{ 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 })
}
}
return json({
checked: candidates?.length || 0,
eligible: eligible.length,
converted,
errors,
idle_minutes: idleMinutes,
results
})
} catch (err) {
console.error('[convert-abandoned-intakes] fatal:', err)
return json({ error: (err as Error).message || 'unexpected' }, 500)
}
})