Merge pull request #4 from m1guelmcf/refactor/user-creation-and-scheduling
Refactor/user creation and scheduling
This commit is contained in:
commit
d55651a0be
@ -1,534 +0,0 @@
|
||||
"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 { 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 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 = () => {
|
||||
const newId = Date.now();
|
||||
handleInputChange('anexos', [...formData.anexos, { id: newId, name: `Documento ${formData.anexos.length + 1}` }]);
|
||||
}
|
||||
|
||||
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="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-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 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="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="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 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>
|
||||
{UF_LIST.map(uf => (
|
||||
<SelectItem key={uf} value={uf}>{uf}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</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>
|
||||
|
||||
|
||||
<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>
|
||||
</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>
|
||||
{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="flex justify-end gap-4 pb-8 pt-4">
|
||||
<Link href="/manager/home">
|
||||
<Button type="button" variant="outline" disabled={isSaving}>
|
||||
Cancelar
|
||||
</Button>
|
||||
</Link>
|
||||
<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>
|
||||
);
|
||||
}
|
||||
@ -158,12 +158,6 @@ export default function DoctorsPage() {
|
||||
<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 Novo
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
@ -1,3 +1,5 @@
|
||||
// /app/manager/usuario/novo/page.tsx
|
||||
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
@ -9,7 +11,8 @@ import { Label } from "@/components/ui/label";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Save, Loader2, Pause } from "lucide-react";
|
||||
import ManagerLayout from "@/components/manager-layout";
|
||||
import { usersService } from "services/usersApi.mjs";
|
||||
import { usersService } from "@/services/usersApi.mjs";
|
||||
import { doctorsService } from "@/services/doctorsApi.mjs"; // Importação adicionada
|
||||
import { login } from "services/api.mjs";
|
||||
|
||||
interface UserFormData {
|
||||
@ -20,6 +23,10 @@ interface UserFormData {
|
||||
senha: string;
|
||||
confirmarSenha: string;
|
||||
cpf: string;
|
||||
// Novos campos para Médico
|
||||
crm: string;
|
||||
crm_uf: string;
|
||||
specialty: string;
|
||||
}
|
||||
|
||||
const defaultFormData: UserFormData = {
|
||||
@ -30,6 +37,10 @@ const defaultFormData: UserFormData = {
|
||||
senha: "",
|
||||
confirmarSenha: "",
|
||||
cpf: "",
|
||||
// Valores iniciais para campos de Médico
|
||||
crm: "",
|
||||
crm_uf: "",
|
||||
specialty: "",
|
||||
};
|
||||
|
||||
const cleanNumber = (value: string): string => value.replace(/\D/g, "");
|
||||
@ -47,7 +58,13 @@ export default function NovoUsuarioPage() {
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleInputChange = (key: keyof UserFormData, value: string) => {
|
||||
const updatedValue = key === "telefone" ? formatPhone(value) : value;
|
||||
let updatedValue = value;
|
||||
if (key === "telefone") {
|
||||
updatedValue = formatPhone(value);
|
||||
} else if (key === "crm_uf") {
|
||||
// Converte UF para maiúsculas
|
||||
updatedValue = value.toUpperCase();
|
||||
}
|
||||
setFormData((prev) => ({ ...prev, [key]: updatedValue }));
|
||||
};
|
||||
|
||||
@ -65,22 +82,56 @@ export default function NovoUsuarioPage() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Validação adicional para Médico
|
||||
if (formData.papel === "medico") {
|
||||
if (!formData.crm || !formData.crm_uf) {
|
||||
setError("Para a função 'Médico', o CRM e a UF do CRM são obrigatórios.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
setIsSaving(true);
|
||||
|
||||
try {
|
||||
const payload = {
|
||||
full_name: formData.nomeCompleto,
|
||||
email: formData.email.trim().toLowerCase(),
|
||||
phone: formData.telefone || null,
|
||||
role: formData.papel,
|
||||
password: formData.senha,
|
||||
cpf: formData.cpf,
|
||||
};
|
||||
if (formData.papel === "medico") {
|
||||
// Lógica para criação de Médico
|
||||
const doctorPayload = {
|
||||
email: formData.email.trim().toLowerCase(),
|
||||
full_name: formData.nomeCompleto,
|
||||
cpf: formData.cpf,
|
||||
crm: formData.crm,
|
||||
crm_uf: formData.crm_uf,
|
||||
specialty: formData.specialty || null,
|
||||
phone_mobile: formData.telefone || null, // Usando phone_mobile conforme o schema
|
||||
};
|
||||
|
||||
console.log("📤 Enviando payload:");
|
||||
console.log(payload);
|
||||
console.log("📤 Enviando payload para Médico:");
|
||||
console.log(doctorPayload);
|
||||
|
||||
await usersService.create_user(payload);
|
||||
// Chamada ao endpoint específico para criação de médico
|
||||
await doctorsService.create(doctorPayload);
|
||||
|
||||
} else {
|
||||
// Lógica para criação de Outras Roles
|
||||
const isPatient = formData.papel === "paciente";
|
||||
|
||||
const userPayload = {
|
||||
email: formData.email.trim().toLowerCase(),
|
||||
password: formData.senha,
|
||||
full_name: formData.nomeCompleto,
|
||||
phone: formData.telefone || null,
|
||||
role: formData.papel,
|
||||
cpf: formData.cpf,
|
||||
create_patient_record: isPatient, // true se a role for 'paciente'
|
||||
phone_mobile: isPatient ? formData.telefone || null : undefined, // Enviar phone_mobile se for paciente
|
||||
};
|
||||
|
||||
console.log("📤 Enviando payload para Usuário Comum:");
|
||||
console.log(userPayload);
|
||||
|
||||
// Chamada ao endpoint padrão para criação de usuário
|
||||
await usersService.create_user(userPayload);
|
||||
}
|
||||
|
||||
router.push("/manager/usuario");
|
||||
} catch (e: any) {
|
||||
@ -91,6 +142,8 @@ export default function NovoUsuarioPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const isMedico = formData.papel === "medico";
|
||||
|
||||
return (
|
||||
<ManagerLayout>
|
||||
<div className="w-full h-full p-4 md:p-8 flex justify-center items-start">
|
||||
@ -140,6 +193,27 @@ export default function NovoUsuarioPage() {
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Campos Condicionais para Médico */}
|
||||
{isMedico && (
|
||||
<>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="crm">CRM *</Label>
|
||||
<Input id="crm" value={formData.crm} onChange={(e) => handleInputChange("crm", e.target.value)} placeholder="Número do CRM" required />
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="crm_uf">UF do CRM *</Label>
|
||||
<Input id="crm_uf" value={formData.crm_uf} onChange={(e) => handleInputChange("crm_uf", e.target.value)} placeholder="Ex: SP" maxLength={2} required />
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 md:col-span-2">
|
||||
<Label htmlFor="specialty">Especialidade (opcional)</Label>
|
||||
<Input id="specialty" value={formData.specialty} onChange={(e) => handleInputChange("specialty", e.target.value)} placeholder="Ex: Cardiologia" />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{/* Fim dos Campos Condicionais */}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="senha">Senha *</Label>
|
||||
<Input id="senha" type="password" value={formData.senha} onChange={(e) => handleInputChange("senha", e.target.value)} placeholder="Mínimo 8 caracteres" minLength={8} required />
|
||||
|
||||
@ -182,8 +182,8 @@ export default function PatientAppointments() {
|
||||
<div className="space-y-6">
|
||||
<div className="flex justify-between items-center">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-gray-900">Minhas Consultas</h1>
|
||||
<p className="text-gray-600">Veja, reagende ou cancele suas consultas</p>
|
||||
<h1 className="text-3xl font-bold text-foreground">Minhas Consultas</h1>
|
||||
<p className="text-muted-foreground">Veja, reagende ou cancele suas consultas</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@ -244,7 +244,13 @@ export default function PatientAppointments() {
|
||||
</Card>
|
||||
))
|
||||
) : (
|
||||
<p className="text-gray-600">Você ainda não possui consultas agendadas.</p>
|
||||
<Card className="p-6 text-center">
|
||||
<CalendarDays className="mx-auto h-12 w-12 text-muted-foreground mb-4" />
|
||||
<CardTitle className="text-xl">Nenhuma Consulta Encontrada</CardTitle>
|
||||
<CardDescription className="mt-2">
|
||||
Você ainda não possui consultas agendadas. Use o menu "Agendar Consulta" para começar.
|
||||
</CardDescription>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@ -134,8 +134,8 @@ export default function ScheduleAppointment() {
|
||||
{/* Médico */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="doctor">Médico</Label>
|
||||
<Select value={selectedDoctor} onValueChange={setSelectedDoctor}>
|
||||
<SelectTrigger>
|
||||
<Select value={selectedDoctor} onValueChange={setSelectedDoctor} disabled={loading}>
|
||||
<SelectTrigger id="doctor">
|
||||
<SelectValue placeholder="Selecione um médico" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
@ -168,7 +168,7 @@ export default function ScheduleAppointment() {
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="time">Horário</Label>
|
||||
<Select value={selectedTime} onValueChange={setSelectedTime}>
|
||||
<SelectTrigger>
|
||||
<SelectTrigger id="time">
|
||||
<SelectValue placeholder="Selecione um horário" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
|
||||
@ -1,676 +1,172 @@
|
||||
// Caminho: app/(manager)/usuario/novo/page.tsx
|
||||
"use client";
|
||||
|
||||
import type React from "react";
|
||||
|
||||
import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
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 { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Upload, Plus, X, ChevronDown } from "lucide-react";
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import SecretaryLayout from "@/components/secretary-layout";
|
||||
import { patientsService } from "@/services/patientsApi.mjs";
|
||||
// O Select foi removido pois não é mais necessário
|
||||
import { Save, Loader2 } from "lucide-react";
|
||||
import ManagerLayout from "@/components/manager-layout";
|
||||
// Os imports originais foram mantidos, como solicitado
|
||||
import { usersService } from "services/usersApi.mjs";
|
||||
import { doctorsService } from "services/doctorsApi.mjs";
|
||||
import { login } from "services/api.mjs";
|
||||
|
||||
export default function NovoPacientePage() {
|
||||
const [anexosOpen, setAnexosOpen] = useState(false);
|
||||
const [anexos, setAnexos] = useState<string[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
// Interface simplificada para refletir apenas os campos necessários
|
||||
interface UserFormData {
|
||||
email: string;
|
||||
nomeCompleto: string;
|
||||
telefone: string;
|
||||
senha: string;
|
||||
confirmarSenha: string;
|
||||
cpf: string;
|
||||
}
|
||||
|
||||
const defaultFormData: UserFormData = {
|
||||
email: "",
|
||||
nomeCompleto: "",
|
||||
telefone: "",
|
||||
senha: "",
|
||||
confirmarSenha: "",
|
||||
cpf: "",
|
||||
};
|
||||
|
||||
const cleanNumber = (value: string): string => value.replace(/\D/g, "");
|
||||
const formatPhone = (value: string): string => {
|
||||
const cleaned = cleanNumber(value).substring(0, 11);
|
||||
if (cleaned.length === 11) return cleaned.replace(/(\d{2})(\d{5})(\d{4})/, "($1) $2-$3");
|
||||
if (cleaned.length === 10) return cleaned.replace(/(\d{2})(\d{4})(\d{4})/, "($1) $2-$3");
|
||||
return cleaned;
|
||||
};
|
||||
|
||||
export default function NovoUsuarioPage() {
|
||||
const router = useRouter();
|
||||
const { toast } = useToast();
|
||||
const [formData, setFormData] = useState<UserFormData>(defaultFormData);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const adicionarAnexo = () => {
|
||||
setAnexos([...anexos, `Documento ${anexos.length + 1}`]);
|
||||
const handleInputChange = (key: keyof UserFormData, value: string) => {
|
||||
const updatedValue = key === "telefone" ? formatPhone(value) : value;
|
||||
setFormData((prev) => ({ ...prev, [key]: updatedValue }));
|
||||
};
|
||||
|
||||
const removerAnexo = (index: number) => {
|
||||
setAnexos(anexos.filter((_, i) => i !== index));
|
||||
};
|
||||
|
||||
|
||||
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})/, '+55 ($1) $2-$3');
|
||||
}
|
||||
return cleaned.replace(/(\d{2})(\d{4})(\d{4})/, '+55 ($1) $2-$3');
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (isLoading) return;
|
||||
setIsLoading(true);
|
||||
const form = e.currentTarget;
|
||||
const formData = new FormData(form);
|
||||
setError(null);
|
||||
|
||||
const apiPayload = {
|
||||
full_name: (formData.get("nome") as string) || "", // obrigatório
|
||||
social_name: (formData.get("nomeSocial") as string) || undefined,
|
||||
cpf: (formatCPF(formData.get("cpf") as string)) || "", // obrigatório
|
||||
email: (formData.get("email") as string) || "", // obrigatório
|
||||
phone_mobile: (formatPhoneMobile(formData.get("celular") as string)) || "", // obrigatório
|
||||
birth_date: formData.get("dataNascimento") ? new Date(formData.get("dataNascimento") as string) : undefined,
|
||||
sex: (formData.get("sexo") as string) || undefined,
|
||||
blood_type: (formData.get("tipoSanguineo") as string) || undefined,
|
||||
weight_kg: formData.get("peso") ? parseFloat(formData.get("peso") as string) : undefined,
|
||||
height_m: formData.get("altura") ? parseFloat(formData.get("altura") as string) : undefined,
|
||||
cep: (formatCEP(formData.get("cep") as string)) || undefined,
|
||||
street: (formData.get("endereco") as string) || undefined,
|
||||
number: (formData.get("numero") as string) || undefined,
|
||||
complement: (formData.get("complemento") as string) || undefined,
|
||||
neighborhood: (formData.get("bairro") as string) || undefined,
|
||||
city: (formData.get("cidade") as string) || undefined,
|
||||
state: (formData.get("estado") as string) || undefined,
|
||||
};
|
||||
|
||||
console.log(apiPayload.email)
|
||||
console.log(apiPayload.cep)
|
||||
console.log(apiPayload.phone_mobile)
|
||||
|
||||
const errors: string[] = [];
|
||||
const fullName = apiPayload.full_name?.trim() || "";
|
||||
if (!fullName || fullName.length < 2 || fullName.length > 255) {
|
||||
errors.push("Nome deve ter entre 2 e 255 caracteres.");
|
||||
}
|
||||
|
||||
const cpf = apiPayload.cpf || "";
|
||||
if (!/^\d{3}\.\d{3}\.\d{3}-\d{2}$/.test(cpf)) {
|
||||
errors.push("CPF deve estar no formato XXX.XXX.XXX-XX.");
|
||||
}
|
||||
|
||||
const sex = apiPayload.sex;
|
||||
const allowedSex = ["Masculino", "Feminino", "outro"];
|
||||
if (!sex || !allowedSex.includes(sex)) {
|
||||
errors.push("Sexo é obrigatório e deve ser masculino, feminino ou outro.");
|
||||
}
|
||||
|
||||
if (!apiPayload.birth_date) {
|
||||
errors.push("Data de nascimento é obrigatória.");
|
||||
}
|
||||
|
||||
const phoneMobile = apiPayload.phone_mobile || "";
|
||||
if (phoneMobile && !/^\+55 \(\d{2}\) \d{4,5}-\d{4}$/.test(phoneMobile)) {
|
||||
errors.push("Celular deve estar no formato +55 (XX) XXXXX-XXXX.");
|
||||
}
|
||||
|
||||
const cep = apiPayload.cep || "";
|
||||
if (cep && !/^\d{5}-\d{3}$/.test(cep)) {
|
||||
errors.push("CEP deve estar no formato XXXXX-XXX.");
|
||||
}
|
||||
|
||||
const state = apiPayload.state || "";
|
||||
if (state && state.length !== 2) {
|
||||
errors.push("Estado (UF) deve ter 2 caracteres.");
|
||||
}
|
||||
if (errors.length) {
|
||||
toast({ title: "Corrija os campos", description: errors[0] });
|
||||
console.log("campos errados")
|
||||
setIsLoading(false);
|
||||
// Validação simplificada
|
||||
if (!formData.email || !formData.nomeCompleto || !formData.senha || !formData.confirmarSenha || !formData.cpf) {
|
||||
setError("Por favor, preencha todos os campos obrigatórios.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (formData.senha !== formData.confirmarSenha) {
|
||||
setError("A Senha e a Confirmação de Senha não coincidem.");
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSaving(true);
|
||||
|
||||
try {
|
||||
const res = await patientsService.create(apiPayload);
|
||||
console.log(res)
|
||||
// Payload agora é fixo para a role 'paciente'
|
||||
const payload = {
|
||||
full_name: formData.nomeCompleto,
|
||||
email: formData.email.trim().toLowerCase(),
|
||||
phone: formData.telefone || null,
|
||||
role: "paciente", // Role fixada
|
||||
password: formData.senha,
|
||||
cpf: formData.cpf,
|
||||
};
|
||||
|
||||
let message = "Paciente cadastrado com sucesso";
|
||||
try {
|
||||
if (!res[0].id) {
|
||||
throw new Error(`${res.error} ${res.message}`|| "A API retornou erro");
|
||||
} else {
|
||||
console.log(message)
|
||||
}
|
||||
} catch {}
|
||||
console.log("📤 Enviando payload para criação de Usuário (Paciente):");
|
||||
console.log(payload);
|
||||
|
||||
toast({
|
||||
title: "Sucesso",
|
||||
description: message,
|
||||
});
|
||||
router.push("/secretary/pacientes");
|
||||
} catch (err: any) {
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: err?.message || "Não foi possível cadastrar o paciente",
|
||||
});
|
||||
// A chamada original à API foi mantida
|
||||
await usersService.create_user(payload);
|
||||
|
||||
router.push("/manager/usuario");
|
||||
} catch (e: any) {
|
||||
console.error("Erro ao criar usuário:", e);
|
||||
setError(e?.message || "Não foi possível criar o usuário. Verifique os dados e tente novamente.");
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<SecretaryLayout>
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Novo Paciente</h1>
|
||||
<p className="text-gray-600">Cadastre um novo paciente no sistema</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form className="space-y-6" onSubmit={handleSubmit}>
|
||||
<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">
|
||||
<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>
|
||||
</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" name="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" name="nomeSocial" placeholder="Nome social ou apelido" className="mt-1" />
|
||||
</div>
|
||||
</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" name="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" name="rg" placeholder="00.000.000-0" className="mt-1" />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="outrosDocumentos" className="text-sm font-medium text-gray-700">
|
||||
Outros Documentos
|
||||
</Label>
|
||||
<Select name="outrosDocumentos">
|
||||
<SelectTrigger className="mt-1">
|
||||
<SelectValue placeholder="Selecione" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="cnh">CNH</SelectItem>
|
||||
<SelectItem value="passaporte">Passaporte</SelectItem>
|
||||
<SelectItem value="carteira-trabalho">Carteira de Trabalho</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</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" required/>
|
||||
<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" required/>
|
||||
<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" name="dataNascimento" type="date" className="mt-1" required/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="estadoCivil" className="text-sm font-medium text-gray-700">
|
||||
Estado Civil
|
||||
</Label>
|
||||
<Select name="estadoCivil">
|
||||
<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 name="etnia">
|
||||
<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 name="raca">
|
||||
<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 name="naturalidade">
|
||||
<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 name="nacionalidade">
|
||||
<SelectTrigger className="mt-1">
|
||||
<SelectValue placeholder="Selecione" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="brasileira">Brasileira</SelectItem>
|
||||
<SelectItem value="estrangeira">Estrangeira</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="profissao" className="text-sm font-medium text-gray-700">
|
||||
Profissão
|
||||
</Label>
|
||||
<Input id="profissao" name="profissao" placeholder="Profissão" className="mt-1" />
|
||||
</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" name="nomeMae" placeholder="Nome da mãe" className="mt-1" />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="profissaoMae" className="text-sm font-medium text-gray-700">
|
||||
Profissão da Mãe
|
||||
</Label>
|
||||
<Input id="profissaoMae" name="profissaoMae" placeholder="Profissão da mãe" className="mt-1" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="nomePai" className="text-sm font-medium text-gray-700">
|
||||
Nome do Pai
|
||||
</Label>
|
||||
<Input id="nomePai" name="nomePai" placeholder="Nome do pai" className="mt-1" />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="profissaoPai" className="text-sm font-medium text-gray-700">
|
||||
Profissão do Pai
|
||||
</Label>
|
||||
<Input id="profissaoPai" name="profissaoPai" placeholder="Profissão do pai" className="mt-1" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="nomeResponsavel" className="text-sm font-medium text-gray-700">
|
||||
Nome do Responsável
|
||||
</Label>
|
||||
<Input id="nomeResponsavel" name="nomeResponsavel" placeholder="Nome do responsável" className="mt-1" />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="cpfResponsavel" className="text-sm font-medium text-gray-700">
|
||||
CPF do Responsável
|
||||
</Label>
|
||||
<Input id="cpfResponsavel" name="cpfResponsavel" placeholder="000.000.000-00" 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" name="nomeEsposo" placeholder="Nome do esposo(a)" className="mt-1" />
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox id="rnGuia" name="rnGuia" />
|
||||
<Label htmlFor="rnGuia" className="text-sm text-gray-700">
|
||||
RN na Guia do convênio
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="codigoLegado" className="text-sm font-medium text-gray-700">
|
||||
Código Legado
|
||||
</Label>
|
||||
<Input id="codigoLegado" name="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" name="observacoes" placeholder="Observações gerais sobre o paciente" className="min-h-[100px] mt-1" />
|
||||
</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>
|
||||
<span className="text-sm font-medium text-gray-700">Anexos do paciente</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" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
<Button variant="outline" onClick={adicionarAnexo} type="button" size="sm">
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
Adicionar Anexo
|
||||
</Button>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
<ManagerLayout>
|
||||
<div className="w-full h-full p-4 md:p-8 flex justify-center items-start">
|
||||
<div className="w-full max-w-screen-lg space-y-8">
|
||||
<div className="flex items-center justify-between border-b pb-4">
|
||||
<div>
|
||||
<h1 className="text-3xl font-extrabold text-gray-900">Novo Usuário</h1>
|
||||
<p className="text-md text-gray-500">Preencha os dados para cadastrar um novo usuário no sistema.</p>
|
||||
</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" name="email" type="email" placeholder="email@exemplo.com" className="mt-1" required/>
|
||||
</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 id="celular" name="celular" placeholder="(XX) XXXXX-XXXX" className="rounded-l-none" required/>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="telefone1" className="text-sm font-medium text-gray-700">
|
||||
Telefone 1
|
||||
</Label>
|
||||
<Input id="telefone1" name="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" name="telefone2" placeholder="(XX) XXXX-XXXX" className="mt-1" />
|
||||
</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" name="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" name="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" name="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" name="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" name="bairro" placeholder="Bairro" className="mt-1" />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="cidade" className="text-sm font-medium text-gray-700">
|
||||
Cidade
|
||||
</Label>
|
||||
<Input id="cidade" name="cidade" placeholder="Cidade" className="mt-1" />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="estado" className="text-sm font-medium text-gray-700">
|
||||
Estado
|
||||
</Label>
|
||||
<Select name="estado">
|
||||
<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 Médicas</h2>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="grid md:grid-cols-4 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="tipoSanguineo" className="text-sm font-medium text-gray-700">
|
||||
Tipo Sanguíneo
|
||||
</Label>
|
||||
<Select name="tipoSanguineo">
|
||||
<SelectTrigger className="mt-1">
|
||||
<SelectValue placeholder="Selecione" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="A+">A+</SelectItem>
|
||||
<SelectItem value="A-">A-</SelectItem>
|
||||
<SelectItem value="B+">B+</SelectItem>
|
||||
<SelectItem value="B-">B-</SelectItem>
|
||||
<SelectItem value="AB+">AB+</SelectItem>
|
||||
<SelectItem value="AB-">AB-</SelectItem>
|
||||
<SelectItem value="O+">O+</SelectItem>
|
||||
<SelectItem value="O-">O-</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="peso" className="text-sm font-medium text-gray-700">
|
||||
Peso
|
||||
</Label>
|
||||
<div className="relative mt-1">
|
||||
<Input id="peso" name="peso" type="number" placeholder="70" />
|
||||
<span className="absolute right-3 top-1/2 transform -translate-y-1/2 text-sm text-gray-500">kg</span>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="altura" className="text-sm font-medium text-gray-700">
|
||||
Altura
|
||||
</Label>
|
||||
<div className="relative mt-1">
|
||||
<Input id="altura" name="altura" type="number" step="0.01" placeholder="1.70" />
|
||||
<span className="absolute right-3 top-1/2 transform -translate-y-1/2 text-sm text-gray-500">m</span>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="imc" className="text-sm font-medium text-gray-700">
|
||||
IMC
|
||||
</Label>
|
||||
<div className="relative mt-1">
|
||||
<Input id="imc" name="imc" placeholder="Calculado automaticamente" disabled />
|
||||
<span className="absolute right-3 top-1/2 transform -translate-y-1/2 text-sm text-gray-500">kg/m²</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="alergias" className="text-sm font-medium text-gray-700">
|
||||
Alergias
|
||||
</Label>
|
||||
<Textarea id="alergias" name="alergias" placeholder="Ex: AAS, Dipirona, etc." className="min-h-[80px] mt-1" />
|
||||
</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 de Convênio</h2>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="convenio" className="text-sm font-medium text-gray-700">
|
||||
Convênio
|
||||
</Label>
|
||||
<Select name="convenio">
|
||||
<SelectTrigger className="mt-1">
|
||||
<SelectValue placeholder="Selecione" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="particular">Particular</SelectItem>
|
||||
<SelectItem value="sus">SUS</SelectItem>
|
||||
<SelectItem value="unimed">Unimed</SelectItem>
|
||||
<SelectItem value="bradesco">Bradesco Saúde</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="plano" className="text-sm font-medium text-gray-700">
|
||||
Plano
|
||||
</Label>
|
||||
<Input id="plano" name="plano" placeholder="Nome do plano" className="mt-1" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="numeroMatricula" className="text-sm font-medium text-gray-700">
|
||||
Nº de Matrícula
|
||||
</Label>
|
||||
<Input id="numeroMatricula" name="numeroMatricula" placeholder="Número da matrícula" className="mt-1" />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="validadeCarteira" className="text-sm font-medium text-gray-700">
|
||||
Validade da Carteira
|
||||
</Label>
|
||||
<Input id="validadeCarteira" name="validadeCarteira" type="date" className="mt-1" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox id="validadeIndeterminada" name="validadeIndeterminada" />
|
||||
<Label htmlFor="validadeIndeterminada" className="text-sm text-gray-700">
|
||||
Validade Indeterminada
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-4">
|
||||
<Link href="/secretary/pacientes">
|
||||
<Button variant="outline" type="button">
|
||||
Cancelar
|
||||
</Button>
|
||||
<Link href="/manager/usuario">
|
||||
<Button variant="outline">Cancelar</Button>
|
||||
</Link>
|
||||
<Button type="submit" className="bg-blue-600 hover:bg-blue-700" disabled={isLoading}>
|
||||
{isLoading ? "Salvando..." : "Salvar Paciente"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-6 bg-white p-6 md:p-10 border rounded-xl shadow-lg">
|
||||
{error && (
|
||||
<div className="p-4 bg-red-50 text-red-700 rounded-lg border border-red-300">
|
||||
<p className="font-semibold">Erro no Cadastro:</p>
|
||||
<p className="text-sm break-words">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div className="space-y-2 md:col-span-2">
|
||||
<Label htmlFor="nomeCompleto">Nome Completo *</Label>
|
||||
<Input id="nomeCompleto" value={formData.nomeCompleto} onChange={(e) => handleInputChange("nomeCompleto", e.target.value)} placeholder="Nome e Sobrenome" required />
|
||||
</div>
|
||||
|
||||
<div className="space-y-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>
|
||||
|
||||
{/* O seletor de Papel (Função) foi removido */}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="senha">Senha *</Label>
|
||||
<Input id="senha" type="password" value={formData.senha} onChange={(e) => handleInputChange("senha", e.target.value)} placeholder="Mínimo 8 caracteres" minLength={8} required />
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="confirmarSenha">Confirmar Senha *</Label>
|
||||
<Input id="confirmarSenha" type="password" value={formData.confirmarSenha} onChange={(e) => handleInputChange("confirmarSenha", e.target.value)} placeholder="Repita a senha" required />
|
||||
{formData.senha && formData.confirmarSenha && formData.senha !== formData.confirmarSenha && <p className="text-xs text-red-500">As senhas não coincidem.</p>}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="telefone">Telefone</Label>
|
||||
<Input id="telefone" value={formData.telefone} onChange={(e) => handleInputChange("telefone", e.target.value)} placeholder="(00) 00000-0000" maxLength={15} />
|
||||
</div>
|
||||
</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="xxx.xxx.xxx-xx" required />
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-4 pt-6 border-t mt-6">
|
||||
<Link href="/manager/usuario">
|
||||
<Button type="button" variant="outline" disabled={isSaving}>
|
||||
Cancelar
|
||||
</Button>
|
||||
</Link>
|
||||
<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 Usuário"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</SecretaryLayout>
|
||||
</ManagerLayout>
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -3,7 +3,10 @@ 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("/functions/v1/create-doctor", data),
|
||||
async create(data) {
|
||||
// Esta é a função usada no page.tsx para criar médicos
|
||||
return await api.post("/functions/v1/create-doctor", data);
|
||||
},
|
||||
update: (id, data) => api.patch(`/rest/v1/doctors?id=eq.${id}`, data),
|
||||
delete: (id) => api.delete(`/rest/v1/doctors?id=eq.${id}`),
|
||||
};
|
||||
};
|
||||
|
||||
@ -1,5 +1,3 @@
|
||||
// SUBSTITUA O OBJETO INTEIRO EM services/usersApi.mjs
|
||||
|
||||
import { api } from "./api.mjs";
|
||||
|
||||
export const usersService = {
|
||||
@ -19,6 +17,7 @@ export const usersService = {
|
||||
},
|
||||
|
||||
async create_user(data) {
|
||||
// Esta é a função usada no page.tsx para criar usuários que não são médicos
|
||||
return await api.post(`/functions/v1/create-user-with-password`, data);
|
||||
},
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user