From 391a2bec39d109592a52e79f2a2d1ff7cd3a7489 Mon Sep 17 00:00:00 2001 From: "Orace.A" Date: Thu, 27 Mar 2025 19:55:12 +0100 Subject: [PATCH] reactor --- src/app/admin/admins/page.tsx | 761 +++++++++++++------------- src/app/admin/home/page.tsx | 1 + src/components/floatingLabelInput.tsx | 2 +- src/components/form/form.tsx | 6 +- 4 files changed, 375 insertions(+), 395 deletions(-) diff --git a/src/app/admin/admins/page.tsx b/src/app/admin/admins/page.tsx index 2a54fa2..5bf52e1 100644 --- a/src/app/admin/admins/page.tsx +++ b/src/app/admin/admins/page.tsx @@ -1,438 +1,417 @@ -"use client" +"use client"; -import FloatingLabelInput from "#/components/floatingLabelInput" -import { Modal } from "#/components/modal" -import Table from "#/components/table/table" -import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query" -import { ColumnDef } from "@tanstack/react-table" -import axios from "axios" -import Image from "next/image" -import { useSession } from "next-auth/react" -import { DropdownMenu } from "radix-ui" -import { icons } from "#/assets/icons" -import { useState } from "react" -import Form from "#/components/form/form" -import { adminSchema } from "#/schema" -import { Admin } from "#/types" +import { useState } from "react"; +import Image from "next/image"; +import { useSession } from "next-auth/react"; +import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; +import { ColumnDef } from "@tanstack/react-table"; +import axios from "axios"; +import { DropdownMenu } from "radix-ui"; +import FloatingLabelInput from "#/components/floatingLabelInput"; +import { Modal } from "#/components/modal"; +import Table from "#/components/table/table"; +import Form from "#/components/form/form"; +import { icons } from "#/assets/icons"; +import { adminSchema } from "#/schema"; +import { Admin } from "#/types"; -export default function Admins (){ - const {data: session, status} = useSession() +export default function Admins() { + const { data: session, status } = useSession(); const [open, setOpen] = useState(false); const [openModal, setOpenModal] = useState(false); const [openDeleteModal, setOpenDeleteModal] = useState(false); const [openEditModal, setOpenEditModal] = useState(false); const [selectedAdminId, setSelectedAdminId] = useState(null); - const queryClient = useQueryClient() - const { data: users, refetch, isLoading} = useQuery({ - enabled: status === 'authenticated', + const queryClient = useQueryClient(); + + const { + data: users, + refetch, + isLoading, + } = useQuery({ + enabled: status === "authenticated", queryKey: ["users"], queryFn: async () => { - try { - const response = await axios.get( - 'https://private-docs-api.intside.co/users', { - headers: { - 'Authorization': `Bearer ${session?.user.access_token}` - } - } - ) - - if(response.data) { - return response.data.data as Admin[] - } - } catch (error) { - console.error(error) - } - } - }) - - const mutation = useMutation({ - mutationFn: async (data: { last_name: string; first_name: string; email: string }) => { - try { - - const result = await axios.post( - `https://private-docs-api.intside.co/users/`, - { - last_name: data.last_name, - first_name: data.first_name, - email: data.email, - user_type: "admin" - }, - { - headers: { - 'Authorization': `Bearer ${session?.user.access_token}` - } - }) - - if(result.status === 200 || result.status === 201) { - console.log('ajout réussie !') - setOpenModal(false) - } - } catch (error: any) { - if (error.message.includes("Network Error")) { - console.error("Problème de connexion au serveur"); - } - - console.error("Autre = ", error); - } - - - }, - onSuccess: () => { - queryClient.invalidateQueries({ queryKey: ["users"] }) - refetch() - }, - onError: (error: Error) => { - console.error(error.message) - }, - }) - - const mutationUpdate = useMutation({ - mutationFn: async (data: { id: string, last_name: string; first_name: string; email: string }) => { - try { - - const result = await axios.put( - `https://private-docs-api.intside.co/users/${data.id}/`, - { - last_name: data.last_name, - first_name: data.first_name, - email: data.email, - }, - { - headers: { - 'Authorization': `Bearer ${session?.user.access_token}` - } - }) - - if(result.status === 200 || result.status === 201) { - console.log('modification réussie !') - setOpenEditModal(false) - } - } catch (error: any) { - if (error.message.includes("Network Error")) { - console.error("Problème de connexion au serveur"); - } - - console.error("Autre = ", error); - } - - - }, - onSuccess: () => { - queryClient.invalidateQueries({ queryKey: ["users"] }) - refetch() - }, - onError: (error: Error) => { - console.error(error.message) - }, - }) - - const bulkDeleteMutation = useMutation({ - mutationFn: async (ids: string[]) => { try { - const deletePromises = ids.map(id => - axios.delete(`https://private-docs-api.intside.co/users/${id}/`, { - headers: { - 'Authorization': `Bearer ${session?.user.access_token}` - } - }) + const response = await axios.get( + "https://private-docs-api.intside.co/users", + { + headers: { Authorization: `Bearer ${session?.user.access_token}` }, + } ); - - await Promise.all(deletePromises); + return response.data.data as Admin[]; } catch (error) { console.error(error); + return []; + } + }, + }); + + + const createMutation = useMutation({ + mutationFn: async (data: { + last_name: string; + first_name: string; + email: string; + }) => { + try { + const response = await axios.post( + "https://private-docs-api.intside.co/users/", + { ...data, user_type: "admin" }, + { headers: { Authorization: `Bearer ${session?.user.access_token}` } } + ); + + if (response.status === 200 || response.status === 201) { + console.log("ajout réussie !"); + setOpenModal(false); + } + } catch (error) { + console.error("Erreur lors de la création", error); } }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ["users"] }); refetch(); - } + }, }); - const { mutate, isPending } = useMutation({ - mutationFn: async (id: string) => { + const updateMutation = useMutation({ + mutationFn: async (data: { + id: string; + last_name: string; + first_name: string; + email: string; + }) => { try { - const response = await axios.delete( - `https://private-docs-api.intside.co/users/${id}/`, { - headers: { - 'Authorization': `Bearer ${session?.user.access_token}` - } - } - ) + const response = await axios.put( + `https://private-docs-api.intside.co/users/${data.id}/`, + data, + { headers: { Authorization: `Bearer ${session?.user.access_token}` } } + ); - if(response.status === 200 || response.status === 201) { - console.log('Suppresion réussie !') - setOpenDeleteModal(false) + if (response.status === 200 || response.status === 201) { + console.log("modification réussie !"); + setOpenEditModal(false); } } catch (error) { - console.error(error) + console.error("Erreur lors de la mise à jour", error); } }, onSuccess: () => { - queryClient.invalidateQueries({ queryKey: ["users"] }) + queryClient.invalidateQueries({ queryKey: ["users"] }); + refetch(); + }, + }); - refetch() - } - }) + const deleteMutation = useMutation({ + mutationFn: async (id: string) => { + try { + const response = await axios.delete( + `https://private-docs-api.intside.co/users/${id}/`, + { + headers: { Authorization: `Bearer ${session?.user.access_token}` }, + } + ); + + if (response.status === 200 || response.status === 201) { + console.log("Suppresion réussie !"); + setOpenDeleteModal(false); + } + } catch (error) { + console.error("Erreur lors de la suppression", error); + } + }, + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ["users"] }); + refetch(); + }, + }); + + const bulkDeleteMutation = useMutation({ + mutationFn: async (ids: string[]) => { + try { + const deletePromises = ids.map((id) => + axios.delete(`https://private-docs-api.intside.co/users/${id}/`, { + headers: { Authorization: `Bearer ${session?.user.access_token}` }, + }) + ); + await Promise.all(deletePromises); + } catch (error) { + console.error("Erreur lors de la suppression groupée", error); + } + }, + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ["users"] }); + refetch(); + }, + }); const columns: ColumnDef[] = [ { header: "Administrateurs", cell: ({ row }) => { - const value = String(row.original.first_name) + " " + String(row.original.last_name) - const initials = String(row.original.first_name[0]) + String(row.original.last_name[0]) - return( + const fullName = `${row.original.first_name} ${row.original.last_name}`; + const initials = `${row.original.first_name[0]}${row.original.last_name[0]}`; + return (
{initials}
-

