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>
This commit is contained in:
Leonardo
2026-06-13 09:09:46 -03:00
parent 9b21642e15
commit f17e9ee786
17 changed files with 164 additions and 98 deletions
@@ -13,7 +13,7 @@
|--------------------------------------------------------------------------
*/
import { adminClient, listTenantSchemas } from '../_shared/tenant.ts'
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
@@ -37,56 +37,48 @@ 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 admin = adminClient()
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()
let checked = 0
let eligibleCount = 0
// 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<{ tenant_id: string; intake_id: string; ok: boolean; error?: string }> = []
const results: Array<{ intake_id: string; ok: boolean; error?: string }> = []
// 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 })
}
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,
eligible: eligibleCount,
checked: candidates?.length || 0,
eligible: eligible.length,
converted,
errors,
idle_minutes: idleMinutes,