✅ ajout de page mon compte - en cours

This commit is contained in:
eric committed 2022-12-02 03:27:55 +01:00
1 parent 7827aa119f
commit 65efdcac94
19 files changed
+2126 -92

No files matched your search

+1 -1
View File
@@ -43,7 +43,7 @@ const options = {
}
},
pages: {
// signIn: '/auth/signin',
signIn: '/mon-compte',
// signOut: '/auth/signout',
error: '/auth/error', // Error code passed in query string as ?error=
verifyRequest: '/verify-request', // (used for check email message)
+13 -12
View File
@@ -21,7 +21,7 @@ export default async function testCode(req: NextApiRequest, res: NextApiResponse
// est-ce que utilisateur est connecté ?
if (!session) {
res.status(401).json({ err: 'Veuillez vous connecter' });
res.status(401).json({ err: 'Connectez-vous pour tester votre code !' });
return;
}
@@ -50,18 +50,14 @@ export default async function testCode(req: NextApiRequest, res: NextApiResponse
})
//ajout du gain au profil de l'utilisateur
const joinGainWithUser = await prisma.user.update({
where: { id: getCurrentUser[0].id },
const joinGain = await prisma.gain.update({
where: { codeCadeau: codeCadeauInfo.codeCadeau },
data: {
gain: {
connect: {
id: codeCadeauInfo.id
}
}
userId: getCurrentUser[0].id
}
})
//mise à jour de la date ou le ticket est utilisé
//retire un ticket du total de ticket restant
@@ -83,12 +79,17 @@ export default async function testCode(req: NextApiRequest, res: NextApiResponse
},
data: {
actif: false,
dateRetrait: new Date()
}
})
//retourne l'id du produit
res.status(200).send({ success: 'Vous avez gagner un gain !', productId: codeCadeauInfo.produitId });
//retourne l'id du produit gagné
const winProduct = await prisma.produit.findFirst({
where: {
id: codeCadeauInfo.produitId
}
})
res.status(200).send({ success: 'Vous avez gagner un gain !', winProduct });
}
+1 -1
View File
@@ -69,7 +69,7 @@ const MainPage = ({ csrfToken }: Props) => {
const connexionWithGoogle = async () => {
if (onCheckTerms()) {
signIn("google")
signIn("google", { callbackUrl: `${window.location.origin}/mon-compte` })
}
await trigger("acceptTerms");
}
+76 -25
View File
@@ -28,20 +28,34 @@ import { GetServerSideProps } from "next";
import { toast } from "react-toastify";
import footerGrass from '../public/images/footer_image.webp'
// // doesn't do anything, supposed to add the land in <html>
// import "next.config.mjs";
import arrowUp from '../public/images/png/arrowup.png'
import footerGrass from '../public/images/footer_image.webp'
type CodeSubmitForm = {
codeCadeau: string;
};
type ResponseData = {
success: string,
winProduct: {
actif: boolean,
id: number,
nomProduit: string,
prixTtc: number
}
}
const MainPage = () => {
const { data: session } = useSession();
const [response, setResponse] = useState(null)
const [response, setResponse] = useState<ResponseData | null>(null)
const [winAnimation, setWinAnimation] = useState(false)
const validationSchema = Yup.object().shape({
// codeCadeau: Yup.string().trim().required("Veuillez rentrer un code cadeau !"),
@@ -55,21 +69,25 @@ const MainPage = () => {
resolver: yupResolver(validationSchema)
});
const mountedStyle = {
animation: "inAnimation 250ms ease-in"
};
const unmountedStyle = {
animation: "outAnimation 270ms ease-out",
animationFillMode: "forwards"
};
const onSubmit = async (data: CodeSubmitForm) => {
if (!errors) {
if (!session) {
return <Layout>
<p>Vous devez vous connecter pour tester votre !</p>
<p>Vous devez vous connecter pour tester votre code cadeau!</p>
</Layout>
}
}
try {
const body = { codeCadeau: data.codeCadeau };
await fetch(`/api/testcode`, {
@@ -78,9 +96,8 @@ const MainPage = () => {
body: JSON.stringify(body),
})
.then((res) => res.json())
.then((data) => {
.then(async (data) => {
setResponse(data);
console.log('response', data);
if (data.err) {
console.log('ERR', data);
toast.error(data.err, {
@@ -96,24 +113,23 @@ const MainPage = () => {
return;
// await Router.push("/profile");
}
console.log('SUCESS', data);
toast.success(data.success, {
position: "top-center",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
});
setWinAnimation(true)
await confettiTime();
})
} catch (error) {
console.error('ERROR :', error);
}
};
const confettiTime = async (): Promise<void> => {
const JSConfetti = (await import('js-confetti')).default
const jsConfetti = new JSConfetti()
jsConfetti.addConfetti()
}
const getCadeau = () => {
Router.push("/mon-compte")
}
return (
<>
<Head>
@@ -163,7 +179,7 @@ const MainPage = () => {
/>
</div>
<div className="col-12 align-items-center d-flex flex-column">
{!winAnimation && <div className="col-12 align-items-center d-flex flex-column">
<div className={`${style['bloc-content']} col-12 col-md-6`}>
<div className={`${style['imageWrapper']}`}>
<Image
@@ -193,7 +209,42 @@ const MainPage = () => {
</form>
</div>
</div>
</div>}
{winAnimation && <div className="col-12 align-items-center d-flex flex-column">
<div className={`${style['cadeau-bloc-content']} col-12 col-md-6`} onClick={() => setWinAnimation(false)}
>
<div className={`${style['cadeau-bloc']}`}>
<h1>Vous avez gagnez : un {response.winProduct.nomProduit} !</h1>
</div>
</div>
<div className={`${style['imageWrapper']}`}>
<Image
src={arrowUp}
alt="thetiptop flèche haute"
width={50}
height={50}
className={`${style['rotatingImage']}`}
/>
</div>
<div className="row">
<button onClick={getCadeau} className={`${style['aButton']} btn btn-primary`}>Voir mes cadeaux !</button>
<button onClick={() => setWinAnimation(false)} className={`${style['aButton']} btn btn-primary mt-2`}>Rejouer un ticket !</button>
</div>
</div>}
</div>
+235
View File
@@ -0,0 +1,235 @@
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 { GrValidate } from 'react-icons/gr'
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, User } from "@prisma/client";
type FormData = {
email: string;
name: string;
surname: string;
address: string;
zipCode: string;
phoneNumber: string;
};
export async function getServerSideProps(context) {
const session = await getSession(context)
const user = await prisma.user.findUnique({
where: {
email: session?.user.email
}
});
const userGains = await prisma.gain.findMany({
where: {
userId: user.id
},
include: {
produit: true
}
})
return {
props: {
user: JSON.parse(JSON.stringify(user)),
userGains: JSON.parse(JSON.stringify(userGains)),
},
}
}
type Props = {
user: User;
userGains: Gain;
}
const MonCompte = (props: Props) => {
const { data: session, status } = useSession();
useEffect(() => {
console.log('user', props.user);
console.log('userGains', props.userGains);
}, [])
const validationSchema = Yup.object().shape({
name: Yup.string()
.trim()
.min(2, "le nom doit comporter au moins 2 caractères")
.max(20, "le nom ne doit pas dépasser 20 caractères"),
surname: Yup.string()
.trim()
.min(2, "le prenom doit comporter au moins 2 caractères")
.max(20, "le prenom ne doit pas dépasser 20 caractères"),
address: Yup.string()
.trim()
.max(50, "l'adresse ne doit pas dépasser 50 caractères"),
zipCode: Yup.number()
.typeError("le code postal est invalide"),
phoneNumber: Yup.string()
.phone("FR", true, "le numéro de téléphone est invalide")
});
const { register, setValue, handleSubmit, formState: { errors } } = useForm<FormData>({
resolver: yupResolver(validationSchema)
});
const onSubmit: SubmitHandler<FormData> = data => console.log(data);
return (
<>
<Head>
<title>Mon Compte</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`}>
<h1 className="fw-light">Mon Compte</h1>
<hr />
<div className="row">
<div className="col-md-6 col-sm-12">
<h1 className="fw-light">Mes informations</h1>
<hr />
<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={session?.user.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' : ''}`} 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' : ''}`} 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' : ''}`} 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' : ''}`} 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' : ''}`} id="phoneNumber" placeholder="0123456789..." />
<div className="invalid-feedback alert alert-danger mt-2">{errors.phoneNumber?.message}</div>
</div>
</div>
<button
type="submit"
className="btn btn-primary mt-2"
>
Sauvegarder les changements
</button>
</div>
</form>
</div>
<div className="col-md-6 col-sm-12">
<h1 className="fw-light">Mes cadeaux</h1>
<hr />
{!props.userGains && <p>Pas encore de cadeau gagné</p>}
</div>
<table className="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Mes codes joué</th>
<th scope="col">Mes cadeaux</th>
<th scope="col">Handle</th>
</tr>
</thead>
<tbody>
{props.userGains.map((info: any) => {
<tr>
<th scope="row"></th>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
})}
</tbody>
</table>
</div>
</div >
</div>
</div >
</>)
};
export default MonCompte;
+2 -1
View File
@@ -28,6 +28,7 @@ type Produit = {
prixTtc: number;
}
const ToutSavoir = ({ produits }: Props) => {
console.log('p', produits);
@@ -56,7 +57,7 @@ const ToutSavoir = ({ produits }: Props) => {
return <div className="col-6 col-lg-3 d-flex justify-content-center my-2 my-lg-3" key={produit.id}>
<div className={`${style.aCard} card`}>
<Image
className="card-img-top" src={test}
className="card-img-top" src={LinkToProduit[produit.nomProduit]}
width="286"
height="180"
alt="produit"
+1 -1
View File
@@ -54,7 +54,7 @@ const VerifyRequest = () => {
<GrValidate size={100} />
<div className="d-grid mt-4">
<button onClick={() => Router.push("/")} type="button" className={`btn btn-primary`}>
Cliquez ici si vous n'êtes pas rediriger à l'accueil
Cliquez ici si vous n'êtes pas redirigé à l'accueil
</button>
</div>
</div >