Merge branch 'main' of https://git.popcode.com.br/RiseUP/riseup-squad21
This commit is contained in:
commit
e6c6a20842
@ -10,7 +10,7 @@ export default function HomePage() {
|
||||
<div className="text-center mb-12">
|
||||
<h1 className="text-4xl font-bold text-foreground mb-4">Central de Operações <br>
|
||||
</br>
|
||||
MedConnect
|
||||
MediConnect
|
||||
|
||||
</h1>
|
||||
<p className="text-xl text-muted-foreground max-w-2xl mx-auto">
|
||||
|
||||
@ -1,231 +1,259 @@
|
||||
"use client"
|
||||
"use client";
|
||||
|
||||
import { useState } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import Link from "next/link"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import { Save, Loader2 } from "lucide-react"
|
||||
import ManagerLayout from "@/components/manager-layout"
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Save, Loader2 } from "lucide-react";
|
||||
import ManagerLayout from "@/components/manager-layout";
|
||||
import { usersService } from "services/usersApi.mjs";
|
||||
import { login } from "services/api.mjs";
|
||||
|
||||
// Adicionada a propriedade 'senha' e 'confirmarSenha'
|
||||
interface UserFormData {
|
||||
email: string;
|
||||
password: string;
|
||||
nomeCompleto: string;
|
||||
telefone: string;
|
||||
papel: string;
|
||||
email: string;
|
||||
nomeCompleto: string;
|
||||
telefone: string;
|
||||
papel: string;
|
||||
senha: string;
|
||||
confirmarSenha: string; // Novo campo para confirmação
|
||||
}
|
||||
|
||||
const defaultFormData: UserFormData = {
|
||||
email: '',
|
||||
password: '',
|
||||
nomeCompleto: '',
|
||||
telefone: '',
|
||||
papel: '',
|
||||
email: "",
|
||||
nomeCompleto: "",
|
||||
telefone: "",
|
||||
papel: "",
|
||||
senha: "",
|
||||
confirmarSenha: "",
|
||||
};
|
||||
|
||||
// Remove todos os caracteres não numéricos
|
||||
const cleanNumber = (value: string): string => value.replace(/\D/g, '');
|
||||
|
||||
// Definição do requisito mínimo de senha
|
||||
const MIN_PASSWORD_LENGTH = 8;
|
||||
|
||||
|
||||
// Funções de formatação de telefone
|
||||
const cleanNumber = (value: string): string => value.replace(/\D/g, "");
|
||||
const formatPhone = (value: string): string => {
|
||||
const cleaned = cleanNumber(value).substring(0, 11);
|
||||
|
||||
if (cleaned.length === 11) {
|
||||
return cleaned.replace(/(\d{2})(\d{5})(\d{4})/, '($1) $2-$3');
|
||||
}
|
||||
|
||||
if (cleaned.length === 10) {
|
||||
return cleaned.replace(/(\d{2})(\d{4})(\d{4})/, '($1) $2-$3');
|
||||
}
|
||||
return cleaned;
|
||||
const cleaned = cleanNumber(value).substring(0, 11);
|
||||
if (cleaned.length === 11)
|
||||
return cleaned.replace(/(\d{2})(\d{5})(\d{4})/, "($1) $2-$3");
|
||||
if (cleaned.length === 10)
|
||||
return cleaned.replace(/(\d{2})(\d{4})(\d{4})/, "($1) $2-$3");
|
||||
return cleaned;
|
||||
};
|
||||
|
||||
|
||||
export default function NovoUsuarioPage() {
|
||||
const router = useRouter();
|
||||
const [formData, setFormData] = useState<UserFormData>(defaultFormData);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const router = useRouter();
|
||||
const [formData, setFormData] = useState<UserFormData>(defaultFormData);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleInputChange = (key: keyof UserFormData, value: string) => {
|
||||
const updatedValue = key === 'telefone' ? formatPhone(value) : value;
|
||||
setFormData((prev) => ({ ...prev, [key]: updatedValue }));
|
||||
};
|
||||
const handleInputChange = (key: keyof UserFormData, value: string) => {
|
||||
const updatedValue = key === "telefone" ? formatPhone(value) : value;
|
||||
setFormData((prev) => ({ ...prev, [key]: updatedValue }));
|
||||
};
|
||||
|
||||
// Handles form submission
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
|
||||
// Basic validation
|
||||
if (!formData.email || !formData.password || !formData.nomeCompleto || !formData.papel) {
|
||||
setError("Por favor, preencha todos os campos obrigatórios.");
|
||||
return;
|
||||
}
|
||||
// Validação de campos obrigatórios
|
||||
if (!formData.email || !formData.nomeCompleto || !formData.papel || !formData.senha || !formData.confirmarSenha) {
|
||||
setError("Por favor, preencha todos os campos obrigatórios.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Validação de comprimento mínimo da senha
|
||||
if (formData.password.length < MIN_PASSWORD_LENGTH) {
|
||||
setError(`A senha deve ter no mínimo ${MIN_PASSWORD_LENGTH} caracteres.`);
|
||||
return;
|
||||
}
|
||||
// Validação de senhas
|
||||
if (formData.senha !== formData.confirmarSenha) {
|
||||
setError("A Senha e a Confirmação de Senha não coincidem.");
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSaving(true);
|
||||
setIsSaving(true);
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// CORREÇÃO FINAL: Usa o formato de telefone que o mock API comprovadamente aceitou.
|
||||
// ----------------------------------------------------------------------
|
||||
const phoneValue = formData.telefone.trim();
|
||||
try {
|
||||
await login();
|
||||
|
||||
// Prepara o payload com os campos obrigatórios
|
||||
const payload: any = {
|
||||
email: formData.email,
|
||||
password: formData.password,
|
||||
full_name: formData.nomeCompleto,
|
||||
role: formData.papel,
|
||||
};
|
||||
const payload = {
|
||||
full_name: formData.nomeCompleto,
|
||||
email: formData.email.trim().toLowerCase(),
|
||||
phone: formData.telefone || null,
|
||||
role: formData.papel,
|
||||
password: formData.senha, // Senha adicionada
|
||||
};
|
||||
|
||||
// Adiciona o telefone APENAS se estiver preenchido, enviando o formato FORMATADO.
|
||||
if (phoneValue.length > 0) {
|
||||
payload.phone = phoneValue;
|
||||
}
|
||||
// ----------------------------------------------------------------------
|
||||
console.log("📤 Enviando payload:", payload);
|
||||
await usersService.create_user(payload);
|
||||
|
||||
try {
|
||||
await usersService.create_user(payload);
|
||||
router.push("/manager/usuario");
|
||||
} catch (e: any) {
|
||||
console.error("Erro ao criar usuário:", e);
|
||||
// Melhorando a mensagem de erro para o usuário final
|
||||
const apiErrorMsg = e.message?.includes("500")
|
||||
? "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.)"
|
||||
: e.message || "Ocorreu um erro inesperado. Tente novamente.";
|
||||
router.push("/manager/usuario");
|
||||
} catch (e: any) {
|
||||
console.error("Erro ao criar usuário:", e);
|
||||
const msg =
|
||||
e.message ||
|
||||
"Não foi possível criar o usuário. Verifique os dados e tente novamente.";
|
||||
setError(msg);
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
setError(apiErrorMsg);
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<ManagerLayout>
|
||||
<div className="w-full max-w-2xl mx-auto space-y-6 p-4 md:p-8">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Novo Usuário</h1>
|
||||
<p className="text-sm text-gray-500">
|
||||
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>
|
||||
return (
|
||||
<ManagerLayout>
|
||||
{/* 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">
|
||||
|
||||
{/* Cabeçalho */}
|
||||
<div className="flex items-center justify-between border-b pb-4">
|
||||
<div>
|
||||
<h1 className="text-3xl font-extrabold text-gray-900">Novo Usuário</h1>
|
||||
<p className="text-md text-gray-500">
|
||||
Preencha os dados para cadastrar um novo usuário no sistema.
|
||||
</p>
|
||||
</div>
|
||||
</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>
|
||||
);
|
||||
}
|
||||
@ -1,15 +1,20 @@
|
||||
// app/manager/usuario/page.tsx
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState, useCallback } from "react";
|
||||
import ManagerLayout from "@/components/manager-layout";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Plus, Edit, Trash2, Eye, Filter, Loader2 } from "lucide-react";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Plus, Eye, Filter, Loader2 } from "lucide-react";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
@ -17,173 +22,144 @@ import {
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
|
||||
import { api, login } from "services/api.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 {
|
||||
id: string;
|
||||
user_id: string;
|
||||
id: string;
|
||||
user_id: string;
|
||||
full_name?: string;
|
||||
email: string;
|
||||
phone?: string | null;
|
||||
role: string;
|
||||
}
|
||||
|
||||
|
||||
interface UserInfoResponse {
|
||||
user: any;
|
||||
profile: any;
|
||||
roles: string[];
|
||||
permissions: Record<string, boolean>;
|
||||
}
|
||||
|
||||
export default function UsersPage() {
|
||||
const router = useRouter();
|
||||
|
||||
|
||||
const [users, setUsers] = useState<FlatUser[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
|
||||
const [userDetails, setUserDetails] = useState<User | null>(null);
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [userToDeleteId, setUserToDeleteId] = useState<number | null>(null);
|
||||
const [userDetails, setUserDetails] = useState<UserInfoResponse | null>(null);
|
||||
const [selectedRole, setSelectedRole] = useState<string>("");
|
||||
|
||||
const fetchUsers = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const data = await usersService.list_roles(); // já retorna o JSON diretamente
|
||||
console.log("Resposta da API list_roles:", data);
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
// 1) pega roles
|
||||
const rolesData: any[] = await usersService.list_roles();
|
||||
// Garante que rolesData é array
|
||||
const rolesArray = Array.isArray(rolesData) ? rolesData : [];
|
||||
|
||||
if (Array.isArray(data)) {
|
||||
const mappedUsers: FlatUser[] = data.map((item: any) => ({
|
||||
id: item.id || (item.user_id ?? ""), // id da linha ou fallback
|
||||
user_id: item.user_id || item.id || "", // garante que user_id exista
|
||||
full_name: item.full_name || "—",
|
||||
email: item.email || "—",
|
||||
phone: item.phone ?? "—",
|
||||
role: item.role || "—",
|
||||
}));
|
||||
// 2) pega todos os profiles de uma vez (para evitar muitos requests)
|
||||
const profilesData: any[] = await api.get(`/rest/v1/profiles?select=id,full_name,email,phone`);
|
||||
const profilesById = new Map<string, any>();
|
||||
if (Array.isArray(profilesData)) {
|
||||
for (const p of profilesData) {
|
||||
if (p?.id) profilesById.set(p.id, p);
|
||||
}
|
||||
}
|
||||
|
||||
setUsers(mappedUsers);
|
||||
} else {
|
||||
console.warn("Formato inesperado recebido em list_roles:", data);
|
||||
// 3) mapear roles -> flat users, usando ID específico de cada item
|
||||
const mapped: FlatUser[] = rolesArray.map((roleItem) => {
|
||||
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([]);
|
||||
} 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(() => {
|
||||
fetchUsers();
|
||||
const init = async () => {
|
||||
try {
|
||||
await login(); // garante token
|
||||
} catch (e) {
|
||||
console.warn("login falhou no init:", e);
|
||||
}
|
||||
await fetchUsers();
|
||||
};
|
||||
init();
|
||||
}, [fetchUsers]);
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
const openDetailsDialog = async (flatUser: FlatUser) => {
|
||||
setDetailsDialogOpen(true);
|
||||
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;
|
||||
setDetailsDialogOpen(true);
|
||||
setUserDetails(null);
|
||||
|
||||
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 (
|
||||
<ManagerLayout>
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Usuários Cadastrados</h1>
|
||||
<p className="text-sm text-gray-500">Gerencie todos os usuários e seus papéis no sistema.</p>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Usuários</h1>
|
||||
<p className="text-sm text-gray-500">Gerencie usuários.</p>
|
||||
</div>
|
||||
<Link href="/manager/usuario/novo">
|
||||
<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>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="flex items-center space-x-4 bg-white p-4 rounded-lg border border-gray-200">
|
||||
<Filter className="w-5 h-5 text-gray-400" />
|
||||
<Select onValueChange={setSelectedRole} value={selectedRole}>
|
||||
<SelectTrigger className="w-[180px]">
|
||||
<SelectValue placeholder="Filtrar por Papel" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Todos</SelectItem>
|
||||
<SelectItem value="admin">Admin</SelectItem>
|
||||
<SelectItem value="gestor">Gestor</SelectItem>
|
||||
<SelectItem value="medico">Médico</SelectItem>
|
||||
<SelectItem value="secretaria">Secretaria</SelectItem>
|
||||
<SelectItem value="user">Usuário</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<SelectTrigger className="w-[180px]">
|
||||
<SelectValue placeholder="Filtrar por papel" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Todos</SelectItem>
|
||||
<SelectItem value="admin">Admin</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="bg-white rounded-lg border border-gray-200 shadow-md overflow-hidden">
|
||||
{loading ? (
|
||||
<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>
|
||||
) : filteredUsers.length === 0 ? (
|
||||
<div className="p-8 text-center text-gray-500">
|
||||
Nenhum usuário encontrado.{" "}
|
||||
<Link href="/manager/usuario/novo" className="text-green-600 hover:underline">
|
||||
Adicione um novo
|
||||
</Link>
|
||||
.
|
||||
Nenhum usuário encontrado.
|
||||
</div>
|
||||
) : (
|
||||
<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">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">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>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="bg-white divide-y divide-gray-200">
|
||||
{filteredUsers.map((user) => (
|
||||
|
||||
<tr key={user.id} className="hover:bg-gray-50">
|
||||
<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">{user.full_name || "—"}</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">{user.phone || "—"}</td>
|
||||
<td className="px-6 py-4 text-sm text-gray-500 capitalize">{user.role || "—"}</td>
|
||||
{filteredUsers.map((u) => (
|
||||
<tr key={u.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-900">{u.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">{u.phone}</td>
|
||||
<td className="px-6 py-4 text-sm text-gray-500 capitalize">{u.role}</td>
|
||||
<td className="px-6 py-4 text-right">
|
||||
<div className="flex justify-end space-x-1">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => openDetailsDialog(user)}
|
||||
title="Visualizar"
|
||||
>
|
||||
<Eye className="h-4 w-4" />
|
||||
</Button>
|
||||
|
||||
</div>
|
||||
<Button variant="outline" size="icon" onClick={() => openDetailsDialog(u)} title="Visualizar">
|
||||
<Eye className="h-4 w-4" />
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
@ -243,59 +206,31 @@ export default function UsersPage() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
|
||||
<AlertDialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle className="text-2xl">
|
||||
{userDetails?.profile?.full_name || userDetails?.user?.email || "Detalhes do Usuário"}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogTitle className="text-2xl">{userDetails?.profile?.full_name || "Detalhes do Usuário"}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
|
||||
{!userDetails ? (
|
||||
<div className="p-4 text-center text-gray-500">
|
||||
{!userDetails ? (
|
||||
<div className="p-4 text-center text-gray-500">
|
||||
<Loader2 className="w-6 h-6 animate-spin mx-auto mb-3 text-green-600" />
|
||||
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>
|
||||
<strong>Permissões:</strong>
|
||||
<ul className="list-disc list-inside">
|
||||
{Object.entries(userDetails.permissions).map(([key, value]) => (
|
||||
<li key={key}>{key}: {value ? "Sim" : "Não"}</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<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>Nome completo:</strong> {userDetails.profile.full_name}</div>
|
||||
<div><strong>Telefone:</strong> {userDetails.profile.phone}</div>
|
||||
<div><strong>Roles:</strong> {userDetails.roles?.join(", ")}</div>
|
||||
<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>
|
||||
)}
|
||||
|
||||
|
||||
)}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
@ -306,4 +241,4 @@ export default function UsersPage() {
|
||||
</div>
|
||||
</ManagerLayout>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -10,12 +10,12 @@ export default function InicialPage() {
|
||||
{}
|
||||
<div className="bg-primary text-primary-foreground text-sm py-2 px-6 flex justify-between">
|
||||
<span> Horário: 08h00 - 21h00</span>
|
||||
<span> Email: contato@medconnect.com</span>
|
||||
<span> Email: contato@mediconnect.com</span>
|
||||
</div>
|
||||
|
||||
{}
|
||||
<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">
|
||||
<a href="#home" className="hover:text-primary"><Link href="/cadastro">Home</Link></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">
|
||||
<p>© 2025 MedConnect</p>
|
||||
<p>© 2025 MediConnect</p>
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
|
||||
@ -135,7 +135,7 @@ export default function DoctorLayout({ children }: PatientLayoutProps) {
|
||||
<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>
|
||||
<span className="font-semibold text-gray-900">MidConnecta</span>
|
||||
<span className="font-semibold text-gray-900">MediConnect</span>
|
||||
</div>
|
||||
)}
|
||||
<Button variant="ghost" size="sm" onClick={() => setSidebarCollapsed(!sidebarCollapsed)} className="p-1">
|
||||
@ -171,7 +171,7 @@ export default function DoctorLayout({ children }: PatientLayoutProps) {
|
||||
<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>
|
||||
<span className="font-semibold text-gray-900">MedConnect</span>
|
||||
<span className="font-semibold text-gray-900">MediConnect</span>
|
||||
</div>
|
||||
)}
|
||||
<Button variant="ghost" size="sm" onClick={() => setSidebarCollapsed(!sidebarCollapsed)} className="p-1">
|
||||
|
||||
@ -125,7 +125,7 @@ export default function FinancierLayout({ children }: PatientLayoutProps) {
|
||||
<div className="w-4 h-4 bg-primary-foreground rounded-sm"></div>
|
||||
</div>
|
||||
<span className="font-semibold text-foreground">
|
||||
MidConnecta
|
||||
MediConnect
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@ -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-4 h-4 bg-primary-foreground rounded-sm"></div>
|
||||
</div>
|
||||
<span className="font-semibold text-foreground">MedConnect</span>
|
||||
<span className="font-semibold text-foreground">MediConnect</span>
|
||||
</div>
|
||||
)}
|
||||
<Button variant="ghost" size="sm" onClick={() => setSidebarCollapsed(!sidebarCollapsed)} className="p-1">
|
||||
|
||||
@ -117,7 +117,9 @@ export default function ManagerLayout({ children }: ManagerLayoutProps) {
|
||||
<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>
|
||||
<span className="font-semibold text-gray-900">MidConnecta</span>
|
||||
<span className="font-semibold text-gray-900">
|
||||
MediConnect
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<Button
|
||||
|
||||
@ -120,7 +120,7 @@ export default function PatientLayout({ children }: PatientLayoutProps) {
|
||||
<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>
|
||||
<span className="font-semibold text-foreground">MedConnect</span>
|
||||
<span className="font-semibold text-foreground">MediConnect</span>
|
||||
</div>
|
||||
)}
|
||||
<Button
|
||||
|
||||
@ -123,7 +123,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-4 h-4 bg-primary-foreground rounded-sm"></div>
|
||||
</div>
|
||||
<span className="font-semibold text-foreground">MedConnect</span>
|
||||
<span className="font-semibold text-foreground">MediConnect</span>
|
||||
</div>
|
||||
)}
|
||||
<Button
|
||||
|
||||
10
package-lock.json
generated
10
package-lock.json
generated
@ -52,7 +52,7 @@
|
||||
"input-otp": "1.4.1",
|
||||
"js-cookie": "^3.0.5",
|
||||
"jwt-decode": "^4.0.0",
|
||||
"lucide-react": "^0.454.0",
|
||||
"lucide-react": "^0.545.0",
|
||||
"next": "^14.2.33",
|
||||
"next-themes": "^0.4.6",
|
||||
"react": "^18.3.1",
|
||||
@ -3381,12 +3381,12 @@
|
||||
}
|
||||
},
|
||||
"node_modules/lucide-react": {
|
||||
"version": "0.454.0",
|
||||
"resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.454.0.tgz",
|
||||
"integrity": "sha512-hw7zMDwykCLnEzgncEEjHeA6+45aeEzRYuKHuyRSOPkhko+J3ySGjGIzu+mmMfDFG1vazHepMaYFYHbTFAZAAQ==",
|
||||
"version": "0.545.0",
|
||||
"resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.545.0.tgz",
|
||||
"integrity": "sha512-7r1/yUuflQDSt4f1bpn5ZAocyIxcTyVyBBChSVtBKn5M+392cPmI5YJMWOJKk/HUWGm5wg83chlAZtCcGbEZtw==",
|
||||
"license": "ISC",
|
||||
"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": {
|
||||
|
||||
@ -53,7 +53,7 @@
|
||||
"input-otp": "1.4.1",
|
||||
"js-cookie": "^3.0.5",
|
||||
"jwt-decode": "^4.0.0",
|
||||
"lucide-react": "^0.454.0",
|
||||
"lucide-react": "^0.545.0",
|
||||
"next": "^14.2.33",
|
||||
"next-themes": "^0.4.6",
|
||||
"react": "^18.3.1",
|
||||
|
||||
@ -56,12 +56,59 @@ async function request(endpoint, options = {}) {
|
||||
...(token ? { "Authorization": `Bearer ${token}` } : {}),
|
||||
...options.headers,
|
||||
};
|
||||
const API_KEY =
|
||||
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Inl1YW5xZnN3aGJlcmtvZXZ0bWZyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTQ5NTQzNjksImV4cCI6MjA3MDUzMDM2OX0.g8Fm4XAvtX46zifBZnYVH4tVuQkqUH6Ia9CXQj4DztQ";
|
||||
|
||||
try {
|
||||
const response = await fetch(`${BASE_URL}${endpoint}`, {
|
||||
...options,
|
||||
headers,
|
||||
});
|
||||
export const apikey = API_KEY;
|
||||
let loginPromise = null;
|
||||
|
||||
// 🔹 Autenticação
|
||||
export async function login() {
|
||||
const res = await fetch(`${BASE_URL}/auth/v1/token?grant_type=password`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
apikey: API_KEY,
|
||||
Prefer: "return=representation",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
email: "riseup@popcode.com.br",
|
||||
password: "riseup",
|
||||
}),
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
if (typeof window !== "undefined") {
|
||||
localStorage.setItem("token", data.access_token);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
async function request(endpoint, options = {}) {
|
||||
if (!loginPromise) loginPromise = login();
|
||||
|
||||
try {
|
||||
await loginPromise;
|
||||
} catch (error) {
|
||||
console.error("Falha ao autenticar:", error);
|
||||
} finally {
|
||||
loginPromise = null;
|
||||
}
|
||||
|
||||
const token =
|
||||
typeof window !== "undefined" ? localStorage.getItem("token") : null;
|
||||
|
||||
const headers = {
|
||||
"Content-Type": "application/json",
|
||||
apikey: API_KEY,
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
...options.headers,
|
||||
};
|
||||
|
||||
const response = await fetch(`${BASE_URL}${endpoint}`, {
|
||||
...options,
|
||||
headers,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
let errorBody;
|
||||
@ -89,4 +136,22 @@ export const api = {
|
||||
patch: (endpoint, data, options) => request(endpoint, { method: "PATCH", body: JSON.stringify(data), ...options }),
|
||||
delete: (endpoint, options) => request(endpoint, { method: "DELETE", ...options }),
|
||||
logout: logout, // <-- EXPORTANDO A NOVA FUNÇÃO
|
||||
};
|
||||
};
|
||||
if (!response.ok) {
|
||||
const msg = await response.text();
|
||||
throw new Error(`Erro HTTP: ${response.status} - Detalhes: ${msg}`);
|
||||
}
|
||||
|
||||
const contentType = response.headers.get("content-type");
|
||||
if (!contentType || !contentType.includes("application/json")) return {};
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
export const api = {
|
||||
get: (endpoint, options) => request(endpoint, { method: "GET", ...options }),
|
||||
post: (endpoint, data) =>
|
||||
request(endpoint, { method: "POST", body: JSON.stringify(data) }),
|
||||
patch: (endpoint, data) =>
|
||||
request(endpoint, { method: "PATCH", body: JSON.stringify(data) }),
|
||||
delete: (endpoint) => request(endpoint, { method: "DELETE" }),
|
||||
};
|
||||
|
||||
@ -1,10 +1,53 @@
|
||||
import { api } from "./api.mjs";
|
||||
|
||||
export const usersService = {
|
||||
create_user: (data) => api.post(`/functions/v1/create-user`),
|
||||
list_roles: () => api.get(`/rest/v1/user_roles`),
|
||||
full_data: (id) => {
|
||||
const endpoint = `/functions/v1/user-info?user_id=${id}`;
|
||||
return api.get(endpoint);
|
||||
async list_roles() {
|
||||
return await api.get(`/rest/v1/user_roles?select=id,user_id,role,created_at`);
|
||||
},
|
||||
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,
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user