corrigindo tabela e criação de users e alterando nome do sistema todo

This commit is contained in:
Lucas Rodrigues 2025-10-15 23:46:31 -03:00
parent bbce3eb932
commit f062929917
14 changed files with 488 additions and 495 deletions

View File

@ -10,7 +10,7 @@ export default function HomePage() {
<div className="text-center mb-12"> <div className="text-center mb-12">
<h1 className="text-4xl font-bold text-foreground mb-4">Central de Operações <br> <h1 className="text-4xl font-bold text-foreground mb-4">Central de Operações <br>
</br> </br>
MedConnect MediConnect
</h1> </h1>
<p className="text-xl text-muted-foreground max-w-2xl mx-auto"> <p className="text-xl text-muted-foreground max-w-2xl mx-auto">

View File

@ -1,231 +1,259 @@
"use client" "use client";
import { useState } from "react" import { useState } from "react";
import { useRouter } from "next/navigation" import { useRouter } from "next/navigation";
import Link from "next/link" 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" import {
import { Save, Loader2 } from "lucide-react" Select,
import ManagerLayout from "@/components/manager-layout" SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Save, Loader2 } from "lucide-react";
import ManagerLayout from "@/components/manager-layout";
import { usersService } from "services/usersApi.mjs"; import { usersService } from "services/usersApi.mjs";
import { login } from "services/api.mjs";
// Adicionada a propriedade 'senha' e 'confirmarSenha'
interface UserFormData { interface UserFormData {
email: string; email: string;
password: string; nomeCompleto: string;
nomeCompleto: string; telefone: string;
telefone: string; papel: string;
papel: string; senha: string;
confirmarSenha: string; // Novo campo para confirmação
} }
const defaultFormData: UserFormData = { const defaultFormData: UserFormData = {
email: '', email: "",
password: '', nomeCompleto: "",
nomeCompleto: '', telefone: "",
telefone: '', papel: "",
papel: '', senha: "",
confirmarSenha: "",
}; };
// Remove todos os caracteres não numéricos // Funções de formatação de telefone
const cleanNumber = (value: string): string => value.replace(/\D/g, ''); const cleanNumber = (value: string): string => value.replace(/\D/g, "");
// Definição do requisito mínimo de senha
const MIN_PASSWORD_LENGTH = 8;
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");
return cleaned;
if (cleaned.length === 10) {
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 }));
}; };
// Handles form submission const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: React.FormEvent) => { e.preventDefault();
e.preventDefault(); setError(null);
setError(null);
// Basic validation // Validação de campos obrigatórios
if (!formData.email || !formData.password || !formData.nomeCompleto || !formData.papel) { if (!formData.email || !formData.nomeCompleto || !formData.papel || !formData.senha || !formData.confirmarSenha) {
setError("Por favor, preencha todos os campos obrigatórios."); setError("Por favor, preencha todos os campos obrigatórios.");
return; return;
} }
// Validação de comprimento mínimo da senha // Validação de senhas
if (formData.password.length < MIN_PASSWORD_LENGTH) { if (formData.senha !== formData.confirmarSenha) {
setError(`A senha deve ter no mínimo ${MIN_PASSWORD_LENGTH} caracteres.`); setError("A Senha e a Confirmação de Senha não coincidem.");
return; return;
} }
setIsSaving(true); setIsSaving(true);
// ---------------------------------------------------------------------- try {
// CORREÇÃO FINAL: Usa o formato de telefone que o mock API comprovadamente aceitou. await login();
// ----------------------------------------------------------------------
const phoneValue = formData.telefone.trim();
// Prepara o payload com os campos obrigatórios const payload = {
const payload: any = { full_name: formData.nomeCompleto,
email: formData.email, email: formData.email.trim().toLowerCase(),
password: formData.password, phone: formData.telefone || null,
full_name: formData.nomeCompleto, role: formData.papel,
role: formData.papel, password: formData.senha, // Senha adicionada
}; };
// Adiciona o telefone APENAS se estiver preenchido, enviando o formato FORMATADO. console.log("📤 Enviando payload:", payload);
if (phoneValue.length > 0) { await usersService.create_user(payload);
payload.phone = phoneValue;
}
// ----------------------------------------------------------------------
try { router.push("/manager/usuario");
await usersService.create_user(payload); } catch (e: any) {
router.push("/manager/usuario"); console.error("Erro ao criar usuário:", e);
} catch (e: any) { const msg =
console.error("Erro ao criar usuário:", e); e.message ||
// Melhorando a mensagem de erro para o usuário final "Não foi possível criar o usuário. Verifique os dados e tente novamente.";
const apiErrorMsg = e.message?.includes("500") setError(msg);
? "Erro interno do servidor. Verifique os logs do backend ou tente novamente mais tarde. (Possível problema: E-mail já em uso ou falha de conexão.)" } finally {
: e.message || "Ocorreu um erro inesperado. Tente novamente."; setIsSaving(false);
}
};
setError(apiErrorMsg); return (
} finally { <ManagerLayout>
setIsSaving(false); {/* Container principal: w-full e centralizado. max-w-screen-lg para evitar expansão excessiva */}
} <div className="w-full h-full p-4 md:p-8 flex justify-center items-start">
}; <div className="w-full max-w-screen-lg space-y-8">
return ( {/* Cabeçalho */}
<ManagerLayout> <div className="flex items-center justify-between border-b pb-4">
<div className="w-full max-w-2xl mx-auto space-y-6 p-4 md:p-8"> <div>
<div className="flex items-center justify-between"> <h1 className="text-3xl font-extrabold text-gray-900">Novo Usuário</h1>
<div> <p className="text-md text-gray-500">
<h1 className="text-2xl font-bold text-gray-900">Novo Usuário</h1> Preencha os dados para cadastrar um novo usuário no sistema.
<p className="text-sm text-gray-500"> </p>
Preencha os dados para cadastrar um novo usuário no sistema.
</p>
</div>
<Link href="/manager/usuario">
<Button variant="outline">Cancelar</Button>
</Link>
</div>
<form onSubmit={handleSubmit} className="space-y-8 bg-white p-8 border rounded-lg shadow-sm">
{/* Error Message Display */}
{error && (
<div className="p-3 bg-red-100 text-red-700 rounded-lg border border-red-300">
<p className="font-medium">Erro no Cadastro:</p>
<p className="text-sm">{error}</p>
</div>
)}
<div className="space-y-4">
<div className="space-y-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="grid md:grid-cols-2 gap-4">
<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="password">Senha *</Label>
<Input
id="password"
type="password"
value={formData.password}
onChange={(e) => handleInputChange("password", e.target.value)}
placeholder="••••••••"
required
minLength={MIN_PASSWORD_LENGTH} // Adiciona validação HTML
/>
{/* MENSAGEM DE AJUDA PARA SENHA */}
<p className="text-xs text-gray-500">Mínimo de {MIN_PASSWORD_LENGTH} caracteres.</p>
</div>
</div>
<div className="grid md:grid-cols-2 gap-4">
<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 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="gestor">Gestor</SelectItem>
<SelectItem value="secretaria">Secretaria</SelectItem>
</SelectContent>
</Select>
</div>
</div>
</div>
{/* Action Buttons */}
<div className="flex justify-end gap-4 pt-4">
<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> <Link href="/manager/usuario">
); <Button variant="outline">Cancelar</Button>
} </Link>
</div>
{/* Formulário */}
<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">{error}</p>
</div>
)}
{/* Campos de Entrada - Usando Grid de 2 colunas para organização */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{/* Nome Completo - Largura total */}
<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>
{/* E-mail (Coluna 1) */}
<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>
{/* Papel (Função) (Coluna 2) */}
<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>
{/* Senha (Coluna 1) */}
<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>
{/* Confirmar Senha (Coluna 2) */}
<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>
{/* Telefone (Opcional, mas mantido no grid) */}
<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>
{/* Botões de Ação */}
<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>
);
}

