add - page mon compte

feature/page-admin
Eric 4 years ago
parent f59662740f
commit 0b9bbe44d6

@ -1,7 +1,2 @@
{
"workbench.colorCustomizations": {
"activityBar.background": "#521342",
"titleBar.activeBackground": "#731B5D",
"titleBar.activeForeground": "#FDF8FC"
}
}

@ -0,0 +1,79 @@
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 updateOrCreate(req: NextApiRequest, res: NextApiResponse) {
const session = await getSession({ req })
const { address, name, phoneNumber, surname, zipCode } = req.body;
// est-ce la méthode est un POST ou PUT?
if (req.method !== ("POST" || "PUT")) {
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: session.user.email },
})
//mise a jour ou création des données pour l'utilisateur
const upsertUser = await prisma.user.upsert({
where: {
email: user.email,
},
update: {
name,
surname,
address,
phoneNumber,
zipCode
},
create: {
name,
surname,
address,
phoneNumber,
zipCode
},
})
res.status(200).send({ message: 'Vos informations ont été mise à jours !', res: upsertUser });
}

@ -22,7 +22,12 @@ import imageConnexion from '../public/images/connexion_image.png'
import Link from "next/link";
import { GrValidate } from 'react-icons/gr'
import { TfiInfoAlt } from 'react-icons/tfi'
import { TfiGift } from 'react-icons/tfi'
import { toast } from "react-toastify";
import { Token } from "nodemailer/lib/xoauth2";
import { isGeneratorFunction } from "util/types";
@ -36,8 +41,8 @@ type FormData = {
name: string;
surname: string;
address: string;
zipCode: string;
phoneNumber: string;
zipCode: number;
phoneNumber: number;
};
export async function getServerSideProps(context) {
@ -52,7 +57,6 @@ export async function getServerSideProps(context) {
}
}
const user = await prisma.user.findUnique({
where: {
email: session?.user.email
@ -68,20 +72,12 @@ export async function getServerSideProps(context) {
}
})
return {
props: {
user: JSON.parse(JSON.stringify(user)),
userGains,
},
}
}
type Props = {
@ -92,6 +88,7 @@ type Props = {
const MonCompte = (props: Props) => {
const { data: session, status } = useSession();
const [response, setResponse] = useState(null)
const validationSchema = Yup.object().shape({
name: Yup.string()
@ -114,9 +111,59 @@ const MonCompte = (props: Props) => {
const { register, setValue, handleSubmit, formState: { errors } } = useForm<FormData>({
resolver: yupResolver(validationSchema)
});
const onSubmit: SubmitHandler<FormData> = data => console.log(data);
const onSubmit = async ({
email,
name,
surname,
address,
zipCode,
phoneNumber }: FormData) => {
try {
const body = {
email,
name,
surname,
address,
zipCode: Number(zipCode),
phoneNumber: Number(phoneNumber),
};
await fetch(`/api/user/`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
})
.then((res) => res.json())
.then(async (data) => {
setResponse(data);
if (data.err) {
toast.error(data.err, {
position: "top-center",
autoClose: 2000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
});
return;
}
toast.success(data.message, {
position: "top-center",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
});
})
} catch (error) {
console.error('ERROR :', error);
}
};
return (
<>
@ -130,11 +177,11 @@ const MonCompte = (props: Props) => {
<div className="container align-items-center d-flex flex-column">
<div className={`${style['bloc-content']} col-12 col-md-12`}>
<h1 className="fw-light">Mon Compte</h1>
<hr />
<div className="row">
<div className="col-md-6 col-sm-12">
<h1 className="fw-light">Mes informations</h1>
<hr />
<h1 className="fw-light">Mes informations <TfiInfoAlt size={40} /></h1>
<hr />
<form onSubmit={handleSubmit(onSubmit)}>
<div className="form-group">
@ -149,7 +196,7 @@ const MonCompte = (props: Props) => {
<div className="form-group row">
<label htmlFor="inputName" className="col-sm-3 col-form-label">Nom :</label>
<div className="col-sm-9">
<input {...register("name")} className={`form-control ${errors.name ? 'is-invalid' : ''}`} id="inputName" placeholder="John..." />
<input {...register("name")} className={`form-control ${errors.name ? 'is-invalid' : ''}`} defaultValue={props.user.name} id="inputName" placeholder="John..." />
<div className="invalid-feedback alert alert-danger mt-2">{errors.name?.message}</div>
</div>
</div>
@ -157,7 +204,7 @@ const MonCompte = (props: Props) => {
<div className="form-group row">
<label htmlFor="surname" className="col-sm-3 col-form-label">Prenom :</label>
<div className="col-sm-9">
<input {...register("surname")} className={`form-control ${errors.surname ? 'is-invalid' : ''}`} id="surname" placeholder="Doe..." />
<input {...register("surname")} className={`form-control ${errors.surname ? 'is-invalid' : ''}`} defaultValue={props.user.surname} id="surname" placeholder="Doe..." />
<div className="invalid-feedback alert alert-danger mt-2">{errors.surname?.message}</div>
</div>
</div>
@ -165,7 +212,7 @@ const MonCompte = (props: Props) => {
<div className="form-group row">
<label htmlFor="address" className="col-sm-3 col-form-label">Adresse :</label>
<div className="col-sm-9">
<input {...register("address")} className={`form-control ${errors.address ? 'is-invalid' : ''}`} id="address" placeholder="1 rue de la paix..." />
<input {...register("address")} className={`form-control ${errors.address ? 'is-invalid' : ''}`} defaultValue={props.user.address} id="address" placeholder="1 rue de la paix..." />
<div className="invalid-feedback alert alert-danger mt-2">{errors.address?.message}</div>
</div>
</div>
@ -173,7 +220,7 @@ const MonCompte = (props: Props) => {
<div className="form-group row">
<label htmlFor="zipCode" className="col-sm-3 col-form-label">Code postale :</label>
<div className="col-sm-9">
<input {...register("zipCode")} className={`form-control ${errors.zipCode ? 'is-invalid' : ''}`} id="zipCode" placeholder="95000..." />
<input {...register("zipCode")} className={`form-control ${errors.zipCode ? 'is-invalid' : ''}`} defaultValue={props.user.zipCode} id="zipCode" placeholder="95000..." />
<div className="invalid-feedback alert alert-danger mt-2">{errors.zipCode?.message}</div>
</div>
</div>
@ -181,42 +228,48 @@ const MonCompte = (props: Props) => {
<div className="form-group row">
<label htmlFor="phoneNumber" className="col-sm-3 col-form-label">Téléphone :</label>
<div className="col-sm-9">
<input {...register("phoneNumber")} className={`form-control ${errors.phoneNumber ? 'is-invalid' : ''}`} id="phoneNumber" placeholder="0123456789..." />
<input {...register("phoneNumber")} className={`form-control ${errors.phoneNumber ? 'is-invalid' : ''}`} defaultValue={props.user.phoneNumber} id="phoneNumber" placeholder="0123456789..." />
<div className="invalid-feedback alert alert-danger mt-2">{errors.phoneNumber?.message}</div>
</div>
</div>
<button
type="submit"
className="btn btn-primary mt-2"
>
Sauvegarder les changements
</button>
<div className="form-group row">
<button
type="submit"
className="btn btn-primary mt-2"
>
Sauvegarder les changements
</button>
</div>
</div>
</form>
</div>
<div className="col-md-6 col-sm-12">
<h1 className="fw-light">Mes cadeaux</h1>
<hr />
{!props.userGains && <p>Pas encore de cadeau gagné</p>}
<table className="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Mes codes joué</th>
<th scope="col">Mes cadeaux</th>
</tr>
</thead>
<tbody>
{props.userGains.map((info: any) => {
return <tr>
<th scope="row"></th>
<td>{info.codeCadeau}</td>
<td>{info.produit.nomProduit}</td>
<h1 className="fw-light">Mes cadeaux <TfiGift size={40} /></h1>
<hr />
{props.userGains.length <= 0 && <p>Pas encore de cadeau gagné</p>}
{props.userGains.length >= 1 &&
<table className="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Mes codes joué</th>
<th scope="col">Mes cadeaux</th>
</tr>
})}
</tbody>
</table>
</thead>
<tbody>
{props.userGains.map((info: any) => {
return <tr>
<th scope="row"></th>
<td>{info.codeCadeau}</td>
<td>{info.produit.nomProduit}</td>
</tr>
})}
</tbody>
</table>
}
</div>

@ -0,0 +1,9 @@
/*
Warnings:
- The `phoneNumber` column on the `users` table would be dropped and recreated. This will lead to data loss if there is data in the column.
*/
-- AlterTable
ALTER TABLE "users" DROP COLUMN "phoneNumber",
ADD COLUMN "phoneNumber" INTEGER;

@ -0,0 +1,9 @@
/*
Warnings:
- The `zipCode` column on the `users` table would be dropped and recreated. This will lead to data loss if there is data in the column.
*/
-- AlterTable
ALTER TABLE "users" DROP COLUMN "zipCode",
ADD COLUMN "zipCode" INTEGER;

@ -44,8 +44,8 @@ model User {
name String?
surname String?
address String?
zipCode String?
phoneNumber String?
zipCode Int?
phoneNumber Int?
email String? @unique
emailVerified DateTime? @map("email_verified")
image String?

Loading…
Cancel
Save