F3 schema-per-tenant: frontend usa tenantDb() pra tabelas tenant

- useTenantDb composable + lib/supabase/tenantClient (tenantDb/tenantSchemaName)
- tenantStore: getters activeTenantSlug/activeTenantSchema; my_tenants() RPC
  passa a devolver slug+nome (migration 07)
- codemod scripts/codemod-tenant-db.py: supabase.from('<84 tabelas + 6 views
  tenant>') -> tenantDb().from(...) em 139 arquivos (777 chamadas), remove
  .eq('tenant_id') das cadeias tenant (173)
- passada manual (4 agentes): remove tenant_id de payloads insert/upsert/update,
  selects, .or/.is de defaults; onConflict ajustado pros uniques sem tenant_id
  (singletons usam 'singleton'); realtime de tabelas tenant aponta pro schema
  do tenant ativo; repos dropam tenant_id defensivamente de payloads externos
- agendaSelects: tenant_id fora do AGENDA_EVENT_SELECT (quebraria PostgREST)
- zero embeds cross-schema (todos FK embeds sao tenant->tenant ou global->global)
- build de producao passa; 67 .js checados

Pendente (fora do escopo F3, sao cross-tenant/anon -> F4/F6):
- AgendadorPublicoPage (anon, resolve tenant por link_slug)
- Saas{Feriados,NotificationTemplates,DocumentTemplates,Whatsapp}Page
  (gerenciam defaults do sistema / views cross-tenant)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Leonardo
2026-06-13 04:44:59 -03:00
parent 05c6746e33
commit a7f6bcbe66
142 changed files with 1404 additions and 1472 deletions
@@ -8,12 +8,13 @@
| Pure functions seguindo blueprints/repository-blueprint.md.
|
| Schema (servicos_prontuarios.sql):
| id, owner_id, tenant_id,
| id, owner_id,
| name text, notes text, default_value numeric(10,2),
| active boolean DEFAULT true, created_at, updated_at
|--------------------------------------------------------------------------
*/
import { supabase } from '@/lib/supabase/client';
import { tenantDb } from '@/lib/supabase/tenantClient';
import { useTenantStore } from '@/stores/tenantStore';
import { assertTenantId, getUid } from './_tenantGuards';
import { INSURANCE_PLAN_SELECT } from './insurancePlansSelects';
@@ -37,7 +38,7 @@ export async function listForOwner({ ownerId, tenantId, includeInactive = false
const tid = resolveTenantId(tenantId);
const uid = ownerId || (await getUid());
let q = supabase.from('insurance_plans').select(INSURANCE_PLAN_SELECT).eq('tenant_id', tid).eq('owner_id', uid).order('name', { ascending: true });
let q = tenantDb().from('insurance_plans').select(INSURANCE_PLAN_SELECT).eq('owner_id', uid).order('name', { ascending: true });
if (!includeInactive) q = q.eq('active', true);
@@ -47,14 +48,14 @@ export async function listForOwner({ ownerId, tenantId, includeInactive = false
}
/**
* Lê convênio por id. Filtra owner_id + tenant_id por segurança.
* Lê convênio por id. Filtra owner_id por segurança.
*/
export async function getById(id, { tenantId } = {}) {
if (!id) throw new Error('ID inválido.');
const tid = resolveTenantId(tenantId);
const uid = await getUid();
const { data, error } = await supabase.from('insurance_plans').select(INSURANCE_PLAN_SELECT).eq('id', id).eq('tenant_id', tid).eq('owner_id', uid).maybeSingle();
const { data, error } = await tenantDb().from('insurance_plans').select(INSURANCE_PLAN_SELECT).eq('id', id).eq('owner_id', uid).maybeSingle();
if (error) throw error;
return data || null;
@@ -76,7 +77,7 @@ export async function findByName({ name, ownerId, tenantId } = {}) {
const safeName = String(name).trim();
if (!safeName) return null;
const { data, error } = await supabase.from('insurance_plans').select(INSURANCE_PLAN_SELECT).eq('tenant_id', tid).eq('owner_id', uid).eq('active', true).ilike('name', safeName).limit(1).maybeSingle();
const { data, error } = await tenantDb().from('insurance_plans').select(INSURANCE_PLAN_SELECT).eq('owner_id', uid).eq('active', true).ilike('name', safeName).limit(1).maybeSingle();
if (error) throw error;
return data || null;
@@ -84,7 +85,7 @@ export async function findByName({ name, ownerId, tenantId } = {}) {
/**
* Cria convênio. Pré-checa duplicidade por nome (case-insensitive) — se já
* existe ativo, lança erro PT-BR. Repository injeta owner_id + tenant_id.
* existe ativo, lança erro PT-BR. Repository injeta owner_id.
*/
export async function create(payload) {
if (!payload) throw new Error('Payload vazio.');
@@ -103,21 +104,20 @@ export async function create(payload) {
const insertPayload = {
owner_id: uid,
tenant_id: tid,
name: name.slice(0, 120),
notes: payload.notes ? String(payload.notes).trim().slice(0, 500) || null : null,
default_value: payload.default_value != null && payload.default_value !== '' ? Number(payload.default_value) : null,
active: payload.active !== false
};
const { data, error } = await supabase.from('insurance_plans').insert([insertPayload]).select(INSURANCE_PLAN_SELECT).single();
const { data, error } = await tenantDb().from('insurance_plans').insert([insertPayload]).select(INSURANCE_PLAN_SELECT).single();
if (error) throw error;
return data;
}
/**
* Atualiza convênio. Filtra por id + tenant_id.
* Atualiza convênio. Filtra por id.
*/
export async function update(id, patch, { tenantId } = {}) {
if (!id) throw new Error('ID inválido.');
@@ -127,7 +127,7 @@ export async function update(id, patch, { tenantId } = {}) {
const safePatch = sanitize(patch);
safePatch.updated_at = new Date().toISOString();
const { data, error } = await supabase.from('insurance_plans').update(safePatch).eq('id', id).eq('tenant_id', tid).select(INSURANCE_PLAN_SELECT).single();
const { data, error } = await tenantDb().from('insurance_plans').update(safePatch).eq('id', id).select(INSURANCE_PLAN_SELECT).single();
if (error) throw error;
return data;
@@ -140,7 +140,7 @@ export async function softDelete(id, { tenantId } = {}) {
if (!id) throw new Error('ID inválido.');
const tid = resolveTenantId(tenantId);
const { error } = await supabase.from('insurance_plans').update({ active: false, updated_at: new Date().toISOString() }).eq('id', id).eq('tenant_id', tid);
const { error } = await tenantDb().from('insurance_plans').update({ active: false, updated_at: new Date().toISOString() }).eq('id', id);
if (error) throw error;
return true;
@@ -149,7 +149,9 @@ export async function softDelete(id, { tenantId } = {}) {
// ─── helpers internos ────────────────────────────────────────────────────────
function sanitize(payload) {
const out = { ...payload };
// Dropa tenant_id defensivamente (schema-per-tenant: coluna não existe mais)
const { tenant_id: _drop, ...rest } = payload;
const out = { ...rest };
if ('name' in out && typeof out.name === 'string') {
const t = out.name.trim();
out.name = t === '' ? null : t.slice(0, 120);