View File

@ -1,15 +1,20 @@
// app/manager/usuario/page.tsx
"use client"; "use client";
import React, { useEffect, useState, useCallback } from "react"; import React, { useEffect, useState, useCallback } from "react";
import ManagerLayout from "@/components/manager-layout"; import ManagerLayout from "@/components/manager-layout";
import Link from "next/link"; import Link from "next/link";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import {
import { Plus, Edit, Trash2, Eye, Filter, Loader2 } from "lucide-react"; Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Plus, Eye, Filter, Loader2 } from "lucide-react";
import { import {
AlertDialog, AlertDialog,
AlertDialogAction,
AlertDialogCancel, AlertDialogCancel,
AlertDialogContent, AlertDialogContent,
AlertDialogDescription, AlertDialogDescription,
@ -17,173 +22,144 @@ import {
AlertDialogHeader, AlertDialogHeader,
AlertDialogTitle, AlertDialogTitle,
} from "@/components/ui/alert-dialog"; } from "@/components/ui/alert-dialog";
import { api, login } from "services/api.mjs";
import { usersService } from "services/usersApi.mjs"; import { usersService } from "services/usersApi.mjs";
interface User {
user: {
id: string;
email: string;
email_confirmed_at?: string;
created_at?: string;
last_sign_in_at?: string;
};
profile: {
id?: string;
full_name?: string;
email?: string;
phone?: string | null;
avatar_url?: string;
disabled?: boolean;
created_at?: string;
updated_at?: string;
};
roles: string[];
permissions: {
isAdmin?: boolean;
isManager?: boolean;
isDoctor?: boolean;
isSecretary?: boolean;
isAdminOrManager?: boolean;
[key: string]: boolean | undefined;
};
}
interface FlatUser { interface FlatUser {
id: string; id: string;
user_id: string; user_id: string;
full_name?: string; full_name?: string;
email: string; email: string;
phone?: string | null; phone?: string | null;
role: string; role: string;
} }
interface UserInfoResponse {
user: any;
profile: any;
roles: string[];
permissions: Record<string, boolean>;
}
export default function UsersPage() { export default function UsersPage() {
const router = useRouter();
const [users, setUsers] = useState<FlatUser[]>([]); const [users, setUsers] = useState<FlatUser[]>([]);
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 [detailsDialogOpen, setDetailsDialogOpen] = useState(false); const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
const [userDetails, setUserDetails] = useState<User | null>(null); const [userDetails, setUserDetails] = useState<UserInfoResponse | null>(null);
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [userToDeleteId, setUserToDeleteId] = useState<number | null>(null);
const [selectedRole, setSelectedRole] = useState<string>(""); const [selectedRole, setSelectedRole] = useState<string>("");
const fetchUsers = useCallback(async () => { const fetchUsers = useCallback(async () => {
setLoading(true); setLoading(true);
setError(null); setError(null);
try { try {
const data = await usersService.list_roles(); // já retorna o JSON diretamente // 1) pega roles
console.log("Resposta da API list_roles:", data); const rolesData: any[] = await usersService.list_roles();
// Garante que rolesData é array
const rolesArray = Array.isArray(rolesData) ? rolesData : [];
if (Array.isArray(data)) { // 2) pega todos os profiles de uma vez (para evitar muitos requests)
const mappedUsers: FlatUser[] = data.map((item: any) => ({ const profilesData: any[] = await api.get(`/rest/v1/profiles?select=id,full_name,email,phone`);
id: item.id || (item.user_id ?? ""), // id da linha ou fallback const profilesById = new Map<string, any>();
user_id: item.user_id || item.id || "", // garante que user_id exista if (Array.isArray(profilesData)) {
full_name: item.full_name || "—", for (const p of profilesData) {
email: item.email || "—", if (p?.id) profilesById.set(p.id, p);
phone: item.phone ?? "—", }
role: item.role || "—", }
}));
setUsers(mappedUsers); // 3) mapear roles -> flat users, usando ID específico de cada item
} else { const mapped: FlatUser[] = rolesArray.map((roleItem) => {
console.warn("Formato inesperado recebido em list_roles:", data); const uid = roleItem.user_id;
const profile = profilesById.get(uid);
return {
id: uid,
user_id: uid,
full_name: profile?.full_name ?? "—",
email: profile?.email ?? "—",
phone: profile?.phone ?? "—",
role: roleItem.role ?? "—",
};
});
setUsers(mapped);
console.log("[fetchUsers] mapped count:", mapped.length);
} catch (err: any) {
console.error("Erro ao buscar usuários:", err);
setError("Não foi possível carregar os usuários. Veja console.");
setUsers([]); setUsers([]);
} finally {
setLoading(false);
} }
} catch (err: any) { }, []);
console.error("Erro ao buscar usuários:", err);
setError("Não foi possível carregar os usuários. Tente novamente.");
setUsers([]);
} finally {
setLoading(false);
}
}, []);
useEffect(() => { useEffect(() => {
fetchUsers(); const init = async () => {
try {
await login(); // garante token
} catch (e) {
console.warn("login falhou no init:", e);
}
await fetchUsers();
};
init();
}, [fetchUsers]); }, [fetchUsers]);
const openDetailsDialog = async (flatUser: FlatUser) => { const openDetailsDialog = async (flatUser: FlatUser) => {
setDetailsDialogOpen(true); setDetailsDialogOpen(true);
setUserDetails(null); setUserDetails(null);
try {
console.log("Buscando detalhes do user_id:", flatUser.user_id);
const fullUserData: User = await usersService.full_data(flatUser.user_id);
setUserDetails(fullUserData);
} catch (err: any) {
console.error("Erro ao buscar detalhes do usuário:", err);
setUserDetails({
user: {
id: flatUser.user_id,
email: flatUser.email || "",
created_at: "Erro ao Carregar",
last_sign_in_at: "Erro ao Carregar",
},
profile: {
full_name: flatUser.full_name || "Erro ao Carregar Detalhes",
phone: flatUser.phone || "—",
},
roles: [],
permissions: {},
} as any);
}
};
const filteredUsers = selectedRole && selectedRole !== "all"
? users.filter((u) => u.role === selectedRole)
: users;
try {
console.log("[openDetailsDialog] user_id:", flatUser.user_id);
const data = await usersService.full_data(flatUser.user_id);
console.log("[openDetailsDialog] full_data returned:", data);
setUserDetails(data);
} catch (err: any) {
console.error("Erro ao carregar detalhes:", err);
// fallback com dados já conhecidos
setUserDetails({
user: { id: flatUser.user_id, email: flatUser.email },
profile: { full_name: flatUser.full_name, phone: flatUser.phone },
roles: [flatUser.role],
permissions: {},
});
}
};
const filteredUsers =
selectedRole && selectedRole !== "all" ? users.filter((u) => u.role === selectedRole) : users;
return ( return (
<ManagerLayout> <ManagerLayout>
<div className="space-y-6"> <div className="space-y-6">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div> <div>
<h1 className="text-2xl font-bold text-gray-900">Usuários Cadastrados</h1> <h1 className="text-2xl font-bold text-gray-900">Usuários</h1>
<p className="text-sm text-gray-500">Gerencie todos os usuários e seus papéis no sistema.</p> <p className="text-sm text-gray-500">Gerencie usuários.</p>
</div> </div>
<Link href="/manager/usuario/novo"> <Link href="/manager/usuario/novo">
<Button className="bg-green-600 hover:bg-green-700"> <Button className="bg-green-600 hover:bg-green-700">
<Plus className="w-4 h-4 mr-2" /> Adicionar Novo <Plus className="w-4 h-4 mr-2" /> Novo Usuário
</Button> </Button>
</Link> </Link>
</div> </div>
<div className="flex items-center space-x-4 bg-white p-4 rounded-lg border border-gray-200"> <div className="flex items-center space-x-4 bg-white p-4 rounded-lg border border-gray-200">
<Filter className="w-5 h-5 text-gray-400" /> <Filter className="w-5 h-5 text-gray-400" />
<Select onValueChange={setSelectedRole} value={selectedRole}> <Select onValueChange={setSelectedRole} value={selectedRole}>
<SelectTrigger className="w-[180px]"> <SelectTrigger className="w-[180px]">
<SelectValue placeholder="Filtrar por Papel" /> <SelectValue placeholder="Filtrar por papel" />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="all">Todos</SelectItem> <SelectItem value="all">Todos</SelectItem>
<SelectItem value="admin">Admin</SelectItem> <SelectItem value="admin">Admin</SelectItem>
<SelectItem value="gestor">Gestor</SelectItem> <SelectItem value="gestor">Gestor</SelectItem>
<SelectItem value="medico">Médico</SelectItem> <SelectItem value="medico">Médico</SelectItem>
<SelectItem value="secretaria">Secretaria</SelectItem> <SelectItem value="secretaria">Secretária</SelectItem>
<SelectItem value="user">Usuário</SelectItem> <SelectItem value="user">Usuário</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
</div> </div>
<div className="bg-white rounded-lg border border-gray-200 shadow-md overflow-hidden"> <div className="bg-white rounded-lg border border-gray-200 shadow-md overflow-hidden">
{loading ? ( {loading ? (
<div className="p-8 text-center text-gray-500"> <div className="p-8 text-center text-gray-500">
@ -194,11 +170,7 @@ export default function UsersPage() {
<div className="p-8 text-center text-red-600">{error}</div> <div className="p-8 text-center text-red-600">{error}</div>
) : filteredUsers.length === 0 ? ( ) : filteredUsers.length === 0 ? (
<div className="p-8 text-center text-gray-500"> <div className="p-8 text-center text-gray-500">
Nenhum usuário encontrado.{" "} Nenhum usuário encontrado.
<Link href="/manager/usuario/novo" className="text-green-600 hover:underline">
Adicione um novo
</Link>
.
</div> </div>
) : ( ) : (
<div className="overflow-x-auto"> <div className="overflow-x-auto">
@ -209,31 +181,22 @@ export default function UsersPage() {
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Nome</th> <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Nome</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">E-mail</th> <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">E-mail</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Telefone</th> <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Telefone</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Papel</th> <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Cargo</th>
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">Ações</th> <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">Ações</th>
</tr> </tr>
</thead> </thead>
<tbody className="bg-white divide-y divide-gray-200"> <tbody className="bg-white divide-y divide-gray-200">
{filteredUsers.map((user) => ( {filteredUsers.map((u) => (
<tr key={u.id} className="hover:bg-gray-50">
<tr key={user.id} className="hover:bg-gray-50"> <td className="px-6 py-4 text-sm text-gray-500">{u.id}</td>
<td className="px-6 py-4 text-sm text-gray-700">{user.id}</td> <td className="px-6 py-4 text-sm text-gray-900">{u.full_name}</td>
<td className="px-6 py-4 text-sm text-gray-900">{user.full_name || "—"}</td> <td className="px-6 py-4 text-sm text-gray-500">{u.email}</td>
<td className="px-6 py-4 text-sm text-gray-500">{user.email || "—"}</td> <td className="px-6 py-4 text-sm text-gray-500">{u.phone}</td>
<td className="px-6 py-4 text-sm text-gray-500">{user.phone || "—"}</td> <td className="px-6 py-4 text-sm text-gray-500 capitalize">{u.role}</td>
<td className="px-6 py-4 text-sm text-gray-500 capitalize">{user.role || "—"}</td>
<td className="px-6 py-4 text-right"> <td className="px-6 py-4 text-right">
<div className="flex justify-end space-x-1"> <Button variant="outline" size="icon" onClick={() => openDetailsDialog(u)} title="Visualizar">
<Button <Eye className="h-4 w-4" />
variant="outline" </Button>
size="icon"
onClick={() => openDetailsDialog(user)}
title="Visualizar"
>
<Eye className="h-4 w-4" />
</Button>
</div>
</td> </td>
</tr> </tr>
))} ))}
@ -243,59 +206,31 @@ export default function UsersPage() {
)} )}
</div> </div>
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}> <AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
<AlertDialogContent> <AlertDialogContent>
<AlertDialogHeader> <AlertDialogHeader>
<AlertDialogTitle className="text-2xl"> <AlertDialogTitle className="text-2xl">{userDetails?.profile?.full_name || "Detalhes do Usuário"}</AlertDialogTitle>
{userDetails?.profile?.full_name || userDetails?.user?.email || "Detalhes do Usuário"}
</AlertDialogTitle>
<AlertDialogDescription> <AlertDialogDescription>
{!userDetails ? (
{!userDetails ? ( <div className="p-4 text-center text-gray-500">
<div className="p-4 text-center text-gray-500">
<Loader2 className="w-6 h-6 animate-spin mx-auto mb-3 text-green-600" /> <Loader2 className="w-6 h-6 animate-spin mx-auto mb-3 text-green-600" />
Buscando dados completos... Buscando dados completos...
</div>
) : (
<div className="space-y-3 pt-2 text-left text-gray-700">
<div><strong>ID:</strong> {userDetails.user.id}</div>
<div><strong>E-mail:</strong> {userDetails.user.email}</div>
<div><strong>Email confirmado em:</strong> {userDetails.user.email_confirmed_at || "—"}</div>
<div><strong>Último login:</strong> {userDetails.user.last_sign_in_at || "—"}</div>
<div><strong>Criado em:</strong> {userDetails.user.created_at || "—"}</div>
<div><strong>Nome completo:</strong> {userDetails.profile.full_name || "—"}</div>
<div><strong>Telefone:</strong> {userDetails.profile.phone || "—"}</div>
{userDetails.profile.avatar_url && (
<div><strong>Avatar:</strong> <img src={userDetails.profile.avatar_url} className="w-16 h-16 rounded-full mt-1" /></div>
)}
<div><strong>Conta desativada:</strong> {userDetails.profile.disabled ? "Sim" : "Não"}</div>
<div><strong>Profile criado em:</strong> {userDetails.profile.created_at || "—"}</div>
<div><strong>Profile atualizado em:</strong> {userDetails.profile.updated_at || "—"}</div>
<div>
<strong>Roles:</strong>
<ul className="list-disc list-inside">
{userDetails.roles.map((role, idx) => <li key={idx}>{role}</li>)}
</ul>
</div> </div>
) : (
<div> <div className="space-y-3 pt-2 text-left text-gray-700">
<strong>Permissões:</strong> <div><strong>ID:</strong> {userDetails.user.id}</div>
<ul className="list-disc list-inside"> <div><strong>E-mail:</strong> {userDetails.user.email}</div>
{Object.entries(userDetails.permissions).map(([key, value]) => ( <div><strong>Nome completo:</strong> {userDetails.profile.full_name}</div>
<li key={key}>{key}: {value ? "Sim" : "Não"}</li> <div><strong>Telefone:</strong> {userDetails.profile.phone}</div>
))} <div><strong>Roles:</strong> {userDetails.roles?.join(", ")}</div>
</ul> <div>
<strong>Permissões:</strong>
<ul className="list-disc list-inside">
{Object.entries(userDetails.permissions || {}).map(([k,v]) => <li key={k}>{k}: {v ? "Sim" : "Não"}</li>)}
</ul>
</div>
</div> </div>
</div> )}
)}
</AlertDialogDescription> </AlertDialogDescription>
</AlertDialogHeader> </AlertDialogHeader>
<AlertDialogFooter> <AlertDialogFooter>
@ -306,4 +241,4 @@ export default function UsersPage() {
</div> </div>
</ManagerLayout> </ManagerLayout>
); );
} }

View File

@ -10,12 +10,12 @@ export default function InicialPage() {
{} {}
<div className="bg-primary text-primary-foreground text-sm py-2 px-6 flex justify-between"> <div className="bg-primary text-primary-foreground text-sm py-2 px-6 flex justify-between">
<span> Horário: 08h00 - 21h00</span> <span> Horário: 08h00 - 21h00</span>
<span> Email: contato@medconnect.com</span> <span> Email: contato@mediconnect.com</span>
</div> </div>
{} {}
<header className="bg-card shadow-md py-4 px-6 flex justify-between items-center"> <header className="bg-card shadow-md py-4 px-6 flex justify-between items-center">
<h1 className="text-2xl font-bold text-primary">MedConnect</h1> <h1 className="text-2xl font-bold text-primary">MediConnect</h1>
<nav className="flex space-x-6 text-muted-foreground font-medium"> <nav className="flex space-x-6 text-muted-foreground font-medium">
<a href="#home" className="hover:text-primary">Home</a> <a href="#home" className="hover:text-primary">Home</a>
<a href="#about" className="hover:text-primary">Sobre</a> <a href="#about" className="hover:text-primary">Sobre</a>
@ -105,7 +105,7 @@ export default function InicialPage() {
{} {}
<footer className="bg-primary text-primary-foreground py-6 text-center"> <footer className="bg-primary text-primary-foreground py-6 text-center">
<p>© 2025 MedConnect</p> <p>© 2025 MediConnect</p>
</footer> </footer>
</div> </div>
); );

View File

@ -143,7 +143,7 @@ useEffect(() => {
<div className="w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center"> <div className="w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center">
<div className="w-4 h-4 bg-white rounded-sm"></div> <div className="w-4 h-4 bg-white rounded-sm"></div>
</div> </div>
<span className="font-semibold text-gray-900">MidConnecta</span> <span className="font-semibold text-gray-900">MediConnect</span>
</div> </div>
)} )}
<Button variant="ghost" size="sm" onClick={() => setSidebarCollapsed(!sidebarCollapsed)} className="p-1"> <Button variant="ghost" size="sm" onClick={() => setSidebarCollapsed(!sidebarCollapsed)} className="p-1">
@ -179,7 +179,7 @@ useEffect(() => {
<div className="w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center"> <div className="w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center">
<div className="w-4 h-4 bg-white rounded-sm"></div> <div className="w-4 h-4 bg-white rounded-sm"></div>
</div> </div>
<span className="font-semibold text-gray-900">MedConnect</span> <span className="font-semibold text-gray-900">MediConnect</span>
</div> </div>
)} )}
<Button variant="ghost" size="sm" onClick={() => setSidebarCollapsed(!sidebarCollapsed)} className="p-1"> <Button variant="ghost" size="sm" onClick={() => setSidebarCollapsed(!sidebarCollapsed)} className="p-1">

