feature/patiente-medical-assignment #45

Merged
JoaoGustavo-dev merged 21 commits from feature/patiente-medical-assignment into develop 2025-10-12 03:57:36 +00:00
6 changed files with 366 additions and 2155 deletions
Showing only changes of commit 2bb0b06375 - Show all commits

File diff suppressed because it is too large Load Diff

View File

@ -4,8 +4,7 @@ import { useState, useEffect, useCallback } from 'react';
import {
Report,
CreateReportData,
UpdateReportData,
ApiError
UpdateReportData
} from '@/types/report-types';
import {
listarRelatorios,

View File

@ -14,11 +14,8 @@ export type ApiOk<T = any> = {
total?: number;
};
};
// ===== TIPOS COMUNS =====
export type Endereco = {
cep?: string;
logradouro?: string;
numero?: string;
complemento?: string;
bairro?: string;
@ -245,14 +242,19 @@ export async function listarPacientes(params?: {
}): Promise<Paciente[]> {
const qs = new URLSearchParams();
if (params?.q) qs.set("q", params.q);
let url = `${ENV_CONFIG.SUPABASE_URL}/rest/v1/patients`;
const qsString = qs.toString();
if (qsString) url += `?${qsString}`;
const url = `${REST}/patients${qs.toString() ? `?${qs.toString()}` : ""}`;
const res = await fetch(url, {
method: "GET",
headers: {
// Use baseHeaders() so the current user token (from local/session storage) and apikey are sent
const headers: HeadersInit = {
...baseHeaders(),
...rangeHeaders(params?.page, params?.limit),
},
};
const res = await fetch(url, {
method: "GET",
headers,
});
return await parse<Paciente[]>(res);
}
@ -299,7 +301,7 @@ export async function buscarPacientes(termo: string): Promise<Paciente[]> {
// Executa as buscas e combina resultados únicos
for (const query of queries) {
try {
const url = `${REST}/patients?${query}&limit=10`;
const url = `${ENV_CONFIG.SUPABASE_URL}/rest/v1/patients?${query}&limit=10`;
const res = await fetch(url, { method: "GET", headers: baseHeaders() });
const arr = await parse<Paciente[]>(res);
@ -325,7 +327,7 @@ export async function buscarPacientePorId(id: string | number): Promise<Paciente
if (typeof id === 'string' && isNaN(Number(id))) {
idParam = `\"${id}\"`;
}
const url = `${REST}/patients?id=eq.${idParam}`;
const url = `${ENV_CONFIG.SUPABASE_URL}/rest/v1/patients?id=eq.${idParam}`;
const res = await fetch(url, { method: "GET", headers: baseHeaders() });
const arr = await parse<Paciente[]>(res);
if (!arr?.length) throw new Error("404: Paciente não encontrado");
@ -333,7 +335,7 @@ export async function buscarPacientePorId(id: string | number): Promise<Paciente
}
export async function criarPaciente(input: PacienteInput): Promise<Paciente> {
const url = `${REST}/patients`;
const url = `${ENV_CONFIG.SUPABASE_URL}/rest/v1/patients`;
const res = await fetch(url, {
method: "POST",
headers: withPrefer({ ...baseHeaders(), "Content-Type": "application/json" }, "return=representation"),
@ -344,7 +346,7 @@ export async function criarPaciente(input: PacienteInput): Promise<Paciente> {
}
export async function atualizarPaciente(id: string | number, input: PacienteInput): Promise<Paciente> {
const url = `${REST}/patients?id=eq.${id}`;
const url = `${ENV_CONFIG.SUPABASE_URL}/rest/v1/patients?id=eq.${id}`;
const res = await fetch(url, {
method: "PATCH",
headers: withPrefer({ ...baseHeaders(), "Content-Type": "application/json" }, "return=representation"),
@ -355,7 +357,7 @@ export async function atualizarPaciente(id: string | number, input: PacienteInpu
}
export async function excluirPaciente(id: string | number): Promise<void> {
const url = `${REST}/patients?id=eq.${id}`;
const url = `${ENV_CONFIG.SUPABASE_URL}/rest/v1/patients?id=eq.${id}`;
const res = await fetch(url, { method: "DELETE", headers: baseHeaders() });
await parse<any>(res);
}

View File

@ -45,29 +45,29 @@ import {
CreateReportData,
UpdateReportData,
ReportsResponse,
ReportResponse,
ApiError
ReportResponse
} from '@/types/report-types';
// URL base da API Mock
const BASE_API_RELATORIOS = 'https://mock.apidog.com/m1/1053378-0-default/rest/v1/reports';
// Definição local para ApiError
type ApiError = {
message: string;
code: string;
};
// Cabeçalhos base para as requisições
function obterCabecalhos(): HeadersInit {
// URL base da API Supabase
const BASE_API_RELATORIOS = 'https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/reports';
// Cabeçalhos base para as requisições Supabase
function obterCabecalhos(token?: string): HeadersInit {
const cabecalhos: HeadersInit = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'apikey': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Inl1YW5xZnN3aGJlcmtvZXZ0bWZyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTQ5NTQzNjksImV4cCI6MjA3MDUzMDM2OX0.g8Fm4XAvtX46zifBZnYVH4tVuQkqUH6Ia9CXQj4DztQ',
'Prefer': 'return=representation',
};
// Adiciona token de autenticação do localStorage se disponível
if (typeof window !== 'undefined') {
const token = localStorage.getItem('token');
if (token) {
cabecalhos['Authorization'] = `Bearer ${token}`;
}
}
return cabecalhos;
}
@ -139,13 +139,15 @@ export async function listarRelatorios(filtros?: { patient_id?: string; status?:
export async function buscarRelatorioPorId(id: string): Promise<Report> {
try {
console.log('🔍 [API RELATÓRIOS] Buscando relatório ID:', id);
const resposta = await fetch(`${BASE_API_RELATORIOS}/${id}`, {
const resposta = await fetch(`${BASE_API_RELATORIOS}?id=eq.${id}`, {
method: 'GET',
headers: obterCabecalhos(),
});
const resultado = await tratarRespostaApi<ReportResponse>(resposta);
console.log('✅ [API RELATÓRIOS] Relatório encontrado:', resultado.data);
return resultado.data;
const resultado = await tratarRespostaApi<Report[]>(resposta);
const relatorio = Array.isArray(resultado) && resultado.length > 0 ? resultado[0] : null;
console.log('✅ [API RELATÓRIOS] Relatório encontrado:', relatorio);
if (!relatorio) throw new Error('Relatório não encontrado');
return relatorio;
} catch (erro) {
console.error('❌ [API RELATÓRIOS] Erro ao buscar relatório:', erro);
throw erro;
@ -155,60 +157,30 @@ export async function buscarRelatorioPorId(id: string): Promise<Report> {
/**
* Cria um novo relatório médico
*/
export async function criarRelatorio(dadosRelatorio: CreateReportData): Promise<Report> {
try {
console.log('📝 [API RELATÓRIOS] Criando novo relatório...');
console.log('📤 [API RELATÓRIOS] Dados enviados:', dadosRelatorio);
export async function criarRelatorio(dadosRelatorio: CreateReportData, token?: string): Promise<Report> {
const resposta = await fetch(BASE_API_RELATORIOS, {
method: 'POST',
headers: obterCabecalhos(),
headers: obterCabecalhos(token),
body: JSON.stringify(dadosRelatorio),
});
console.log('📝 [API RELATÓRIOS] Status da criação:', resposta.status);
console.log('📝 [API RELATÓRIOS] Response OK:', resposta.ok);
console.log('📝 [API RELATÓRIOS] Response URL:', resposta.url);
if (!resposta.ok) {
let mensagemErro = `HTTP ${resposta.status}: ${resposta.statusText}`;
try {
const dadosErro = await resposta.json();
mensagemErro = dadosErro.message || dadosErro.error || mensagemErro;
console.log('📝 [API RELATÓRIOS] Erro da API:', dadosErro);
} catch (e) {
console.log('📝 [API RELATÓRIOS] Não foi possível parsear erro como JSON');
}
const erro: ApiError = {
} catch (e) {}
const erro: any = {
message: mensagemErro,
code: resposta.status.toString(),
};
throw erro;
}
const resultadoBruto = await resposta.json();
console.log('📝 [API RELATÓRIOS] Resposta bruta da criação:', resultadoBruto);
console.log('📝 [API RELATÓRIOS] Tipo da resposta:', typeof resultadoBruto);
console.log('📝 [API RELATÓRIOS] Chaves da resposta:', Object.keys(resultadoBruto || {}));
let relatorioCriado: Report;
// Verifica formato da resposta similar ao listarRelatorios
if (resultadoBruto && resultadoBruto.data) {
relatorioCriado = resultadoBruto.data;
} else if (resultadoBruto && resultadoBruto.id) {
relatorioCriado = resultadoBruto;
} else if (Array.isArray(resultadoBruto) && resultadoBruto.length > 0) {
relatorioCriado = resultadoBruto[0];
} else {
console.warn('📝 [API RELATÓRIOS] Formato de resposta inesperado, criando relatório local');
relatorioCriado = {
id: 'local-' + Date.now() + '-' + Math.random().toString(36).substr(2, 5),
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
...dadosRelatorio
};
}
console.log('✅ [API RELATÓRIOS] Relatório processado:', relatorioCriado);
return relatorioCriado;
} catch (erro) {
console.error('❌ [API RELATÓRIOS] Erro ao criar relatório:', erro);
throw erro;
const resultado = await resposta.json();
// Supabase retorna array
if (Array.isArray(resultado) && resultado.length > 0) {
return resultado[0];
}
throw new Error('Resposta inesperada da API Supabase');
}
/**
@ -218,14 +190,16 @@ export async function atualizarRelatorio(id: string, dadosRelatorio: UpdateRepor
try {
console.log('📝 [API RELATÓRIOS] Atualizando relatório ID:', id);
console.log('📤 [API RELATÓRIOS] Dados:', dadosRelatorio);
const resposta = await fetch(`${BASE_API_RELATORIOS}/${id}`, {
const resposta = await fetch(`${BASE_API_RELATORIOS}?id=eq.${id}`, {
method: 'PATCH',
headers: obterCabecalhos(),
body: JSON.stringify(dadosRelatorio),
});
const resultado = await tratarRespostaApi<ReportResponse>(resposta);
console.log('✅ [API RELATÓRIOS] Relatório atualizado:', resultado.data);
return resultado.data;
const resultado = await tratarRespostaApi<Report[]>(resposta);
const relatorio = Array.isArray(resultado) && resultado.length > 0 ? resultado[0] : null;
console.log('✅ [API RELATÓRIOS] Relatório atualizado:', relatorio);
if (!relatorio) throw new Error('Relatório não encontrado');
return relatorio;
} catch (erro) {
console.error('❌ [API RELATÓRIOS] Erro ao atualizar relatório:', erro);
throw erro;
@ -256,13 +230,13 @@ export async function deletarRelatorio(id: string): Promise<void> {
export async function listarRelatoriosPorPaciente(idPaciente: string): Promise<Report[]> {
try {
console.log('👤 [API RELATÓRIOS] Buscando relatórios do paciente:', idPaciente);
const resposta = await fetch(`${BASE_API_RELATORIOS}?patient_id=${idPaciente}`, {
const resposta = await fetch(`${BASE_API_RELATORIOS}?patient_id=eq.${idPaciente}`, {
method: 'GET',
headers: obterCabecalhos(),
});
const resultado = await tratarRespostaApi<ReportsResponse>(resposta);
console.log('✅ [API RELATÓRIOS] Relatórios do paciente encontrados:', resultado.data?.length || 0);
return resultado.data || [];
const resultado = await tratarRespostaApi<Report[]>(resposta);
console.log('✅ [API RELATÓRIOS] Relatórios do paciente encontrados:', resultado.length);
return resultado;
} catch (erro) {
console.error('❌ [API RELATÓRIOS] Erro ao buscar relatórios do paciente:', erro);
throw erro;
@ -275,13 +249,13 @@ export async function listarRelatoriosPorPaciente(idPaciente: string): Promise<R
export async function listarRelatoriosPorMedico(idMedico: string): Promise<Report[]> {
try {
console.log('👨‍⚕️ [API RELATÓRIOS] Buscando relatórios do médico:', idMedico);
const resposta = await fetch(`${BASE_API_RELATORIOS}?doctor_id=${idMedico}`, {
const resposta = await fetch(`${BASE_API_RELATORIOS}?requested_by=eq.${idMedico}`, {
method: 'GET',
headers: obterCabecalhos(),
});
const resultado = await tratarRespostaApi<ReportsResponse>(resposta);
console.log('✅ [API RELATÓRIOS] Relatórios do médico encontrados:', resultado.data?.length || 0);
return resultado.data || [];
const resultado = await tratarRespostaApi<Report[]>(resposta);
console.log('✅ [API RELATÓRIOS] Relatórios do médico encontrados:', resultado.length);
return resultado;
} catch (erro) {
console.error('❌ [API RELATÓRIOS] Erro ao buscar relatórios do médico:', erro);
throw erro;

View File

@ -1,5 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
/// <reference path="./.next/types/routes.d.ts" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/building-your-application/configuring/typescript for more information.
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.

View File

@ -4,60 +4,66 @@ export interface ApiError {
code?: string;
}
// Este arquivo foi renomeado de report.ts para report-types.ts para evitar confusão com outros arquivos de lógica.
// Tipos para o endpoint de Relatórios Médicos
// Tipos para o endpoint Supabase de Relatórios Médicos
export interface Report {
id: string;
patient_id: string;
doctor_id: string;
report_type: string;
chief_complaint: string;
clinical_history: string;
symptoms_and_signs: string;
physical_examination: string;
complementary_exams: string;
exam_results: string;
order_number: string;
exam: string;
diagnosis: string;
prognosis?: string;
treatment_performed: string;
objective_recommendations: string;
icd_code?: string;
report_date: string;
conclusion: string;
cid_code: string;
content_html: string;
content_json: any;
status: string;
requested_by: string;
due_at: string;
hide_date: boolean;
hide_signature: boolean;
created_at: string;
updated_at: string;
// Dados expandidos (quando incluir dados relacionados)
patient?: {
id: string;
full_name: string;
cpf?: string;
birth_date?: string;
};
doctor?: {
id: string;
full_name: string;
crm?: string;
specialty?: string;
};
created_by: string;
}
export interface CreateReportData {
patient_id: string;
order_number: string;
exam: string;
diagnosis: string;
conclusion: string;
cid_code: string;
content_html: string;
content_json: any;
status: string;
requested_by: string;
due_at: string;
hide_date: boolean;
hide_signature: boolean;
created_by: string;
}
export interface UpdateReportData extends Partial<CreateReportData> {
updated_at?: string;
}
export type ReportsResponse = Report[];
export type ReportResponse = Report;
// Dados para criar um novo relatório
export interface CreateReportData {
patient_id: string;
doctor_id: string;
report_type: string;
chief_complaint: string;
clinical_history: string;
symptoms_and_signs: string;
physical_examination: string;
complementary_exams: string;
exam_results: string;
order_number: string;
exam: string;
diagnosis: string;
prognosis?: string;
treatment_performed: string;
objective_recommendations: string;
icd_code?: string;
report_date: string;
conclusion: string;
cid_code: string;
content_html: string;
content_json: any;
status: string;
requested_by: string;
due_at: string;
hide_date: boolean;
hide_signature: boolean;
}
// Dados para atualizar um relatório existente
@ -66,18 +72,6 @@ export interface UpdateReportData extends Partial<CreateReportData> {
}
// Resposta da API ao listar relatórios
export interface ReportsResponse {
data: Report[];
success: boolean;
message?: string;
}
// Resposta da API ao criar/atualizar um relatório
export interface ReportResponse {
data: Report;
success: boolean;
message?: string;
}
// Dados do formulário (adaptado para a estrutura do front-end existente)
export interface ReportFormData {
@ -86,15 +80,19 @@ export interface ReportFormData {
profissionalCrm: string;
// Identificação do Paciente
pacienteId: string;
pacienteNome: string;
pacienteCpf: string;
pacienteIdade: string;
// Informações do Relatório
motivoRelatorio: string;
cid?: string;
dataRelatorio: string;
patient_id: string;
report_type: string;
symptoms_and_signs: string;
diagnosis: string;
prognosis?: string;
treatment_performed: string;
icd_code?: string;
report_date: string;
hipotesesDiagnosticas: string;
condutaMedica: string;
prescricoes: string;
retornoAgendado: string;
// cid10: string; // Removed, not present in schema
// Histórico Clínico
historicoClinico: string;
@ -104,4 +102,4 @@ export interface ReportFormData {
examesRealizados: string;
resultadosExames: string;
// ...restante do código...
}