diff --git a/app/secretary/pacientes/page.tsx b/app/secretary/pacientes/page.tsx
index c72bb85..4df1802 100644
--- a/app/secretary/pacientes/page.tsx
+++ b/app/secretary/pacientes/page.tsx
@@ -8,6 +8,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@
import { Plus, Edit, Trash2, Eye, Calendar, Filter } from "lucide-react";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
import SecretaryLayout from "@/components/secretary-layout";
+import { patientsService } from "@/services/patientsApi.mjs"
export default function PacientesPage() {
const [searchTerm, setSearchTerm] = useState("");
@@ -28,40 +29,41 @@ export default function PacientesPage() {
setDetailsDialogOpen(true);
setPatientDetails(null);
try {
- const res = await fetch(`https://mock.apidog.com/m1/1053378-0-default/pacientes/${patientId}`);
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- const json = await res.json();
- setPatientDetails(json?.data ?? null);
+ const res = await patientsService.getById(patientId);
+ setPatientDetails(res[0]);
} catch (e: any) {
setPatientDetails({ error: e?.message || "Erro ao buscar detalhes" });
}
};
-
+
const fetchPacientes = useCallback(
async (pageToFetch: number) => {
if (isFetching || !hasNext) return;
setIsFetching(true);
setError(null);
try {
- const res = await fetch(`https://mock.apidog.com/m1/1053378-0-default/pacientes?page=${pageToFetch}&limit=20`);
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- const json = await res.json();
- const items = Array.isArray(json?.data) ? json.data : [];
- const mapped = items.map((p: any) => ({
- id: String(p.id ?? ""),
- nome: p.nome ?? "",
- telefone: p?.contato?.celular ?? p?.contato?.telefone1 ?? p?.telefone ?? "",
- cidade: p?.endereco?.cidade ?? p?.cidade ?? "",
- estado: p?.endereco?.estado ?? p?.estado ?? "",
- ultimoAtendimento: p.ultimo_atendimento ?? p.ultimoAtendimento ?? undefined,
- proximoAtendimento: p.proximo_atendimento ?? p.proximoAtendimento ?? undefined,
- convenio: p.convenio ?? "",
- vip: Boolean(p.vip ?? false),
- status: p.status ?? undefined,
- }));
- setPatients((prev) => [...prev, ...mapped]);
- setHasNext(Boolean(json?.pagination?.has_next));
- setPage(pageToFetch + 1);
+ const res = await patientsService.list();
+ const mapped = res.map((p: any) => ({
+ id: String(p.id ?? ""),
+ nome: p.full_name ?? "",
+ telefone: p.phone_mobile ?? p.phone1 ?? "",
+ cidade: p.city ?? "",
+ estado: p.state ?? "",
+ ultimoAtendimento: p.last_visit_at ?? "",
+ proximoAtendimento: p.next_appointment_at ?? "",
+ vip: Boolean(p.vip ?? false),
+ convenio: p.convenio ?? "", // se não existir, fica vazio
+ status: p.status ?? undefined,
+ }));
+
+ setPatients((prev) => {
+ const all = [...prev, ...mapped];
+ const unique = Array.from(new Map(all.map(p => [p.id, p])).values());
+ return unique;
+ });
+
+ if (mapped.length === 0) setHasNext(false); // parar carregamento
+ else setPage(prev => prev + 1);
} catch (e: any) {
setError(e?.message || "Erro ao buscar pacientes");
} finally {
@@ -89,9 +91,21 @@ export default function PacientesPage() {
};
}, [fetchPacientes, page, hasNext, isFetching]);
- const handleDeletePatient = (patientId: string) => {
+ const handleDeletePatient = async (patientId: string) => {
// Remove from current list (client-side deletion)
- setPatients((prev) => prev.filter((p) => String(p.id) !== String(patientId)));
+ try{
+ const res = await patientsService.delete(patientId);
+
+ if(res){
+ alert(`${res.error} ${res.message}`)
+ }
+
+ setPatients((prev) => prev.filter((p) => String(p.id) !== String(patientId)));
+
+
+ } catch (e: any) {
+ setError(e?.message || "Erro ao deletar paciente");
+ }
setDeleteDialogOpen(false);
setPatientToDelete(null);
};
@@ -311,33 +325,24 @@ export default function PacientesPage() {
{patientDetails.error}
) : (
-
- Nome: {patientDetails.nome}
-
-
- Telefone: {patientDetails?.contato?.celular ?? patientDetails?.contato?.telefone1 ?? patientDetails?.telefone ?? ""}
-
-
- Cidade: {patientDetails?.endereco?.cidade ?? patientDetails?.cidade ?? ""}
-
-
- Estado: {patientDetails?.endereco?.estado ?? patientDetails?.estado ?? ""}
-
-
- Convênio: {patientDetails.convenio ?? ""}
-
-
- VIP: {patientDetails.vip ? "Sim" : "Não"}
-
-
- Status: {patientDetails.status ?? ""}
-
-
- Último atendimento: {patientDetails.ultimo_atendimento ?? patientDetails.ultimoAtendimento ?? ""}
-
-
- Próximo atendimento: {patientDetails.proximo_atendimento ?? patientDetails.proximoAtendimento ?? ""}
-
+
Nome: {patientDetails.full_name}
+
CPF: {patientDetails.cpf}
+
Email: {patientDetails.email}
+
Telefone: {patientDetails.phone_mobile ?? patientDetails.phone1 ?? patientDetails.phone2 ?? "-"}
+
Nome social: {patientDetails.social_name ?? "-"}
+
Sexo: {patientDetails.sex ?? "-"}
+
Tipo sanguíneo: {patientDetails.blood_type ?? "-"}
+
Peso: {patientDetails.weight_kg ?? "-"}{patientDetails.weight_kg ? "kg": ""}
+
Altura: {patientDetails.height_m ?? "-"}{patientDetails.height_m ? "m": ""}
+
IMC: {patientDetails.bmi ?? "-"}
+
Endereço: {patientDetails.street ?? "-"}
+
Bairro: {patientDetails.neighborhood ?? "-"}
+
Cidade: {patientDetails.city ?? "-"}
+
Estado: {patientDetails.state ?? "-"}
+
CEP: {patientDetails.cep ?? "-"}
+
Criado em: {patientDetails.created_at ?? "-"}
+
Atualizado em: {patientDetails.updated_at ?? "-"}
+
Id: {patientDetails.id ?? "-"}
)}
diff --git a/components/secretary-layout.tsx b/components/secretary-layout.tsx
index c7805dc..78d817c 100644
--- a/components/secretary-layout.tsx
+++ b/components/secretary-layout.tsx
@@ -66,13 +66,13 @@ export default function SecretaryLayout({ children }: PatientLayoutProps) {
const menuItems = [
{
- href: "#",
+ href: "##",
icon: Home,
label: "Dashboard",
// Botão para o dashboard da secretária
},
{
- href: "#",
+ href: "###",
icon: Calendar,
label: "Consultas",
// Botão para página de consultas marcadas
diff --git a/services/api.mjs b/services/api.mjs
index 493d8c8..f8ee049 100644
--- a/services/api.mjs
+++ b/services/api.mjs
@@ -4,36 +4,38 @@ const BASE_URL = "https://yuanqfswhberkoevtmfr.supabase.co";
const API_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Inl1YW5xZnN3aGJlcmtvZXZ0bWZyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTQ5NTQzNjksImV4cCI6MjA3MDUzMDM2OX0.g8Fm4XAvtX46zifBZnYVH4tVuQkqUH6Ia9CXQj4DztQ";
var tempToken;
-async function login() {
+export async function login() {
const response = await fetch("https://yuanqfswhberkoevtmfr.supabase.co/auth/v1/token?grant_type=password", {
method: "POST",
headers: {
"Content-Type": "application/json",
+ Prefer: "return=representation",
"apikey": API_KEY, // valor fixo
},
- body: JSON.stringify({ email: "hugo@popcode.com.br", password: "hdoria" }),
+ body: JSON.stringify({ email: "riseup@popcode.com.br", password: "riseup" }),
});
const data = await response.json();
-
- console.log("Resposta da API:", data);
- console.log("Token:", data.access_token);
// salvar o token do usuário
- //localStorage.setItem("token", data.access_token);
- tempToken = data.access_token
+ localStorage.setItem("token", data.access_token);
+
return data;
}
-await login()
+
+async function run(){
+ await login()
+}
+run()
async function request(endpoint, options = {}) {
- //const token = localStorage.getItem("token"); // token do usuário, salvo no login
- const token = tempToken;
+ const token = localStorage.getItem("token"); // token do usuário, salvo no login
+
const headers = {
"Content-Type": "application/json",
"apikey": API_KEY, // obrigatório sempre
- ...(token ? { Authorization: `Bearer ${token}` } : {}), // obrigatório em todas EXCETO login
+ ...(token ? { "Authorization": `Bearer ${token}` } : {}), // obrigatório em todas EXCETO login
...options.headers,
};
@@ -44,10 +46,19 @@ async function request(endpoint, options = {}) {
});
if (!response.ok) {
+ const text = await response.text();
+ console.error("Erro HTTP:", response.status, text);
throw new Error(`Erro HTTP: ${response.status}`);
}
- return await response.json();
+ // Lê a resposta como texto
+ const text = await response.text();
+
+ // Se não tiver conteúdo (204 ou 201 sem body), retorna null
+ if (!text) return null;
+
+ // Se tiver conteúdo, parseia como JSON
+ return JSON.parse(text);
} catch (error) {
console.error("Erro na requisição:", error);
throw error;
diff --git a/services/patientsApi.mjs b/services/patientsApi.mjs
index 5f0571b..2a5ba54 100644
--- a/services/patientsApi.mjs
+++ b/services/patientsApi.mjs
@@ -2,8 +2,8 @@ import { api } from "./api.mjs";
export const patientsService = {
list: () => api.get("/rest/v1/patients"),
- getById: (id) => api.get(`/rest/v1/patients/${id}`),
+ getById: (id) => api.get(`/rest/v1/patients?id=eq.${id}`),
create: (data) => api.post("/rest/v1/patients", data),
- update: (id, data) => api.patch(`/rest/v1/patients/${id}`, data),
- delete: (id) => api.delete(`/rest/v1/patients/${id}`),
+ update: (id, data) => api.patch(`/rest/v1/patients?id=eq.${id}`, data),
+ delete: (id) => api.delete(`/rest/v1/patients?id=eq.${id}`),
};