⚡️ add - api generationGain , api superadmin , readme , fichier de seed

feature/page-admin
Eric 4 years ago
parent 141d9e53e8
commit e85117b2c7

@ -12,3 +12,7 @@ GOOGLE_CLIENT_SECRET=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
# Email (magic link) # Email (magic link)
EMAIL_SERVER=smtp://2bfdbee5372880:af828174d7f2ad@smtp.mailtrap.io:2525 EMAIL_SERVER=smtp://2bfdbee5372880:af828174d7f2ad@smtp.mailtrap.io:2525
EMAIL_FROM=thetiptop@test.com EMAIL_FROM=thetiptop@test.com
DATABASE_URL="postgres://postgres:postgrespwd@localhost:5432/thetiptop"

@ -1,4 +1,24 @@
# Fullstack Authentication Example with Next.js and NextAuth.js # Fullstack App with Next.js and NextAuth.js
docker compose up
pour créer les containers avec la base de donnée PosgreSQL et PGAdmin
npm install
npx prisma migrate dev
va hydrater la db et jouer le fichier de seed
npx prisma db
va reset la db et re-executer le fichier de seed
npm run dev
va lancer l'application sur le localhost:3000
npx prisma studio
pour naviguer dans la db via le localhost:5555
***********************************
This example shows how to implement a **fullstack app in TypeScript with [Next.js](https://nextjs.org/)** using [React](https://reactjs.org/) (frontend), [Next.js API routes](https://nextjs.org/docs/api-routes/introduction) and [Prisma Client](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client) (backend). It also demonstrates how to implement authentication using [NextAuth.js](https://next-auth.js.org/). The example uses an SQLite database file with some initial dummy data which you can find at [`./prisma/dev.db`](./prisma/dev.db). This example shows how to implement a **fullstack app in TypeScript with [Next.js](https://nextjs.org/)** using [React](https://reactjs.org/) (frontend), [Next.js API routes](https://nextjs.org/docs/api-routes/introduction) and [Prisma Client](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client) (backend). It also demonstrates how to implement authentication using [NextAuth.js](https://next-auth.js.org/). The example uses an SQLite database file with some initial dummy data which you can find at [`./prisma/dev.db`](./prisma/dev.db).

@ -0,0 +1,41 @@
version: '3.5'
services:
postgres:
container_name: postgres_container
image: postgres
environment:
POSTGRES_USER: ${POSTGRES_USER:-postgres}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-postgrespwd}
PGDATA: /data/postgres
volumes:
- postgres:/data/postgres
ports:
- "5432:5432"
networks:
- postgres
restart: unless-stopped
pgadmin:
container_name: pgadmin_container
image: dpage/pgadmin4
environment:
PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL:-pgadmin4@pgadmin.org}
PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_DEFAULT_PASSWORD:-admin}
PGADMIN_CONFIG_SERVER_MODE: 'False'
volumes:
- pgadmin:/var/lib/pgadmin
ports:
- "${PGADMIN_PORT:-5050}:80"
networks:
- postgres
restart: unless-stopped
networks:
postgres:
driver: bridge
volumes:
postgres:
pgadmin:

@ -0,0 +1,7 @@
export enum Cadeaux {
CoffretDecouvert69 = 1,
CoffretDecouvert39 = 2,
TheSignature = 3,
TheDetox = 4,
Infuseur = 5,
}

@ -0,0 +1,5 @@
export enum Role {
USER = 'USER',
ADMIN = 'ADMIN',
SUPERADMIN = 'SUPERADMIN'
}

84
package-lock.json generated