View File

@ -138,7 +138,7 @@ export default function FinancierLayout({ children }: PatientLayoutProps) {
<div className="w-4 h-4 bg-primary-foreground rounded-sm"></div> <div className="w-4 h-4 bg-primary-foreground rounded-sm"></div>
</div> </div>
<span className="font-semibold text-foreground"> <span className="font-semibold text-foreground">
MidConnecta MediConnect
</span> </span>
</div> </div>
)} )}

View File

@ -123,7 +123,7 @@ export default function HospitalLayout({ children }: HospitalLayoutProps) {
<div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center"> <div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center">
<div className="w-4 h-4 bg-primary-foreground rounded-sm"></div> <div className="w-4 h-4 bg-primary-foreground rounded-sm"></div>
</div> </div>
<span className="font-semibold text-foreground">MedConnect</span> <span className="font-semibold text-foreground">MediConnect</span>
</div> </div>
)} )}
<Button variant="ghost" size="sm" onClick={() => setSidebarCollapsed(!sidebarCollapsed)} className="p-1"> <Button variant="ghost" size="sm" onClick={() => setSidebarCollapsed(!sidebarCollapsed)} className="p-1">

View File

@ -131,7 +131,7 @@ export default function ManagerLayout({ children }: ManagerLayoutProps) {
<div className="w-4 h-4 bg-white rounded-sm"></div> <div className="w-4 h-4 bg-white rounded-sm"></div>
</div> </div>
<span className="font-semibold text-gray-900"> <span className="font-semibold text-gray-900">
MidConnecta MediConnect
</span> </span>
</div> </div>
)} )}

