Compare commits
11 commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bed3989eda | ||
|
|
cefd6fd561 | ||
|
|
a1d08b9be0 | ||
|
|
cb51e0ed19 | ||
|
|
15b4338ada | ||
|
|
ef8c499f37 | ||
|
|
e33bb452cf | ||
|
|
5351fd4be8 | ||
|
|
c92e903c3c | ||
|
|
a8eb911832 | ||
|
|
3ff500b515 |
45 changed files with 997 additions and 100 deletions
155
src/app/(protected)/administrativo/(user)/usuarios/page.tsx
Normal file
155
src/app/(protected)/administrativo/(user)/usuarios/page.tsx
Normal file
|
|
@ -0,0 +1,155 @@
|
|||
'use client';
|
||||
|
||||
import { useEffect, useState, useCallback } from 'react';
|
||||
|
||||
// Componentes de UI Genéricos
|
||||
import z from 'zod';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import Loading from '@/shared/components/loading/loading';
|
||||
import Header from '@/shared/components/structure/Header';
|
||||
import ConfirmDialog from '@/shared/components/confirmDialog/ConfirmDialog';
|
||||
import { useConfirmDialog } from '@/shared/components/confirmDialog/useConfirmDialog';
|
||||
|
||||
// Componentes de UI Específicos de Usuário
|
||||
import UserTable from '@/packages/administrativo/components/User/UserTable';
|
||||
import UserForm from '@/packages/administrativo/components/User/UserForm';
|
||||
|
||||
// Hooks Específicos de Usuário
|
||||
import { useUserIndexHook } from '@/packages/administrativo/hooks/User/useUserIndexHook';
|
||||
import { useUserSaveHook } from '@/packages/administrativo/hooks/User/useUserSaveHook';
|
||||
import { useUserDeleteHook } from '@/packages/administrativo/hooks/User/useUserDeleteHook';
|
||||
|
||||
// Interface
|
||||
import { UserInterface } from '@/packages/administrativo/interfaces/User/UserInterface';
|
||||
import { UserSchema } from '@/packages/administrativo/schemas/User/UserSchema';
|
||||
import { SituacoesEnum } from '@/shared/enums/SituacoesEnum';
|
||||
|
||||
const initialUser: UserInterface = {
|
||||
user_id: 0,
|
||||
name: '',
|
||||
email: '',
|
||||
password: '',
|
||||
team: '',
|
||||
position: 'string',
|
||||
status: SituacoesEnum.ATIVO,
|
||||
user_id_create: null,
|
||||
user_id_update: null,
|
||||
}
|
||||
|
||||
export default function UsersPage() {
|
||||
|
||||
const [buttonIsLoading, setButtonIsLoading] = useState(false);
|
||||
// 1. Hooks de dados para Usuário
|
||||
const { usuarios, fetchUsuarios } = useUserIndexHook();
|
||||
const { saveUser } = useUserSaveHook();
|
||||
const { removeUser } = useUserDeleteHook(); // Presumindo que o hook existe e expõe `removeUser`
|
||||
|
||||
// 2. Estados da página
|
||||
const [selectedUser, setSelectedUser] = useState<UserInterface | null>(null);
|
||||
const [isFormOpen, setIsFormOpen] = useState(false);
|
||||
const [userToDelete, setUserToDelete] = useState<UserInterface | null>(null);
|
||||
|
||||
// Hook do modal de confirmação
|
||||
const {
|
||||
isOpen: isConfirmOpen,
|
||||
openDialog: openConfirmDialog,
|
||||
handleCancel,
|
||||
} = useConfirmDialog();
|
||||
|
||||
// 3. Funções de manipulação do formulário
|
||||
const handleOpenForm = useCallback((user: UserInterface | null) => {
|
||||
setSelectedUser(user);
|
||||
setIsFormOpen(true);
|
||||
}, []);
|
||||
|
||||
const handleCloseForm = useCallback(() => {
|
||||
setSelectedUser(null);
|
||||
setIsFormOpen(false);
|
||||
}, []);
|
||||
|
||||
// 4. Função para salvar (criar ou editar)
|
||||
const handleSave = useCallback(
|
||||
async (formData: UserInterface) => {
|
||||
|
||||
setButtonIsLoading(true);
|
||||
|
||||
await saveUser(formData);
|
||||
|
||||
setButtonIsLoading(false);
|
||||
|
||||
setIsFormOpen(false);
|
||||
|
||||
fetchUsuarios(); // Atualiza a lista de usuários
|
||||
},
|
||||
[saveUser, fetchUsuarios, handleCloseForm],
|
||||
);
|
||||
|
||||
// 5. Funções para exclusão
|
||||
const handleConfirmDelete = useCallback(
|
||||
(user: UserInterface) => {
|
||||
setUserToDelete(user);
|
||||
openConfirmDialog();
|
||||
},
|
||||
[openConfirmDialog],
|
||||
);
|
||||
|
||||
const handleDelete = useCallback(async () => {
|
||||
if (!userToDelete) return;
|
||||
|
||||
await removeUser(userToDelete); // Chama o hook de remoção
|
||||
await fetchUsuarios(); // Atualiza a lista
|
||||
setUserToDelete(null); // Limpa o estado
|
||||
handleCancel(); // Fecha o modal de confirmação
|
||||
}, [userToDelete, fetchUsuarios, handleCancel]);
|
||||
|
||||
// 6. Busca inicial dos dados
|
||||
useEffect(() => {
|
||||
fetchUsuarios();
|
||||
}, []);
|
||||
|
||||
// 7. Renderização condicional de loading
|
||||
if (usuarios?.length == 0) {
|
||||
return <Loading type={2} />;
|
||||
}
|
||||
|
||||
// 8. Renderização da página
|
||||
return (
|
||||
<div>
|
||||
<Header
|
||||
title={'Usuários'}
|
||||
description={'Gerenciamento de Usuários do Sistema'}
|
||||
buttonText={'Novo Usuário'}
|
||||
buttonAction={(data) => handleOpenForm(data = initialUser)}
|
||||
/>
|
||||
|
||||
<Card>
|
||||
<CardContent>
|
||||
<UserTable
|
||||
data={usuarios}
|
||||
onEdit={handleOpenForm}
|
||||
onDelete={handleConfirmDelete}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<ConfirmDialog
|
||||
isOpen={isConfirmOpen}
|
||||
title="Confirmar exclusão"
|
||||
description="Esta ação não pode ser desfeita."
|
||||
message={`Deseja realmente excluir o usuário "${userToDelete?.name}"?`}
|
||||
confirmText="Sim, excluir"
|
||||
cancelText="Cancelar"
|
||||
onConfirm={handleDelete}
|
||||
onCancel={handleCancel}
|
||||
/>
|
||||
|
||||
<UserForm
|
||||
isOpen={isFormOpen}
|
||||
data={selectedUser}
|
||||
onClose={handleCloseForm}
|
||||
onSave={handleSave}
|
||||
buttonIsLoading={buttonIsLoading}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import { LoginForm } from '@/packages/administrativo/components/GUsuario/GUsuarioLoginForm';
|
||||
import { LoginForm } from '@/packages/administrativo/components/User/UserLoginForm';
|
||||
|
||||
export default function LoginPage() {
|
||||
return (
|
||||
|
|
|
|||
|
|
@ -18,14 +18,14 @@ import {
|
|||
useSidebar,
|
||||
} from '@/components/ui/sidebar';
|
||||
|
||||
import GUsuarioAuthenticatedInterface from '@/shared/interfaces/GUsuarioAuthenticatedInterface';
|
||||
import UserAuthenticatedInterface from '@/shared/interfaces/UserAuthenticatedInterface';
|
||||
import ConfirmDialog from '@/shared/components/confirmDialog/ConfirmDialog';
|
||||
import { useGUsuarioLogoutHook } from '@/packages/administrativo/hooks/GUsuario/useGUsuarioLogoutHook';
|
||||
import { useUserLogoutHook } from '@/packages/administrativo/hooks/User/useUserLogoutHook';
|
||||
import { use, useCallback, useState } from 'react';
|
||||
|
||||
export function NavUser({ user }: { user: GUsuarioAuthenticatedInterface }) {
|
||||
export function NavUser({ user }: { user: UserAuthenticatedInterface }) {
|
||||
// Hook para encerrar sessão
|
||||
const { logoutUsuario } = useGUsuarioLogoutHook();
|
||||
const { logoutUsuario } = useUserLogoutHook();
|
||||
|
||||
// Controle de exibição do formulário de confirmação
|
||||
const [isConfirmOpen, setIsConfirmOpen] = useState(false);
|
||||
|
|
|
|||
204
src/packages/administrativo/components/User/UserForm.tsx
Normal file
204
src/packages/administrativo/components/User/UserForm.tsx
Normal file
|
|
@ -0,0 +1,204 @@
|
|||
'use client';
|
||||
|
||||
import z from 'zod';
|
||||
import { useEffect } from 'react';
|
||||
import { useForm, Controller } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@/components/ui/form';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { SituacoesEnum } from '@/shared/enums/SituacoesEnum';
|
||||
import { UserSchema } from '../../schemas/User/UserSchema';
|
||||
import LoadingButton from '@/shared/components/loadingButton/LoadingButton';
|
||||
|
||||
type FormValues = z.infer<typeof UserSchema>;
|
||||
|
||||
interface Props {
|
||||
isOpen: boolean;
|
||||
data: FormValues | null;
|
||||
onClose: (item: null, isFormStatus: boolean) => void;
|
||||
onSave: (data: FormValues) => void;
|
||||
buttonIsLoading: boolean;
|
||||
}
|
||||
|
||||
export default function UserForm({ isOpen, data, onClose, onSave, buttonIsLoading }: Props) {
|
||||
const form = useForm<FormValues>({
|
||||
resolver: zodResolver(UserSchema),
|
||||
defaultValues: {
|
||||
user_id: 0,
|
||||
name: '',
|
||||
email: '',
|
||||
password: '',
|
||||
team: '',
|
||||
position: 'string',
|
||||
status: SituacoesEnum.ATIVO,
|
||||
user_id_create: null,
|
||||
user_id_update: null,
|
||||
date_register: new Date().toISOString(),
|
||||
date_update: null
|
||||
},
|
||||
});
|
||||
|
||||
// Atualiza o formulário quando recebe dados para edição
|
||||
useEffect(() => {
|
||||
if (data) form.reset(data);
|
||||
console.log("form", form.getValues())
|
||||
}, [data, form]);
|
||||
|
||||
function onError(error: any) {
|
||||
console.log("error", error)
|
||||
}
|
||||
|
||||
function submit(response: any) {
|
||||
console.log("submit", response)
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={isOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) onClose(null, false);
|
||||
}}
|
||||
>
|
||||
<DialogContent className="sm:max-w-[425px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{data?.user_id ? 'Editar Usuário' : 'Novo Usuário'}</DialogTitle>
|
||||
<DialogDescription>Gerencie os dados do usuário aqui.</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSave, onError)} className="space-y-4">
|
||||
{/* Nome */}
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Nome</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} placeholder="Digite o nome completo" />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
{/* Email */}
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="email"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Email</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="email" {...field} placeholder="exemplo@email.com" />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
{/* Senha */}
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="password"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Senha</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="password" {...field} placeholder={data ? 'Deixe em branco para não alterar' : 'Digite a senha'} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
{/* Equipe */}
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="team"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Equipe</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} placeholder="Digite o nome da equipe" />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
{/* Cargo */}
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="position"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Cargo</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} placeholder="Digite o cargo do usuário" />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
{/* Status */}
|
||||
<Controller
|
||||
name="status"
|
||||
control={form.control}
|
||||
render={({ field }) => (
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
checked={field.value === 'A'}
|
||||
onCheckedChange={(checked) => field.onChange(checked ? 'A' : 'I')}
|
||||
/>
|
||||
<Label>Ativo</Label>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
{/* Rodapé */}
|
||||
<DialogFooter className="mt-4">
|
||||
<DialogClose asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
type="button"
|
||||
onClick={() => onClose(null, false)}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
</DialogClose>
|
||||
<LoadingButton
|
||||
text={data?.user_id ? 'Salvar' : 'Cadastrar'}
|
||||
textLoading="Aguarde..."
|
||||
type="submit"
|
||||
loading={buttonIsLoading}
|
||||
/>
|
||||
</DialogFooter>
|
||||
{/* Campo oculto para o ID */}
|
||||
<input type="hidden" {...form.register('user_id')} />
|
||||
<input type="hidden" {...form.register('date_register')} />
|
||||
<input type="hidden" {...form.register('date_update')} />
|
||||
</form>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
|
@ -6,34 +6,35 @@ import { Card, CardContent } from '@/components/ui/card';
|
|||
import { Input } from '@/components/ui/input';
|
||||
import z from 'zod';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import GUsuarioLoginService from '@/packages/administrativo/services/GUsuario/GUsuarioLoginService';
|
||||
import UserLoginService from '@/packages/administrativo/services/User/UserLoginService';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { useState } from 'react';
|
||||
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '../../../../components/ui/form';
|
||||
import LoadingButton from '@/shared/components/loadingButton/LoadingButton';
|
||||
import { Button } from '../../../../components/ui/button';
|
||||
import { GUsuarioLoginSchema } from '@/packages/administrativo/schemas/GUsuario/GUsuarioLoginSchema';
|
||||
import { UserLoginSchema } from '@/packages/administrativo/schemas/User/UserLoginSchema';
|
||||
|
||||
type FormValues = z.infer<typeof GUsuarioLoginSchema>;
|
||||
type FormValues = z.infer<typeof UserLoginSchema>;
|
||||
|
||||
export function LoginForm({ className, ...props }: React.ComponentProps<'div'>) {
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const form = useForm<FormValues>({
|
||||
resolver: zodResolver(GUsuarioLoginSchema),
|
||||
resolver: zodResolver(UserLoginSchema),
|
||||
defaultValues: {
|
||||
login: '',
|
||||
senha_api: '',
|
||||
email: '',
|
||||
password: '',
|
||||
},
|
||||
});
|
||||
|
||||
// onSubmit agora recebe o evento do form através do handleSubmit
|
||||
const onSubmit = async (values: FormValues) => {
|
||||
console.log("dados para login",values)
|
||||
// Ativa o estado de loading do botão
|
||||
setLoading(true);
|
||||
|
||||
// Realiza o login
|
||||
await GUsuarioLoginService(values);
|
||||
await UserLoginService(values);
|
||||
|
||||
// Removo o estado de loading do botão
|
||||
setLoading(false);
|
||||
|
|
@ -53,7 +54,7 @@ export function LoginForm({ className, ...props }: React.ComponentProps<'div'>)
|
|||
</div>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="login"
|
||||
name="email"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Login</FormLabel>
|
||||
|
|
@ -66,7 +67,7 @@ export function LoginForm({ className, ...props }: React.ComponentProps<'div'>)
|
|||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="senha_api"
|
||||
name="password"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Senha</FormLabel>
|
||||
105
src/packages/administrativo/components/User/UserTable.tsx
Normal file
105
src/packages/administrativo/components/User/UserTable.tsx
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
'use client';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
|
||||
import { EllipsisIcon, PencilIcon, Trash2Icon } from 'lucide-react';
|
||||
import { UserInterface } from '../../interfaces/User/UserInterface'; // Ajuste o caminho conforme necessário
|
||||
import { SituacoesEnum } from '@/shared/enums/SituacoesEnum';
|
||||
|
||||
interface UserTableProps {
|
||||
data: UserInterface[];
|
||||
onEdit: (user: UserInterface) => void;
|
||||
onDelete: (user: UserInterface) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renderiza o badge de situação (Ativo/Inativo)
|
||||
*/
|
||||
function StatusBadge({ status }: { status: SituacoesEnum }) {
|
||||
const isActive = status === 'A';
|
||||
const baseClasses = 'text-xs font-medium px-2.5 py-0.5 rounded-sm me-2';
|
||||
const activeClasses = 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300';
|
||||
const inactiveClasses = 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-300';
|
||||
|
||||
return (
|
||||
<span className={`${baseClasses} ${isActive ? activeClasses : inactiveClasses}`}>
|
||||
{isActive ? 'Ativo' : 'Inativo'}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export default function UserTable({ data, onEdit, onDelete }: UserTableProps) {
|
||||
return (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>#</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead>Nome</TableHead>
|
||||
<TableHead>Email</TableHead>
|
||||
<TableHead>Equipe</TableHead>
|
||||
<TableHead className="text-right">Ações</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
|
||||
<TableBody>
|
||||
{data.map((user) => (
|
||||
<TableRow key={user.user_id}>
|
||||
<TableCell className="font-medium">{user.user_id}</TableCell>
|
||||
<TableCell>
|
||||
<StatusBadge status={user.status} />
|
||||
</TableCell>
|
||||
<TableCell>{user.name}</TableCell>
|
||||
<TableCell>{user.email}</TableCell>
|
||||
<TableCell>{user.team}</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" size="icon" className="cursor-pointer">
|
||||
<EllipsisIcon />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
|
||||
<DropdownMenuContent side="left" align="start">
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuItem
|
||||
className="cursor-pointer"
|
||||
onSelect={() => onEdit(user)}
|
||||
>
|
||||
<PencilIcon className="mr-2 h-4 w-4" />
|
||||
Editar
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
className="cursor-pointer"
|
||||
onSelect={() => onDelete(user)}
|
||||
>
|
||||
<Trash2Icon className="mr-2 h-4 w-4" />
|
||||
Remover
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,16 +0,0 @@
|
|||
'use server';
|
||||
|
||||
import { Methods } from '@/shared/services/api/enums/ApiMethodEnum';
|
||||
import API from '@/shared/services/api/Api';
|
||||
|
||||
export default async function GUsuarioLoginData(form: any) {
|
||||
const api = new API();
|
||||
// Realiza o envio dos dados
|
||||
const response = await api.send({
|
||||
method: Methods.POST,
|
||||
endpoint: `administrativo/g_usuario/authenticate`,
|
||||
body: form,
|
||||
});
|
||||
|
||||
return response;
|
||||
}
|
||||
20
src/packages/administrativo/data/User/UserDeleteData.ts
Normal file
20
src/packages/administrativo/data/User/UserDeleteData.ts
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
'use server'
|
||||
|
||||
import { Methods } from '@/shared/services/api/enums/ApiMethodEnum';
|
||||
import API from '@/shared/services/api/Api';
|
||||
import { withClientErrorHandler } from '@/withClientErrorHandler/withClientErrorHandler';
|
||||
|
||||
async function executeUserDeleteData(usuarioId: number) {
|
||||
|
||||
const api = new API();
|
||||
|
||||
const response = await api.send({
|
||||
'method': Methods.DELETE,
|
||||
'endpoint': `administrativo/user/${usuarioId}`
|
||||
});
|
||||
|
||||
return response;
|
||||
|
||||
}
|
||||
|
||||
export const UserDeleteData = withClientErrorHandler(executeUserDeleteData)
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
'use server'
|
||||
import { Methods } from '@/shared/services/api/enums/ApiMethodEnum';
|
||||
import API from '@/shared/services/api/Api';
|
||||
import { withClientErrorHandler } from '@/withClientErrorHandler/withClientErrorHandler';
|
||||
|
||||
async function executeUserIndexByEmailData(email: string) {
|
||||
|
||||
const api = new API();
|
||||
|
||||
const response = await api.send({
|
||||
'method': Methods.GET,
|
||||
'endpoint': `administrativo/user/email?email=${email}`
|
||||
});
|
||||
|
||||
return response;
|
||||
|
||||
}
|
||||
|
||||
export const UserIndexByEmailData = withClientErrorHandler(executeUserIndexByEmailData)
|
||||
19
src/packages/administrativo/data/User/UserIndexByIDData.ts
Normal file
19
src/packages/administrativo/data/User/UserIndexByIDData.ts
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
'use server'
|
||||
import { Methods } from '@/shared/services/api/enums/ApiMethodEnum';
|
||||
import API from '@/shared/services/api/Api';
|
||||
import { withClientErrorHandler } from '@/withClientErrorHandler/withClientErrorHandler';
|
||||
|
||||
async function executeUserIndexByIDData(user_id: number) {
|
||||
|
||||
const api = new API();
|
||||
|
||||
const response = await api.send({
|
||||
'method': Methods.GET,
|
||||
'endpoint': `administrativo/user/${user_id}`
|
||||
});
|
||||
|
||||
return response;
|
||||
|
||||
}
|
||||
|
||||
export const UserIndexByIDData = withClientErrorHandler(executeUserIndexByIDData)
|
||||
19
src/packages/administrativo/data/User/UserIndexData.ts
Normal file
19
src/packages/administrativo/data/User/UserIndexData.ts
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
'use server'
|
||||
import { Methods } from '@/shared/services/api/enums/ApiMethodEnum';
|
||||
import API from '@/shared/services/api/Api';
|
||||
import { withClientErrorHandler } from '@/withClientErrorHandler/withClientErrorHandler';
|
||||
|
||||
async function executeUserIndexData() {
|
||||
|
||||
const api = new API();
|
||||
|
||||
const response = await api.send({
|
||||
'method': Methods.GET,
|
||||
'endpoint': `administrativo/user/`
|
||||
});
|
||||
|
||||
return response;
|
||||
|
||||
}
|
||||
|
||||
export const UserIndexData = withClientErrorHandler(executeUserIndexData)
|
||||
19
src/packages/administrativo/data/User/UserLoggedIndexData.ts
Normal file
19
src/packages/administrativo/data/User/UserLoggedIndexData.ts
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
'use server'
|
||||
import { Methods } from '@/shared/services/api/enums/ApiMethodEnum';
|
||||
import API from '@/shared/services/api/Api';
|
||||
import { withClientErrorHandler } from '@/withClientErrorHandler/withClientErrorHandler';
|
||||
|
||||
async function executeUserLoggedIndexData() {
|
||||
|
||||
const api = new API();
|
||||
|
||||
const response = await api.send({
|
||||
'method': Methods.GET,
|
||||
'endpoint': `administrativo/user/me`
|
||||
});
|
||||
|
||||
return response;
|
||||
|
||||
}
|
||||
|
||||
export const UserLoggedIndexData = withClientErrorHandler(executeUserLoggedIndexData)
|
||||
21
src/packages/administrativo/data/User/UserLoginData.ts
Normal file
21
src/packages/administrativo/data/User/UserLoginData.ts
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
'use server';
|
||||
|
||||
import { Methods } from '@/shared/services/api/enums/ApiMethodEnum';
|
||||
import API from '@/shared/services/api/Api';
|
||||
import { AuthenticateUserInterface } from '@/shared/interfaces/AuthenticateUserInterface';
|
||||
import { withClientErrorHandler } from '@/withClientErrorHandler/withClientErrorHandler';
|
||||
|
||||
export default async function UserLoginData(form: any) {
|
||||
const api = new API();
|
||||
|
||||
const response = await api.send({
|
||||
method: Methods.POST,
|
||||
endpoint: `administrativo/user/authenticate`,
|
||||
body: form,
|
||||
});
|
||||
|
||||
console.log("resposta da api",response)
|
||||
|
||||
return response;
|
||||
|
||||
}
|
||||
20
src/packages/administrativo/data/User/UserReadData.ts
Normal file
20
src/packages/administrativo/data/User/UserReadData.ts
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
'use server'
|
||||
|
||||
import { Methods } from '@/shared/services/api/enums/ApiMethodEnum';
|
||||
import API from '@/shared/services/api/Api';
|
||||
import { withClientErrorHandler } from '@/withClientErrorHandler/withClientErrorHandler';
|
||||
|
||||
async function executeUserReadData(usuarioId: number) {
|
||||
|
||||
const api = new API();
|
||||
|
||||
const response = await api.send({
|
||||
'method': Methods.GET,
|
||||
'endpoint': `administrativo/user/${usuarioId}`
|
||||
});
|
||||
|
||||
return response
|
||||
|
||||
}
|
||||
|
||||
export const UserReadData = withClientErrorHandler(executeUserReadData)
|
||||
23
src/packages/administrativo/data/User/UserSaveData.ts
Normal file
23
src/packages/administrativo/data/User/UserSaveData.ts
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
'use server'
|
||||
|
||||
import { Methods } from '@/shared/services/api/enums/ApiMethodEnum';
|
||||
import API from '@/shared/services/api/Api';
|
||||
import { withClientErrorHandler } from '@/withClientErrorHandler/withClientErrorHandler';
|
||||
import { UserInterface } from '../../interfaces/User/UserInterface';
|
||||
|
||||
async function executeUserSaveData(form: UserInterface) {
|
||||
const isUpdate = Boolean(form.user_id)
|
||||
|
||||
const api = new API();
|
||||
|
||||
const response = await api.send({
|
||||
'method': isUpdate ? Methods.PUT : Methods.POST,
|
||||
'endpoint': `administrativo/user/${form.user_id || ''}`,
|
||||
'body': form
|
||||
});
|
||||
|
||||
return response;
|
||||
|
||||
}
|
||||
|
||||
export const UserSaveData = withClientErrorHandler(executeUserSaveData)
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
'use client';
|
||||
|
||||
import GUsuarioLogoutService from '../../services/GUsuario/GUsuarioLogoutService';
|
||||
|
||||
export const useGUsuarioLogoutHook = () => {
|
||||
const logoutUsuario = async () => {
|
||||
await GUsuarioLogoutService('access_token');
|
||||
};
|
||||
|
||||
return { logoutUsuario };
|
||||
};
|
||||
28
src/packages/administrativo/hooks/User/useUserDeleteHook.ts
Normal file
28
src/packages/administrativo/hooks/User/useUserDeleteHook.ts
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useResponse } from '@/shared/components/response/ResponseContext';
|
||||
import { UserDeleteService } from '../../services/User/UserDeleteService'; // Ajuste o caminho conforme necessário
|
||||
import { UserInterface } from '../../interfaces/User/UserInterface'; // Ajuste o caminho
|
||||
|
||||
export const useUserDeleteHook = () => {
|
||||
// Hook de contexto para fornecer feedback (toast, modal, etc.)
|
||||
const { setResponse } = useResponse();
|
||||
|
||||
const removeUser = async (user: UserInterface) => {
|
||||
|
||||
try {
|
||||
// Chama o serviço de exclusão, passando apenas o ID do usuário
|
||||
const response = await UserDeleteService(user.user_id);
|
||||
|
||||
// Define a resposta para que o ResponseContext possa exibir um feedback
|
||||
setResponse(response);
|
||||
} catch (error) {
|
||||
// O withClientErrorHandler já trata o erro, mas um log pode ser útil
|
||||
console.error('Erro ao remover usuário:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// Retorna a função de remoção e o estado de carregamento
|
||||
return { removeUser };
|
||||
};
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { UserInterface } from '../../interfaces/User/UserInterface';
|
||||
import { UserIndexByEmailService } from '../../services/User/UserIndexByEmailService';
|
||||
import { useResponse } from '@/shared/components/response/ResponseContext';
|
||||
|
||||
export const useUserIndexByEmailHook = () => {
|
||||
const { setResponse } = useResponse();
|
||||
|
||||
const [user, setUser] = useState<UserInterface | null>(null);
|
||||
|
||||
const fetchUserByEmail = async (email: string) => {
|
||||
try {
|
||||
const response = await UserIndexByEmailService(email);
|
||||
|
||||
setUser(response.data);
|
||||
setResponse(response);
|
||||
} catch (error) {
|
||||
console.error("Erro ao buscar usuário por Email:", error);
|
||||
}
|
||||
};
|
||||
|
||||
return { user, fetchUserByEmail };
|
||||
};
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { UserInterface } from '../../interfaces/User/UserInterface';
|
||||
import { UserIndexByIDService } from '../../services/User/UserIndexByIDService';
|
||||
import { useResponse } from '@/shared/components/response/ResponseContext';
|
||||
|
||||
export const useUserIndexByIdHook = () => {
|
||||
const { setResponse } = useResponse();
|
||||
|
||||
const [user, setUser] = useState<UserInterface | null>(null);
|
||||
|
||||
const fetchUserById = async (userId: number) => {
|
||||
try {
|
||||
const response = await UserIndexByIDService(userId);
|
||||
|
||||
setUser(response.data);
|
||||
setResponse(response);
|
||||
} catch (error) {
|
||||
// O withClientErrorHandler já deve tratar o erro e formatar a 'response',
|
||||
// mas um catch local pode ser útil para lógicas adicionais se necessário.
|
||||
console.error("Erro ao buscar usuário por ID:", error);
|
||||
}
|
||||
};
|
||||
|
||||
return { user, fetchUserById };
|
||||
};
|
||||
23
src/packages/administrativo/hooks/User/useUserIndexHook.ts
Normal file
23
src/packages/administrativo/hooks/User/useUserIndexHook.ts
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { UserInterface } from '../../interfaces/User/UserInterface';
|
||||
import { UserIndexService } from '../../services/User/UserIndexService';
|
||||
import { useResponse } from '@/shared/components/response/ResponseContext';
|
||||
|
||||
export const useUserIndexHook = () => {
|
||||
const { setResponse } = useResponse();
|
||||
|
||||
const [usuarios, setUsuarios] = useState<UserInterface[]>([]);
|
||||
|
||||
const fetchUsuarios = async () => {
|
||||
const response = await UserIndexService();
|
||||
|
||||
setUsuarios(response.data);
|
||||
|
||||
// Define os dados do componente de resposta (toast, modal, etc)
|
||||
setResponse(response);
|
||||
};
|
||||
|
||||
return { usuarios, fetchUsuarios };
|
||||
};
|
||||
11
src/packages/administrativo/hooks/User/useUserLogoutHook.ts
Normal file
11
src/packages/administrativo/hooks/User/useUserLogoutHook.ts
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
'use client';
|
||||
|
||||
import { UserLogoutService } from '../../services/User/UserLogoutService';
|
||||
|
||||
export const useUserLogoutHook = () => {
|
||||
const logoutUsuario = async () => {
|
||||
await UserLogoutService('access_token');
|
||||
};
|
||||
|
||||
return { logoutUsuario };
|
||||
};
|
||||
22
src/packages/administrativo/hooks/User/useUserReadHooks.ts
Normal file
22
src/packages/administrativo/hooks/User/useUserReadHooks.ts
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { UserInterface } from '../../interfaces/User/UserInterface';
|
||||
import { UserReadService } from '../../services/User/UserReadService';
|
||||
import { useResponse } from '@/shared/components/response/ResponseContext';
|
||||
|
||||
export const useUserReadHooks = () => {
|
||||
const { setResponse } = useResponse();
|
||||
|
||||
const [User, setUser] = useState<UserInterface>();
|
||||
|
||||
const fetchUser = async (User: UserInterface) => {
|
||||
const response = await UserReadService(User.user_id);
|
||||
|
||||
setUser(response.data);
|
||||
|
||||
setResponse(response);
|
||||
};
|
||||
|
||||
return { User, fetchUser };
|
||||
};
|
||||
22
src/packages/administrativo/hooks/User/useUserSaveHook.ts
Normal file
22
src/packages/administrativo/hooks/User/useUserSaveHook.ts
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { UserInterface } from '../../interfaces/User/UserInterface';
|
||||
import { UserSaveService } from '../../services/User/UserSaveService';
|
||||
import { useResponse } from '@/shared/components/response/ResponseContext';
|
||||
|
||||
export const useUserSaveHook = () => {
|
||||
const { setResponse } = useResponse();
|
||||
|
||||
const [usuarios, setUser] = useState<UserInterface>();
|
||||
|
||||
const saveUser = async (User: any) => {
|
||||
const response = await UserSaveService(User);
|
||||
|
||||
setUser(response.data);
|
||||
|
||||
setResponse(response);
|
||||
};
|
||||
|
||||
return { usuarios, saveUser };
|
||||
};
|
||||
|
|
@ -1,34 +0,0 @@
|
|||
export default interface GUsuario {
|
||||
usuario_id: number;
|
||||
trocarsenha: string;
|
||||
login: string;
|
||||
senha: string;
|
||||
situacao: string;
|
||||
nome_completo: string;
|
||||
funcao: string;
|
||||
assina: string;
|
||||
sigla: string;
|
||||
usuario_tab: string;
|
||||
ultimo_login: string;
|
||||
ultimo_login_regs: string;
|
||||
data_expiracao: string;
|
||||
senha_anterior: string;
|
||||
andamento_padrao: string;
|
||||
lembrete_pergunta: string;
|
||||
lembrete_resposta: string;
|
||||
andamento_padrao2: string;
|
||||
receber_mensagem_arrolamento: string;
|
||||
email: string;
|
||||
assina_certidao: string;
|
||||
receber_email_penhora: string;
|
||||
foto: string;
|
||||
nao_receber_chat_todos: string;
|
||||
pode_alterar_caixa: string;
|
||||
receber_chat_certidao_online: string;
|
||||
receber_chat_cancelamento: string;
|
||||
cpf: string;
|
||||
somente_leitura: string;
|
||||
receber_chat_envio_onr: string;
|
||||
tipo_usuario: string;
|
||||
senha_api: string;
|
||||
}
|
||||
15
src/packages/administrativo/interfaces/User/UserInterface.ts
Normal file
15
src/packages/administrativo/interfaces/User/UserInterface.ts
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
import { SituacoesEnum } from "@/shared/enums/SituacoesEnum";
|
||||
|
||||
export interface UserInterface {
|
||||
user_id?: number;
|
||||
name: string;
|
||||
email: string;
|
||||
password: string;
|
||||
position: string;
|
||||
team: string;
|
||||
status: SituacoesEnum; // 'A' ou 'I'
|
||||
date_register?: string;
|
||||
date_update?: string | null;
|
||||
user_id_create: number | null,
|
||||
user_id_update: number | null
|
||||
}
|
||||
|
|
@ -1,6 +0,0 @@
|
|||
import { z } from 'zod';
|
||||
|
||||
export const GUsuarioLoginSchema = z.object({
|
||||
login: z.string().min(1, 'O campo deve ser preenchido'),
|
||||
senha_api: z.string().min(1, 'O campo deve ser preenchido'),
|
||||
});
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
import { z } from 'zod';
|
||||
|
||||
export const UserLoginSchema = z.object({
|
||||
email: z.string().min(1, 'O campo deve ser preenchido'),
|
||||
password: z.string().min(1, 'O campo deve ser preenchido'),
|
||||
});
|
||||
16
src/packages/administrativo/schemas/User/UserSchema.ts
Normal file
16
src/packages/administrativo/schemas/User/UserSchema.ts
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import { z } from "zod";
|
||||
import { SituacoesEnum } from "@/shared/enums/SituacoesEnum";
|
||||
|
||||
export const UserSchema = z.object({
|
||||
user_id: z.number().optional(),
|
||||
name: z.string().min(3, { message: "O nome deve ter no mínimo 3 caracteres." }),
|
||||
email: z.email({ message: "Por favor, insira um email válido." }),
|
||||
password: z.string().min(6, { message: "A senha deve ter pelo menos 6 caracteres." }),
|
||||
position: z.string().nullable().optional(),
|
||||
team: z.string().min(1, { message: "A equipe é obrigatória." }),
|
||||
status: z.enum(SituacoesEnum), // 'A' ou 'I'
|
||||
date_register: z.string().optional(),
|
||||
date_update: z.string().nullable().optional(),
|
||||
user_id_create: z.number().nullable(),
|
||||
user_id_update: z.number().nullable(),
|
||||
});
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
'use server'
|
||||
|
||||
import { withClientErrorHandler } from "@/withClientErrorHandler/withClientErrorHandler"
|
||||
import { UserDeleteData } from "../../data/User/UserDeleteData"
|
||||
|
||||
async function executeUserDeleteService(usuarioId: number) {
|
||||
|
||||
if (usuarioId <= 0) {
|
||||
return {
|
||||
'code': 400,
|
||||
'message': 'Usuário informado inválido',
|
||||
}
|
||||
}
|
||||
|
||||
const response = await UserDeleteData(usuarioId)
|
||||
return response
|
||||
|
||||
}
|
||||
|
||||
export const UserDeleteService = withClientErrorHandler(executeUserDeleteService)
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
'use server'
|
||||
|
||||
import { withClientErrorHandler } from "@/withClientErrorHandler/withClientErrorHandler";
|
||||
import { UserIndexByEmailData } from "../../data/User/UserIndexByEmailData";
|
||||
|
||||
async function executeUserIndexByEmailService(email: string) {
|
||||
|
||||
const response = await UserIndexByEmailData(email);
|
||||
|
||||
return response;
|
||||
|
||||
}
|
||||
|
||||
export const UserIndexByEmailService = withClientErrorHandler(executeUserIndexByEmailService)
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
'use server'
|
||||
|
||||
import { withClientErrorHandler } from "@/withClientErrorHandler/withClientErrorHandler";
|
||||
import { UserIndexByIDData } from "../../data/User/UserIndexByIDData";
|
||||
|
||||
async function executeUserIndexByIDService(user_id: number) {
|
||||
|
||||
const response = await UserIndexByIDData(user_id);
|
||||
|
||||
return response;
|
||||
|
||||
}
|
||||
|
||||
export const UserIndexByIDService = withClientErrorHandler(executeUserIndexByIDService)
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
'use server'
|
||||
|
||||
import { withClientErrorHandler } from "@/withClientErrorHandler/withClientErrorHandler";
|
||||
import { UserIndexData } from "../../data/User/UserIndexData";
|
||||
|
||||
async function executeUserIndexService() {
|
||||
|
||||
const response = await UserIndexData();
|
||||
|
||||
return response;
|
||||
|
||||
}
|
||||
|
||||
export const UserIndexService = withClientErrorHandler(executeUserIndexService)
|
||||
|
|
@ -2,14 +2,17 @@
|
|||
|
||||
import { cookies } from 'next/headers';
|
||||
|
||||
import GUsuarioLoginData from '../../data/GUsuario/GUsuarioLoginData';
|
||||
import UserLoginData from '../../data/User/UserLoginData';
|
||||
import { redirect } from 'next/navigation';
|
||||
import { withClientErrorHandler } from '@/withClientErrorHandler/withClientErrorHandler';
|
||||
|
||||
export default async function GUsuarioLoginService(form: any) {
|
||||
export default async function UserLoginService(form: any) {
|
||||
// Obtem a resposta da requisição
|
||||
const response = await GUsuarioLoginData(form);
|
||||
const response = await UserLoginData(form);
|
||||
|
||||
console.log("service",response)
|
||||
// Verifica se localizou o usuário
|
||||
if (response.data.usuario_id <= 0) {
|
||||
if (response.data.user_id <= 0) {
|
||||
return {
|
||||
code: 404,
|
||||
message: 'Não foi localizado o usuário',
|
||||
|
|
@ -29,5 +32,5 @@ export default async function GUsuarioLoginService(form: any) {
|
|||
});
|
||||
|
||||
// Redireciona para a págian desejada
|
||||
redirect('/servicos');
|
||||
redirect('/administrativo/usuarios');
|
||||
}
|
||||
|
|
@ -1,10 +1,11 @@
|
|||
'use server';
|
||||
|
||||
import { withClientErrorHandler } from '@/withClientErrorHandler/withClientErrorHandler';
|
||||
import { cookies } from 'next/headers';
|
||||
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
export default async function GUsuarioLogoutService(token: string) {
|
||||
async function executeUserLogoutService(token: string) {
|
||||
const cookieStore = await cookies();
|
||||
cookieStore.set(token, '', {
|
||||
expires: new Date(0),
|
||||
|
|
@ -13,3 +14,5 @@ export default async function GUsuarioLogoutService(token: string) {
|
|||
|
||||
redirect('/login');
|
||||
}
|
||||
|
||||
export const UserLogoutService = withClientErrorHandler(executeUserLogoutService)
|
||||
22
src/packages/administrativo/services/User/UserReadService.ts
Normal file
22
src/packages/administrativo/services/User/UserReadService.ts
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
'use server'
|
||||
|
||||
import { withClientErrorHandler } from "@/withClientErrorHandler/withClientErrorHandler";
|
||||
import { UserReadData } from "../../data/User/UserReadData";
|
||||
|
||||
async function executeUserReadService(usuarioId: number) {
|
||||
|
||||
// Verifica se o id informado é válido
|
||||
if (usuarioId <= 0) {
|
||||
return {
|
||||
'code': 400,
|
||||
'message': 'Usuário informado inválido',
|
||||
}
|
||||
}
|
||||
|
||||
const response = await UserReadData(usuarioId);
|
||||
return response
|
||||
|
||||
|
||||
}
|
||||
|
||||
export const UserReadService = withClientErrorHandler(executeUserReadService)
|
||||
12
src/packages/administrativo/services/User/UserSaveService.ts
Normal file
12
src/packages/administrativo/services/User/UserSaveService.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
'use server'
|
||||
|
||||
import { withClientErrorHandler } from "@/withClientErrorHandler/withClientErrorHandler";
|
||||
import { UserSaveData } from "../../data/User/UserSaveData";
|
||||
|
||||
async function executeUserSave(form: any) {
|
||||
|
||||
return await UserSaveData(form);
|
||||
|
||||
}
|
||||
|
||||
export const UserSaveService = withClientErrorHandler(executeUserSave)
|
||||
|
|
@ -8,8 +8,6 @@ import { toast } from 'sonner';
|
|||
export default function Response() {
|
||||
const { response, clearResponse } = useResponse();
|
||||
|
||||
console.log(response);
|
||||
|
||||
useEffect(() => {
|
||||
switch (Number(response?.status)) {
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
export enum SituacoesEnum {
|
||||
A = 'A',
|
||||
I = 'I',
|
||||
ATIVO = 'A',
|
||||
INATIVO = 'I',
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { useEffect, useState } from 'react';
|
|||
import { jwtDecode } from 'jwt-decode';
|
||||
import CookiesGet from '../../actions/cookies/CookiesGet';
|
||||
import GetSigla from '@/shared/actions/text/GetSigla';
|
||||
import GUsuarioAuthenticatedInterface from '@/shared/interfaces/GUsuarioAuthenticatedInterface';
|
||||
import GUsuarioAuthenticatedInterface from '@/shared/interfaces/UserAuthenticatedInterface';
|
||||
|
||||
interface JwtPayload {
|
||||
id: string;
|
||||
|
|
|
|||
4
src/shared/interfaces/AuthenticateUserInterface.ts
Normal file
4
src/shared/interfaces/AuthenticateUserInterface.ts
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
export interface AuthenticateUserInterface {
|
||||
email: string;
|
||||
password: string
|
||||
}
|
||||
|
|
@ -1,7 +0,0 @@
|
|||
export default interface GUsuarioAuthenticatedInterface {
|
||||
usuario_id?: number;
|
||||
login?: string;
|
||||
nome?: string;
|
||||
email?: string;
|
||||
sigla?: string;
|
||||
}
|
||||
7
src/shared/interfaces/UserAuthenticatedInterface.ts
Normal file
7
src/shared/interfaces/UserAuthenticatedInterface.ts
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
export default interface UserAuthenticatedInterface {
|
||||
user_id?: number;
|
||||
login?: string;
|
||||
nome?: string;
|
||||
email?: string;
|
||||
sigla?: string;
|
||||
}
|
||||
|
|
@ -21,6 +21,8 @@ export default class API {
|
|||
// Define os dados para envio
|
||||
const _data = data;
|
||||
|
||||
|
||||
|
||||
try {
|
||||
// Verifica se todos os dados estão corretos
|
||||
this.ApiSchema.url = this.config.api.url;
|
||||
|
|
@ -38,7 +40,6 @@ export default class API {
|
|||
const filteredBody = _data.body
|
||||
? Object.fromEntries(Object.entries(_data.body).filter(([_, v]) => v != null && v !== ''))
|
||||
: null;
|
||||
|
||||
// Realiza a requisição
|
||||
const response = await fetch(
|
||||
`${this.ApiSchema.url}${this.ApiSchema.prefix}${this.ApiSchema.endpoint}`,
|
||||
|
|
|
|||
32
src/withClientErrorHandler/withClientErrorHandler.ts
Normal file
32
src/withClientErrorHandler/withClientErrorHandler.ts
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
import withClientErrorHandlerInterface from "./withClientErrorHandlerInterface";
|
||||
|
||||
/**
|
||||
* Códigos de erro que começam com 6, são do front entd, na ordem do alfabeto o F de frontend é a sexta letra
|
||||
*/
|
||||
export function withClientErrorHandler<T extends (...args: any[]) => Promise<any>>(
|
||||
action: T
|
||||
) {
|
||||
return async (...args: Parameters<T>): Promise<withClientErrorHandlerInterface> => {
|
||||
|
||||
try {
|
||||
|
||||
// Executa a função definida
|
||||
const data = await action(...args);
|
||||
|
||||
// Retorna exatamente a mesma resposta retornada pela função
|
||||
return data;
|
||||
|
||||
} catch (error: any) {
|
||||
|
||||
// Retorna o erro de execuçãformatado
|
||||
return {
|
||||
status: 600,
|
||||
message: error?.message || "Erro interno do servidor",
|
||||
data: error
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
export default interface withClientErrorHandlerInterface<T = any> {
|
||||
|
||||
status: number;
|
||||
data?: T;
|
||||
message?: string;
|
||||
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue