import React, { useEffect, useState, useSyncExternalStore } from "react"; import prisma from '../lib/prisma' import dateFormat, { masks } from "dateformat"; import Image from 'next/image'; import * as Yup from 'yup'; import Head from "next/head"; import { getCsrfToken, getSession, signIn, useSession } from "next-auth/react"; import { yupResolver } from "@hookform/resolvers/yup"; import "yup-phone"; import { SubmitHandler, useForm } from "react-hook-form"; import { AiOutlineCheck } from 'react-icons/ai' import Router from "next/router"; import { useRouter } from 'next/navigation'; import style from '../styles/Connexion.module.css'; import imageConnexion from '../public/images/connexion_image.png' import Link from "next/link"; import { TfiInfoAlt } from 'react-icons/tfi' import { TfiGift } from 'react-icons/tfi' import { toast } from "react-toastify"; import { Token } from "nodemailer/lib/xoauth2"; import { isGeneratorFunction } from "util/types"; import { UserProps } from "../types/user"; import { UserGainProps } from "../types/userGain"; import { Gain, Produit, Role, User } from "@prisma/client"; type FormData = { email: string; name: string; surname: string; address: string; zipCode: number; phoneNumber: number; }; export async function getServerSideProps(context) { const session = await getSession(context) const isAdmin = ['SELLER', 'ADMIN', 'SUPERADMIN'].includes(session?.user['role']); if (!session || !isAdmin) { return { redirect: { destination: '/', permanent: false } } } const users = await prisma.user.findMany({ include: { gains: true } }); const user = await prisma.user.findUnique({ where: { email: session?.user.email } }); const produits = await prisma.produit.findMany({}) return { props: { user: JSON.parse(JSON.stringify(user)), produits: JSON.parse(JSON.stringify(produits)), users: JSON.parse(JSON.stringify(users)) }, } } type Props = { user: User; produits: Produit[]; users: User[] } const Admin = (props: Props) => { const { data: session, status } = useSession(); const [response, setResponse] = useState(null) const [currentUser, setCurrentUser] = useState(null) const [users, setUsers] = useState(props.users) const [currentUserGain, setCurrentUserGain] = useState(null) const router = useRouter() const { register, setValue, handleSubmit, formState: { errors } } = useForm({ }); const fetcher = async (url, method, body = {}, callback?: any) => { try { await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }) .then((res) => res.json()) .then(async (data) => { setResponse(data); callback; if (data.err) { toast.error(data.err, { position: "top-center", autoClose: 2000, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, draggable: true, progress: undefined, theme: "light", }); return; } toast.success(data.message, { position: "top-center", autoClose: 5000, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, draggable: true, progress: undefined, theme: "light", }); }) } catch (error) { console.error('ERROR :', error); } } const onSubmit = async ({ email, name, surname, address, zipCode, phoneNumber }: FormData) => { const body = { selectedUserEmail: email, selectedUserName: name, selectedUserSurname: surname, selectedUserAddress: address, selectedUserZipCode: Number(zipCode), selectedUserPhoneNumber: Number(phoneNumber), }; fetcher('/api/user/update', 'POST', body) }; const onChangeRole = async (e: React.ChangeEvent, user: User) => { const body = { selectedUserEmail: user.email, selectedUserRole: e.target.value } fetcher('/api/user/update', 'PUT', body) }; const onDeleteUser = async (userEmail: string) => { const body = { selectedUserEmail: userEmail } if (props.user.email === userEmail) { toast.error('Vous devez être déconnecté pour supprimer votre compte', { position: "top-center", autoClose: 2000, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, draggable: true, progress: undefined, theme: "light", }); return; } fetcher('/api/user/delete', 'DELETE', body) }; const selectUser = (user: any) => { console.log('d', user.gains) setCurrentUser(user); setCurrentUserGain(user.gains) setValue("name", user.name) setValue("email", user.email) setValue("surname", user.surname) setValue("address", user.address) setValue("zipCode", user.zipCode) setValue("phoneNumber", user.phoneNumber) } const changeGiftStatus = async (gain: Gain) => { const body = { gain } fetcher('/api/user/update-gift', 'PUT', body) console.log('g', gain); setCurrentUserGain(gain) // router.refresh(); }; return ( <> Administration

Utilisateurs


{users.length <= 0 &&

Pas encore d'utilisateur

} {users.length >= 1 && {users.map((info: User, index: number) => { return selectUser(info)}> })}
# Nom Prénom Email Types
{++index} {info.surname} {info.name} {info.email}
}

{currentUser?.email || 'utilisateur'}


{currentUser &&
{errors.name?.message}
{errors.surname?.message}
{errors.address?.message}
{errors.zipCode?.message}
{errors.phoneNumber?.message}
} {!currentUser &&

Séléctionner un utilisateur

}

Cadeaux de {currentUser?.email || "l'utilisateur"}


{currentUser?.gains?.length <= 0 &&

Pas encore de cadeaux gagné

} {currentUser?.gains?.length >= 1 && {currentUserGain.map((gain: Gain, index: number) => { return })}
# Codes joués Cadeaux Retiré en magasin Date Retrait
{++index} {gain?.codeCadeau} {props.produits[gain.produitId - 1].nomProduit} {gain?.retrait ? '❌ déja récupéré' : '✔️ disponible'} {gain?.dateRetrait ? dateFormat(gain?.dateRetrait, "dd/mm/yyyy") : ''}
}
) }; export default Admin;