Sessoes 1-6 acumuladas: hardening B2, defesa em camadas, +192 testes
Repositorio estava ha ~5 sessoes sem commit. Consolida tudo desde d088a89.
Ver commit.md na raiz para descricao completa por sessao.
# Numeros
- A# auditoria abertos: 0/30
- V# verificacoes abertos: 5/52 (todos adiados com plano)
- T# testes escritos: 10/10
- Vitest: 192/192
- SQL integration: 33/33
- E2E (Playwright, novo): 5/5
- Migrations: 17 (10 novas Sessao 6)
- Areas auditadas: 7 (+documentos com 10 V#)
# Highlights Sessao 6 (hoje)
- V#34/V#41 Opcao B2: tenant_features com plano + override (RPC SECURITY DEFINER, tela /saas/tenant-features)
- A#20 rev2 self-hosted: defesa em 5 camadas (honeypot + rate limit + math captcha condicional + paranoid mode + dashboard /saas/security)
- Documentos hardening (V#43-V#49): tenant scoping em storage policies (vazamento entre clinicas eliminado), RPC validate_share_token, signatures policy granular
- SaaS Twilio Config (/saas/twilio-config): UI editavel para SID/webhook/cotacao; AUTH_TOKEN permanece em env var
- T#9 + T#10: useAgendaEvents.spec.js + Playwright E2E (descobriu bug no front que foi corrigido)
# Sessoes anteriores (1-5) consolidadas
- Sessao 1: auth/router/session, normalizeRole extraido
- Sessao 2: agenda - composables/services consolidados
- Sessao 3: pacientes - tenant_id em todas queries
- Sessao 4: security review pagina publica - 14/15 vulnerabilidades corrigidas
- Sessao 5: SaaS - P0 (A#30: 7 tabelas com RLS off corrigidas)
# .gitignore ajustado
- supabase/* + !supabase/functions/ (mantem 10 edge functions, ignora .temp/migrations gerados pelo CLI)
- database-novo/backups/ (regeneravel via db.cjs backup)
- test-results/ + playwright-report/
- .claude/settings.local.json (config local com senha de dev removida do tracking)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -81,12 +81,12 @@ describe('mapAgendaEventosToCalendarEvents', () => {
|
||||
|
||||
it('aplica cor de fundo para status faltou', () => {
|
||||
const [ev] = mapAgendaEventosToCalendarEvents([evento({ status: 'faltou' })]);
|
||||
expect(ev.backgroundColor).toBe('#ef4444');
|
||||
expect(ev.backgroundColor).toBe('#f97316');
|
||||
});
|
||||
|
||||
it('aplica cor de fundo para status cancelado', () => {
|
||||
const [ev] = mapAgendaEventosToCalendarEvents([evento({ status: 'cancelado' })]);
|
||||
expect(ev.backgroundColor).toBe('#f97316');
|
||||
expect(ev.backgroundColor).toBe('#ef4444');
|
||||
});
|
||||
|
||||
it('aplica cor de fundo para status remarcado', () => {
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Agência PSI
|
||||
|--------------------------------------------------------------------------
|
||||
| Arquivo: src/features/agenda/services/_tenantGuards.js
|
||||
|
|
||||
| Guards compartilhados entre composables e repositories do feature agenda.
|
||||
| Antes: assertTenantId e getUid duplicados em 3+ arquivos.
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
import { supabase } from '@/lib/supabase/client';
|
||||
|
||||
export function assertTenantId(tenantId) {
|
||||
if (!tenantId || tenantId === 'null' || tenantId === 'undefined') {
|
||||
throw new Error('Tenant ativo inválido. Selecione a clínica/tenant antes de operar na agenda.');
|
||||
}
|
||||
}
|
||||
|
||||
export async function getUid() {
|
||||
const { data, error } = await supabase.auth.getUser();
|
||||
if (error) throw error;
|
||||
const uid = data?.user?.id;
|
||||
if (!uid) throw new Error('Usuário não autenticado.');
|
||||
return uid;
|
||||
}
|
||||
|
||||
export function assertIsoRange(startISO, endISO) {
|
||||
if (!startISO || !endISO) throw new Error('Intervalo inválido (startISO/endISO).');
|
||||
}
|
||||
|
||||
export function sanitizeOwnerIds(ownerIds) {
|
||||
return (ownerIds || []).filter((id) => typeof id === 'string' && id && id !== 'null' && id !== 'undefined');
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Agência PSI
|
||||
|--------------------------------------------------------------------------
|
||||
| Criado e desenvolvido por Leonardo Nohama
|
||||
|
|
||||
| Tecnologia aplicada à escuta.
|
||||
| Estrutura para o cuidado.
|
||||
|
|
||||
| Arquivo: src/features/agenda/services/agenda.service.js
|
||||
| Data: 2026
|
||||
| Local: São Carlos/SP — Brasil
|
||||
|--------------------------------------------------------------------------
|
||||
| © 2026 — Todos os direitos reservados
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
@@ -15,20 +15,12 @@
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
import { supabase } from '@/lib/supabase/client';
|
||||
|
||||
function assertValidTenantId(tenantId) {
|
||||
if (!tenantId || tenantId === 'null' || tenantId === 'undefined') {
|
||||
throw new Error('Tenant ativo inválido. Selecione a clínica/tenant antes de carregar a agenda.');
|
||||
}
|
||||
}
|
||||
|
||||
function assertValidIsoRange(startISO, endISO) {
|
||||
if (!startISO || !endISO) throw new Error('Intervalo inválido (startISO/endISO).');
|
||||
}
|
||||
|
||||
function sanitizeOwnerIds(ownerIds) {
|
||||
return (ownerIds || []).filter((id) => typeof id === 'string' && id && id !== 'null' && id !== 'undefined');
|
||||
}
|
||||
import {
|
||||
assertTenantId as assertValidTenantId,
|
||||
assertIsoRange as assertValidIsoRange,
|
||||
sanitizeOwnerIds
|
||||
} from './_tenantGuards';
|
||||
import { AGENDA_EVENT_SELECT, flattenAgendaRow } from './agendaSelects';
|
||||
|
||||
/**
|
||||
* Lista eventos para mosaico da clínica (admin/secretaria) dentro de um tenant específico.
|
||||
@@ -44,7 +36,7 @@ export async function listClinicEvents({ tenantId, ownerIds, startISO, endISO }
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('agenda_eventos')
|
||||
.select('*, patients!agenda_eventos_patient_id_fkey(id, nome_completo, avatar_url, status), determined_commitments!agenda_eventos_determined_commitment_fk(id, bg_color, text_color)')
|
||||
.select(AGENDA_EVENT_SELECT)
|
||||
.eq('tenant_id', tenantId)
|
||||
.in('owner_id', safeOwnerIds)
|
||||
.gte('inicio_em', startISO)
|
||||
@@ -52,7 +44,7 @@ export async function listClinicEvents({ tenantId, ownerIds, startISO, endISO }
|
||||
.order('inicio_em', { ascending: true });
|
||||
|
||||
if (error) throw error;
|
||||
return data || [];
|
||||
return (data || []).map(flattenAgendaRow);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -91,10 +83,14 @@ export async function createClinicAgendaEvento(payload, { tenantId } = {}) {
|
||||
tenant_id: tenantId
|
||||
};
|
||||
|
||||
const { data, error } = await supabase.from('agenda_eventos').insert(insertPayload).select('*').single();
|
||||
const { data, error } = await supabase
|
||||
.from('agenda_eventos')
|
||||
.insert(insertPayload)
|
||||
.select(AGENDA_EVENT_SELECT)
|
||||
.single();
|
||||
|
||||
if (error) throw error;
|
||||
return data;
|
||||
return flattenAgendaRow(data);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -107,10 +103,16 @@ export async function updateClinicAgendaEvento(id, patch, { tenantId } = {}) {
|
||||
if (!patch) throw new Error('Patch vazio.');
|
||||
assertValidTenantId(tenantId);
|
||||
|
||||
const { data, error } = await supabase.from('agenda_eventos').update(patch).eq('id', id).eq('tenant_id', tenantId).select('*').single();
|
||||
const { data, error } = await supabase
|
||||
.from('agenda_eventos')
|
||||
.update(patch)
|
||||
.eq('id', id)
|
||||
.eq('tenant_id', tenantId)
|
||||
.select(AGENDA_EVENT_SELECT)
|
||||
.single();
|
||||
|
||||
if (error) throw error;
|
||||
return data;
|
||||
return flattenAgendaRow(data);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -243,7 +243,7 @@ function _statusBgColor(status) {
|
||||
realizado: '#22c55e', // verde
|
||||
faltou: '#f97316', // laranja
|
||||
cancelado: '#ef4444', // vermelho
|
||||
remarcar: '#a855f7', // roxo
|
||||
remarcado: '#a855f7', // roxo
|
||||
bloqueado: '#6b7280' // cinza
|
||||
};
|
||||
return map[status] ?? null;
|
||||
@@ -253,7 +253,7 @@ function _statusIcon(status, isOccurrence, hasSerie) {
|
||||
if (status === 'realizado') return '✓ ';
|
||||
if (status === 'faltou') return '✗ ';
|
||||
if (status === 'cancelado') return '∅ ';
|
||||
if (status === 'remarcar') return '↺ ';
|
||||
if (status === 'remarcado') return '↺ ';
|
||||
if (status === 'bloqueado') return '⊘ ';
|
||||
if (hasSerie || isOccurrence) return '↻ ';
|
||||
return '';
|
||||
|
||||
@@ -16,206 +16,140 @@
|
||||
*/
|
||||
import { supabase } from '@/lib/supabase/client';
|
||||
import { useTenantStore } from '@/stores/tenantStore';
|
||||
import { assertTenantId as assertValidTenantId, assertIsoRange, getUid } from './_tenantGuards';
|
||||
import { AGENDA_EVENT_SELECT, flattenAgendaRow } from './agendaSelects';
|
||||
|
||||
function assertValidTenantId(tenantId) {
|
||||
if (!tenantId || tenantId === 'null' || tenantId === 'undefined') {
|
||||
throw new Error('Tenant ativo inválido. Selecione a clínica/tenant antes de carregar a agenda.');
|
||||
}
|
||||
}
|
||||
// ─── Configurações & jornada ────────────────────────────────────────────────
|
||||
|
||||
async function getUid() {
|
||||
const { data: userRes, error: userErr } = await supabase.auth.getUser();
|
||||
if (userErr) throw userErr;
|
||||
|
||||
const uid = userRes?.user?.id;
|
||||
if (!uid) throw new Error('Usuário não autenticado.');
|
||||
return uid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configurações da agenda (por owner)
|
||||
* Se você decidir que configurações são por tenant também, adicionamos tenant_id aqui.
|
||||
*/
|
||||
export async function getMyAgendaSettings() {
|
||||
const uid = await getUid();
|
||||
|
||||
const { data, error } = await supabase.from('agenda_configuracoes').select('*').eq('owner_id', uid).order('created_at', { ascending: false }).limit(1).maybeSingle();
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('agenda_configuracoes')
|
||||
.select('*')
|
||||
.eq('owner_id', uid)
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(1)
|
||||
.maybeSingle();
|
||||
if (error) throw error;
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Regras semanais de jornada (agenda_regras_semanais):
|
||||
* retorna os dias ativos com hora_inicio/hora_fim por dia.
|
||||
*/
|
||||
export async function getMyWorkSchedule() {
|
||||
const uid = await getUid();
|
||||
|
||||
const { data, error } = await supabase.from('agenda_regras_semanais').select('dia_semana, hora_inicio, hora_fim, ativo').eq('owner_id', uid).eq('ativo', true).order('dia_semana');
|
||||
|
||||
if (error) throw error;
|
||||
return data || [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Lista agenda do terapeuta (somente do owner logado) dentro do tenant ativo.
|
||||
* Isso impede misturar eventos caso o terapeuta atue em múltiplas clínicas.
|
||||
*/
|
||||
export async function listMyAgendaEvents({ startISO, endISO, tenantId: tenantIdArg } = {}) {
|
||||
const uid = await getUid();
|
||||
|
||||
const tenantStore = useTenantStore();
|
||||
const tenantId = tenantIdArg || tenantStore.activeTenantId;
|
||||
assertValidTenantId(tenantId);
|
||||
|
||||
if (!startISO || !endISO) throw new Error('Intervalo inválido (startISO/endISO).');
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('agenda_eventos')
|
||||
.select('*, patients(id, nome_completo, avatar_url), determined_commitments!determined_commitment_id(id, bg_color, text_color)')
|
||||
.eq('tenant_id', tenantId)
|
||||
.from('agenda_regras_semanais')
|
||||
.select('dia_semana, hora_inicio, hora_fim, ativo')
|
||||
.eq('owner_id', uid)
|
||||
.gte('inicio_em', startISO)
|
||||
.lt('inicio_em', endISO)
|
||||
.order('inicio_em', { ascending: true });
|
||||
|
||||
if (error) throw error;
|
||||
return data || [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Lista eventos para mosaico da clínica (admin/secretaria) dentro de um tenant específico.
|
||||
* IMPORTANTE: SEM tenant_id aqui vira vazamento multi-tenant.
|
||||
*/
|
||||
export async function listClinicEvents({ tenantId, ownerIds, startISO, endISO }) {
|
||||
assertValidTenantId(tenantId);
|
||||
if (!ownerIds?.length) return [];
|
||||
if (!startISO || !endISO) throw new Error('Intervalo inválido (startISO/endISO).');
|
||||
|
||||
// Sanitiza ownerIds
|
||||
const safeOwnerIds = ownerIds.filter((id) => typeof id === 'string' && id && id !== 'null' && id !== 'undefined');
|
||||
|
||||
if (!safeOwnerIds.length) return [];
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('agenda_eventos')
|
||||
.select('*, determined_commitments!determined_commitment_id(id, bg_color, text_color)')
|
||||
.eq('tenant_id', tenantId)
|
||||
.in('owner_id', safeOwnerIds)
|
||||
.gte('inicio_em', startISO)
|
||||
.lt('inicio_em', endISO)
|
||||
.order('inicio_em', { ascending: true });
|
||||
|
||||
.eq('ativo', true)
|
||||
.order('dia_semana');
|
||||
if (error) throw error;
|
||||
return data || [];
|
||||
}
|
||||
|
||||
export async function listTenantStaff(tenantId) {
|
||||
assertValidTenantId(tenantId);
|
||||
|
||||
const { data, error } = await supabase.from('v_tenant_staff').select('*').eq('tenant_id', tenantId);
|
||||
|
||||
if (error) throw error;
|
||||
return data || [];
|
||||
}
|
||||
|
||||
// ─── Agenda do terapeuta ────────────────────────────────────────────────────
|
||||
|
||||
function resolveTenantId(tenantIdArg) {
|
||||
const tenantStore = useTenantStore();
|
||||
const tenantId = tenantIdArg || tenantStore.activeTenantId;
|
||||
assertValidTenantId(tenantId);
|
||||
return tenantId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lista eventos do terapeuta logado (owner_id = uid) dentro do tenant ativo.
|
||||
* Retorna rows flattened (paciente_nome/paciente_avatar/paciente_status no topo).
|
||||
*
|
||||
* Parâmetros:
|
||||
* - startISO/endISO: half-open range (lt no final — consistente com clinic)
|
||||
* - ownerId: opcional — default é o uid do usuário logado
|
||||
* - tenantId: opcional — default é tenantStore.activeTenantId
|
||||
* - excludeMirror: se true, filtra mirror_of_event_id IS NULL (agenda do terapeuta
|
||||
* não deve mostrar eventos espelho de outra clínica)
|
||||
*/
|
||||
export async function listMyAgendaEvents({ startISO, endISO, ownerId, tenantId, excludeMirror = true } = {}) {
|
||||
assertIsoRange(startISO, endISO);
|
||||
const uid = ownerId || (await getUid());
|
||||
const tid = resolveTenantId(tenantId);
|
||||
|
||||
let q = supabase
|
||||
.from('agenda_eventos')
|
||||
.select(AGENDA_EVENT_SELECT)
|
||||
.eq('tenant_id', tid)
|
||||
.eq('owner_id', uid)
|
||||
.gte('inicio_em', startISO)
|
||||
.lt('inicio_em', endISO)
|
||||
.order('inicio_em', { ascending: true });
|
||||
|
||||
if (excludeMirror) q = q.is('mirror_of_event_id', null);
|
||||
|
||||
const { data, error } = await q;
|
||||
if (error) throw error;
|
||||
return (data || []).map(flattenAgendaRow);
|
||||
}
|
||||
|
||||
/**
|
||||
* Criação segura:
|
||||
* - injeta tenant_id do tenantStore
|
||||
* - injeta owner_id do usuário logado (ignora owner_id vindo de fora)
|
||||
*
|
||||
* Observação:
|
||||
* - Para admin/secretária criar para outros owners, o ideal é ter uma função separada
|
||||
* (ex.: createClinicAgendaEvento) que permita owner_id explicitamente.
|
||||
* Por enquanto, deixo esta função como "safe default" para terapeuta.
|
||||
* - dropa paciente_id (campo legado) se vier no payload
|
||||
*/
|
||||
export async function createAgendaEvento(payload) {
|
||||
const uid = await getUid();
|
||||
const tenantStore = useTenantStore();
|
||||
const tenantId = tenantStore.activeTenantId;
|
||||
assertValidTenantId(tenantId);
|
||||
|
||||
if (!payload) throw new Error('Payload vazio.');
|
||||
const uid = await getUid();
|
||||
const tid = resolveTenantId();
|
||||
|
||||
const insertPayload = {
|
||||
...payload,
|
||||
tenant_id: tenantId,
|
||||
owner_id: uid
|
||||
};
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
const { paciente_id: _dropped, ...rest } = payload;
|
||||
const insertPayload = { ...rest, tenant_id: tid, owner_id: uid };
|
||||
|
||||
const { data, error } = await supabase.from('agenda_eventos').insert(insertPayload).select('*').single();
|
||||
const { data, error } = await supabase
|
||||
.from('agenda_eventos')
|
||||
.insert([insertPayload])
|
||||
.select(AGENDA_EVENT_SELECT)
|
||||
.single();
|
||||
|
||||
if (error) throw error;
|
||||
return data;
|
||||
return flattenAgendaRow(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Atualização segura:
|
||||
* - filtra por id + tenant_id (evita update cruzado por acidente)
|
||||
* RLS deve reforçar isso no banco.
|
||||
* Atualização segura: filtra por id + tenant_id (RLS reforça no banco).
|
||||
*/
|
||||
export async function updateAgendaEvento(id, patch, { tenantId: tenantIdArg } = {}) {
|
||||
export async function updateAgendaEvento(id, patch, { tenantId } = {}) {
|
||||
if (!id) throw new Error('ID inválido.');
|
||||
if (!patch) throw new Error('Patch vazio.');
|
||||
const tid = resolveTenantId(tenantId);
|
||||
|
||||
const tenantStore = useTenantStore();
|
||||
const tenantId = tenantIdArg || tenantStore.activeTenantId;
|
||||
assertValidTenantId(tenantId);
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
const { paciente_id: _dropped, ...safePatch } = patch;
|
||||
|
||||
const { data, error } = await supabase.from('agenda_eventos').update(patch).eq('id', id).eq('tenant_id', tenantId).select('*').single();
|
||||
const { data, error } = await supabase
|
||||
.from('agenda_eventos')
|
||||
.update(safePatch)
|
||||
.eq('id', id)
|
||||
.eq('tenant_id', tid)
|
||||
.select(AGENDA_EVENT_SELECT)
|
||||
.single();
|
||||
|
||||
if (error) throw error;
|
||||
return data;
|
||||
return flattenAgendaRow(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete seguro:
|
||||
* - filtra por id + tenant_id
|
||||
* Delete seguro: filtra por id + tenant_id.
|
||||
*/
|
||||
export async function deleteAgendaEvento(id, { tenantId: tenantIdArg } = {}) {
|
||||
export async function deleteAgendaEvento(id, { tenantId } = {}) {
|
||||
if (!id) throw new Error('ID inválido.');
|
||||
const tid = resolveTenantId(tenantId);
|
||||
|
||||
const tenantStore = useTenantStore();
|
||||
const tenantId = tenantIdArg || tenantStore.activeTenantId;
|
||||
assertValidTenantId(tenantId);
|
||||
|
||||
const { error } = await supabase.from('agenda_eventos').delete().eq('id', id).eq('tenant_id', tenantId);
|
||||
|
||||
const { error } = await supabase.from('agenda_eventos').delete().eq('id', id).eq('tenant_id', tid);
|
||||
if (error) throw error;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Adicione no mesmo arquivo: src/features/agenda/services/agendaRepository.js
|
||||
|
||||
/**
|
||||
* Criação para a área da clínica (admin/secretária):
|
||||
* - exige tenantId explícito (ou cai no tenantStore)
|
||||
* - permite definir owner_id (terapeuta dono do compromisso)
|
||||
*
|
||||
* Segurança real deve ser garantida por RLS:
|
||||
* - clinic_admin/tenant_admin pode criar para qualquer owner dentro do tenant
|
||||
* - therapist não deve conseguir passar daqui (guard + RLS)
|
||||
*/
|
||||
export async function createClinicAgendaEvento(payload, { tenantId: tenantIdArg } = {}) {
|
||||
const tenantStore = useTenantStore();
|
||||
const tenantId = tenantIdArg || tenantStore.activeTenantId;
|
||||
assertValidTenantId(tenantId);
|
||||
|
||||
if (!payload) throw new Error('Payload vazio.');
|
||||
|
||||
const ownerId = payload.owner_id;
|
||||
if (!ownerId || ownerId === 'null' || ownerId === 'undefined') {
|
||||
throw new Error('owner_id é obrigatório para criação pela clínica.');
|
||||
}
|
||||
|
||||
const insertPayload = {
|
||||
...payload,
|
||||
tenant_id: tenantId
|
||||
};
|
||||
|
||||
const { data, error } = await supabase.from('agenda_eventos').insert(insertPayload).select('*').single();
|
||||
|
||||
if (error) throw error;
|
||||
return data;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Agência PSI
|
||||
|--------------------------------------------------------------------------
|
||||
| Arquivo: src/features/agenda/services/agendaSelects.js
|
||||
|
|
||||
| Fonte única do SELECT de agenda_eventos. Antes estava duplicado em 3
|
||||
| lugares (useAgendaEvents, agendaRepository, agendaClinicRepository) com
|
||||
| inconsistências sutis (FKs explícitas em uns, não em outros).
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/**
|
||||
* Select canônico de agenda_eventos com joins do paciente e do commitment.
|
||||
*
|
||||
* FKs explícitas (obrigatórias para evitar ambiguidade quando agenda_eventos
|
||||
* tem múltiplas colunas apontando para a mesma tabela):
|
||||
* - agenda_eventos_patient_id_fkey
|
||||
* - agenda_eventos_determined_commitment_fk
|
||||
*/
|
||||
export const AGENDA_EVENT_SELECT = `
|
||||
id, owner_id, patient_id, tipo, status,
|
||||
titulo, titulo_custom, observacoes, inicio_em, fim_em,
|
||||
terapeuta_id, tenant_id, visibility_scope,
|
||||
determined_commitment_id, link_online, extra_fields, modalidade,
|
||||
recurrence_id, recurrence_date,
|
||||
mirror_of_event_id, price,
|
||||
insurance_plan_id, insurance_guide_number, insurance_value, insurance_plan_service_id,
|
||||
patients!agenda_eventos_patient_id_fkey (
|
||||
id, nome_completo, avatar_url, status
|
||||
),
|
||||
determined_commitments!agenda_eventos_determined_commitment_fk (
|
||||
id, bg_color, text_color
|
||||
)
|
||||
`.trim();
|
||||
|
||||
/**
|
||||
* Achata o aninhamento de patients dentro da row.
|
||||
* O resto do app usa tanto `paciente_nome` (flat) quanto `patients?.nome_completo`
|
||||
* (aninhado). Mantemos ambos após o flatten.
|
||||
*/
|
||||
export function flattenAgendaRow(r) {
|
||||
if (!r) return r;
|
||||
const patient = r.patients || null;
|
||||
const out = { ...r };
|
||||
out.paciente_nome = patient?.nome_completo || r.paciente_nome || '';
|
||||
out.paciente_avatar = patient?.avatar_url || r.paciente_avatar || '';
|
||||
out.paciente_status = patient?.status || r.paciente_status || '';
|
||||
return out;
|
||||
}
|
||||
Reference in New Issue
Block a user