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.
111 lines
2.6 KiB
111 lines
2.6 KiB
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 });
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|