✅add : correction ajout de gain et api test code
This commit is contained in:
1 parent
04423aa6c7
commit
fec63499c6
16 files changed
+339
-83
No files matched your search
@@ -45,7 +45,7 @@ const options = {
|
||||
pages: {
|
||||
// signIn: '/auth/signin',
|
||||
// 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)
|
||||
// newUser: '/auth/new-user' // New users will be directed here on first sign in (leave the property out if not of interest)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
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';
|
||||
@@ -38,7 +40,8 @@ export default async function generationGain(req: NextApiRequest, res: NextApiRe
|
||||
if (isAdmin || isSuperAdmin) {
|
||||
|
||||
//creation d'un numéro de gain aléatoire
|
||||
const gainNumber = (Math.random() + 1).toString(36).substring(7).toUpperCase()
|
||||
const gainNumber = cryptoRandomString({ length: 10, type: 'distinguishable' });
|
||||
|
||||
|
||||
//création d'un id de produit de façon pondérée
|
||||
let weightedRandomGainId = chance().weighted([
|
||||
@@ -97,11 +100,6 @@ export default async function generationGain(req: NextApiRequest, res: NextApiRe
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import prisma from '../../../lib/prisma';
|
||||
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 tester le code cadeau
|
||||
|
||||
export default async function testCode(req: NextApiRequest, res: NextApiResponse) {
|
||||
const session = await getSession({ req })
|
||||
const { codeCadeau } = req.body;
|
||||
const regex = /[A-Z0-9]{10}/;
|
||||
|
||||
// est-ce la méthode est un POST ?
|
||||
if (req.method !== "POST") {
|
||||
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: 'Veuillez vous connecter' });
|
||||
return;
|
||||
}
|
||||
|
||||
//est-ce que le code tapé par l'utilisateur est valide ?
|
||||
const isValidCodeCadeau = codeCadeau.match(regex);
|
||||
if (!isValidCodeCadeau) {
|
||||
res.status(401).json({ err: 'Ce code est invalide' });
|
||||
return
|
||||
}
|
||||
|
||||
//si oui ? récupération des informations concernant le code
|
||||
const codeCadeauInfo = await prisma.gain.findUnique({
|
||||
where: { codeCadeau }
|
||||
})
|
||||
|
||||
//check si le code a déja été utilisé
|
||||
if (!codeCadeauInfo.actif) {
|
||||
res.status(401).json({ err: 'Ce code a déja été utilisé' });
|
||||
return;
|
||||
}
|
||||
|
||||
//CODE BON ? =>
|
||||
//récupération des informations de l'utilisateur connecté
|
||||
const getCurrentUser = await prisma.user.findMany({
|
||||
where: { email: session.user.email },
|
||||
})
|
||||
|
||||
//ajout du gain au profil de l'utilisateur
|
||||
const joinGainWithUser = await prisma.user.update({
|
||||
where: { id: getCurrentUser[0].id },
|
||||
data: {
|
||||
gain: {
|
||||
connect: {
|
||||
id: codeCadeauInfo.id
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
})
|
||||
|
||||
//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: {
|
||||
id: 1
|
||||
},
|
||||
data: {
|
||||
total: {
|
||||
decrement: 1
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
//passage du code en non-actif
|
||||
const codeUpdate = await prisma.gain.update({
|
||||
where: {
|
||||
id: codeCadeauInfo.id
|
||||
},
|
||||
data: {
|
||||
actif: false,
|
||||
dateRetrait: new Date()
|
||||
}
|
||||
})
|
||||
|
||||
//retourne l'id du produit
|
||||
res.status(200).send({ success: 'Vous avez gagner un gain !', productId: codeCadeauInfo.produitId });
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import React, { useEffect } from "react";
|
||||
import prisma from '../lib/prisma'
|
||||
|
||||
|
||||
import Image from 'next/image';
|
||||
import * as Yup from 'yup';
|
||||
import Head from "next/head";
|
||||
import { getCsrfToken, signIn, useSession } from "next-auth/react";
|
||||
import { yupResolver } from "@hookform/resolvers/yup";
|
||||
import { 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";
|
||||
|
||||
|
||||
|
||||
const AuthError = () => {
|
||||
|
||||
//va rediriger après 3 seconde
|
||||
useEffect(() => {
|
||||
setTimeout(() => {
|
||||
Router.push("/")
|
||||
}, 3000)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>Page Confirmation email</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-lg-6`}>
|
||||
<h1 className="fw-light">Un email a été envoyé</h1>
|
||||
<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
|
||||
</button>
|
||||
</div>
|
||||
</div >
|
||||
</div>
|
||||
</div>
|
||||
</>)
|
||||
};
|
||||
|
||||
export default AuthError;
|
||||
|
||||
|
||||
+2
-4
@@ -65,10 +65,8 @@ const MainPage = ({ csrfToken }: Props) => {
|
||||
resolver: yupResolver(validationSchema)
|
||||
});
|
||||
|
||||
|
||||
const acceptTermCheckBox = watch("acceptTerms")
|
||||
|
||||
|
||||
const connexionWithGoogle = async () => {
|
||||
if (onCheckTerms()) {
|
||||
signIn("google")
|
||||
@@ -76,7 +74,6 @@ const MainPage = ({ csrfToken }: Props) => {
|
||||
await trigger("acceptTerms");
|
||||
}
|
||||
|
||||
|
||||
const onMailSubmit = async (data: LoginSubmitForm) => {
|
||||
if (onCheckTerms()) {
|
||||
signIn("email", { email: data.email, callbackUrl: `${window.location.origin}/create` })
|
||||
@@ -87,7 +84,7 @@ const MainPage = ({ csrfToken }: Props) => {
|
||||
|
||||
|
||||
|
||||
const onCheckTerms = (): any => {
|
||||
const onCheckTerms = () => {
|
||||
if (acceptTermCheckBox) {
|
||||
return true;
|
||||
} else {
|
||||
@@ -101,6 +98,7 @@ const MainPage = ({ csrfToken }: Props) => {
|
||||
progress: undefined,
|
||||
theme: "light",
|
||||
});
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+54
-39
@@ -1,4 +1,4 @@
|
||||
import React from "react";
|
||||
import React, { useState } from "react";
|
||||
import Layout from "../components/Layout";
|
||||
import prisma from '../lib/prisma'
|
||||
|
||||
@@ -29,9 +29,6 @@ import { GetServerSideProps } from "next";
|
||||
|
||||
import { toast } from "react-toastify";
|
||||
|
||||
// // doesn't do anything, supposed to add the land in <html>
|
||||
// import "next.config.mjs";
|
||||
|
||||
|
||||
type CodeSubmitForm = {
|
||||
codeCadeau: string;
|
||||
@@ -40,9 +37,10 @@ type CodeSubmitForm = {
|
||||
|
||||
const MainPage = () => {
|
||||
const { data: session } = useSession();
|
||||
const [response, setResponse] = useState(null)
|
||||
|
||||
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 !"),
|
||||
});
|
||||
|
||||
const {
|
||||
@@ -55,43 +53,60 @@ const MainPage = () => {
|
||||
|
||||
const onSubmit = async (data: CodeSubmitForm) => {
|
||||
|
||||
toast.error(errors.codeCadeau?.message, {
|
||||
position: "top-center",
|
||||
autoClose: 5000,
|
||||
hideProgressBar: false,
|
||||
closeOnClick: true,
|
||||
pauseOnHover: true,
|
||||
draggable: true,
|
||||
progress: undefined,
|
||||
theme: "light",
|
||||
});
|
||||
|
||||
|
||||
|
||||
if (!session) {
|
||||
return <Layout>
|
||||
<p>Vous devez vous connecter pour tester votre !</p>
|
||||
</Layout>
|
||||
if (!errors) {
|
||||
if (!session) {
|
||||
return <Layout>
|
||||
<p>Vous devez vous connecter pour tester votre !</p>
|
||||
</Layout>
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// try {
|
||||
// const body = { bioValue: data.bio };
|
||||
// await fetch(`/api/profile`, {
|
||||
// method: "POST",
|
||||
// headers: { "Content-Type": "application/json" },
|
||||
// body: JSON.stringify(body),
|
||||
// })
|
||||
// .then((res) => res.json())
|
||||
// .then((data) => {
|
||||
// setResponse(data);
|
||||
// console.log('response', data);
|
||||
// })
|
||||
// await Router.push("/profile");
|
||||
// } catch (error) {
|
||||
// console.error(error);
|
||||
// }
|
||||
|
||||
|
||||
|
||||
try {
|
||||
const body = { codeCadeau: data.codeCadeau };
|
||||
await fetch(`/api/testcode`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
.then((res) => res.json())
|
||||
.then((data) => {
|
||||
setResponse(data);
|
||||
console.log('response', data);
|
||||
if (data.err) {
|
||||
console.log('ERR', data);
|
||||
toast.error(data.err, {
|
||||
position: "top-center",
|
||||
autoClose: 2000,
|
||||
hideProgressBar: false,
|
||||
closeOnClick: true,
|
||||
pauseOnHover: true,
|
||||
draggable: true,
|
||||
progress: undefined,
|
||||
theme: "light",
|
||||
});
|
||||
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",
|
||||
});
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('ERROR :', error);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -162,7 +177,7 @@ const MainPage = () => {
|
||||
|
||||
/>
|
||||
<small id="codeHelp" className="form-text text-muted">Code à usage unique</small>
|
||||
<div className="invalid-feedback alert alert-danger">{errors.codeCadeau?.message}</div>
|
||||
<div className="invalid-feedback">{errors.codeCadeau?.message}</div>
|
||||
</div>
|
||||
<div className="form-group mx-auto my-3 w-100">
|
||||
<button type="submit" className={`${style['aButton']} btn btn-primary`}>Découvrir mon cadeau !</button>
|
||||
|
||||
Reference in new issue
Block a user