forked from RiseUP/riseup-squad21
correção de erros
This commit is contained in:
parent
2a015a7f63
commit
a48ba7af2b
@ -8,15 +8,45 @@ import { Label } from "@/components/ui/label";
|
|||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
import DoctorLayout from "@/components/doctor-layout";
|
import DoctorLayout from "@/components/doctor-layout";
|
||||||
import { AvailabilityService } from "@/services/availabilityApi.mjs";
|
import { AvailabilityService } from "@/services/availabilityApi.mjs";
|
||||||
|
import { usersService } from "@/services/usersApi.mjs";
|
||||||
import { toast } from "@/hooks/use-toast";
|
import { toast } from "@/hooks/use-toast";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
|
|
||||||
|
interface UserPermissions {
|
||||||
|
isAdmin: boolean;
|
||||||
|
isManager: boolean;
|
||||||
|
isDoctor: boolean;
|
||||||
|
isSecretary: boolean;
|
||||||
|
isAdminOrManager: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface UserData {
|
||||||
|
user: {
|
||||||
|
id: string;
|
||||||
|
email: string;
|
||||||
|
email_confirmed_at: string | null;
|
||||||
|
created_at: string | null;
|
||||||
|
last_sign_in_at: string | null;
|
||||||
|
};
|
||||||
|
profile: {
|
||||||
|
id: string;
|
||||||
|
full_name: string;
|
||||||
|
email: string;
|
||||||
|
phone: string;
|
||||||
|
avatar_url: string | null;
|
||||||
|
disabled: boolean;
|
||||||
|
created_at: string | null;
|
||||||
|
updated_at: string | null;
|
||||||
|
};
|
||||||
|
roles: string[];
|
||||||
|
permissions: UserPermissions;
|
||||||
|
}
|
||||||
|
|
||||||
export default function AvailabilityPage() {
|
export default function AvailabilityPage() {
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const userInfo = JSON.parse(localStorage.getItem("user_info") || "{}");
|
const [userData, setUserData] = useState<UserData>();
|
||||||
const doctorIdTemp = "3bb9ee4a-cfdd-4d81-b628-383907dfa225";
|
|
||||||
const [modalidadeConsulta, setModalidadeConsulta] = useState<string>("");
|
const [modalidadeConsulta, setModalidadeConsulta] = useState<string>("");
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@ -24,6 +54,9 @@ export default function AvailabilityPage() {
|
|||||||
try {
|
try {
|
||||||
const response = await AvailabilityService.list();
|
const response = await AvailabilityService.list();
|
||||||
console.log(response);
|
console.log(response);
|
||||||
|
const user = await usersService.getMe();
|
||||||
|
console.log(user);
|
||||||
|
setUserData(user);
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
alert(`${e?.error} ${e?.message}`);
|
alert(`${e?.error} ${e?.message}`);
|
||||||
}
|
}
|
||||||
@ -40,8 +73,7 @@ export default function AvailabilityPage() {
|
|||||||
const formData = new FormData(form);
|
const formData = new FormData(form);
|
||||||
|
|
||||||
const apiPayload = {
|
const apiPayload = {
|
||||||
doctor_id: doctorIdTemp,
|
doctor_id: userData?.user.id,
|
||||||
created_by: doctorIdTemp,
|
|
||||||
weekday: (formData.get("weekday") as string) || undefined,
|
weekday: (formData.get("weekday") as string) || undefined,
|
||||||
start_time: (formData.get("horarioEntrada") as string) || undefined,
|
start_time: (formData.get("horarioEntrada") as string) || undefined,
|
||||||
end_time: (formData.get("horarioSaida") as string) || undefined,
|
end_time: (formData.get("horarioSaida") as string) || undefined,
|
||||||
|
|||||||
@ -6,267 +6,176 @@ import Link from "next/link";
|
|||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { Label } from "@/components/ui/label";
|
import { Label } from "@/components/ui/label";
|
||||||
import {
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
Select,
|
import { Save, Loader2, Pause } from "lucide-react";
|
||||||
SelectContent,
|
|
||||||
SelectItem,
|
|
||||||
SelectTrigger,
|
|
||||||
SelectValue,
|
|
||||||
} from "@/components/ui/select";
|
|
||||||
import { Save, Loader2 } from "lucide-react";
|
|
||||||
import ManagerLayout from "@/components/manager-layout";
|
import ManagerLayout from "@/components/manager-layout";
|
||||||
import { usersService } from "services/usersApi.mjs";
|
import { usersService } from "services/usersApi.mjs";
|
||||||
import { login } from "services/api.mjs";
|
import { login } from "services/api.mjs";
|
||||||
|
|
||||||
interface UserFormData {
|
interface UserFormData {
|
||||||
email: string;
|
email: string;
|
||||||
nomeCompleto: string;
|
nomeCompleto: string;
|
||||||
telefone: string;
|
telefone: string;
|
||||||
papel: string;
|
papel: string;
|
||||||
senha: string;
|
senha: string;
|
||||||
confirmarSenha: string;
|
confirmarSenha: string;
|
||||||
cpf : string
|
cpf: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
const defaultFormData: UserFormData = {
|
const defaultFormData: UserFormData = {
|
||||||
email: "",
|
email: "",
|
||||||
nomeCompleto: "",
|
nomeCompleto: "",
|
||||||
telefone: "",
|
telefone: "",
|
||||||
papel: "",
|
papel: "",
|
||||||
senha: "",
|
senha: "",
|
||||||
confirmarSenha: "",
|
confirmarSenha: "",
|
||||||
cpf : ""
|
cpf: "",
|
||||||
};
|
};
|
||||||
|
|
||||||
const cleanNumber = (value: string): string => value.replace(/\D/g, "");
|
const cleanNumber = (value: string): string => value.replace(/\D/g, "");
|
||||||
const formatPhone = (value: string): string => {
|
const formatPhone = (value: string): string => {
|
||||||
const cleaned = cleanNumber(value).substring(0, 11);
|
const cleaned = cleanNumber(value).substring(0, 11);
|
||||||
if (cleaned.length === 11)
|
if (cleaned.length === 11) return cleaned.replace(/(\d{2})(\d{5})(\d{4})/, "($1) $2-$3");
|
||||||
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");
|
||||||
if (cleaned.length === 10)
|
return cleaned;
|
||||||
return cleaned.replace(/(\d{2})(\d{4})(\d{4})/, "($1) $2-$3");
|
|
||||||
return cleaned;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function NovoUsuarioPage() {
|
export default function NovoUsuarioPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [formData, setFormData] = useState<UserFormData>(defaultFormData);
|
const [formData, setFormData] = useState<UserFormData>(defaultFormData);
|
||||||
const [isSaving, setIsSaving] = useState(false);
|
const [isSaving, setIsSaving] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
const handleInputChange = (key: keyof UserFormData, value: string) => {
|
const handleInputChange = (key: keyof UserFormData, value: string) => {
|
||||||
const updatedValue = key === "telefone" ? formatPhone(value) : value;
|
const updatedValue = key === "telefone" ? formatPhone(value) : value;
|
||||||
setFormData((prev) => ({ ...prev, [key]: updatedValue }));
|
setFormData((prev) => ({ ...prev, [key]: updatedValue }));
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
setError(null);
|
setError(null);
|
||||||
|
|
||||||
if (
|
if (!formData.email || !formData.nomeCompleto || !formData.papel || !formData.senha || !formData.confirmarSenha) {
|
||||||
!formData.email ||
|
setError("Por favor, preencha todos os campos obrigatórios.");
|
||||||
!formData.nomeCompleto ||
|
return;
|
||||||
!formData.papel ||
|
}
|
||||||
!formData.senha ||
|
|
||||||
!formData.confirmarSenha
|
|
||||||
) {
|
|
||||||
setError("Por favor, preencha todos os campos obrigatórios.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (formData.senha !== formData.confirmarSenha) {
|
if (formData.senha !== formData.confirmarSenha) {
|
||||||
setError("A Senha e a Confirmação de Senha não coincidem.");
|
setError("A Senha e a Confirmação de Senha não coincidem.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
setIsSaving(true);
|
setIsSaving(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await login();
|
const payload = {
|
||||||
|
full_name: formData.nomeCompleto,
|
||||||
|
email: formData.email.trim().toLowerCase(),
|
||||||
|
phone: formData.telefone || null,
|
||||||
|
role: formData.papel,
|
||||||
|
password: formData.senha,
|
||||||
|
cpf: formData.cpf,
|
||||||
|
};
|
||||||
|
|
||||||
const payload = {
|
console.log("📤 Enviando payload:");
|
||||||
full_name: formData.nomeCompleto,
|
console.log(payload);
|
||||||
email: formData.email.trim().toLowerCase(),
|
|
||||||
phone: formData.telefone || null,
|
|
||||||
role: formData.papel,
|
|
||||||
password: formData.senha,
|
|
||||||
cpf : formData.cpf
|
|
||||||
};
|
|
||||||
|
|
||||||
console.log("📤 Enviando payload:", payload);
|
await usersService.create_user(payload);
|
||||||
|
|
||||||
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 {
|
||||||
|
setIsSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
router.push("/manager/usuario");
|
return (
|
||||||
} catch (e: any) {
|
<ManagerLayout>
|
||||||
console.error("Erro ao criar usuário:", e);
|
<div className="w-full h-full p-4 md:p-8 flex justify-center items-start">
|
||||||
setError(
|
<div className="w-full max-w-screen-lg space-y-8">
|
||||||
e?.message ||
|
<div className="flex items-center justify-between border-b pb-4">
|
||||||
"Não foi possível criar o usuário. Verifique os dados e tente novamente."
|
<div>
|
||||||
);
|
<h1 className="text-3xl font-extrabold text-gray-900">Novo Usuário</h1>
|
||||||
} finally {
|
<p className="text-md text-gray-500">Preencha os dados para cadastrar um novo usuário no sistema.</p>
|
||||||
setIsSaving(false);
|
</div>
|
||||||
}
|
<Link href="/manager/usuario">
|
||||||
};
|
<Button variant="outline">Cancelar</Button>
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
|
||||||
return (
|
<form onSubmit={handleSubmit} className="space-y-6 bg-white p-6 md:p-10 border rounded-xl shadow-lg">
|
||||||
<ManagerLayout>
|
{error && (
|
||||||
<div className="w-full h-full p-4 md:p-8 flex justify-center items-start">
|
<div className="p-4 bg-red-50 text-red-700 rounded-lg border border-red-300">
|
||||||
<div className="w-full max-w-screen-lg space-y-8">
|
<p className="font-semibold">Erro no Cadastro:</p>
|
||||||
<div className="flex items-center justify-between border-b pb-4">
|
<p className="text-sm break-words">{error}</p>
|
||||||
<div>
|
</div>
|
||||||
<h1 className="text-3xl font-extrabold text-gray-900">
|
)}
|
||||||
Novo Usuário
|
|
||||||
</h1>
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||||
<p className="text-md text-gray-500">
|
<div className="space-y-2 md:col-span-2">
|
||||||
Preencha os dados para cadastrar um novo usuário no sistema.
|
<Label htmlFor="nomeCompleto">Nome Completo *</Label>
|
||||||
</p>
|
<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>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="papel">Papel (Função) *</Label>
|
||||||
|
<Select value={formData.papel} onValueChange={(v) => handleInputChange("papel", v)} required>
|
||||||
|
<SelectTrigger id="papel">
|
||||||
|
<SelectValue placeholder="Selecione uma função" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="admin">Administrador</SelectItem>
|
||||||
|
<SelectItem value="gestor">Gestor</SelectItem>
|
||||||
|
<SelectItem value="medico">Médico</SelectItem>
|
||||||
|
<SelectItem value="secretaria">Secretária</SelectItem>
|
||||||
|
<SelectItem value="paciente">Usuário</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<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" type="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>
|
</div>
|
||||||
<Link href="/manager/usuario">
|
</ManagerLayout>
|
||||||
<Button variant="outline">Cancelar</Button>
|
);
|
||||||
</Link>
|
}
|
||||||
</div>
|
|
||||||
|
|
||||||
<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>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="papel">Papel (Função) *</Label>
|
|
||||||
<Select
|
|
||||||
value={formData.papel}
|
|
||||||
onValueChange={(v) => handleInputChange("papel", v)}
|
|
||||||
required
|
|
||||||
>
|
|
||||||
<SelectTrigger id="papel">
|
|
||||||
<SelectValue placeholder="Selecione uma função" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="admin">Administrador</SelectItem>
|
|
||||||
<SelectItem value="gestor">Gestor</SelectItem>
|
|
||||||
<SelectItem value="medico">Médico</SelectItem>
|
|
||||||
<SelectItem value="secretaria">Secretária</SelectItem>
|
|
||||||
<SelectItem value="user">Usuário</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<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"
|
|
||||||
type="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>
|
|
||||||
</ManagerLayout>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|||||||
@ -16,328 +16,309 @@ import { toast } from "sonner";
|
|||||||
import { appointmentsService } from "@/services/appointmentsApi.mjs";
|
import { appointmentsService } from "@/services/appointmentsApi.mjs";
|
||||||
import { patientsService } from "@/services/patientsApi.mjs";
|
import { patientsService } from "@/services/patientsApi.mjs";
|
||||||
import { doctorsService } from "@/services/doctorsApi.mjs";
|
import { doctorsService } from "@/services/doctorsApi.mjs";
|
||||||
|
import { usersService } from "@/services/usersApi.mjs";
|
||||||
|
|
||||||
const APPOINTMENTS_STORAGE_KEY = "clinic-appointments";
|
const APPOINTMENTS_STORAGE_KEY = "clinic-appointments";
|
||||||
|
|
||||||
// Simulação do paciente logado
|
interface UserPermissions {
|
||||||
const LOGGED_PATIENT_ID = "P001";
|
isAdmin: boolean;
|
||||||
|
isManager: boolean;
|
||||||
|
isDoctor: boolean;
|
||||||
|
isSecretary: boolean;
|
||||||
|
isAdminOrManager: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface UserData {
|
||||||
|
user: {
|
||||||
|
id: string;
|
||||||
|
email: string;
|
||||||
|
email_confirmed_at: string | null;
|
||||||
|
created_at: string | null;
|
||||||
|
last_sign_in_at: string | null;
|
||||||
|
};
|
||||||
|
profile: {
|
||||||
|
id: string;
|
||||||
|
full_name: string;
|
||||||
|
email: string;
|
||||||
|
phone: string;
|
||||||
|
avatar_url: string | null;
|
||||||
|
disabled: boolean;
|
||||||
|
created_at: string | null;
|
||||||
|
updated_at: string | null;
|
||||||
|
};
|
||||||
|
roles: string[];
|
||||||
|
permissions: UserPermissions;
|
||||||
|
}
|
||||||
|
|
||||||
export default function PatientAppointments() {
|
export default function PatientAppointments() {
|
||||||
const [appointments, setAppointments] = useState<any[]>([]);
|
const [appointments, setAppointments] = useState<any[]>([]);
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
const [selectedAppointment, setSelectedAppointment] = useState<any>(null);
|
const [selectedAppointment, setSelectedAppointment] = useState<any>(null);
|
||||||
|
const [userData, setUserData] = useState<UserData>();
|
||||||
|
|
||||||
// Modais
|
// Modais
|
||||||
const [rescheduleModal, setRescheduleModal] = useState(false);
|
const [rescheduleModal, setRescheduleModal] = useState(false);
|
||||||
const [cancelModal, setCancelModal] = useState(false);
|
const [cancelModal, setCancelModal] = useState(false);
|
||||||
|
|
||||||
// Formulário de reagendamento/cancelamento
|
// Formulário de reagendamento/cancelamento
|
||||||
const [rescheduleData, setRescheduleData] = useState({ date: "", time: "", reason: "" });
|
const [rescheduleData, setRescheduleData] = useState({ date: "", time: "", reason: "" });
|
||||||
const [cancelReason, setCancelReason] = useState("");
|
const [cancelReason, setCancelReason] = useState("");
|
||||||
|
|
||||||
const timeSlots = [
|
const timeSlots = ["08:00", "08:30", "09:00", "09:30", "10:00", "10:30", "11:00", "11:30", "14:00", "14:30", "15:00", "15:30", "16:00", "16:30", "17:00", "17:30"];
|
||||||
"08:00",
|
|
||||||
"08:30",
|
|
||||||
"09:00",
|
|
||||||
"09:30",
|
|
||||||
"10:00",
|
|
||||||
"10:30",
|
|
||||||
"11:00",
|
|
||||||
"11:30",
|
|
||||||
"14:00",
|
|
||||||
"14:30",
|
|
||||||
"15:00",
|
|
||||||
"15:30",
|
|
||||||
"16:00",
|
|
||||||
"16:30",
|
|
||||||
"17:00",
|
|
||||||
"17:30",
|
|
||||||
];
|
|
||||||
|
|
||||||
const fetchData = async () => {
|
const fetchData = async () => {
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
try {
|
try {
|
||||||
const [appointmentList, patientList, doctorList] = await Promise.all([
|
const queryParams = "order=scheduled_at.desc";
|
||||||
appointmentsService.list(),
|
const appointmentList = await appointmentsService.search_appointment(queryParams);
|
||||||
patientsService.list(),
|
const patientList = await patientsService.list();
|
||||||
doctorsService.list(),
|
const doctorList = await doctorsService.list();
|
||||||
]);
|
|
||||||
|
|
||||||
const doctorMap = new Map(doctorList.map((d: any) => [d.id, d]));
|
const user = await usersService.getMe();
|
||||||
const patientMap = new Map(patientList.map((p: any) => [p.id, p]));
|
setUserData(user);
|
||||||
|
|
||||||
// Filtra apenas as consultas do paciente logado
|
const doctorMap = new Map(doctorList.map((d: any) => [d.id, d]));
|
||||||
const patientAppointments = appointmentList
|
const patientMap = new Map(patientList.map((p: any) => [p.id, p]));
|
||||||
.filter((apt: any) => apt.patient_id === LOGGED_PATIENT_ID)
|
|
||||||
.map((apt: any) => ({
|
|
||||||
...apt,
|
|
||||||
doctor: doctorMap.get(apt.doctor_id) || { full_name: "Médico não encontrado", specialty: "N/A" },
|
|
||||||
patient: patientMap.get(apt.patient_id) || { full_name: "Paciente não encontrado" },
|
|
||||||
}));
|
|
||||||
|
|
||||||
setAppointments(patientAppointments);
|
console.log(appointmentList);
|
||||||
} catch (error) {
|
|
||||||
console.error("Erro ao carregar consultas:", error);
|
|
||||||
toast.error("Não foi possível carregar suas consultas.");
|
|
||||||
} finally {
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
// Filtra apenas as consultas do paciente logado
|
||||||
fetchData();
|
const patientAppointments = appointmentList
|
||||||
}, []);
|
.filter((apt: any) => apt.patient_id === userData?.user.id)
|
||||||
|
.map((apt: any) => ({
|
||||||
|
...apt,
|
||||||
|
doctor: doctorMap.get(apt.doctor_id) || { full_name: "Médico não encontrado", specialty: "N/A" },
|
||||||
|
patient: patientMap.get(apt.patient_id) || { full_name: "Paciente não encontrado" },
|
||||||
|
}));
|
||||||
|
|
||||||
const getStatusBadge = (status: string) => {
|
setAppointments(patientAppointments);
|
||||||
switch (status) {
|
} catch (error) {
|
||||||
case "requested":
|
console.error("Erro ao carregar consultas:", error);
|
||||||
return <Badge className="bg-yellow-100 text-yellow-800">Solicitada</Badge>;
|
toast.error("Não foi possível carregar suas consultas.");
|
||||||
case "confirmed":
|
} finally {
|
||||||
return <Badge className="bg-blue-100 text-blue-800">Confirmada</Badge>;
|
setIsLoading(false);
|
||||||
case "checked_in":
|
}
|
||||||
return <Badge className="bg-indigo-100 text-indigo-800">Check-in</Badge>;
|
};
|
||||||
case "completed":
|
|
||||||
return <Badge className="bg-green-100 text-green-800">Realizada</Badge>;
|
|
||||||
case "cancelled":
|
|
||||||
return <Badge className="bg-red-100 text-red-800">Cancelada</Badge>;
|
|
||||||
default:
|
|
||||||
return <Badge variant="secondary">{status}</Badge>;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleReschedule = (appointment: any) => {
|
useEffect(() => {
|
||||||
setSelectedAppointment(appointment);
|
fetchData();
|
||||||
setRescheduleData({ date: "", time: "", reason: "" });
|
}, []);
|
||||||
setRescheduleModal(true);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleCancel = (appointment: any) => {
|
const getStatusBadge = (status: string) => {
|
||||||
setSelectedAppointment(appointment);
|
switch (status) {
|
||||||
setCancelReason("");
|
case "requested":
|
||||||
setCancelModal(true);
|
return <Badge className="bg-yellow-100 text-yellow-800">Solicitada</Badge>;
|
||||||
};
|
case "confirmed":
|
||||||
|
return <Badge className="bg-blue-100 text-blue-800">Confirmada</Badge>;
|
||||||
|
case "checked_in":
|
||||||
|
return <Badge className="bg-indigo-100 text-indigo-800">Check-in</Badge>;
|
||||||
|
case "completed":
|
||||||
|
return <Badge className="bg-green-100 text-green-800">Realizada</Badge>;
|
||||||
|
case "cancelled":
|
||||||
|
return <Badge className="bg-red-100 text-red-800">Cancelada</Badge>;
|
||||||
|
default:
|
||||||
|
return <Badge variant="secondary">{status}</Badge>;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const confirmReschedule = async () => {
|
const handleReschedule = (appointment: any) => {
|
||||||
if (!rescheduleData.date || !rescheduleData.time) {
|
setSelectedAppointment(appointment);
|
||||||
toast.error("Por favor, selecione uma nova data e horário.");
|
setRescheduleData({ date: "", time: "", reason: "" });
|
||||||
return;
|
setRescheduleModal(true);
|
||||||
}
|
};
|
||||||
try {
|
|
||||||
const newScheduledAt = new Date(`${rescheduleData.date}T${rescheduleData.time}:00Z`).toISOString();
|
|
||||||
|
|
||||||
await appointmentsService.update(selectedAppointment.id, {
|
const handleCancel = (appointment: any) => {
|
||||||
scheduled_at: newScheduledAt,
|
setSelectedAppointment(appointment);
|
||||||
status: "requested",
|
setCancelReason("");
|
||||||
});
|
setCancelModal(true);
|
||||||
|
};
|
||||||
|
|
||||||
setAppointments((prev) =>
|
const confirmReschedule = async () => {
|
||||||
prev.map((apt) =>
|
if (!rescheduleData.date || !rescheduleData.time) {
|
||||||
apt.id === selectedAppointment.id ? { ...apt, scheduled_at: newScheduledAt, status: "requested" } : apt
|
toast.error("Por favor, selecione uma nova data e horário.");
|
||||||
)
|
return;
|
||||||
);
|
}
|
||||||
|
try {
|
||||||
|
const newScheduledAt = new Date(`${rescheduleData.date}T${rescheduleData.time}:00Z`).toISOString();
|
||||||
|
|
||||||
setRescheduleModal(false);
|
await appointmentsService.update(selectedAppointment.id, {
|
||||||
toast.success("Consulta reagendada com sucesso!");
|
scheduled_at: newScheduledAt,
|
||||||
} catch (error) {
|
status: "requested",
|
||||||
console.error("Erro ao reagendar consulta:", error);
|
});
|
||||||
toast.error("Não foi possível reagendar a consulta.");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const confirmCancel = async () => {
|
setAppointments((prev) => prev.map((apt) => (apt.id === selectedAppointment.id ? { ...apt, scheduled_at: newScheduledAt, status: "requested" } : apt)));
|
||||||
if (!cancelReason.trim() || cancelReason.trim().length < 10) {
|
|
||||||
toast.error("Por favor, informe um motivo de cancelamento (mínimo 10 caracteres).");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
await appointmentsService.update(selectedAppointment.id, {
|
|
||||||
status: "cancelled",
|
|
||||||
cancel_reason: cancelReason,
|
|
||||||
});
|
|
||||||
|
|
||||||
setAppointments((prev) =>
|
setRescheduleModal(false);
|
||||||
prev.map((apt) =>
|
toast.success("Consulta reagendada com sucesso!");
|
||||||
apt.id === selectedAppointment.id ? { ...apt, status: "cancelled" } : apt
|
} catch (error) {
|
||||||
)
|
console.error("Erro ao reagendar consulta:", error);
|
||||||
);
|
toast.error("Não foi possível reagendar a consulta.");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
setCancelModal(false);
|
const confirmCancel = async () => {
|
||||||
toast.success("Consulta cancelada com sucesso!");
|
if (!cancelReason.trim() || cancelReason.trim().length < 10) {
|
||||||
} catch (error) {
|
toast.error("Por favor, informe um motivo de cancelamento (mínimo 10 caracteres).");
|
||||||
console.error("Erro ao cancelar consulta:", error);
|
return;
|
||||||
toast.error("Não foi possível cancelar a consulta.");
|
}
|
||||||
}
|
try {
|
||||||
};
|
await appointmentsService.update(selectedAppointment.id, {
|
||||||
|
status: "cancelled",
|
||||||
|
cancel_reason: cancelReason,
|
||||||
|
});
|
||||||
|
|
||||||
return (
|
setAppointments((prev) => prev.map((apt) => (apt.id === selectedAppointment.id ? { ...apt, status: "cancelled" } : apt)));
|
||||||
<PatientLayout>
|
|
||||||
<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>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid gap-6">
|
setCancelModal(false);
|
||||||
{isLoading ? (
|
toast.success("Consulta cancelada com sucesso!");
|
||||||
<p>Carregando suas consultas...</p>
|
} catch (error) {
|
||||||
) : appointments.length > 0 ? (
|
console.error("Erro ao cancelar consulta:", error);
|
||||||
appointments.map((appointment) => (
|
toast.error("Não foi possível cancelar a consulta.");
|
||||||
<Card key={appointment.id}>
|
}
|
||||||
<CardHeader>
|
};
|
||||||
<div className="flex justify-between items-start">
|
|
||||||
|
return (
|
||||||
|
<PatientLayout>
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="flex justify-between items-center">
|
||||||
<div>
|
<div>
|
||||||
<CardTitle className="text-lg">{appointment.doctor.full_name}</CardTitle>
|
<h1 className="text-3xl font-bold text-gray-900">Minhas Consultas</h1>
|
||||||
<CardDescription>{appointment.doctor.specialty}</CardDescription>
|
<p className="text-gray-600">Veja, reagende ou cancele suas consultas</p>
|
||||||
</div>
|
</div>
|
||||||
{getStatusBadge(appointment.status)}
|
</div>
|
||||||
</div>
|
|
||||||
</CardHeader>
|
<div className="grid gap-6">
|
||||||
<CardContent>
|
{isLoading ? (
|
||||||
<div className="grid md:grid-cols-2 gap-3">
|
<p>Carregando suas consultas...</p>
|
||||||
<div className="space-y-2 text-sm text-gray-700">
|
) : appointments.length > 0 ? (
|
||||||
<div className="flex items-center">
|
appointments.map((appointment) => (
|
||||||
<Calendar className="mr-2 h-4 w-4 text-gray-500" />
|
<Card key={appointment.id}>
|
||||||
{new Date(appointment.scheduled_at).toLocaleDateString("pt-BR", { timeZone: "UTC" })}
|
<CardHeader>
|
||||||
</div>
|
<div className="flex justify-between items-start">
|
||||||
<div className="flex items-center">
|
<div>
|
||||||
<Clock className="mr-2 h-4 w-4 text-gray-500" />
|
<CardTitle className="text-lg">{appointment.doctor.full_name}</CardTitle>
|
||||||
{new Date(appointment.scheduled_at).toLocaleTimeString("pt-BR", {
|
<CardDescription>{appointment.doctor.specialty}</CardDescription>
|
||||||
hour: "2-digit",
|
</div>
|
||||||
minute: "2-digit",
|
{getStatusBadge(appointment.status)}
|
||||||
timeZone: "UTC",
|
</div>
|
||||||
})}
|
</CardHeader>
|
||||||
</div>
|
<CardContent>
|
||||||
<div className="flex items-center">
|
<div className="grid md:grid-cols-2 gap-3">
|
||||||
<MapPin className="mr-2 h-4 w-4 text-gray-500" />
|
<div className="space-y-2 text-sm text-gray-700">
|
||||||
{appointment.doctor.location || "Local a definir"}
|
<div className="flex items-center">
|
||||||
</div>
|
<Calendar className="mr-2 h-4 w-4 text-gray-500" />
|
||||||
<div className="flex items-center">
|
{new Date(appointment.scheduled_at).toLocaleDateString("pt-BR", { timeZone: "UTC" })}
|
||||||
<Phone className="mr-2 h-4 w-4 text-gray-500" />
|
</div>
|
||||||
{appointment.doctor.phone || "N/A"}
|
<div className="flex items-center">
|
||||||
</div>
|
<Clock className="mr-2 h-4 w-4 text-gray-500" />
|
||||||
|
{new Date(appointment.scheduled_at).toLocaleTimeString("pt-BR", {
|
||||||
|
hour: "2-digit",
|
||||||
|
minute: "2-digit",
|
||||||
|
timeZone: "UTC",
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center">
|
||||||
|
<MapPin className="mr-2 h-4 w-4 text-gray-500" />
|
||||||
|
{appointment.doctor.location || "Local a definir"}
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center">
|
||||||
|
<Phone className="mr-2 h-4 w-4 text-gray-500" />
|
||||||
|
{appointment.doctor.phone || "N/A"}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{appointment.status !== "cancelled" && (
|
||||||
|
<div className="flex gap-2 mt-4 pt-4 border-t">
|
||||||
|
<Button variant="outline" size="sm" onClick={() => handleReschedule(appointment)}>
|
||||||
|
<CalendarDays className="mr-2 h-4 w-4" />
|
||||||
|
Reagendar
|
||||||
|
</Button>
|
||||||
|
<Button variant="outline" size="sm" className="text-red-600 hover:text-red-700 hover:bg-red-50" onClick={() => handleCancel(appointment)}>
|
||||||
|
<X className="mr-2 h-4 w-4" />
|
||||||
|
Cancelar
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
))
|
||||||
|
) : (
|
||||||
|
<p className="text-gray-600">Você ainda não possui consultas agendadas.</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* MODAL DE REAGENDAMENTO */}
|
||||||
|
<Dialog open={rescheduleModal} onOpenChange={setRescheduleModal}>
|
||||||
|
<DialogContent className="sm:max-w-[425px]">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Reagendar Consulta</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
Escolha uma nova data e horário para sua consulta com <strong>{selectedAppointment?.doctor?.full_name}</strong>.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<div className="grid gap-4 py-4">
|
||||||
|
<div className="grid gap-2">
|
||||||
|
<Label htmlFor="date">Nova Data</Label>
|
||||||
|
<Input id="date" type="date" value={rescheduleData.date} onChange={(e) => setRescheduleData((prev) => ({ ...prev, date: e.target.value }))} min={new Date().toISOString().split("T")[0]} />
|
||||||
|
</div>
|
||||||
|
<div className="grid gap-2">
|
||||||
|
<Label htmlFor="time">Novo Horário</Label>
|
||||||
|
<Select value={rescheduleData.time} onValueChange={(value) => setRescheduleData((prev) => ({ ...prev, time: value }))}>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue placeholder="Selecione um horário" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{timeSlots.map((time) => (
|
||||||
|
<SelectItem key={time} value={time}>
|
||||||
|
{time}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
<div className="grid gap-2">
|
||||||
|
<Label htmlFor="reason">Motivo (opcional)</Label>
|
||||||
|
<Textarea id="reason" placeholder="Explique brevemente o motivo do reagendamento..." value={rescheduleData.reason} onChange={(e) => setRescheduleData((prev) => ({ ...prev, reason: e.target.value }))} />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
<DialogFooter>
|
||||||
|
<Button variant="outline" onClick={() => setRescheduleModal(false)}>
|
||||||
|
Cancelar
|
||||||
|
</Button>
|
||||||
|
<Button onClick={confirmReschedule}>Confirmar</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
{appointment.status !== "cancelled" && (
|
{/* MODAL DE CANCELAMENTO */}
|
||||||
<div className="flex gap-2 mt-4 pt-4 border-t">
|
<Dialog open={cancelModal} onOpenChange={setCancelModal}>
|
||||||
<Button variant="outline" size="sm" onClick={() => handleReschedule(appointment)}>
|
<DialogContent className="sm:max-w-[425px]">
|
||||||
<CalendarDays className="mr-2 h-4 w-4" />
|
<DialogHeader>
|
||||||
Reagendar
|
<DialogTitle>Cancelar Consulta</DialogTitle>
|
||||||
</Button>
|
<DialogDescription>
|
||||||
<Button
|
Deseja realmente cancelar sua consulta com <strong>{selectedAppointment?.doctor?.full_name}</strong>?
|
||||||
variant="outline"
|
</DialogDescription>
|
||||||
size="sm"
|
</DialogHeader>
|
||||||
className="text-red-600 hover:text-red-700 hover:bg-red-50"
|
<div className="grid gap-4 py-4">
|
||||||
onClick={() => handleCancel(appointment)}
|
<div className="grid gap-2">
|
||||||
>
|
<Label htmlFor="cancel-reason" className="text-sm font-medium">
|
||||||
<X className="mr-2 h-4 w-4" />
|
Motivo do Cancelamento <span className="text-red-500">*</span>
|
||||||
Cancelar
|
</Label>
|
||||||
</Button>
|
<Textarea id="cancel-reason" placeholder="Informe o motivo do cancelamento (mínimo 10 caracteres)" value={cancelReason} onChange={(e) => setCancelReason(e.target.value)} className="min-h-[100px]" />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
<DialogFooter>
|
||||||
</CardContent>
|
<Button variant="outline" onClick={() => setCancelModal(false)}>
|
||||||
</Card>
|
Voltar
|
||||||
))
|
</Button>
|
||||||
) : (
|
<Button variant="destructive" onClick={confirmCancel}>
|
||||||
<p className="text-gray-600">Você ainda não possui consultas agendadas.</p>
|
Confirmar Cancelamento
|
||||||
)}
|
</Button>
|
||||||
</div>
|
</DialogFooter>
|
||||||
</div>
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
{/* MODAL DE REAGENDAMENTO */}
|
</PatientLayout>
|
||||||
<Dialog open={rescheduleModal} onOpenChange={setRescheduleModal}>
|
);
|
||||||
<DialogContent className="sm:max-w-[425px]">
|
|
||||||
<DialogHeader>
|
|
||||||
<DialogTitle>Reagendar Consulta</DialogTitle>
|
|
||||||
<DialogDescription>
|
|
||||||
Escolha uma nova data e horário para sua consulta com{" "}
|
|
||||||
<strong>{selectedAppointment?.doctor?.full_name}</strong>.
|
|
||||||
</DialogDescription>
|
|
||||||
</DialogHeader>
|
|
||||||
<div className="grid gap-4 py-4">
|
|
||||||
<div className="grid gap-2">
|
|
||||||
<Label htmlFor="date">Nova Data</Label>
|
|
||||||
<Input
|
|
||||||
id="date"
|
|
||||||
type="date"
|
|
||||||
value={rescheduleData.date}
|
|
||||||
onChange={(e) => setRescheduleData((prev) => ({ ...prev, date: e.target.value }))}
|
|
||||||
min={new Date().toISOString().split("T")[0]}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="grid gap-2">
|
|
||||||
<Label htmlFor="time">Novo Horário</Label>
|
|
||||||
<Select
|
|
||||||
value={rescheduleData.time}
|
|
||||||
onValueChange={(value) => setRescheduleData((prev) => ({ ...prev, time: value }))}
|
|
||||||
>
|
|
||||||
<SelectTrigger>
|
|
||||||
<SelectValue placeholder="Selecione um horário" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
{timeSlots.map((time) => (
|
|
||||||
<SelectItem key={time} value={time}>
|
|
||||||
{time}
|
|
||||||
</SelectItem>
|
|
||||||
))}
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
<div className="grid gap-2">
|
|
||||||
<Label htmlFor="reason">Motivo (opcional)</Label>
|
|
||||||
<Textarea
|
|
||||||
id="reason"
|
|
||||||
placeholder="Explique brevemente o motivo do reagendamento..."
|
|
||||||
value={rescheduleData.reason}
|
|
||||||
onChange={(e) => setRescheduleData((prev) => ({ ...prev, reason: e.target.value }))}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<DialogFooter>
|
|
||||||
<Button variant="outline" onClick={() => setRescheduleModal(false)}>
|
|
||||||
Cancelar
|
|
||||||
</Button>
|
|
||||||
<Button onClick={confirmReschedule}>Confirmar</Button>
|
|
||||||
</DialogFooter>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
|
|
||||||
{/* MODAL DE CANCELAMENTO */}
|
|
||||||
<Dialog open={cancelModal} onOpenChange={setCancelModal}>
|
|
||||||
<DialogContent className="sm:max-w-[425px]">
|
|
||||||
<DialogHeader>
|
|
||||||
<DialogTitle>Cancelar Consulta</DialogTitle>
|
|
||||||
<DialogDescription>
|
|
||||||
Deseja realmente cancelar sua consulta com{" "}
|
|
||||||
<strong>{selectedAppointment?.doctor?.full_name}</strong>?
|
|
||||||
</DialogDescription>
|
|
||||||
</DialogHeader>
|
|
||||||
<div className="grid gap-4 py-4">
|
|
||||||
<div className="grid gap-2">
|
|
||||||
<Label htmlFor="cancel-reason" className="text-sm font-medium">
|
|
||||||
Motivo do Cancelamento <span className="text-red-500">*</span>
|
|
||||||
</Label>
|
|
||||||
<Textarea
|
|
||||||
id="cancel-reason"
|
|
||||||
placeholder="Informe o motivo do cancelamento (mínimo 10 caracteres)"
|
|
||||||
value={cancelReason}
|
|
||||||
onChange={(e) => setCancelReason(e.target.value)}
|
|
||||||
className="min-h-[100px]"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<DialogFooter>
|
|
||||||
<Button variant="outline" onClick={() => setCancelModal(false)}>
|
|
||||||
Voltar
|
|
||||||
</Button>
|
|
||||||
<Button variant="destructive" onClick={confirmCancel}>
|
|
||||||
Confirmar Cancelamento
|
|
||||||
</Button>
|
|
||||||
</DialogFooter>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
</PatientLayout>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,354 +1,293 @@
|
|||||||
"use client"
|
"use client";
|
||||||
|
|
||||||
import { useState, useEffect, useCallback } from "react"
|
import { useState, useEffect, useCallback } from "react";
|
||||||
import { Calendar, Clock, User } from "lucide-react"
|
import { Calendar, Clock, User } from "lucide-react";
|
||||||
import PatientLayout from "@/components/patient-layout"
|
import PatientLayout from "@/components/patient-layout";
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import { Button } from "@/components/ui/button"
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input"
|
import { Input } from "@/components/ui/input";
|
||||||
import { Label } from "@/components/ui/label"
|
import { Label } from "@/components/ui/label";
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
import { Textarea } from "@/components/ui/textarea"
|
import { Textarea } from "@/components/ui/textarea";
|
||||||
import { doctorsService } from "services/doctorsApi.mjs"
|
import { doctorsService } from "services/doctorsApi.mjs";
|
||||||
|
|
||||||
interface Doctor {
|
interface Doctor {
|
||||||
id: string
|
id: string;
|
||||||
full_name: string
|
full_name: string;
|
||||||
specialty: string
|
specialty: string;
|
||||||
phone_mobile: string
|
phone_mobile: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
const APPOINTMENTS_STORAGE_KEY = "clinic-appointments"
|
const APPOINTMENTS_STORAGE_KEY = "clinic-appointments";
|
||||||
|
|
||||||
export default function ScheduleAppointment() {
|
export default function ScheduleAppointment() {
|
||||||
const [selectedDoctor, setSelectedDoctor] = useState("")
|
const [selectedDoctor, setSelectedDoctor] = useState("");
|
||||||
const [selectedDate, setSelectedDate] = useState("")
|
const [selectedDate, setSelectedDate] = useState("");
|
||||||
const [selectedTime, setSelectedTime] = useState("")
|
const [selectedTime, setSelectedTime] = useState("");
|
||||||
const [notes, setNotes] = useState("")
|
const [notes, setNotes] = useState("");
|
||||||
|
|
||||||
// novos campos
|
// novos campos
|
||||||
const [tipoConsulta, setTipoConsulta] = useState("presencial")
|
const [tipoConsulta, setTipoConsulta] = useState("presencial");
|
||||||
const [duracao, setDuracao] = useState("30")
|
const [duracao, setDuracao] = useState("30");
|
||||||
const [convenio, setConvenio] = useState("")
|
const [convenio, setConvenio] = useState("");
|
||||||
const [queixa, setQueixa] = useState("")
|
const [queixa, setQueixa] = useState("");
|
||||||
const [obsPaciente, setObsPaciente] = useState("")
|
const [obsPaciente, setObsPaciente] = useState("");
|
||||||
const [obsInternas, setObsInternas] = useState("")
|
const [obsInternas, setObsInternas] = useState("");
|
||||||
|
|
||||||
const [doctors, setDoctors] = useState<Doctor[]>([])
|
const [doctors, setDoctors] = useState<Doctor[]>([]);
|
||||||
const [loading, setLoading] = useState(true)
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState<string | null>(null)
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
const fetchDoctors = useCallback(async () => {
|
const fetchDoctors = useCallback(async () => {
|
||||||
setLoading(true)
|
setLoading(true);
|
||||||
setError(null)
|
setError(null);
|
||||||
try {
|
try {
|
||||||
const data: Doctor[] = await doctorsService.list()
|
const data: Doctor[] = await doctorsService.list();
|
||||||
setDoctors(data || [])
|
console.log(data);
|
||||||
} catch (e: any) {
|
setDoctors(data || []);
|
||||||
console.error("Erro ao carregar lista de médicos:", e)
|
} catch (e: any) {
|
||||||
setError("Não foi possível carregar a lista de médicos. Verifique a conexão com a API.")
|
console.error("Erro ao carregar lista de médicos:", e);
|
||||||
setDoctors([])
|
setError("Não foi possível carregar a lista de médicos. Verifique a conexão com a API.");
|
||||||
} finally {
|
setDoctors([]);
|
||||||
setLoading(false)
|
} finally {
|
||||||
}
|
setLoading(false);
|
||||||
}, [])
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchDoctors()
|
fetchDoctors();
|
||||||
}, [fetchDoctors])
|
}, [fetchDoctors]);
|
||||||
|
|
||||||
const availableTimes = [
|
const availableTimes = ["08:00", "08:30", "09:00", "09:30", "10:00", "10:30", "14:00", "14:30", "15:00", "15:30", "16:00", "16:30"];
|
||||||
"08:00",
|
|
||||||
"08:30",
|
|
||||||
"09:00",
|
|
||||||
"09:30",
|
|
||||||
"10:00",
|
|
||||||
"10:30",
|
|
||||||
"14:00",
|
|
||||||
"14:30",
|
|
||||||
"15:00",
|
|
||||||
"15:30",
|
|
||||||
"16:00",
|
|
||||||
"16:30",
|
|
||||||
]
|
|
||||||
|
|
||||||
const handleSubmit = (e: React.FormEvent) => {
|
const handleSubmit = (e: React.FormEvent) => {
|
||||||
e.preventDefault()
|
e.preventDefault();
|
||||||
|
|
||||||
const doctorDetails = doctors.find((d) => d.id === selectedDoctor)
|
const doctorDetails = doctors.find((d) => d.id === selectedDoctor);
|
||||||
const patientDetails = {
|
const patientDetails = {
|
||||||
id: "P001",
|
id: "P001",
|
||||||
full_name: "Paciente Exemplo Único",
|
full_name: "Paciente Exemplo Único",
|
||||||
location: "Clínica Geral",
|
location: "Clínica Geral",
|
||||||
phone: "(11) 98765-4321",
|
phone: "(11) 98765-4321",
|
||||||
}
|
};
|
||||||
|
|
||||||
if (!patientDetails || !doctorDetails) {
|
if (!patientDetails || !doctorDetails) {
|
||||||
alert("Erro: Selecione o médico ou dados do paciente indisponíveis.")
|
alert("Erro: Selecione o médico ou dados do paciente indisponíveis.");
|
||||||
return
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const newAppointment = {
|
const newAppointment = {
|
||||||
id: new Date().getTime(),
|
id: new Date().getTime(),
|
||||||
patientName: patientDetails.full_name,
|
patientName: patientDetails.full_name,
|
||||||
doctor: doctorDetails.full_name,
|
doctor: doctorDetails.full_name,
|
||||||
specialty: doctorDetails.specialty,
|
specialty: doctorDetails.specialty,
|
||||||
date: selectedDate,
|
date: selectedDate,
|
||||||
time: selectedTime,
|
time: selectedTime,
|
||||||
tipoConsulta,
|
tipoConsulta,
|
||||||
duracao,
|
duracao,
|
||||||
convenio,
|
convenio,
|
||||||
queixa,
|
queixa,
|
||||||
obsPaciente,
|
obsPaciente,
|
||||||
obsInternas,
|
obsInternas,
|
||||||
notes,
|
notes,
|
||||||
status: "agendada",
|
status: "agendada",
|
||||||
phone: patientDetails.phone,
|
phone: patientDetails.phone,
|
||||||
}
|
};
|
||||||
|
|
||||||
const storedAppointmentsRaw = localStorage.getItem(APPOINTMENTS_STORAGE_KEY)
|
const storedAppointmentsRaw = localStorage.getItem(APPOINTMENTS_STORAGE_KEY);
|
||||||
const currentAppointments = storedAppointmentsRaw ? JSON.parse(storedAppointmentsRaw) : []
|
const currentAppointments = storedAppointmentsRaw ? JSON.parse(storedAppointmentsRaw) : [];
|
||||||
const updatedAppointments = [...currentAppointments, newAppointment]
|
const updatedAppointments = [...currentAppointments, newAppointment];
|
||||||
localStorage.setItem(APPOINTMENTS_STORAGE_KEY, JSON.stringify(updatedAppointments))
|
localStorage.setItem(APPOINTMENTS_STORAGE_KEY, JSON.stringify(updatedAppointments));
|
||||||
|
|
||||||
alert(`Consulta com ${doctorDetails.full_name} agendada com sucesso!`)
|
alert(`Consulta com ${doctorDetails.full_name} agendada com sucesso!`);
|
||||||
|
|
||||||
// resetar campos
|
// resetar campos
|
||||||
setSelectedDoctor("")
|
setSelectedDoctor("");
|
||||||
setSelectedDate("")
|
setSelectedDate("");
|
||||||
setSelectedTime("")
|
setSelectedTime("");
|
||||||
setNotes("")
|
setNotes("");
|
||||||
setTipoConsulta("presencial")
|
setTipoConsulta("presencial");
|
||||||
setDuracao("30")
|
setDuracao("30");
|
||||||
setConvenio("")
|
setConvenio("");
|
||||||
setQueixa("")
|
setQueixa("");
|
||||||
setObsPaciente("")
|
setObsPaciente("");
|
||||||
setObsInternas("")
|
setObsInternas("");
|
||||||
}
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PatientLayout>
|
<PatientLayout>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-3xl font-bold text-gray-900">Agendar Consulta</h1>
|
<h1 className="text-3xl font-bold text-gray-900">Agendar Consulta</h1>
|
||||||
<p className="text-gray-600">Escolha o médico, data e horário para sua consulta</p>
|
<p className="text-gray-600">Escolha o médico, data e horário para sua consulta</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid lg:grid-cols-3 gap-6">
|
<div className="grid lg:grid-cols-3 gap-6">
|
||||||
<div className="lg:col-span-2">
|
<div className="lg:col-span-2">
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>Dados da Consulta</CardTitle>
|
<CardTitle>Dados da Consulta</CardTitle>
|
||||||
<CardDescription>Preencha as informações para agendar sua consulta</CardDescription>
|
<CardDescription>Preencha as informações para agendar sua consulta</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<form onSubmit={handleSubmit} className="space-y-6">
|
<form onSubmit={handleSubmit} className="space-y-6">
|
||||||
|
{/* Médico */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="doctor">Médico</Label>
|
||||||
|
<Select value={selectedDoctor} onValueChange={setSelectedDoctor}>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue placeholder="Selecione um médico" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{loading ? (
|
||||||
|
<SelectItem value="loading" disabled>
|
||||||
|
Carregando médicos...
|
||||||
|
</SelectItem>
|
||||||
|
) : error ? (
|
||||||
|
<SelectItem value="error" disabled>
|
||||||
|
Erro ao carregar
|
||||||
|
</SelectItem>
|
||||||
|
) : (
|
||||||
|
doctors.map((doctor) => (
|
||||||
|
<SelectItem key={doctor.id} value={doctor.id}>
|
||||||
|
{doctor.full_name} - {doctor.specialty}
|
||||||
|
</SelectItem>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Data e horário */}
|
||||||
|
<div className="grid md:grid-cols-2 gap-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="date">Data</Label>
|
||||||
|
<Input id="date" type="date" value={selectedDate} onChange={(e) => setSelectedDate(e.target.value)} min={new Date().toISOString().split("T")[0]} />
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* Médico */}
|
<div className="space-y-2">
|
||||||
<div className="space-y-2">
|
<Label htmlFor="time">Horário</Label>
|
||||||
<Label htmlFor="doctor">Médico</Label>
|
<Select value={selectedTime} onValueChange={setSelectedTime}>
|
||||||
<Select value={selectedDoctor} onValueChange={setSelectedDoctor}>
|
<SelectTrigger>
|
||||||
<SelectTrigger>
|
<SelectValue placeholder="Selecione um horário" />
|
||||||
<SelectValue placeholder="Selecione um médico" />
|
</SelectTrigger>
|
||||||
</SelectTrigger>
|
<SelectContent>
|
||||||
<SelectContent>
|
{availableTimes.map((time) => (
|
||||||
{loading ? (
|
<SelectItem key={time} value={time}>
|
||||||
<SelectItem value="loading" disabled>
|
{time}
|
||||||
Carregando médicos...
|
</SelectItem>
|
||||||
</SelectItem>
|
))}
|
||||||
) : error ? (
|
</SelectContent>
|
||||||
<SelectItem value="error" disabled>
|
</Select>
|
||||||
Erro ao carregar
|
</div>
|
||||||
</SelectItem>
|
</div>
|
||||||
) : (
|
{/* Tipo e Duração */}
|
||||||
doctors.map((doctor) => (
|
<div className="grid md:grid-cols-2 gap-4">
|
||||||
<SelectItem key={doctor.id} value={doctor.id}>
|
<div className="space-y-2">
|
||||||
{doctor.full_name} - {doctor.specialty}
|
<Label htmlFor="tipoConsulta">Tipo de Consulta</Label>
|
||||||
</SelectItem>
|
<Select value={tipoConsulta} onValueChange={setTipoConsulta}>
|
||||||
))
|
<SelectTrigger id="tipoConsulta">
|
||||||
)}
|
<SelectValue placeholder="Selecione o tipo" />
|
||||||
</SelectContent>
|
</SelectTrigger>
|
||||||
</Select>
|
<SelectContent>
|
||||||
</div>
|
<SelectItem value="presencial">Presencial</SelectItem>
|
||||||
|
<SelectItem value="online">Telemedicina</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* Data e horário */}
|
<div className="space-y-2">
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
<Label htmlFor="duracao">Duração (minutos)</Label>
|
||||||
<div className="space-y-2">
|
<Input id="duracao" type="number" min={10} max={120} value={duracao} onChange={(e) => setDuracao(e.target.value)} />
|
||||||
<Label htmlFor="date">Data</Label>
|
</div>
|
||||||
<Input
|
</div>
|
||||||
id="date"
|
|
||||||
type="date"
|
{/* Convênio */}
|
||||||
value={selectedDate}
|
<div className="space-y-2">
|
||||||
onChange={(e) => setSelectedDate(e.target.value)}
|
<Label htmlFor="convenio">Convênio (opcional)</Label>
|
||||||
min={new Date().toISOString().split("T")[0]}
|
<Input id="convenio" placeholder="Nome do convênio do paciente" value={convenio} onChange={(e) => setConvenio(e.target.value)} />
|
||||||
/>
|
</div>
|
||||||
|
|
||||||
|
{/* Queixa Principal */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="queixa">Queixa Principal (opcional)</Label>
|
||||||
|
<Textarea id="queixa" placeholder="Descreva brevemente o motivo da consulta..." value={queixa} onChange={(e) => setQueixa(e.target.value)} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Observações do Paciente */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="obsPaciente">Observações do Paciente (opcional)</Label>
|
||||||
|
<Textarea id="obsPaciente" placeholder="Anotações relevantes informadas pelo paciente..." value={obsPaciente} onChange={(e) => setObsPaciente(e.target.value)} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Observações Internas */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="obsInternas">Observações Internas (opcional)</Label>
|
||||||
|
<Textarea id="obsInternas" placeholder="Anotações para a equipe da clínica..." value={obsInternas} onChange={(e) => setObsInternas(e.target.value)} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Observações gerais */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="notes">Observações gerais (opcional)</Label>
|
||||||
|
<Textarea id="notes" placeholder="Descreva brevemente o motivo da consulta ou observações importantes" value={notes} onChange={(e) => setNotes(e.target.value)} rows={3} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Botão */}
|
||||||
|
<Button type="submit" className="w-full" disabled={!selectedDoctor || !selectedDate || !selectedTime}>
|
||||||
|
Agendar Consulta
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
{/* Resumo */}
|
||||||
<Label htmlFor="time">Horário</Label>
|
<div className="space-y-6">
|
||||||
<Select value={selectedTime} onValueChange={setSelectedTime}>
|
<Card>
|
||||||
<SelectTrigger>
|
<CardHeader>
|
||||||
<SelectValue placeholder="Selecione um horário" />
|
<CardTitle className="flex items-center">
|
||||||
</SelectTrigger>
|
<Calendar className="mr-2 h-5 w-5" />
|
||||||
<SelectContent>
|
Resumo
|
||||||
{availableTimes.map((time) => (
|
</CardTitle>
|
||||||
<SelectItem key={time} value={time}>
|
</CardHeader>
|
||||||
{time}
|
<CardContent className="space-y-4">
|
||||||
</SelectItem>
|
{selectedDoctor && (
|
||||||
))}
|
<div className="flex items-center space-x-2">
|
||||||
</SelectContent>
|
<User className="h-4 w-4 text-gray-500" />
|
||||||
</Select>
|
<span className="text-sm">{doctors.find((d) => d.id === selectedDoctor)?.full_name}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{selectedDate && (
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<Calendar className="h-4 w-4 text-gray-500" />
|
||||||
|
<span className="text-sm">{new Date(selectedDate).toLocaleDateString("pt-BR")}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{selectedTime && (
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<Clock className="h-4 w-4 text-gray-500" />
|
||||||
|
<span className="text-sm">{selectedTime}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Informações Importantes</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="text-sm text-gray-600 space-y-2">
|
||||||
|
<p>• Chegue com 15 minutos de antecedência</p>
|
||||||
|
<p>• Traga documento com foto</p>
|
||||||
|
<p>• Traga carteirinha do convênio</p>
|
||||||
|
<p>• Traga exames anteriores, se houver</p>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{/* Tipo e Duração */}
|
</div>
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
</PatientLayout>
|
||||||
<div className="space-y-2">
|
);
|
||||||
<Label htmlFor="tipoConsulta">Tipo de Consulta</Label>
|
|
||||||
<Select value={tipoConsulta} onValueChange={setTipoConsulta}>
|
|
||||||
<SelectTrigger id="tipoConsulta">
|
|
||||||
<SelectValue placeholder="Selecione o tipo" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="presencial">Presencial</SelectItem>
|
|
||||||
<SelectItem value="online">Telemedicina</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="duracao">Duração (minutos)</Label>
|
|
||||||
<Input
|
|
||||||
id="duracao"
|
|
||||||
type="number"
|
|
||||||
min={10}
|
|
||||||
max={120}
|
|
||||||
value={duracao}
|
|
||||||
onChange={(e) => setDuracao(e.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Convênio */}
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="convenio">Convênio (opcional)</Label>
|
|
||||||
<Input
|
|
||||||
id="convenio"
|
|
||||||
placeholder="Nome do convênio do paciente"
|
|
||||||
value={convenio}
|
|
||||||
onChange={(e) => setConvenio(e.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Queixa Principal */}
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="queixa">Queixa Principal (opcional)</Label>
|
|
||||||
<Textarea
|
|
||||||
id="queixa"
|
|
||||||
placeholder="Descreva brevemente o motivo da consulta..."
|
|
||||||
value={queixa}
|
|
||||||
onChange={(e) => setQueixa(e.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Observações do Paciente */}
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="obsPaciente">Observações do Paciente (opcional)</Label>
|
|
||||||
<Textarea
|
|
||||||
id="obsPaciente"
|
|
||||||
placeholder="Anotações relevantes informadas pelo paciente..."
|
|
||||||
value={obsPaciente}
|
|
||||||
onChange={(e) => setObsPaciente(e.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Observações Internas */}
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="obsInternas">Observações Internas (opcional)</Label>
|
|
||||||
<Textarea
|
|
||||||
id="obsInternas"
|
|
||||||
placeholder="Anotações para a equipe da clínica..."
|
|
||||||
value={obsInternas}
|
|
||||||
onChange={(e) => setObsInternas(e.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Observações gerais */}
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="notes">Observações gerais (opcional)</Label>
|
|
||||||
<Textarea
|
|
||||||
id="notes"
|
|
||||||
placeholder="Descreva brevemente o motivo da consulta ou observações importantes"
|
|
||||||
value={notes}
|
|
||||||
onChange={(e) => setNotes(e.target.value)}
|
|
||||||
rows={3}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Botão */}
|
|
||||||
<Button
|
|
||||||
type="submit"
|
|
||||||
className="w-full"
|
|
||||||
disabled={!selectedDoctor || !selectedDate || !selectedTime}
|
|
||||||
>
|
|
||||||
Agendar Consulta
|
|
||||||
</Button>
|
|
||||||
</form>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Resumo */}
|
|
||||||
<div className="space-y-6">
|
|
||||||
<Card>
|
|
||||||
<CardHeader>
|
|
||||||
<CardTitle className="flex items-center">
|
|
||||||
<Calendar className="mr-2 h-5 w-5" />
|
|
||||||
Resumo
|
|
||||||
</CardTitle>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="space-y-4">
|
|
||||||
{selectedDoctor && (
|
|
||||||
<div className="flex items-center space-x-2">
|
|
||||||
<User className="h-4 w-4 text-gray-500" />
|
|
||||||
<span className="text-sm">
|
|
||||||
{doctors.find((d) => d.id === selectedDoctor)?.full_name}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{selectedDate && (
|
|
||||||
<div className="flex items-center space-x-2">
|
|
||||||
<Calendar className="h-4 w-4 text-gray-500" />
|
|
||||||
<span className="text-sm">
|
|
||||||
{new Date(selectedDate).toLocaleDateString("pt-BR")}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{selectedTime && (
|
|
||||||
<div className="flex items-center space-x-2">
|
|
||||||
<Clock className="h-4 w-4 text-gray-500" />
|
|
||||||
<span className="text-sm">{selectedTime}</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
<Card>
|
|
||||||
<CardHeader>
|
|
||||||
<CardTitle>Informações Importantes</CardTitle>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="text-sm text-gray-600 space-y-2">
|
|
||||||
<p>• Chegue com 15 minutos de antecedência</p>
|
|
||||||
<p>• Traga documento com foto</p>
|
|
||||||
<p>• Traga carteirinha do convênio</p>
|
|
||||||
<p>• Traga exames anteriores, se houver</p>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</PatientLayout>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,9 +1,9 @@
|
|||||||
// Caminho: components/LoginForm.tsx
|
// Caminho: components/LoginForm.tsx
|
||||||
"use client"
|
"use client";
|
||||||
|
|
||||||
import type React from "react"
|
import type React from "react";
|
||||||
import { useState } from "react"
|
import { useState } from "react";
|
||||||
import { useRouter } from "next/navigation"
|
import { useRouter } from "next/navigation";
|
||||||
|
|
||||||
// Nossos serviços de API centralizados e limpos
|
// Nossos serviços de API centralizados e limpos
|
||||||
import { login, api } from "@/services/api.mjs";
|
import { login, api } from "@/services/api.mjs";
|
||||||
@ -16,202 +16,196 @@ import { useToast } from "@/hooks/use-toast";
|
|||||||
import { Eye, EyeOff, Mail, Lock, Loader2 } from "lucide-react";
|
import { Eye, EyeOff, Mail, Lock, Loader2 } from "lucide-react";
|
||||||
|
|
||||||
interface LoginFormProps {
|
interface LoginFormProps {
|
||||||
children?: React.ReactNode
|
children?: React.ReactNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface FormState {
|
interface FormState {
|
||||||
email: string
|
email: string;
|
||||||
password: string
|
password: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function LoginForm({ children }: LoginFormProps) {
|
export function LoginForm({ children }: LoginFormProps) {
|
||||||
const [form, setForm] = useState<FormState>({ email: "", password: "" })
|
const [form, setForm] = useState<FormState>({ email: "", password: "" });
|
||||||
const [showPassword, setShowPassword] = useState(false)
|
const [showPassword, setShowPassword] = useState(false);
|
||||||
const [isLoading, setIsLoading] = useState(false)
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const router = useRouter()
|
const router = useRouter();
|
||||||
const { toast } = useToast()
|
const { toast } = useToast();
|
||||||
|
|
||||||
// --- NOVOS ESTADOS PARA CONTROLE DE MÚLTIPLOS PERFIS ---
|
// --- NOVOS ESTADOS PARA CONTROLE DE MÚLTIPLOS PERFIS ---
|
||||||
const [userRoles, setUserRoles] = useState<string[]>([]);
|
const [userRoles, setUserRoles] = useState<string[]>([]);
|
||||||
const [authenticatedUser, setAuthenticatedUser] = useState<any>(null);
|
const [authenticatedUser, setAuthenticatedUser] = useState<any>(null);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* --- NOVA FUNÇÃO ---
|
* --- NOVA FUNÇÃO ---
|
||||||
* Finaliza o login com o perfil de dashboard escolhido e redireciona.
|
* Finaliza o login com o perfil de dashboard escolhido e redireciona.
|
||||||
*/
|
*/
|
||||||
const handleRoleSelection = (selectedDashboardRole: string) => {
|
const handleRoleSelection = (selectedDashboardRole: string) => {
|
||||||
const user = authenticatedUser;
|
const user = authenticatedUser;
|
||||||
if (!user) {
|
if (!user) {
|
||||||
toast({ title: "Erro de Sessão", description: "Não foi possível encontrar os dados do usuário. Tente novamente.", variant: "destructive" });
|
toast({ title: "Erro de Sessão", description: "Não foi possível encontrar os dados do usuário. Tente novamente.", variant: "destructive" });
|
||||||
setUserRoles([]); // Volta para a tela de login
|
setUserRoles([]); // Volta para a tela de login
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const completeUserInfo = { ...user, user_metadata: { ...user.user_metadata, role: selectedDashboardRole } };
|
|
||||||
localStorage.setItem('user_info', JSON.stringify(completeUserInfo));
|
|
||||||
|
|
||||||
let redirectPath = "";
|
|
||||||
switch (selectedDashboardRole) {
|
|
||||||
case "manager": redirectPath = "/manager/home"; break;
|
|
||||||
case "doctor": redirectPath = "/doctor/medicos"; break;
|
|
||||||
case "secretary": redirectPath = "/secretary/pacientes"; break;
|
|
||||||
case "patient": redirectPath = "/patient/dashboard"; break;
|
|
||||||
case "finance": redirectPath = "/finance/home"; break;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (redirectPath) {
|
|
||||||
toast({ title: `Entrando como ${selectedDashboardRole}...` });
|
|
||||||
router.push(redirectPath);
|
|
||||||
} else {
|
|
||||||
toast({ title: "Erro", description: "Perfil selecionado inválido.", variant: "destructive" });
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* --- FUNÇÃO ATUALIZADA ---
|
|
||||||
* Lida com a submissão do formulário, busca os perfis e decide o próximo passo.
|
|
||||||
*/
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
|
||||||
e.preventDefault();
|
|
||||||
setIsLoading(true);
|
|
||||||
localStorage.removeItem("token");
|
|
||||||
localStorage.removeItem("user_info");
|
|
||||||
|
|
||||||
try {
|
|
||||||
// A chamada de login continua a mesma
|
|
||||||
const authData = await login();
|
|
||||||
const user = authData.user;
|
|
||||||
if (!user || !user.id) {
|
|
||||||
throw new Error("Resposta de autenticação inválida.");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Armazena o usuário para uso posterior na seleção de perfil
|
|
||||||
setAuthenticatedUser(user);
|
|
||||||
|
|
||||||
// A busca de roles também continua a mesma, usando nosso 'api.get'
|
|
||||||
const rolesData = await api.get(`/rest/v1/user_roles?user_id=eq.${user.id}&select=role`);
|
|
||||||
|
|
||||||
if (!rolesData || rolesData.length === 0) {
|
|
||||||
throw new Error("Nenhum perfil de acesso foi encontrado para este usuário.");
|
|
||||||
}
|
|
||||||
|
|
||||||
const rolesFromApi: string[] = rolesData.map((r: any) => r.role);
|
|
||||||
|
|
||||||
// --- AQUI COMEÇA A NOVA LÓGICA DE DECISÃO ---
|
|
||||||
|
|
||||||
// Caso 1: Usuário é ADMIN, mostra todos os dashboards possíveis.
|
|
||||||
if (rolesFromApi.includes('admin')) {
|
|
||||||
setUserRoles(["manager", "doctor", "secretary", "patient", "finance"]);
|
|
||||||
setIsLoading(false); // Para o loading para mostrar a tela de seleção
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mapeia os roles da API para os perfis de dashboard que o usuário pode acessar
|
const completeUserInfo = { ...user, user_metadata: { ...user.user_metadata, role: selectedDashboardRole } };
|
||||||
const displayRoles = new Set<string>();
|
localStorage.setItem("user_info", JSON.stringify(completeUserInfo));
|
||||||
rolesFromApi.forEach(role => {
|
|
||||||
switch (role) {
|
|
||||||
case 'gestor':
|
|
||||||
displayRoles.add('manager');
|
|
||||||
displayRoles.add('finance');
|
|
||||||
break;
|
|
||||||
case 'medico':
|
|
||||||
displayRoles.add('doctor');
|
|
||||||
break;
|
|
||||||
case 'secretaria':
|
|
||||||
displayRoles.add('secretary');
|
|
||||||
break;
|
|
||||||
case 'patient': // Mapeamento de 'patient' (ou outro nome que você use para paciente)
|
|
||||||
displayRoles.add('patient');
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const finalRoles = Array.from(displayRoles);
|
let redirectPath = "";
|
||||||
|
switch (selectedDashboardRole) {
|
||||||
// Caso 2: Se o usuário tem apenas UM perfil de dashboard, redireciona direto.
|
case "manager":
|
||||||
if (finalRoles.length === 1) {
|
redirectPath = "/manager/home";
|
||||||
handleRoleSelection(finalRoles[0]);
|
break;
|
||||||
}
|
case "doctor":
|
||||||
// Caso 3: Se tem múltiplos perfis (ex: 'gestor'), mostra a tela de seleção.
|
redirectPath = "/doctor/medicos";
|
||||||
else {
|
break;
|
||||||
setUserRoles(finalRoles);
|
case "secretary":
|
||||||
|
redirectPath = "/secretary/pacientes";
|
||||||
|
break;
|
||||||
|
case "patient":
|
||||||
|
redirectPath = "/patient/dashboard";
|
||||||
|
break;
|
||||||
|
case "finance":
|
||||||
|
redirectPath = "/finance/home";
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (error) {
|
if (redirectPath) {
|
||||||
|
toast({ title: `Entrando como ${selectedDashboardRole}...` });
|
||||||
|
router.push(redirectPath);
|
||||||
|
} else {
|
||||||
|
toast({ title: "Erro", description: "Perfil selecionado inválido.", variant: "destructive" });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* --- FUNÇÃO ATUALIZADA ---
|
||||||
|
* Lida com a submissão do formulário, busca os perfis e decide o próximo passo.
|
||||||
|
*/
|
||||||
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setIsLoading(true);
|
||||||
localStorage.removeItem("token");
|
localStorage.removeItem("token");
|
||||||
localStorage.removeItem("user_info");
|
localStorage.removeItem("user_info");
|
||||||
|
|
||||||
toast({
|
try {
|
||||||
title: "Erro no Login",
|
// A chamada de login continua a mesma
|
||||||
description: error instanceof Error ? error.message : "Ocorreu um erro inesperado.",
|
const authData = await login(form.email, form.password);
|
||||||
variant: "destructive",
|
const user = authData.user;
|
||||||
});
|
if (!user || !user.id) {
|
||||||
} finally {
|
throw new Error("Resposta de autenticação inválida.");
|
||||||
// Apenas para o loading se não houver redirecionamento ou seleção de perfil
|
}
|
||||||
if (userRoles.length === 0) {
|
|
||||||
setIsLoading(false);
|
// Armazena o usuário para uso posterior na seleção de perfil
|
||||||
|
setAuthenticatedUser(user);
|
||||||
|
|
||||||
|
// A busca de roles também continua a mesma, usando nosso 'api.get'
|
||||||
|
const rolesData = await api.get(`/rest/v1/user_roles?user_id=eq.${user.id}&select=role`);
|
||||||
|
|
||||||
|
if (!rolesData || rolesData.length === 0) {
|
||||||
|
throw new Error("Nenhum perfil de acesso foi encontrado para este usuário.");
|
||||||
|
}
|
||||||
|
|
||||||
|
const rolesFromApi: string[] = rolesData.map((r: any) => r.role);
|
||||||
|
|
||||||
|
// --- AQUI COMEÇA A NOVA LÓGICA DE DECISÃO ---
|
||||||
|
|
||||||
|
// Caso 1: Usuário é ADMIN, mostra todos os dashboards possíveis.
|
||||||
|
if (rolesFromApi.includes("admin")) {
|
||||||
|
setUserRoles(["manager", "doctor", "secretary", "paciente", "finance"]);
|
||||||
|
setIsLoading(false); // Para o loading para mostrar a tela de seleção
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mapeia os roles da API para os perfis de dashboard que o usuário pode acessar
|
||||||
|
const displayRoles = new Set<string>();
|
||||||
|
rolesFromApi.forEach((role) => {
|
||||||
|
switch (role) {
|
||||||
|
case "gestor":
|
||||||
|
displayRoles.add("manager");
|
||||||
|
displayRoles.add("finance");
|
||||||
|
break;
|
||||||
|
case "medico":
|
||||||
|
displayRoles.add("doctor");
|
||||||
|
break;
|
||||||
|
case "secretaria":
|
||||||
|
displayRoles.add("secretary");
|
||||||
|
break;
|
||||||
|
case "paciente": // Mapeamento de 'patient' (ou outro nome que você use para paciente)
|
||||||
|
displayRoles.add("patient");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const finalRoles = Array.from(displayRoles);
|
||||||
|
|
||||||
|
// Caso 2: Se o usuário tem apenas UM perfil de dashboard, redireciona direto.
|
||||||
|
if (finalRoles.length === 1) {
|
||||||
|
handleRoleSelection(finalRoles[0]);
|
||||||
|
}
|
||||||
|
// Caso 3: Se tem múltiplos perfis (ex: 'gestor'), mostra a tela de seleção.
|
||||||
|
else {
|
||||||
|
setUserRoles(finalRoles);
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
localStorage.removeItem("token");
|
||||||
|
localStorage.removeItem("user_info");
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: "Erro no Login",
|
||||||
|
description: error instanceof Error ? error.message : "Ocorreu um erro inesperado.",
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// --- JSX ATUALIZADO COM RENDERIZAÇÃO CONDICIONAL ---
|
setIsLoading(false);
|
||||||
return (
|
};
|
||||||
<Card className="w-full bg-transparent border-0 shadow-none">
|
|
||||||
<CardContent className="p-0">
|
|
||||||
{userRoles.length === 0 ? (
|
|
||||||
// VISÃO 1: Formulário de Login (se nenhum perfil foi carregado ainda)
|
|
||||||
<form onSubmit={handleSubmit} className="space-y-6">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="email">E-mail</Label>
|
|
||||||
<div className="relative">
|
|
||||||
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground w-5 h-5" />
|
|
||||||
<Input
|
|
||||||
id="email" type="email" placeholder="seu.email@exemplo.com"
|
|
||||||
value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })}
|
|
||||||
className="pl-10 h-11" required disabled={isLoading} autoComplete="username"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="password">Senha</Label>
|
|
||||||
<div className="relative">
|
|
||||||
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground w-5 h-5" />
|
|
||||||
<Input
|
|
||||||
id="password" type={showPassword ? "text" : "password"} placeholder="Digite sua senha"
|
|
||||||
value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })}
|
|
||||||
className="pl-10 pr-12 h-11" required disabled={isLoading} autoComplete="current-password"
|
|
||||||
/>
|
|
||||||
<button type="button" onClick={() => setShowPassword(!showPassword)} className="absolute right-2 top-1/2 -translate-y-1/2 h-8 w-8 p-0 text-muted-foreground hover:text-foreground" disabled={isLoading}>
|
|
||||||
{showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<Button type="submit" className="w-full h-11 text-base font-semibold" disabled={isLoading}>
|
|
||||||
{isLoading ? <Loader2 className="w-5 h-5 animate-spin" /> : "Entrar"}
|
|
||||||
</Button>
|
|
||||||
</form>
|
|
||||||
) : (
|
|
||||||
// VISÃO 2: Tela de Seleção de Perfil (se múltiplos perfis foram encontrados)
|
|
||||||
<div className="space-y-4 animate-in fade-in-50">
|
|
||||||
<h3 className="text-lg font-medium text-center text-foreground">Você tem múltiplos perfis</h3>
|
|
||||||
<p className="text-sm text-muted-foreground text-center">Selecione com qual perfil deseja entrar:</p>
|
|
||||||
<div className="flex flex-col space-y-3 pt-2">
|
|
||||||
{userRoles.map((role) => (
|
|
||||||
<Button
|
|
||||||
key={role}
|
|
||||||
variant="outline"
|
|
||||||
className="h-11 text-base"
|
|
||||||
onClick={() => handleRoleSelection(role)}
|
|
||||||
>
|
|
||||||
Entrar como: {role.charAt(0).toUpperCase() + role.slice(1)}
|
|
||||||
</Button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{children}
|
// --- JSX ATUALIZADO COM RENDERIZAÇÃO CONDICIONAL ---
|
||||||
</CardContent>
|
return (
|
||||||
</Card>
|
<Card className="w-full bg-transparent border-0 shadow-none">
|
||||||
)
|
<CardContent className="p-0">
|
||||||
}
|
{userRoles.length === 0 ? (
|
||||||
|
// VISÃO 1: Formulário de Login (se nenhum perfil foi carregado ainda)
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-6">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="email">E-mail</Label>
|
||||||
|
<div className="relative">
|
||||||
|
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground w-5 h-5" />
|
||||||
|
<Input id="email" type="email" placeholder="seu.email@exemplo.com" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} className="pl-10 h-11" required disabled={isLoading} autoComplete="username" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="password">Senha</Label>
|
||||||
|
<div className="relative">
|
||||||
|
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground w-5 h-5" />
|
||||||
|
<Input id="password" type={showPassword ? "text" : "password"} placeholder="Digite sua senha" value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })} className="pl-10 pr-12 h-11" required disabled={isLoading} autoComplete="current-password" />
|
||||||
|
<button type="button" onClick={() => setShowPassword(!showPassword)} className="absolute right-2 top-1/2 -translate-y-1/2 h-8 w-8 p-0 text-muted-foreground hover:text-foreground" disabled={isLoading}>
|
||||||
|
{showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Button type="submit" className="w-full h-11 text-base font-semibold" disabled={isLoading}>
|
||||||
|
{isLoading ? <Loader2 className="w-5 h-5 animate-spin" /> : "Entrar"}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
) : (
|
||||||
|
// VISÃO 2: Tela de Seleção de Perfil (se múltiplos perfis foram encontrados)
|
||||||
|
<div className="space-y-4 animate-in fade-in-50">
|
||||||
|
<h3 className="text-lg font-medium text-center text-foreground">Você tem múltiplos perfis</h3>
|
||||||
|
<p className="text-sm text-muted-foreground text-center">Selecione com qual perfil deseja entrar:</p>
|
||||||
|
<div className="flex flex-col space-y-3 pt-2">
|
||||||
|
{userRoles.map((role) => (
|
||||||
|
<Button key={role} variant="outline" className="h-11 text-base" onClick={() => handleRoleSelection(role)}>
|
||||||
|
Entrar como: {role.charAt(0).toUpperCase() + role.slice(1)}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{children}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@ -1,129 +1,52 @@
|
|||||||
'use client'
|
"use client";
|
||||||
|
|
||||||
import * as React from 'react'
|
import * as React from "react";
|
||||||
import * as ToastPrimitives from '@radix-ui/react-toast'
|
import * as ToastPrimitives from "@radix-ui/react-toast";
|
||||||
import { cva, type VariantProps } from 'class-variance-authority'
|
import { cva, type VariantProps } from "class-variance-authority";
|
||||||
import { X } from 'lucide-react'
|
import { X } from "lucide-react";
|
||||||
|
|
||||||
import { cn } from '@/lib/utils'
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
const ToastProvider = ToastPrimitives.Provider
|
const ToastProvider = ToastPrimitives.Provider;
|
||||||
|
|
||||||
const ToastViewport = React.forwardRef<
|
const ToastViewport = React.forwardRef<React.ElementRef<typeof ToastPrimitives.Viewport>, React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>>(({ className, ...props }, ref) => <ToastPrimitives.Viewport ref={ref} className={cn("fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]", className)} {...props} />);
|
||||||
React.ElementRef<typeof ToastPrimitives.Viewport>,
|
ToastViewport.displayName = ToastPrimitives.Viewport.displayName;
|
||||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>
|
|
||||||
>(({ className, ...props }, ref) => (
|
|
||||||
<ToastPrimitives.Viewport
|
|
||||||
ref={ref}
|
|
||||||
className={cn(
|
|
||||||
'fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]',
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
))
|
|
||||||
ToastViewport.displayName = ToastPrimitives.Viewport.displayName
|
|
||||||
|
|
||||||
const toastVariants = cva(
|
const toastVariants = cva("group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full", {
|
||||||
'group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full',
|
|
||||||
{
|
|
||||||
variants: {
|
variants: {
|
||||||
variant: {
|
variant: {
|
||||||
default: 'border bg-background text-foreground',
|
default: "border bg-background text-foreground",
|
||||||
destructive:
|
destructive: "destructive group border-destructive bg-destructive text-foreground",
|
||||||
'destructive group border-destructive bg-destructive text-destructive-foreground',
|
},
|
||||||
},
|
|
||||||
},
|
},
|
||||||
defaultVariants: {
|
defaultVariants: {
|
||||||
variant: 'default',
|
variant: "default",
|
||||||
},
|
},
|
||||||
},
|
});
|
||||||
)
|
|
||||||
|
|
||||||
const Toast = React.forwardRef<
|
const Toast = React.forwardRef<React.ElementRef<typeof ToastPrimitives.Root>, React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> & VariantProps<typeof toastVariants>>(({ className, variant, ...props }, ref) => {
|
||||||
React.ElementRef<typeof ToastPrimitives.Root>,
|
return <ToastPrimitives.Root ref={ref} className={cn(toastVariants({ variant }), className)} {...props} />;
|
||||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> &
|
});
|
||||||
VariantProps<typeof toastVariants>
|
Toast.displayName = ToastPrimitives.Root.displayName;
|
||||||
>(({ className, variant, ...props }, ref) => {
|
|
||||||
return (
|
|
||||||
<ToastPrimitives.Root
|
|
||||||
ref={ref}
|
|
||||||
className={cn(toastVariants({ variant }), className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
})
|
|
||||||
Toast.displayName = ToastPrimitives.Root.displayName
|
|
||||||
|
|
||||||
const ToastAction = React.forwardRef<
|
const ToastAction = React.forwardRef<React.ElementRef<typeof ToastPrimitives.Action>, React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>>(({ className, ...props }, ref) => <ToastPrimitives.Action ref={ref} className={cn("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive", className)} {...props} />);
|
||||||
React.ElementRef<typeof ToastPrimitives.Action>,
|
ToastAction.displayName = ToastPrimitives.Action.displayName;
|
||||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>
|
|
||||||
>(({ className, ...props }, ref) => (
|
|
||||||
<ToastPrimitives.Action
|
|
||||||
ref={ref}
|
|
||||||
className={cn(
|
|
||||||
'inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive',
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
))
|
|
||||||
ToastAction.displayName = ToastPrimitives.Action.displayName
|
|
||||||
|
|
||||||
const ToastClose = React.forwardRef<
|
const ToastClose = React.forwardRef<React.ElementRef<typeof ToastPrimitives.Close>, React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>>(({ className, ...props }, ref) => (
|
||||||
React.ElementRef<typeof ToastPrimitives.Close>,
|
<ToastPrimitives.Close ref={ref} className={cn("absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600", className)} toast-close="" {...props}>
|
||||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>
|
<X className="h-4 w-4" />
|
||||||
>(({ className, ...props }, ref) => (
|
</ToastPrimitives.Close>
|
||||||
<ToastPrimitives.Close
|
));
|
||||||
ref={ref}
|
ToastClose.displayName = ToastPrimitives.Close.displayName;
|
||||||
className={cn(
|
|
||||||
'absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600',
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
toast-close=""
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<X className="h-4 w-4" />
|
|
||||||
</ToastPrimitives.Close>
|
|
||||||
))
|
|
||||||
ToastClose.displayName = ToastPrimitives.Close.displayName
|
|
||||||
|
|
||||||
const ToastTitle = React.forwardRef<
|
const ToastTitle = React.forwardRef<React.ElementRef<typeof ToastPrimitives.Title>, React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>>(({ className, ...props }, ref) => <ToastPrimitives.Title ref={ref} className={cn("text-sm font-semibold", className)} {...props} />);
|
||||||
React.ElementRef<typeof ToastPrimitives.Title>,
|
ToastTitle.displayName = ToastPrimitives.Title.displayName;
|
||||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>
|
|
||||||
>(({ className, ...props }, ref) => (
|
|
||||||
<ToastPrimitives.Title
|
|
||||||
ref={ref}
|
|
||||||
className={cn('text-sm font-semibold', className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
))
|
|
||||||
ToastTitle.displayName = ToastPrimitives.Title.displayName
|
|
||||||
|
|
||||||
const ToastDescription = React.forwardRef<
|
const ToastDescription = React.forwardRef<React.ElementRef<typeof ToastPrimitives.Description>, React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>>(({ className, ...props }, ref) => <ToastPrimitives.Description ref={ref} className={cn("text-sm opacity-90", className)} {...props} />);
|
||||||
React.ElementRef<typeof ToastPrimitives.Description>,
|
ToastDescription.displayName = ToastPrimitives.Description.displayName;
|
||||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>
|
|
||||||
>(({ className, ...props }, ref) => (
|
|
||||||
<ToastPrimitives.Description
|
|
||||||
ref={ref}
|
|
||||||
className={cn('text-sm opacity-90', className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
))
|
|
||||||
ToastDescription.displayName = ToastPrimitives.Description.displayName
|
|
||||||
|
|
||||||
type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>
|
type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>;
|
||||||
|
|
||||||
type ToastActionElement = React.ReactElement<typeof ToastAction>
|
type ToastActionElement = React.ReactElement<typeof ToastAction>;
|
||||||
|
|
||||||
export {
|
export { type ToastProps, type ToastActionElement, ToastProvider, ToastViewport, Toast, ToastTitle, ToastDescription, ToastClose, ToastAction };
|
||||||
type ToastProps,
|
|
||||||
type ToastActionElement,
|
|
||||||
ToastProvider,
|
|
||||||
ToastViewport,
|
|
||||||
Toast,
|
|
||||||
ToastTitle,
|
|
||||||
ToastDescription,
|
|
||||||
ToastClose,
|
|
||||||
ToastAction,
|
|
||||||
}
|
|
||||||
|
|||||||
136
services/api.mjs
136
services/api.mjs
@ -9,58 +9,58 @@ const API_KEY = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
|
|||||||
* Função de login que o seu formulário usa.
|
* Função de login que o seu formulário usa.
|
||||||
* Ela continua exatamente como era.
|
* Ela continua exatamente como era.
|
||||||
*/
|
*/
|
||||||
export async function login() {
|
export async function login(email, senha) {
|
||||||
console.log("🔐 Iniciando login...");
|
console.log("🔐 Iniciando login...");
|
||||||
const res = await fetch(`${BASE_URL}/auth/v1/token?grant_type=password`, {
|
const res = await fetch(`${BASE_URL}/auth/v1/token?grant_type=password`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
apikey: API_KEY,
|
apikey: API_KEY,
|
||||||
Prefer: "return=representation",
|
Prefer: "return=representation",
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
email: "riseup@popcode.com.br",
|
email: email,
|
||||||
password: "riseup",
|
password: senha,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const msg = await res.text();
|
const msg = await res.text();
|
||||||
console.error("❌ Erro no login:", res.status, msg);
|
console.error("❌ Erro no login:", res.status, msg);
|
||||||
throw new Error(`Erro ao autenticar: ${res.status} - ${msg}`);
|
throw new Error(`Erro ao autenticar: ${res.status} - ${msg}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
console.log("✅ Login bem-sucedido:", data);
|
console.log("✅ Login bem-sucedido:", data);
|
||||||
|
|
||||||
if (typeof window !== "undefined" && data.access_token) {
|
if (typeof window !== "undefined" && data.access_token) {
|
||||||
localStorage.setItem("token", data.access_token);
|
localStorage.setItem("token", data.access_token);
|
||||||
}
|
}
|
||||||
|
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Função de logout.
|
* Função de logout.
|
||||||
*/
|
*/
|
||||||
async function logout() {
|
async function logout() {
|
||||||
const token = localStorage.getItem("token");
|
const token = localStorage.getItem("token");
|
||||||
if (!token) return;
|
if (!token) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await fetch(`${BASE_URL}/auth/v1/logout`, {
|
await fetch(`${BASE_URL}/auth/v1/logout`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"apikey": API_KEY,
|
apikey: API_KEY,
|
||||||
"Authorization": `Bearer ${token}`,
|
Authorization: `Bearer ${token}`,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Falha ao invalidar token no servidor:", error);
|
console.error("Falha ao invalidar token no servidor:", error);
|
||||||
} finally {
|
} finally {
|
||||||
localStorage.removeItem("token");
|
localStorage.removeItem("token");
|
||||||
localStorage.removeItem("user_info");
|
localStorage.removeItem("user_info");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -68,40 +68,40 @@ async function logout() {
|
|||||||
* Agora com a correção para respostas vazias.
|
* Agora com a correção para respostas vazias.
|
||||||
*/
|
*/
|
||||||
async function request(endpoint, options = {}) {
|
async function request(endpoint, options = {}) {
|
||||||
const token = typeof window !== 'undefined' ? localStorage.getItem("token") : null;
|
const token = typeof window !== "undefined" ? localStorage.getItem("token") : null;
|
||||||
|
|
||||||
const headers = {
|
const headers = {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
"apikey": API_KEY,
|
apikey: API_KEY,
|
||||||
...(token && { "Authorization": `Bearer ${token}` }),
|
...(token && { Authorization: `Bearer ${token}` }),
|
||||||
...options.headers,
|
...options.headers,
|
||||||
};
|
};
|
||||||
|
|
||||||
const response = await fetch(`${BASE_URL}${endpoint}`, { ...options, headers });
|
const response = await fetch(`${BASE_URL}${endpoint}`, { ...options, headers });
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const errorBody = await response.json().catch(() => response.text());
|
const errorBody = await response.json().catch(() => response.text());
|
||||||
console.error("Erro na requisição:", response.status, errorBody);
|
console.error("Erro na requisição:", response.status, errorBody);
|
||||||
throw new Error(`Erro na API: ${errorBody.message || JSON.stringify(errorBody)}`);
|
throw new Error(`Erro na API: ${errorBody.message || JSON.stringify(errorBody)}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- CORREÇÃO 1: PARA O SUBMIT DO AGENDAMENTO ---
|
// --- CORREÇÃO 1: PARA O SUBMIT DO AGENDAMENTO ---
|
||||||
// Se a resposta for um sucesso de criação (201) ou sem conteúdo (204), não quebra.
|
// Se a resposta for um sucesso de criação (201) ou sem conteúdo (204), não quebra.
|
||||||
if (response.status === 201 || response.status === 204) {
|
if (response.status === 201 || response.status === 204) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return response.json();
|
return response.json();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Exportamos o objeto 'api' com os métodos que os componentes vão usar.
|
// Exportamos o objeto 'api' com os métodos que os componentes vão usar.
|
||||||
export const api = {
|
export const api = {
|
||||||
// --- CORREÇÃO 2: PARA CARREGAR O ID DO USUÁRIO ---
|
// --- CORREÇÃO 2: PARA CARREGAR O ID DO USUÁRIO ---
|
||||||
getSession: () => request('/auth/v1/user'),
|
getSession: () => request("/auth/v1/user"),
|
||||||
|
|
||||||
get: (endpoint, options) => request(endpoint, { method: "GET", ...options }),
|
get: (endpoint, options) => request(endpoint, { method: "GET", ...options }),
|
||||||
post: (endpoint, data, options) => request(endpoint, { method: "POST", body: JSON.stringify(data), ...options }),
|
post: (endpoint, data, options) => request(endpoint, { method: "POST", body: JSON.stringify(data), ...options }),
|
||||||
patch: (endpoint, data, options) => request(endpoint, { method: "PATCH", body: JSON.stringify(data), ...options }),
|
patch: (endpoint, data, options) => request(endpoint, { method: "PATCH", body: JSON.stringify(data), ...options }),
|
||||||
delete: (endpoint, options) => request(endpoint, { method: "DELETE", ...options }),
|
delete: (endpoint, options) => request(endpoint, { method: "DELETE", ...options }),
|
||||||
logout: logout,
|
logout: logout,
|
||||||
};
|
};
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user