// ARQUIVO COMPLETO PARA: app/manager/usuario/novo/page.tsx "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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Save, Loader2 } from "lucide-react"; import ManagerLayout from "@/components/manager-layout"; import { usersService } from "@/services/usersApi.mjs"; import { doctorsService } from "@/services/doctorsApi.mjs"; import { login } from "services/api.mjs"; import { isValidCPF } from "@/lib/utils"; // 1. IMPORTAÇÃO DA FUNÇÃO DE VALIDAÇÃO interface UserFormData { email: string; nomeCompleto: string; telefone: string; papel: string; senha: string; confirmarSenha: string; cpf: string; crm: string; crm_uf: string; specialty: string; } const defaultFormData: UserFormData = { email: "", nomeCompleto: "", telefone: "", papel: "", senha: "", confirmarSenha: "", cpf: "", crm: "", crm_uf: "", specialty: "", }; 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 [formData, setFormData] = useState(defaultFormData); const [isSaving, setIsSaving] = useState(false); const [error, setError] = useState(null); const handleInputChange = (key: keyof UserFormData, value: string) => { let updatedValue = value; if (key === "telefone") { updatedValue = formatPhone(value); } else if (key === "crm_uf") { updatedValue = value.toUpperCase(); } setFormData((prev) => ({ ...prev, [key]: updatedValue })); }; const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); setError(null); if (!formData.email || !formData.nomeCompleto || !formData.papel || !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; } // 2. VALIDAÇÃO DO CPF ANTES DO ENVIO if (!isValidCPF(formData.cpf)) { setError("O CPF informado é inválido. Por favor, verifique os dígitos."); return; } 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 { if (formData.papel === "medico") { 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, }; await doctorsService.create(doctorPayload); } else { 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, phone_mobile: isPatient ? formData.telefone || null : undefined, }; await usersService.create_user(userPayload); } router.push("/manager/usuario"); } catch (e: any) { console.error("Erro ao criar usuário:", e); // 3. MENSAGEM DE ERRO MELHORADA const detail = e.message?.split('detail:"')[1]?.split('"')[0] || e.message; setError(detail.replace(/\\/g, '') || "Não foi possível criar o usuário. Verifique os dados e tente novamente."); } finally { setIsSaving(false); } }; const isMedico = formData.papel === "medico"; return (

Novo Usuário

Preencha os dados para cadastrar um novo usuário no sistema.

{error && (

Erro no Cadastro:

{error}

)}
handleInputChange("nomeCompleto", e.target.value)} placeholder="Nome e Sobrenome" required />
handleInputChange("email", e.target.value)} placeholder="exemplo@dominio.com" required />
{isMedico && ( <>
handleInputChange("crm", e.target.value)} placeholder="Número do CRM" required />
handleInputChange("crm_uf", e.target.value)} placeholder="Ex: SP" maxLength={2} required />
handleInputChange("specialty", e.target.value)} placeholder="Ex: Cardiologia" />
)}
handleInputChange("senha", e.target.value)} placeholder="Mínimo 8 caracteres" minLength={8} required />
handleInputChange("confirmarSenha", e.target.value)} placeholder="Repita a senha" required /> {formData.senha && formData.confirmarSenha && formData.senha !== formData.confirmarSenha &&

As senhas não coincidem.

}
handleInputChange("telefone", e.target.value)} placeholder="(00) 00000-0000" maxLength={15} />
handleInputChange("cpf", e.target.value)} placeholder="Apenas números" required />
); }