✅ ajout de page mon compte - en cours

feature/page-admin
Eric 4 years ago
parent 7827aa119f
commit 65efdcac94

@ -40,15 +40,15 @@ const NavBar = () => {
<div className={`justify-content-center text-center ${style['hidden-mobile']}`}> <div className={`justify-content-center text-center ${style['hidden-mobile']}`}>
<Link href="/" legacyBehavior><a className={style.link} >Accueil</a></Link> | <Link href="/" legacyBehavior><a className={style.link} >Accueil </a></Link><p>|</p>
<Link href="/" legacyBehavior><a className={style.link} >Nos produits</a></Link> | <Link href="/" legacyBehavior><a className={style.link} >Nos produits</a></Link><p>|</p>
<Link href="/contact" legacyBehavior><a className={style.link} >Contactez-nous</a></Link> | <Link href="/contact" legacyBehavior><a className={style.link} >Contactez-nous</a></Link><p>|</p>
{!session && <Link href="/connexion" legacyBehavior><a className={style.link} >Connexion</a></Link>} {!session && <><Link href="/connexion" legacyBehavior><a className={style.link} >Connexion</a></Link></>}
{session && <Link href="/connexion" legacyBehavior><a className={style.link} >Mon compte</a></Link>} {session && <><Link href="/mon-compte" legacyBehavior><a className={style.link} >Mon compte</a></Link><p>|</p></>}
{session && <Link href="/" legacyBehavior><a onClick={() => signOut()} className={style.link} >Se déconnecter</a></Link>} {session && <><Link href="/" legacyBehavior><a onClick={() => signOut()} className={style.link} >Se déconnecter</a></Link></>}
{session && <span className={`${style.connexion} badge rounded-pill bg-light text-dark`}><FiArrowRight />{session.user.email}</span>} {session && <span className={`${style.connexion} badge rounded-pill bg-light text-dark`}>Vous-êtes connecté <FiArrowRight /> {session.user.email}</span>}
</div> </div>

1697
package-lock.json generated

File diff suppressed because it is too large Load Diff

@ -19,6 +19,7 @@
"bootstrap": "^5.2.2", "bootstrap": "^5.2.2",
"chance": "^1.1.9", "chance": "^1.1.9",
"crypto-random-string": "^3.0.0", "crypto-random-string": "^3.0.0",
"js-confetti": "^0.11.0",
"next": "13.0.2", "next": "13.0.2",
"next-auth": "4.16.4", "next-auth": "4.16.4",
"nodemailer": "^6.8.0", "nodemailer": "^6.8.0",
@ -28,7 +29,8 @@
"react-icons": "^4.6.0", "react-icons": "^4.6.0",
"react-markdown": "8.0.3", "react-markdown": "8.0.3",
"react-toastify": "^9.1.1", "react-toastify": "^9.1.1",
"yup": "^0.32.11" "yup": "^0.32.11",
"yup-phone": "^1.3.2"
}, },
"devDependencies": { "devDependencies": {
"@types/chance": "^1.1.3", "@types/chance": "^1.1.3",
@ -42,5 +44,4 @@
"prisma": { "prisma": {
"seed": "ts-node prisma/seed.ts" "seed": "ts-node prisma/seed.ts"
} }
} }