@ -11,8 +11,9 @@
"dependencies": { "dependencies": {
"@hookform/resolvers": "^2.9.10", "@hookform/resolvers": "^2.9.10",
"@next-auth/prisma-adapter": "1.0.5", "@next-auth/prisma-adapter": "1.0.5",
"@prisma/client": "4.6.0", "@prisma/client": "^4.6.1",
"bootstrap": "^5.2.2", "bootstrap": "^5.2.2",
"chance": "^1.1.9",
"next": "13.0.2", "next": "13.0.2",
"next-auth": "4.16.4", "next-auth": "4.16.4",
"react": "18.2.0", "react": "18.2.0",
@ -22,10 +23,11 @@
"yup": "^0.32.11" "yup": "^0.32.11"
}, },
"devDependencies": { "devDependencies": {
"@types/chance": "^1.1.3",
"@types/next-auth": "3.13.0", "@types/next-auth": "3.13.0",
"@types/node": "18.11.9", "@types/node": "18.11.9",
"@types/react": "18.0.25", "@types/react": "18.0.25",
"prisma": "4.6.0", "prisma": "^4.6.1",
"ts-node": "10.9.1", "ts-node": "10.9.1",
"typescript": "4.8.4" "typescript": "4.8.4"
} }
@ -323,12 +325,12 @@
} }
}, },
"node_modules/@prisma/client": { "node_modules/@prisma/client": {
"version": "4.6.0", "version": "4.6.1",
"resolved": "https://registry.npmjs.org/@prisma/client/-/client-4.6.0.tgz", "resolved": "https://registry.npmjs.org/@prisma/client/-/client-4.6.1.tgz",
"integrity": "sha512-D9LaQinDxOHinRpcJTw2tjMtjhc9HTP+aF1IRd2oLldp/8TiwIfxK8x17OhBBiX4y1PzbJXXET7kS+5wB3es/w==", "integrity": "sha512-M1+NNrMzqaOIxT7PBGcTs3IZo7d1EW/+gVQd4C4gUgWBDGgD9AcIeZnUSidgWClmpMSgVUdnVORjsWWGUameYA==",
"hasInstallScript": true, "hasInstallScript": true,
"dependencies": { "dependencies": {
"@prisma/engines-version": "4.6.0-53.2e719efb80b56a3f32d18a62489de95bb9c130e3" "@prisma/engines-version": "4.6.1-3.694eea289a8462c80264df36757e4fdc129b1b32"
}, },
"engines": { "engines": {
"node": ">=14.17" "node": ">=14.17"
@ -343,16 +345,16 @@
} }
}, },
"node_modules/@prisma/engines": { "node_modules/@prisma/engines": {
"version": "4.6.0", "version": "4.6.1",
"resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-4.6.0.tgz", "resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-4.6.1.tgz",
"integrity": "sha512-S+72PAl0zTCbIGou1uXD/McvzdtP+bjOs0LRmGZfcOQcVqR9x/0f6Z+dqpUU0zIcqHEl+0DOB8UXaTwRvssFsQ==", "integrity": "sha512-3u2/XxvxB+Q7cMXHnKU0CpBiUK1QWqpgiBv28YDo1zOIJE3FCF8DI2vrp6vuwjGt5h0JGXDSvmSf4D4maVjJdw==",
"devOptional": true, "devOptional": true,
"hasInstallScript": true "hasInstallScript": true
}, },
"node_modules/@prisma/engines-version": { "node_modules/@prisma/engines-version": {
"version": "4.6.0-53.2e719efb80b56a3f32d18a62489de95bb9c130e3", "version": "4.6.1-3.694eea289a8462c80264df36757e4fdc129b1b32",
"resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-4.6.0-53.2e719efb80b56a3f32d18a62489de95bb9c130e3.tgz", "resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-4.6.1-3.694eea289a8462c80264df36757e4fdc129b1b32.tgz",
"integrity": "sha512-0CTnfEuUbLlO6n1fM89ERDbSwI4LoyZn+1OKVSwG+aVqohj34+mXRfwOWIM0ONtYtLGGBpddvQAnAZkg+cgS6g==" "integrity": "sha512-HUCmkXAU2jqp2O1RvNtbE+seLGLyJGEABZS/R38rZjSAafAy0WzBuHq+tbZMnD+b5OSCsTVtIPVcuvx1ySxcWQ=="
}, },
"node_modules/@sqltools/formatter": { "node_modules/@sqltools/formatter": {
"version": "1.2.5", "version": "1.2.5",
@ -392,6 +394,12 @@
"integrity": "sha512-yOlFc+7UtL/89t2ZhjPvvB/DeAr3r+Dq58IgzsFkOAvVC6NMJXmCGjbptdXdR9qsX7pKcTL+s87FtYREi2dEEQ==", "integrity": "sha512-yOlFc+7UtL/89t2ZhjPvvB/DeAr3r+Dq58IgzsFkOAvVC6NMJXmCGjbptdXdR9qsX7pKcTL+s87FtYREi2dEEQ==",
"dev": true "dev": true
}, },
"node_modules/@types/chance": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/@types/chance/-/chance-1.1.3.tgz",
"integrity": "sha512-X6c6ghhe4/sQh4XzcZWSFaTAUOda38GQHmq9BUanYkOE/EO7ZrkazwKmtsj3xzTjkLWmwULE++23g3d3CCWaWw==",
"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",
@ -665,6 +673,11 @@
"url": "https://github.com/chalk/chalk?sponsor=1" "url": "https://github.com/chalk/chalk?sponsor=1"
} }
}, },
"node_modules/chance": {
"version": "1.1.9",
"resolved": "https://registry.npmjs.org/chance/-/chance-1.1.9.tgz",
"integrity": "sha512-TfxnA/DcZXRTA4OekA2zL9GH8qscbbl6X0ZqU4tXhGveVY/mXWvEQLt5GwZcYXTEyEFflVtj+pG8nc8EwSm1RQ=="
},
"node_modules/character-entities": { "node_modules/character-entities": {
"version": "2.0.2", "version": "2.0.2",
"resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.2.tgz", "resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.2.tgz",
@ -1897,13 +1910,13 @@
"integrity": "sha512-WuxUnVtlWL1OfZFQFuqvnvs6MiAGk9UNsBostyBOB0Is9wb5uRESevA6rnl/rkksXaGX3GzZhPup5d6Vp1nFew==" "integrity": "sha512-WuxUnVtlWL1OfZFQFuqvnvs6MiAGk9UNsBostyBOB0Is9wb5uRESevA6rnl/rkksXaGX3GzZhPup5d6Vp1nFew=="
}, },
"node_modules/prisma": { "node_modules/prisma": {
"version": "4.6.0", "version": "4.6.1",
"resolved": "https://registry.npmjs.org/prisma/-/prisma-4.6.0.tgz", "resolved": "https://registry.npmjs.org/prisma/-/prisma-4.6.1.tgz",
"integrity": "sha512-TAnObUMGCM9NLt9nsRs1WWYQGPKsJOK8bN/7gSAnBcYIxMCFFDe+XtFYJbyTzsJZ/i+0rH4zg8au3m7HX354LA==", "integrity": "sha512-BR4itMCuzrDV4tn3e2TF+nh1zIX/RVU0isKtKoN28ADeoJ9nYaMhiuRRkFd2TZN8+l/XfYzoRKyHzUFXLQhmBQ==",
"devOptional": true, "devOptional": true,
"hasInstallScript": true, "hasInstallScript": true,
"dependencies": { "dependencies": {
"@prisma/engines": "4.6.0" "@prisma/engines": "4.6.1"
}, },
"bin": { "bin": {
"prisma": "build/index.js", "prisma": "build/index.js",
@ -2863,23 +2876,23 @@
"peer": true "peer": true
}, },
"@prisma/client": { "@prisma/client": {
"version": "4.6.0", "version": "4.6.1",
"resolved": "https://registry.npmjs.org/@prisma/client/-/client-4.6.0.tgz", "resolved": "https://registry.npmjs.org/@prisma/client/-/client-4.6.1.tgz",
"integrity": "sha512-D9LaQinDxOHinRpcJTw2tjMtjhc9HTP+aF1IRd2oLldp/8TiwIfxK8x17OhBBiX4y1PzbJXXET7kS+5wB3es/w==", "integrity": "sha512-M1+NNrMzqaOIxT7PBGcTs3IZo7d1EW/+gVQd4C4gUgWBDGgD9AcIeZnUSidgWClmpMSgVUdnVORjsWWGUameYA==",
"requires": { "requires": {
"@prisma/engines-version": "4.6.0-53.2e719efb80b56a3f32d18a62489de95bb9c130e3" "@prisma/engines-version": "4.6.1-3.694eea289a8462c80264df36757e4fdc129b1b32"
} }
}, },
"@prisma/engines": { "@prisma/engines": {
"version": "4.6.0", "version": "4.6.1",
"resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-4.6.0.tgz", "resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-4.6.1.tgz",
"integrity": "sha512-S+72PAl0zTCbIGou1uXD/McvzdtP+bjOs0LRmGZfcOQcVqR9x/0f6Z+dqpUU0zIcqHEl+0DOB8UXaTwRvssFsQ==", "integrity": "sha512-3u2/XxvxB+Q7cMXHnKU0CpBiUK1QWqpgiBv28YDo1zOIJE3FCF8DI2vrp6vuwjGt5h0JGXDSvmSf4D4maVjJdw==",
"devOptional": true "devOptional": true
}, },
"@prisma/engines-version": { "@prisma/engines-version": {
"version": "4.6.0-53.2e719efb80b56a3f32d18a62489de95bb9c130e3", "version": "4.6.1-3.694eea289a8462c80264df36757e4fdc129b1b32",
"resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-4.6.0-53.2e719efb80b56a3f32d18a62489de95bb9c130e3.tgz", "resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-4.6.1-3.694eea289a8462c80264df36757e4fdc129b1b32.tgz",
"integrity": "sha512-0CTnfEuUbLlO6n1fM89ERDbSwI4LoyZn+1OKVSwG+aVqohj34+mXRfwOWIM0ONtYtLGGBpddvQAnAZkg+cgS6g==" "integrity": "sha512-HUCmkXAU2jqp2O1RvNtbE+seLGLyJGEABZS/R38rZjSAafAy0WzBuHq+tbZMnD+b5OSCsTVtIPVcuvx1ySxcWQ=="
}, },
"@sqltools/formatter": { "@sqltools/formatter": {
"version": "1.2.5", "version": "1.2.5",
@ -2919,6 +2932,12 @@
"integrity": "sha512-yOlFc+7UtL/89t2ZhjPvvB/DeAr3r+Dq58IgzsFkOAvVC6NMJXmCGjbptdXdR9qsX7pKcTL+s87FtYREi2dEEQ==", "integrity": "sha512-yOlFc+7UtL/89t2ZhjPvvB/DeAr3r+Dq58IgzsFkOAvVC6NMJXmCGjbptdXdR9qsX7pKcTL+s87FtYREi2dEEQ==",
"dev": true "dev": true
}, },
"@types/chance": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/@types/chance/-/chance-1.1.3.tgz",
"integrity": "sha512-X6c6ghhe4/sQh4XzcZWSFaTAUOda38GQHmq9BUanYkOE/EO7ZrkazwKmtsj3xzTjkLWmwULE++23g3d3CCWaWw==",
"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",
@ -3111,6 +3130,11 @@
"supports-color": "^7.1.0" "supports-color": "^7.1.0"
} }
}, },
"chance": {
"version": "1.1.9",
"resolved": "https://registry.npmjs.org/chance/-/chance-1.1.9.tgz",
"integrity": "sha512-TfxnA/DcZXRTA4OekA2zL9GH8qscbbl6X0ZqU4tXhGveVY/mXWvEQLt5GwZcYXTEyEFflVtj+pG8nc8EwSm1RQ=="
},
"character-entities": { "character-entities": {
"version": "2.0.2", "version": "2.0.2",
"resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.2.tgz", "resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.2.tgz",
@ -3892,12 +3916,12 @@
"integrity": "sha512-WuxUnVtlWL1OfZFQFuqvnvs6MiAGk9UNsBostyBOB0Is9wb5uRESevA6rnl/rkksXaGX3GzZhPup5d6Vp1nFew==" "integrity": "sha512-WuxUnVtlWL1OfZFQFuqvnvs6MiAGk9UNsBostyBOB0Is9wb5uRESevA6rnl/rkksXaGX3GzZhPup5d6Vp1nFew=="
}, },
"prisma": { "prisma": {
"version": "4.6.0", "version": "4.6.1",
"resolved": "https://registry.npmjs.org/prisma/-/prisma-4.6.0.tgz", "resolved": "https://registry.npmjs.org/prisma/-/prisma-4.6.1.tgz",
"integrity": "sha512-TAnObUMGCM9NLt9nsRs1WWYQGPKsJOK8bN/7gSAnBcYIxMCFFDe+XtFYJbyTzsJZ/i+0rH4zg8au3m7HX354LA==", "integrity": "sha512-BR4itMCuzrDV4tn3e2TF+nh1zIX/RVU0isKtKoN28ADeoJ9nYaMhiuRRkFd2TZN8+l/XfYzoRKyHzUFXLQhmBQ==",
"devOptional": true, "devOptional": true,
"requires": { "requires": {
"@prisma/engines": "4.6.0" "@prisma/engines": "4.6.1"
} }
}, },
"prop-types": { "prop-types": {

@ -8,13 +8,15 @@
"scripts": { "scripts": {
"dev": "next", "dev": "next",
"build": "next build", "build": "next build",
"start": "next start" "start": "next start",
"db": "npx prisma migrate reset --force"
}, },
"dependencies": { "dependencies": {
"@hookform/resolvers": "^2.9.10", "@hookform/resolvers": "^2.9.10",
"@next-auth/prisma-adapter": "1.0.5", "@next-auth/prisma-adapter": "1.0.5",
"@prisma/client": "4.6.0", "@prisma/client": "^4.6.1",
"bootstrap": "^5.2.2", "bootstrap": "^5.2.2",
"chance": "^1.1.9",
"next": "13.0.2", "next": "13.0.2",
"next-auth": "4.16.4", "next-auth": "4.16.4",
"react": "18.2.0", "react": "18.2.0",
@ -24,10 +26,11 @@
"yup": "^0.32.11" "yup": "^0.32.11"
}, },
"devDependencies": { "devDependencies": {
"@types/chance": "^1.1.3",
"@types/next-auth": "3.13.0", "@types/next-auth": "3.13.0",
"@types/node": "18.11.9", "@types/node": "18.11.9",
"@types/react": "18.0.25", "@types/react": "18.0.25",
"prisma": "4.6.0", "prisma": "^4.6.1",
"ts-node": "10.9.1", "ts-node": "10.9.1",
"typescript": "4.8.4" "typescript": "4.8.4"
}, },

@ -0,0 +1,107 @@
import prisma from '../../../lib/prisma';
import chance from 'chance'
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 = (Math.random() + 1).toString(36).substring(7).toUpperCase()
//création d'un id de produit de façon pondérée
let weightedRandomGainId = chance().weighted([
Cadeaux.CoffretDecouvert69,
Cadeaux.CoffretDecouvert39,
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' })
}
}

@ -7,6 +7,7 @@ import { getSession } from 'next-auth/react'
// Required fields in body: title // Required fields in body: title
export default async function handle(req: NextApiRequest, res: NextApiResponse) { export default async function handle(req: NextApiRequest, res: NextApiResponse) {
const { bioValue } = req.body; const { bioValue } = req.body;
console.log('server biovalue:', bioValue)
const session = await getSession({ req }); const session = await getSession({ req });
if (req.method === "PUT") { if (req.method === "PUT") {

@ -0,0 +1,36 @@
import { NextApiRequest, NextApiResponse } from 'next';
import { getSession } from 'next-auth/react';
import { Role } from '../../../enum/role.enum';
import prisma from '../../../lib/prisma';
//api qui va rendre un utilisateur super admin (pour les developpeurs)
//--> http://localhost:3000/api/superadmin?pass=1234 (a effacer)
export default async function makeMeSuper(req: NextApiRequest, res: NextApiResponse) {
const { pass } = req.query;
const session = await getSession({ req })
const goodPassword = pass === '1234';
//si utilisateur connecté et que le parametre 'pass' est '1234'
if (session && goodPassword) {
//MAJ de l'utilisateur en superadmin
await prisma.user.update({
where: { email: session.user.email },
data: {
role: Role.SUPERADMIN,
},
})
return res.status(200).send({ message: 'Profiled updated welcome SUPERADMIN !' });
} else {
res.status(401).send({ message: 'Unauthorized' })
}
}

@ -1,60 +1,87 @@
import React from "react"; import React from "react";
import type { GetServerSideProps } from "next";
import Layout from "../components/Layout"; import Layout from "../components/Layout";
import Post, { PostProps } from "../components/Post";
import prisma from '../lib/prisma' import prisma from '../lib/prisma'
export const getServerSideProps: GetServerSideProps = async () => { import { yupResolver } from "@hookform/resolvers/yup";
const feed = await prisma.post.findMany({ import { useForm } from "react-hook-form";
where: { import * as Yup from 'yup';
published: true, import { useSession } from "next-auth/react";
},
include: { type CodeSubmitForm = {
author: { codeCadeau: string;
select: {
name: true,
},
},
},
});
return {
props: { feed },
};
}; };
type Props = { const MainPage = () => {
feed: PostProps[]; const { data: session } = useSession();
const validationSchema = Yup.object().shape({
codeCadeau: Yup.string().trim().required("Vous n'avez pas rentrer de code cadeau !"),
});
const {
register,
handleSubmit,
formState: { errors }
} = useForm<CodeSubmitForm>({
resolver: yupResolver(validationSchema)
});
const onSubmit = async (data: CodeSubmitForm) => {
if (!session) {
return <Layout>
<p>Vous devez vous connecter pour tester votre !</p>
</Layout>
}
// try {
// const body = { bioValue: data.bio };
// await fetch(`/api/profile`, {
// method: "POST",
// headers: { "Content-Type": "application/json" },
// body: JSON.stringify(body),
// })
// .then((res) => res.json())
// .then((data) => {
// setResponse(data);
// console.log('response', data);
// })
// await Router.push("/profile");
// } catch (error) {
// console.error(error);
// }
}; };
const Blog = (props : Props) => {
return ( return (
<Layout> <Layout>
<div className="page"> <div className="page">
<h1>Public Feed</h1> <h1>TheTipTop - jeu concours !</h1>
<main> <main>
{props.feed.map((post) => ( <form onSubmit={handleSubmit(onSubmit)}>
<div key={post.id} className="post"> <div className="form-group">
<Post post={post} /> <label>Entre votre code :</label>
<input
placeholder="A123456B..."
type="text"
{...register('codeCadeau')}
className={`form-control ${errors.codeCadeau ? 'is-invalid' : ''}`}
/>
<div className="invalid-feedback">{errors.codeCadeau?.message}</div>
</div>
<div className="form-group">
<button type="submit" className="btn btn-primary">
Tester mon code cadeau !
</button>
</div> </div>
))} </form>
</main> </main>
</div> </div>
<style jsx>{`
.post {
background: white;
transition: box-shadow 0.1s ease-in;
}
.post:hover {
box-shadow: 1px 1px 3px #aaa;
}
.post + .post {
margin-top: 2rem;
}
`}</style>
</Layout> </Layout>
); );
}; };
export default Blog; export default MainPage;

@ -3,30 +3,54 @@ import { GetServerSideProps } from "next";
import Layout from "../components/Layout"; import Layout from "../components/Layout";
import { useSession, getSession } from "next-auth/react"; import { useSession, getSession } from "next-auth/react";
import prisma from '../lib/prisma' import prisma from '../lib/prisma'
import Image from "next/image";
import Router from "next/router"; import Router from "next/router";
import { ProfileProps } from "../types/profile"; import { ProfileProps } from "../types/profile";
import { Resolver, SubmitHandler, useForm } from "react-hook-form"; import { Resolver, SubmitHandler } from "react-hook-form";
//https://www.bezkoder.com/react-hook-form-typescript/
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as Yup from 'yup';
type UserSubmitForm = {
bio: string;
};
type Profil = {
isUserProfile: any;
}
interface ResponseData {
result: string;
message: string
}
export const getServerSideProps: GetServerSideProps = async ({ req, res }) => { export const getServerSideProps: GetServerSideProps = async ({ req, res }) => {
const session = await getSession({ req }); const session = await getSession({ req });
//pas de session ? on ne retourne un code erreur
//voir pour rediriger vers la page de connection
//ou afficher pop up "vous n'est pas connecter"
if (!session) { if (!session) {
res.statusCode = 403; res.statusCode = 403;
return { props: { profile: null } }; return { props: { profile: null } };
} }
// si profil ? on retour le Profil
// si session ? on récupére le profil de l'utilisateur si il existe
if (session) { if (session) {
const isUserProfile = await prisma.profile.findMany({ const isUserProfile = await prisma.profile.findMany({
where: { where: {
user: { email: session.user.email }, user: { email: session.user.email },
} }
}) })
console.log('profil utilisateur ?', isUserProfile);
if (!isUserProfile) {
const createProfile = await prisma.profile.create({ // il n'existe pas ? on le crée
if (isUserProfile.length <= 0) {
const newProfil = await prisma.profile.create({
data: { data: {
bio: "", bio: "",
user: { user: {
@ -34,48 +58,40 @@ export const getServerSideProps: GetServerSideProps = async ({ req, res }) => {
}, },
}, },
}); });
return { props: { createProfile } }; console.log('newProfil', newProfil);
}
return { props: { isUserProfile } };
} }
};
// type Props = {
// profile: any;
// };
interface ResponseData { // on renvoi le profil
result: string; return { props: { isUserProfile } };
message: string
} }
type FormValues = {
bio: string;
}; };
const Profil = ({ isUserProfile }: Profil) => {
const validationSchema = Yup.object().shape({
bio: Yup.string().trim().required("ce champ ne peux etre vide..."),
});
const {
register,
handleSubmit,
reset,
formState: { errors }
} = useForm<UserSubmitForm>({
resolver: yupResolver(validationSchema)
});
const Profil = (props: any) => {
const { register, handleSubmit, formState: { errors } } = useForm<FormValues>({ resolver });
const [bio, setBio] = useState(props.isUserProfile[0].bio || "");
const [response, setResponse] = useState<ResponseData | undefined>(); const [response, setResponse] = useState<ResponseData | undefined>();
const { data: session } = useSession(); const { data: session } = useSession();
React.useEffect(() => { React.useEffect(() => {
console.log('user profil', props.isUserProfile) console.log('user profil props', isUserProfile)
}, []) }, [])
const onSubmit = async (data: UserSubmitForm) => {
const onSubmit: SubmitHandler<FormValues> = async (data) => { console.log(data);
console.log('input value', data.bio);
setBio(data.bio)
try { try {
const body = { bioValue: data.bio }; const body = { bioValue: data.bio };
@ -89,8 +105,6 @@ const Profil = (props: any) => {
setResponse(data); setResponse(data);
console.log('response', data); console.log('response', data);
}) })
await Router.push("/profile"); await Router.push("/profile");
} catch (error) { } catch (error) {
console.error(error); console.error(error);
@ -111,36 +125,47 @@ const Profil = (props: any) => {
<div className="page"> <div className="page">
<h1>Mon compte</h1> <h1>Mon compte</h1>
<main> <main>
<div className="register-form">
<p>Ma bio : {isUserProfile[0]?.bio}</p>
<form onSubmit={handleSubmit(onSubmit)}> <form onSubmit={handleSubmit(onSubmit)}>
<p>Ma bio : {bio}</p> <div className="form-group">
<label>Ma bio :</label>
<input <input
autoFocus
placeholder="Ma bio..." placeholder="Ma bio..."
defaultValue={bio} defaultValue={isUserProfile[0]?.bio}
{...register("bio")} type="text"
{...register('bio')}
className={`form-control ${errors.bio ? 'is-invalid' : ''}`}
/> />
<input type="submit" value="Save changes" /> <div className="invalid-feedback">{errors.bio?.message}</div>
</div>
<div className="form-group">
<button type="submit" className="btn btn-primary">
Valider les changements
</button>
<button
type="button"
onClick={() => reset()}
className="btn btn-warning float-right"
>
Reset
</button>
</div>
</form> </form>
</div>
<p>Email : {session.user.email}</p> <p>Email : {session.user.email}</p>
{response && <p>{response.message}</p>} {response && <p>{response.message}</p>}
</main> </main>
</div> </div>
<style jsx>{`
.post {
background: white;
transition: box-shadow 0.1s ease-in;
}
.post:hover {
box-shadow: 1px 1px 3px #aaa;
}
.post + .post {
margin-top: 2rem;
}
`}</style>
</Layout> </Layout>
); );
}; };
export default Profil; export default Profil;

Binary file not shown.

@ -1,70 +0,0 @@
-- CreateTable
CREATE TABLE "Post" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"title" TEXT NOT NULL,
"content" TEXT,
"published" BOOLEAN NOT NULL DEFAULT false,
"authorId" INTEGER,
CONSTRAINT "Post_authorId_fkey" FOREIGN KEY ("authorId") REFERENCES "users" ("id") ON DELETE SET NULL ON UPDATE CASCADE
);
-- CreateTable
CREATE TABLE "accounts" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"user_id" INTEGER NOT NULL,
"type" TEXT NOT NULL,
"provider" TEXT NOT NULL,
"provider_account_id" TEXT NOT NULL,
"refresh_token" TEXT,
"access_token" TEXT,
"expires_at" INTEGER,
"token_type" TEXT,
"scope" TEXT,
"id_token" TEXT,
"session_state" TEXT,
"oauth_token_secret" TEXT,
"oauth_token" TEXT,
CONSTRAINT "accounts_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE CASCADE
);
-- CreateTable
CREATE TABLE "sessions" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"session_token" TEXT NOT NULL,
"user_id" INTEGER NOT NULL,
"expires" DATETIME NOT NULL,
CONSTRAINT "sessions_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE CASCADE
);
-- CreateTable
CREATE TABLE "users" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"name" TEXT,
"email" TEXT,
"email_verified" DATETIME,
"image" TEXT,
"created_at" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" DATETIME NOT NULL
);
-- CreateTable
CREATE TABLE "verificationtokens" (
"identifier" TEXT NOT NULL,
"token" TEXT NOT NULL,
"expires" DATETIME NOT NULL
);
-- CreateIndex
CREATE UNIQUE INDEX "accounts_provider_provider_account_id_key" ON "accounts"("provider", "provider_account_id");
-- CreateIndex
CREATE UNIQUE INDEX "sessions_session_token_key" ON "sessions"("session_token");
-- CreateIndex
CREATE UNIQUE INDEX "users_email_key" ON "users"("email");
-- CreateIndex
CREATE UNIQUE INDEX "verificationtokens_token_key" ON "verificationtokens"("token");
-- CreateIndex
CREATE UNIQUE INDEX "verificationtokens_identifier_token_key" ON "verificationtokens"("identifier", "token");

@ -1,10 +0,0 @@
-- CreateTable
CREATE TABLE "Profile" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"bio" TEXT,
"userId" INTEGER NOT NULL,
CONSTRAINT "Profile_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
);
-- CreateIndex
CREATE UNIQUE INDEX "Profile_userId_key" ON "Profile"("userId");

@ -1,21 +0,0 @@
/*
Warnings:
- You are about to drop the `Profile` table. If the table is not empty, all the data it contains will be lost.
*/
-- DropTable
PRAGMA foreign_keys=off;
DROP TABLE "Profile";
PRAGMA foreign_keys=on;
-- CreateTable
CREATE TABLE "Profil" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"bio" TEXT,
"userId" INTEGER NOT NULL,
CONSTRAINT "Profil_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
);
-- CreateIndex
CREATE UNIQUE INDEX "Profil_userId_key" ON "Profil"("userId");

@ -1,21 +0,0 @@
/*
Warnings:
- You are about to drop the `Profil` table. If the table is not empty, all the data it contains will be lost.
*/
-- DropTable
PRAGMA foreign_keys=off;
DROP TABLE "Profil";
PRAGMA foreign_keys=on;
-- CreateTable
CREATE TABLE "Profile" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"bio" TEXT,
"userId" INTEGER NOT NULL,
CONSTRAINT "Profile_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
);
-- CreateIndex
CREATE UNIQUE INDEX "Profile_userId_key" ON "Profile"("userId");

