You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
505 lines
18 KiB
505 lines
18 KiB
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, TicketsRestants, User } from "@prisma/client";
|
|
import { Doughnut } from "react-chartjs-2";
|
|
import { Chart as ChartJS, ArcElement, Tooltip, Legend, RadialLinearScale } from 'chart.js';
|
|
import { PolarArea } from 'react-chartjs-2';
|
|
|
|
|
|
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 tickets = await prisma.gain.findMany({})
|
|
const totalTirageRestant = await prisma.ticketsRestants.findFirst({})
|
|
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)),
|
|
tickets: JSON.parse(JSON.stringify(tickets)),
|
|
totalTirageRestant: JSON.parse(JSON.stringify(totalTirageRestant))
|
|
},
|
|
}
|
|
}
|
|
|
|
type Props = {
|
|
user: User;
|
|
produits: Produit[];
|
|
users: any,
|
|
tickets: Gain[]
|
|
totalTirageRestant: TicketsRestants
|
|
}
|
|
|
|
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 [query, setQuery] = useState("");
|
|
const router = useRouter()
|
|
|
|
const isAdmin = session?.user['role'] === Role.ADMIN
|
|
const isSuperAdmin = session?.user['role'] === Role.SUPERADMIN
|
|
const bigWinner = users?.find((user) => user?.isBigWinner)
|
|
|
|
ChartJS.register(RadialLinearScale, ArcElement, Tooltip, Legend);
|
|
|
|
const TicketRestants = props.tickets?.filter(ticket => ticket.codeActif === true).length
|
|
console.log("🚀 ~ file: admin.tsx:103 ~ Admin ~ TicketRestants", TicketRestants)
|
|
const TicketUtilise = props.tickets?.filter(ticket => ticket.codeActif === false).length
|
|
console.log("🚀 ~ file: admin.tsx:104 ~ Admin ~ TicketUtilise", TicketUtilise)
|
|
const TicketTotal = props.totalTirageRestant.total;
|
|
console.log("🚀 ~ file: admin.tsx:107 ~ Admin ~ TicketTotal", TicketTotal)
|
|
|
|
|
|
|
|
const TotalTirageRestant = props.totalTirageRestant?.total;
|
|
|
|
const ticketDataChart = {
|
|
labels: ['Tickets généré utlisés', 'Tickets généré restants'],
|
|
datasets: [
|
|
{
|
|
label: 'Tickets restants généré',
|
|
data: [TicketUtilise, TicketRestants],
|
|
backgroundColor: [
|
|
'rgba(255, 99, 132, 0.2)',
|
|
'rgba(54, 162, 235, 0.2)',
|
|
],
|
|
borderColor: [
|
|
'rgba(255, 99, 132, 1)',
|
|
'rgba(54, 162, 235, 1)',
|
|
],
|
|
borderWidth: 1,
|
|
},
|
|
],
|
|
};
|
|
|
|
const TotalTirageRestantData = {
|
|
labels: ['Total tirage restant'],
|
|
datasets: [
|
|
{
|
|
label: 'Tirage de ticket',
|
|
data: [TotalTirageRestant],
|
|
backgroundColor: [
|
|
'rgba(54, 162, 235, 0.5)',
|
|
],
|
|
borderWidth: 1,
|
|
},
|
|
],
|
|
}
|
|
|
|
|
|
|
|
const { register, setValue, handleSubmit, formState: { errors } } = useForm<FormData>({
|
|
});
|
|
|
|
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<HTMLSelectElement>, user: User) => {
|
|
const body = { selectedUserEmail: user.email, selectedUserRole: e.target.value }
|
|
fetcher('/api/user/update', 'PUT', body)
|
|
setTimeout(() => {
|
|
router.refresh();
|
|
}, 2000)
|
|
};
|
|
|
|
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) => {
|
|
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)
|
|
setTimeout(() => {
|
|
router.refresh();
|
|
}, 2000)
|
|
};
|
|
|
|
const selectWinUser = async () => {
|
|
const customers = users.filter((user) => user.role === 'USER')
|
|
|
|
if (users.length <= 0) {
|
|
toast.error("Il n'y a pas encore d'utilisateur", {
|
|
position: "top-center",
|
|
autoClose: 2000,
|
|
hideProgressBar: false,
|
|
closeOnClick: true,
|
|
pauseOnHover: true,
|
|
draggable: true,
|
|
progress: undefined,
|
|
theme: "light",
|
|
});
|
|
return;
|
|
}
|
|
|
|
const customersWithTicket = customers.filter((user) => user.gains.length >= 1)
|
|
|
|
if (customersWithTicket.length <= 0) {
|
|
toast.error("Il n'y a pas encore d'utilisateurs ayant joué", {
|
|
position: "top-center",
|
|
autoClose: 2000,
|
|
hideProgressBar: false,
|
|
closeOnClick: true,
|
|
pauseOnHover: true,
|
|
draggable: true,
|
|
progress: undefined,
|
|
theme: "light",
|
|
});
|
|
return;
|
|
}
|
|
|
|
const winUser = customersWithTicket[Math.floor(Math.random() * customersWithTicket.length)]
|
|
const body = { selectedUserEmail: winUser.email }
|
|
console.log(body)
|
|
fetcher('/api/user/bigwinner', 'PUT', body)
|
|
setTimeout(() => {
|
|
router.refresh();
|
|
}, 2000)
|
|
}
|
|
|
|
|
|
const searchFilter = (array: any) => {
|
|
return array.filter((el: User) => {
|
|
if (query === "") return props.users
|
|
return el.email?.toLowerCase().includes(query)
|
|
}
|
|
)
|
|
}
|
|
|
|
const filtered = searchFilter(props.users)
|
|
|
|
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
|
setQuery(e.target.value)
|
|
}
|
|
|
|
return (
|
|
<>
|
|
<Head>
|
|
<title>Administration</title>
|
|
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="" />
|
|
</Head>
|
|
<div className={`${style['masthead']} d-flex justify-content-center align-items-center text-center`}>
|
|
<div className="container align-items-center d-flex flex-column">
|
|
<div className={`${style['bloc-content']} col-12 col-md-12`}>
|
|
<div className="row">
|
|
<div className="col-md-12 col-sm-12">
|
|
<hr />
|
|
<h1 className="fw-light">Dashboard Administration</h1>
|
|
<hr />
|
|
|
|
|
|
<div className="container" style={{ width: '30vw' }}>
|
|
<div className="row">
|
|
<div className="col-12 justify-content-center">
|
|
<p>Total tirages restant 📈 {props.totalTirageRestant?.total?.toString()}</p>
|
|
<Doughnut
|
|
data={ticketDataChart} />
|
|
</div>
|
|
</div>
|
|
|
|
</div>
|
|
|
|
|
|
{(isAdmin ||
|
|
isSuperAdmin) && <div>
|
|
<p className="fw-light">Grand jeu concours : séléctionner l'utilisateur gagnant pour les 1 an de thé</p>
|
|
<p className="fw-light">En cliquant sur le bouton</p>
|
|
<p className="fw-light"> 👇</p>
|
|
<button className="btn btn-primary" disabled={users?.some((user) => user?.isBigWinner)} onClick={selectWinUser}>Séléctionner</button>
|
|
<hr />
|
|
</div>}
|
|
{bigWinner ? <p>Grand gagnant 📢</p> : <p>Pas encore de gagnant tiré au sort 🤫</p>}
|
|
<p>{bigWinner && bigWinner.email}</p>
|
|
{users.length <= 0 && <p>Pas encore d'utilisateur</p>}
|
|
{users.length >= 1 && <>
|
|
<div className="input-group mb-3">
|
|
<span className="input-group-text" id="basic-addon1">🔎</span>
|
|
<input type="text" className="form-control" onChange={handleChange} placeholder='Rechercher un utilisateur avec son email...' aria-label="search" />
|
|
</div>
|
|
<table className={`table table-hover`}>
|
|
<thead>
|
|
<tr>
|
|
<th scope="col">#</th>
|
|
<th scope="col">Nom</th>
|
|
<th scope="col">Prénom</th>
|
|
<th scope="col">Email</th>
|
|
<th scope="col">Types</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{filtered.map((info: User, index: number) => {
|
|
return <tr key={index} className={`${style.cursor}`} onClick={() => selectUser(info)}>
|
|
<th scope="row">{++index}</th>
|
|
<td>{info.surname}</td>
|
|
<td>{info.name}</td>
|
|
<td>{info.isBigWinner && '🎁'}{info.email}</td>
|
|
{info.role !== Role.SELLER && <td>
|
|
<select className="custom-select" defaultValue={info.role} onChange={(e) => onChangeRole(e, info)}>
|
|
<option value="USER">Client</option>
|
|
<option value="SELLER">Vendeur</option>
|
|
<option value="ADMIN">Administrateur</option>
|
|
{isSuperAdmin && <option value="SUPERADMIN">SuperAdmin</option>}
|
|
</select>
|
|
</td>}
|
|
{info.role !== Role.SELLER && <td><button className="btn btn-primary" onClick={() => onDeleteUser(info.email)}>Supprimer</button></td>}
|
|
</tr>;
|
|
})}
|
|
</tbody>
|
|
</table>
|
|
</>}
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<div className="row">
|
|
<div className="col-md-6 col-sm-12">
|
|
<hr />
|
|
<h1 className="fw-light text-truncate">{currentUser?.email || 'utilisateur'} <TfiInfoAlt size={40} /></h1>
|
|
<hr />
|
|
{currentUser && <form onSubmit={handleSubmit(onSubmit)}>
|
|
<div className="form-group">
|
|
|
|
<div className="form-group row">
|
|
<label htmlFor="staticEmail" className="col-sm-3 col-form-label">Email :</label>
|
|
<div className="col-sm-9">
|
|
<input type="text" readOnly className="form-control-plaintext text-sm-center" id="staticEmail" value={currentUser?.email || ''} />
|
|
</div>
|
|
</div>
|
|
|
|
<div className="form-group row">
|
|
<label htmlFor="inputName" className="col-sm-3 col-form-label">Nom :</label>
|
|
<div className="col-sm-9">
|
|
<input {...register("name")} className={`form-control ${errors.name ? 'is-invalid' : ''}`} defaultValue={currentUser?.name || ''} id="inputName" placeholder="John..." />
|
|
<div className="invalid-feedback alert alert-danger mt-2">{errors.name?.message}</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="form-group row">
|
|
<label htmlFor="surname" className="col-sm-3 col-form-label">Prenom :</label>
|
|
<div className="col-sm-9">
|
|
<input {...register("surname")} className={`form-control ${errors.surname ? 'is-invalid' : ''}`} defaultValue={currentUser?.surname || ''} id="surname" placeholder="Doe..." />
|
|
<div className="invalid-feedback alert alert-danger mt-2">{errors.surname?.message}</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="form-group row">
|
|
<label htmlFor="address" className="col-sm-3 col-form-label">Adresse :</label>
|
|
<div className="col-sm-9">
|
|
<input {...register("address")} className={`form-control ${errors.address ? 'is-invalid' : ''}`} defaultValue={currentUser?.address || ''} id="address" placeholder="1 rue de la paix..." />
|
|
<div className="invalid-feedback alert alert-danger mt-2">{errors.address?.message}</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="form-group row">
|
|
<label htmlFor="zipCode" className="col-sm-3 col-form-label">Code postale :</label>
|
|
<div className="col-sm-9">
|
|
<input {...register("zipCode")} className={`form-control ${errors.zipCode ? 'is-invalid' : ''}`} defaultValue={currentUser?.zipCode || ''} id="zipCode" placeholder="95000..." />
|
|
<div className="invalid-feedback alert alert-danger mt-2">{errors.zipCode?.message}</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="form-group row">
|
|
<label htmlFor="phoneNumber" className="col-sm-3 col-form-label">Téléphone :</label>
|
|
<div className="col-sm-9">
|
|
<input {...register("phoneNumber")} className={`form-control ${errors.phoneNumber ? 'is-invalid' : ''}`} defaultValue={currentUser?.phoneNumber || ''} id="phoneNumber" placeholder="0123456789..." />
|
|
<div className="invalid-feedback alert alert-danger mt-2">{errors.phoneNumber?.message}</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="form-group">
|
|
<button
|
|
type="submit"
|
|
className="btn btn-primary mt-2"
|
|
>
|
|
Sauvegarder mes changements
|
|
</button>
|
|
</div>
|
|
</div>
|
|
|
|
</form>}
|
|
{!currentUser && <p>Séléctionner un utilisateur</p>}
|
|
</div>
|
|
<div className="col-md-6 col-sm-12">
|
|
<hr />
|
|
<h1 className="fw-light">Cadeaux <TfiGift size={40} /></h1>
|
|
<hr />
|
|
{currentUser?.gains?.length <= 0 && <p>Pas encore de cadeaux gagné</p>}
|
|
{currentUser?.gains?.length >= 1 &&
|
|
<table className="table">
|
|
<thead>
|
|
<tr>
|
|
<th scope="col">#</th>
|
|
<th scope="col">Codes joués</th>
|
|
<th scope="col">Cadeaux</th>
|
|
<th scope="col">Retiré en magasin</th>
|
|
<th scope="col">Date Retrait</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{currentUserGain.map((gain: Gain, index: number) => {
|
|
return <tr key={index}>
|
|
<th scope="row">{++index}</th>
|
|
<td>{gain?.codeCadeau}</td>
|
|
<td>{props.produits[gain.produitId - 1].nomProduit}</td>
|
|
<td>{gain?.retrait ? '❌ déja récupéré' : '✔️ disponible'}</td>
|
|
<td>{gain?.dateRetrait ? dateFormat(gain?.dateRetrait, "dd/mm/yyyy") : ''}</td>
|
|
<td>
|
|
<button className="btn btn-primary" disabled={gain?.retrait} onClick={() => changeGiftStatus(gain)}>OUI</button>
|
|
</td>
|
|
</tr>
|
|
})}
|
|
</tbody>
|
|
</table>
|
|
}
|
|
</div>
|
|
</div>
|
|
|
|
|
|
</div>
|
|
</div >
|
|
</div >
|
|
</>)
|
|
};
|
|
|
|
export default Admin;
|
|
|
|
|