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:
@@ -6,6 +6,7 @@
|
||||
<script setup>
|
||||
import { ref, computed, onMounted, watch } from 'vue';
|
||||
import { supabase } from '@/lib/supabase/client';
|
||||
import { tenantDb } from '@/lib/supabase/tenantClient';
|
||||
import { useConversationDrawerStore } from '@/stores/conversationDrawerStore';
|
||||
import { formatDistanceToNow, format } from 'date-fns';
|
||||
import { ptBR } from 'date-fns/locale';
|
||||
@@ -31,8 +32,7 @@ async function load() {
|
||||
if (!props.patientId) return;
|
||||
loading.value = true;
|
||||
try {
|
||||
const { data, error } = await supabase
|
||||
.from('conversation_messages')
|
||||
const { data, error } = await tenantDb().from('conversation_messages')
|
||||
.select('id, channel, direction, from_number, to_number, body, media_url, media_mime, provider, kanban_status, received_at, created_at, responded_at, delivery_status')
|
||||
.eq('patient_id', props.patientId)
|
||||
.order('created_at', { ascending: true })
|
||||
|
||||
@@ -27,6 +27,7 @@ import Popover from 'primevue/popover';
|
||||
import { useToast } from 'primevue/usetoast';
|
||||
import { useConfirm } from 'primevue/useconfirm';
|
||||
import { supabase } from '@/lib/supabase/client';
|
||||
import { tenantDb } from '@/lib/supabase/tenantClient';
|
||||
import { useTenantStore } from '@/stores/tenantStore';
|
||||
import { useConversationDrawerStore } from '@/stores/conversationDrawerStore';
|
||||
|
||||
@@ -379,8 +380,7 @@ async function updateSessionStatus(ev, novoStatus, msg) {
|
||||
if (!ev?.id || sessionBusy.value) return;
|
||||
sessionBusy.value = true;
|
||||
try {
|
||||
const { error } = await supabase
|
||||
.from('agenda_eventos')
|
||||
const { error } = await tenantDb().from('agenda_eventos')
|
||||
.update({ status: novoStatus })
|
||||
.eq('id', ev.id);
|
||||
if (error) throw error;
|
||||
@@ -432,8 +432,7 @@ function openAddPhone() {
|
||||
// bloqueamos save por falha no check.
|
||||
async function findPhoneOwner(digits, excludeId) {
|
||||
try {
|
||||
const { data: byPat } = await supabase
|
||||
.from('patients')
|
||||
const { data: byPat } = await tenantDb().from('patients')
|
||||
.select('id, nome_completo')
|
||||
.eq('telefone', digits)
|
||||
.neq('id', excludeId)
|
||||
@@ -441,8 +440,7 @@ async function findPhoneOwner(digits, excludeId) {
|
||||
.maybeSingle();
|
||||
if (byPat?.id) return byPat;
|
||||
|
||||
const { data: byCp } = await supabase
|
||||
.from('contact_phones')
|
||||
const { data: byCp } = await tenantDb().from('contact_phones')
|
||||
.select('entity_id')
|
||||
.eq('entity_type', 'patient')
|
||||
.eq('number', digits)
|
||||
@@ -450,8 +448,7 @@ async function findPhoneOwner(digits, excludeId) {
|
||||
.limit(1)
|
||||
.maybeSingle();
|
||||
if (byCp?.entity_id) {
|
||||
const { data: p } = await supabase
|
||||
.from('patients')
|
||||
const { data: p } = await tenantDb().from('patients')
|
||||
.select('id, nome_completo')
|
||||
.eq('id', byCp.entity_id)
|
||||
.maybeSingle();
|
||||
@@ -508,8 +505,7 @@ async function _persistPhone(id, digits, tenantId) {
|
||||
|
||||
// 1) Garante o contact_type "whatsapp" (system, slug fixo via
|
||||
// seed_014_global_data).
|
||||
const { data: ctype, error: errType } = await supabase
|
||||
.from('contact_types')
|
||||
const { data: ctype, error: errType } = await tenantDb().from('contact_types')
|
||||
.select('id')
|
||||
.eq('slug', 'whatsapp')
|
||||
.order('is_system', { ascending: false })
|
||||
@@ -519,8 +515,7 @@ async function _persistPhone(id, digits, tenantId) {
|
||||
if (!ctype?.id) throw new Error('Tipo de contato "WhatsApp" não encontrado.');
|
||||
|
||||
// 2) Insere ou atualiza em contact_phones (entity_type=patient).
|
||||
const { data: existing } = await supabase
|
||||
.from('contact_phones')
|
||||
const { data: existing } = await tenantDb().from('contact_phones')
|
||||
.select('id, is_primary')
|
||||
.eq('entity_type', 'patient')
|
||||
.eq('entity_id', id)
|
||||
@@ -529,22 +524,18 @@ async function _persistPhone(id, digits, tenantId) {
|
||||
.maybeSingle();
|
||||
|
||||
if (existing?.id) {
|
||||
const { error: errUpd } = await supabase
|
||||
.from('contact_phones')
|
||||
const { error: errUpd } = await tenantDb().from('contact_phones')
|
||||
.update({ number: digits, whatsapp_linked_at: new Date().toISOString() })
|
||||
.eq('id', existing.id);
|
||||
if (errUpd) throw errUpd;
|
||||
} else {
|
||||
const { count } = await supabase
|
||||
.from('contact_phones')
|
||||
const { count } = await tenantDb().from('contact_phones')
|
||||
.select('id', { count: 'exact', head: true })
|
||||
.eq('entity_type', 'patient')
|
||||
.eq('entity_id', id);
|
||||
const isPrimary = (count || 0) === 0;
|
||||
const { error: errIns } = await supabase
|
||||
.from('contact_phones')
|
||||
const { error: errIns } = await tenantDb().from('contact_phones')
|
||||
.insert({
|
||||
tenant_id: tenantId,
|
||||
entity_type: 'patient',
|
||||
entity_id: id,
|
||||
contact_type_id: ctype.id,
|
||||
@@ -820,8 +811,7 @@ async function loadSessions(patientId) {
|
||||
sessionsLoading.value = true;
|
||||
sessions.value = [];
|
||||
try {
|
||||
const { data, error } = await supabase
|
||||
.from('agenda_eventos')
|
||||
const { data, error } = await tenantDb().from('agenda_eventos')
|
||||
.select('id, inicio_em, fim_em, status, modalidade, tipo, titulo, titulo_custom, observacoes')
|
||||
.eq('patient_id', patientId)
|
||||
.order('inicio_em', { ascending: false })
|
||||
@@ -840,8 +830,7 @@ async function loadRecentMessages(patientId) {
|
||||
messagesLoading.value = true;
|
||||
recentMessages.value = [];
|
||||
try {
|
||||
const { data, error } = await supabase
|
||||
.from('conversation_messages')
|
||||
const { data, error } = await tenantDb().from('conversation_messages')
|
||||
.select('id, body, direction, created_at, channel, kanban_status')
|
||||
.eq('patient_id', patientId)
|
||||
.order('created_at', { ascending: false })
|
||||
@@ -858,8 +847,7 @@ async function loadDocumentsList(patientId) {
|
||||
documentsLoading.value = true;
|
||||
documentsList.value = [];
|
||||
try {
|
||||
const { data, error } = await supabase
|
||||
.from('documents')
|
||||
const { data, error } = await tenantDb().from('documents')
|
||||
.select('id, tipo_documento, created_at, status_revisao, tamanho_bytes')
|
||||
.eq('patient_id', patientId)
|
||||
.is('deleted_at', null)
|
||||
@@ -878,8 +866,7 @@ async function loadFinancialRecent(patientId) {
|
||||
financialLoading.value = true;
|
||||
financialRecords.value = [];
|
||||
try {
|
||||
const { data, error } = await supabase
|
||||
.from('financial_records')
|
||||
const { data, error } = await tenantDb().from('financial_records')
|
||||
.select('id, type, amount, due_date, paid_at, description, payment_method, category, created_at')
|
||||
.eq('patient_id', patientId)
|
||||
.eq('type', 'receita')
|
||||
@@ -892,15 +879,15 @@ async function loadFinancialRecent(patientId) {
|
||||
}
|
||||
|
||||
async function getPatientById(id) {
|
||||
const { data, error } = await supabase.from('patients').select('*').eq('id', id).maybeSingle();
|
||||
const { data, error } = await tenantDb().from('patients').select('*').eq('id', id).maybeSingle();
|
||||
if (error) throw error;
|
||||
return data;
|
||||
}
|
||||
|
||||
async function getPatientRelations(id) {
|
||||
const { data: g, error: ge } = await supabase.from('patient_group_patient').select('patient_group_id').eq('patient_id', id);
|
||||
const { data: g, error: ge } = await tenantDb().from('patient_group_patient').select('patient_group_id').eq('patient_id', id);
|
||||
if (ge) throw ge;
|
||||
const { data: t, error: te } = await supabase.from('patient_patient_tag').select('tag_id').eq('patient_id', id);
|
||||
const { data: t, error: te } = await tenantDb().from('patient_patient_tag').select('tag_id').eq('patient_id', id);
|
||||
if (te) throw te;
|
||||
return {
|
||||
groupIds: (g || []).map(x => x.patient_group_id).filter(Boolean),
|
||||
@@ -910,14 +897,14 @@ async function getPatientRelations(id) {
|
||||
|
||||
async function getGroupsByIds(ids) {
|
||||
if (!ids?.length) return [];
|
||||
const { data, error } = await supabase.from('patient_groups').select('id, nome').in('id', ids).order('nome', { ascending: true });
|
||||
const { data, error } = await tenantDb().from('patient_groups').select('id, nome').in('id', ids).order('nome', { ascending: true });
|
||||
if (error) throw error;
|
||||
return (data || []).map(g => ({ id: g.id, name: g.nome }));
|
||||
}
|
||||
|
||||
async function getTagsByIds(ids) {
|
||||
if (!ids?.length) return [];
|
||||
const { data, error } = await supabase.from('patient_tags').select('id, nome, cor').in('id', ids).order('nome', { ascending: true });
|
||||
const { data, error } = await tenantDb().from('patient_tags').select('id, nome, cor').in('id', ids).order('nome', { ascending: true });
|
||||
if (error) throw error;
|
||||
return (data || []).map(t => ({ id: t.id, name: t.nome, color: t.cor }));
|
||||
}
|
||||
@@ -989,8 +976,7 @@ async function setProximaSessaoStatus(novoStatus, msgSucesso) {
|
||||
if (!ev?.id || sessionBusy.value) return;
|
||||
sessionBusy.value = true;
|
||||
try {
|
||||
const { error } = await supabase
|
||||
.from('agenda_eventos')
|
||||
const { error } = await tenantDb().from('agenda_eventos')
|
||||
.update({ status: novoStatus })
|
||||
.eq('id', ev.id);
|
||||
if (error) throw error;
|
||||
|
||||
@@ -5,9 +5,9 @@
|
||||
| Arquivo: src/features/patients/prontuario/services/clinicalNoteTemplatesRepository.js
|
||||
|
|
||||
| Repository de clinical_note_templates. Escopo escalonado:
|
||||
| - Sistema (is_system=true, tenant_id NULL) — todos authenticated leem
|
||||
| - Tenant-wide (tenant_id, owner_id NULL) — membros do tenant
|
||||
| - Owner (tenant_id + owner_id) — só o owner
|
||||
| - Sistema (is_system=true) — todos authenticated leem
|
||||
| - Tenant-wide (owner_id NULL) — membros do tenant (schema do tenant)
|
||||
| - Owner (owner_id) — só o owner
|
||||
|
|
||||
| RLS bloqueia INSERT/UPDATE/DELETE de templates is_system — só via seed.
|
||||
| Templates do tenant podem ser criados/editados pelo tenant_admin.
|
||||
@@ -16,6 +16,7 @@
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
import { supabase } from '@/lib/supabase/client';
|
||||
import { tenantDb } from '@/lib/supabase/tenantClient';
|
||||
import { useTenantStore } from '@/stores/tenantStore';
|
||||
import { assertTenantId, getUid } from './_tenantGuards';
|
||||
import { CLINICAL_NOTE_TEMPLATE_SELECT } from './clinicalNotesSelects';
|
||||
@@ -41,7 +42,7 @@ function resolveTenantId(tenantIdArg) {
|
||||
export async function listAvailable({ noteType, tenantId, includeInactive = false } = {}) {
|
||||
resolveTenantId(tenantId); // garante tenant ativo (RLS depende)
|
||||
|
||||
let q = supabase.from('clinical_note_templates').select(CLINICAL_NOTE_TEMPLATE_SELECT).order('is_system', { ascending: false }).order('name', { ascending: true });
|
||||
let q = tenantDb().from('clinical_note_templates').select(CLINICAL_NOTE_TEMPLATE_SELECT).order('is_system', { ascending: false }).order('name', { ascending: true });
|
||||
|
||||
if (!includeInactive) q = q.eq('active', true);
|
||||
if (noteType) q = q.eq('note_type', noteType);
|
||||
@@ -57,7 +58,7 @@ export async function listAvailable({ noteType, tenantId, includeInactive = fals
|
||||
export async function getById(templateId) {
|
||||
if (!templateId) throw new Error('ID inválido.');
|
||||
|
||||
const { data, error } = await supabase.from('clinical_note_templates').select(CLINICAL_NOTE_TEMPLATE_SELECT).eq('id', templateId).maybeSingle();
|
||||
const { data, error } = await tenantDb().from('clinical_note_templates').select(CLINICAL_NOTE_TEMPLATE_SELECT).eq('id', templateId).maybeSingle();
|
||||
|
||||
if (error) throw error;
|
||||
return data || null;
|
||||
@@ -70,7 +71,7 @@ export async function getById(templateId) {
|
||||
export async function getByKey(key, { noteType } = {}) {
|
||||
if (!key) throw new Error('Key inválida.');
|
||||
|
||||
let q = supabase.from('clinical_note_templates').select(CLINICAL_NOTE_TEMPLATE_SELECT).eq('key', key).eq('active', true);
|
||||
let q = tenantDb().from('clinical_note_templates').select(CLINICAL_NOTE_TEMPLATE_SELECT).eq('key', key).eq('active', true);
|
||||
if (noteType) q = q.eq('note_type', noteType);
|
||||
|
||||
const { data, error } = await q.order('is_system', { ascending: false }).limit(1).maybeSingle();
|
||||
@@ -94,7 +95,6 @@ export async function create(payload) {
|
||||
const tid = resolveTenantId();
|
||||
|
||||
const row = {
|
||||
tenant_id: tid,
|
||||
owner_id: payload.ownerScoped ? uid : null,
|
||||
key: String(payload.key).trim(),
|
||||
name: String(payload.name).trim(),
|
||||
@@ -106,7 +106,7 @@ export async function create(payload) {
|
||||
active: payload.active !== false
|
||||
};
|
||||
|
||||
const { data, error } = await supabase.from('clinical_note_templates').insert([row]).select(CLINICAL_NOTE_TEMPLATE_SELECT).single();
|
||||
const { data, error } = await tenantDb().from('clinical_note_templates').insert([row]).select(CLINICAL_NOTE_TEMPLATE_SELECT).single();
|
||||
|
||||
if (error) throw error;
|
||||
return data;
|
||||
@@ -120,8 +120,9 @@ export async function update(templateId, patch) {
|
||||
|
||||
const safePatch = { ...patch, updated_at: new Date().toISOString() };
|
||||
if ('is_system' in safePatch) delete safePatch.is_system; // RLS bloqueia mas defesa em profundidade
|
||||
if ('tenant_id' in safePatch) delete safePatch.tenant_id; // schema-per-tenant: coluna não existe mais
|
||||
|
||||
const { data, error } = await supabase.from('clinical_note_templates').update(safePatch).eq('id', templateId).select(CLINICAL_NOTE_TEMPLATE_SELECT).single();
|
||||
const { data, error } = await tenantDb().from('clinical_note_templates').update(safePatch).eq('id', templateId).select(CLINICAL_NOTE_TEMPLATE_SELECT).single();
|
||||
|
||||
if (error) throw error;
|
||||
return data;
|
||||
@@ -133,7 +134,7 @@ export async function update(templateId, patch) {
|
||||
export async function softDelete(templateId) {
|
||||
if (!templateId) throw new Error('ID inválido.');
|
||||
|
||||
const { error } = await supabase.from('clinical_note_templates').update({ active: false, updated_at: new Date().toISOString() }).eq('id', templateId);
|
||||
const { error } = await tenantDb().from('clinical_note_templates').update({ active: false, updated_at: new Date().toISOString() }).eq('id', templateId);
|
||||
|
||||
if (error) throw error;
|
||||
return true;
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
import { supabase } from '@/lib/supabase/client';
|
||||
import { tenantDb } from '@/lib/supabase/tenantClient';
|
||||
import { useTenantStore } from '@/stores/tenantStore';
|
||||
import { assertTenantId, getUid } from './_tenantGuards';
|
||||
import {
|
||||
@@ -55,10 +56,9 @@ export async function listForPatient(patientId, { tenantId, noteType = null, inc
|
||||
const tid = resolveTenantId(tenantId);
|
||||
const select = brief ? CLINICAL_NOTE_SELECT_BRIEF : CLINICAL_NOTE_SELECT;
|
||||
|
||||
let q = supabase
|
||||
.from('clinical_notes')
|
||||
let q = tenantDb().from('clinical_notes')
|
||||
.select(select)
|
||||
.eq('tenant_id', tid)
|
||||
|
||||
.eq('patient_id', patientId)
|
||||
.order('pinned', { ascending: false })
|
||||
.order('created_at', { ascending: false });
|
||||
@@ -80,7 +80,7 @@ export async function listForSession(sessionEventId, { tenantId, brief = false }
|
||||
const tid = resolveTenantId(tenantId);
|
||||
const select = brief ? CLINICAL_NOTE_SELECT_BRIEF : CLINICAL_NOTE_SELECT;
|
||||
|
||||
const { data, error } = await supabase.from('clinical_notes').select(select).eq('tenant_id', tid).eq('session_event_id', sessionEventId).is('deleted_at', null).order('created_at', { ascending: false });
|
||||
const { data, error } = await tenantDb().from('clinical_notes').select(select).eq('session_event_id', sessionEventId).is('deleted_at', null).order('created_at', { ascending: false });
|
||||
|
||||
if (error) throw error;
|
||||
return (data || []).map(flattenNoteRow);
|
||||
@@ -93,7 +93,7 @@ export async function getById(noteId, { tenantId } = {}) {
|
||||
if (!noteId) throw new Error('ID inválido.');
|
||||
const tid = resolveTenantId(tenantId);
|
||||
|
||||
const { data, error } = await supabase.from('clinical_notes').select(CLINICAL_NOTE_SELECT).eq('id', noteId).eq('tenant_id', tid).maybeSingle();
|
||||
const { data, error } = await tenantDb().from('clinical_notes').select(CLINICAL_NOTE_SELECT).eq('id', noteId).maybeSingle();
|
||||
|
||||
if (error) throw error;
|
||||
return data ? flattenNoteRow(data) : null;
|
||||
@@ -140,7 +140,7 @@ export async function create(payload) {
|
||||
created_by: uid
|
||||
};
|
||||
|
||||
const { data, error } = await supabase.from('clinical_notes').insert([row]).select(CLINICAL_NOTE_SELECT).single();
|
||||
const { data, error } = await tenantDb().from('clinical_notes').insert([row]).select(CLINICAL_NOTE_SELECT).single();
|
||||
|
||||
if (error) throw error;
|
||||
return flattenNoteRow(data);
|
||||
@@ -164,7 +164,7 @@ export async function update(noteId, patch, { tenantId } = {}) {
|
||||
|
||||
const safePatch = { ...sanitize(patch), updated_by: uid };
|
||||
|
||||
const { data, error } = await supabase.from('clinical_notes').update(safePatch).eq('id', noteId).eq('tenant_id', tid).select(CLINICAL_NOTE_SELECT).single();
|
||||
const { data, error } = await tenantDb().from('clinical_notes').update(safePatch).eq('id', noteId).select(CLINICAL_NOTE_SELECT).single();
|
||||
|
||||
if (error) throw error;
|
||||
return flattenNoteRow(data);
|
||||
@@ -179,11 +179,10 @@ export async function softDelete(noteId, { tenantId } = {}) {
|
||||
const tid = resolveTenantId(tenantId);
|
||||
const uid = await getUid();
|
||||
|
||||
const { error } = await supabase
|
||||
.from('clinical_notes')
|
||||
const { error } = await tenantDb().from('clinical_notes')
|
||||
.update({ deleted_at: new Date().toISOString(), deleted_by: uid, updated_by: uid })
|
||||
.eq('id', noteId)
|
||||
.eq('tenant_id', tid);
|
||||
;
|
||||
|
||||
if (error) throw error;
|
||||
return true;
|
||||
@@ -197,7 +196,7 @@ export async function restore(noteId, { tenantId } = {}) {
|
||||
const tid = resolveTenantId(tenantId);
|
||||
const uid = await getUid();
|
||||
|
||||
const { error } = await supabase.from('clinical_notes').update({ deleted_at: null, deleted_by: null, updated_by: uid }).eq('id', noteId).eq('tenant_id', tid);
|
||||
const { error } = await tenantDb().from('clinical_notes').update({ deleted_at: null, deleted_by: null, updated_by: uid }).eq('id', noteId);
|
||||
|
||||
if (error) throw error;
|
||||
return true;
|
||||
@@ -216,7 +215,7 @@ export async function setPinned(noteId, pinned, { tenantId } = {}) {
|
||||
export async function listVersions(noteId) {
|
||||
if (!noteId) return [];
|
||||
|
||||
const { data, error } = await supabase.from('clinical_note_versions').select(CLINICAL_NOTE_VERSION_SELECT).eq('note_id', noteId).order('version_number', { ascending: false });
|
||||
const { data, error } = await tenantDb().from('clinical_note_versions').select(CLINICAL_NOTE_VERSION_SELECT).eq('note_id', noteId).order('version_number', { ascending: false });
|
||||
|
||||
if (error) throw error;
|
||||
return data || [];
|
||||
@@ -229,7 +228,7 @@ export async function getVersion(noteId, versionNumber) {
|
||||
if (!noteId) throw new Error('noteId obrigatório.');
|
||||
if (!versionNumber) throw new Error('versionNumber obrigatório.');
|
||||
|
||||
const { data, error } = await supabase.from('clinical_note_versions').select(CLINICAL_NOTE_VERSION_SELECT).eq('note_id', noteId).eq('version_number', versionNumber).maybeSingle();
|
||||
const { data, error } = await tenantDb().from('clinical_note_versions').select(CLINICAL_NOTE_VERSION_SELECT).eq('note_id', noteId).eq('version_number', versionNumber).maybeSingle();
|
||||
|
||||
if (error) throw error;
|
||||
return data || null;
|
||||
|
||||
Reference in New Issue
Block a user