{value}

+

{fullName}

- ) - } + ); + }, }, { accessorKey: "email", - header: "Adresse e-mail" + header: "Adresse e-mail", }, - // { - // accessorKey: "status", - // header: "Statut", - // cell: ({ cell }) => { - // const status = String(cell.getValue()) - // return ( - //

- // { - // status === "active" ? "Actif" : - // status === "inactive" ? "Inactif" : - // status === "pending" ? "En attente" : - // status === "blocked" ? "Bloquée" : - // "" - // } - //

- // ) - // } - // }, { - id: "delete", - cell: ({ cell }) => { - const admin = cell.row.original - return ( -
{ mutate(id) }} - > - - { - if (!isOpen) { - setSelectedAdminId(null); - setOpenEditModal(false); - } - }} - trigger={ -
{ + id: "actions", + cell: ({ row }) => { + const admin = row.original; + return ( +
+ {/* Modal d'édition */} + { + if (!isOpen) { + setSelectedAdminId(null); + setOpenEditModal(false); + } + }} + trigger={ +
{ setSelectedAdminId(admin.id); - setOpenEditModal(true) - }}> - -
- } - title={ -

Modifier un admin

- } - content={ - <> -
setOpenModal(false)} type="submit" className="btn-auth">{isLoading ? "Chargement..." : "Modifier"}} - /> - } - - /> - - { - if (!isOpen) { - setSelectedAdminId(null); - setOpenDeleteModal(false); - } - }} - trigger={ -
{ - setSelectedAdminId(admin.id); - setOpenDeleteModal(true) - }}> - -
- } - title={ -

Supprimer un admin

- } - content={ -
-

Voulez-vous vraiment supprimer cet admin ?

- -
- - -
-
- } - /> -
- ) - } - } - ] - - return ( - <> - { - const ids = table.getRowModel().rows.filter((row) => row.getIsSelected()).map(row => row.original.id ) - if(bulkDeleteMutation.isSuccess) { - table.toggleAllPageRowsSelected(false) - } - return ( - <> -
-
- table.toggleAllPageRowsSelected(e.target.checked)} - type="checkbox" name="" id="" /> - - - -

- Sélectionner une action -

-
- - - - bulkDeleteMutation.mutate(ids)} className="p-2 text-[14px] cursor-pointer hover:bg-blue-100 hover:border-blue-100 hover:text-blue-500 hover:rounded-md outline-none"> - Supprimer - - - -
-
- -
- setOpenModal(true)} className="cursor-pointer p-3 bg-blue-600 text-white rounded-full"> - Ajouter un admin -
} - content={ - <> - {isLoading ? "Chargement..." : "Créer le compte"}} - /> - - } - - /> - - table.setGlobalFilter(value)} - button={ - - } + setOpenEditModal(true); + }} + > +
- - - ) - }} - /> - - ) -} \ No newline at end of file + } + title="Modifier un admin" + content={ + + Modifier + + } + /> + } + /> + + {/* Modal de suppression */} + { + if (!isOpen) { + setSelectedAdminId(null); + setOpenDeleteModal(false); + } + }} + trigger={ +
{ + setSelectedAdminId(admin.id); + setOpenDeleteModal(true); + }} + > + +
+ } + title="Supprimer un admin" + content={ +
+

Voulez-vous vraiment supprimer cet admin ?

+
+ + +
+
+ } + /> + + ); + }, + }, + ]; + + return ( +
{ + const selectedIds = table + .getRowModel() + .rows.filter((row) => row.getIsSelected()) + .map((row) => row.original.id); + + return ( +
+
+ + table.toggleAllPageRowsSelected(e.target.checked) + } + /> + + + +

+ Sélectionner une action +

+
+ + + + bulkDeleteMutation.mutate(selectedIds)} + className="p-2 text-[14px] cursor-pointer hover:bg-blue-100 hover:text-blue-500 rounded-md" + > + Supprimer + + + +
+
+ +
+ {/* Modal d'ajout */} + { + if (!isOpen) { + setOpen(false); + } + }} + trigger={ +
setOpenModal(true)} + className="cursor-pointer p-3 bg-blue-600 text-white rounded-full" + > + Ajouter un admin +
+ } + content={ + + Créer le compte + + } + /> + } + /> + + table.setGlobalFilter(value)} + button={ + + } + /> +
+
+ ); + }} + /> + ); +} diff --git a/src/app/admin/home/page.tsx b/src/app/admin/home/page.tsx index 552aff0..bc69bc2 100644 --- a/src/app/admin/home/page.tsx +++ b/src/app/admin/home/page.tsx @@ -55,6 +55,7 @@ export default function HomePage () { if(response.status === 200 || response.status === 201) { console.log('Suppresion réussie !') + setOpen(false) } } catch (error) { console.error(error) diff --git a/src/components/floatingLabelInput.tsx b/src/components/floatingLabelInput.tsx index 7cc4593..0ce83cb 100644 --- a/src/components/floatingLabelInput.tsx +++ b/src/components/floatingLabelInput.tsx @@ -14,7 +14,7 @@ export default function FloatingLabelInput({ showPasswordToggle = false, name, defaultValue, - onChange + onChange, }: FloatingLabelInputProps) { const [showPassword, setShowPassword] = useState(false); diff --git a/src/components/form/form.tsx b/src/components/form/form.tsx index 6a44dfe..67552a2 100644 --- a/src/components/form/form.tsx +++ b/src/components/form/form.tsx @@ -42,12 +42,12 @@ export default function Form({ } return ( - +

{title}

-
+
{ fields.map((item, index) => ( @@ -67,8 +67,8 @@ export default function Form({
)) } - {child}
+ {child} )