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:
@@ -16,6 +16,7 @@
|
||||
-->
|
||||
<script setup>
|
||||
import { supabase } from '@/lib/supabase/client';
|
||||
import { tenantDb } from '@/lib/supabase/tenantClient';
|
||||
import {
|
||||
listGroupsByPatient,
|
||||
listTagsByPatient,
|
||||
@@ -76,13 +77,12 @@ async function abrirSessoes(pat) {
|
||||
recorrencias.value = [];
|
||||
try {
|
||||
const [evts, recs] = await Promise.all([
|
||||
supabase
|
||||
.from('agenda_eventos')
|
||||
tenantDb().from('agenda_eventos')
|
||||
.select('id, titulo, tipo, status, inicio_em, fim_em, modalidade, insurance_guide_number, insurance_value, insurance_plans(name)')
|
||||
.eq('patient_id', pat.id)
|
||||
.order('inicio_em', { ascending: false })
|
||||
.limit(100),
|
||||
supabase.from('recurrence_rules').select('id, type, interval, weekdays, start_date, end_date, start_time, duration_min, status').eq('patient_id', pat.id).order('start_date', { ascending: false })
|
||||
tenantDb().from('recurrence_rules').select('id, type, interval, weekdays, start_date, end_date, start_time, duration_min, status').eq('patient_id', pat.id).order('start_date', { ascending: false })
|
||||
]);
|
||||
sessoesLista.value = evts.data || [];
|
||||
recorrencias.value = recs.data || [];
|
||||
@@ -487,11 +487,9 @@ function withOwnerFilter(q) {
|
||||
return uid.value ? q.eq('owner_id', uid.value) : q;
|
||||
}
|
||||
|
||||
// Defesa em profundidade: filtra por tenant_id do tenantStore em todas as queries.
|
||||
// RLS cobre no backend, mas blindamos no cliente (padrão do projeto).
|
||||
// Schema-per-tenant: isolamento via schema tenant_<slug>; tabela não tem mais coluna tenant_id.
|
||||
function withTenantFilter(q) {
|
||||
const tid = tenantStore.activeTenantId;
|
||||
return tid ? q.eq('tenant_id', tid) : q;
|
||||
return q;
|
||||
}
|
||||
|
||||
// ── Filtered rows ─────────────────────────────────────────
|
||||
@@ -547,13 +545,13 @@ async function fetchAll() {
|
||||
discountMap.value = {};
|
||||
if (uid.value) {
|
||||
const now = new Date().toISOString();
|
||||
const { data: discRows } = await supabase.from('patient_discounts').select('patient_id, discount_pct, discount_flat').eq('owner_id', uid.value).eq('active', true).or(`active_to.is.null,active_to.gte.${now}`);
|
||||
const { data: discRows } = await tenantDb().from('patient_discounts').select('patient_id, discount_pct, discount_flat').eq('owner_id', uid.value).eq('active', true).or(`active_to.is.null,active_to.gte.${now}`);
|
||||
if (discRows) discountMap.value = Object.fromEntries(discRows.map((d) => [d.patient_id, d]));
|
||||
}
|
||||
|
||||
insuranceMap.value = {};
|
||||
if (uid.value) {
|
||||
const { data: insRows } = await supabase.from('agenda_eventos').select('patient_id, insurance_plan_id, insurance_plans(name)').eq('owner_id', uid.value).not('insurance_plan_id', 'is', null).order('inicio_em', { ascending: false });
|
||||
const { data: insRows } = await tenantDb().from('agenda_eventos').select('patient_id, insurance_plan_id, insurance_plans(name)').eq('owner_id', uid.value).not('insurance_plan_id', 'is', null).order('inicio_em', { ascending: false });
|
||||
if (insRows) {
|
||||
for (const row of insRows) {
|
||||
if (!insuranceMap.value[row.patient_id]) insuranceMap.value[row.patient_id] = row.insurance_plans?.name ?? null;
|
||||
@@ -574,7 +572,7 @@ async function fetchAll() {
|
||||
}
|
||||
|
||||
async function listPatients() {
|
||||
let q = supabase.from('patients').select('id, owner_id, nome_completo, email_principal, telefone, avatar_url, status, last_attended_at, created_at, updated_at').order('created_at', { ascending: false });
|
||||
let q = tenantDb().from('patients').select('id, owner_id, nome_completo, email_principal, telefone, avatar_url, status, last_attended_at, created_at, updated_at').order('created_at', { ascending: false });
|
||||
q = withTenantFilter(withOwnerFilter(q));
|
||||
const { data, error } = await q;
|
||||
if (error) throw error;
|
||||
@@ -590,7 +588,7 @@ async function listPatients() {
|
||||
}
|
||||
|
||||
async function listGroups() {
|
||||
let q = supabase.from('patient_groups').select('id, owner_id, nome, cor, is_system, is_active').eq('is_active', true).order('nome', { ascending: true });
|
||||
let q = tenantDb().from('patient_groups').select('id, owner_id, nome, cor, is_system, is_active').eq('is_active', true).order('nome', { ascending: true });
|
||||
q = withTenantFilter(q);
|
||||
if (uid.value) q = q.or(`is_system.eq.true,owner_id.eq.${uid.value}`);
|
||||
else q = q.eq('is_system', true);
|
||||
@@ -600,7 +598,7 @@ async function listGroups() {
|
||||
}
|
||||
|
||||
async function listTags() {
|
||||
let q = supabase.from('patient_tags').select('id, owner_id, nome, cor').order('nome', { ascending: true });
|
||||
let q = tenantDb().from('patient_tags').select('id, owner_id, nome, cor').order('nome', { ascending: true });
|
||||
q = withTenantFilter(q);
|
||||
if (uid.value) q = q.eq('owner_id', uid.value);
|
||||
const { data, error } = await q;
|
||||
|
||||
@@ -64,6 +64,7 @@ import { useRoleGuard } from '@/composables/useRoleGuard'
|
||||
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 { logError } from '@/support/supportLogger'
|
||||
import { digitsOnly, fmtCPF, fmtRG, fmtPhone, toISODate, generateCPF } from '@/utils/validators'
|
||||
@@ -647,7 +648,7 @@ async function onSubmit () {
|
||||
await openPanel(0); return
|
||||
}
|
||||
const payload = sanitizePayload(form.value, ownerId)
|
||||
payload.tenant_id = tenantId; payload.responsible_member_id = memberId
|
||||
payload.responsible_member_id = memberId
|
||||
if (isEdit.value) {
|
||||
await updatePatient(patientId.value, payload)
|
||||
await maybeUploadAvatar(ownerId, patientId.value)
|
||||
@@ -706,7 +707,7 @@ async function doDelete () {
|
||||
['patients', 'id'],
|
||||
]
|
||||
for (const [tbl, col] of tables) {
|
||||
const { error } = await supabase.from(tbl).delete().eq(col, pid); if (error) throw error
|
||||
const { error } = await tenantDb().from(tbl).delete().eq(col, pid); if (error) throw error
|
||||
}
|
||||
toast.add({ severity:'success', summary:'Excluído', detail:'Paciente removido.', life:2500 })
|
||||
if (props.dialogMode) { emit('created', null); return }
|
||||
@@ -766,7 +767,7 @@ async function createGroupPersist () {
|
||||
createGroupSaving.value=true
|
||||
try {
|
||||
const ownerId=await getOwnerId(); const { tenantId }=await resolveTenantContextOrFail()
|
||||
const { data, error }=await supabase.from('patient_groups').insert({ owner_id:ownerId, tenant_id:tenantId, nome:name, cor:color, is_system:false, is_active:true }).select('id').single()
|
||||
const { data, error }=await tenantDb().from('patient_groups').insert({ owner_id:ownerId, nome:name, cor:color, is_system:false, is_active:true }).select('id').single()
|
||||
if (error) throw error
|
||||
groups.value=await listGroups(); if (data?.id) grupoIdSelecionado.value=data.id
|
||||
toast.add({ severity:'success', summary:'Grupo criado.', life:2500 }); createGroupDialog.value=false
|
||||
@@ -782,7 +783,7 @@ async function createTagPersist () {
|
||||
createTagSaving.value=true
|
||||
try {
|
||||
const ownerId=await getOwnerId(); const { tenantId }=await resolveTenantContextOrFail()
|
||||
const { data, error }=await supabase.from('patient_tags').insert({ owner_id:ownerId, tenant_id:tenantId, nome:name, cor:color }).select('id').single()
|
||||
const { data, error }=await tenantDb().from('patient_tags').insert({ owner_id:ownerId, nome:name, cor:color }).select('id').single()
|
||||
if (error) throw error
|
||||
tags.value=await listTags()
|
||||
if (data?.id) { const s=new Set([...(tagIdsSelecionadas.value||[]),data.id]); tagIdsSelecionadas.value=Array.from(s) }
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
-->
|
||||
<script setup>
|
||||
import { supabase } from '@/lib/supabase/client';
|
||||
import { tenantDb } from '@/lib/supabase/tenantClient';
|
||||
import { useTenantStore } from '@/stores/tenantStore';
|
||||
// Fase 2 (Graphify hotspot): convertToPatient duplicado em 2 pages — INSERT/UPDATE
|
||||
// extraídos pro repository pra remover duplicação.
|
||||
@@ -275,7 +276,7 @@ const intakeSections = computed(() => {
|
||||
async function fetchIntakes() {
|
||||
loading.value = true;
|
||||
try {
|
||||
const { data, error } = await supabase.from('patient_intake_requests').select('*').order('created_at', { ascending: false });
|
||||
const { data, error } = await tenantDb().from('patient_intake_requests').select('*').order('created_at', { ascending: false });
|
||||
if (error) throw error;
|
||||
const weight = (s) => (s === 'new' ? 0 : s === 'converted' ? 1 : s === 'rejected' ? 2 : 9);
|
||||
rows.value = (data || []).slice().sort((a, b) => {
|
||||
@@ -322,7 +323,7 @@ async function markRejected() {
|
||||
dlg.value.saving = true;
|
||||
try {
|
||||
const reason = String(dlg.value.reject_note || '').trim() || null;
|
||||
const { error } = await supabase.from('patient_intake_requests').update({ status: 'rejected', rejected_reason: reason, updated_at: new Date().toISOString() }).eq('id', item.id);
|
||||
const { error } = await tenantDb().from('patient_intake_requests').update({ status: 'rejected', rejected_reason: reason, updated_at: new Date().toISOString() }).eq('id', item.id);
|
||||
if (error) throw error;
|
||||
toast.add({ severity: 'success', summary: 'Rejeitado', detail: 'Solicitação rejeitada.', life: 2500 });
|
||||
await fetchIntakes();
|
||||
@@ -371,7 +372,6 @@ async function convertToPatient() {
|
||||
const intakeAvatar = cleanStr(item.avatar_url) || cleanStr(item.foto_url) || cleanStr(item.photo_url) || null;
|
||||
|
||||
const patientPayload = {
|
||||
tenant_id: tenantId,
|
||||
responsible_member_id: responsibleMemberId,
|
||||
owner_id: ownerId,
|
||||
nome_completo: cleanStr(fNome(item)),
|
||||
|
||||
@@ -21,6 +21,7 @@ import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { useRouter } from 'vue-router';
|
||||
|
||||
import { supabase } from '@/lib/supabase/client';
|
||||
import { tenantDb } from '@/lib/supabase/tenantClient';
|
||||
import Checkbox from 'primevue/checkbox';
|
||||
import Menu from 'primevue/menu';
|
||||
|
||||
@@ -201,7 +202,7 @@ function applyRealCountsToGroups(groupsArr, countMap) {
|
||||
async function fetchRealGroupCountsForOwner() {
|
||||
const ownerId = (await supabase.auth.getUser())?.data?.user?.id;
|
||||
if (!ownerId) throw new Error('Sessão inválida.');
|
||||
const { data, error } = await supabase.from('patient_group_patient').select('patient_group_id, patient:patients!inner(id, owner_id)').eq('patient.owner_id', ownerId);
|
||||
const { data, error } = await tenantDb().from('patient_group_patient').select('patient_group_id, patient:patients!inner(id, owner_id)').eq('patient.owner_id', ownerId);
|
||||
if (error) throw error;
|
||||
const map = Object.create(null);
|
||||
for (const row of data || []) {
|
||||
@@ -362,7 +363,7 @@ async function openGroupPatientsModal(groupRow) {
|
||||
patientsDialog.items = [];
|
||||
patientsDialog.search = '';
|
||||
try {
|
||||
const { data, error } = await supabase.from('patient_group_patient').select('patient_id, patient:patients(id, nome_completo, email_principal, telefone, avatar_url)').eq('patient_group_id', groupRow.id);
|
||||
const { data, error } = await tenantDb().from('patient_group_patient').select('patient_id, patient:patients(id, nome_completo, email_principal, telefone, avatar_url)').eq('patient_group_id', groupRow.id);
|
||||
if (error) throw error;
|
||||
patientsDialog.items = (data || [])
|
||||
.map((r) => r.patient)
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
| V#3 — fundação: queries de patients centralizadas.
|
||||
|
|
||||
| Pages e composables devem chamar este repo em vez de fazer
|
||||
| supabase.from('patients') direto.
|
||||
| tenantDb().from('patients') direto.
|
||||
|
|
||||
| Inclui também reads cross-feature em escopo de paciente (agenda_eventos,
|
||||
| financial_records, documents, recurrence_rules, conversation_messages,
|
||||
@@ -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 '@/features/agenda/services/_tenantGuards';
|
||||
import {
|
||||
@@ -51,7 +52,7 @@ function resolveTenantId(tenantIdArg) {
|
||||
export async function listPatients({ tenantId, ownerId = null, includeInactive = true, limit = null } = {}) {
|
||||
const tid = resolveTenantId(tenantId);
|
||||
|
||||
let q = supabase.from('patients').select(PATIENTS_SELECT_BASE).eq('tenant_id', tid);
|
||||
let q = tenantDb().from('patients').select(PATIENTS_SELECT_BASE);
|
||||
if (ownerId) q = q.eq('owner_id', ownerId);
|
||||
if (!includeInactive) q = q.neq('status', 'Inativo');
|
||||
if (limit) q = q.limit(limit);
|
||||
@@ -65,7 +66,7 @@ export async function listPatients({ tenantId, ownerId = null, includeInactive =
|
||||
export async function getPatientById(id, { tenantId } = {}) {
|
||||
if (!id) throw new Error('id obrigatório');
|
||||
const tid = resolveTenantId(tenantId);
|
||||
const { data, error } = await supabase.from('patients').select(PATIENTS_SELECT_BASE).eq('id', id).eq('tenant_id', tid).maybeSingle();
|
||||
const { data, error } = await tenantDb().from('patients').select(PATIENTS_SELECT_BASE).eq('id', id).maybeSingle();
|
||||
if (error) throw error;
|
||||
return data;
|
||||
}
|
||||
@@ -77,9 +78,9 @@ export async function createPatient(payload) {
|
||||
// criar pacientes "de outro terapeuta". Repository é defesa em profundidade.
|
||||
const ownerId = await getUid();
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
const { owner_id: _dropped, ...rest } = payload || {};
|
||||
const row = { ...rest, tenant_id: tid, owner_id: ownerId };
|
||||
const { data, error } = await supabase.from('patients').insert(row).select(PATIENTS_SELECT_BASE).single();
|
||||
const { owner_id: _dropped, tenant_id: _tenantDropped, ...rest } = payload || {};
|
||||
const row = { ...rest, owner_id: ownerId };
|
||||
const { data, error } = await tenantDb().from('patients').insert(row).select(PATIENTS_SELECT_BASE).single();
|
||||
if (error) throw error;
|
||||
return data;
|
||||
}
|
||||
@@ -87,7 +88,7 @@ export async function createPatient(payload) {
|
||||
export async function updatePatient(id, patch, { tenantId } = {}) {
|
||||
if (!id) throw new Error('id obrigatório');
|
||||
const tid = resolveTenantId(tenantId);
|
||||
const { data, error } = await supabase.from('patients').update(patch).eq('id', id).eq('tenant_id', tid).select(PATIENTS_SELECT_BASE).single();
|
||||
const { data, error } = await tenantDb().from('patients').update(patch).eq('id', id).select(PATIENTS_SELECT_BASE).single();
|
||||
if (error) throw error;
|
||||
return data;
|
||||
}
|
||||
@@ -95,7 +96,7 @@ export async function updatePatient(id, patch, { tenantId } = {}) {
|
||||
export async function softDeletePatient(id, { tenantId } = {}) {
|
||||
if (!id) throw new Error('id obrigatório');
|
||||
const tid = resolveTenantId(tenantId);
|
||||
const { error } = await supabase.from('patients').update({ status: 'Arquivado' }).eq('id', id).eq('tenant_id', tid);
|
||||
const { error } = await tenantDb().from('patients').update({ status: 'Arquivado' }).eq('id', id);
|
||||
if (error) throw error;
|
||||
}
|
||||
|
||||
@@ -111,8 +112,8 @@ export async function softDeletePatient(id, { tenantId } = {}) {
|
||||
export async function getPatientRelations(patientId) {
|
||||
if (!patientId) return { groupIds: [], tagIds: [] };
|
||||
const [{ data: g, error: ge }, { data: t, error: te }] = await Promise.all([
|
||||
supabase.from('patient_group_patient').select('patient_group_id').eq('patient_id', patientId),
|
||||
supabase.from('patient_patient_tag').select('tag_id').eq('patient_id', patientId)
|
||||
tenantDb().from('patient_group_patient').select('patient_group_id').eq('patient_id', patientId),
|
||||
tenantDb().from('patient_patient_tag').select('tag_id').eq('patient_id', patientId)
|
||||
]);
|
||||
if (ge) throw ge;
|
||||
if (te) throw te;
|
||||
@@ -126,7 +127,7 @@ export async function getPatientRelations(patientId) {
|
||||
|
||||
export async function listGroups({ tenantId, ownerId = null } = {}) {
|
||||
const tid = resolveTenantId(tenantId);
|
||||
let q = supabase.from('patient_groups').select(PATIENT_GROUPS_SELECT).eq('tenant_id', tid).eq('is_active', true);
|
||||
let q = tenantDb().from('patient_groups').select(PATIENT_GROUPS_SELECT).eq('is_active', true);
|
||||
if (ownerId) q = q.or(`is_system.eq.true,owner_id.eq.${ownerId}`);
|
||||
q = q.order('nome', { ascending: true });
|
||||
const { data, error } = await q;
|
||||
@@ -137,7 +138,7 @@ export async function listGroups({ tenantId, ownerId = null } = {}) {
|
||||
export async function listGroupsByPatient(patientIds, { tenantId } = {}) {
|
||||
if (!patientIds?.length) return [];
|
||||
const tid = resolveTenantId(tenantId);
|
||||
const { data, error } = await supabase.from('patient_group_patient').select('patient_id, patient_group_id').eq('tenant_id', tid).in('patient_id', patientIds);
|
||||
const { data, error } = await tenantDb().from('patient_group_patient').select('patient_id, patient_group_id').in('patient_id', patientIds);
|
||||
if (error) throw error;
|
||||
return data || [];
|
||||
}
|
||||
@@ -147,7 +148,7 @@ export async function listGroupsByPatient(patientIds, { tenantId } = {}) {
|
||||
*/
|
||||
export async function getGroupsByIds(ids) {
|
||||
if (!ids?.length) return [];
|
||||
const { data, error } = await supabase.from('patient_groups').select(PATIENT_GROUPS_SELECT_BRIEF).in('id', ids).order('nome', { ascending: true });
|
||||
const { data, error } = await tenantDb().from('patient_groups').select(PATIENT_GROUPS_SELECT_BRIEF).in('id', ids).order('nome', { ascending: true });
|
||||
if (error) throw error;
|
||||
return (data || []).map((g) => ({ id: g.id, name: g.nome }));
|
||||
}
|
||||
@@ -158,10 +159,10 @@ export async function getGroupsByIds(ids) {
|
||||
export async function replacePatientGroup(patientId, groupId, { tenantId } = {}) {
|
||||
if (!patientId) throw new Error('patientId obrigatório');
|
||||
const tid = resolveTenantId(tenantId);
|
||||
const { error: del } = await supabase.from('patient_group_patient').delete().eq('patient_id', patientId).eq('tenant_id', tid);
|
||||
const { error: del } = await tenantDb().from('patient_group_patient').delete().eq('patient_id', patientId);
|
||||
if (del) throw del;
|
||||
if (!groupId) return;
|
||||
const { error: ins } = await supabase.from('patient_group_patient').insert({ patient_id: patientId, patient_group_id: groupId, tenant_id: tid });
|
||||
const { error: ins } = await tenantDb().from('patient_group_patient').insert({ patient_id: patientId, patient_group_id: groupId });
|
||||
if (ins) throw ins;
|
||||
}
|
||||
|
||||
@@ -169,7 +170,7 @@ export async function replacePatientGroup(patientId, groupId, { tenantId } = {})
|
||||
|
||||
export async function listTags({ tenantId, ownerId = null } = {}) {
|
||||
const tid = resolveTenantId(tenantId);
|
||||
let q = supabase.from('patient_tags').select(PATIENT_TAGS_SELECT).eq('tenant_id', tid);
|
||||
let q = tenantDb().from('patient_tags').select(PATIENT_TAGS_SELECT);
|
||||
if (ownerId) q = q.eq('owner_id', ownerId);
|
||||
const { data, error } = await q;
|
||||
if (error) throw error;
|
||||
@@ -179,7 +180,7 @@ export async function listTags({ tenantId, ownerId = null } = {}) {
|
||||
export async function listTagsByPatient(patientIds, { tenantId } = {}) {
|
||||
if (!patientIds?.length) return [];
|
||||
const tid = resolveTenantId(tenantId);
|
||||
const { data, error } = await supabase.from('patient_patient_tag').select('patient_id, tag_id').eq('tenant_id', tid).in('patient_id', patientIds);
|
||||
const { data, error } = await tenantDb().from('patient_patient_tag').select('patient_id, tag_id').in('patient_id', patientIds);
|
||||
if (error) throw error;
|
||||
return data || [];
|
||||
}
|
||||
@@ -189,7 +190,7 @@ export async function listTagsByPatient(patientIds, { tenantId } = {}) {
|
||||
*/
|
||||
export async function getTagsByIds(ids) {
|
||||
if (!ids?.length) return [];
|
||||
const { data, error } = await supabase.from('patient_tags').select(PATIENT_TAGS_SELECT_BRIEF).in('id', ids).order('nome', { ascending: true });
|
||||
const { data, error } = await tenantDb().from('patient_tags').select(PATIENT_TAGS_SELECT_BRIEF).in('id', ids).order('nome', { ascending: true });
|
||||
if (error) throw error;
|
||||
return (data || []).map((t) => ({ id: t.id, name: t.nome, color: t.cor }));
|
||||
}
|
||||
@@ -202,12 +203,12 @@ export async function replacePatientTags(patientId, tagIds, { tenantId, ownerId
|
||||
if (!ownerId) throw new Error('ownerId obrigatório');
|
||||
const tid = resolveTenantId(tenantId);
|
||||
|
||||
const { error: del } = await supabase.from('patient_patient_tag').delete().eq('patient_id', patientId).eq('owner_id', ownerId).eq('tenant_id', tid);
|
||||
const { error: del } = await tenantDb().from('patient_patient_tag').delete().eq('patient_id', patientId).eq('owner_id', ownerId);
|
||||
if (del) throw del;
|
||||
|
||||
const clean = Array.from(new Set((tagIds || []).filter(Boolean)));
|
||||
if (!clean.length) return;
|
||||
const { error: ins } = await supabase.from('patient_patient_tag').insert(clean.map((tag_id) => ({ owner_id: ownerId, patient_id: patientId, tag_id, tenant_id: tid })));
|
||||
const { error: ins } = await tenantDb().from('patient_patient_tag').insert(clean.map((tag_id) => ({ owner_id: ownerId, patient_id: patientId, tag_id })));
|
||||
if (ins) throw ins;
|
||||
}
|
||||
|
||||
@@ -224,10 +225,9 @@ export async function replacePatientTags(patientId, tagIds, { tenantId, ownerId
|
||||
export async function listSessionsByPatient(patientId, { tenantId } = {}) {
|
||||
if (!patientId) return [];
|
||||
const tid = resolveTenantId(tenantId);
|
||||
const { data, error } = await supabase
|
||||
.from('agenda_eventos')
|
||||
const { data, error } = await tenantDb().from('agenda_eventos')
|
||||
.select(PATIENT_SESSIONS_SELECT)
|
||||
.eq('tenant_id', tid)
|
||||
|
||||
.eq('patient_id', patientId)
|
||||
.order('inicio_em', { ascending: false })
|
||||
.limit(100);
|
||||
@@ -251,7 +251,6 @@ export async function createPatientSession(patientId, payload) {
|
||||
const row = {
|
||||
patient_id: patientId,
|
||||
owner_id: uid,
|
||||
tenant_id: tid,
|
||||
inicio_em: payload.inicio_em,
|
||||
fim_em: payload.fim_em,
|
||||
status: payload.status || 'agendado',
|
||||
@@ -266,7 +265,7 @@ export async function createPatientSession(patientId, payload) {
|
||||
price: payload.price ?? null
|
||||
};
|
||||
|
||||
const { data, error } = await supabase.from('agenda_eventos').insert([row]).select().single();
|
||||
const { data, error } = await tenantDb().from('agenda_eventos').insert([row]).select().single();
|
||||
if (error) throw error;
|
||||
return data;
|
||||
}
|
||||
@@ -277,7 +276,7 @@ export async function createPatientSession(patientId, payload) {
|
||||
export async function updatePatientSessionStatus(sessionId, status, { tenantId } = {}) {
|
||||
if (!sessionId) throw new Error('sessionId obrigatório');
|
||||
const tid = resolveTenantId(tenantId);
|
||||
const { error } = await supabase.from('agenda_eventos').update({ status }).eq('id', sessionId).eq('tenant_id', tid);
|
||||
const { error } = await tenantDb().from('agenda_eventos').update({ status }).eq('id', sessionId);
|
||||
if (error) throw error;
|
||||
}
|
||||
|
||||
@@ -287,7 +286,7 @@ export async function updatePatientSessionStatus(sessionId, status, { tenantId }
|
||||
*/
|
||||
export async function findSessionByRecurrence(recurrenceId, recurrenceDate) {
|
||||
if (!recurrenceId || !recurrenceDate) return null;
|
||||
const { data, error } = await supabase.from('agenda_eventos').select('id').eq('recurrence_id', recurrenceId).eq('recurrence_date', recurrenceDate).maybeSingle();
|
||||
const { data, error } = await tenantDb().from('agenda_eventos').select('id').eq('recurrence_id', recurrenceId).eq('recurrence_date', recurrenceDate).maybeSingle();
|
||||
if (error) throw error;
|
||||
return data || null;
|
||||
}
|
||||
@@ -303,10 +302,9 @@ export async function findSessionByRecurrence(recurrenceId, recurrenceDate) {
|
||||
export async function listFinancialRecordsByPatient(patientId, { tenantId } = {}) {
|
||||
if (!patientId) return [];
|
||||
const tid = resolveTenantId(tenantId);
|
||||
const { data, error } = await supabase
|
||||
.from('financial_records')
|
||||
const { data, error } = await tenantDb().from('financial_records')
|
||||
.select(PATIENT_FINANCIAL_RECORDS_SELECT)
|
||||
.eq('tenant_id', tid)
|
||||
|
||||
.eq('patient_id', patientId)
|
||||
.eq('type', 'receita')
|
||||
.order('created_at', { ascending: false })
|
||||
@@ -329,7 +327,6 @@ export async function createFinancialRecord(patientId, payload) {
|
||||
const row = {
|
||||
patient_id: patientId,
|
||||
owner_id: uid,
|
||||
tenant_id: tid,
|
||||
type: 'receita',
|
||||
amount: Number(payload.amount),
|
||||
due_date: payload.due_date || null,
|
||||
@@ -338,7 +335,7 @@ export async function createFinancialRecord(patientId, payload) {
|
||||
paid_at: null
|
||||
};
|
||||
|
||||
const { data, error } = await supabase.from('financial_records').insert([row]).select().single();
|
||||
const { data, error } = await tenantDb().from('financial_records').insert([row]).select().single();
|
||||
if (error) throw error;
|
||||
return data;
|
||||
}
|
||||
@@ -349,7 +346,7 @@ export async function createFinancialRecord(patientId, payload) {
|
||||
export async function markFinancialRecordPaid(recordId, { tenantId } = {}) {
|
||||
if (!recordId) throw new Error('recordId obrigatório');
|
||||
const tid = resolveTenantId(tenantId);
|
||||
const { error } = await supabase.from('financial_records').update({ paid_at: new Date().toISOString() }).eq('id', recordId).eq('tenant_id', tid);
|
||||
const { error } = await tenantDb().from('financial_records').update({ paid_at: new Date().toISOString() }).eq('id', recordId);
|
||||
if (error) throw error;
|
||||
}
|
||||
|
||||
@@ -359,7 +356,7 @@ export async function markFinancialRecordPaid(recordId, { tenantId } = {}) {
|
||||
export async function markFinancialRecordUnpaid(recordId, { tenantId } = {}) {
|
||||
if (!recordId) throw new Error('recordId obrigatório');
|
||||
const tid = resolveTenantId(tenantId);
|
||||
const { error } = await supabase.from('financial_records').update({ paid_at: null }).eq('id', recordId).eq('tenant_id', tid);
|
||||
const { error } = await tenantDb().from('financial_records').update({ paid_at: null }).eq('id', recordId);
|
||||
if (error) throw error;
|
||||
}
|
||||
|
||||
@@ -370,10 +367,9 @@ export async function markFinancialRecordUnpaid(recordId, { tenantId } = {}) {
|
||||
export async function listDocumentsByPatient(patientId, { tenantId } = {}) {
|
||||
if (!patientId) return [];
|
||||
const tid = resolveTenantId(tenantId);
|
||||
const { data, error } = await supabase
|
||||
.from('documents')
|
||||
const { data, error } = await tenantDb().from('documents')
|
||||
.select(PATIENT_DOCUMENTS_SELECT)
|
||||
.eq('tenant_id', tid)
|
||||
|
||||
.eq('patient_id', patientId)
|
||||
.is('deleted_at', null)
|
||||
.order('created_at', { ascending: false })
|
||||
@@ -390,10 +386,9 @@ export async function listDocumentsByPatient(patientId, { tenantId } = {}) {
|
||||
export async function listMessagesByPatient(patientId, { tenantId } = {}) {
|
||||
if (!patientId) return [];
|
||||
const tid = resolveTenantId(tenantId);
|
||||
const { data, error } = await supabase
|
||||
.from('conversation_messages')
|
||||
const { data, error } = await tenantDb().from('conversation_messages')
|
||||
.select(PATIENT_MESSAGES_SELECT)
|
||||
.eq('tenant_id', tid)
|
||||
|
||||
.eq('patient_id', patientId)
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(200);
|
||||
@@ -409,10 +404,9 @@ export async function listMessagesByPatient(patientId, { tenantId } = {}) {
|
||||
export async function listRecurrencesByPatient(patientId, { tenantId } = {}) {
|
||||
if (!patientId) return [];
|
||||
const tid = resolveTenantId(tenantId);
|
||||
const { data, error } = await supabase
|
||||
.from('recurrence_rules')
|
||||
const { data, error } = await tenantDb().from('recurrence_rules')
|
||||
.select(PATIENT_RECURRENCE_RULES_SELECT)
|
||||
.eq('tenant_id', tid)
|
||||
|
||||
.eq('patient_id', patientId)
|
||||
.order('start_date', { ascending: false });
|
||||
if (error) throw error;
|
||||
@@ -425,7 +419,7 @@ export async function listRecurrencesByPatient(patientId, { tenantId } = {}) {
|
||||
export async function updateRecurrenceStatus(ruleId, status, { tenantId } = {}) {
|
||||
if (!ruleId) throw new Error('ruleId obrigatório');
|
||||
const tid = resolveTenantId(tenantId);
|
||||
const { error } = await supabase.from('recurrence_rules').update({ status, updated_at: new Date().toISOString() }).eq('id', ruleId).eq('tenant_id', tid);
|
||||
const { error } = await tenantDb().from('recurrence_rules').update({ status, updated_at: new Date().toISOString() }).eq('id', ruleId);
|
||||
if (error) throw error;
|
||||
}
|
||||
|
||||
@@ -436,7 +430,7 @@ export async function updateRecurrenceStatus(ruleId, status, { tenantId } = {})
|
||||
export async function listSupportContactsByPatient(patientId, { tenantId } = {}) {
|
||||
if (!patientId) return [];
|
||||
const tid = resolveTenantId(tenantId);
|
||||
const { data, error } = await supabase.from('patient_support_contacts').select(PATIENT_SUPPORT_CONTACTS_SELECT).eq('tenant_id', tid).eq('patient_id', patientId).order('is_primario', { ascending: false });
|
||||
const { data, error } = await tenantDb().from('patient_support_contacts').select(PATIENT_SUPPORT_CONTACTS_SELECT).eq('patient_id', patientId).order('is_primario', { ascending: false });
|
||||
if (error) throw error;
|
||||
return data || [];
|
||||
}
|
||||
@@ -452,7 +446,7 @@ export async function replacePatientSupportContacts(patientId, contacts, { tenan
|
||||
if (!ownerId) throw new Error('ownerId obrigatório');
|
||||
const tid = resolveTenantId(tenantId);
|
||||
|
||||
const { error: del } = await supabase.from('patient_support_contacts').delete().eq('patient_id', patientId).eq('owner_id', ownerId).eq('tenant_id', tid);
|
||||
const { error: del } = await tenantDb().from('patient_support_contacts').delete().eq('patient_id', patientId).eq('owner_id', ownerId);
|
||||
if (del) throw del;
|
||||
|
||||
if (!contacts?.length) return;
|
||||
@@ -460,11 +454,10 @@ export async function replacePatientSupportContacts(patientId, contacts, { tenan
|
||||
const rows = contacts.map((c) => ({
|
||||
...c,
|
||||
patient_id: patientId,
|
||||
owner_id: ownerId,
|
||||
tenant_id: tid
|
||||
owner_id: ownerId
|
||||
}));
|
||||
|
||||
const { error: ins } = await supabase.from('patient_support_contacts').insert(rows);
|
||||
const { error: ins } = await tenantDb().from('patient_support_contacts').insert(rows);
|
||||
if (ins) throw ins;
|
||||
}
|
||||
|
||||
@@ -490,8 +483,7 @@ export async function markIntakeConverted(intakeId, patientId, { tenantId } = {}
|
||||
|
||||
// tenant_id no patient_intake_requests pode ser nullable (intake público sem tenant)
|
||||
// — só filtramos se passado explícito.
|
||||
let q = supabase
|
||||
.from('patient_intake_requests')
|
||||
let q = tenantDb().from('patient_intake_requests')
|
||||
.update({
|
||||
status: 'converted',
|
||||
converted_patient_id: patientId,
|
||||
@@ -499,11 +491,6 @@ export async function markIntakeConverted(intakeId, patientId, { tenantId } = {}
|
||||
})
|
||||
.eq('id', intakeId);
|
||||
|
||||
if (tenantId) {
|
||||
const tid = resolveTenantId(tenantId);
|
||||
q = q.eq('tenant_id', tid);
|
||||
}
|
||||
|
||||
const { error } = await q;
|
||||
if (error) throw error;
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ import { useRouter } from 'vue-router';
|
||||
|
||||
import PatientCadastroDialog from '@/components/ui/PatientCadastroDialog.vue';
|
||||
import { supabase } from '@/lib/supabase/client';
|
||||
import { tenantDb } from '@/lib/supabase/tenantClient';
|
||||
import { logError } from '@/support/supportLogger';
|
||||
|
||||
const router = useRouter();
|
||||
@@ -204,7 +205,7 @@ async function buscarEtiquetas() {
|
||||
const ownerId = await getOwnerId();
|
||||
|
||||
// 1) tenta view com contagem
|
||||
const v = await supabase.from('v_tag_patient_counts').select('*').eq('owner_id', ownerId).order('nome', { ascending: true });
|
||||
const v = await tenantDb().from('v_tag_patient_counts').select('*').eq('owner_id', ownerId).order('nome', { ascending: true });
|
||||
|
||||
if (!v.error) {
|
||||
etiquetas.value = (v.data || []).map(normalizarEtiquetaRow);
|
||||
@@ -212,10 +213,10 @@ async function buscarEtiquetas() {
|
||||
}
|
||||
|
||||
// 2) fallback tabela direta
|
||||
const t = await supabase.from('patient_tags').select('id, owner_id, nome, cor, is_padrao, name, color, is_native, created_at, updated_at').eq('owner_id', ownerId).order('nome', { ascending: true });
|
||||
const t = await tenantDb().from('patient_tags').select('id, owner_id, nome, cor, is_padrao, name, color, is_native, created_at, updated_at').eq('owner_id', ownerId).order('nome', { ascending: true });
|
||||
|
||||
if (t.error && /column .*nome/i.test(String(t.error.message || ''))) {
|
||||
const t2 = await supabase.from('patient_tags').select('id, owner_id, name, color, is_native, created_at, updated_at').eq('owner_id', ownerId).order('name', { ascending: true });
|
||||
const t2 = await tenantDb().from('patient_tags').select('id, owner_id, name, color, is_native, created_at, updated_at').eq('owner_id', ownerId).order('name', { ascending: true });
|
||||
if (t2.error) throw t2.error;
|
||||
etiquetas.value = (t2.data || []).map((r) => normalizarEtiquetaRow({ ...r, patient_count: 0 }));
|
||||
return;
|
||||
@@ -262,14 +263,14 @@ async function salvarDlg() {
|
||||
|
||||
if (dlg.mode === 'create') {
|
||||
const tenantId = await getActiveTenantId(ownerId);
|
||||
const res = await supabase.from('patient_tags').insert({ owner_id: ownerId, tenant_id: tenantId, nome, cor });
|
||||
const res = await tenantDb().from('patient_tags').insert({ owner_id: ownerId, nome, cor });
|
||||
if (res.error) throw res.error;
|
||||
toast.add({ severity: 'success', summary: 'Tag criada', detail: nome, life: 2500 });
|
||||
} else {
|
||||
let res = await supabase.from('patient_tags').update({ nome, cor, updated_at: new Date().toISOString() }).eq('id', dlg.id).eq('owner_id', ownerId);
|
||||
let res = await tenantDb().from('patient_tags').update({ nome, cor, updated_at: new Date().toISOString() }).eq('id', dlg.id).eq('owner_id', ownerId);
|
||||
// fallback legado
|
||||
if (res.error && /column .*nome/i.test(String(res.error.message || ''))) {
|
||||
res = await supabase.from('patient_tags').update({ name: nome, color: cor, updated_at: new Date().toISOString() }).eq('id', dlg.id).eq('owner_id', ownerId);
|
||||
res = await tenantDb().from('patient_tags').update({ name: nome, color: cor, updated_at: new Date().toISOString() }).eq('id', dlg.id).eq('owner_id', ownerId);
|
||||
}
|
||||
if (res.error) throw res.error;
|
||||
toast.add({ severity: 'success', summary: 'Tag atualizada', detail: nome, life: 2500 });
|
||||
@@ -326,9 +327,9 @@ async function excluirTags(rows) {
|
||||
toast.add({ severity: 'warn', summary: 'Nada para excluir', detail: 'Tags padrão não podem ser removidas.', life: 4000 });
|
||||
return;
|
||||
}
|
||||
const pivotDel = await supabase.from('patient_patient_tag').delete().eq('owner_id', ownerId).in('tag_id', ids);
|
||||
const pivotDel = await tenantDb().from('patient_patient_tag').delete().eq('owner_id', ownerId).in('tag_id', ids);
|
||||
if (pivotDel.error) throw pivotDel.error;
|
||||
const tagDel = await supabase.from('patient_tags').delete().eq('owner_id', ownerId).in('id', ids);
|
||||
const tagDel = await tenantDb().from('patient_tags').delete().eq('owner_id', ownerId).in('id', ids);
|
||||
if (tagDel.error) throw tagDel.error;
|
||||
etiquetasSelecionadas.value = [];
|
||||
toast.add({ severity: 'success', summary: 'Excluído', detail: `${ids.length} tag(s) removida(s).`, life: 3000 });
|
||||
@@ -359,7 +360,7 @@ async function carregarPacientesDaTag(tag) {
|
||||
modalPacientes.error = '';
|
||||
try {
|
||||
const ownerId = await getOwnerId();
|
||||
const { data, error } = await supabase.from('patient_patient_tag').select('patient_id, patients:patients(id, nome_completo, email_principal, telefone, avatar_url)').eq('owner_id', ownerId).eq('tag_id', tag.id);
|
||||
const { data, error } = await tenantDb().from('patient_patient_tag').select('patient_id, patients:patients(id, nome_completo, email_principal, telefone, avatar_url)').eq('owner_id', ownerId).eq('tag_id', tag.id);
|
||||
if (error) throw error;
|
||||
modalPacientes.items = (data || [])
|
||||
.map((r) => r.patients)
|
||||
|
||||
Reference in New Issue
Block a user