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:
Leonardo
2026-04-19 15:42:46 -03:00
parent d088a89fb7
commit 7c20b518d4
175 changed files with 37325 additions and 37968 deletions
@@ -295,7 +295,7 @@ watch(
async (newVal, oldVal) => {
if (_skipStatusWatch.value) return;
if (!isEdit.value || !form.value?.id) return;
if (newVal !== 'cancelado' && newVal !== 'remarcar') return;
if (newVal !== 'cancelado' && newVal !== 'remarcado') return;
_prevStatus.value = oldVal;
@@ -1073,7 +1073,7 @@ const statusOptions = [
{ label: 'Realizado', value: 'realizado' },
{ label: 'Faltou', value: 'faltou' },
{ label: 'Cancelado', value: 'cancelado' },
{ label: 'Remarcar', value: 'remarcar' }
{ label: 'Remarcar', value: 'remarcado' }
];
const serieCountByStatus = computed(() => {
@@ -1122,7 +1122,7 @@ const statusOptionsFiltered = computed(() => [
{ label: 'Realizado', value: 'realizado' },
{ label: 'Faltou', value: 'faltou' },
{ label: 'Cancelado', value: 'cancelado' },
{ label: 'Remarcar', value: 'remarcar', disabled: isInativoFutureEdit.value }
{ label: 'Remarcar', value: 'remarcado', disabled: isInativoFutureEdit.value }
]);
function fmtWeekdayShort(iso) {
return new Date(iso).toLocaleDateString('pt-BR', { weekday: 'short' }).replace('.', '').slice(0, 3);
@@ -1661,7 +1661,7 @@ const googleCalendarUrl = computed(() => {
});
function labelStatusSessao(v) {
const map = { agendado: 'Agendado', realizado: 'Realizado', faltou: 'Faltou', cancelado: 'Cancelado', remarcar: 'Remarcar' };
const map = { agendado: 'Agendado', realizado: 'Realizado', faltou: 'Faltou', cancelado: 'Cancelado', remarcado: 'Remarcado' };
return map[v] || '—';
}
function statusSeverity(v) {
@@ -1669,11 +1669,11 @@ function statusSeverity(v) {
if (v === 'realizado') return 'success';
if (v === 'faltou') return 'warn';
if (v === 'cancelado') return 'danger';
if (v === 'remarcar') return 'secondary'; // cor real via classe CSS
if (v === 'remarcado') return 'secondary'; // cor real via classe CSS
return 'secondary';
}
function statusExtraClass(v) {
return v === 'remarcar' ? 'tag-remarcar' : '';
return v === 'remarcado' ? 'tag-remarcado' : '';
}
</script>
@@ -1949,7 +1949,7 @@ function statusExtraClass(v) {
<span v-if="serieCountByStatus.realizado"> · {{ serieCountByStatus.realizado }} realizadas</span>
<span v-if="serieCountByStatus.faltou"> · {{ serieCountByStatus.faltou }} faltaram</span>
<span v-if="serieCountByStatus.cancelado"> · {{ serieCountByStatus.cancelado }} canceladas</span>
<span v-if="serieCountByStatus.remarcar"> · {{ serieCountByStatus.remarcar }} para remarcar</span>
<span v-if="serieCountByStatus.remarcado"> · {{ serieCountByStatus.remarcado }} para remarcar</span>
</div>
<span v-if="serieLoading" class="ml-auto text-xs opacity-50">Carregando</span>
</div>
@@ -2482,8 +2482,8 @@ function statusExtraClass(v) {
padding: 0.75rem;
}
/* ── tag: remarcar (roxo — sem severity nativo no PrimeVue) ─ */
:deep(.tag-remarcar) {
/* ── tag: remarcado (roxo — sem severity nativo no PrimeVue) ─ */
:deep(.tag-remarcado) {
background: #a855f7 !important;
color: #fff !important;
}
@@ -3302,7 +3302,7 @@ function statusExtraClass(v) {
.serie-pill--cancelado {
border-left-color: var(--surface-border);
}
.serie-pill--remarcar {
.serie-pill--remarcado {
border-left-color: var(--orange-400, #fb923c);
}
.serie-pill__date {
@@ -207,7 +207,7 @@ async function confirmar() {
const { error } = await supabase.from('agenda_bloqueios').insert(rows);
if (error) throw error;
// Marcar sessões existentes como "remarcar"
// Marcar sessões existentes como "remarcado"
await marcarSessoesParaRemarcar(rows);
toast.add({
@@ -226,10 +226,10 @@ async function confirmar() {
}
async function marcarSessoesParaRemarcar(bloqueios) {
// Para cada bloqueio, tenta marcar sessões existentes como 'remarcar'
// Para cada bloqueio, tenta marcar sessões existentes como 'remarcado'
for (const b of bloqueios) {
try {
let query = supabase.from('agenda_eventos').update({ status: 'remarcar' }).eq('owner_id', props.ownerId).eq('tipo', 'sessao').gte('inicio_em', `${b.data_inicio}T00:00:00`).lte('inicio_em', `${b.data_fim}T23:59:59`);
let query = supabase.from('agenda_eventos').update({ status: 'remarcado' }).eq('owner_id', props.ownerId).eq('tipo', 'sessao').gte('inicio_em', `${b.data_inicio}T00:00:00`).lte('inicio_em', `${b.data_fim}T23:59:59`);
if (b.hora_inicio && b.hora_fim) {
// filtra pela hora aproximada — comparação UTC simplificada
@@ -156,8 +156,8 @@ async function confirmarBloqueio(feriado) {
const { error } = await supabase.from('agenda_bloqueios').insert([row]);
if (error) throw error;
// Marcar sessões existentes no dia como 'remarcar'
await supabase.from('agenda_eventos').update({ status: 'remarcar' }).eq('owner_id', _ownerId.value).eq('tipo', 'sessao').gte('inicio_em', `${feriado.data}T00:00:00`).lte('inicio_em', `${feriado.data}T23:59:59`);
// Marcar sessões existentes no dia como 'remarcado'
await supabase.from('agenda_eventos').update({ status: 'remarcado' }).eq('owner_id', _ownerId.value).eq('tipo', 'sessao').gte('inicio_em', `${feriado.data}T00:00:00`).lte('inicio_em', `${feriado.data}T23:59:59`);
bloqueiosDatas.value = new Set([...bloqueiosDatas.value, feriado.data]);
toast.add({
@@ -0,0 +1,155 @@
/**
* useAgendaEvents.spec.js — T#9
*
* Wrapper fino do agendaRepository. Cobertura focada nos contratos:
* - rows/loading/error reativos
* - delega I/O ao repository (nada de fetch direto)
* - sem ownerId, loadMyRange é no-op (proteção tenant scoping)
* - error é capturado em loadMyRange e zera rows; create/update/remove propagam
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
const listMock = vi.fn();
const createMock = vi.fn();
const updateMock = vi.fn();
const removeMock = vi.fn();
vi.mock('@/features/agenda/services/agendaRepository', () => ({
listMyAgendaEvents: (...a) => listMock(...a),
createAgendaEvento: (...a) => createMock(...a),
updateAgendaEvento: (...a) => updateMock(...a),
deleteAgendaEvento: (...a) => removeMock(...a)
}));
const { useAgendaEvents } = await import('../useAgendaEvents.js');
beforeEach(() => {
listMock.mockReset();
createMock.mockReset();
updateMock.mockReset();
removeMock.mockReset();
});
describe('useAgendaEvents — estado inicial', () => {
it('rows vazio, loading false, error null', () => {
const { rows, loading, error } = useAgendaEvents();
expect(rows.value).toEqual([]);
expect(loading.value).toBe(false);
expect(error.value).toBe(null);
});
});
describe('loadMyRange', () => {
it('sem ownerId, não chama o repository (no-op de segurança)', async () => {
const { rows, loadMyRange } = useAgendaEvents();
await loadMyRange('2026-01-01', '2026-01-31', null);
await loadMyRange('2026-01-01', '2026-01-31', '');
await loadMyRange('2026-01-01', '2026-01-31', undefined);
expect(listMock).not.toHaveBeenCalled();
expect(rows.value).toEqual([]);
});
it('chama listMyAgendaEvents com payload correto e popula rows', async () => {
listMock.mockResolvedValue([{ id: 'a' }, { id: 'b' }]);
const { rows, loading, loadMyRange } = useAgendaEvents();
const promise = loadMyRange('2026-01-01', '2026-01-31', 'u-1');
// loading vira true durante a execução
expect(loading.value).toBe(true);
await promise;
expect(listMock).toHaveBeenCalledWith({
startISO: '2026-01-01',
endISO: '2026-01-31',
ownerId: 'u-1'
});
expect(rows.value).toEqual([{ id: 'a' }, { id: 'b' }]);
expect(loading.value).toBe(false);
});
it('captura erro, zera rows e seta error.message', async () => {
listMock.mockRejectedValue(new Error('fetch fail'));
const { rows, loading, error, loadMyRange } = useAgendaEvents();
await loadMyRange('2026-01-01', '2026-01-31', 'u-1');
expect(rows.value).toEqual([]);
expect(loading.value).toBe(false);
expect(error.value).toBe('fetch fail');
});
it('reseta error em call subsequente bem-sucedida', async () => {
listMock.mockRejectedValueOnce(new Error('first fail')).mockResolvedValueOnce([{ id: 'x' }]);
const { error, loadMyRange } = useAgendaEvents();
await loadMyRange('2026-01-01', '2026-01-31', 'u-1');
expect(error.value).toBe('first fail');
await loadMyRange('2026-01-01', '2026-01-31', 'u-1');
expect(error.value).toBe(null);
});
it('error sem message vira fallback string', async () => {
listMock.mockRejectedValue({}); // sem .message
const { error, loadMyRange } = useAgendaEvents();
await loadMyRange('2026-01-01', '2026-01-31', 'u-1');
expect(error.value).toBe('Erro ao carregar eventos');
});
});
describe('create / update / remove — delegação pura', () => {
it('create encaminha payload e retorna o resultado do repository', async () => {
createMock.mockResolvedValue({ id: 'new', titulo: 'X' });
const { create } = useAgendaEvents();
const result = await create({ titulo: 'X' });
expect(createMock).toHaveBeenCalledWith({ titulo: 'X' });
expect(result).toEqual({ id: 'new', titulo: 'X' });
});
it('update encaminha id+patch e retorna o resultado', async () => {
updateMock.mockResolvedValue({ id: '42', titulo: 'updated' });
const { update } = useAgendaEvents();
const result = await update('42', { titulo: 'updated' });
expect(updateMock).toHaveBeenCalledWith('42', { titulo: 'updated' });
expect(result).toEqual({ id: '42', titulo: 'updated' });
});
it('remove encaminha id (sem retorno)', async () => {
removeMock.mockResolvedValue(undefined);
const { remove } = useAgendaEvents();
const result = await remove('99');
expect(removeMock).toHaveBeenCalledWith('99');
expect(result).toBeUndefined();
});
it('create propaga erro (não engole)', async () => {
createMock.mockRejectedValue(new Error('insert blocked by RLS'));
const { create } = useAgendaEvents();
await expect(create({ titulo: 'X' })).rejects.toThrow(/RLS/);
});
it('update propaga erro', async () => {
updateMock.mockRejectedValue(new Error('not found'));
const { update } = useAgendaEvents();
await expect(update('1', { x: 1 })).rejects.toThrow(/not found/);
});
it('remove propaga erro', async () => {
removeMock.mockRejectedValue(new Error('cascade fail'));
const { remove } = useAgendaEvents();
await expect(remove('1')).rejects.toThrow(/cascade/);
});
});
describe('isolamento entre instâncias', () => {
it('cada useAgendaEvents() retorna refs independentes', async () => {
listMock.mockResolvedValue([{ id: 'a' }]);
const a = useAgendaEvents();
const b = useAgendaEvents();
await a.loadMyRange('2026-01-01', '2026-01-31', 'u-1');
expect(a.rows.value).toEqual([{ id: 'a' }]);
expect(b.rows.value).toEqual([]); // b não foi tocado
});
});
@@ -16,75 +16,33 @@
*/
/**
* useAgendaEvents.js
* src/features/agenda/composables/useAgendaEvents.js
*
* Gerencia apenas eventos reais (agenda_eventos).
* Sessões com recurrence_id são sessões reais de uma série.
* Wrapper fino sobre agendaRepository — agrega estado reativo (rows/loading/error)
* e delega toda a lógica de I/O ao repository. Mesmo padrão de useAgendaClinicEvents.
*
* Só gerencia eventos reais (agenda_eventos). Ocorrências virtuais de séries são
* responsabilidade do useRecurrence.
*/
import { ref } from 'vue';
import { supabase } from '@/lib/supabase/client';
import { useTenantStore } from '@/stores/tenantStore';
// ─── helpers internos ────────────────────────────────────────────────────────
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.');
}
}
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;
}
const BASE_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();
import {
listMyAgendaEvents,
createAgendaEvento,
updateAgendaEvento,
deleteAgendaEvento
} from '@/features/agenda/services/agendaRepository';
export function useAgendaEvents() {
const rows = ref([]);
const loading = ref(false);
const error = ref(null);
async function loadMyRange(start, end, ownerId) {
async function loadMyRange(startISO, endISO, ownerId) {
if (!ownerId) return;
const tenantStore = useTenantStore();
const tenantId = tenantStore.activeTenantId;
assertTenantId(tenantId);
loading.value = true;
error.value = null;
try {
const { data, error: err } = await supabase
.from('agenda_eventos')
.select(BASE_SELECT)
.eq('tenant_id', tenantId)
.eq('owner_id', ownerId)
.is('mirror_of_event_id', null)
.gte('inicio_em', start)
.lte('inicio_em', end)
.order('inicio_em', { ascending: true });
if (err) throw err;
rows.value = (data || []).map(flattenRow);
rows.value = await listMyAgendaEvents({ startISO, endISO, ownerId });
} catch (e) {
error.value = e?.message || 'Erro ao carregar eventos';
rows.value = [];
@@ -93,89 +51,17 @@ export function useAgendaEvents() {
}
}
/**
* Cria um evento injetando tenant_id e owner_id automaticamente.
* owner_id é sempre o usuário autenticado — nunca vem do payload externo.
* tenant_id vem do tenantStore ativo — nunca do payload externo.
*/
async function create(payload) {
const tenantStore = useTenantStore();
const tenantId = tenantStore.activeTenantId;
assertTenantId(tenantId);
const uid = await getUid();
// eslint-disable-next-line no-unused-vars
const { paciente_id: _dropped, ...rest } = payload;
const safePayload = {
...rest,
tenant_id: tenantId,
owner_id: uid
};
const { data, error: err } = await supabase.from('agenda_eventos').insert([safePayload]).select(BASE_SELECT).single();
if (err) throw err;
return flattenRow(data);
return createAgendaEvento(payload);
}
async function update(id, patch) {
if (!id) throw new Error('ID inválido.');
const tenantStore = useTenantStore();
const tenantId = tenantStore.activeTenantId;
assertTenantId(tenantId);
// eslint-disable-next-line no-unused-vars
const { paciente_id: _dropped, ...safePatch } = patch;
const { data, error: err } = await supabase.from('agenda_eventos').update(safePatch).eq('id', id).eq('tenant_id', tenantId).select(BASE_SELECT).single();
if (err) throw err;
return flattenRow(data);
return updateAgendaEvento(id, patch);
}
async function remove(id) {
if (!id) throw new Error('ID inválido.');
const tenantStore = useTenantStore();
const tenantId = tenantStore.activeTenantId;
assertTenantId(tenantId);
const { error: err } = await supabase.from('agenda_eventos').delete().eq('id', id).eq('tenant_id', tenantId);
if (err) throw err;
await deleteAgendaEvento(id);
}
async function removeSeriesFrom(recurrenceId, fromDateISO) {
if (!recurrenceId) throw new Error('recurrenceId inválido.');
const tenantStore = useTenantStore();
const tenantId = tenantStore.activeTenantId;
assertTenantId(tenantId);
const { error: err } = await supabase.from('agenda_eventos').delete().eq('recurrence_id', recurrenceId).eq('tenant_id', tenantId).gte('recurrence_date', fromDateISO);
if (err) throw err;
}
async function removeAllSeries(recurrenceId) {
if (!recurrenceId) throw new Error('recurrenceId inválido.');
const tenantStore = useTenantStore();
const tenantId = tenantStore.activeTenantId;
assertTenantId(tenantId);
const { error: err } = await supabase.from('agenda_eventos').delete().eq('recurrence_id', recurrenceId).eq('tenant_id', tenantId);
if (err) throw err;
}
return { rows, loading, error, loadMyRange, create, update, remove, removeSeriesFrom, removeAllSeries };
}
function flattenRow(r) {
if (!r) return r;
const patient = r.patients || null;
const out = { ...r };
delete out.patients;
out.paciente_nome = patient?.nome_completo || out.paciente_nome || '';
out.paciente_avatar = patient?.avatar_url || out.paciente_avatar || '';
out.paciente_status = patient?.status || out.paciente_status || '';
return out;
return { rows, loading, error, loadMyRange, create, update, remove };
}
@@ -31,6 +31,8 @@
import { ref } from 'vue';
import { supabase } from '@/lib/supabase/client';
import { useTenantStore } from '@/stores/tenantStore';
import { assertTenantId } from '@/features/agenda/services/_tenantGuards';
import { logRecurrence, logError, logPerf } from '@/support/supportLogger';
// ─── helpers de data ────────────────────────────────────────────────────────
@@ -197,6 +199,11 @@ export function generateDates(rule, rangeStart, rangeEnd) {
// ─── expansão principal ──────────────────────────────────────────────────────
// Cap defensivo: a agenda real sempre passa ranges mensais/semanais (≤42d).
// Range muito grande com muitas regras = milhares de ocorrências no browser.
// Não bloqueamos (relatórios legítimos podem precisar), só avisamos.
const MAX_RANGE_DAYS = 730; // 2 anos
/**
* Expande regras em ocorrências, aplica exceções.
*
@@ -207,6 +214,15 @@ export function generateDates(rule, rangeStart, rangeEnd) {
* @returns {Array} occurrences — objetos com shape compatível com FullCalendar
*/
export function expandRules(rules, exceptions, rangeStart, rangeEnd) {
const rangeDays = Math.round((rangeEnd.getTime() - rangeStart.getTime()) / 86_400_000);
if (rangeDays > MAX_RANGE_DAYS) {
logError('useRecurrence', 'expandRules: range grande pode degradar UI', {
rangeDays,
maxRecommended: MAX_RANGE_DAYS,
ruleCount: (rules || []).length
});
}
// índice de exceções por regra+data
const exMap = new Map();
for (const ex of exceptions || []) {
@@ -399,6 +415,13 @@ export function useRecurrence() {
const exceptions = ref([]);
const loading = ref(false);
const error = ref(null);
const tenantStore = useTenantStore();
function currentTenantId() {
const tid = tenantStore.activeTenantId;
assertTenantId(tid);
return tid;
}
/**
* Carrega regras ativas para um owner no range dado.
@@ -493,6 +516,7 @@ export function useRecurrence() {
return true;
});
} catch (e) {
logError('useRecurrence', 'loadExceptions ERRO', e);
error.value = e?.message || 'Erro ao carregar exceções';
exceptions.value = [];
}
@@ -546,13 +570,16 @@ export function useRecurrence() {
// ── CRUD de regras ──────────────────────────────────────────────────────────
/**
* Cria uma nova regra de recorrência
* Cria uma nova regra de recorrência.
* tenant_id é injetado do tenantStore se não vier no payload (defesa em profundidade).
* @param {Object} rule - campos da tabela recurrence_rules
* @returns {Object} regra criada
*/
async function createRule(rule) {
const tenantId = currentTenantId();
logRecurrence('createRule →', { patient_id: rule?.patient_id, type: rule?.type });
const { data, error: err } = await supabase.from('recurrence_rules').insert([rule]).select('*').single();
const safeRule = { ...rule, tenant_id: rule?.tenant_id || tenantId };
const { data, error: err } = await supabase.from('recurrence_rules').insert([safeRule]).select('*').single();
if (err) {
logError('useRecurrence', 'createRule ERRO', err);
throw err;
@@ -562,13 +589,16 @@ export function useRecurrence() {
}
/**
* Atualiza a regra toda (editar todos)
* Atualiza a regra toda (editar todos).
* Filtro adicional por tenant_id — defesa em profundidade (RLS cobre, mas reforçamos).
*/
async function updateRule(id, patch) {
const tenantId = currentTenantId();
const { data, error: err } = await supabase
.from('recurrence_rules')
.update({ ...patch, updated_at: new Date().toISOString() })
.eq('id', id)
.eq('tenant_id', tenantId)
.select('*')
.single();
if (err) throw err;
@@ -576,10 +606,15 @@ export function useRecurrence() {
}
/**
* Cancela a série inteira
* Cancela a série inteira (filtro por tenant_id — defesa em profundidade).
*/
async function cancelRule(id) {
const { error: err } = await supabase.from('recurrence_rules').update({ status: 'cancelado', updated_at: new Date().toISOString() }).eq('id', id);
const tenantId = currentTenantId();
const { error: err } = await supabase
.from('recurrence_rules')
.update({ status: 'cancelado', updated_at: new Date().toISOString() })
.eq('id', id)
.eq('tenant_id', tenantId);
if (err) throw err;
}
@@ -610,19 +645,33 @@ export function useRecurrence() {
// ── CRUD de exceções ────────────────────────────────────────────────────────
/**
* Cria ou atualiza uma exceção para uma ocorrência específica
* Cria ou atualiza uma exceção para uma ocorrência específica.
* tenant_id é injetado do tenantStore se não vier no payload.
*/
async function upsertException(ex) {
const { data, error: err } = await supabase.from('recurrence_exceptions').upsert([ex], { onConflict: 'recurrence_id,original_date' }).select('*').single();
const tenantId = currentTenantId();
const safeEx = { ...ex, tenant_id: ex?.tenant_id || tenantId };
const { data, error: err } = await supabase
.from('recurrence_exceptions')
.upsert([safeEx], { onConflict: 'recurrence_id,original_date' })
.select('*')
.single();
if (err) throw err;
return data;
}
/**
* Remove uma exceção (restaura a ocorrência ao normal)
* Remove uma exceção (restaura a ocorrência ao normal).
* Filtro por tenant_id — defesa em profundidade.
*/
async function deleteException(recurrenceId, originalDate) {
const { error: err } = await supabase.from('recurrence_exceptions').delete().eq('recurrence_id', recurrenceId).eq('original_date', originalDate);
const tenantId = currentTenantId();
const { error: err } = await supabase
.from('recurrence_exceptions')
.delete()
.eq('recurrence_id', recurrenceId)
.eq('original_date', originalDate)
.eq('tenant_id', tenantId);
if (err) throw err;
}
@@ -1968,7 +1968,7 @@ async function bloquearFeriadoDoAlerta(feriado) {
}
]);
if (error) throw error;
await supabase.from('agenda_eventos').update({ status: 'remarcar' }).eq('owner_id', clinicOwnerId.value).eq('tipo', 'sessao').gte('inicio_em', `${feriado.data}T00:00:00`).lte('inicio_em', `${feriado.data}T23:59:59`);
await supabase.from('agenda_eventos').update({ status: 'remarcado' }).eq('owner_id', clinicOwnerId.value).eq('tipo', 'sessao').gte('inicio_em', `${feriado.data}T00:00:00`).lte('inicio_em', `${feriado.data}T23:59:59`);
feriadosAlertaBloqueados.value = new Set([...feriadosAlertaBloqueados.value, feriado.data]);
miniBlockedDaySet.value = new Set([...miniBlockedDaySet.value, feriado.data]);
@@ -1330,7 +1330,7 @@ async function bloquearFeriadoDoAlerta(feriado) {
}
]);
if (error) throw error;
await supabase.from('agenda_eventos').update({ status: 'remarcar' }).eq('owner_id', ownerId.value).eq('tipo', 'sessao').gte('inicio_em', `${feriado.data}T00:00:00`).lte('inicio_em', `${feriado.data}T23:59:59`);
await supabase.from('agenda_eventos').update({ status: 'remarcado' }).eq('owner_id', ownerId.value).eq('tipo', 'sessao').gte('inicio_em', `${feriado.data}T00:00:00`).lte('inicio_em', `${feriado.data}T23:59:59`);
feriadosAlertaBloqueados.value = new Set([...feriadosAlertaBloqueados.value, feriado.data]);
miniBlockedDaySet.value = new Set([...miniBlockedDaySet.value, feriado.data]);
@@ -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 '';
+84 -150
View File
@@ -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;
}