You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
103 lines
2.4 KiB
103 lines
2.4 KiB
import prisma from '../../../lib/prisma';
|
|
import { NextApiRequest, NextApiResponse } from 'next';
|
|
import { getSession } from 'next-auth/react';
|
|
|
|
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: 'Connectez-vous pour tester votre code !' });
|
|
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.codeActif) {
|
|
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 joinGain = await prisma.gain.update({
|
|
where: { codeCadeau: codeCadeauInfo.codeCadeau },
|
|
data: {
|
|
userId: getCurrentUser[0].id
|
|
}
|
|
})
|
|
|
|
//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: {
|
|
codeActif: false,
|
|
}
|
|
})
|
|
|
|
//retourne l'id du produit gagné
|
|
const winProduct = await prisma.produit.findFirst({
|
|
where: {
|
|
id: codeCadeauInfo.produitId
|
|
}
|
|
})
|
|
return res.status(200).send({ success: 'Vous avez gagner un gain !', winProduct });
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|