✅add : correction ajout de gain et api test code

feature/page-admin
Eric 4 years ago
parent 04423aa6c7
commit fec63499c6

@ -20,4 +20,6 @@ EMAIL_FROM=thetiptop@test.com
DATABASE_URL="postgres://postgres:postgrespwd@127.0.0.1:5454/thetiptop" DATABASE_URL="postgres://postgres:postgrespwd@127.0.0.1:5454/thetiptop"
API_KEY=1234

@ -0,0 +1,12 @@
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
return NextResponse.redirect(new URL('/about-2', request.url))
}
// See "Matching Paths" below to learn more
export const config = {
matcher: '/api/',
}

93
package-lock.json generated

@ -15,6 +15,7 @@
"@types/nodemailer": "^6.4.6", "@types/nodemailer": "^6.4.6",
"bootstrap": "^5.2.2", "bootstrap": "^5.2.2",
"chance": "^1.1.9", "chance": "^1.1.9",
"crypto-random-string": "^3.0.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",
@ -421,9 +422,9 @@
} }
}, },
"node_modules/@types/lodash": { "node_modules/@types/lodash": {
"version": "4.14.188", "version": "4.14.189",
"resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.14.188.tgz", "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.14.189.tgz",
"integrity": "sha512-zmEmF5OIM3rb7SbLCFYoQhO4dGt2FRM9AMkxvA3LaADOF1n8in/zGJlWji9fmafLoNyz+FoL6FE0SLtGIArD7w==" "integrity": "sha512-kb9/98N6X8gyME9Cf7YaqIMvYGnBSWqEci6tiettE6iJWH1XdJz/PO8LB0GtLCG7x8dU3KWhZT+lA1a35127tA=="
}, },
"node_modules/@types/mdast": { "node_modules/@types/mdast": {
"version": "3.0.10", "version": "3.0.10",
@ -803,9 +804,9 @@
"dev": true "dev": true
}, },
"node_modules/comma-separated-tokens": { "node_modules/comma-separated-tokens": {
"version": "2.0.2", "version": "2.0.3",
"resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.2.tgz", "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz",
"integrity": "sha512-G5yTt3KQN4Yn7Yk4ed73hlZ1evrFKXeUW3086p3PRFNp7m2vIjI6Pg+Kgb+oyzhd9F2qdcoj67+y3SdxL5XWsg==", "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==",
"funding": { "funding": {
"type": "github", "type": "github",
"url": "https://github.com/sponsors/wooorm" "url": "https://github.com/sponsors/wooorm"
@ -831,6 +832,17 @@
"integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==", "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==",
"dev": true "dev": true
}, },
"node_modules/crypto-random-string": {
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/crypto-random-string/-/crypto-random-string-3.3.1.tgz",
"integrity": "sha512-5j88ECEn6h17UePrLi6pn1JcLtAiANa3KExyr9y9Z5vo2mv56Gh3I4Aja/B9P9uyMwyxNHAHWv+nE72f30T5Dg==",
"dependencies": {
"type-fest": "^0.8.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/csstype": { "node_modules/csstype": {
"version": "3.1.1", "version": "3.1.1",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.1.tgz", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.1.tgz",
@ -1902,9 +1914,9 @@
} }
}, },
"node_modules/preact": { "node_modules/preact": {
"version": "10.11.2", "version": "10.11.3",
"resolved": "https://registry.npmjs.org/preact/-/preact-10.11.2.tgz", "resolved": "https://registry.npmjs.org/preact/-/preact-10.11.3.tgz",
"integrity": "sha512-skAwGDFmgxhq1DCBHke/9e12ewkhc7WYwjuhHB8HHS8zkdtITXLRmUMTeol2ldxvLwYtwbFeifZ9uDDWuyL4Iw==", "integrity": "sha512-eY93IVpod/zG3uMF22Unl8h9KkrcKIRs2EGar8hwLZZDU1lkjph303V9HZBwufh2s736U6VXuhD109LYqPoffg==",
"funding": { "funding": {
"type": "opencollective", "type": "opencollective",
"url": "https://opencollective.com/preact" "url": "https://opencollective.com/preact"
@ -1996,9 +2008,9 @@
} }
}, },
"node_modules/react-hook-form": { "node_modules/react-hook-form": {
"version": "7.39.3", "version": "7.39.4",
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.39.3.tgz", "resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.39.4.tgz",
"integrity": "sha512-H/vwk1vBf+TiXuyW6+hWz+zCujiDO6NqHlN5sPE/a+NGKKGK95XTM65DZz3NmEgs2M20Wka+g4uv4VD367wDBA==", "integrity": "sha512-B0e78r9kR9L2M4A4AXGbHoA/vyv34sB/n8QWJAw33TFz8f5t9helBbYAeqnbvcQf1EYzJxKX/bGQQh9K+evCyQ==",
"engines": { "engines": {
"node": ">=12.22.0" "node": ">=12.22.0"
}, },
@ -2181,9 +2193,9 @@
} }
}, },
"node_modules/space-separated-tokens": { "node_modules/space-separated-tokens": {
"version": "2.0.1", "version": "2.0.2",
"resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.1.tgz", "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz",
"integrity": "sha512-ekwEbFp5aqSPKaqeY1PGrlGQxPNaq+Cnx4+bE2D8sciBQrHpbwoBbawqTN2+6jPs9IdWxxiUcN0K2pkczD3zmw==", "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==",
"funding": { "funding": {
"type": "github", "type": "github",
"url": "https://github.com/sponsors/wooorm" "url": "https://github.com/sponsors/wooorm"
@ -2349,6 +2361,14 @@
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.4.1.tgz", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.4.1.tgz",
"integrity": "sha512-tGyy4dAjRIEwI7BzsB0lynWgOpfqjUdq91XXAlIWD2OwKBH7oCl/GZG/HT4BOHrTlPMOASlMQ7veyTqpmRcrNA==" "integrity": "sha512-tGyy4dAjRIEwI7BzsB0lynWgOpfqjUdq91XXAlIWD2OwKBH7oCl/GZG/HT4BOHrTlPMOASlMQ7veyTqpmRcrNA=="
}, },
"node_modules/type-fest": {
"version": "0.8.1",
"resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.8.1.tgz",
"integrity": "sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA==",
"engines": {
"node": ">=8"
}
},
"node_modules/typeorm": { "node_modules/typeorm": {
"version": "0.2.45", "version": "0.2.45",
"resolved": "https://registry.npmjs.org/typeorm/-/typeorm-0.2.45.tgz", "resolved": "https://registry.npmjs.org/typeorm/-/typeorm-0.2.45.tgz",
@ -2992,9 +3012,9 @@
} }
}, },
"@types/lodash": { "@types/lodash": {
"version": "4.14.188", "version": "4.14.189",
"resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.14.188.tgz", "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.14.189.tgz",
"integrity": "sha512-zmEmF5OIM3rb7SbLCFYoQhO4dGt2FRM9AMkxvA3LaADOF1n8in/zGJlWji9fmafLoNyz+FoL6FE0SLtGIArD7w==" "integrity": "sha512-kb9/98N6X8gyME9Cf7YaqIMvYGnBSWqEci6tiettE6iJWH1XdJz/PO8LB0GtLCG7x8dU3KWhZT+lA1a35127tA=="
}, },
"@types/mdast": { "@types/mdast": {
"version": "3.0.10", "version": "3.0.10",
@ -3269,9 +3289,9 @@
"dev": true "dev": true
}, },
"comma-separated-tokens": { "comma-separated-tokens": {
"version": "2.0.2", "version": "2.0.3",
"resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.2.tgz", "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz",
"integrity": "sha512-G5yTt3KQN4Yn7Yk4ed73hlZ1evrFKXeUW3086p3PRFNp7m2vIjI6Pg+Kgb+oyzhd9F2qdcoj67+y3SdxL5XWsg==" "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg=="
}, },
"concat-map": { "concat-map": {
"version": "0.0.1", "version": "0.0.1",
@ -3290,6 +3310,14 @@
"integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==", "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==",
"dev": true "dev": true
}, },
"crypto-random-string": {
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/crypto-random-string/-/crypto-random-string-3.3.1.tgz",
"integrity": "sha512-5j88ECEn6h17UePrLi6pn1JcLtAiANa3KExyr9y9Z5vo2mv56Gh3I4Aja/B9P9uyMwyxNHAHWv+nE72f30T5Dg==",
"requires": {
"type-fest": "^0.8.1"
}
},
"csstype": { "csstype": {
"version": "3.1.1", "version": "3.1.1",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.1.tgz", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.1.tgz",
@ -3945,9 +3973,9 @@
} }
}, },
"preact": { "preact": {
"version": "10.11.2", "version": "10.11.3",
"resolved": "https://registry.npmjs.org/preact/-/preact-10.11.2.tgz", "resolved": "https://registry.npmjs.org/preact/-/preact-10.11.3.tgz",
"integrity": "sha512-skAwGDFmgxhq1DCBHke/9e12ewkhc7WYwjuhHB8HHS8zkdtITXLRmUMTeol2ldxvLwYtwbFeifZ9uDDWuyL4Iw==" "integrity": "sha512-eY93IVpod/zG3uMF22Unl8h9KkrcKIRs2EGar8hwLZZDU1lkjph303V9HZBwufh2s736U6VXuhD109LYqPoffg=="
}, },
"preact-render-to-string": { "preact-render-to-string": {
"version": "5.2.6", "version": "5.2.6",
@ -4016,9 +4044,9 @@
} }
}, },
"react-hook-form": { "react-hook-form": {
"version": "7.39.3", "version": "7.39.4",
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.39.3.tgz", "resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.39.4.tgz",
"integrity": "sha512-H/vwk1vBf+TiXuyW6+hWz+zCujiDO6NqHlN5sPE/a+NGKKGK95XTM65DZz3NmEgs2M20Wka+g4uv4VD367wDBA==", "integrity": "sha512-B0e78r9kR9L2M4A4AXGbHoA/vyv34sB/n8QWJAw33TFz8f5t9helBbYAeqnbvcQf1EYzJxKX/bGQQh9K+evCyQ==",
"requires": {} "requires": {}
}, },
"react-icons": { "react-icons": {
@ -4144,9 +4172,9 @@
"integrity": "sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==" "integrity": "sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw=="
}, },
"space-separated-tokens": { "space-separated-tokens": {
"version": "2.0.1", "version": "2.0.2",
"resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.1.tgz", "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz",
"integrity": "sha512-ekwEbFp5aqSPKaqeY1PGrlGQxPNaq+Cnx4+bE2D8sciBQrHpbwoBbawqTN2+6jPs9IdWxxiUcN0K2pkczD3zmw==" "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q=="
}, },
"string-width": { "string-width": {
"version": "4.2.3", "version": "4.2.3",
@ -4252,6 +4280,11 @@
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.4.1.tgz", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.4.1.tgz",
"integrity": "sha512-tGyy4dAjRIEwI7BzsB0lynWgOpfqjUdq91XXAlIWD2OwKBH7oCl/GZG/HT4BOHrTlPMOASlMQ7veyTqpmRcrNA==" "integrity": "sha512-tGyy4dAjRIEwI7BzsB0lynWgOpfqjUdq91XXAlIWD2OwKBH7oCl/GZG/HT4BOHrTlPMOASlMQ7veyTqpmRcrNA=="
}, },
"type-fest": {
"version": "0.8.1",
"resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.8.1.tgz",
"integrity": "sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA=="
},
"typeorm": { "typeorm": {
"version": "0.2.45", "version": "0.2.45",
"resolved": "https://registry.npmjs.org/typeorm/-/typeorm-0.2.45.tgz", "resolved": "https://registry.npmjs.org/typeorm/-/typeorm-0.2.45.tgz",

@ -18,6 +18,7 @@
"@types/nodemailer": "^6.4.6", "@types/nodemailer": "^6.4.6",
"bootstrap": "^5.2.2", "bootstrap": "^5.2.2",
"chance": "^1.1.9", "chance": "^1.1.9",
"crypto-random-string": "^3.0.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",
@ -41,4 +42,5 @@
"prisma": { "prisma": {
"seed": "ts-node prisma/seed.ts" "seed": "ts-node prisma/seed.ts"
} }
} }

