Compare commits

..

No commits in common. 'master' and 'feature/cookie' have entirely different histories.

@ -1,2 +1,7 @@
{ {
"workbench.colorCustomizations": {
"activityBar.background": "#4C1F25",
"titleBar.activeBackground": "#6A2C34",
"titleBar.activeForeground": "#FEFCFC"
}
} }

2
Jenkinsfile vendored

@ -5,7 +5,7 @@ pipeline {
steps { steps {
sh '''echo " sh '''echo "
NEXTAUTH_URL=\'https://devops.dsp-archiwebo21-ad-ec-cb-mt.fr\' NEXTAUTH_URL=\'https://devops.dsp-archiwebo21-ad-ec-cb-mt.fr\'
DATABASE_URL="postgres://postgres:dandanalaa@127.0.0.1:5454/thetiptop" DATABASE_URL="postgres://postgres:dandanalaa@212.227.206.140:5454/thetiptop"
GITHUB_ID=YOUR_GITHUB_CLIENT_ID GITHUB_ID=YOUR_GITHUB_CLIENT_ID
GITHUB_SECRET=YOUR_GITHUB_CLIENT_SECRET GITHUB_SECRET=YOUR_GITHUB_CLIENT_SECRET

@ -29,10 +29,6 @@ const NavBar = () => {
const checkRole = () => { const checkRole = () => {
const isAdmin = ['SELLER', 'ADMIN', 'SUPERADMIN'].includes(session?.user['role']); const isAdmin = ['SELLER', 'ADMIN', 'SUPERADMIN'].includes(session?.user['role']);
console.log('isAdmin', isAdmin);
console.log('role', session?.user['role']);
return isAdmin ? setIsAdmin(true) : setIsAdmin(false); return isAdmin ? setIsAdmin(true) : setIsAdmin(false);
} }

@ -1,5 +0,0 @@
/** @type {import('next-sitemap').IConfig} */
module.exports = {
siteUrl: process.env.NEXTAUTH_URL || 'https://dsp-archiwebo21-ad-ec-cb-mt.fr/',
generateRobotsTxt: true
}

71
package-lock.json generated

@ -22,7 +22,6 @@
"js-confetti": "^0.11.0", "js-confetti": "^0.11.0",
"next": "13.0.2", "next": "13.0.2",
"next-auth": "4.16.4", "next-auth": "4.16.4",
"next-sitemap": "^3.1.42",
"nodemailer": "^6.8.0", "nodemailer": "^6.8.0",
"react": "18.2.0", "react": "18.2.0",
"react-chartjs-2": "^5.0.1", "react-chartjs-2": "^5.0.1",
@ -44,7 +43,6 @@
"@testing-library/user-event": "^14.4.3", "@testing-library/user-event": "^14.4.3",
"@tomfreudenberg/next-auth-mock": "^0.5.5", "@tomfreudenberg/next-auth-mock": "^0.5.5",
"@types/chance": "^1.1.3", "@types/chance": "^1.1.3",
"@types/dateformat": "^5.0.0",
"@types/jest": "^29.2.4", "@types/jest": "^29.2.4",
"@types/next-auth": "3.13.0", "@types/next-auth": "3.13.0",
"@types/node": "^18.11.9", "@types/node": "^18.11.9",
@ -668,11 +666,6 @@
"integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==", "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==",
"dev": true "dev": true
}, },
"node_modules/@corex/deepmerge": {
"version": "4.0.29",
"resolved": "https://registry.npmjs.org/@corex/deepmerge/-/deepmerge-4.0.29.tgz",
"integrity": "sha512-q/yVUnqckA8Do+EvAfpy7RLdumnBy9ZsducMUtZTvpdbJC7azEf1hGtnYYxm0QfphYxjwggv6XtH64prvS1W+A=="
},
"node_modules/@cspotcode/source-map-support": { "node_modules/@cspotcode/source-map-support": {
"version": "0.8.1", "version": "0.8.1",
"resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz",
@ -1967,12 +1960,6 @@
"integrity": "sha512-X6c6ghhe4/sQh4XzcZWSFaTAUOda38GQHmq9BUanYkOE/EO7ZrkazwKmtsj3xzTjkLWmwULE++23g3d3CCWaWw==", "integrity": "sha512-X6c6ghhe4/sQh4XzcZWSFaTAUOda38GQHmq9BUanYkOE/EO7ZrkazwKmtsj3xzTjkLWmwULE++23g3d3CCWaWw==",
"dev": true "dev": true
}, },
"node_modules/@types/dateformat": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/@types/dateformat/-/dateformat-5.0.0.tgz",
"integrity": "sha512-SZg4JdHIWHQGEokbYGZSDvo5wA4TLYPXaqhigs/wH+REDOejcJzgH+qyY+HtEUtWOZxEUkbhbdYPqQDiEgrXeA==",
"dev": true
},
"node_modules/@types/debug": { "node_modules/@types/debug": {
"version": "4.1.7", "version": "4.1.7",
"resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.7.tgz", "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.7.tgz",
@ -6430,14 +6417,6 @@
"node": "*" "node": "*"
} }
}, },
"node_modules/minimist": {
"version": "1.2.7",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.7.tgz",
"integrity": "sha512-bzfL1YUZsP41gmu/qjrEk0Q6i2ix/cVeAhbCbqH9u3zYutS1cLg00qhrD0M2MVdCcx4Sc0UpP2eBWo9rotpq6g==",
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/mkdirp": { "node_modules/mkdirp": {
"version": "1.0.4", "version": "1.0.4",
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz",
@ -6586,31 +6565,6 @@
"url": "https://github.com/sponsors/panva" "url": "https://github.com/sponsors/panva"
} }
}, },
"node_modules/next-sitemap": {
"version": "3.1.42",
"resolved": "https://registry.npmjs.org/next-sitemap/-/next-sitemap-3.1.42.tgz",
"integrity": "sha512-z/m440ZDCTxoE3FWbBWZLK66ZEh9e2R+j/Bm0d1Vo4PFkMi4yhWdIjWqhj//kyFyBvMYk3YWs8QQqVCCe15E6g==",
"funding": [
{
"url": "https://github.com/iamvishnusankar/next-sitemap.git"
}
],
"dependencies": {
"@corex/deepmerge": "^4.0.29",
"minimist": "^1.2.7"
},
"bin": {
"next-sitemap": "bin/next-sitemap.mjs",
"next-sitemap-cjs": "bin/next-sitemap.cjs"
},
"engines": {
"node": ">=14.18"
},
"peerDependencies": {
"@next/env": "*",
"next": "*"
}
},
"node_modules/nice-try": { "node_modules/nice-try": {
"version": "1.0.5", "version": "1.0.5",
"resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz", "resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz",
@ -9428,11 +9382,6 @@
"integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==", "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==",
"dev": true "dev": true
}, },
"@corex/deepmerge": {
"version": "4.0.29",
"resolved": "https://registry.npmjs.org/@corex/deepmerge/-/deepmerge-4.0.29.tgz",
"integrity": "sha512-q/yVUnqckA8Do+EvAfpy7RLdumnBy9ZsducMUtZTvpdbJC7azEf1hGtnYYxm0QfphYxjwggv6XtH64prvS1W+A=="
},
"@cspotcode/source-map-support": { "@cspotcode/source-map-support": {
"version": "0.8.1", "version": "0.8.1",
"resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz",
@ -10406,12 +10355,6 @@
"integrity": "sha512-X6c6ghhe4/sQh4XzcZWSFaTAUOda38GQHmq9BUanYkOE/EO7ZrkazwKmtsj3xzTjkLWmwULE++23g3d3CCWaWw==", "integrity": "sha512-X6c6ghhe4/sQh4XzcZWSFaTAUOda38GQHmq9BUanYkOE/EO7ZrkazwKmtsj3xzTjkLWmwULE++23g3d3CCWaWw==",
"dev": true "dev": true
}, },
"@types/dateformat": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/@types/dateformat/-/dateformat-5.0.0.tgz",
"integrity": "sha512-SZg4JdHIWHQGEokbYGZSDvo5wA4TLYPXaqhigs/wH+REDOejcJzgH+qyY+HtEUtWOZxEUkbhbdYPqQDiEgrXeA==",
"dev": true
},
"@types/debug": { "@types/debug": {
"version": "4.1.7", "version": "4.1.7",
"resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.7.tgz", "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.7.tgz",
@ -13629,11 +13572,6 @@
"brace-expansion": "^1.1.7" "brace-expansion": "^1.1.7"
} }
}, },
"minimist": {
"version": "1.2.7",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.7.tgz",
"integrity": "sha512-bzfL1YUZsP41gmu/qjrEk0Q6i2ix/cVeAhbCbqH9u3zYutS1cLg00qhrD0M2MVdCcx4Sc0UpP2eBWo9rotpq6g=="
},
"mkdirp": { "mkdirp": {
"version": "1.0.4", "version": "1.0.4",
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz",
@ -13726,15 +13664,6 @@
} }
} }
}, },
"next-sitemap": {
"version": "3.1.42",
"resolved": "https://registry.npmjs.org/next-sitemap/-/next-sitemap-3.1.42.tgz",
"integrity": "sha512-z/m440ZDCTxoE3FWbBWZLK66ZEh9e2R+j/Bm0d1Vo4PFkMi4yhWdIjWqhj//kyFyBvMYk3YWs8QQqVCCe15E6g==",
"requires": {
"@corex/deepmerge": "^4.0.29",
"minimist": "^1.2.7"
}
},
"nice-try": { "nice-try": {
"version": "1.0.5", "version": "1.0.5",
"resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz", "resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz",

@ -10,8 +10,7 @@
"build": "next build", "build": "next build",
"start": "next start", "start": "next start",
"db": "npx prisma migrate reset --force", "db": "npx prisma migrate reset --force",
"test": "playwright test", "test": "playwright test"
"postbuild": "next-sitemap"
}, },
"dependencies": { "dependencies": {
"@hookform/resolvers": "^2.9.10", "@hookform/resolvers": "^2.9.10",
@ -27,7 +26,6 @@
"js-confetti": "^0.11.0", "js-confetti": "^0.11.0",
"next": "13.0.2", "next": "13.0.2",
"next-auth": "4.16.4", "next-auth": "4.16.4",
"next-sitemap": "^3.1.42",
"nodemailer": "^6.8.0", "nodemailer": "^6.8.0",
"react": "18.2.0", "react": "18.2.0",
"react-chartjs-2": "^5.0.1", "react-chartjs-2": "^5.0.1",
@ -49,7 +47,6 @@
"@testing-library/user-event": "^14.4.3", "@testing-library/user-event": "^14.4.3",
"@tomfreudenberg/next-auth-mock": "^0.5.5", "@tomfreudenberg/next-auth-mock": "^0.5.5",
"@types/chance": "^1.1.3", "@types/chance": "^1.1.3",
"@types/dateformat": "^5.0.0",
"@types/jest": "^29.2.4", "@types/jest": "^29.2.4",
"@types/next-auth": "3.13.0", "@types/next-auth": "3.13.0",
"@types/node": "^18.11.9", "@types/node": "^18.11.9",

@ -21,18 +21,11 @@ import { Token } from "nodemailer/lib/xoauth2";
import { isGeneratorFunction } from "util/types"; import { isGeneratorFunction } from "util/types";
import { UserProps } from "../types/user"; import { UserProps } from "../types/user";
import { UserGainProps } from "../types/userGain"; import { UserGainProps } from "../types/userGain";
import { Gain, Produit, Role, User } from "@prisma/client"; import { Gain, Produit, Role, TicketsRestants, User } from "@prisma/client";
import { Doughnut } from "react-chartjs-2"; import { Doughnut } from "react-chartjs-2";
import { import { Chart as ChartJS, ArcElement, Tooltip, Legend, RadialLinearScale } from 'chart.js';
Chart as ChartJS, import { PolarArea } from 'react-chartjs-2';
CategoryScale,
LinearScale,
BarElement,
Title,
Tooltip,
Legend,
} from 'chart.js';
import { Bar } from 'react-chartjs-2';
type FormData = { type FormData = {
email: string; email: string;
@ -68,26 +61,8 @@ export async function getServerSideProps(context) {
} }
}); });
const ticketRestants = await prisma.gain.count({ const tickets = await prisma.gain.findMany({})
where: { const totalTirageRestant = await prisma.ticketsRestants.findFirst({})
dateAchat: {
not: null,
}
}
})
const ticketsSaisis = await prisma.gain.count({
where: {
codeActif: false,
},
})
const gainsRetires = await prisma.gain.count({
where: {
retrait: true
},
})
const produits = await prisma.produit.findMany({}) const produits = await prisma.produit.findMany({})
return { return {
@ -95,9 +70,8 @@ export async function getServerSideProps(context) {
user: JSON.parse(JSON.stringify(user)), user: JSON.parse(JSON.stringify(user)),
produits: JSON.parse(JSON.stringify(produits)), produits: JSON.parse(JSON.stringify(produits)),
users: JSON.parse(JSON.stringify(users)), users: JSON.parse(JSON.stringify(users)),
ticketRestants: JSON.parse(JSON.stringify(ticketRestants)), tickets: JSON.parse(JSON.stringify(tickets)),
ticketsSaisis: JSON.parse(JSON.stringify(ticketsSaisis)), totalTirageRestant: JSON.parse(JSON.stringify(totalTirageRestant))
gainsRetires: JSON.parse(JSON.stringify(gainsRetires)),
}, },
} }
} }
@ -106,12 +80,10 @@ type Props = {
user: User; user: User;
produits: Produit[]; produits: Produit[];
users: any, users: any,
ticketRestants: number, tickets: Gain[]
ticketsSaisis: number, totalTirageRestant: TicketsRestants
gainsRetires: number,
} }
const Admin = (props: Props) => { const Admin = (props: Props) => {
const { data: session, status } = useSession(); const { data: session, status } = useSession();
const [response, setResponse] = useState(null) const [response, setResponse] = useState(null)
@ -121,56 +93,58 @@ const Admin = (props: Props) => {
const [query, setQuery] = useState(""); const [query, setQuery] = useState("");
const router = useRouter() const router = useRouter()
const isAdmin = session?.user['role'] === Role.ADMIN const isAdmin = session?.user['role'] === Role.ADMIN
const isSuperAdmin = session?.user['role'] === Role.SUPERADMIN const isSuperAdmin = session?.user['role'] === Role.SUPERADMIN
const bigWinner = users?.find((user) => user?.isBigWinner) const bigWinner = users?.find((user) => user?.isBigWinner)
ChartJS.register( ChartJS.register(RadialLinearScale, ArcElement, Tooltip, Legend);
CategoryScale,
LinearScale, const TicketRestants = props.tickets?.filter(ticket => ticket.codeActif === true).length
BarElement, console.log("🚀 ~ file: admin.tsx:103 ~ Admin ~ TicketRestants", TicketRestants)
Title, const TicketUtilise = props.tickets?.filter(ticket => ticket.codeActif === false).length
Tooltip, console.log("🚀 ~ file: admin.tsx:104 ~ Admin ~ TicketUtilise", TicketUtilise)
Legend const TicketTotal = props.totalTirageRestant.total;
); console.log("🚀 ~ file: admin.tsx:107 ~ Admin ~ TicketTotal", TicketTotal)
const labels = ['Tickets générés', 'Codes saisis', 'Cadeaux récupérés'];
const data = { const TotalTirageRestant = props.totalTirageRestant?.total;
labels: labels,
datasets: [{ const ticketDataChart = {
data: [props.ticketRestants, props.ticketsSaisis, props.gainsRetires], labels: ['Tickets généré utlisés', 'Tickets généré restants'],
datasets: [
{
label: 'Tickets restants généré',
data: [TicketUtilise, TicketRestants],
backgroundColor: [ backgroundColor: [
'rgba(255, 99, 132, 0.2)', 'rgba(255, 99, 132, 0.2)',
'rgba(255, 159, 64, 0.2)', 'rgba(54, 162, 235, 0.2)',
'rgba(255, 205, 86, 0.2)',
], ],
borderColor: [ borderColor: [
'rgb(255, 99, 132)', 'rgba(255, 99, 132, 1)',
'rgb(255, 159, 64)', 'rgba(54, 162, 235, 1)',
'rgb(255, 205, 86)',
], ],
borderWidth: 1 borderWidth: 1,
}]
};
const options = {
responsive: true,
plugins: {
legend: {
display: false
},
title: {
display: false,
},
}, },
],
}; };
const numberWithSpaces = (x: number): string => { const TotalTirageRestantData = {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " "); labels: ['Total tirage restant'],
datasets: [
{
label: 'Tirage de ticket',
data: [TotalTirageRestant],
backgroundColor: [
'rgba(54, 162, 235, 0.5)',
],
borderWidth: 1,
},
],
} }
const { register, setValue, handleSubmit, formState: { errors } } = useForm<FormData>({ const { register, setValue, handleSubmit, formState: { errors } } = useForm<FormData>({
}); });
@ -186,19 +160,7 @@ const Admin = (props: Props) => {
setResponse(data); setResponse(data);
callback; callback;
if (data.err) { if (data.err) {
toastError(data.err); toast.error(data.err, {
return;
}
toastSuccess(data.message);
})
}
catch (error) {
console.error('ERROR :', error);
}
}
const toastError = (text: string) => {
toast.error(text, {
position: "top-center", position: "top-center",
autoClose: 2000, autoClose: 2000,
hideProgressBar: false, hideProgressBar: false,
@ -208,10 +170,9 @@ const Admin = (props: Props) => {
progress: undefined, progress: undefined,
theme: "light", theme: "light",
}); });
return;
} }
toast.success(data.message, {
const toastSuccess = (text: string) => {
toast.success(text, {
position: "top-center", position: "top-center",
autoClose: 5000, autoClose: 5000,
hideProgressBar: false, hideProgressBar: false,
@ -221,6 +182,11 @@ const Admin = (props: Props) => {
progress: undefined, progress: undefined,
theme: "light", theme: "light",
}); });
})
}
catch (error) {
console.error('ERROR :', error);
}
} }
const onSubmit = async ({ const onSubmit = async ({
@ -252,13 +218,19 @@ const Admin = (props: Props) => {
const onDeleteUser = async (userEmail: string) => { const onDeleteUser = async (userEmail: string) => {
const body = { selectedUserEmail: userEmail } const body = { selectedUserEmail: userEmail }
if (props.user.email === userEmail) { if (props.user.email === userEmail) {
toastError('Vous devez être déconnecté pour supprimer votre compte') toast.error('Vous devez être déconnecté pour supprimer votre compte', {
position: "top-center",
autoClose: 2000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
});
return; return;
} }
fetcher('/api/user/delete', 'DELETE', body) fetcher('/api/user/delete', 'DELETE', body)
setTimeout(() => {
router.refresh();
}, 2000)
}; };
const selectUser = (user: any) => { const selectUser = (user: any) => {
@ -284,19 +256,38 @@ const Admin = (props: Props) => {
const customers = users.filter((user) => user.role === 'USER') const customers = users.filter((user) => user.role === 'USER')
if (users.length <= 0) { if (users.length <= 0) {
toastError("Il n'y a pas encore d'utilisateur") toast.error("Il n'y a pas encore d'utilisateur", {
position: "top-center",
autoClose: 2000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
});
return; return;
} }
const customersWithTicket = customers.filter((user) => user.gains.length >= 1) const customersWithTicket = customers.filter((user) => user.gains.length >= 1)
if (customersWithTicket.length <= 0) { if (customersWithTicket.length <= 0) {
toastError("Il n'y a pas encore d'utilisateurs ayant joué"); toast.error("Il n'y a pas encore d'utilisateurs ayant joué", {
position: "top-center",
autoClose: 2000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
});
return; return;
} }
const winUser = customersWithTicket[Math.floor(Math.random() * customersWithTicket.length)] const winUser = customersWithTicket[Math.floor(Math.random() * customersWithTicket.length)]
const body = { selectedUserEmail: winUser.email } const body = { selectedUserEmail: winUser.email }
console.log(body)
fetcher('/api/user/bigwinner', 'PUT', body) fetcher('/api/user/bigwinner', 'PUT', body)
setTimeout(() => { setTimeout(() => {
router.refresh(); router.refresh();
@ -315,7 +306,7 @@ const Admin = (props: Props) => {
const filtered = searchFilter(props.users) const filtered = searchFilter(props.users)
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => { const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setQuery(e.target.value); setQuery(e.target.value)
} }
return ( return (
@ -333,13 +324,17 @@ const Admin = (props: Props) => {
<hr /> <hr />
<h1 className="fw-light">Dashboard Administration</h1> <h1 className="fw-light">Dashboard Administration</h1>
<hr /> <hr />
<div className="container" style={{ width: '30vw' }}> <div className="container" style={{ width: '30vw' }}>
<div className="row"> <div className="row">
<div className="col-12 justify-content-center"> <div className="col-12 justify-content-center">
<p>Total tirages restant 📈 {numberWithSpaces(props.ticketRestants).toString()}</p> <p>Total tirages restant 📈 {props.totalTirageRestant?.total?.toString()}</p>
<Bar options={options} data={data} /> <Doughnut
data={ticketDataChart} />
</div> </div>
</div> </div>
</div> </div>
@ -366,7 +361,7 @@ const Admin = (props: Props) => {
<th scope="col">Nom</th> <th scope="col">Nom</th>
<th scope="col">Prénom</th> <th scope="col">Prénom</th>
<th scope="col">Email</th> <th scope="col">Email</th>
{session?.user['role'] !== Role.SELLER && <th scope="col">Types</th>} <th scope="col">Types</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@ -376,7 +371,7 @@ const Admin = (props: Props) => {
<td>{info.surname}</td> <td>{info.surname}</td>
<td>{info.name}</td> <td>{info.name}</td>
<td>{info.isBigWinner && '🎁'}{info.email}</td> <td>{info.isBigWinner && '🎁'}{info.email}</td>
{session?.user['role'] !== Role.SELLER && <td> {info.role !== Role.SELLER && <td>
<select className="custom-select" defaultValue={info.role} onChange={(e) => onChangeRole(e, info)}> <select className="custom-select" defaultValue={info.role} onChange={(e) => onChangeRole(e, info)}>
<option value="USER">Client</option> <option value="USER">Client</option>
<option value="SELLER">Vendeur</option> <option value="SELLER">Vendeur</option>
@ -384,7 +379,7 @@ const Admin = (props: Props) => {
{isSuperAdmin && <option value="SUPERADMIN">SuperAdmin</option>} {isSuperAdmin && <option value="SUPERADMIN">SuperAdmin</option>}
</select> </select>
</td>} </td>}
{session?.user['role'] !== Role.SELLER && <td><button className="btn btn-primary" onClick={() => onDeleteUser(info.email)}>Supprimer</button></td>} {info.role !== Role.SELLER && <td><button className="btn btn-primary" onClick={() => onDeleteUser(info.email)}>Supprimer</button></td>}
</tr>; </tr>;
})} })}
</tbody> </tbody>

@ -0,0 +1,99 @@
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';
import process from 'process';
//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
//--> http://localhost:3000/api/apiGain?pass=... (a effacer)
export default async function apiGain(req: NextApiRequest, res: NextApiResponse) {
const { pass } = req.query;
const goodPassword = pass === 'P9RDK2b47x1XQV5s3fSaW6erGpzTNudk8jZwCycJYtMHAqhEnm';
if (!process.env.ACTION_API) {
return res.status(401).send({ message: 'Unauthorized' })
}
//récuperation des tickets disponible
const getTickets = await prisma.ticketsRestants.findFirst({
where: {
id: 1
},
})
const { total } = getTickets;
const isTicketsAvaible = total > 0;
if (isTicketsAvaible && goodPassword) {
//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
}
}
})
return res.status(200).send({ message: 'Gain has been generated !', result: gainResult });
} else {
return res.status(401).send({ message: 'Unauthorized' })
}
}

@ -23,7 +23,7 @@ export default async function testCode(req: NextApiRequest, res: NextApiResponse
//est-ce que le code tapé par l'utilisateur est valide ? //est-ce que le code tapé par l'utilisateur est valide ?
const isValidCodeCadeau = codeCadeau.match(regex); const isValidCodeCadeau = codeCadeau.match(regex);
if (!isValidCodeCadeau) { if (!isValidCodeCadeau) {
res.status(406).json({ err: 'Ce code est invalide' }); res.status(401).json({ err: 'Ce code est invalide' });
return return
} }
@ -32,15 +32,9 @@ export default async function testCode(req: NextApiRequest, res: NextApiResponse
where: { codeCadeau } where: { codeCadeau }
}) })
//si l'API gain n'a pas instancié une date pour ce gain
if (!codeCadeauInfo.dateAchat) {
res.status(406).json({ err: 'Ce code est invalide' });
return;
}
//check si le code a déja été utilisé //check si le code a déja été utilisé
if (!codeCadeauInfo.codeActif) { if (!codeCadeauInfo.codeActif) {
res.status(406).json({ err: 'Ce code a déja été utilisé' }); res.status(401).json({ err: 'Ce code a déja été utilisé' });
return; return;
} }
@ -51,16 +45,27 @@ export default async function testCode(req: NextApiRequest, res: NextApiResponse
}) })
//ajout du gain au profil de l'utilisateur //ajout du gain au profil de l'utilisateur
await prisma.gain.update({ const joinGain = await prisma.gain.update({
where: { codeCadeau: codeCadeauInfo.codeCadeau }, where: { codeCadeau: codeCadeauInfo.codeCadeau },
data: { data: {
userId: getCurrentUser[0].id 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 //passage du code en non-actif
await prisma.gain.update({ const codeUpdate = await prisma.gain.update({
where: { where: {
id: codeCadeauInfo.id id: codeCadeauInfo.id
}, },

@ -1,49 +0,0 @@
import prisma from '../../../lib/prisma';
import { NextApiRequest, NextApiResponse } from 'next';
import { getSession } from 'next-auth/react';
export default async function updateOrCreate(req: NextApiRequest, res: NextApiResponse) {
const session = await getSession({ req })
const { targetUserMail } = req.body;
// est-ce la méthode est un POST ou PUT?
if (!(['POST'].indexOf(req.method) > -1)) {
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: "Vous devez être connecté" });
return;
}
//récupération des informations de l'utilisateur connecté
const user = await prisma.user.findFirst({
where: { email: targetUserMail },
})
res.status(200).send({ message: 'user :', res: user });
}

@ -51,7 +51,7 @@ export default async function updtateGift(req: NextApiRequest, res: NextApiRespo
include: { gains: true } include: { gains: true }
}) })
return res.status(200).send({ message: `Le gain a été mis à jour !`, res: updatedCurrentUser }); return res.status(200).send({ message: `Le gain a ont été mis à jour !`, res: updatedCurrentUser });
} }

@ -45,6 +45,14 @@ const Index = () => {
} = useForm<CodeSubmitForm>(); } = useForm<CodeSubmitForm>();
const onSubmit = async (data: CodeSubmitForm) => { const onSubmit = async (data: CodeSubmitForm) => {
if (!errors) {
if (!session) {
return <Layout>
<p>Vous devez vous connecter pour tester votre code cadeau!</p>
</Layout>
}
}
try { try {
const body = { codeCadeau: data.codeCadeau }; const body = { codeCadeau: data.codeCadeau };
await fetch(`/api/testcode`, { await fetch(`/api/testcode`, {
@ -75,7 +83,7 @@ const Index = () => {
} catch (error) { } catch (error) {
console.error('ERROR :', error); console.error('ERROR :', error);
} }
} };
const confettiTime = async (): Promise<void> => { const confettiTime = async (): Promise<void> => {
const JSConfetti = (await import('js-confetti')).default const JSConfetti = (await import('js-confetti')).default
@ -157,7 +165,7 @@ const Index = () => {
<div className={`${style['imageWrapper']}`}> <div className={`${style['imageWrapper']}`}>
<Image <Image
src={testerCodeCadeau} src={testerCodeCadeau}
alt="Tester le code cadeau" alt="thetiptop navigation logo"
layout="responsive" layout="responsive"
className={`${style['rotatingImage']}`} className={`${style['rotatingImage']}`}
/> />

@ -60,10 +60,14 @@ model User {
@@map(name: "users") @@map(name: "users")
} }
model TicketsRestants {
id Int @id @default(autoincrement())
total Int
}
model Gain { model Gain {
id Int @id @default(autoincrement()) id Int @id @default(autoincrement())
codeCadeau String @unique codeCadeau String @unique
dateAchat DateTime?
dateRetrait DateTime? dateRetrait DateTime?
produit Produit? @relation(fields: [produitId], references: [id]) produit Produit? @relation(fields: [produitId], references: [id])
produitId Int? produitId Int?

@ -1,6 +1,7 @@
import { PrismaClient } from '@prisma/client'; import { PrismaClient } from '@prisma/client';
// import prisma from '../lib/prisma' // import prisma from '../lib/prisma'
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'
@ -9,6 +10,14 @@ const prisma = new PrismaClient();
async function main() { async function main() {
console.log(`Start seeding ...`) console.log(`Start seeding ...`)
//création des tickets restants
const tickets = await prisma.ticketsRestants.create({
data: {
total: 1500000
},
})
console.log(`Created ticket: ${tickets.total}`)
//création des produits //création des produits
for (const p of produitsData) { for (const p of produitsData) {
@ -28,6 +37,11 @@ async function main() {
console.log(`Created user with id: ${user.id}`) console.log(`Created user with id: ${user.id}`)
} }
//création de gains
for (let i = 1; i <= (50); i++) {
await generateGains();
}
console.log(`Seeding finished.`) console.log(`Seeding finished.`)
} }

@ -0,0 +1,52 @@
// import { produits } from './produits';
import prisma from '../../lib/prisma'
import { Chance } from 'chance'
import { Cadeaux } from '../../enum/cadeaux.enum';
import cryptoRandomString from 'crypto-random-string';
let chance = new Chance();
export const generateGains = async () => {
//génération d'un code cadeau
const randomNoGain = cryptoRandomString({ length: 10, type: 'distinguishable' });
//création d'un gain
const gainCreated = await prisma.gain.create({
data: {
codeCadeau: randomNoGain,
codeActif: true,
retrait: false
}
})
//crétion d'un id de produit de façon pondérée
let weightedRandomGain = chance.weighted([
Cadeaux.GrandCoffretDecouverte,
Cadeaux.CoffretDecouverte,
Cadeaux.TheSignature,
Cadeaux.TheDetox,
Cadeaux.Infuseur],
[4, 6, 10, 20, 60]);
//mise à jour du gain avec l'id de produit pondéré
const gainUpdated = await prisma.gain.update({
where: { id: gainCreated.id },
data: {
produitId: weightedRandomGain,
}
})
//on retire 1 ticket
await prisma.ticketsRestants.update({
where: {
id: 1
},
data: {
total: {
decrement: 1
}
}
})
console.log(`Created gain ! : ${gainUpdated.codeCadeau}`)
}

@ -11,7 +11,7 @@ export const userData: Prisma.UserCreateInput[] = [
name: 'John', name: 'John',
email: 'john@prisma.io', email: 'john@prisma.io',
createdAt: new Date(), createdAt: new Date(),
role: 'USER' role: 'SELLER'
}, },
{ {
name: 'Mosse', name: 'Mosse',
@ -19,59 +19,4 @@ export const userData: Prisma.UserCreateInput[] = [
createdAt: new Date(), createdAt: new Date(),
role: 'USER' role: 'USER'
}, },
{
name: 'doug',
email: 'doug@prisma.io',
createdAt: new Date(),
role: 'USER'
},
{
name: 'molda',
email: 'molda@prisma.io',
createdAt: new Date(),
role: 'USER'
},
{
name: 'pierro',
email: 'pierro@prisma.io',
createdAt: new Date(),
role: 'USER'
},
{
name: 'brian',
email: 'brian@prisma.io',
createdAt: new Date(),
role: 'USER'
},
{
name: 'benji',
email: 'benji@prisma.io',
createdAt: new Date(),
role: 'USER'
},
{
name: 'abdel',
email: 'abdel@prisma.io',
createdAt: new Date(),
role: 'USER'
},
{
name: 'guillaume',
email: 'guillaume@prisma.io',
createdAt: new Date(),
role: 'USER'
},
{
name: 'roger',
email: 'roger@prisma.io',
createdAt: new Date(),
role: 'USER'
},
{
name: 'jacko',
email: 'jacko@prisma.io',
createdAt: new Date(),
role: 'USER'
},
] ]

@ -1,11 +0,0 @@
# *
User-agent: *
Allow: /*
Disallow: /admin
Disallow: /mon-compte
# Host
Host: https://dsp-archiwebo21-ad-ec-cb-mt.fr
# Sitemaps
Sitemap: https://dsp-archiwebo21-ad-ec-cb-mt.fr/sitemap.xml

@ -1,13 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:news="http://www.google.com/schemas/sitemap-news/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:mobile="http://www.google.com/schemas/sitemap-mobile/1.0" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xmlns:video="http://www.google.com/schemas/sitemap-video/1.1">
<url><loc>https://dsp-archiwebo21-ad-ec-cb-mt.fr</loc><lastmod>2022-12-15T20:38:21.840Z</lastmod><changefreq>daily</changefreq><priority>0.7</priority></url>
<url><loc>https://dsp-archiwebo21-ad-ec-cb-mt.fr/admin</loc><lastmod>2022-12-15T20:38:21.840Z</lastmod><changefreq>daily</changefreq><priority>0.7</priority></url>
<url><loc>https://dsp-archiwebo21-ad-ec-cb-mt.fr/auth-error</loc><lastmod>2022-12-15T20:38:21.840Z</lastmod><changefreq>daily</changefreq><priority>0.7</priority></url>
<url><loc>https://dsp-archiwebo21-ad-ec-cb-mt.fr/cgu</loc><lastmod>2022-12-15T20:38:21.840Z</lastmod><changefreq>daily</changefreq><priority>0.7</priority></url>
<url><loc>https://dsp-archiwebo21-ad-ec-cb-mt.fr/connexion</loc><lastmod>2022-12-15T20:38:21.840Z</lastmod><changefreq>daily</changefreq><priority>0.7</priority></url>
<url><loc>https://dsp-archiwebo21-ad-ec-cb-mt.fr/contact</loc><lastmod>2022-12-15T20:38:21.840Z</lastmod><changefreq>daily</changefreq><priority>0.7</priority></url>
<url><loc>https://dsp-archiwebo21-ad-ec-cb-mt.fr/mentions-legales</loc><lastmod>2022-12-15T20:38:21.840Z</lastmod><changefreq>daily</changefreq><priority>0.7</priority></url>
<url><loc>https://dsp-archiwebo21-ad-ec-cb-mt.fr/mon-compte</loc><lastmod>2022-12-15T20:38:21.840Z</lastmod><changefreq>daily</changefreq><priority>0.7</priority></url>
<url><loc>https://dsp-archiwebo21-ad-ec-cb-mt.fr/tout-savoir</loc><lastmod>2022-12-15T20:38:21.840Z</lastmod><changefreq>daily</changefreq><priority>0.7</priority></url>
<url><loc>https://dsp-archiwebo21-ad-ec-cb-mt.fr/verify-request</loc><lastmod>2022-12-15T20:38:21.840Z</lastmod><changefreq>daily</changefreq><priority>0.7</priority></url>
</urlset>

@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap><loc>https://dsp-archiwebo21-ad-ec-cb-mt.fr/sitemap-0.xml</loc></sitemap>
</sitemapindex>

@ -1,18 +1,29 @@
#!/usr/bin/env sh #!/usr/bin/env sh
echo 'The following "npm" command builds your Node.js/React application for'
echo 'production in the local "build" directory (i.e. within the'
echo '"/var/jenkins_home/workspace/simple-node-js-react-app" directory),'
echo 'correctly bundles React in production mode and optimizes the build for'
echo 'the best performance.'
set -x set -x
npm run build npm run build
set +x set +x
echo 'The following "npm" command runs your Node.js/React application in'
echo 'development mode and makes the application available for web browsing.'
echo 'The "npm start" command has a trailing ampersand so that the command runs'
echo 'as a background process (i.e. asynchronously). Otherwise, this command'
echo 'can pause running builds of CI/CD applications indefinitely. "npm start"'
echo 'is followed by another command that retrieves the process ID (PID) value'
echo 'of the previously run process (i.e. "npm start") and writes this value to'
echo 'the file ".pidfile".'
set -x set -x
npm start & npm start &
sleep 1 sleep 1
echo $! > .pidfile echo $! > .pidfile
set +x set +x
echo 'Maintenant...' echo 'Now...'
echo 'Visiter https://devops.dsp-archiwebo21-ad-ec-cb-mt.fr/ ' echo 'Visit http://localhost:3000 to see your Node.js/React application in action.'
echo 'L_application tourne sur le docker jenkins sur via le port 3000 voici un ip a' echo '(This is why you specified the "args ''-p 3000:3000''" parameter when you'
ip a echo 'created your initial Pipeline as a Jenkinsfile.)'
echo 'Pour fermer l_application a appuyer sur le bouton proced'
Loading…
Cancel
Save