View File

@ -131,7 +131,7 @@ export default function HospitalLayout({ children }: HospitalLayoutProps) {
<div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center"> <div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center">
<div className="w-4 h-4 bg-primary-foreground rounded-sm"></div> <div className="w-4 h-4 bg-primary-foreground rounded-sm"></div>
</div> </div>
<span className="font-semibold text-foreground">MedConnect</span> <span className="font-semibold text-foreground">MediConnect</span>
</div> </div>
)} )}
<Button <Button

View File

@ -105,7 +105,7 @@ export default function SecretaryLayout({ children }: SecretaryLayoutProps) {
<div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center"> <div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center">
<div className="w-4 h-4 bg-primary-foreground rounded-sm"></div> <div className="w-4 h-4 bg-primary-foreground rounded-sm"></div>
</div> </div>
<span className="font-semibold text-foreground">MedConnect</span> <span className="font-semibold text-foreground">MediConnect</span>
</div> </div>
)} )}
<Button <Button

10
package-lock.json generated
View File

@ -52,7 +52,7 @@
"input-otp": "1.4.1", "input-otp": "1.4.1",
"js-cookie": "^3.0.5", "js-cookie": "^3.0.5",
"jwt-decode": "^4.0.0", "jwt-decode": "^4.0.0",
"lucide-react": "^0.454.0", "lucide-react": "^0.545.0",
"next": "^14.2.33", "next": "^14.2.33",
"next-themes": "^0.4.6", "next-themes": "^0.4.6",
"react": "^18.3.1", "react": "^18.3.1",
@ -3381,12 +3381,12 @@
} }
}, },
"node_modules/lucide-react": { "node_modules/lucide-react": {
"version": "0.454.0", "version": "0.545.0",
"resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.454.0.tgz", "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.545.0.tgz",
"integrity": "sha512-hw7zMDwykCLnEzgncEEjHeA6+45aeEzRYuKHuyRSOPkhko+J3ySGjGIzu+mmMfDFG1vazHepMaYFYHbTFAZAAQ==", "integrity": "sha512-7r1/yUuflQDSt4f1bpn5ZAocyIxcTyVyBBChSVtBKn5M+392cPmI5YJMWOJKk/HUWGm5wg83chlAZtCcGbEZtw==",
"license": "ISC", "license": "ISC",
"peerDependencies": { "peerDependencies": {
"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0-rc" "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"
} }
}, },
"node_modules/magic-string": { "node_modules/magic-string": {

View File

@ -53,7 +53,7 @@
"input-otp": "1.4.1", "input-otp": "1.4.1",
"js-cookie": "^3.0.5", "js-cookie": "^3.0.5",
"jwt-decode": "^4.0.0", "jwt-decode": "^4.0.0",
"lucide-react": "^0.454.0", "lucide-react": "^0.545.0",
"next": "^14.2.33", "next": "^14.2.33",
"next-themes": "^0.4.6", "next-themes": "^0.4.6",
"react": "^18.3.1", "react": "^18.3.1",

View File

@ -1,86 +1,73 @@
const BASE_URL = "https://yuanqfswhberkoevtmfr.supabase.co"; const BASE_URL = "https://yuanqfswhberkoevtmfr.supabase.co";
const API_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Inl1YW5xZnN3aGJlcmtvZXZ0bWZyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTQ5NTQzNjksImV4cCI6MjA3MDUzMDM2OX0.g8Fm4XAvtX46zifBZnYVH4tVuQkqUH6Ia9CXQj4DztQ"; const API_KEY =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Inl1YW5xZnN3aGJlcmtvZXZ0bWZyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTQ5NTQzNjksImV4cCI6MjA3MDUzMDM2OX0.g8Fm4XAvtX46zifBZnYVH4tVuQkqUH6Ia9CXQj4DztQ";
export const apikey = API_KEY; export const apikey = API_KEY;
var tempToken; let loginPromise = null;
// 🔹 Autenticação
export async function login() { export async function login() {
const response = await fetch("https://yuanqfswhberkoevtmfr.supabase.co/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",
Prefer: "return=representation", apikey: API_KEY,
apikey: API_KEY, // valor fixo Prefer: "return=representation",
}, },
body: JSON.stringify({ email: "riseup@popcode.com.br", password: "riseup" }), body: JSON.stringify({
}); email: "riseup@popcode.com.br",
password: "riseup",
}),
});
const data = await response.json(); const data = await res.json();
if (typeof window !== "undefined") {
if (typeof window !== 'undefined') { localStorage.setItem("token", data.access_token);
localStorage.setItem("token", data.access_token); }
} return data;
return data;
} }
let loginPromise = login();
async function request(endpoint, options = {}) { async function request(endpoint, options = {}) {
if (loginPromise) { if (!loginPromise) loginPromise = login();
try {
await loginPromise;
} catch (error) {
console.error("Falha na autenticação inicial:", error);
}
loginPromise = null; try {
} await loginPromise;
} catch (error) {
console.error("Falha ao autenticar:", error);
} finally {
loginPromise = null;
}
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,
}; };
try { const response = await fetch(`${BASE_URL}${endpoint}`, {
const response = await fetch(`${BASE_URL}${endpoint}`, { ...options,
...options, headers,
headers, });
});
if (!response.ok) { if (!response.ok) {
let errorBody = `Status: ${response.status}`; const msg = await response.text();
try { throw new Error(`Erro HTTP: ${response.status} - Detalhes: ${msg}`);
const contentType = response.headers.get("content-type"); }
if (contentType && contentType.includes("application/json")) {
const jsonError = await response.json();
errorBody = jsonError.message || JSON.stringify(jsonError); const contentType = response.headers.get("content-type");
} else { if (!contentType || !contentType.includes("application/json")) return {};
errorBody = await response.text(); return await response.json();
}
} catch (e) {
errorBody = `Status: ${response.status} - Falha ao ler corpo do erro.`;
}
throw new Error(`Erro HTTP: ${response.status} - Detalhes: ${errorBody}`);
}
const contentType = response.headers.get("content-type");
if (response.status === 204 || (contentType && !contentType.includes("application/json")) || !contentType) {
return {};
}
return await response.json();
} catch (error) {
console.error("Erro na requisição:", error);
throw error;
}
} }
export const api = { export const api = {
get: (endpoint, options) => request(endpoint, { method: "GET", ...options }), get: (endpoint, options) => request(endpoint, { method: "GET", ...options }),
post: (endpoint, data) => request(endpoint, { method: "POST", body: JSON.stringify(data) }), post: (endpoint, data) =>
patch: (endpoint, data) => request(endpoint, { method: "PATCH", body: JSON.stringify(data) }), request(endpoint, { method: "POST", body: JSON.stringify(data) }),
delete: (endpoint) => request(endpoint, { method: "DELETE" }), patch: (endpoint, data) =>
request(endpoint, { method: "PATCH", body: JSON.stringify(data) }),
delete: (endpoint) => request(endpoint, { method: "DELETE" }),
}; };

