Merge remote-tracking branch 'upstream/troca-de-api'
This commit is contained in:
commit
a96082e1f6
@ -117,7 +117,7 @@ export default function HomePage() {
|
||||
<span>Gestão de usuários</span>
|
||||
</div>
|
||||
</div>
|
||||
<Link href="#" className="block mt-auto">
|
||||
<Link href="/manager/login" className="block mt-auto">
|
||||
<Button className="w-full bg-blue-600 hover:bg-blue-700">Entrar como Gestor</Button>
|
||||
</Link>
|
||||
</CardContent>
|
||||
@ -144,7 +144,7 @@ export default function HomePage() {
|
||||
<span>Controle de pagamentos</span>
|
||||
</div>
|
||||
</div>
|
||||
<Link href="#" className="block mt-auto">
|
||||
<Link href="finance/login" className="block mt-auto">
|
||||
<Button className="w-full bg-orange-600 hover:bg-orange-700">Entrar como Financeiro</Button>
|
||||
</Link>
|
||||
</CardContent>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,479 +1,534 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import Link from "next/link"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import { Upload, Plus, X, ChevronDown } from "lucide-react"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import { Upload, X, ChevronDown, Save, Loader2 } from "lucide-react"
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"
|
||||
import ManagerLayout from "@/components/manager-layout"
|
||||
import { doctorsService } from "services/doctorsApi.mjs";
|
||||
|
||||
|
||||
const UF_LIST = ["AC", "AL", "AP", "AM", "BA", "CE", "DF", "ES", "GO", "MA", "MT", "MS", "MG", "PA", "PB", "PR", "PE", "PI", "RJ", "RN", "RS", "RO", "RR", "SC", "SP", "SE", "TO"];
|
||||
|
||||
|
||||
|
||||
interface DoctorFormData {
|
||||
|
||||
nomeCompleto: string;
|
||||
crm: string;
|
||||
crmEstado: string;
|
||||
cpf: string;
|
||||
email: string;
|
||||
especialidade: string;
|
||||
telefoneCelular: string;
|
||||
telefone2: string;
|
||||
cep: string;
|
||||
endereco: string;
|
||||
numero: string;
|
||||
complemento: string;
|
||||
bairro: string;
|
||||
cidade: string;
|
||||
estado: string;
|
||||
dataNascimento: string;
|
||||
rg: string;
|
||||
ativo: boolean;
|
||||
observacoes: string;
|
||||
anexos: { id: number, name: string }[];
|
||||
}
|
||||
|
||||
|
||||
const apiMap: { [K in keyof DoctorFormData]: string | null } = {
|
||||
nomeCompleto: 'full_name',
|
||||
crm: 'crm',
|
||||
crmEstado: 'crm_uf',
|
||||
cpf: 'cpf',
|
||||
email: 'email',
|
||||
|
||||
especialidade: 'specialty',
|
||||
telefoneCelular: 'phone_mobile',
|
||||
telefone2: 'phone2',
|
||||
cep: 'cep',
|
||||
endereco: 'street',
|
||||
numero: 'number',
|
||||
complemento: 'complement',
|
||||
bairro: 'neighborhood',
|
||||
cidade: 'city',
|
||||
estado: 'state',
|
||||
dataNascimento: 'birth_date',
|
||||
rg: 'rg',
|
||||
ativo: 'active',
|
||||
|
||||
observacoes: null,
|
||||
anexos: null,
|
||||
};
|
||||
|
||||
|
||||
const defaultFormData: DoctorFormData = {
|
||||
nomeCompleto: '', crm: '', crmEstado: '', cpf: '', email: '',
|
||||
especialidade: '', telefoneCelular: '', telefone2: '', cep: '',
|
||||
endereco: '', numero: '', complemento: '', bairro: '', cidade: '', estado: '',
|
||||
dataNascimento: '', rg: '', ativo: true,
|
||||
observacoes: '', anexos: [],
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
const cleanNumber = (value: string): string => value.replace(/\D/g, '');
|
||||
|
||||
const formatCPF = (value: string): string => {
|
||||
const cleaned = cleanNumber(value).substring(0, 11);
|
||||
return cleaned.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3-$4');
|
||||
};
|
||||
|
||||
const formatCEP = (value: string): string => {
|
||||
const cleaned = cleanNumber(value).substring(0, 8);
|
||||
return cleaned.replace(/(\d{5})(\d{3})/, '$1-$2');
|
||||
};
|
||||
|
||||
const formatPhoneMobile = (value: string): string => {
|
||||
const cleaned = cleanNumber(value).substring(0, 11);
|
||||
if (cleaned.length > 10) {
|
||||
return cleaned.replace(/(\d{2})(\d{5})(\d{4})/, '($1) $2-$3');
|
||||
}
|
||||
return cleaned.replace(/(\d{2})(\d{4})(\d{4})/, '($1) $2-$3');
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
export default function NovoMedicoPage() {
|
||||
const [anexosOpen, setAnexosOpen] = useState(false)
|
||||
const [anexos, setAnexos] = useState<string[]>([])
|
||||
const router = useRouter();
|
||||
const [formData, setFormData] = useState<DoctorFormData>(defaultFormData);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [anexosOpen, setAnexosOpen] = useState(false);
|
||||
|
||||
|
||||
const handleInputChange = (key: keyof DoctorFormData, value: string | boolean | { id: number, name: string }[]) => {
|
||||
|
||||
|
||||
if (typeof value === 'string') {
|
||||
let maskedValue = value;
|
||||
if (key === 'cpf') maskedValue = formatCPF(value);
|
||||
if (key === 'cep') maskedValue = formatCEP(value);
|
||||
if (key === 'telefoneCelular' || key === 'telefone2') maskedValue = formatPhoneMobile(value);
|
||||
|
||||
setFormData((prev) => ({ ...prev, [key]: maskedValue }));
|
||||
} else {
|
||||
setFormData((prev) => ({ ...prev, [key]: value }));
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
const adicionarAnexo = () => {
|
||||
setAnexos([...anexos, `Documento ${anexos.length + 1}`])
|
||||
const newId = Date.now();
|
||||
handleInputChange('anexos', [...formData.anexos, { id: newId, name: `Documento ${formData.anexos.length + 1}` }]);
|
||||
}
|
||||
|
||||
const removerAnexo = (index: number) => {
|
||||
setAnexos(anexos.filter((_, i) => i !== index))
|
||||
const removerAnexo = (id: number) => {
|
||||
handleInputChange('anexos', formData.anexos.filter((anexo) => anexo.id !== id));
|
||||
}
|
||||
|
||||
|
||||
const requiredFields = [
|
||||
{ key: 'nomeCompleto', name: 'Nome Completo' },
|
||||
{ key: 'crm', name: 'CRM' },
|
||||
{ key: 'crmEstado', name: 'UF do CRM' },
|
||||
{ key: 'cpf', name: 'CPF' },
|
||||
{ key: 'email', name: 'E-mail' },
|
||||
] as const;
|
||||
|
||||
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setIsSaving(true);
|
||||
|
||||
|
||||
for (const field of requiredFields) {
|
||||
let valueToCheck = formData[field.key];
|
||||
|
||||
|
||||
if (!valueToCheck || String(valueToCheck).trim() === '') {
|
||||
setError(`O campo obrigatório "${field.name}" deve ser preenchido.`);
|
||||
setIsSaving(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const finalPayload: { [key: string]: any } = {};
|
||||
const formKeys = Object.keys(formData) as Array<keyof DoctorFormData>;
|
||||
|
||||
|
||||
formKeys.forEach((key) => {
|
||||
const apiFieldName = apiMap[key];
|
||||
|
||||
if (!apiFieldName) return;
|
||||
|
||||
let value = formData[key];
|
||||
|
||||
if (typeof value === 'string') {
|
||||
let trimmedValue = value.trim();
|
||||
|
||||
|
||||
const isOptional = !requiredFields.some(f => f.key === key);
|
||||
|
||||
if (isOptional && trimmedValue === '') {
|
||||
finalPayload[apiFieldName] = null;
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (key === 'crmEstado' || key === 'estado') {
|
||||
trimmedValue = trimmedValue.toUpperCase();
|
||||
}
|
||||
|
||||
value = trimmedValue;
|
||||
}
|
||||
|
||||
finalPayload[apiFieldName] = value;
|
||||
});
|
||||
|
||||
|
||||
try {
|
||||
|
||||
const response = await doctorsService.create(finalPayload);
|
||||
router.push("/manager/home");
|
||||
} catch (e: any) {
|
||||
console.error("Erro ao salvar o médico:", e);
|
||||
|
||||
let detailedError = `Erro na requisição. Verifique se o **CRM** ou **CPF** já existem ou se as **Máscaras/Datas** estão incorretas.`;
|
||||
|
||||
|
||||
if (e.message && e.message.includes("duplicate key value violates unique constraint")) {
|
||||
|
||||
detailedError = "O CPF ou CRM informado já está cadastrado no sistema. Por favor, verifique os dados de identificação.";
|
||||
} else if (e.message && e.message.includes("Detalhes:")) {
|
||||
|
||||
detailedError = e.message.split("Detalhes:")[1].trim();
|
||||
} else if (e.message) {
|
||||
detailedError = e.message;
|
||||
}
|
||||
|
||||
setError(`Erro ao cadastrar. Detalhes: ${detailedError}`);
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<ManagerLayout>
|
||||
<div className="space-y-6">
|
||||
<div className="w-full space-y-6 p-4 md:p-8">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Novo Médico</h1>
|
||||
<p className="text-gray-600">Cadastre um novo médico no sistema</p>
|
||||
<p className="text-sm text-gray-500">
|
||||
Preencha os dados do novo médico para cadastro.
|
||||
</p>
|
||||
</div>
|
||||
<Link href="/manager/home">
|
||||
<Button variant="outline">Cancelar</Button>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<form className="space-y-6">
|
||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Dados Pessoais</h2>
|
||||
|
||||
<div className="space-y-6">
|
||||
{/* Foto */}
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center">
|
||||
<Upload className="w-8 h-8 text-gray-400" />
|
||||
</div>
|
||||
<Button variant="outline" type="button" size="sm">
|
||||
<Upload className="w-4 h-4 mr-2" />
|
||||
Carregar Foto
|
||||
</Button>
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
|
||||
{error && (
|
||||
<div className="p-3 bg-red-100 text-red-700 rounded-lg border border-red-300">
|
||||
<p className="font-medium">Erro no Cadastro:</p>
|
||||
<p className="text-sm">{error}</p>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="nome" className="text-sm font-medium text-gray-700">
|
||||
Nome *
|
||||
</Label>
|
||||
<Input id="nome" placeholder="Nome completo" required className="mt-1" />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="nomeSocial" className="text-sm font-medium text-gray-700">
|
||||
Nome Social
|
||||
</Label>
|
||||
<Input id="nomeSocial" placeholder="Nome social ou apelido" className="mt-1" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
<div className="space-y-4">
|
||||
<h2 className="text-lg font-semibold text-gray-800 border-b pb-2">
|
||||
Dados Principais e Pessoais
|
||||
</h2>
|
||||
|
||||
|
||||
<div className="grid md:grid-cols-4 gap-4">
|
||||
<div className="space-y-2 col-span-2">
|
||||
<Label htmlFor="nomeCompleto">Nome Completo *</Label>
|
||||
<Input
|
||||
id="nomeCompleto"
|
||||
value={formData.nomeCompleto}
|
||||
onChange={(e) => handleInputChange("nomeCompleto", e.target.value)}
|
||||
placeholder="Nome do Médico"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-3 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="cpf" className="text-sm font-medium text-gray-700">
|
||||
CPF *
|
||||
</Label>
|
||||
<Input id="cpf" placeholder="000.000.000-00" required className="mt-1" />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="rg" className="text-sm font-medium text-gray-700">
|
||||
RG
|
||||
</Label>
|
||||
<Input id="rg" placeholder="00.000.000-0" className="mt-1" />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="crm" className="text-sm font-medium text-gray-700">
|
||||
CRM *
|
||||
</Label>
|
||||
<Input id="crm" placeholder="CRM/UF 12345" required className="mt-1" />
|
||||
</div>
|
||||
<div className="space-y-2 col-span-1">
|
||||
<Label htmlFor="crm">CRM *</Label>
|
||||
<Input
|
||||
id="crm"
|
||||
value={formData.crm}
|
||||
onChange={(e) => handleInputChange("crm", e.target.value)}
|
||||
placeholder="Ex: 123456"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="outrosDocumentos" className="text-sm font-medium text-gray-700">
|
||||
Outros Documentos
|
||||
</Label>
|
||||
<Select>
|
||||
<SelectTrigger className="mt-1">
|
||||
<SelectValue placeholder="Selecione" />
|
||||
<div className="space-y-2 col-span-1">
|
||||
<Label htmlFor="crmEstado">UF do CRM *</Label>
|
||||
<Select value={formData.crmEstado} onValueChange={(v) => handleInputChange("crmEstado", v)}>
|
||||
<SelectTrigger id="crmEstado">
|
||||
<SelectValue placeholder="UF" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="cnh">CNH</SelectItem>
|
||||
<SelectItem value="passaporte">Passaporte</SelectItem>
|
||||
<SelectItem value="carteira-trabalho">Carteira de Trabalho</SelectItem>
|
||||
{UF_LIST.map(uf => (
|
||||
<SelectItem key={uf} value={uf}>{uf}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-3 gap-4">
|
||||
<div>
|
||||
<Label className="text-sm font-medium text-gray-700">Sexo</Label>
|
||||
<div className="flex gap-4 mt-2">
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="radio" name="sexo" value="masculino" className="text-blue-600" />
|
||||
<span className="text-sm">Masculino</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="radio" name="sexo" value="feminino" className="text-blue-600" />
|
||||
<span className="text-sm">Feminino</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="dataNascimento" className="text-sm font-medium text-gray-700">
|
||||
Data de Nascimento
|
||||
</Label>
|
||||
<Input id="dataNascimento" type="date" className="mt-1" />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="estadoCivil" className="text-sm font-medium text-gray-700">
|
||||
Estado Civil
|
||||
</Label>
|
||||
<Select>
|
||||
<SelectTrigger className="mt-1">
|
||||
<SelectValue placeholder="Selecione" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="solteiro">Solteiro(a)</SelectItem>
|
||||
<SelectItem value="casado">Casado(a)</SelectItem>
|
||||
<SelectItem value="divorciado">Divorciado(a)</SelectItem>
|
||||
<SelectItem value="viuvo">Viúvo(a)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="etnia" className="text-sm font-medium text-gray-700">
|
||||
Etnia
|
||||
</Label>
|
||||
<Select>
|
||||
<SelectTrigger className="mt-1">
|
||||
<SelectValue placeholder="Selecione" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="branca">Branca</SelectItem>
|
||||
<SelectItem value="preta">Preta</SelectItem>
|
||||
<SelectItem value="parda">Parda</SelectItem>
|
||||
<SelectItem value="amarela">Amarela</SelectItem>
|
||||
<SelectItem value="indigena">Indígena</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="raca" className="text-sm font-medium text-gray-700">
|
||||
Raça
|
||||
</Label>
|
||||
<Select>
|
||||
<SelectTrigger className="mt-1">
|
||||
<SelectValue placeholder="Selecione" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="branca">Branca</SelectItem>
|
||||
<SelectItem value="preta">Preta</SelectItem>
|
||||
<SelectItem value="parda">Parda</SelectItem>
|
||||
<SelectItem value="amarela">Amarela</SelectItem>
|
||||
<SelectItem value="indigena">Indígena</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="naturalidade" className="text-sm font-medium text-gray-700">
|
||||
Naturalidade
|
||||
</Label>
|
||||
<Select>
|
||||
<SelectTrigger className="mt-1">
|
||||
<SelectValue placeholder="Selecione" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="aracaju">Aracaju</SelectItem>
|
||||
<SelectItem value="salvador">Salvador</SelectItem>
|
||||
<SelectItem value="recife">Recife</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="nacionalidade" className="text-sm font-medium text-gray-700">
|
||||
Nacionalidade
|
||||
</Label>
|
||||
<Select>
|
||||
<SelectTrigger className="mt-1">
|
||||
<SelectValue placeholder="Selecione" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="brasileira">Brasileira</SelectItem>
|
||||
<SelectItem value="estrangeira">Estrangeira</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="profissao" className="text-sm font-medium text-gray-700">
|
||||
Profissão
|
||||
</Label>
|
||||
<Input id="profissao" placeholder="Médico" className="mt-1" />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="especialidade" className="text-sm font-medium text-gray-700">
|
||||
Especialidade *
|
||||
</Label>
|
||||
<Select>
|
||||
<SelectTrigger className="mt-1">
|
||||
<SelectValue placeholder="Selecione" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="cardiologia">Cardiologia</SelectItem>
|
||||
<SelectItem value="pediatria">Pediatria</SelectItem>
|
||||
<SelectItem value="ortopedia">Ortopedia</SelectItem>
|
||||
<SelectItem value="ginecologia">Ginecologia</SelectItem>
|
||||
<SelectItem value="neurologia">Neurologia</SelectItem>
|
||||
<SelectItem value="dermatologia">Dermatologia</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="nomeMae" className="text-sm font-medium text-gray-700">
|
||||
Nome da Mãe
|
||||
</Label>
|
||||
<Input id="nomeMae" placeholder="Nome da mãe" className="mt-1" />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="nomePai" className="text-sm font-medium text-gray-700">
|
||||
Nome do Pai
|
||||
</Label>
|
||||
<Input id="nomePai" placeholder="Nome do pai" className="mt-1" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="nomeEsposo" className="text-sm font-medium text-gray-700">
|
||||
Nome do Esposo(a)
|
||||
</Label>
|
||||
<Input id="nomeEsposo" placeholder="Nome do esposo(a)" className="mt-1" />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="codigoLegado" className="text-sm font-medium text-gray-700">
|
||||
Código Legado
|
||||
</Label>
|
||||
<Input id="codigoLegado" placeholder="Código do sistema anterior" className="mt-1" />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="observacoes" className="text-sm font-medium text-gray-700">
|
||||
Observações
|
||||
</Label>
|
||||
<Textarea
|
||||
id="observacoes"
|
||||
placeholder="Observações gerais sobre o médico"
|
||||
className="min-h-[100px] mt-1"
|
||||
</div>
|
||||
|
||||
|
||||
<div className="grid md:grid-cols-3 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="especialidade">Especialidade</Label>
|
||||
<Input
|
||||
id="especialidade"
|
||||
value={formData.especialidade}
|
||||
onChange={(e) => handleInputChange("especialidade", e.target.value)}
|
||||
placeholder="Ex: Cardiologia"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="cpf">CPF *</Label>
|
||||
<Input
|
||||
id="cpf"
|
||||
value={formData.cpf}
|
||||
onChange={(e) => handleInputChange("cpf", e.target.value)}
|
||||
placeholder="000.000.000-00"
|
||||
maxLength={14}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="rg">RG</Label>
|
||||
<Input
|
||||
id="rg"
|
||||
value={formData.rg}
|
||||
onChange={(e) => handleInputChange("rg", e.target.value)}
|
||||
placeholder="00.000.000-0"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="grid md:grid-cols-3 gap-4">
|
||||
<div className="space-y-2 col-span-2">
|
||||
<Label htmlFor="email">E-mail *</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
value={formData.email}
|
||||
onChange={(e) => handleInputChange("email", e.target.value)}
|
||||
placeholder="exemplo@dominio.com"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2 col-span-1">
|
||||
<Label htmlFor="dataNascimento">Data de Nascimento</Label>
|
||||
<Input
|
||||
id="dataNascimento"
|
||||
type="date"
|
||||
value={formData.dataNascimento}
|
||||
onChange={(e) => handleInputChange("dataNascimento", e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Collapsible open={anexosOpen} onOpenChange={setAnexosOpen}>
|
||||
<CollapsibleTrigger asChild>
|
||||
<Button variant="ghost" type="button" className="w-full justify-between p-0 h-auto text-left">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-4 h-4 bg-gray-400 rounded-sm flex items-center justify-center">
|
||||
<span className="text-white text-xs">📎</span>
|
||||
|
||||
<div className="space-y-4">
|
||||
<h2 className="text-lg font-semibold text-gray-800 border-b pb-2">
|
||||
Contato e Endereço
|
||||
</h2>
|
||||
|
||||
|
||||
<div className="grid md:grid-cols-3 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="telefoneCelular">Telefone Celular</Label>
|
||||
<Input
|
||||
id="telefoneCelular"
|
||||
value={formData.telefoneCelular}
|
||||
onChange={(e) => handleInputChange("telefoneCelular", e.target.value)}
|
||||
placeholder="(00) 00000-0000"
|
||||
maxLength={15}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="telefone2">Telefone Adicional</Label>
|
||||
<Input
|
||||
id="telefone2"
|
||||
value={formData.telefone2}
|
||||
onChange={(e) => handleInputChange("telefone2", e.target.value)}
|
||||
placeholder="(00) 00000-0000"
|
||||
maxLength={15}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2 flex items-end justify-center pb-1">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id="ativo"
|
||||
checked={formData.ativo}
|
||||
onCheckedChange={(checked) => handleInputChange("ativo", checked === true)}
|
||||
/>
|
||||
<Label htmlFor="ativo">Médico Ativo</Label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="grid md:grid-cols-4 gap-4">
|
||||
<div className="space-y-2 col-span-1">
|
||||
<Label htmlFor="cep">CEP</Label>
|
||||
<Input
|
||||
id="cep"
|
||||
value={formData.cep}
|
||||
onChange={(e) => handleInputChange("cep", e.target.value)}
|
||||
placeholder="00000-000"
|
||||
maxLength={9}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2 col-span-3">
|
||||
<Label htmlFor="endereco">Rua</Label>
|
||||
<Input
|
||||
id="endereco"
|
||||
value={formData.endereco}
|
||||
onChange={(e) => handleInputChange("endereco", e.target.value)}
|
||||
placeholder="Rua, Avenida, etc."
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid md:grid-cols-4 gap-4">
|
||||
<div className="space-y-2 col-span-1">
|
||||
<Label htmlFor="numero">Número</Label>
|
||||
<Input
|
||||
id="numero"
|
||||
value={formData.numero}
|
||||
onChange={(e) => handleInputChange("numero", e.target.value)}
|
||||
placeholder="123"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2 col-span-3">
|
||||
<Label htmlFor="complemento">Complemento</Label>
|
||||
<Input
|
||||
id="complemento"
|
||||
value={formData.complemento}
|
||||
onChange={(e) => handleInputChange("complemento", e.target.value)}
|
||||
placeholder="Apto, Bloco, etc."
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid md:grid-cols-4 gap-4">
|
||||
<div className="space-y-2 col-span-2">
|
||||
<Label htmlFor="bairro">Bairro</Label>
|
||||
<Input
|
||||
id="bairro"
|
||||
value={formData.bairro}
|
||||
onChange={(e) => handleInputChange("bairro", e.target.value)}
|
||||
placeholder="Bairro"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2 col-span-1">
|
||||
<Label htmlFor="estado">Estado</Label>
|
||||
<Input
|
||||
id="estado"
|
||||
value={formData.estado}
|
||||
onChange={(e) => handleInputChange("estado", e.target.value)}
|
||||
placeholder="SP"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2 col-span-1">
|
||||
<Label htmlFor="cidade">Cidade</Label>
|
||||
<Input
|
||||
id="cidade"
|
||||
value={formData.cidade}
|
||||
onChange={(e) => handleInputChange("cidade", e.target.value)}
|
||||
placeholder="São Paulo"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="space-y-4">
|
||||
<h2 className="text-lg font-semibold text-gray-800 border-b pb-2">
|
||||
Outras Informações (Internas)
|
||||
</h2>
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="observacoes">Observações (Apenas internas)</Label>
|
||||
<Textarea
|
||||
id="observacoes"
|
||||
value={formData.observacoes}
|
||||
onChange={(e) => handleInputChange("observacoes", e.target.value)}
|
||||
placeholder="Notas internas sobre o médico..."
|
||||
className="min-h-[100px]"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-4">
|
||||
<Collapsible open={anexosOpen} onOpenChange={setAnexosOpen}>
|
||||
<CollapsibleTrigger asChild>
|
||||
<div className="flex justify-between items-center cursor-pointer pb-2 border-b">
|
||||
<h2 className="text-md font-semibold text-gray-800">Anexos ({formData.anexos.length})</h2>
|
||||
<ChevronDown className={`w-5 h-5 transition-transform ${anexosOpen ? 'rotate-180' : 'rotate-0'}`} />
|
||||
</div>
|
||||
<span className="text-sm font-medium text-gray-700">Anexos do médico</span>
|
||||
</div>
|
||||
<ChevronDown className={`w-4 h-4 transition-transform ${anexosOpen ? "rotate-180" : ""}`} />
|
||||
</Button>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent className="space-y-4 mt-4">
|
||||
{anexos.map((anexo, index) => (
|
||||
<div key={index} className="flex items-center justify-between p-3 border rounded-lg bg-gray-50">
|
||||
<span className="text-sm">{anexo}</span>
|
||||
<Button variant="ghost" size="sm" onClick={() => removerAnexo(index)} type="button">
|
||||
<X className="w-4 h-4" />
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent className="space-y-4 pt-2">
|
||||
<Button type="button" onClick={adicionarAnexo} variant="outline" className="w-full">
|
||||
<Upload className="w-4 h-4 mr-2" />
|
||||
Adicionar Documento
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
<Button variant="outline" onClick={adicionarAnexo} type="button" size="sm">
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
Adicionar Anexo
|
||||
</Button>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Contato</h2>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="grid md:grid-cols-3 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="email" className="text-sm font-medium text-gray-700">
|
||||
E-mail
|
||||
</Label>
|
||||
<Input id="email" type="email" placeholder="email@exemplo.com" className="mt-1" />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="celular" className="text-sm font-medium text-gray-700">
|
||||
Celular
|
||||
</Label>
|
||||
<div className="flex mt-1">
|
||||
<Select>
|
||||
<SelectTrigger className="w-20 rounded-r-none">
|
||||
<SelectValue placeholder="+55" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="+55">+55</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Input placeholder="(XX) XXXXX-XXXX" className="rounded-l-none" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="telefone1" className="text-sm font-medium text-gray-700">
|
||||
Telefone 1
|
||||
</Label>
|
||||
<Input id="telefone1" placeholder="(XX) XXXX-XXXX" className="mt-1" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="telefone2" className="text-sm font-medium text-gray-700">
|
||||
Telefone 2
|
||||
</Label>
|
||||
<Input id="telefone2" placeholder="(XX) XXXX-XXXX" className="mt-1" />
|
||||
{formData.anexos.map((anexo) => (
|
||||
<div key={anexo.id} className="flex items-center justify-between p-3 bg-gray-50 border rounded-lg">
|
||||
<span className="text-sm text-gray-700">{anexo.name}</span>
|
||||
<Button type="button" variant="ghost" size="icon" onClick={() => removerAnexo(anexo.id)}>
|
||||
<X className="w-4 h-4 text-red-500" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Endereço</h2>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<Label htmlFor="cep" className="text-sm font-medium text-gray-700">
|
||||
CEP
|
||||
</Label>
|
||||
<Input id="cep" placeholder="00000-000" className="mt-1 max-w-xs" />
|
||||
</div>
|
||||
<div className="grid md:grid-cols-3 gap-4">
|
||||
<div className="md:col-span-2">
|
||||
<Label htmlFor="endereco" className="text-sm font-medium text-gray-700">
|
||||
Endereço
|
||||
</Label>
|
||||
<Input id="endereco" placeholder="Rua, Avenida..." className="mt-1" />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="numero" className="text-sm font-medium text-gray-700">
|
||||
Número
|
||||
</Label>
|
||||
<Input id="numero" placeholder="123" className="mt-1" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="complemento" className="text-sm font-medium text-gray-700">
|
||||
Complemento
|
||||
</Label>
|
||||
<Input id="complemento" placeholder="Apto, Bloco..." className="mt-1" />
|
||||
</div>
|
||||
<div className="grid md:grid-cols-3 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="bairro" className="text-sm font-medium text-gray-700">
|
||||
Bairro
|
||||
</Label>
|
||||
<Input id="bairro" placeholder="Bairro" className="mt-1" />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="cidade" className="text-sm font-medium text-gray-700">
|
||||
Cidade
|
||||
</Label>
|
||||
<Input id="cidade" placeholder="Cidade" className="mt-1" />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="estado" className="text-sm font-medium text-gray-700">
|
||||
Estado
|
||||
</Label>
|
||||
<Select>
|
||||
<SelectTrigger className="mt-1">
|
||||
<SelectValue placeholder="Selecione" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="SE">Sergipe</SelectItem>
|
||||
<SelectItem value="BA">Bahia</SelectItem>
|
||||
<SelectItem value="AL">Alagoas</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-lg border border-gray-200 p-6">
|
||||
<h2 className="text-lg font-semibold text-gray-900 mb-6">Informações Profissionais</h2>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="numeroConselho" className="text-sm font-medium text-gray-700">
|
||||
Número do Conselho
|
||||
</Label>
|
||||
<Input id="numeroConselho" placeholder="Número do CRM" className="mt-1" />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="ufConselho" className="text-sm font-medium text-gray-700">
|
||||
UF do Conselho
|
||||
</Label>
|
||||
<Select>
|
||||
<SelectTrigger className="mt-1">
|
||||
<SelectValue placeholder="Selecione" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="SE">SE</SelectItem>
|
||||
<SelectItem value="BA">BA</SelectItem>
|
||||
<SelectItem value="AL">AL</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="dataFormatura" className="text-sm font-medium text-gray-700">
|
||||
Data de Formatura
|
||||
</Label>
|
||||
<Input id="dataFormatura" type="date" className="mt-1" />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="instituicaoFormacao" className="text-sm font-medium text-gray-700">
|
||||
Instituição de Formação
|
||||
</Label>
|
||||
<Input id="instituicaoFormacao" placeholder="Nome da universidade" className="mt-1" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="especialidades" className="text-sm font-medium text-gray-700">
|
||||
Especialidades Adicionais
|
||||
</Label>
|
||||
<Textarea
|
||||
id="especialidades"
|
||||
placeholder="Liste outras especialidades ou subespecialidades..."
|
||||
className="min-h-[80px] mt-1"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-4">
|
||||
<div className="flex justify-end gap-4 pb-8 pt-4">
|
||||
<Link href="/manager/home">
|
||||
<Button variant="outline">Cancelar</Button>
|
||||
<Button type="button" variant="outline" disabled={isSaving}>
|
||||
Cancelar
|
||||
</Button>
|
||||
</Link>
|
||||
<Button type="submit" className="bg-green-600 hover:bg-green-700">
|
||||
Salvar Médico
|
||||
<Button
|
||||
type="submit"
|
||||
className="bg-green-600 hover:bg-green-700"
|
||||
disabled={isSaving}
|
||||
>
|
||||
{isSaving ? (
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
) : (
|
||||
<Save className="w-4 h-4 mr-2" />
|
||||
)}
|
||||
{isSaving ? "Salvando..." : "Salvar Médico"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</ManagerLayout>
|
||||
)
|
||||
}
|
||||
</ManagerLayout>
|
||||
);
|
||||
}
|
||||
@ -1,12 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState } from "react"
|
||||
import React, { useEffect, useState, useCallback } from "react"
|
||||
import ManagerLayout from "@/components/manager-layout";
|
||||
import Link from "next/link"
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import { Plus, Edit, Trash2, Eye, Calendar, Filter } from "lucide-react"
|
||||
import { Plus, Edit, Trash2, Eye, Calendar, Filter, MoreVertical, Loader2 } from "lucide-react"
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
@ -18,284 +19,307 @@ import {
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog"
|
||||
|
||||
import { doctorsService } from "services/doctorsApi.mjs";
|
||||
|
||||
|
||||
interface Doctor {
|
||||
id: number;
|
||||
full_name: string;
|
||||
specialty: string;
|
||||
crm: string;
|
||||
phone_mobile: string | null;
|
||||
city: string | null;
|
||||
state: string | null;
|
||||
|
||||
}
|
||||
|
||||
|
||||
interface DoctorDetails {
|
||||
nome: string;
|
||||
crm: string;
|
||||
especialidade: string;
|
||||
|
||||
contato: {
|
||||
celular?: string;
|
||||
telefone1?: string;
|
||||
}
|
||||
endereco: {
|
||||
cidade?: string;
|
||||
estado?: string;
|
||||
}
|
||||
convenio?: string;
|
||||
vip?: boolean;
|
||||
status?: string;
|
||||
ultimo_atendimento?: string;
|
||||
proximo_atendimento?: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export default function DoctorsPage() {
|
||||
const router = useRouter();
|
||||
|
||||
|
||||
const [doctors, setDoctors] = useState<Doctor[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
||||
const [doctorDetails, setDoctorDetails] = useState<DoctorDetails | null>(null);
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [doctorToDeleteId, setDoctorToDeleteId] = useState<number | null>(null);
|
||||
|
||||
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false)
|
||||
const [doctorDetails, setDoctorDetails] = useState<any | null>(null)
|
||||
const openDetailsDialog = async (doctorId: string) => {
|
||||
setDetailsDialogOpen(true)
|
||||
setDoctorDetails(null)
|
||||
try {
|
||||
const res = await fetch(`https://mock.apidog.com/m1/1053378-0-default/pacientes/${doctorId}`)
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`)
|
||||
const json = await res.json()
|
||||
setDoctorDetails(json?.data ?? null)
|
||||
} catch (e: any) {
|
||||
setDoctorDetails({ error: e?.message || "Erro ao buscar detalhes" })
|
||||
}
|
||||
}
|
||||
const [searchTerm, setSearchTerm] = useState("")
|
||||
const [especialidadeFilter, setEspecialidadeFilter] = useState("all")
|
||||
const [statusFilter, setStatusFilter] = useState("all")
|
||||
const [doctors, setDoctors] = useState<any[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
|
||||
const [doctorToDelete, setDoctorToDelete] = useState<string | null>(null)
|
||||
const [page, setPage] = useState(1)
|
||||
const [hasNext, setHasNext] = useState(true)
|
||||
const [isFetching, setIsFetching] = useState(false)
|
||||
const observerRef = React.useRef<HTMLDivElement | null>(null)
|
||||
|
||||
|
||||
const fetchMedicos = React.useCallback(async (pageToFetch: number) => {
|
||||
if (isFetching || !hasNext) return
|
||||
setIsFetching(true)
|
||||
setError(null)
|
||||
|
||||
const fetchDoctors = useCallback(async () => {
|
||||
setLoading(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 ?? "",
|
||||
crm: p.crm ?? "", // mock não tem crm, pode deixar vazio
|
||||
especialidade: p.especialidade ?? "", // mock não tem especialidade, pode deixar vazio
|
||||
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 ?? "",
|
||||
proximoAtendimento: p.proximo_atendimento ?? p.proximoAtendimento ?? "",
|
||||
status: p.status ?? "",
|
||||
}))
|
||||
setDoctors((prev) => [...prev, ...mapped])
|
||||
setHasNext(Boolean(json?.pagination?.has_next))
|
||||
setPage(pageToFetch + 1)
|
||||
|
||||
const data: Doctor[] = await doctorsService.list();
|
||||
setDoctors(data || []);
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Erro ao buscar médicos")
|
||||
console.error("Erro ao carregar lista de médicos:", e);
|
||||
setError("Não foi possível carregar a lista de médicos. Verifique a conexão com a API.");
|
||||
setDoctors([]);
|
||||
} finally {
|
||||
setIsFetching(false)
|
||||
setLoading(false);
|
||||
}
|
||||
}, [isFetching, hasNext])
|
||||
}, []);
|
||||
|
||||
React.useEffect(() => {
|
||||
fetchMedicos(page)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
fetchDoctors();
|
||||
}, [fetchDoctors]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!observerRef.current || !hasNext) return
|
||||
const observer = new window.IntersectionObserver((entries) => {
|
||||
if (entries[0].isIntersecting && !isFetching && hasNext) {
|
||||
fetchMedicos(page)
|
||||
}
|
||||
})
|
||||
observer.observe(observerRef.current)
|
||||
return () => {
|
||||
if (observerRef.current) observer.unobserve(observerRef.current)
|
||||
}
|
||||
}, [fetchMedicos, page, hasNext, isFetching])
|
||||
|
||||
const handleDeleteDoctor = async (doctorId: string) => {
|
||||
const openDetailsDialog = async (doctor: Doctor) => {
|
||||
setDetailsDialogOpen(true);
|
||||
|
||||
setDoctorDetails({
|
||||
nome: doctor.full_name,
|
||||
crm: doctor.crm,
|
||||
especialidade: doctor.specialty,
|
||||
contato: {
|
||||
celular: doctor.phone_mobile ?? undefined,
|
||||
telefone1: undefined
|
||||
},
|
||||
endereco: {
|
||||
cidade: doctor.city ?? undefined,
|
||||
estado: doctor.state ?? undefined,
|
||||
},
|
||||
|
||||
convenio: "Particular",
|
||||
vip: false,
|
||||
status: "Ativo",
|
||||
ultimo_atendimento: "N/A",
|
||||
proximo_atendimento: "N/A",
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (doctorToDeleteId === null) return;
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
await fetch(`https://mock.apidog.com/m1/1053378-0-default/pacientes/${doctorId}`, {
|
||||
method: "DELETE",
|
||||
})
|
||||
} catch { }
|
||||
setDoctors((prev) => prev.filter((doctor) => String(doctor.id) !== String(doctorId)))
|
||||
setDeleteDialogOpen(false)
|
||||
setDoctorToDelete(null)
|
||||
}
|
||||
await doctorsService.delete(doctorToDeleteId);
|
||||
|
||||
console.log(`Médico com ID ${doctorToDeleteId} excluído com sucesso!`);
|
||||
|
||||
const openDeleteDialog = (doctorId: string) => {
|
||||
setDoctorToDelete(doctorId)
|
||||
setDeleteDialogOpen(true)
|
||||
}
|
||||
setDeleteDialogOpen(false);
|
||||
setDoctorToDeleteId(null);
|
||||
await fetchDoctors();
|
||||
} catch (e) {
|
||||
console.error("Erro ao excluir:", e);
|
||||
|
||||
alert("Erro ao excluir médico.");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const filteredDoctors = doctors.filter((doctor) => {
|
||||
const matchesSearch =
|
||||
doctor.nome.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
doctor.crm.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
doctor.telefone.includes(searchTerm)
|
||||
const matchesEspecialidade = especialidadeFilter === "all" || doctor.especialidade === especialidadeFilter
|
||||
const matchesStatus = statusFilter === "all" || doctor.status === statusFilter
|
||||
const openDeleteDialog = (doctorId: number) => {
|
||||
setDoctorToDeleteId(doctorId);
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
|
||||
|
||||
const handleEdit = (doctorId: number) => {
|
||||
|
||||
router.push(`/manager/home/${doctorId}/editar`);
|
||||
};
|
||||
|
||||
return matchesSearch && matchesEspecialidade && matchesStatus
|
||||
})
|
||||
|
||||
return (
|
||||
<ManagerLayout>
|
||||
<div className="space-y-6">
|
||||
{/* ...layout e filtros... */}
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Médicos</h1>
|
||||
<p className="text-gray-600">Gerencie as informações dos médicos</p>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Médicos Cadastrados</h1>
|
||||
<p className="text-sm text-gray-500">Gerencie todos os profissionais de saúde.</p>
|
||||
</div>
|
||||
<Link href="/manager/home/novo">
|
||||
<Button className="bg-green-600 hover:bg-green-700">
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
Adicionar
|
||||
Adicionar Novo
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
<div className="flex items-center gap-4 bg-white p-4 rounded-lg border border-gray-200">
|
||||
{/* ...filtros... */}
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium text-gray-700">Especialidade</span>
|
||||
<Select value={especialidadeFilter} onValueChange={setEspecialidadeFilter}>
|
||||
<SelectTrigger className="w-40">
|
||||
<SelectValue placeholder="Selecione a Especialidade" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Todas</SelectItem>
|
||||
<SelectItem value="Cardiologia">Cardiologia</SelectItem>
|
||||
<SelectItem value="Pediatria">Pediatria</SelectItem>
|
||||
<SelectItem value="Ortopedia">Ortopedia</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium text-gray-700">Status</span>
|
||||
<Select value={statusFilter} onValueChange={setStatusFilter}>
|
||||
<SelectTrigger className="w-32">
|
||||
<SelectValue placeholder="Selecione" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Todos</SelectItem>
|
||||
<SelectItem value="Ativo">Ativo</SelectItem>
|
||||
<SelectItem value="Inativo">Inativo</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<Button variant="outline" className="ml-auto bg-transparent">
|
||||
<Filter className="w-4 h-4 mr-2" />
|
||||
Filtro avançado
|
||||
</Button>
|
||||
|
||||
|
||||
<div className="flex items-center space-x-4 bg-white p-4 rounded-lg border border-gray-200">
|
||||
<Filter className="w-5 h-5 text-gray-400" />
|
||||
<Select>
|
||||
<SelectTrigger className="w-[180px]">
|
||||
<SelectValue placeholder="Especialidade" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="cardiologia">Cardiologia</SelectItem>
|
||||
<SelectItem value="dermatologia">Dermatologia</SelectItem>
|
||||
<SelectItem value="pediatria">Pediatria</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select>
|
||||
<SelectTrigger className="w-[180px]">
|
||||
<SelectValue placeholder="Status" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="ativo">Ativo</SelectItem>
|
||||
<SelectItem value="ferias">Férias</SelectItem>
|
||||
<SelectItem value="inativo">Inativo</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="bg-white rounded-lg border border-gray-200">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full">
|
||||
<thead className="bg-gray-50 border-b border-gray-200">
|
||||
<tr>
|
||||
<th className="text-left p-4 font-medium text-gray-700">Nome</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700">CRM</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700">Telefone</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700">Cidade</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700">Estado</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700">Último atendimento</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700">Próximo atendimento</th>
|
||||
<th className="text-left p-4 font-medium text-gray-700">Ações</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{error ? (
|
||||
|
||||
|
||||
<div className="bg-white rounded-lg border border-gray-200 shadow-md overflow-hidden">
|
||||
{loading ? (
|
||||
<div className="p-8 text-center text-gray-500">
|
||||
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-3 text-green-600" />
|
||||
Carregando médicos...
|
||||
</div>
|
||||
) : error ? (
|
||||
<div className="p-8 text-center text-red-600">
|
||||
{error}
|
||||
</div>
|
||||
) : doctors.length === 0 ? (
|
||||
<div className="p-8 text-center text-gray-500">
|
||||
Nenhum médico cadastrado. <Link href="/manager/home/novo" className="text-green-600 hover:underline">Adicione um novo</Link>.
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="min-w-full divide-y divide-gray-200">
|
||||
<thead className="bg-gray-50">
|
||||
<tr>
|
||||
<td colSpan={8} className="p-6 text-red-600">{`Erro: ${error}`}</td>
|
||||
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Nome</th>
|
||||
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">CRM</th>
|
||||
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Especialidade</th>
|
||||
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Celular</th>
|
||||
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Cidade/Estado</th>
|
||||
<th scope="col" className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Ações</th>
|
||||
</tr>
|
||||
) : filteredDoctors.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={8} className="p-8 text-center text-gray-500">Nenhum registro encontrado</td>
|
||||
</tr>
|
||||
) : (
|
||||
filteredDoctors.map((doctor) => (
|
||||
<tr key={doctor.id} className="border-b border-gray-100 hover:bg-gray-50">
|
||||
<td className="p-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 bg-gray-100 rounded-full flex items-center justify-center">
|
||||
<span className="text-gray-600 font-medium text-sm">{doctor.nome?.charAt(0) || "?"}</span>
|
||||
</div>
|
||||
<span className="font-medium text-gray-900">{doctor.nome}</span>
|
||||
</thead>
|
||||
<tbody className="bg-white divide-y divide-gray-200">
|
||||
{doctors.map((doctor) => (
|
||||
<tr key={doctor.id} className="hover:bg-gray-50">
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{doctor.full_name}</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{doctor.crm}</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{doctor.specialty}</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{doctor.phone_mobile || "N/A"}</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
|
||||
{(doctor.city || doctor.state) ? `${doctor.city || ''}${doctor.city && doctor.state ? '/' : ''}${doctor.state || ''}` : "N/A"}
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
|
||||
|
||||
<div className="flex justify-end space-x-1">
|
||||
|
||||
<Button variant="outline" size="icon" onClick={() => openDetailsDialog(doctor)} title="Visualizar Detalhes">
|
||||
<Eye className="h-4 w-4" />
|
||||
</Button>
|
||||
|
||||
<Button variant="outline" size="icon" onClick={() => handleEdit(doctor.id)} title="Editar">
|
||||
<Edit className="h-4 w-4 text-blue-600" />
|
||||
</Button>
|
||||
|
||||
<Button variant="outline" size="icon" onClick={() => openDeleteDialog(doctor.id)} title="Excluir">
|
||||
<Trash2 className="h-4 w-4 text-red-600" />
|
||||
</Button>
|
||||
|
||||
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" className="h-8 w-8 p-0" title="Mais Ações">
|
||||
<span className="sr-only">Mais Ações</span>
|
||||
<MoreVertical className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem>
|
||||
<Calendar className="mr-2 h-4 w-4" />
|
||||
Agendar Consulta
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</td>
|
||||
<td className="p-4 text-gray-600">{doctor.crm}</td>
|
||||
<td className="p-4 text-gray-600">{doctor.telefone}</td>
|
||||
<td className="p-4 text-gray-600">{doctor.cidade}</td>
|
||||
<td className="p-4 text-gray-600">{doctor.estado}</td>
|
||||
<td className="p-4 text-gray-600">{doctor.ultimoAtendimento}</td>
|
||||
<td className="p-4 text-gray-600">{doctor.proximoAtendimento}</td>
|
||||
<td className="p-4">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<div className="text-blue-600 cursor-pointer">
|
||||
Ações
|
||||
</div>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => openDetailsDialog(String(doctor.id))}>
|
||||
<Eye className="w-4 h-4 mr-2" />
|
||||
Ver detalhes
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href={`/manager/home/${doctor.id}/editar`}>
|
||||
<Edit className="w-4 h-4 mr-2" />
|
||||
Editar
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem>
|
||||
<Calendar className="w-4 h-4 mr-2" />
|
||||
Ver agenda
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="text-red-600" onClick={() => openDeleteDialog(String(doctor.id))}>
|
||||
<Trash2 className="w-4 h-4 mr-2" />
|
||||
Excluir
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
<div ref={observerRef} style={{ height: 1 }} />
|
||||
{isFetching && (
|
||||
<div className="p-4 text-center text-gray-500">Carregando mais médicos...</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
|
||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Confirmar exclusão</AlertDialogTitle>
|
||||
<AlertDialogTitle>Confirma a exclusão?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Tem certeza que deseja excluir este médico? Esta ação não pode ser desfeita.
|
||||
Esta ação é irreversível e excluirá permanentemente o registro deste médico.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancelar</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() => doctorToDelete && handleDeleteDoctor(doctorToDelete)}
|
||||
className="bg-red-600 hover:bg-red-700"
|
||||
>
|
||||
Excluir
|
||||
<AlertDialogCancel disabled={loading}>Cancelar</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={handleDelete} className="bg-red-600 hover:bg-red-700" disabled={loading}>
|
||||
{loading ? (
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
) : null}
|
||||
Excluir
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
{/* Modal de detalhes do médico */}
|
||||
|
||||
|
||||
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Detalhes do Médico</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{doctorDetails === null ? (
|
||||
<div className="text-gray-500">Carregando...</div>
|
||||
) : doctorDetails?.error ? (
|
||||
<div className="text-red-600">{doctorDetails.error}</div>
|
||||
) : (
|
||||
<div className="space-y-2 text-left">
|
||||
<div><strong>Nome:</strong> {doctorDetails.nome}</div>
|
||||
<div><strong>Telefone:</strong> {doctorDetails?.contato?.celular ?? doctorDetails?.contato?.telefone1 ?? doctorDetails?.telefone ?? ""}</div>
|
||||
<div><strong>Cidade:</strong> {doctorDetails?.endereco?.cidade ?? doctorDetails?.cidade ?? ""}</div>
|
||||
<div><strong>Estado:</strong> {doctorDetails?.endereco?.estado ?? doctorDetails?.estado ?? ""}</div>
|
||||
<div><strong>Convênio:</strong> {doctorDetails.convenio ?? ""}</div>
|
||||
<div><strong>VIP:</strong> {doctorDetails.vip ? "Sim" : "Não"}</div>
|
||||
<div><strong>Status:</strong> {doctorDetails.status ?? ""}</div>
|
||||
<div><strong>Último atendimento:</strong> {doctorDetails.ultimo_atendimento ?? doctorDetails.ultimoAtendimento ?? ""}</div>
|
||||
<div><strong>Próximo atendimento:</strong> {doctorDetails.proximo_atendimento ?? doctorDetails.proximoAtendimento ?? ""}</div>
|
||||
<AlertDialogTitle className="text-2xl">{doctorDetails?.nome}</AlertDialogTitle>
|
||||
<AlertDialogDescription className="text-left text-gray-700">
|
||||
{doctorDetails && (
|
||||
<div className="space-y-3 text-left">
|
||||
<h3 className="font-semibold mt-2">Informações Principais</h3>
|
||||
<div className="grid grid-cols-2 gap-y-1 gap-x-4 text-sm">
|
||||
<div><strong>CRM:</strong> {doctorDetails.crm}</div>
|
||||
<div><strong>Especialidade:</strong> {doctorDetails.especialidade}</div>
|
||||
<div><strong>Celular:</strong> {doctorDetails.contato.celular || 'N/A'}</div>
|
||||
<div><strong>Localização:</strong> {`${doctorDetails.endereco.cidade || 'N/A'}/${doctorDetails.endereco.estado || 'N/A'}`}</div>
|
||||
</div>
|
||||
|
||||
<h3 className="font-semibold mt-4">Atendimento e Convênio</h3>
|
||||
<div className="grid grid-cols-2 gap-y-1 gap-x-4 text-sm">
|
||||
<div><strong>Convênio:</strong> {doctorDetails.convenio || 'N/A'}</div>
|
||||
<div><strong>VIP:</strong> {doctorDetails.vip ? "Sim" : "Não"}</div>
|
||||
<div><strong>Status:</strong> {doctorDetails.status || 'N/A'}</div>
|
||||
<div><strong>Último atendimento:</strong> {doctorDetails.ultimo_atendimento || 'N/A'}</div>
|
||||
<div><strong>Próximo atendimento:</strong> {doctorDetails.proximo_atendimento || 'N/A'}</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{doctorDetails === null && !loading && (
|
||||
<div className="text-red-600">Detalhes não disponíveis.</div>
|
||||
)}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
|
||||
@ -29,7 +29,6 @@ export default function ManagerLogin() {
|
||||
e.preventDefault()
|
||||
setIsLoading(true)
|
||||
|
||||
// Simular autenticação
|
||||
setTimeout(() => {
|
||||
if (form.email && form.password) {
|
||||
const managerData = {
|
||||
|
||||
@ -1,5 +1,4 @@
|
||||
|
||||
// váriaveis básicas
|
||||
const BASE_URL = "https://yuanqfswhberkoevtmfr.supabase.co";
|
||||
const API_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Inl1YW5xZnN3aGJlcmtvZXZ0bWZyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTQ5NTQzNjksImV4cCI6MjA3MDUzMDM2OX0.g8Fm4XAvtX46zifBZnYVH4tVuQkqUH6Ia9CXQj4DztQ";
|
||||
var tempToken;
|
||||
@ -16,26 +15,35 @@ export async function login() {
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
// salvar o token do usuário
|
||||
|
||||
localStorage.setItem("token", data.access_token);
|
||||
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
async function run(){
|
||||
await login()
|
||||
}
|
||||
run()
|
||||
|
||||
let loginPromise = login();
|
||||
|
||||
|
||||
|
||||
async function request(endpoint, options = {}) {
|
||||
const token = localStorage.getItem("token"); // token do usuário, salvo no login
|
||||
|
||||
if (loginPromise) {
|
||||
try {
|
||||
await loginPromise;
|
||||
} catch (error) {
|
||||
console.error("Falha na autenticação inicial:", error);
|
||||
}
|
||||
|
||||
loginPromise = null;
|
||||
}
|
||||
|
||||
const token = localStorage.getItem("token");
|
||||
|
||||
const headers = {
|
||||
"Content-Type": "application/json",
|
||||
"apikey": API_KEY, // obrigatório sempre
|
||||
...(token ? { "Authorization": `Bearer ${token}` } : {}), // obrigatório em todas EXCETO login
|
||||
"apikey": API_KEY,
|
||||
...(token ? { "Authorization": `Bearer ${token}` } : {}),
|
||||
...options.headers,
|
||||
};
|
||||
|
||||
@ -46,30 +54,37 @@ 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}`);
|
||||
|
||||
let errorBody = `Status: ${response.status}`;
|
||||
try {
|
||||
const contentType = response.headers.get("content-type");
|
||||
if (contentType && contentType.includes("application/json")) {
|
||||
const jsonError = await response.json();
|
||||
|
||||
errorBody = jsonError.message || JSON.stringify(jsonError);
|
||||
} else {
|
||||
errorBody = await response.text();
|
||||
}
|
||||
} catch (e) {
|
||||
|
||||
errorBody = `Status: ${response.status} - Falha ao ler corpo do erro.`;
|
||||
}
|
||||
|
||||
throw new Error(`Erro HTTP: ${response.status} - Detalhes: ${errorBody}`);
|
||||
}
|
||||
|
||||
// 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);
|
||||
const contentType = response.headers.get("content-type");
|
||||
if (response.status === 204 || (contentType && !contentType.includes("application/json")) || !contentType) {
|
||||
return {};
|
||||
}
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error("Erro na requisição:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export const api = {
|
||||
get: (endpoint) => request(endpoint, { method: "GET" }),
|
||||
post: (endpoint, body) =>
|
||||
request(endpoint, { method: "POST", body: JSON.stringify(body) }),
|
||||
patch: (endpoint, body) =>
|
||||
request(endpoint, { method: "PATCH", body: JSON.stringify(body) }),
|
||||
post: (endpoint, data) => request(endpoint, { method: "POST", body: JSON.stringify(data) }),
|
||||
patch: (endpoint, data) => request(endpoint, { method: "PATCH", body: JSON.stringify(data) }),
|
||||
delete: (endpoint) => request(endpoint, { method: "DELETE" }),
|
||||
};
|
||||
};
|
||||
@ -0,0 +1,9 @@
|
||||
import { api } from "./api.mjs";
|
||||
|
||||
export const doctorsService = {
|
||||
list: () => api.get("/rest/v1/doctors"),
|
||||
getById: (id) => api.get(`/rest/v1/doctors?id=eq.${id}`).then(data => data[0]),
|
||||
create: (data) => api.post("/rest/v1/doctors", data),
|
||||
update: (id, data) => api.patch(`/rest/v1/doctors?id=eq.${id}`, data),
|
||||
delete: (id) => api.delete(`/rest/v1/doctors?id=eq.${id}`),
|
||||
};
|
||||
Loading…
x
Reference in New Issue
Block a user