@ -43,7 +43,7 @@ const options = {
} }
}, },
pages: { pages: {
// signIn: '/auth/signin', signIn: '/mon-compte',
// signOut: '/auth/signout', // signOut: '/auth/signout',
error: '/auth/error', // Error code passed in query string as ?error= error: '/auth/error', // Error code passed in query string as ?error=
verifyRequest: '/verify-request', // (used for check email message) verifyRequest: '/verify-request', // (used for check email message)

@ -21,7 +21,7 @@ export default async function testCode(req: NextApiRequest, res: NextApiResponse
// est-ce que utilisateur est connecté ? // est-ce que utilisateur est connecté ?
if (!session) { if (!session) {
res.status(401).json({ err: 'Veuillez vous connecter' }); res.status(401).json({ err: 'Connectez-vous pour tester votre code !' });
return; return;
} }
@ -50,18 +50,14 @@ export default async function testCode(req: NextApiRequest, res: NextApiResponse
}) })
//ajout du gain au profil de l'utilisateur //ajout du gain au profil de l'utilisateur
const joinGainWithUser = await prisma.user.update({ const joinGain = await prisma.gain.update({
where: { id: getCurrentUser[0].id }, where: { codeCadeau: codeCadeauInfo.codeCadeau },
data: { data: {
gain: { userId: getCurrentUser[0].id
connect: {
id: codeCadeauInfo.id
}
}
} }
}) })
//mise à jour de la date ou le ticket est utilisé //mise à jour de la date ou le ticket est utilisé
//retire un ticket du total de ticket restant //retire un ticket du total de ticket restant
@ -83,12 +79,17 @@ export default async function testCode(req: NextApiRequest, res: NextApiResponse
}, },
data: { data: {
actif: false, actif: false,
dateRetrait: new Date()
} }
}) })
//retourne l'id du produit //retourne l'id du produit gagné
res.status(200).send({ success: 'Vous avez gagner un gain !', productId: codeCadeauInfo.produitId }); const winProduct = await prisma.produit.findFirst({
where: {
id: codeCadeauInfo.produitId
}
})
res.status(200).send({ success: 'Vous avez gagner un gain !', winProduct });
} }