@ -45,7 +45,7 @@ const options = {
pages: { pages: {
// signIn: '/auth/signin', // signIn: '/auth/signin',
// 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)
// newUser: '/auth/new-user' // New users will be directed here on first sign in (leave the property out if not of interest) // 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 prisma from '../../../lib/prisma';
import chance from 'chance' import chance from 'chance'
import cryptoRandomString from 'crypto-random-string';
import { NextApiRequest, NextApiResponse } from 'next'; import { NextApiRequest, NextApiResponse } from 'next';
import { getSession } from 'next-auth/react'; import { getSession } from 'next-auth/react';
@ -38,7 +40,8 @@ export default async function generationGain(req: NextApiRequest, res: NextApiRe
if (isAdmin || isSuperAdmin) { if (isAdmin || isSuperAdmin) {
//creation d'un numéro de gain aléatoire //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 //création d'un id de produit de façon pondérée
let weightedRandomGainId = chance().weighted([ 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;

@ -65,10 +65,8 @@ const MainPage = ({ csrfToken }: Props) => {
resolver: yupResolver(validationSchema) resolver: yupResolver(validationSchema)
}); });
const acceptTermCheckBox = watch("acceptTerms") const acceptTermCheckBox = watch("acceptTerms")
const connexionWithGoogle = async () => { const connexionWithGoogle = async () => {
if (onCheckTerms()) { if (onCheckTerms()) {
signIn("google") signIn("google")
@ -76,7 +74,6 @@ const MainPage = ({ csrfToken }: Props) => {
await trigger("acceptTerms"); await trigger("acceptTerms");
} }
const onMailSubmit = async (data: LoginSubmitForm) => { const onMailSubmit = async (data: LoginSubmitForm) => {
if (onCheckTerms()) { if (onCheckTerms()) {
signIn("email", { email: data.email, callbackUrl: `${window.location.origin}/create` }) 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) { if (acceptTermCheckBox) {
return true; return true;
} else { } else {
@ -101,6 +98,7 @@ const MainPage = ({ csrfToken }: Props) => {
progress: undefined, progress: undefined,
theme: "light", theme: "light",
}); });
return false
} }
} }

@ -1,4 +1,4 @@
import React from "react"; import React, { useState } from "react";
import Layout from "../components/Layout"; import Layout from "../components/Layout";
import prisma from '../lib/prisma' import prisma from '../lib/prisma'
@ -29,9 +29,6 @@ import { GetServerSideProps } from "next";
import { toast } from "react-toastify"; import { toast } from "react-toastify";
// // doesn't do anything, supposed to add the land in <html>
// import "next.config.mjs";
type CodeSubmitForm = { type CodeSubmitForm = {
codeCadeau: string; codeCadeau: string;
@ -40,9 +37,10 @@ type CodeSubmitForm = {
const MainPage = () => { const MainPage = () => {
const { data: session } = useSession(); const { data: session } = useSession();
const [response, setResponse] = useState(null)
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 !"),
}); });
const { const {
@ -55,43 +53,60 @@ const MainPage = () => {
const onSubmit = async (data: CodeSubmitForm) => { const onSubmit = async (data: CodeSubmitForm) => {
toast.error(errors.codeCadeau?.message, { if (!errors) {
position: "top-center", if (!session) {
autoClose: 5000, return <Layout>
hideProgressBar: false, <p>Vous devez vous connecter pour tester votre !</p>
closeOnClick: true, </Layout>
pauseOnHover: true, }
draggable: true, }
progress: undefined,
theme: "light",
});
if (!session) {
return <Layout>
<p>Vous devez vous connecter pour tester votre !</p>
</Layout>
}
// try { try {
// const body = { bioValue: data.bio }; const body = { codeCadeau: data.codeCadeau };
// await fetch(`/api/profile`, { await fetch(`/api/testcode`, {
// method: "POST", method: "POST",
// headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
// body: JSON.stringify(body), body: JSON.stringify(body),
// }) })
// .then((res) => res.json()) .then((res) => res.json())
// .then((data) => { .then((data) => {
// setResponse(data); setResponse(data);
// console.log('response', data); console.log('response', data);
// }) if (data.err) {
// await Router.push("/profile"); console.log('ERR', data);
// } catch (error) { toast.error(data.err, {
// console.error(error); 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> <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>
<div className="form-group mx-auto my-3 w-100"> <div className="form-group mx-auto my-3 w-100">
<button type="submit" className={`${style['aButton']} btn btn-primary`}>Découvrir mon cadeau !</button> <button type="submit" className={`${style['aButton']} btn btn-primary`}>Découvrir mon cadeau !</button>

@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Gain" ADD COLUMN "disponible" BOOLEAN NOT NULL DEFAULT true;

@ -0,0 +1,9 @@
/*
Warnings:
- You are about to drop the column `disponible` on the `Gain` table. All the data in the column will be lost.
*/
-- AlterTable
ALTER TABLE "Gain" DROP COLUMN "disponible",
ADD COLUMN "actif" BOOLEAN NOT NULL DEFAULT true;

@ -86,6 +86,7 @@ model Gain {
produitId Int? produitId Int?
user User? @relation(fields: [userId], references: [id]) user User? @relation(fields: [userId], references: [id])
userId Int? @unique userId Int? @unique
actif Boolean @default(true)
} }
model Produit { model Produit {

@ -1,5 +1,6 @@
import { PrismaClient } from '@prisma/client';
// import prisma from '../lib/prisma' // import prisma from '../lib/prisma'
import { PrismaClient } from '@prisma/client'
import { generateGains } from './seed/gains' import { generateGains } from './seed/gains'
import { produitsData } from './seed/produits' import { produitsData } from './seed/produits'
// import { userData } from './seed/user' // import { userData } from './seed/user'

@ -2,11 +2,12 @@
import prisma from '../../lib/prisma' import prisma from '../../lib/prisma'
import { Chance } from 'chance' import { Chance } from 'chance'
import { Cadeaux } from '../../enum/cadeaux.enum'; import { Cadeaux } from '../../enum/cadeaux.enum';
import cryptoRandomString from 'crypto-random-string';
let chance = new Chance(); let chance = new Chance();
export const generateGains = async () => { export const generateGains = async () => {
//génération d'un code cadeau //génération d'un code cadeau
const randomNoGain = (Math.random() + 1).toString(36).substring(7).toUpperCase() const randomNoGain = cryptoRandomString({ length: 10, type: 'distinguishable' });
//création d'un gain //création d'un gain
const gainCreated = await prisma.gain.create({ const gainCreated = await prisma.gain.create({
@ -46,3 +47,4 @@ export const generateGains = async () => {
console.log(`Created gain ! : ${gainUpdated.codeCadeau}`) console.log(`Created gain ! : ${gainUpdated.codeCadeau}`)
} }

@ -31,5 +31,8 @@
"compilerOptions": { "compilerOptions": {
"module": "commonjs" "module": "commonjs"
} }
} },
"type": "module"
} }

Loading…
Cancel
Save