@ -0,0 +1,144 @@
-- CreateEnum
CREATE TYPE "Role" AS ENUM ('USER', 'ADMIN', 'SUPERADMIN');
-- CreateTable
CREATE TABLE "accounts" (
"id" SERIAL NOT NULL,
"user_id" INTEGER NOT NULL,
"type" TEXT NOT NULL,
"provider" TEXT NOT NULL,
"provider_account_id" TEXT NOT NULL,
"refresh_token" TEXT,
"access_token" TEXT,
"expires_at" INTEGER,
"token_type" TEXT,
"scope" TEXT,
"id_token" TEXT,
"session_state" TEXT,
"oauth_token_secret" TEXT,
"oauth_token" TEXT,
CONSTRAINT "accounts_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "sessions" (
"id" SERIAL NOT NULL,
"session_token" TEXT NOT NULL,
"user_id" INTEGER NOT NULL,
"expires" TIMESTAMP(3) NOT NULL,
CONSTRAINT "sessions_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "users" (
"id" SERIAL NOT NULL,
"name" TEXT,
"email" TEXT,
"email_verified" TIMESTAMP(3),
"image" TEXT,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
"role" "Role" NOT NULL DEFAULT 'USER',
CONSTRAINT "users_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Post" (
"id" SERIAL NOT NULL,
"title" TEXT NOT NULL,
"content" TEXT,
"published" BOOLEAN NOT NULL DEFAULT false,
"authorId" INTEGER,
CONSTRAINT "Post_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Profile" (
"id" SERIAL NOT NULL,
"bio" TEXT,
"userId" INTEGER NOT NULL,
CONSTRAINT "Profile_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "TicketsRestants" (
"id" SERIAL NOT NULL,
"total" INTEGER NOT NULL,
CONSTRAINT "TicketsRestants_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Gain" (
"id" SERIAL NOT NULL,
"codeCadeau" TEXT NOT NULL,
"dateRetrait" TIMESTAMP(3),
"produitId" INTEGER,
"userId" INTEGER,
CONSTRAINT "Gain_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Produit" (
"id" SERIAL NOT NULL,
"actif" BOOLEAN,
"nomProduit" TEXT,
"prixTtc" DECIMAL(65,30),
CONSTRAINT "Produit_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "verificationtokens" (
"identifier" TEXT NOT NULL,
"token" TEXT NOT NULL,
"expires" TIMESTAMP(3) NOT NULL
);
-- CreateIndex
CREATE UNIQUE INDEX "accounts_provider_provider_account_id_key" ON "accounts"("provider", "provider_account_id");
-- CreateIndex
CREATE UNIQUE INDEX "sessions_session_token_key" ON "sessions"("session_token");
-- CreateIndex
CREATE UNIQUE INDEX "users_email_key" ON "users"("email");
-- CreateIndex
CREATE UNIQUE INDEX "Profile_userId_key" ON "Profile"("userId");
-- CreateIndex
CREATE UNIQUE INDEX "Gain_codeCadeau_key" ON "Gain"("codeCadeau");
-- CreateIndex
CREATE UNIQUE INDEX "Gain_userId_key" ON "Gain"("userId");
-- CreateIndex
CREATE UNIQUE INDEX "verificationtokens_token_key" ON "verificationtokens"("token");
-- CreateIndex
CREATE UNIQUE INDEX "verificationtokens_identifier_token_key" ON "verificationtokens"("identifier", "token");
-- AddForeignKey
ALTER TABLE "accounts" ADD CONSTRAINT "accounts_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "sessions" ADD CONSTRAINT "sessions_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Post" ADD CONSTRAINT "Post_authorId_fkey" FOREIGN KEY ("authorId") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Profile" ADD CONSTRAINT "Profile_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Gain" ADD CONSTRAINT "Gain_produitId_fkey" FOREIGN KEY ("produitId") REFERENCES "Produit"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Gain" ADD CONSTRAINT "Gain_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;

@ -1,3 +1,3 @@
# Please do not edit this file manually # Please do not edit this file manually
# It should be added in your version-control system (i.e. Git) # It should be added in your version-control system (i.e. Git)
provider = "sqlite" provider = "postgresql"

@ -3,8 +3,8 @@ generator client {
} }
datasource db { datasource db {
provider = "sqlite" provider = "postgresql"
url = "file:./dev.db" url = env("DATABASE_URL")
} }
model Account { model Account {
@ -51,6 +51,8 @@ model User {
accounts Account[] accounts Account[]
sessions Session[] sessions Session[]
profile Profile? profile Profile?
gain Gain?
role Role @default(USER)
@@map(name: "users") @@map(name: "users")
} }
@ -71,6 +73,35 @@ model Profile {
userId Int @unique userId Int @unique
} }
model TicketsRestants {
id Int @id @default(autoincrement())
total Int
}
model Gain {
id Int @id @default(autoincrement())
codeCadeau String @unique
dateRetrait DateTime?
produit Produit? @relation(fields: [produitId], references: [id])
produitId Int?
user User? @relation(fields: [userId], references: [id])
userId Int? @unique
}
model Produit {
id Int @id @default(autoincrement())
actif Boolean?
nomProduit String?
prixTtc Decimal?
refGain Gain[]
}
enum Role {
USER
ADMIN
SUPERADMIN
}
model VerificationToken { model VerificationToken {
identifier String identifier String
token String @unique token String @unique

@ -1,64 +1,50 @@
import { PrismaClient, Prisma } from '@prisma/client' // import prisma from '../lib/prisma'
import { PrismaClient } from '@prisma/client'
import { generateGains } from './seed/gains'
import { produitsData } from './seed/produits'
// import { userData } from './seed/user'
const prisma = new PrismaClient() const prisma = new PrismaClient();
const userData: Prisma.UserCreateInput[] = [
{
name: 'Alice',
email: 'alice@prisma.io',
posts: {
create: [
{
title: 'Join the Prisma Slack',
content: 'https://slack.prisma.io',
published: true,
},
],
},
},
{
name: 'Nilu',
email: 'nilu@prisma.io',
posts: {
create: [
{
title: 'Follow Prisma on Twitter',
content: 'https://www.twitter.com/prisma',
published: true,
},
],
},
},
{
name: 'Mahmoud',
email: 'mahmoud@prisma.io',
posts: {
create: [
{
title: 'Ask a question about Prisma on GitHub',
content: 'https://www.github.com/prisma/prisma/discussions',
published: true,
},
{
title: 'Prisma on YouTube',
content: 'https://pris.ly/youtube',
},
],
},
},
]
async function main() { async function main() {
console.log(`Start seeding ...`) console.log(`Start seeding ...`)
for (const u of userData) {
const user = await prisma.user.create({ //création des tickets restants
data: u, const tickets = await prisma.ticketsRestants.create({
data: {
total: 1500000
},
})
console.log(`Created ticket: ${tickets.total}`)
//création des produits
for (const p of produitsData) {
const produit = await prisma.produit.create({
data: p,
}) })
console.log(`Created user with id: ${user.id}`) console.log(`Created produit: ${produit.nomProduit}`)
} }
/////////////////////////////////////////////////////
//création des utilisateurs
// for (const u of userData) {
// const user = await prisma.user.create({
// data: u,
// })
// console.log(`Created user with id: ${user.id}`)
// }
//création de 5 gains
for (let i = 1; i <= 5; i++) {
await generateGains();
}
console.log(`Seeding finished.`) console.log(`Seeding finished.`)
} }
main() main()
.then(async () => { .then(async () => {
await prisma.$disconnect() await prisma.$disconnect()

@ -0,0 +1,48 @@
// import { produits } from './produits';
import prisma from '../../lib/prisma'
import { Chance } from 'chance'
import { Cadeaux } from '../../enum/cadeaux.enum';
let chance = new Chance();
export const generateGains = async () => {
//génération d'un code cadeau
const randomNoGain = (Math.random() + 1).toString(36).substring(7).toUpperCase()
//création d'un gain
const gainCreated = await prisma.gain.create({
data: {
codeCadeau: randomNoGain,
}
})
//crétion d'un id de produit de façon pondérée
let weightedRandomGain = chance.weighted([
Cadeaux.CoffretDecouvert69,
Cadeaux.CoffretDecouvert39,
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}`)
}

@ -0,0 +1,24 @@
import { Prisma } from "@prisma/client";
export const produitsData: Prisma.ProduitCreateInput[] = [
{
nomProduit: 'coffret découverte à 69€',
prixTtc: 69,
},
{
nomProduit: 'coffret découverte à 39€',
prixTtc: 39,
},
{
nomProduit: 'thé signature',
prixTtc: 10,
},
{
nomProduit: 'thé détox ou infusion',
prixTtc: 6,
},
{
nomProduit: 'infuseur à thé',
prixTtc: 3,
}]

@ -0,0 +1,47 @@
import { Prisma } from "@prisma/client";
export const userData: Prisma.UserCreateInput[] = [
{
name: 'Alice',
email: 'alice@prisma.io',
posts: {
create: [
{
title: 'Join the Prisma Slack',
content: 'https://slack.prisma.io',
published: true,
},
],
},
},
{
name: 'Nilu',
email: 'nilu@prisma.io',
posts: {
create: [
{
title: 'Follow Prisma on Twitter',
content: 'https://www.twitter.com/prisma',
published: true,
},
],
},
},
{
name: 'Mahmoud',
email: 'mahmoud@prisma.io',
posts: {
create: [
{
title: 'Ask a question about Prisma on GitHub',
content: 'https://www.github.com/prisma/prisma/discussions',
published: true,
},
{
title: 'Prisma on YouTube',
content: 'https://pris.ly/youtube',
},
],
},
},
]
Loading…
Cancel
Save