From 27187c6c68624491765fc1698a71377e5a6e0c54 Mon Sep 17 00:00:00 2001 From: Eric Date: Wed, 7 Dec 2022 15:11:50 +0100 Subject: [PATCH] add - loading spinner, administration, navbar modfications --- .env | 10 +- .vscode/settings.json | 5 + components/Loader.tsx | 15 ++ components/NavBar.tsx | 50 +++-- context/globalContext.tsx | 37 ++++ context/index.tsx | 5 + enum/role.enum.ts | 1 + package-lock.json | 47 +++++ package.json | 3 + pages/_app.tsx | 40 +++- pages/admin.tsx | 354 ++++++++++++++++++++++++++++++++ pages/api/auth/[...nextauth].ts | 8 +- pages/api/superadmin/index.ts | 36 ---- pages/api/testcode/index.ts | 7 +- pages/api/user/delete.ts | 74 +++++++ pages/api/user/get-current.ts | 102 +++++++++ pages/api/user/update.ts | 96 +++++++++ pages/connexion.tsx | 2 +- pages/index.tsx | 2 +- pages/mon-compte.tsx | 16 +- prisma/schema.prisma | 2 +- prisma/seed.ts | 16 +- prisma/seed/gains.ts | 2 + prisma/seed/user.ts | 20 +- styles/Connexion.module.css | 4 + styles/Loader.module.css | 34 +++ styles/NavBar.module.css | 11 +- types/userGain.ts | 3 +- 28 files changed, 886 insertions(+), 116 deletions(-) create mode 100644 components/Loader.tsx create mode 100644 context/globalContext.tsx create mode 100644 context/index.tsx create mode 100644 pages/admin.tsx delete mode 100644 pages/api/superadmin/index.ts create mode 100644 pages/api/user/delete.ts create mode 100644 pages/api/user/get-current.ts create mode 100644 pages/api/user/update.ts create mode 100644 styles/Loader.module.css diff --git a/.env b/.env index f56fd6f..e02a63f 100644 --- a/.env +++ b/.env @@ -12,11 +12,11 @@ GOOGLE_CLIENT_SECRET=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 DATABASE_URL="postgres://postgres:postgrespwd@localhost:5432/thetiptop" # Email (magic link) -EMAIL_SERVER_USER=2bfdbee5372880 -EMAIL_SERVER_PASSWORD=af828174d7f2ad -EMAIL_SERVER_HOST=smtp.mailtrap.io -EMAIL_SERVER_PORT=2525 -EMAIL_FROM=thetiptop@test.com +EMAIL_SERVER_USER=contact@dsp-archiwebo21-ad-ec-cb-mt.fr +EMAIL_SERVER_PASSWORD=Acem@2022a +EMAIL_SERVER_HOST=mail50.lwspanel.com +EMAIL_SERVER_PORT=587 +EMAIL_FROM=contact@dsp-archiwebo21-ad-ec-cb-mt.fr DATABASE_URL="postgres://postgres:postgrespwd@127.0.0.1:5454/thetiptop" diff --git a/.vscode/settings.json b/.vscode/settings.json index 7a73a41..297b8d0 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,2 +1,7 @@ { + "workbench.colorCustomizations": { + "activityBar.background": "#4C1F25", + "titleBar.activeBackground": "#6A2C34", + "titleBar.activeForeground": "#FEFCFC" + } } \ No newline at end of file diff --git a/components/Loader.tsx b/components/Loader.tsx new file mode 100644 index 0000000..f4a2535 --- /dev/null +++ b/components/Loader.tsx @@ -0,0 +1,15 @@ +import styles from '../styles/Loader.module.css' +import { MoonLoader } from 'react-spinners' + +const Loader = () => { + return ( +
+ +
+ ); +} + +export default Loader; \ No newline at end of file diff --git a/components/NavBar.tsx b/components/NavBar.tsx index b14f948..ce5faab 100644 --- a/components/NavBar.tsx +++ b/components/NavBar.tsx @@ -1,4 +1,4 @@ -import React, { useRef } from "react"; +import React, { useEffect, useRef, useState } from "react"; import logo from '../public/images/thetiptop_logo.webp'; import Link from "next/link"; import { useRouter } from "next/router"; @@ -7,12 +7,13 @@ import style from '../styles/NavBar.module.css'; import Image from 'next/image'; import { FiArrowRight } from 'react-icons/fi'; +import { MdAdminPanelSettings } from 'react-icons/md'; +import { BiExit } from 'react-icons/bi' const NavBar = () => { const navRef = useRef(); - const router = useRouter(); - const { data: session, status } = useSession(); - console.log('role', session) + const [isAdmin, setIsAdmin] = useState(false) + const { data: session } = useSession(); const closeNav = () => { navRef.current.style.height = "0%"; @@ -26,9 +27,17 @@ const NavBar = () => { signOut() } + const checkRole = () => { + const isAdmin = ['SELLER', 'ADMIN', 'SUPERADMIN'].includes(session?.user['role']); + return isAdmin ? setIsAdmin(true) : setIsAdmin(false); + } + + useEffect(() => { + checkRole(); + }, [session?.user['role']]) + let visitor = ( - ) - return (<> {visitor} ) - - - }; export default NavBar; diff --git a/context/globalContext.tsx b/context/globalContext.tsx new file mode 100644 index 0000000..c1137a3 --- /dev/null +++ b/context/globalContext.tsx @@ -0,0 +1,37 @@ +import { createContext, ReactNode, useContext, useState } from "react"; + +export type IGlobalContextProps = { + role: string; + setRole: (role: string) => void; +}; + +export const globalContextDefaultValues: IGlobalContextProps = { + role: null, + setRole: () => { }, +} + +export const GlobalContext = createContext(globalContextDefaultValues); + +type Props = { + children: ReactNode; +}; + +export const GlobalContextProvider = (props: Props) => { + const [role, setCurrentRole] = useState(null) + + return ( + + {props.children} + + ); +}; + +// import { useGlobalContext } from 'context'; +// const { user } = useGlobalContext(); + +// Pour utiliser le context n'importe ou \ No newline at end of file diff --git a/context/index.tsx b/context/index.tsx new file mode 100644 index 0000000..1195d65 --- /dev/null +++ b/context/index.tsx @@ -0,0 +1,5 @@ +import { useContext } from 'react'; + +import { GlobalContext } from './globalContext'; + +export const useGlobalContext = () => useContext(GlobalContext); \ No newline at end of file diff --git a/enum/role.enum.ts b/enum/role.enum.ts index 210d216..36851b6 100644 --- a/enum/role.enum.ts +++ b/enum/role.enum.ts @@ -1,5 +1,6 @@ export enum Role { USER = 'USER', ADMIN = 'ADMIN', + SELLER = 'SELLER', SUPERADMIN = 'SUPERADMIN' } \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index ea84862..5325928 100644 --- a/package-lock.json +++ b/package-lock.json @@ -20,12 +20,15 @@ "next": "13.0.2", "next-auth": "4.16.4", "nodemailer": "^6.8.0", + "nprogress": "^0.2.0", "react": "18.2.0", "react-dom": "18.2.0", "react-hook-form": "^7.39.2", "react-icons": "^4.6.0", "react-markdown": "8.0.3", + "react-spinners": "^0.13.7", "react-toastify": "^9.1.1", + "usehooks-ts": "^2.9.1", "yup": "^0.32.11", "yup-phone": "^1.3.2" }, @@ -2416,6 +2419,11 @@ "which": "bin/which" } }, + "node_modules/nprogress": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/nprogress/-/nprogress-0.2.0.tgz", + "integrity": "sha512-I19aIingLgR1fmhftnbWWO3dXc0hSxqHQHQb3H8m+K3TnEn/iSeTZZOyvKXWqQESMwuUVnatlCnZdLBZZt2VSA==" + }, "node_modules/oauth": { "version": "0.9.15", "resolved": "https://registry.npmjs.org/oauth/-/oauth-0.9.15.tgz", @@ -2774,6 +2782,15 @@ "react": ">=16" } }, + "node_modules/react-spinners": { + "version": "0.13.7", + "resolved": "https://registry.npmjs.org/react-spinners/-/react-spinners-0.13.7.tgz", + "integrity": "sha512-mRamn56bfxWbGcacif5RT3UbeJaXi2AttjtPwSmomuv2IcxjpbfETCzdTvaQpNDk0E33ENJsStsQeKAZFuJcpA==", + "peerDependencies": { + "react": "^16.0.0 || ^17.0.0 || ^18.0.0", + "react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0" + } + }, "node_modules/react-toastify": { "version": "9.1.1", "resolved": "https://registry.npmjs.org/react-toastify/-/react-toastify-9.1.1.tgz", @@ -3502,6 +3519,19 @@ "react": "^16.8.0 || ^17.0.0 || ^18.0.0" } }, + "node_modules/usehooks-ts": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/usehooks-ts/-/usehooks-ts-2.9.1.tgz", + "integrity": "sha512-2FAuSIGHlY+apM9FVlj8/oNhd+1y+Uwv5QNkMQz1oSfdHk4PXo1qoCw9I5M7j0vpH8CSWFJwXbVPeYDjLCx9PA==", + "engines": { + "node": ">=16.15.0", + "npm": ">=8" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0", + "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0" + } + }, "node_modules/uuid": { "version": "8.3.2", "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", @@ -5292,6 +5322,11 @@ } } }, + "nprogress": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/nprogress/-/nprogress-0.2.0.tgz", + "integrity": "sha512-I19aIingLgR1fmhftnbWWO3dXc0hSxqHQHQb3H8m+K3TnEn/iSeTZZOyvKXWqQESMwuUVnatlCnZdLBZZt2VSA==" + }, "oauth": { "version": "0.9.15", "resolved": "https://registry.npmjs.org/oauth/-/oauth-0.9.15.tgz", @@ -5551,6 +5586,12 @@ "vfile": "^5.0.0" } }, + "react-spinners": { + "version": "0.13.7", + "resolved": "https://registry.npmjs.org/react-spinners/-/react-spinners-0.13.7.tgz", + "integrity": "sha512-mRamn56bfxWbGcacif5RT3UbeJaXi2AttjtPwSmomuv2IcxjpbfETCzdTvaQpNDk0E33ENJsStsQeKAZFuJcpA==", + "requires": {} + }, "react-toastify": { "version": "9.1.1", "resolved": "https://registry.npmjs.org/react-toastify/-/react-toastify-9.1.1.tgz", @@ -6010,6 +6051,12 @@ "integrity": "sha512-eEgnFxGQ1Ife9bzYs6VLi8/4X6CObHMw9Qr9tPY43iKwsPw8xE8+EFsf/2cFZ5S3esXgpWgtSCtLNS41F+sKPA==", "requires": {} }, + "usehooks-ts": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/usehooks-ts/-/usehooks-ts-2.9.1.tgz", + "integrity": "sha512-2FAuSIGHlY+apM9FVlj8/oNhd+1y+Uwv5QNkMQz1oSfdHk4PXo1qoCw9I5M7j0vpH8CSWFJwXbVPeYDjLCx9PA==", + "requires": {} + }, "uuid": { "version": "8.3.2", "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", diff --git a/package.json b/package.json index 2d8bb57..b4bd3c0 100644 --- a/package.json +++ b/package.json @@ -23,12 +23,15 @@ "next": "13.0.2", "next-auth": "4.16.4", "nodemailer": "^6.8.0", + "nprogress": "^0.2.0", "react": "18.2.0", "react-dom": "18.2.0", "react-hook-form": "^7.39.2", "react-icons": "^4.6.0", "react-markdown": "8.0.3", + "react-spinners": "^0.13.7", "react-toastify": "^9.1.1", + "usehooks-ts": "^2.9.1", "yup": "^0.32.11", "yup-phone": "^1.3.2" }, diff --git a/pages/_app.tsx b/pages/_app.tsx index 9a88c49..73bbcfc 100644 --- a/pages/_app.tsx +++ b/pages/_app.tsx @@ -1,6 +1,8 @@ import { SessionProvider } from "next-auth/react"; import { AppProps } from "next/app"; -import { useEffect } from "react"; +import { useEffect, useState } from "react"; +import Router from 'next/router' +import Loader from '../components/Loader'; import 'bootstrap/dist/css/bootstrap.css' import "../styles/globals.css"; @@ -8,19 +10,39 @@ import 'react-toastify/dist/ReactToastify.css'; import { ToastContainer } from 'react-toastify'; import Layout from "../components/Layout"; +import { GlobalContextProvider } from '../context/globalContext'; + + + const App = ({ Component, pageProps }: AppProps) => { + + const [isLoading, setIsLoading] = useState(false); + useEffect(() => { import("bootstrap/dist/js/bootstrap"); - }, []); + Router.events.on("routeChangeStart", (url) => { + setIsLoading(true) + }); + Router.events.on("routeChangeComplete", (url) => { + setIsLoading(false) + }); + Router.events.on("routeChangeError", (url) => { + setIsLoading(false) + }); + }, [Router]); return ( - - - - - - - + <> + {isLoading && } + + + + + + + + + ); }; diff --git a/pages/admin.tsx b/pages/admin.tsx new file mode 100644 index 0000000..5141444 --- /dev/null +++ b/pages/admin.tsx @@ -0,0 +1,354 @@ +import React, { useEffect, useState, useSyncExternalStore } from "react"; +import prisma from '../lib/prisma' + + +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 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 { register, setValue, handleSubmit, formState: { errors } } = useForm({ + }); + + const fetcher = async (url, method, body = {}) => { + try { + await fetch(url, { + method, + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + }) + .then((res) => res.json()) + .then(async (data) => { + setResponse(data); + setUsers(data.res) + 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: User) => { + setCurrentUser(user); + setValue("name", user.name) + setValue("email", user.email) + setValue("surname", user.surname) + setValue("address", user.address) + setValue("zipCode", user.zipCode) + setValue("phoneNumber", user.phoneNumber) + } + + return ( + <> + + Administration + + + +
+
+
+
+
+
+

Utilisateurs

+
+ {users.length <= 0 &&

Pas encore d'utilisateur

} + {users.length >= 1 && + + + + + + + + + + + + {users.map((info: User, index: number) => { + return selectUser(info)}> + + + + + + + + })} + +
#NomPrénomEmailTypes
{++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 && + + + + + + + + + + + + + {currentUser?.gains.map((gain: Gain, index: number) => { + return + + + + + + + })} + +
#Codes jouésCadeauxRetiré en magasinRetraitDate Retrait
{++index}{gain?.codeCadeau}{props.produits[gain.produitId - 1].nomProduit}{gain?.retrait ? '❌ déja récupéré' : '✔️ disponible'} + +
+ } +
+
+ + +
+
+
+ ) +}; + +export default Admin; + + diff --git a/pages/api/auth/[...nextauth].ts b/pages/api/auth/[...nextauth].ts index 38ab104..2daf7dd 100644 --- a/pages/api/auth/[...nextauth].ts +++ b/pages/api/auth/[...nextauth].ts @@ -5,6 +5,7 @@ import { PrismaAdapter } from '@next-auth/prisma-adapter' import GoogleProvider from "next-auth/providers/google"; import EmailProvider from 'next-auth/providers/email' import prisma from '../../../lib/prisma' +import { Session } from "@prisma/client"; const authHandler: NextApiHandler = (req, res) => NextAuth(req, res, options); @@ -32,14 +33,17 @@ const options = { adapter: PrismaAdapter(prisma), secret: process.env.SECRET, callbacks: { - async session({ session, user }) { + async session({ session, user }: { + session: any, + user: any + }) { const getCurrentUser = await prisma.user.findMany({ where: { email: session.user.email }, }) //récupération du role const { role } = getCurrentUser[0]; session.user.role = role - return session + return session; } }, pages: { diff --git a/pages/api/superadmin/index.ts b/pages/api/superadmin/index.ts deleted file mode 100644 index 5feae3f..0000000 --- a/pages/api/superadmin/index.ts +++ /dev/null @@ -1,36 +0,0 @@ - -import { NextApiRequest, NextApiResponse } from 'next'; -import { getSession } from 'next-auth/react'; -import { Role } from '../../../enum/role.enum'; -import prisma from '../../../lib/prisma'; - - -//api qui va rendre un utilisateur super admin (pour les developpeurs) -//--> http://localhost:3000/api/superadmin?pass=1234 (a effacer) - -export default async function makeMeSuper(req: NextApiRequest, res: NextApiResponse) { - const { pass } = req.query; - const session = await getSession({ req }) - const goodPassword = pass === '1234'; - - //si utilisateur connecté et que le parametre 'pass' est '1234' - if (session && goodPassword) { - - //MAJ de l'utilisateur en superadmin - await prisma.user.update({ - where: { email: session.user.email }, - data: { - role: Role.SUPERADMIN, - }, - }) - return res.status(200).send({ message: 'Profiled updated welcome SUPERADMIN !' }); - } else { - res.status(401).send({ message: 'Unauthorized' }) - } -} - - - - - - diff --git a/pages/api/testcode/index.ts b/pages/api/testcode/index.ts index aa16471..ef801ab 100644 --- a/pages/api/testcode/index.ts +++ b/pages/api/testcode/index.ts @@ -38,7 +38,7 @@ export default async function testCode(req: NextApiRequest, res: NextApiResponse }) //check si le code a déja été utilisé - if (!codeCadeauInfo.actif) { + if (!codeCadeauInfo.codeActif) { res.status(401).json({ err: 'Ce code a déja été utilisé' }); return; } @@ -57,9 +57,6 @@ export default async function testCode(req: NextApiRequest, res: NextApiResponse } }) - - //mise à jour de la date ou le ticket est utilisé - //retire un ticket du total de ticket restant const ticketUpdate = await prisma.ticketsRestants.update({ where: { @@ -78,7 +75,7 @@ export default async function testCode(req: NextApiRequest, res: NextApiResponse id: codeCadeauInfo.id }, data: { - actif: false, + codeActif: false, } }) diff --git a/pages/api/user/delete.ts b/pages/api/user/delete.ts new file mode 100644 index 0000000..4580229 --- /dev/null +++ b/pages/api/user/delete.ts @@ -0,0 +1,74 @@ +import prisma from '../../../lib/prisma'; +import chance from 'chance' +import cryptoRandomString from 'crypto-random-string'; + + +import { NextApiRequest, NextApiResponse } from 'next'; +import { getSession } from 'next-auth/react'; +import { Cadeaux } from '../../../enum/cadeaux.enum'; +import { Role } from '../../../enum/role.enum'; + + + +//API gain qui va generer un code cadeau qui sera sur la facture du client +//On part du principe qu'une 'API caisse'(qu'on ne gere pas) déclenche l'appel à l'API gain + +export default async function deleteUser(req: NextApiRequest, res: NextApiResponse) { + + + const session = await getSession({ req }) + const { selectedUserEmail } = req.body; + + // est-ce la méthode est DELETE ? + if (req.method !== ("DELETE")) { + throw new Error( + `The HTTP ${req.method} method is not supported at this route.` + ); + } + + // est-ce que utilisateur est connecté ? + if (!session) { + res.status(401).json({ err: "Vous devez être connecté" }); + return; + } + + //supprime l'utilisateur connecté + const user = await prisma.user.delete({ + where: { email: selectedUserEmail }, + }) + + // est-ce que utilisateur est un client classique ? Donc interdit pour lui de faire des updates + // A ACTIVER EN PRODUCTION + // if (user.role === 'USER') { + // res.status(401).json({ err: "Vous n'avez pas l'autorisation" }); + // return; + // } + + //////////////////////////////////////////////// + + + + //renvoi la liste des users mis à jour + const users = await prisma.user.findMany({}) + + res.status(200).send({ message: `L'utilisateur ${user.name} a été supprimé !`, res: users }); + +} + + + + + + + + + + + + + + + + + + diff --git a/pages/api/user/get-current.ts b/pages/api/user/get-current.ts new file mode 100644 index 0000000..711a117 --- /dev/null +++ b/pages/api/user/get-current.ts @@ -0,0 +1,102 @@ +import prisma from '../../../lib/prisma'; +import chance from 'chance' +import cryptoRandomString from 'crypto-random-string'; + + +import { NextApiRequest, NextApiResponse } from 'next'; +import { getSession } from 'next-auth/react'; +import { Cadeaux } from '../../../enum/cadeaux.enum'; +import { Role } from '../../../enum/role.enum'; + + + +//API gain qui va generer un code cadeau qui sera sur la facture du client +//On part du principe qu'une 'API caisse'(qu'on ne gere pas) déclenche l'appel à l'API gain + +export default async function getCurrent(req: NextApiRequest, res: NextApiResponse) { + const session = await getSession({ req }) + const { selectedUserRole, selectedUserEmail, selectedUserName, + selectedUserSurname, + selectedUserAddress, + selectedUserZipCode, + selectedUserPhoneNumber, } = req.body; + + + + // est-ce la méthode est un POST ou PUT? + if (req.method !== ("POST" || "PUT")) { + throw new Error( + `The HTTP ${req.method} method is not supported at this route.` + ); + } + + // est-ce que utilisateur est connecté ? + if (!session) { + res.status(401).json({ err: "Vous devez être connecté" }); + return; + } + + //récupération des informations de l'utilisateur connecté + const user = await prisma.user.findFirst({ + where: { email: session.user.email }, + }) + + // est-ce que utilisateur est un client classique ? Donc interdit pour lui de faire des updates + // A ACTIVER EN PRODUCTION + // if (user.role === 'USER') { + // res.status(401).json({ err: "Vous n'avez pas l'autorisation" }); + // return; + // } + + //////////////////////////////////////////////// + + + + //récupération des informations de l'utilisateur selectionné + const selectedUser = await prisma.user.findFirst({ + where: { email: selectedUserEmail }, + }) + + console.log('selectedUser', selectedUser); + + + //mise a jour des données pour l'utilisateur + const updatedUser = await prisma.user.update({ + where: { + email: selectedUserEmail, + + + + }, + data: { + name: selectedUserName || undefined, + surname: selectedUserSurname || undefined, + address: selectedUserAddress || undefined, + zipCode: selectedUserZipCode || undefined, + phoneNumber: selectedUserPhoneNumber || undefined, + email: selectedUserEmail || undefined, + role: selectedUserRole || undefined + }, + + }) + res.status(200).send({ message: `Les informations de ${selectedUserName} ont été mise à jours !`, res: updatedUser }); + +} + + + + + + + + + + + + + + + + + + diff --git a/pages/api/user/update.ts b/pages/api/user/update.ts new file mode 100644 index 0000000..850765f --- /dev/null +++ b/pages/api/user/update.ts @@ -0,0 +1,96 @@ +import prisma from '../../../lib/prisma'; +import chance from 'chance' +import cryptoRandomString from 'crypto-random-string'; + + +import { NextApiRequest, NextApiResponse } from 'next'; +import { getSession } from 'next-auth/react'; +import { Cadeaux } from '../../../enum/cadeaux.enum'; +import { Role } from '../../../enum/role.enum'; + + + +//API gain qui va generer un code cadeau qui sera sur la facture du client +//On part du principe qu'une 'API caisse'(qu'on ne gere pas) déclenche l'appel à l'API gain + +export default async function updateUser(req: NextApiRequest, res: NextApiResponse) { + + + + const session = await getSession({ req }) + const { selectedUserRole, selectedUserEmail, selectedUserName, + selectedUserSurname, + selectedUserAddress, + selectedUserZipCode, + selectedUserPhoneNumber } = req.body; + + // est-ce la méthode est un POST ou PUT? + // if (req.method !== ("POST" || 'PUT')) { + // throw new Error( + // `The HTTP ${req.method} method is not supported at this route.` + // ); + // } + + // est-ce que utilisateur est connecté ? + if (!session) { + res.status(401).json({ err: "Vous devez être connecté" }); + return; + } + + //récupération des informations de l'utilisateur connecté + const user = await prisma.user.findFirst({ + where: { email: session.user.email }, + }) + + // est-ce que utilisateur est un client classique ? Donc interdit pour lui de faire des updates + // A ACTIVER EN PRODUCTION + // if (user.role === 'USER') { + // res.status(401).json({ err: "Vous n'avez pas l'autorisation" }); + // return; + // } + + //////////////////////////////////////////////// + + + + //mise a jour des données de l'utilisateur séléctionné + const updatedUser = await prisma.user.update({ + where: { + email: selectedUserEmail, + }, + data: { + name: selectedUserName || undefined, + surname: selectedUserSurname || undefined, + address: selectedUserAddress || undefined, + zipCode: selectedUserZipCode || undefined, + phoneNumber: selectedUserPhoneNumber || undefined, + role: Role[selectedUserRole] || Role.USER + }, + + }) + + //renvoi la liste des users mis à jour + const users = await prisma.user.findMany({}) + + console.log(updatedUser); + res.status(200).send({ message: `Les informations de ${selectedUserEmail} ont été mise à jours !`, res: users }); + +} + + + + + + + + + + + + + + + + + + diff --git a/pages/connexion.tsx b/pages/connexion.tsx index d1a8709..58eacc6 100644 --- a/pages/connexion.tsx +++ b/pages/connexion.tsx @@ -76,7 +76,7 @@ const MainPage = ({ csrfToken }: Props) => { const onMailSubmit = async (data: LoginSubmitForm) => { if (onCheckTerms()) { - signIn("email", { email: data.email, callbackUrl: `${window.location.origin}/create` }) + signIn("email", { email: data.email, callbackUrl: `${window.location.origin}/mon-compte` }) } await trigger("acceptTerms"); await trigger("email"); diff --git a/pages/index.tsx b/pages/index.tsx index a6f889a..47b1821 100644 --- a/pages/index.tsx +++ b/pages/index.tsx @@ -217,7 +217,7 @@ const MainPage = () => {
setWinAnimation(false)} >
-

Vous avez gagnez : un {response.winProduct.nomProduit} !

+

Vous avez gagnez : un {response.winProduct.nomProduit.toLowerCase()} !

diff --git a/pages/mon-compte.tsx b/pages/mon-compte.tsx index bf62492..0800b8f 100644 --- a/pages/mon-compte.tsx +++ b/pages/mon-compte.tsx @@ -82,7 +82,7 @@ export async function getServerSideProps(context) { type Props = { user: User; - userGains: any; + userGains: Gain[]; } const MonCompte = (props: Props) => { @@ -196,7 +196,7 @@ const MonCompte = (props: Props) => {
- +
{errors.name?.message}
@@ -204,7 +204,7 @@ const MonCompte = (props: Props) => {
- +
{errors.surname?.message}
@@ -233,12 +233,12 @@ const MonCompte = (props: Props) => { -
+
@@ -257,14 +257,16 @@ const MonCompte = (props: Props) => { # Mes codes joué Mes cadeaux + Statut - {props.userGains.map((info: any) => { + {props.userGains.map((info: any, index: number) => { return - + {++index} {info.codeCadeau} {info.produit.nomProduit} + {info.produit.retrait ? '❌ déja récupéré' : '✔️ venir me chercher !'} })} diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 879562a..30b8351 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -53,7 +53,7 @@ model User { updatedAt DateTime @updatedAt @map(name: "updated_at") accounts Account[] sessions Session[] - gain Gain[] + gains Gain[] role Role @default(USER) @@map(name: "users") diff --git a/prisma/seed.ts b/prisma/seed.ts index bb97f82..117a53e 100644 --- a/prisma/seed.ts +++ b/prisma/seed.ts @@ -3,7 +3,7 @@ import { PrismaClient } from '@prisma/client'; import { generateGains } from './seed/gains' import { produitsData } from './seed/produits' -// import { userData } from './seed/user' +import { userData } from './seed/user' const prisma = new PrismaClient(); @@ -29,13 +29,13 @@ async function main() { ///////////////////////////////////////////////////// - //création des utilisateurs - // for (const u of userData) { - // const user = await prisma.user.create({ - // data: u, - // }) - // console.log(`Created user with id: ${user.id}`) - // } + // création des utilisateurs + for (const u of userData) { + const user = await prisma.user.create({ + data: u, + }) + console.log(`Created user with id: ${user.id}`) + } //création de 5 gains for (let i = 1; i <= 5; i++) { diff --git a/prisma/seed/gains.ts b/prisma/seed/gains.ts index 9ecc250..ac4b6e8 100644 --- a/prisma/seed/gains.ts +++ b/prisma/seed/gains.ts @@ -13,6 +13,8 @@ export const generateGains = async () => { const gainCreated = await prisma.gain.create({ data: { codeCadeau: randomNoGain, + codeActif: true, + retrait: false } }) diff --git a/prisma/seed/user.ts b/prisma/seed/user.ts index 1e19ad6..b1f839c 100644 --- a/prisma/seed/user.ts +++ b/prisma/seed/user.ts @@ -4,17 +4,19 @@ export const userData: Prisma.UserCreateInput[] = [ { name: 'Alice', email: 'alice@prisma.io', - + createdAt: new Date(), + role: 'USER' }, { - name: 'Nilu', - email: 'nilu@prisma.io', - + name: 'John', + email: 'john@prisma.io', + createdAt: new Date(), + role: 'SELLER' }, - }, -{ - name: 'Mahmoud', - email: 'mahmoud@prisma.io', - }, + { + name: 'Mosse', + email: 'mosse@prisma.io', + createdAt: new Date(), + role: 'USER' }, ] \ No newline at end of file diff --git a/styles/Connexion.module.css b/styles/Connexion.module.css index b86b1c0..1027061 100644 --- a/styles/Connexion.module.css +++ b/styles/Connexion.module.css @@ -9,6 +9,10 @@ z-index: 8888 } +.cursor:hover { + cursor: pointer; +} + .imageWrapper { display: block; } diff --git a/styles/Loader.module.css b/styles/Loader.module.css new file mode 100644 index 0000000..459bee2 --- /dev/null +++ b/styles/Loader.module.css @@ -0,0 +1,34 @@ +.wrapper { + width: 100%; + height: 100vh; + position: absolute; + top: 0; + left: 0; + background-color: rgb(0, 0, 0, 0.3); + backdrop-filter: blur(10px); + display: flex; + justify-content: center; + align-items: center; + z-index: 9999; +} + +/*code for custom loading icon*/ + +.loader { + border: 10px solid #f3f3f3; + border-radius: 50%; + border-top: 10px solid #505050; + width: 60px; + height: 60px; + animation: spin 2s linear infinite; +} + +@keyframes spin { + 0% { + transform: rotate(0deg); + } + + 100% { + transform: rotate(360deg); + } +} \ No newline at end of file diff --git a/styles/NavBar.module.css b/styles/NavBar.module.css index 3b281a4..957946c 100644 --- a/styles/NavBar.module.css +++ b/styles/NavBar.module.css @@ -17,11 +17,11 @@ /**************************/ .overlay { - height: 0; width: 100%; bottom: 100%; position: fixed; z-index: 9001; + top: 0; left: 0; background-color: rgb(0, 0, 0); @@ -36,14 +36,14 @@ .overlay-content { position: relative; - top: 25%; + height: 90%; + top: 10px; width: 100%; text-align: center; - margin-top: 30px; + margin-top: 5px; display: flex; flex-direction: column; align-items: center; - margin-top: 20vh; } .overlay a { @@ -70,6 +70,9 @@ } @media screen and (max-height: 450px) { + + + .overlay a { font-size: 20px } diff --git a/types/userGain.ts b/types/userGain.ts index 5dbd626..c6ca48c 100644 --- a/types/userGain.ts +++ b/types/userGain.ts @@ -5,5 +5,6 @@ export type UserGainProps = { dateRetrait: Date; produit: Produit; produitId: number; - actif: Boolean; + codeActif: true, + retrait: false } \ No newline at end of file