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.
106 lines
2.7 KiB
106 lines
2.7 KiB
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';
|
|
import { Cadeaux } from '../../../enum/cadeaux.enum';
|
|
import { Role } from '../../../enum/role.enum';
|
|
|
|
|
|
|
|
//API gain qui va generer un code cadeau qui sera sur la facture du client
|
|
//On part du principe qu'une 'API caisse'(qu'on ne gere pas) déclenche l'appel à l'API gain
|
|
|
|
export default async function generationGain(req: NextApiRequest, res: NextApiResponse) {
|
|
const session = await getSession({ req })
|
|
|
|
//récuperation des tickets disponible
|
|
const getTickets = await prisma.ticketsRestants.findFirst({
|
|
where: {
|
|
id: 1
|
|
},
|
|
})
|
|
|
|
const { total } = getTickets;
|
|
const isTicketsAvaible = total > 0;
|
|
|
|
//récupération des informations de l'utilisateur connecté
|
|
const getCurrentUser = await prisma.user.findMany({
|
|
where: { email: session.user.email },
|
|
})
|
|
|
|
//récupération du role
|
|
const { role } = getCurrentUser[0];
|
|
const isAdmin = role === Role.ADMIN;
|
|
const isSuperAdmin = Role.SUPERADMIN;
|
|
|
|
if (session && isTicketsAvaible) {
|
|
if (isAdmin || isSuperAdmin) {
|
|
|
|
//creation d'un numéro de gain aléatoire
|
|
const gainNumber = cryptoRandomString({ length: 10, type: 'distinguishable' });
|
|
|
|
|
|
//création d'un id de produit de façon pondérée
|
|
let weightedRandomGainId = chance().weighted([
|
|
Cadeaux.GrandCoffretDecouverte,
|
|
Cadeaux.CoffretDecouverte,
|
|
Cadeaux.TheSignature,
|
|
Cadeaux.TheDetox,
|
|
Cadeaux.Infuseur],
|
|
[4, 6, 10, 20, 60]);
|
|
|
|
//création d'un gain
|
|
const gainCreated = await prisma.gain.create({
|
|
data: {
|
|
codeCadeau: gainNumber,
|
|
}
|
|
})
|
|
|
|
//mise à jour du gain avec l'id de produit pondéré
|
|
const gainResult = await prisma.gain.update({
|
|
where: { id: gainCreated.id },
|
|
data: {
|
|
produitId: weightedRandomGainId,
|
|
}
|
|
})
|
|
|
|
//on retire 1 ticket
|
|
await prisma.ticketsRestants.update({
|
|
where: {
|
|
id: getTickets.id
|
|
},
|
|
data: {
|
|
total: {
|
|
decrement: 1
|
|
}
|
|
}
|
|
})
|
|
res.status(200).send({ message: 'Gain has been generated !', result: gainResult });
|
|
}
|
|
} else {
|
|
res.status(401).send({ message: 'Unauthorized' })
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|