Compare commits

...

11 Commits

18 changed files with 1283 additions and 223 deletions

View File

@ -10,6 +10,7 @@
}, },
"dependencies": { "dependencies": {
"@radix-ui/react-dialog": "^1.1.6", "@radix-ui/react-dialog": "^1.1.6",
"@radix-ui/themes": "^3.2.1",
"@tanstack/react-query": "^5.69.0", "@tanstack/react-query": "^5.69.0",
"@tanstack/react-table": "^8.21.2", "@tanstack/react-table": "^8.21.2",
"axios": "^1.8.4", "axios": "^1.8.4",
@ -24,6 +25,7 @@
"react-dom": "^19.0.0", "react-dom": "^19.0.0",
"react-hook-form": "^7.54.2", "react-hook-form": "^7.54.2",
"sass": "^1.86.0", "sass": "^1.86.0",
"sonner": "^2.0.2",
"zod": "^3.24.2" "zod": "^3.24.2"
}, },
"devDependencies": { "devDependencies": {

52
pnpm-lock.yaml generated
View File

@ -11,6 +11,9 @@ importers:
'@radix-ui/react-dialog': '@radix-ui/react-dialog':
specifier: ^1.1.6 specifier: ^1.1.6
version: 1.1.6(@types/react-dom@19.0.4(@types/react@19.0.12))(@types/react@19.0.12)(react-dom@19.0.0(react@19.0.0))(react@19.0.0) version: 1.1.6(@types/react-dom@19.0.4(@types/react@19.0.12))(@types/react@19.0.12)(react-dom@19.0.0(react@19.0.0))(react@19.0.0)
'@radix-ui/themes':
specifier: ^3.2.1
version: 3.2.1(@types/react-dom@19.0.4(@types/react@19.0.12))(@types/react@19.0.12)(react-dom@19.0.0(react@19.0.0))(react@19.0.0)
'@tanstack/react-query': '@tanstack/react-query':
specifier: ^5.69.0 specifier: ^5.69.0
version: 5.69.0(react@19.0.0) version: 5.69.0(react@19.0.0)
@ -53,6 +56,9 @@ importers:
sass: sass:
specifier: ^1.86.0 specifier: ^1.86.0
version: 1.86.0 version: 1.86.0
sonner:
specifier: ^2.0.2
version: 2.0.2(react-dom@19.0.0(react@19.0.0))(react@19.0.0)
zod: zod:
specifier: ^3.24.2 specifier: ^3.24.2
version: 3.24.2 version: 3.24.2
@ -1012,6 +1018,9 @@ packages:
resolution: {integrity: sha512-dfUnCxiN9H4ap84DvD2ubjw+3vUNpstxa0TneY/Paat8a3R4uQZDLSvWjmznAY/DoahqTHl9V46HF/Zs3F29pg==} resolution: {integrity: sha512-dfUnCxiN9H4ap84DvD2ubjw+3vUNpstxa0TneY/Paat8a3R4uQZDLSvWjmznAY/DoahqTHl9V46HF/Zs3F29pg==}
engines: {node: '>= 10.0.0'} engines: {node: '>= 10.0.0'}
'@radix-ui/colors@3.0.0':
resolution: {integrity: sha512-FUOsGBkHrYJwCSEtWRCIfQbZG7q1e6DgxCIOe1SUQzDe/7rXXeA47s8yCn6fuTNQAj1Zq4oTFi9Yjp3wzElcxg==}
'@radix-ui/number@1.1.0': '@radix-ui/number@1.1.0':
resolution: {integrity: sha512-V3gRzhVNU1ldS5XhAPTom1fOIo4ccrjjJgmE+LI2h/WaFpHmx0MQApT+KZHnx8abG6Avtfcz4WoEciMnpFT3HQ==} resolution: {integrity: sha512-V3gRzhVNU1ldS5XhAPTom1fOIo4ccrjjJgmE+LI2h/WaFpHmx0MQApT+KZHnx8abG6Avtfcz4WoEciMnpFT3HQ==}
@ -1658,6 +1667,19 @@ packages:
'@radix-ui/rect@1.1.0': '@radix-ui/rect@1.1.0':
resolution: {integrity: sha512-A9+lCBZoaMJlVKcRBz2YByCG+Cp2t6nAnMnNba+XiWxnj6r4JUFqfsgwocMBZU9LPtdxC6wB56ySYpc7LQIoJg==} resolution: {integrity: sha512-A9+lCBZoaMJlVKcRBz2YByCG+Cp2t6nAnMnNba+XiWxnj6r4JUFqfsgwocMBZU9LPtdxC6wB56ySYpc7LQIoJg==}
'@radix-ui/themes@3.2.1':
resolution: {integrity: sha512-WJL2YKAGItkunwm3O4cLTFKCGJTfAfF6Hmq7f5bCo1ggqC9qJQ/wfg/25AAN72aoEM1yqXZQ+pslsw48AFR0Xg==}
peerDependencies:
'@types/react': '*'
'@types/react-dom': '*'
react: 16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
react-dom: 16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
peerDependenciesMeta:
'@types/react':
optional: true
'@types/react-dom':
optional: true
'@rtsao/scc@1.1.0': '@rtsao/scc@1.1.0':
resolution: {integrity: sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==} resolution: {integrity: sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==}
@ -2128,6 +2150,9 @@ packages:
resolution: {integrity: sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==} resolution: {integrity: sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==}
engines: {node: '>= 14.16.0'} engines: {node: '>= 14.16.0'}
classnames@2.5.1:
resolution: {integrity: sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==}
client-only@0.0.1: client-only@0.0.1:
resolution: {integrity: sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==} resolution: {integrity: sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==}
@ -3446,6 +3471,12 @@ packages:
snake-case@3.0.4: snake-case@3.0.4:
resolution: {integrity: sha512-LAOh4z89bGQvl9pFfNF8V146i7o7/CqFPbqzYgP+yYzDIDeS9HaNFtXABamRW+AQzEVODcvE79ljJ+8a9YSdMg==} resolution: {integrity: sha512-LAOh4z89bGQvl9pFfNF8V146i7o7/CqFPbqzYgP+yYzDIDeS9HaNFtXABamRW+AQzEVODcvE79ljJ+8a9YSdMg==}
sonner@2.0.2:
resolution: {integrity: sha512-xOeXErZ4blqQd11ZnlDmoRmg+ctUJBkTU8H+HVh9rnWi9Ke28xiL39r4iCTeDX31ODTe/s1MaiaY333dUzLCtA==}
peerDependencies:
react: ^18.0.0 || ^19.0.0 || ^19.0.0-rc
react-dom: ^18.0.0 || ^19.0.0 || ^19.0.0-rc
source-map-js@1.2.1: source-map-js@1.2.1:
resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
engines: {node: '>=0.10.0'} engines: {node: '>=0.10.0'}
@ -4685,6 +4716,8 @@ snapshots:
'@parcel/watcher-win32-x64': 2.5.1 '@parcel/watcher-win32-x64': 2.5.1
optional: true optional: true
'@radix-ui/colors@3.0.0': {}
'@radix-ui/number@1.1.0': {} '@radix-ui/number@1.1.0': {}
'@radix-ui/primitive@1.1.1': {} '@radix-ui/primitive@1.1.1': {}
@ -5380,6 +5413,18 @@ snapshots:
'@radix-ui/rect@1.1.0': {} '@radix-ui/rect@1.1.0': {}
'@radix-ui/themes@3.2.1(@types/react-dom@19.0.4(@types/react@19.0.12))(@types/react@19.0.12)(react-dom@19.0.0(react@19.0.0))(react@19.0.0)':
dependencies:
'@radix-ui/colors': 3.0.0
classnames: 2.5.1
radix-ui: 1.1.3(@types/react-dom@19.0.4(@types/react@19.0.12))(@types/react@19.0.12)(react-dom@19.0.0(react@19.0.0))(react@19.0.0)
react: 19.0.0
react-dom: 19.0.0(react@19.0.0)
react-remove-scroll-bar: 2.3.8(@types/react@19.0.12)(react@19.0.0)
optionalDependencies:
'@types/react': 19.0.12
'@types/react-dom': 19.0.4(@types/react@19.0.12)
'@rtsao/scc@1.1.0': {} '@rtsao/scc@1.1.0': {}
'@rushstack/eslint-patch@1.11.0': {} '@rushstack/eslint-patch@1.11.0': {}
@ -5893,6 +5938,8 @@ snapshots:
dependencies: dependencies:
readdirp: 4.1.2 readdirp: 4.1.2
classnames@2.5.1: {}
client-only@0.0.1: {} client-only@0.0.1: {}
clsx@2.1.1: {} clsx@2.1.1: {}
@ -7354,6 +7401,11 @@ snapshots:
dot-case: 3.0.4 dot-case: 3.0.4
tslib: 2.8.1 tslib: 2.8.1
sonner@2.0.2(react-dom@19.0.0(react@19.0.0))(react@19.0.0):
dependencies:
react: 19.0.0
react-dom: 19.0.0(react@19.0.0)
source-map-js@1.2.1: {} source-map-js@1.2.1: {}
stable-hash@0.0.5: {} stable-hash@0.0.5: {}

View File

@ -1,13 +1,14 @@
"use client"; "use client";
import Form from "#/components/form/form" import Form from "#/components/form/form"
import { loginSchema } from "#/schema/loginSchema" import { loginSchema } from "#/schema"
import { useMutation } from "@tanstack/react-query" import { useMutation } from "@tanstack/react-query"
import { signIn } from "next-auth/react" import { signIn } from "next-auth/react"
import { useRouter } from "next/navigation"; import { useRouter, useSearchParams } from "next/navigation";
export default function LoginPage() { export default function LoginPage() {
const router = useRouter() const router = useRouter()
const params = useSearchParams().get("redirect_to");
const mutation = useMutation({ const mutation = useMutation({
mutationKey: ['login'], mutationKey: ['login'],
@ -25,19 +26,22 @@ export default function LoginPage() {
: result.error; : result.error;
console.error(errorMessage) console.error(errorMessage)
throw new Error(result.error) throw new Error(result.error)
} else {
if (params) {
router.push(params);
} else {
router.push('/admin/home')
}
} }
return result return result
} catch (error: any) { } catch (error: unknown) {
if (error.message.includes("Network Error")) { if (error instanceof Error && error.message.includes("Network Error")) {
console.error("Problème de connexion au serveur"); console.error("Problème de connexion au serveur");
} }
console.error("Autre = ", error); console.error("Autre = ", error);
} }
},
onSuccess: () => {
router.push('/admin/home')
}, },
onError: (error: Error) => { onError: (error: Error) => {
console.error(error.message) console.error(error.message)
@ -48,7 +52,7 @@ export default function LoginPage() {
<div> <div>
<Form <Form
title="Connexion" title="Connexion"
className="bg-white p-10 shadow-2xl w-3/4 lg:w-lg" formClassName="bg-white p-10 shadow-2xl w-3/4 lg:w-lg"
fields={[ fields={[
{ {
label: "Email", label: "Email",
@ -66,7 +70,7 @@ export default function LoginPage() {
]} ]}
submit={mutation.mutate} submit={mutation.mutate}
schema={loginSchema} schema={loginSchema}
child={<button type="submit" className="btn-auth">Connexion</button>} child={<button disabled={mutation.isPending} type="submit" className={`${mutation.isPending ? "btn-auth-loading" : "btn-auth"} mt-4`}>{mutation.isPending ? "Chargement..." : "Connexion"}</button>}
/> />
</div> </div>
) )

View File

@ -1,8 +1,419 @@
"use client";
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();
const [openModal, setOpenModal] = useState(false);
const [openDeleteModal, setOpenDeleteModal] = useState(false);
const [openEditModal, setOpenEditModal] = useState(false);
const [selectedAdminId, setSelectedAdminId] = useState<string | null>(null);
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}` },
}
);
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 updateMutation = useMutation({
mutationFn: async (data: {
id: string;
last_name: string;
first_name: string;
email: string;
}) => {
try {
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("modification réussie !");
setOpenEditModal(false);
}
} catch (error) {
console.error("Erreur lors de la mise à jour", error);
}
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["users"] });
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<Admin>[] = [
{
header: "Administrateurs",
cell: ({ row }) => {
const fullName = `${row.original.first_name} ${row.original.last_name}`;
const initials = `${row.original.first_name[0]}${row.original.last_name[0]}`;
return (
<div className="flex space-x-2 items-center">
<div className="flex items-center justify-center bg-[#DCDCFE] text-[#246BFD] w-10 h-10 rounded-full">
{initials}
</div>
<p>{fullName}</p>
</div>
);
},
},
{
accessorKey: "email",
header: "Adresse e-mail",
},
{
id: "actions",
cell: ({ row }) => {
const admin = row.original;
return (
<div className="flex justify-end p-2 space-x-2">
{/* Modal d'édition */}
<Modal
open={openEditModal && selectedAdminId === admin.id}
onOpenChange={(isOpen) => {
if (!isOpen) {
setSelectedAdminId(null);
setOpenEditModal(false);
}
}}
trigger={
<div
onClick={() => {
setSelectedAdminId(admin.id);
setOpenEditModal(true);
}}
>
<Image
alt="Éditer"
width={24}
height={24}
src={icons.editIcon}
className="cursor-pointer responsive-icon"
/>
</div>
}
title="Modifier un admin"
content={
<Form
fields={[
{ name: "id", type: "hidden", defaultValue: admin.id },
{
name: "last_name",
label: "Nom",
type: "text",
placeholder: "Entrer le nom de l'admin",
defaultValue: admin.last_name,
},
{
name: "first_name",
label: "Prénom",
type: "text",
placeholder: "Entrer le prénom de l'admin",
defaultValue: admin.first_name,
},
{
name: "email",
label: "Adresse e-mail",
type: "text",
placeholder: "Entrer l'email de l'admin",
defaultValue: admin.email,
},
]}
submit={updateMutation.mutate}
schema={adminSchema}
child={
<button
type="submit"
disabled={updateMutation.isPending}
className={`${updateMutation.isPending ? "btn-auth-loading" : "btn-auth"} mt-4 cursor-pointer`}
>
{updateMutation.isPending ? "En cours..." : "Modifier"}
</button>
}
/>
}
/>
{/* Modal de suppression */}
<Modal
open={openDeleteModal && selectedAdminId === admin.id}
onOpenChange={(isOpen) => {
if (!isOpen) {
setSelectedAdminId(null);
setOpenDeleteModal(false);
}
}}
trigger={
<div
onClick={() => {
setSelectedAdminId(admin.id);
setOpenDeleteModal(true);
}}
>
<Image
alt="Supprimer"
src={icons.trash}
className="cursor-pointer responsive-icon"
/>
</div>
}
title="Supprimer un admin"
content={
<div>
<p className="text-center">Voulez-vous vraiment supprimer cet admin ?</p>
<div className="grid grid-cols-2 gap-3 mt-3">
<button
className="bg-blue-100 text-blue-600 py-2 px-4 rounded-full cursor-pointer"
onClick={() => {
setOpenDeleteModal(false);
}}
>
Annuler
</button>
<button
className="bg-red-500 text-white py-2 px-4 rounded-full hover:bg-red-600 cursor-pointer"
onClick={() => {
deleteMutation.mutate(admin.id);
}}
>
Supprimer
</button>
</div>
</div>
}
/>
</div>
);
},
},
];
export default function Admins (){
return ( return (
<> <Table
</> columns={columns}
) data={users || []}
} pageSize={5}
isDataLoading={isLoading}
header={(table) => {
const selectedIds = table
.getRowModel()
.rows.filter((row) => row.getIsSelected())
.map((row) => row.original.id);
return (
<div className="grid grid-cols-1 lg:grid-cols-2 w-full space-y-3">
<div className="flex items-center space-x-3">
<input
type="checkbox"
checked={
table.getIsAllPageRowsSelected() ||
(table.getIsSomePageRowsSelected() && undefined)
}
onChange={(e) =>
table.toggleAllPageRowsSelected(e.target.checked)
}
/>
<DropdownMenu.Root>
<DropdownMenu.Trigger asChild>
<p className="cursor-pointer rounded-full bg-gray-300 text-gray-500 p-2">
Sélectionner une action
</p>
</DropdownMenu.Trigger>
<DropdownMenu.Portal>
<DropdownMenu.Content
className="min-w-[150px] shadow-sm bg-white rounded-md p-1"
sideOffset={5}
>
<DropdownMenu.Item
onClick={() => bulkDeleteMutation.mutate(selectedIds)}
className="p-2 text-[14px] cursor-pointer hover:bg-blue-100 hover:text-blue-500 rounded-md"
>
Supprimer
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Portal>
</DropdownMenu.Root>
</div>
<div className="flex justify-between lg:justify-end space-x-3">
{/* Modal d'ajout */}
<Modal
title="Ajouter un admin"
open={openModal}
onOpenChange={(isOpen) => {
if (!isOpen) {
setOpenModal(false);
}
}}
trigger={
<div
onClick={() => setOpenModal(true)}
className="cursor-pointer p-3 bg-blue-600 text-white rounded-full"
>
Ajouter un admin
</div>
}
content={
<Form
fields={[
{
name: "last_name",
label: "Nom",
type: "text",
placeholder: "Entrer le nom de l'admin",
},
{
name: "first_name",
label: "Prénom",
type: "text",
placeholder: "Entrer le prénom de l'admin",
},
{
name: "email",
label: "Adresse e-mail",
type: "text",
placeholder: "Entrer l'email de l'admin",
},
]}
submit={createMutation.mutate}
schema={adminSchema}
child={
<button
type="submit"
disabled={createMutation.isPending}
className={`${createMutation.isPending ? "btn-auth-loading" : "btn-auth"} mt-4 cursor-pointer`}
>
{createMutation.isPending ? "Création de l'admin..." : "Créer le compte"}
</button>
}
/>
}
/>
<FloatingLabelInput
name="search"
placeholder="Effectuer une recherche"
type="search"
onChange={(value) => table.setGlobalFilter(value)}
button={
<Image
alt="Filtrer"
src={icons.filterIcon}
className="cursor-pointer"
/>
}
/>
</div>
</div>
);
}}
/>
);
}

View File

@ -17,6 +17,7 @@ export default function HomePage () {
const {data: session, status} = useSession() const {data: session, status} = useSession()
const queryClient = useQueryClient() const queryClient = useQueryClient()
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [selectedId, setSelectedId] = useState<string | null>(null);
console.log("Session = ", session) console.log("Session = ", session)
@ -42,7 +43,7 @@ export default function HomePage () {
} }
}) })
const { mutate, isPending } = useMutation({ const { mutate } = useMutation({
mutationFn: async (id: string) => { mutationFn: async (id: string) => {
try { try {
const response = await axios.delete( const response = await axios.delete(
@ -55,6 +56,7 @@ export default function HomePage () {
if(response.status === 200 || response.status === 201) { if(response.status === 200 || response.status === 201) {
console.log('Suppresion réussie !') console.log('Suppresion réussie !')
setOpen(false)
} }
} catch (error) { } catch (error) {
console.error(error) console.error(error)
@ -74,16 +76,22 @@ export default function HomePage () {
accessorKey: "name", accessorKey: "name",
header: "Organisations", header: "Organisations",
}, },
// { {
// accessorKey: "Utilisateurs", accessorKey: "total_users",
// header: "Utilisateurs", header: "Utilisateurs",
// }, },
{ {
header: "Administrateurs", header: "Administrateurs",
cell: ({ row }) => { cell: ({ row }) => {
const value = String(row.original.owner.first_name) + " " + String(row.original.owner.last_name) const value = String(row.original.owner.first_name) + " " + String(row.original.owner.last_name)
const initials = String(row.original.owner.first_name[0]) + String(row.original.owner.last_name[0])
return( return(
<p>{value}</p> <div className="flex space-x-2 items-center">
<div className="flex items-center justify-center bg-[#DCDCFE] text-[#246BFD] w-10 h-10 rounded-full">
{initials}
</div>
<p>{value}</p>
</div>
) )
} }
}, },
@ -121,50 +129,67 @@ export default function HomePage () {
}, },
{ {
id: "delete", id: "delete",
cell: ({ cell }) => { cell: ({ row }) => {
const id = String(cell.row.original.id) const id = String(row.original.id);
return ( return (
<div className="relative p-2 cursor-pointer" <div className="relative p-2 cursor-pointer">
// onClick={() => { mutate(id) }} <Modal
> open={selectedId === id}
<Modal onOpenChange={(isOpen) => {
open={open} if (!isOpen) {
trigger={ setSelectedId(null);
<div onClick={() => setOpen(true)}>
<Image alt="" src={icons.trash} className="absolute right-2 top-[-50%] transform translate-middle-y hover:text-blue-500" />
</div>
} }
title={ }}
<p className="font-bold text-3xl">Supprimer une organisation</p> trigger={
} <div
content={ onClick={() => {
<div> setSelectedId(id);
<p>Voulez-vous vraiment supprimer cette organisation ?</p> }}
>
<Image
alt=""
src={icons.trash}
className="cursor-pointer responsive-icon"
/>
</div>
}
title={
<p className="font-bold text-3xl">
Supprimer cette organisation
</p>
}
content={
<div>
<p className="text-center">
Voulez-vous vraiment supprimer cette organisation ?
</p>
<div className="grid grid-cols-2 gap-3 mt-3"> <div className="grid grid-cols-2 gap-3 mt-3">
<button <button
className="bg-blue-100 text-blue-600 py-2 px-4 text-lg rounded-full text-center hover:bg-blue-200" className="bg-blue-100 text-blue-600 py-2 px-4 text-lg rounded-full text-center hover:bg-blue-200"
onClick={() => { setOpen(false) }} onClick={() => {
> setSelectedId(null);
Annuler }}
</button> >
<button Annuler
className="bg-red-500 text-white py-2 px-4 text-lg rounded-full text-center hover:bg-red-600" </button>
onClick={() => { <button
mutate(id) className="bg-red-500 text-white py-2 px-4 text-lg rounded-full text-center hover:bg-red-600"
setOpen(false) onClick={() => {
}} mutate(id);
> setSelectedId(null);
Supprimer }}
</button> >
</div> Supprimer
</button>
</div> </div>
} </div>
/> }
</div> />
) </div>
} );
} },
},
] ]
return( return(
@ -175,6 +200,7 @@ export default function HomePage () {
<Table <Table
columns={columns} columns={columns}
isDataLoading={isLoading}
data={companies || []} data={companies || []}
pageSize={5} pageSize={5}
/> />

View File

@ -1,9 +1,24 @@
import { ReactNode } from "react"; "use client"
import { ReactNode, useEffect } from "react";
import "../../assets/css/admin.css" import "../../assets/css/admin.css"
import Sidebar from "../../components/admin/sidebar"; import Sidebar from "../../components/admin/sidebar";
import Header from "../../components/admin/adminHeader"; import Header from "../../components/admin/adminHeader";
import { signOutFunc } from "#/lib/function";
import { usePathname } from "next/navigation";
import { useSession } from "next-auth/react";
export default function Dashboard({ children }: { children: ReactNode }) { export default function Dashboard({ children }: { children: ReactNode }) {
const { status, data } = useSession();
const path = usePathname();
useEffect(() => {
if (status !== "loading") {
if (status === "unauthenticated" || (data && !data.user.access_token)) {
signOutFunc();
}
}
}, [data, status, path]);
return ( return (

View File

@ -1,10 +1,414 @@
"use client";
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 { companySchema } from "#/schema";
import { Admin, Company } from "#/types";
import Link from "next/link"; import Link from "next/link";
export default function Organizations() {
const { data: session, status } = useSession();
const [openModal, setOpenModal] = useState(false);
const [openDeleteModal, setOpenDeleteModal] = useState(false);
const [selectedAdminId, setSelectedAdminId] = useState<string | null>(null);
const queryClient = useQueryClient();
const {
data: companies,
refetch,
isLoading,
} = useQuery({
enabled: status === "authenticated",
queryKey: ["companies"],
queryFn: async () => {
try {
const response = await axios.get(
"https://private-docs-api.intside.co/companies",
{
headers: {
Authorization: `Bearer ${session?.user.access_token}`,
},
}
);
if (response.data) {
return response.data.data as Company[];
}
} catch (error) {
console.error(error);
}
},
});
const {
data: users,
} = useQuery({
enabled: status === "authenticated",
queryKey: ["organizations"],
queryFn: async () => {
try {
const response = await axios.get(
"https://private-docs-api.intside.co/users",
{
headers: { Authorization: `Bearer ${session?.user.access_token}` },
}
);
return response.data.data.map((user: Admin) => ({
id: user.id,
name: `${user.first_name} ${user.last_name}`,
}));
} catch (error) {
console.error(error);
return [];
}
},
});
const createMutation = useMutation({
mutationFn: async (data: {
name: string;
description: string;
status: string;
is_premium: string;
owner: string;
}) => {
try {
const response = await axios.post(
"https://private-docs-api.intside.co/companies/",
data,
{ 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: ["organizations"] });
refetch();
},
});
const deleteMutation = useMutation({
mutationFn: async (id: string) => {
try {
const response = await axios.delete(
`https://private-docs-api.intside.co/companies/${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: ["organizations"] });
refetch();
},
});
const bulkDeleteMutation = useMutation({
mutationFn: async (ids: string[]) => {
try {
const deletePromises = ids.map((id) =>
axios.delete(`https://private-docs-api.intside.co/companies/${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: ["organizations"] });
refetch();
},
});
const columns: ColumnDef<Company>[] = [
{
accessorKey: "name",
header: "Organisations",
cell: ({ row }) => {
const company = row.original;
return (
<Link href={`/admin/organizations/${company.id}`}>
<p className="text-blue-600 hover:underline">{company.name}</p>
</Link>
);
},
},
{
accessorKey: "total_users",
header: "Utilisateurs",
},
{
header: "Administrateurs",
cell: ({ row }) => {
const value = String(row.original.owner.first_name) + " " + String(row.original.owner.last_name)
const initials = String(row.original.owner.first_name[0]) + String(row.original.owner.last_name[0])
return(
<div className="flex space-x-2 items-center">
<div className="flex items-center justify-center bg-[#DCDCFE] text-[#246BFD] w-10 h-10 rounded-full">
{initials}
</div>
<p>{value}</p>
</div>
)
}
},
{
accessorKey: "owner.email",
header: "Adresse e-mail"
},
{
accessorKey: "status",
header: "Statut",
cell: ({ cell }) => {
const status = String(cell.getValue())
return (
<p
className={`rounded-full px-2 py-1 font-medium text-sm w-20 h-6 text-center
${
status === "active" ? "bg-[#ECF9E8] text-[#49C91E]" :
status === "inactive" ? "bg-[#E7EBF3] text-[#9FA8BC]" :
status === "pending" ? "bg-[#EAF7FC] text-[#30B2EA]" :
status === "blocked" ? "bg-[#FDEBE8] text-[#F33F19]" :
""
}
`}
>
{
status === "active" ? "Actif" :
status === "inactive" ? "Inactif" :
status === "pending" ? "En attente" :
status === "blocked" ? "Bloquée" :
""
}
</p>
)
}
},
{
id: "delete",
cell: ({ row }) => {
const company = row.original;
return (
<div className="flex justify-end p-2 space-x-2"
// onClick={() => { mutate(id) }}
>
{/* Modal de suppression */}
<Modal
open={openDeleteModal && selectedAdminId === company.id}
onOpenChange={(isOpen) => {
if (!isOpen) {
setSelectedAdminId(null);
setOpenDeleteModal(false);
}
}}
trigger={
<div
onClick={() => {
setSelectedAdminId(company.id);
setOpenDeleteModal(true);
}}
>
<Image
alt="Supprimer"
src={icons.trash}
className="cursor-pointer responsive-icon"
/>
</div>
}
title="Supprimer une organisation"
content={
<div>
<p className="text-center">Voulez-vous vraiment supprimer cette organisation ?</p>
<div className="grid grid-cols-2 gap-3 mt-3">
<button
className="bg-blue-100 text-blue-600 py-2 px-4 rounded-full cursor-pointer"
onClick={() => {
setOpenDeleteModal(false);
}}
>
Annuler
</button>
<button
className="bg-red-500 text-white py-2 px-4 rounded-full hover:bg-red-600 cursor-pointer"
onClick={() => {
deleteMutation.mutate(company.id);
}}
>
Supprimer
</button>
</div>
</div>
}
/>
</div>
)
}
}
]
export default function Organizations (){
return ( return (
<> <Table
<Link href="/admin/organizations/971ff270-6253-4424-b100-21b9ebf0ec7f">Organization Profile</Link> columns={columns}
</> data={companies || []}
) pageSize={5}
} isDataLoading={isLoading}
header={(table) => {
const selectedIds = table
.getRowModel()
.rows.filter((row) => row.getIsSelected())
.map((row) => row.original.id);
return (
<div className="grid grid-cols-1 lg:grid-cols-2 w-full space-y-3">
<div className="flex items-center space-x-3">
<input
type="checkbox"
checked={
table.getIsAllPageRowsSelected() ||
(table.getIsSomePageRowsSelected() && undefined)
}
onChange={(e) =>
table.toggleAllPageRowsSelected(e.target.checked)
}
/>
<DropdownMenu.Root>
<DropdownMenu.Trigger asChild>
<p className="cursor-pointer rounded-full bg-gray-300 text-gray-500 p-2">
Sélectionner une action
</p>
</DropdownMenu.Trigger>
<DropdownMenu.Portal>
<DropdownMenu.Content
className="min-w-[150px] shadow-sm bg-white rounded-md p-1"
sideOffset={5}
>
<DropdownMenu.Item
onClick={() => bulkDeleteMutation.mutate(selectedIds)}
className="p-2 text-[14px] cursor-pointer hover:bg-blue-100 hover:text-blue-500 rounded-md"
>
Supprimer
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Portal>
</DropdownMenu.Root>
</div>
<div className="flex justify-between lg:justify-end space-x-3">
{/* Modal d'ajout */}
<Modal
title="Ajouter une organisation"
open={openModal}
onOpenChange={(isOpen) => {
if (!isOpen) {
setOpenModal(false);
}
}}
trigger={
<div
onClick={() => setOpenModal(true)}
className="cursor-pointer p-3 bg-blue-600 text-white rounded-full"
>
Ajouter une organisation
</div>
}
content={
<Form
fields={[
{
name: "name",
label: "Nom de l'organisation",
type: "text",
placeholder: "Entrer le nom de l'organisation",
},
{
name: "description",
label: "Description",
type: "textarea",
placeholder: "Entrer la description de l'organisation",
},
{
name: "status",
label: "Statut",
type: "select",
options: [
{ label: "Actif", value: "active" },
{ label: "Inactif", value: "inactive" },
{ label: "En attente", value: "pending" },
{ label: "Bloqué", value: "blocked" },
],
},
{
name: "owner",
label: "Administrateur",
type: "select",
options: users?.map((user: { id: string; name: string }) => ({
label: user.name,
value: user.id,
})) || [],
},
]}
submit={createMutation.mutate} // Le type est maintenant compatible
schema={companySchema}
child={
<button
type="submit"
disabled={createMutation.isPending}
className={`${createMutation.isPending ? "btn-auth-loading" : "btn-auth"} mt-4 cursor-pointer`}
>
{createMutation.isPending ? "En cours..." : "Créer l'organisation"}
</button>
}
/>
}
/>
<FloatingLabelInput
name="search"
placeholder="Effectuer une recherche"
type="search"
onChange={(value) => table.setGlobalFilter(value)}
button={
<Image
alt="Filtrer"
src={icons.filterIcon}
className="cursor-pointer"
/>
}
/>
</div>
</div>
);
}}
/>
);
}

View File

@ -57,9 +57,16 @@ body {
z-index: 1; z-index: 1;
} }
.btn-floating { .btn-floating-right {
position: absolute; position: absolute;
right: 12px; right: 8px;
top: 50%;
transform: translateY(-50%);
}
.btn-floating-left {
position: absolute;
left: 8px;
top: 50%; top: 50%;
transform: translateY(-50%); transform: translateY(-50%);
} }
@ -77,6 +84,22 @@ body {
} }
} }
.btn-auth-loading {
border-radius: 9999px;
background-color: #93b4f8;
color: white;
width: 100%;
padding: 8px;
}
.responsive-icon {
min-width: 16px;
min-height: 16px;
width: 24px;
height: 24px;
transition: width 0.2s, height 0.2s;
}
.cta{ .cta{
padding: 10px 24px; padding: 10px 24px;
color: white; color: white;
@ -141,3 +164,18 @@ hr{
::-webkit-scrollbar-thumb:hover { ::-webkit-scrollbar-thumb:hover {
background: var(--primary); background: var(--primary);
} }
@media (max-width: 768px) {
.responsive-icon {
width: 20px;
height: 20px;
}
}
@media (max-width: 480px) {
.responsive-icon {
width: 16px;
height: 16px;
}
}

View File

@ -1,13 +1,10 @@
import type { Metadata } from "next"; import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css"; import "./globals.css";
import NextTopLoader from "nextjs-toploader"; import NextTopLoader from "nextjs-toploader";
import "../assets/css/ruben-ui.css" import "../assets/css/ruben-ui.css"
import { AuthProvider } from "#/components/provider/authProvider"; import { AuthProvider } from "#/components/provider/authProvider";
import { QueryClientProvide } from "#/components/provider/queryClient"; import { QueryClientProvide } from "#/components/provider/queryClient";
const inter = Inter({ subsets: ["latin"] });
export const metadata: Metadata = { export const metadata: Metadata = {
title: "Private Docs", title: "Private Docs",
description: "L'appli de gestion de documents par excellence !", description: "L'appli de gestion de documents par excellence !",

View File

@ -7,15 +7,13 @@ import { DropdownMenu } from "radix-ui";
import Link from "next/link"; import Link from "next/link";
import Theme from "./theme"; import Theme from "./theme";
import ProfilePicture from "../../assets/icons/profile.svg"
export default function AdminHeader() { export default function AdminHeader() {
const [open, setOpen] = React.useState(false); const [open, setOpen] = React.useState(false);
return ( return (
<> <>
<nav className="header r-flex-between px-[44px] py-[20px] "> <nav className="header r-flex-between px-[44px] py-[20px] ">
<h1 className="name text-[26px]">Bienvenue, <span>Ken B.</span> </h1> <p className="name text-[26px]">Bienvenue, <span>Ken B.</span> </p>
<div className="r-flex-between justify-center items-center r-gap-12"> <div className="r-flex-between justify-center items-center r-gap-12">
<Theme /> <Theme />
{/* <ProfilePicture /> */} {/* <ProfilePicture /> */}
@ -43,7 +41,7 @@ export default function AdminHeader() {
</Link> </Link>
</DropdownMenu.Item> </DropdownMenu.Item>
<DropdownMenu.Item className="DropdownMenuItem dropdown-item text-[14px]"> <DropdownMenu.Item className="DropdownMenuItem dropdown-item text-[14px]">
<Link href="/login" className="d-flex items-start r-danger "> <Link href="#" className="d-flex items-start r-danger ">
<Image src={icons.logoutRed} alt="Deconnexion" /> <Image src={icons.logoutRed} alt="Deconnexion" />
Déconnexion Déconnexion
</Link> </Link>

View File

@ -13,26 +13,34 @@ export default function FloatingLabelInput({
button, button,
showPasswordToggle = false, showPasswordToggle = false,
name, name,
defaultValue defaultValue,
onChange,
}: FloatingLabelInputProps) { }: FloatingLabelInputProps) {
const [showPassword, setShowPassword] = useState(false); const [showPassword, setShowPassword] = useState(false);
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
const value = e.target.value;
if (onChange) {
onChange(value);
}
};
const renderInput = () => { const renderInput = () => {
switch(type) { switch(type) {
case 'select': case 'select':
return ( return (
<div className="relative w-full"> <div className="relative w-full">
<select <select
className="input-form focus:ring-2 focus:ring-blue-500" className="input-form focus:ring-2 focus:ring-blue-500 outline-none"
required
name={name} name={name}
defaultValue={defaultValue} defaultValue={defaultValue}
> >
{options?.map((option, index) => ( {options?.map((option, index) => (
<option key={index} value={option}>{option}</option> <option key={index} value={option.value}>{option.label}</option>
))} ))}
</select> </select>
{button && <div className="btn-floating">{button}</div>} {button && <div className="btn-floating-right">{button}</div>}
</div> </div>
); );
@ -43,15 +51,15 @@ export default function FloatingLabelInput({
name={name} name={name}
type={showPassword ? "text" : "password"} type={showPassword ? "text" : "password"}
placeholder={placeholder} placeholder={placeholder}
className="input-form focus:ring-2 focus:ring-blue-500 pr-10" className="input-form focus:ring-2 focus:ring-blue-500 pr-10 outline-none"
defaultValue={defaultValue} defaultValue={defaultValue}
required
/> />
{showPasswordToggle && ( {showPasswordToggle && (
<button <button
type="button" type="button"
onClick={() => setShowPassword(!showPassword)} onClick={() => setShowPassword(!showPassword)}
className="btn-floating text-gray-500 hover:text-gray-700 focus:outline-none" className="btn-floating-right text-gray-500 hover:text-gray-700 focus:outline-none"
> >
{showPassword ? ( {showPassword ? (
<Image <Image
@ -72,19 +80,38 @@ export default function FloatingLabelInput({
)} )}
</div> </div>
); );
case 'search':
return (
<div className="relative w-full">
<div className='btn-floating-left'>
<Image alt='' src={icons.searchIcon} />
</div>
<input
type="text"
placeholder={placeholder}
className="focus:ring-2 focus:ring-blue-500 outline-none px-10 py-3 w-full text-black border border-[#d1d5dc] rounded-full"
name={name}
defaultValue={defaultValue}
onChange={handleChange}
/>
{button && <div className="btn-floating-right">{button}</div>}
</div>
);
default: default:
return ( return (
<div className="relative w-full"> <div className="relative w-full">
<input <input
type={type} type={type}
placeholder={placeholder} placeholder={placeholder}
className="floating-label input-form focus:ring-2 focus:ring-blue-500" className="input-form focus:ring-2 focus:ring-blue-500 outline-none"
required
name={name} name={name}
defaultValue={defaultValue} defaultValue={defaultValue}
onChange={handleChange}
/> />
{button && <div className="absolute right-0 top-1/2 transform -translate-y-1/2">{button}</div>} {button && <div className="btn-floating-right">{button}</div>}
</div> </div>
); );
} }

View File

@ -5,71 +5,72 @@ import { FormProps } from "#/types"
import { FormEvent, useState } from "react" import { FormEvent, useState } from "react"
export default function Form({ export default function Form({
fields, fields,
submit, submit,
className, className,
child, child,
title, title,
schema schema,
}: FormProps) { formClassName
const [errors, setErrors] = useState<Record<string, string>>({}); } : FormProps) {
const [errors, setErrors] = useState<Record<string, string>>({});
const handleSubmit = (e: FormEvent<HTMLFormElement>) => { const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault() e.preventDefault()
const formData = new FormData(e.currentTarget) const formData = new FormData(e.currentTarget)
const data = Object.fromEntries(formData) const data = Object.fromEntries(formData)
console.log("FORM DATA = ", data) console.log("FORM DATA = ", data)
const result = schema.safeParse(data); const result = schema.safeParse(data);
console.log("ZOD = ", result.error?.format()) console.log("ZOD = ", result.error?.format())
if (!result.success) { if(!result.success) {
const formatedErrors = result.error.format() as Record<string, { _errors?: string[] }>; const formatedErrors = result.error.format() as Record<string, { _errors?: string[] }>;
const newErrors: Record<string, string> = {}; const newErrors: Record<string, string> = {};
Object.keys(formatedErrors).forEach((field) => { Object.keys(formatedErrors).forEach((field) => {
if (field !== "_errors" && formatedErrors[field]._errors?.length) { if (field !== "_errors" && formatedErrors[field]._errors?.length) {
newErrors[field] = formatedErrors[field]._errors[0]; newErrors[field] = formatedErrors[field]._errors[0];
}
});
setErrors(newErrors)
} else {
setErrors({})
submit(result.data)
} }
});
setErrors(newErrors)
} else {
setErrors({})
submit(result.data)
} }
}
return ( return (
<form className={className} onSubmit={handleSubmit}> <form onSubmit={handleSubmit} className={formClassName}>
<div className="flex justify-center text-black"> <div className="flex justify-center text-black">
<p className="text-3xl font-bold">{title}</p> <p className="text-3xl font-bold">{title}</p>
</div>
<div className="flex flex-col gap-8 mt-2">
{
fields.map((item, index) => (
<div key={index}>
<FloatingLabelInput
label={item.label}
name={item.name}
type={item.type}
button={item.button}
defaultValue={item.defaultValue}
options={item.options}
placeholder={item.placeholder}
showPasswordToggle={item.showPasswordToggle}
/>
<span className="text-red-500 text-xs mt-1">{errors[item.name]}</span>
</div> </div>
))
}
{child}
</div>
</form>
) <div className={`space-y-8 my-2 ${className}`}>
{
fields.map((item, index) => (
<div key={index}>
<FloatingLabelInput
label={item.label}
name={item.name}
type={item.type}
button={item.button}
defaultValue={item.defaultValue}
options={item.options}
placeholder={item.placeholder}
showPasswordToggle={item.showPasswordToggle}
/>
<span className="text-red-500 text-xs mt-1">{errors[item.name]}</span>
</div>
))
}
</div>
{child}
</form>
)
} }

View File

@ -1,37 +1,42 @@
import * as Dialog from "@radix-ui/react-dialog"; import * as Dialog from "@radix-ui/react-dialog";
import { ReactNode, useState } from "react"; import { ReactNode } from "react";
export function Modal({ export function Modal({
trigger, trigger,
title, title,
content, content,
open open,
onOpenChange
}: { }: {
trigger: ReactNode; trigger: ReactNode;
title: string | ReactNode; title?: string | ReactNode;
content: ReactNode; content: ReactNode;
open?: boolean; open?: boolean;
onOpenChange?: (open: boolean) => void;
}) { }) {
const [toggle, setToggle] = useState(open);
return ( return (
<Dialog.Root open={toggle}> <Dialog.Root open={open} onOpenChange={onOpenChange}>
<Dialog.Trigger asChild> <Dialog.Trigger asChild>
{trigger} {trigger}
</Dialog.Trigger> </Dialog.Trigger>
<Dialog.Portal> <Dialog.Portal>
<Dialog.Overlay className="fixed inset-0 bg-black/25 z-40" /> <Dialog.Overlay className="fixed inset-0 bg-black/25 z-40" />
<Dialog.Content className="fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-full max-w-md bg-white rounded-lg shadow-xl z-50 p-6"> <Dialog.Content className="fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-full max-w-md bg-white rounded-lg shadow-xl z-50 p-6"
// onPointerDownOutside={(e) => e.preventDefault()}
>
<Dialog.Title className="text-xl font-bold text-center my-4"> <Dialog.Title className="text-xl font-bold text-center my-4">
{title} {title}
</Dialog.Title> </Dialog.Title>
{content}
<div className=" justify-center">
{content}
</div>
{/* <div className="absolute top-4 right-4 text-gray-500 hover:text-gray-700 cursor-pointer" <div className="absolute top-4 right-4 text-gray-500 hover:text-gray-700 cursor-pointer"
onClick={() => {setToggle(false)}} onClick={() => {onOpenChange?.(false)}}
> >
Fermer X
</div> */} </div>
</Dialog.Content> </Dialog.Content>
</Dialog.Portal> </Dialog.Portal>
</Dialog.Root> </Dialog.Root>

View File

@ -25,7 +25,7 @@ export default function Statistics() {
if(response.data) { if(response.data) {
return response.data as Stats return response.data as Stats
} }
} catch (error: any) { } catch (error) {
console.error(error) console.error(error)
} }
} }

View File

@ -5,25 +5,29 @@ import {
getCoreRowModel, getCoreRowModel,
useReactTable, useReactTable,
getPaginationRowModel, getPaginationRowModel,
SortingState,
ColumnFiltersState, ColumnFiltersState,
getFilteredRowModel, getFilteredRowModel,
Table as TableType,
} from "@tanstack/react-table" } from "@tanstack/react-table"
import { useState } from "react"; import { ReactNode, useEffect, useRef, useState } from "react";
import { clsx, type ClassValue } from "clsx"
import Image from "next/image"; import Image from "next/image";
import { icons } from "#/assets/icons"; import { icons } from "#/assets/icons";
import clsx from "clsx";
interface DataTableProps<TData, TValue> { interface DataTableProps<TData, TValue> {
columns: ColumnDef<TData, TValue>[] columns: ColumnDef<TData, TValue>[]
data: TData[], data: TData[],
pageSize?: number pageSize?: number,
header?: ReactNode | ((table: TableType<TData>) => ReactNode),
isDataLoading?: boolean
} }
export default function Table<TData, TValue>({ export default function Table<TData, TValue>({
columns, columns,
data, data,
pageSize = 10 pageSize = 10,
header,
isDataLoading = true
}: DataTableProps<TData, TValue>) { }: DataTableProps<TData, TValue>) {
const [rowSelection, setRowSelection] = useState({}) const [rowSelection, setRowSelection] = useState({})
const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>( const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>(
@ -51,6 +55,26 @@ export default function Table<TData, TValue>({
onColumnFiltersChange: setColumnFilters, onColumnFiltersChange: setColumnFilters,
}) })
const headerCheckboxRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (headerCheckboxRef.current) {
headerCheckboxRef.current.indeterminate =
table.getIsSomePageRowsSelected() && !table.getIsAllPageRowsSelected();
}
const selectedRows = table.getSelectedRowModel().rows;
const filteredSelectedRows = table
.getRowModel()
.rows.filter((row) => row.getIsSelected())
.map((row) => row.original);
console.log("SELECTED ALL = ", selectedRows);
console.log("SELECTED = ", filteredSelectedRows);
}, [
table
]);
const totalPages = table.getPageCount() const totalPages = table.getPageCount()
const currentPage = table.getState().pagination.pageIndex + 1 const currentPage = table.getState().pagination.pageIndex + 1
@ -62,63 +86,93 @@ export default function Table<TData, TValue>({
return pages return pages
} }
const render = () => {
if(!header) return null
return(
<div className="mb-4">
{typeof header === 'function'
? header(table)
: header}
</div>
)
}
return( return(
<div> <div className="w-full">
{render()}
<div className="rounded-lg border border-gray-200 w-auto"> <div className="rounded-lg border border-gray-200 w-auto">
<table className="w-full overflow-x-auto rounded-lg"> <div className="overflow-x-auto">
<thead className="h-10"> <table className="w-full overflow-x-auto rounded-lg">
{table.getHeaderGroups().map((headerGroup) => ( <thead className="h-10">
<tr key={headerGroup.id} className="rounded-lg"> {table.getHeaderGroups().map((headerGroup) => (
<th className="bg-blue-300 p-3 text-start first:rounded-tl-lg"> <tr key={headerGroup.id} className="rounded-lg">
<input checked={ {header
table.getIsAllPageRowsSelected() || ?
(table.getIsSomePageRowsSelected() && undefined) <th className="bg-[#E9F0FF] p-3 text-start first:rounded-tl-lg">
}
onChange={(e) => table.toggleAllPageRowsSelected(e.target.checked)} </th>
type="checkbox" name="" id="" :
/> <th className="bg-[#E9F0FF] p-3 text-start first:rounded-tl-lg">
</th>
{headerGroup.headers.map((header) => {
return(
<th key={header.id} className="bg-blue-300 p-3 text-start last:rounded-tr-lg">
{flexRender(
header.column.columnDef.header,
header.getContext()
)}
</th>
)
})}
</tr>
))}
</thead>
<tbody>
{table.getRowModel().rows.length ? (
table.getRowModel().rows.map((row) => (
<tr key={row.id} className={clsx('hover:bg-gray-100 border-t border-gray-200', { 'bg-gray-300': row.getIsSelected()})}>
<td className="p-3 text-start">
<input <input
checked={row.getIsSelected()} ref={headerCheckboxRef}
onChange={(e) => row.toggleSelected(e.target.checked)} checked={!!table.getIsAllPageRowsSelected()}
onChange={(e) => table.toggleAllPageRowsSelected(e.target.checked)}
type="checkbox" name="" id="" type="checkbox" name="" id=""
/> />
</td> </th>
{row.getVisibleCells().map((cell) => ( }
<td key={cell.id} className="p-3 text-start"> {headerGroup.headers.map((header) => {
{flexRender(cell.column.columnDef.cell, cell.getContext())} return(
</td> <th key={header.id} className="bg-[#E9F0FF] p-3 text-start last:rounded-tr-lg">
))} {flexRender(
header.column.columnDef.header,
header.getContext()
)}
</th>
)
})}
</tr> </tr>
)) ))}
) </thead>
: ( <tbody>
<tr> {table.getRowModel().rows.length ? (
<td colSpan={columns.length}> table.getRowModel().rows.map((row) => (
Aucun résultats <tr key={row.id} className={clsx('hover:bg-gray-100 border-t border-gray-200', { 'bg-gray-300': row.getIsSelected()})}>
</td> <td className="p-3 text-start">
</tr> <input
)} checked={row.getIsSelected()}
</tbody> onChange={(e) => row.toggleSelected(e.target.checked)}
</table> type="checkbox" name="" id=""
/>
</td>
{row.getVisibleCells().map((cell) => (
<td key={cell.id} className="p-3 text-start">
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</td>
))}
</tr>
))
)
: isDataLoading ?
(
<tr>
<td colSpan={columns.length} className="h-20 text-center">
Chargement...
</td>
</tr>
)
: (
<tr>
<td colSpan={columns.length} className="h-20 text-center">
Aucun résultats
</td>
</tr>
)}
</tbody>
</table>
</div>
</div> </div>
<div className="flex items-center justify-end space-x-2 py-4"> <div className="flex items-center justify-end space-x-2 py-4">

11
src/lib/function.ts Normal file
View File

@ -0,0 +1,11 @@
import { signOut } from "next-auth/react";
export const signOutFunc = () => {
signOut({
callbackUrl: `/login?redirect_to=${
window.location.pathname === "/logout"
? "/home"
: window.location.pathname
}`,
});
};

View File

@ -11,4 +11,11 @@ export const adminSchema = z.object({
first_name: z.string(), first_name: z.string(),
email: z.string().min(1, "L'email est requis").email("Email invalide"), email: z.string().min(1, "L'email est requis").email("Email invalide"),
organization: z.string().optional(), organization: z.string().optional(),
}); });
export const companySchema = z.object({
name: z.string().min(1, "Le nom est requis"),
description: z.string(),
status: z.string(),
owner: z.string()
})

View File

@ -1,24 +1,30 @@
import { FormEventHandler, ReactNode } from "react"; import { ReactNode } from "react";
import { ZodSchema } from "zod"; import { ZodSchema } from "zod";
export interface Option {
label: string
value: string
}
export interface FloatingLabelInputProps { export interface FloatingLabelInputProps {
label: string; label?: string;
placeholder?: string; placeholder?: string;
type: 'text' | 'password' | 'select' | 'email' | 'number'; type: 'text' | 'password' | 'select' | 'email' | 'number' | 'hidden' | 'search' | 'textarea';
options?: string[]; options?: Option[];
button?: React.ReactNode; button?: React.ReactNode;
showPasswordToggle?: boolean; showPasswordToggle?: boolean;
name: string; name: string;
defaultValue?: string; defaultValue?: string;
onChange?: (value: string) => void;
} }
export interface FormProps { export interface FormProps{
title?: string, title?: string,
fields: FloatingLabelInputProps[], fields: FloatingLabelInputProps[],
submit: (param: any) => unknown, submit: (param: any) => unknown,
className: string, className?: string,
child: ReactNode, child: ReactNode,
schema: ZodSchema schema: ZodSchema,
formClassName?: string
} }
export interface StatsType { export interface StatsType {
@ -39,9 +45,11 @@ export interface Stats {
export interface Company { export interface Company {
id: string id: string
name: string name: string
description?: string;
is_premium: boolean is_premium: boolean
status: string status: string
owner: Owner owner: Owner
total_users?: number
} }
export interface Owner { export interface Owner {