View File

@ -1,10 +1,53 @@
import { api } from "./api.mjs"; import { api } from "./api.mjs";
export const usersService = { export const usersService = {
create_user: (data) => api.post(`/functions/v1/create-user`), async list_roles() {
list_roles: () => api.get(`/rest/v1/user_roles`), return await api.get(`/rest/v1/user_roles?select=id,user_id,role,created_at`);
full_data: (id) => {
const endpoint = `/functions/v1/user-info?user_id=${id}`;
return api.get(endpoint);
}, },
summary_data: () => api.get(`/auth/v1/user`)
} async create_user(data) {
return await api.post(`/functions/v1/user-create`, data);
},
// 🚀 Busca dados completos do usuário direto do banco (sem função bloqueada)
async full_data(user_id) {
if (!user_id) throw new Error("user_id é obrigatório");
// Busca o perfil
const [profile] = await api.get(`/rest/v1/profiles?id=eq.${user_id}`);
// Busca o papel (role)
const [role] = await api.get(`/rest/v1/user_roles?user_id=eq.${user_id}`);
// Busca as permissões se existirem em alguma tabela
const permissions = {
isAdmin: role?.role === "admin",
isManager: role?.role === "gestor",
isDoctor: role?.role === "medico",
isSecretary: role?.role === "secretaria",
isAdminOrManager:
role?.role === "admin" || role?.role === "gestor" ? true : false,
};
// Monta o objeto no mesmo formato do endpoint `user-info`
return {
user: {
id: user_id,
email: profile?.email ?? "—",
email_confirmed_at: null,
created_at: profile?.created_at ?? "—",
last_sign_in_at: null,
},
profile: {
id: profile?.id ?? user_id,
full_name: profile?.full_name ?? "—",
email: profile?.email ?? "—",
phone: profile?.phone ?? "—",
avatar_url: profile?.avatar_url ?? null,
disabled: profile?.disabled ?? false,
created_at: profile?.created_at ?? null,
updated_at: profile?.updated_at ?? null,
},
roles: [role?.role ?? "—"],
permissions,
};
},
};