@ -69,7 +69,7 @@ const MainPage = ({ csrfToken }: Props) => {
const connexionWithGoogle = async () => { const connexionWithGoogle = async () => {
if (onCheckTerms()) { if (onCheckTerms()) {
signIn("google") signIn("google", { callbackUrl: `${window.location.origin}/mon-compte` })
} }
await trigger("acceptTerms"); await trigger("acceptTerms");
} }

@ -28,20 +28,34 @@ import { GetServerSideProps } from "next";
import { toast } from "react-toastify"; 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 = { type CodeSubmitForm = {
codeCadeau: string; codeCadeau: string;
}; };
type ResponseData = {
success: string,
winProduct: {
actif: boolean,
id: number,
nomProduit: string,
prixTtc: number
}
}
const MainPage = () => { const MainPage = () => {
const { data: session } = useSession(); 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({ const validationSchema = Yup.object().shape({
// codeCadeau: Yup.string().trim().required("Veuillez rentrer un code cadeau !"), // codeCadeau: Yup.string().trim().required("Veuillez rentrer un code cadeau !"),
@ -55,21 +69,25 @@ const MainPage = () => {
resolver: yupResolver(validationSchema) resolver: yupResolver(validationSchema)
}); });
const mountedStyle = {
animation: "inAnimation 250ms ease-in"
};
const unmountedStyle = {
animation: "outAnimation 270ms ease-out",
animationFillMode: "forwards"
};
const onSubmit = async (data: CodeSubmitForm) => { const onSubmit = async (data: CodeSubmitForm) => {
if (!errors) { if (!errors) {
if (!session) { if (!session) {
return <Layout> return <Layout>
<p>Vous devez vous connecter pour tester votre !</p> <p>Vous devez vous connecter pour tester votre code cadeau!</p>
</Layout> </Layout>
} }
} }
try { try {
const body = { codeCadeau: data.codeCadeau }; const body = { codeCadeau: data.codeCadeau };
await fetch(`/api/testcode`, { await fetch(`/api/testcode`, {
@ -78,9 +96,8 @@ const MainPage = () => {
body: JSON.stringify(body), body: JSON.stringify(body),
}) })
.then((res) => res.json()) .then((res) => res.json())
.then((data) => { .then(async (data) => {
setResponse(data); setResponse(data);
console.log('response', data);
if (data.err) { if (data.err) {
console.log('ERR', data); console.log('ERR', data);
toast.error(data.err, { toast.error(data.err, {
@ -96,24 +113,23 @@ const MainPage = () => {
return; return;
// await Router.push("/profile"); // await Router.push("/profile");
} }
console.log('SUCESS', data); setWinAnimation(true)
toast.success(data.success, { await confettiTime();
position: "top-center",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
});
}) })
} catch (error) { } catch (error) {
console.error('ERROR :', 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 ( return (
<> <>
<Head> <Head>
@ -163,7 +179,7 @@ const MainPage = () => {
/> />
</div> </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['bloc-content']} col-12 col-md-6`}>
<div className={`${style['imageWrapper']}`}> <div className={`${style['imageWrapper']}`}>
<Image <Image
@ -193,7 +209,42 @@ const MainPage = () => {
</form> </form>
</div> </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> </div>

@ -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;

@ -28,6 +28,7 @@ type Produit = {
prixTtc: number; prixTtc: number;
} }
const ToutSavoir = ({ produits }: Props) => { const ToutSavoir = ({ produits }: Props) => {
console.log('p', produits); 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}> 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`}> <div className={`${style.aCard} card`}>
<Image <Image
className="card-img-top" src={test} className="card-img-top" src={LinkToProduit[produit.nomProduit]}
width="286" width="286"
height="180" height="180"
alt="produit" alt="produit"

@ -54,7 +54,7 @@ const VerifyRequest = () => {
<GrValidate size={100} /> <GrValidate size={100} />
<div className="d-grid mt-4"> <div className="d-grid mt-4">
<button onClick={() => Router.push("/")} type="button" className={`btn btn-primary`}> <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> </button>
</div> </div>
</div > </div >

@ -0,0 +1,31 @@
/*
Warnings:
- You are about to alter the column `prixTtc` on the `Produit` table. The data in that column could be lost. The data in that column will be cast from `Decimal(65,30)` to `Integer`.
- You are about to drop the `Post` table. If the table is not empty, all the data it contains will be lost.
- You are about to drop the `Profile` table. If the table is not empty, all the data it contains will be lost.
*/
-- DropForeignKey
ALTER TABLE "Post" DROP CONSTRAINT "Post_authorId_fkey";
-- DropForeignKey
ALTER TABLE "Profile" DROP CONSTRAINT "Profile_userId_fkey";
-- DropIndex
DROP INDEX "Gain_userId_key";
-- AlterTable
ALTER TABLE "Produit" ALTER COLUMN "prixTtc" SET DATA TYPE INTEGER;
-- AlterTable
ALTER TABLE "users" ADD COLUMN "address" TEXT,
ADD COLUMN "phoneNumber" TEXT,
ADD COLUMN "surname" TEXT,
ADD COLUMN "zipCode" TEXT;
-- DropTable
DROP TABLE "Post";
-- DropTable
DROP TABLE "Profile";

@ -42,37 +42,23 @@ model Session {
model User { model User {
id Int @id @default(autoincrement()) id Int @id @default(autoincrement())
name String? name String?
surname String?
address String?
zipCode String?
phoneNumber String?
email String? @unique email String? @unique
emailVerified DateTime? @map("email_verified") emailVerified DateTime? @map("email_verified")
image String? image String?
createdAt DateTime @default(now()) @map(name: "created_at") createdAt DateTime @default(now()) @map(name: "created_at")
updatedAt DateTime @updatedAt @map(name: "updated_at") updatedAt DateTime @updatedAt @map(name: "updated_at")
posts Post[]
accounts Account[] accounts Account[]
sessions Session[] sessions Session[]
profile Profile? gain Gain[]
gain Gain?
role Role @default(USER) role Role @default(USER)
@@map(name: "users") @@map(name: "users")
} }
model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
author User? @relation(fields: [authorId], references: [id])
authorId Int?
}
model Profile {
id Int @id @default(autoincrement())
bio String?
user User? @relation(fields: [userId], references: [id])
userId Int @unique
}
model TicketsRestants { model TicketsRestants {
id Int @id @default(autoincrement()) id Int @id @default(autoincrement())
total Int total Int
@ -85,7 +71,7 @@ model Gain {
produit Produit? @relation(fields: [produitId], references: [id]) produit Produit? @relation(fields: [produitId], references: [id])
produitId Int? produitId Int?
user User? @relation(fields: [userId], references: [id]) user User? @relation(fields: [userId], references: [id])
userId Int? @unique userId Int?
actif Boolean @default(true) actif Boolean @default(true)
} }

@ -15,7 +15,7 @@ export const produitsData: Prisma.ProduitCreateInput[] = [
prixTtc: 10, prixTtc: 10,
}, },
{ {
nomProduit: 'thé détox ou infusion', nomProduit: 'thé détox',
prixTtc: 6, prixTtc: 6,
}, },
{ {

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 552 KiB

@ -19,6 +19,26 @@
z-index: 9000; z-index: 9000;
} }
.cadeau-bloc-content {
text-shadow: rgb(255, 255, 255) 5px 0 10px;
color: rgb(0, 0, 0);
padding: 10vh;
border-radius: 10px;
background-image: url('/images/png/cadeauwin.png');
background-position: 50% 50%;
background-repeat: no-repeat;
background-size: contain;
animation: zoomInOut 2s ease-in-out infinite;
z-index: 9000;
}
.cadeau-bloc {
background: radial-gradient(circle, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 0) 100%);
animation: zoomInOut 1s ease-in-out infinite;
}
.zoomInOutCadeau { .zoomInOutCadeau {
animation: zoomInOut 1s ease-in-out infinite; animation: zoomInOut 1s ease-in-out infinite;
} }
@ -71,6 +91,7 @@
} }
@keyframes blinking { @keyframes blinking {
0%, 0%,
50%, 50%,
100% { 100% {
@ -91,11 +112,12 @@
display: block; display: block;
} }
.masthead .aButton { .aButton {
position: relative; position: relative;
z-index: 9992;
} }
.masthead .aButton:after { .aButton:after {
content: ""; content: "";
position: absolute; position: absolute;
@ -109,11 +131,12 @@
height: calc(100% + var(--aButton-base-padding)); height: calc(100% + var(--aButton-base-padding));
} }
.masthead .aButton:hover:after { .aButton:hover:after {
display: block; display: block;
animation: 0.7s linear infinite alternate expand; animation: 0.7s linear infinite alternate expand;
} }
@keyframes expand { @keyframes expand {
to { to {
left: calc(var(--aButton-base-padding) - var(--aButton-grow-padding)); left: calc(var(--aButton-base-padding) - var(--aButton-grow-padding));
@ -147,7 +170,10 @@
} }
.feuilleGauche, .feuilleDroite, .cadeau, .jeuConcours { .feuilleGauche,
.feuilleDroite,
.cadeau,
.jeuConcours {
position: absolute; position: absolute;
} }
@ -220,6 +246,30 @@
bottom: -20px; bottom: -20px;
} }
} }
@keyframes inAnimation {
0% {
opacity: 0;
visibility: hidden;
}
100% {
opacity: 1;
visibility: visible;
}
}
@keyframes outAnimation {
0% {
opacity: 1;
}
100% {
opacity: 0;
visibility: hidden;
}
}
/* @keyframes moveLeftRight { /* @keyframes moveLeftRight {
0%, 0%,
100% { 100% {

@ -1,4 +1,4 @@
.navbar{ .navbar {
display: table-header-group; display: table-header-group;
} }
@ -11,6 +11,7 @@
position: absolute; position: absolute;
top: 0; top: 0;
right: 0; right: 0;
margin: 2vh;
} }
/**************************/ /**************************/

@ -1,4 +1,9 @@
export type UserProps = { export type UserProps = {
role?: string; name: string;
email?: string role: string;
email: string;
surname?: string;
address?: string;
zipCode?: string;
phoneNumber?: string;
} }

@ -0,0 +1,9 @@
import { Produit } from ".prisma/client";
export type UserGainProps = {
codeCadeau: string;
dateRetrait: Date;
produit: Produit;
produitId: number;
actif: Boolean;
}
Loading…
Cancel
Save