mise a jour
This commit is contained in:
@@ -9,4 +9,11 @@ MAIL_HOST=smtp.gmail.com
|
||||
MAIL_PORT=587
|
||||
MAIL_USER=yourmail_adress@gmail.com
|
||||
MAIL_PASS=_______________________
|
||||
MAIL_FROM="Thé Tip Top <yourmail_adress@gmail.com>"
|
||||
MAIL_FROM="Thé Tip Top <yourmail_adress@gmail.com>"
|
||||
|
||||
# SMTP (email verification + password reset)
|
||||
SMTP_HOST="smtp.gmail.com"
|
||||
SMTP_PORT="587"
|
||||
SMTP_USER="engongomo.emma27@gmail.com"
|
||||
SMTP_PASS="your-gmail-app-password"
|
||||
SMTP_FROM="BizManager <engongomo.emma27@gmail.com>"
|
||||
39
backend/package-lock.json
generated
39
backend/package-lock.json
generated
@@ -14,7 +14,7 @@
|
||||
"cors": "^2.8.6",
|
||||
"express": "^5.2.1",
|
||||
"jsonwebtoken": "^9.0.3",
|
||||
"nodemailer": "^9.0.1",
|
||||
"nodemailer": "^9.0.3",
|
||||
"prisma": "^6.19.3",
|
||||
"swagger-jsdoc": "^6.3.0",
|
||||
"swagger-ui-express": "^5.0.1",
|
||||
@@ -108,6 +108,7 @@
|
||||
"integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/code-frame": "^7.29.7",
|
||||
"@babel/generator": "^7.29.7",
|
||||
@@ -603,31 +604,6 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@emnapi/core": {
|
||||
"version": "1.11.1",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.1.tgz",
|
||||
"integrity": "sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@emnapi/wasi-threads": "1.2.2",
|
||||
"tslib": "^2.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@emnapi/runtime": {
|
||||
"version": "1.11.1",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.1.tgz",
|
||||
"integrity": "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"tslib": "^2.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@emnapi/wasi-threads": {
|
||||
"version": "1.2.2",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.2.tgz",
|
||||
@@ -635,7 +611,6 @@
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"tslib": "^2.4.0"
|
||||
}
|
||||
@@ -1987,6 +1962,7 @@
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",
|
||||
"integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
@@ -2305,6 +2281,7 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"baseline-browser-mapping": "^2.10.38",
|
||||
"caniuse-lite": "^1.0.30001799",
|
||||
@@ -3171,6 +3148,7 @@
|
||||
"resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz",
|
||||
"integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"accepts": "^2.0.0",
|
||||
"body-parser": "^2.2.1",
|
||||
@@ -5457,9 +5435,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/nodemailer": {
|
||||
"version": "9.0.1",
|
||||
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-9.0.1.tgz",
|
||||
"integrity": "sha512-Gwv8SQewT616ZM/URn0H54b8PWo/Wum7md3EW2aWy1lO27+WZCX+Xyak3J+NlmHUjDh5ME+uesJUDRbR3Ye8Bw==",
|
||||
"version": "9.0.3",
|
||||
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-9.0.3.tgz",
|
||||
"integrity": "sha512-n+YP+NKwR5zRWa60k3GiQ6Q3B4KXCoAw40dAKeCtYn020iNN74aWK2liXIC3ZEATeGql7we3tE3t8QwhY0eskw==",
|
||||
"license": "MIT-0",
|
||||
"engines": {
|
||||
"node": ">=6.0.0"
|
||||
@@ -5894,6 +5872,7 @@
|
||||
"integrity": "sha512-++ZJ0ijLrDJF6hNB4t4uxg2br3fC4H9Yc9tcbjr2fcNFP3rh/SBNrAgjhsqBU4Ght8JPrVofG/ZkXfnSfnYsFg==",
|
||||
"hasInstallScript": true,
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@prisma/config": "6.19.3",
|
||||
"@prisma/engines": "6.19.3"
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
"cors": "^2.8.6",
|
||||
"express": "^5.2.1",
|
||||
"jsonwebtoken": "^9.0.3",
|
||||
"nodemailer": "^9.0.1",
|
||||
"nodemailer": "^9.0.3",
|
||||
"prisma": "^6.19.3",
|
||||
"swagger-jsdoc": "^6.3.0",
|
||||
"swagger-ui-express": "^5.0.1",
|
||||
|
||||
@@ -304,11 +304,42 @@ const me = async (req, res) => {
|
||||
});
|
||||
};
|
||||
|
||||
const changePassword = async (req, res) => {
|
||||
try {
|
||||
const { currentPassword, newPassword } = req.body;
|
||||
const userId = req.user.id;
|
||||
|
||||
if (!currentPassword || !newPassword) {
|
||||
return res.status(400).json({ message: "Les deux mots de passe sont requis." });
|
||||
}
|
||||
|
||||
if (newPassword.length < 8) {
|
||||
return res.status(400).json({ message: "Le nouveau mot de passe doit faire au moins 8 caractères." });
|
||||
}
|
||||
|
||||
const user = await prisma.user.findUnique({ where: { id: userId } });
|
||||
|
||||
const isValid = await bcrypt.compare(currentPassword, user.password);
|
||||
if (!isValid) {
|
||||
return res.status(401).json({ message: "Mot de passe actuel incorrect." });
|
||||
}
|
||||
|
||||
const hashed = await bcrypt.hash(newPassword, 10);
|
||||
await prisma.user.update({ where: { id: userId }, data: { password: hashed } });
|
||||
|
||||
return res.json({ message: "Mot de passe modifié avec succès." });
|
||||
} catch (error) {
|
||||
console.error("Erreur changePassword:", error);
|
||||
return res.status(500).json({ message: "Erreur serveur lors du changement de mot de passe." });
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
register,
|
||||
login,
|
||||
me,
|
||||
verifyEmail,
|
||||
resetPassword,
|
||||
forgotPassword
|
||||
forgotPassword,
|
||||
changePassword,
|
||||
};
|
||||
@@ -1,5 +1,5 @@
|
||||
const express = require("express");
|
||||
const { register, login, verifyEmail, forgotPassword, resetPassword, me } = require("../controllers/auth.controller");
|
||||
const { register, login, verifyEmail, forgotPassword, resetPassword, me, changePassword } = require("../controllers/auth.controller");
|
||||
const authMiddleware = require("../middlewares/auth.middleware");
|
||||
const validate = require("../middlewares/validate.middleware");
|
||||
const { registerSchema, loginSchema } = require("../validations/auth.validation");
|
||||
@@ -155,7 +155,8 @@ router.post("/forgot-password", forgotPassword);
|
||||
* 500:
|
||||
* description: Erreur serveur.
|
||||
*/
|
||||
router.post("/reset-password/:token",resetPassword);
|
||||
router.post("/reset-password/:token", resetPassword);
|
||||
|
||||
router.patch("/change-password", authMiddleware, changePassword);
|
||||
|
||||
module.exports = router;
|
||||
@@ -23,7 +23,7 @@ async function createAdmin() {
|
||||
},
|
||||
})
|
||||
|
||||
console.log('✅ Admin créé avec succès')
|
||||
console.log(' Admin créé avec succès')
|
||||
console.log(' Email :', email)
|
||||
console.log(' Mot de passe :', password)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'
|
||||
import { AuthProvider } from './context/AuthContext.jsx'
|
||||
import Layout from './components/Layout.jsx'
|
||||
import ProtectedRoute from './components/ProtectedRoute.jsx'
|
||||
import Connexion from './pages/Connexion'
|
||||
@@ -21,6 +22,7 @@ import Contact from './pages/Contact.jsx'
|
||||
export default function App() {
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<AuthProvider>
|
||||
<Routes>
|
||||
<Route path="/" element={<Navigate to="/connexion" replace />} />
|
||||
<Route path="/connexion" element={<Connexion />} />
|
||||
@@ -73,6 +75,7 @@ export default function App() {
|
||||
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Routes>
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,18 +1,17 @@
|
||||
import { useState } from 'react'
|
||||
import { Link, useLocation, useNavigate } from 'react-router-dom'
|
||||
import logo from '../assets/img/logo.png'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
|
||||
export default function Header() {
|
||||
const [menuOpen, setMenuOpen] = useState(false)
|
||||
const { pathname } = useLocation()
|
||||
const navigate = useNavigate()
|
||||
|
||||
const user = JSON.parse(localStorage.getItem('user') || 'null')
|
||||
const { user, logout } = useAuth()
|
||||
const isLoggedIn = !!user
|
||||
|
||||
const handleLogout = () => {
|
||||
localStorage.removeItem('token')
|
||||
localStorage.removeItem('user')
|
||||
logout()
|
||||
setMenuOpen(false)
|
||||
navigate('/connexion')
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { Navigate } from 'react-router-dom'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
|
||||
export default function ProtectedRoute({ children, roles }) {
|
||||
const token = localStorage.getItem('token')
|
||||
const user = JSON.parse(localStorage.getItem('user') || 'null')
|
||||
const { user } = useAuth()
|
||||
|
||||
if (!token || !user) {
|
||||
if (!user) {
|
||||
return <Navigate to="/connexion" replace />
|
||||
}
|
||||
|
||||
|
||||
@@ -40,10 +40,10 @@ export default function UserNav({ active }) {
|
||||
<Link
|
||||
key={tab.key}
|
||||
to={tab.to}
|
||||
className={`flex-1 flex items-center justify-center gap-1.5 py-3 text-xs sm:text-sm font-medium transition-colors ${
|
||||
className={`flex-1 flex items-center justify-center gap-1.5 py-3 text-xs sm:text-sm font-medium transition-colors border-b-2 ${
|
||||
active === tab.key
|
||||
? 'text-[#006B6B] border-b-2 border-[#006B6B]'
|
||||
: 'text-gray-400 hover:text-gray-600'
|
||||
? 'text-[#006B6B] border-[#006B6B]'
|
||||
: 'text-gray-400 border-transparent hover:text-gray-600'
|
||||
}`}
|
||||
>
|
||||
{tab.icon}
|
||||
|
||||
31
frontend/src/context/AuthContext.jsx
Normal file
31
frontend/src/context/AuthContext.jsx
Normal file
@@ -0,0 +1,31 @@
|
||||
import { createContext, useContext, useState } from 'react'
|
||||
|
||||
const AuthContext = createContext(null)
|
||||
|
||||
export function AuthProvider({ children }) {
|
||||
const [user, setUser] = useState(() =>
|
||||
JSON.parse(localStorage.getItem('user') || 'null')
|
||||
)
|
||||
|
||||
function login(userData, token) {
|
||||
localStorage.setItem('token', token)
|
||||
localStorage.setItem('user', JSON.stringify(userData))
|
||||
setUser(userData)
|
||||
}
|
||||
|
||||
function logout() {
|
||||
localStorage.removeItem('token')
|
||||
localStorage.removeItem('user')
|
||||
setUser(null)
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ user, login, logout }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
return useContext(AuthContext)
|
||||
}
|
||||
16
frontend/src/hooks/useHandleAuthError.js
Normal file
16
frontend/src/hooks/useHandleAuthError.js
Normal file
@@ -0,0 +1,16 @@
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
|
||||
export function useHandleAuthError() {
|
||||
const { logout } = useAuth()
|
||||
const navigate = useNavigate()
|
||||
|
||||
return function handleAuthError(err) {
|
||||
if (err.status === 401) {
|
||||
logout()
|
||||
navigate('/connexion')
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
import { useState } from 'react'
|
||||
import { Link, useNavigate, useLocation } from 'react-router-dom'
|
||||
import { loginApi } from '../services/auth'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
|
||||
export default function Connexion() {
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
const { login } = useAuth()
|
||||
const justRegistered = location.state?.registered === true
|
||||
const [form, setForm] = useState({ email: '', password: '' })
|
||||
const [showPassword, setShowPassword] = useState(false)
|
||||
@@ -19,8 +21,7 @@ export default function Connexion() {
|
||||
setLoading(true)
|
||||
try {
|
||||
const { token, user } = await loginApi(form)
|
||||
localStorage.setItem('token', token)
|
||||
localStorage.setItem('user', JSON.stringify(user))
|
||||
login(user, token)
|
||||
if (user.role === 'ADMIN') navigate('/admin')
|
||||
else if (user.role === 'EMPLOYEE') navigate('/employe')
|
||||
else navigate('/mes-gains')
|
||||
|
||||
@@ -1,74 +1,211 @@
|
||||
import { useState } from 'react'
|
||||
import { searchTicketApi, deliverClaimApi } from '../services/employee'
|
||||
import { useHandleAuthError } from '../hooks/useHandleAuthError'
|
||||
|
||||
function formatDate(dateStr) {
|
||||
return new Date(dateStr).toLocaleDateString('fr-FR', {
|
||||
day: '2-digit',
|
||||
month: 'long',
|
||||
year: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
})
|
||||
}
|
||||
|
||||
const STATUS_CONFIG = {
|
||||
PENDING: { label: 'À remettre', classes: 'bg-yellow-100 text-yellow-800' },
|
||||
DELIVERED: { label: 'Déjà remis', classes: 'bg-green-100 text-green-800' },
|
||||
CANCELLED: { label: 'Expiré', classes: 'bg-gray-100 text-gray-500' },
|
||||
}
|
||||
|
||||
export default function Employe() {
|
||||
const [code, setCode] = useState('')
|
||||
const [gain, setGain] = useState(null)
|
||||
const handleAuthError = useHandleAuthError()
|
||||
const [code, setCode] = useState('')
|
||||
const [result, setResult] = useState(null)
|
||||
const [searching, setSearching] = useState(false)
|
||||
const [delivering, setDelivering] = useState(false)
|
||||
const [searchError, setSearchError] = useState('')
|
||||
const [deliverError, setDeliverError] = useState('')
|
||||
const [success, setSuccess] = useState(false)
|
||||
|
||||
const handleSearch = (e) => {
|
||||
const handleSearch = async (e) => {
|
||||
e.preventDefault()
|
||||
// TODO: connecter au backend
|
||||
setGain({
|
||||
code,
|
||||
lot: 'Thé signature (100g)',
|
||||
client: 'Jean Dupont',
|
||||
email: 'jean.dupont@email.com',
|
||||
status: 'PENDING',
|
||||
})
|
||||
setResult(null)
|
||||
setSuccess(false)
|
||||
setDeliverError('')
|
||||
setSearchError('')
|
||||
setSearching(true)
|
||||
try {
|
||||
const data = await searchTicketApi(code.trim())
|
||||
setResult(data)
|
||||
} catch (err) {
|
||||
if (!handleAuthError(err)) setSearchError(err.message)
|
||||
} finally {
|
||||
setSearching(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDeliver = () => {
|
||||
// TODO: connecter au backend
|
||||
setGain({ ...gain, status: 'DELIVERED' })
|
||||
const handleDeliver = async () => {
|
||||
if (!result?.claim?.id) return
|
||||
setDeliverError('')
|
||||
setDelivering(true)
|
||||
try {
|
||||
await deliverClaimApi(result.claim.id)
|
||||
setResult((prev) => ({
|
||||
...prev,
|
||||
claim: { ...prev.claim, status: 'DELIVERED', claimedAt: new Date().toISOString() },
|
||||
}))
|
||||
setSuccess(true)
|
||||
} catch (err) {
|
||||
if (!handleAuthError(err)) setDeliverError(err.message)
|
||||
} finally {
|
||||
setDelivering(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleReset = () => {
|
||||
setCode('')
|
||||
setResult(null)
|
||||
setSuccess(false)
|
||||
setSearchError('')
|
||||
setDeliverError('')
|
||||
}
|
||||
|
||||
const statusCfg = result ? (STATUS_CONFIG[result.claim?.status] ?? STATUS_CONFIG.PENDING) : null
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 p-4 sm:p-6">
|
||||
<div className="min-h-screen bg-gray-50 px-4 py-8 sm:py-12">
|
||||
<div className="max-w-lg mx-auto">
|
||||
<h1 className="text-xl sm:text-2xl font-bold text-gray-800 mb-1">Espace Employé</h1>
|
||||
<p className="text-gray-500 mb-5 sm:mb-6 text-sm sm:text-base">Vérifier et remettre un lot</p>
|
||||
|
||||
<form onSubmit={handleSearch} className="flex flex-col sm:flex-row gap-2 mb-5 sm:mb-6">
|
||||
{/* En-tête */}
|
||||
<div className="mb-8">
|
||||
<h1 className="text-2xl sm:text-3xl font-bold text-gray-900">Espace Employé</h1>
|
||||
<p className="text-gray-500 mt-1 text-sm">Recherchez un code ticket pour remettre le lot au client.</p>
|
||||
</div>
|
||||
|
||||
{/* Formulaire de recherche */}
|
||||
<form onSubmit={handleSearch} className="flex gap-2 mb-6">
|
||||
<input
|
||||
type="text"
|
||||
value={code}
|
||||
onChange={(e) => setCode(e.target.value)}
|
||||
onChange={(e) => setCode(e.target.value.toUpperCase())}
|
||||
required
|
||||
placeholder="Code ticket (TTT-XXXXX)"
|
||||
className="flex-1 border border-gray-300 rounded-lg px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-green-500 font-mono text-sm"
|
||||
placeholder="Code ticket (10 caractères)"
|
||||
maxLength={10}
|
||||
className="flex-1 border border-gray-300 rounded-lg px-4 py-3 text-sm font-mono uppercase tracking-widest focus:outline-none focus:ring-2 focus:ring-[#006B6B] focus:border-[#006B6B]"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
className="bg-green-700 hover:bg-green-800 text-white font-semibold px-5 py-2.5 rounded-lg transition-colors text-sm sm:text-base whitespace-nowrap"
|
||||
disabled={searching || code.trim().length === 0}
|
||||
className="bg-[#006B6B] hover:bg-[#005959] disabled:opacity-50 text-white font-semibold px-5 py-3 rounded-lg transition-colors text-sm whitespace-nowrap"
|
||||
>
|
||||
Rechercher
|
||||
{searching ? 'Recherche…' : 'Rechercher'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{gain && (
|
||||
<div className="bg-white rounded-xl shadow p-4 sm:p-6 space-y-3">
|
||||
<div className="flex flex-col sm:flex-row sm:justify-between sm:items-start gap-2">
|
||||
<div>
|
||||
<p className="font-bold text-gray-800 text-base sm:text-lg">{gain.lot}</p>
|
||||
<p className="text-xs sm:text-sm text-gray-500 font-mono">{gain.code}</p>
|
||||
</div>
|
||||
<span className={`self-start text-xs font-semibold px-3 py-1 rounded-full ${gain.status === 'DELIVERED' ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800'}`}>
|
||||
{gain.status === 'DELIVERED' ? 'Remis' : 'À remettre'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="border-t pt-3 space-y-1">
|
||||
<p className="text-sm text-gray-600"><span className="font-medium">Client :</span> {gain.client}</p>
|
||||
<p className="text-sm text-gray-600"><span className="font-medium">Email :</span> {gain.email}</p>
|
||||
</div>
|
||||
{gain.status === 'PENDING' && (
|
||||
<button
|
||||
onClick={handleDeliver}
|
||||
className="w-full bg-green-700 hover:bg-green-800 text-white font-semibold py-2.5 rounded-lg transition-colors mt-2 text-sm sm:text-base"
|
||||
>
|
||||
Confirmer la remise du lot
|
||||
</button>
|
||||
)}
|
||||
{/* Erreur de recherche */}
|
||||
{searchError && (
|
||||
<div className="mb-4 px-4 py-3 rounded-lg bg-red-50 border border-red-200 text-red-600 text-sm">
|
||||
{searchError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Résultat */}
|
||||
{result && (
|
||||
<div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
|
||||
|
||||
{/* Bandeau succès remise */}
|
||||
{success && (
|
||||
<div className="bg-green-500 px-5 py-3 flex items-center gap-3">
|
||||
<svg className="w-5 h-5 text-white flex-shrink-0" fill="none" stroke="currentColor" strokeWidth={2.5} viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
<p className="text-white text-sm font-semibold">Lot remis avec succès — espace client mis à jour.</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* En-tête carte : lot + statut */}
|
||||
<div className="px-5 py-4 flex items-start justify-between gap-3 border-b border-gray-100">
|
||||
<div>
|
||||
<p className="font-bold text-gray-900 text-base">{result.lot.name}</p>
|
||||
<p className="text-gray-500 text-xs mt-0.5">{result.lot.description}</p>
|
||||
{result.lot.value && (
|
||||
<p className="text-[#006B6B] text-xs font-semibold mt-1">Valeur : {result.lot.value} €</p>
|
||||
)}
|
||||
</div>
|
||||
<span className={`flex-shrink-0 text-xs font-semibold px-3 py-1 rounded-full ${statusCfg.classes}`}>
|
||||
{statusCfg.label}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Infos client */}
|
||||
<div className="px-5 py-4 space-y-2 border-b border-gray-100">
|
||||
<p className="text-xs text-gray-400 font-medium uppercase tracking-wider mb-2">Client</p>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-9 h-9 rounded-full bg-[#006B6B] flex items-center justify-center text-white text-sm font-bold flex-shrink-0">
|
||||
{(result.client.firstname?.[0] ?? '?').toUpperCase()}{(result.client.lastname?.[0] ?? '?').toUpperCase()}
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-semibold text-gray-800">
|
||||
{result.client.firstname} {result.client.lastname}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">{result.client.email}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Infos ticket */}
|
||||
<div className="px-5 py-4 space-y-1 border-b border-gray-100">
|
||||
<p className="text-xs text-gray-400 font-medium uppercase tracking-wider mb-2">Ticket</p>
|
||||
<p className="text-sm text-gray-700">
|
||||
<span className="font-medium">Code :</span>{' '}
|
||||
<span className="font-mono">{result.ticket.code}</span>
|
||||
</p>
|
||||
<p className="text-sm text-gray-700">
|
||||
<span className="font-medium">Utilisé le :</span> {formatDate(result.ticket.usedAt)}
|
||||
</p>
|
||||
{result.claim.claimedAt && (
|
||||
<p className="text-sm text-gray-700">
|
||||
<span className="font-medium">Remis le :</span> {formatDate(result.claim.claimedAt)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="px-5 py-4 space-y-3">
|
||||
{deliverError && (
|
||||
<div className="px-4 py-2 rounded-lg bg-red-50 border border-red-200 text-red-600 text-sm">
|
||||
{deliverError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{result.claim.status === 'PENDING' && !success && (
|
||||
<button
|
||||
onClick={handleDeliver}
|
||||
disabled={delivering}
|
||||
className="w-full bg-[#006B6B] hover:bg-[#005959] disabled:opacity-50 text-white font-semibold py-3 rounded-xl transition-colors text-sm"
|
||||
>
|
||||
{delivering ? 'Confirmation en cours…' : 'Confirmer la remise du lot'}
|
||||
</button>
|
||||
)}
|
||||
|
||||
{result.claim.status === 'CANCELLED' && (
|
||||
<div className="px-4 py-3 rounded-lg bg-gray-50 border border-gray-200 text-gray-500 text-sm text-center">
|
||||
Ce gain est expiré et ne peut plus être remis.
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
onClick={handleReset}
|
||||
className="w-full border border-gray-200 text-gray-600 hover:bg-gray-50 font-medium py-2.5 rounded-xl transition-colors text-sm"
|
||||
>
|
||||
Rechercher un autre code
|
||||
</button>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
)}
|
||||
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -15,7 +15,7 @@ export default function Inscription() {
|
||||
useEffect(() => {
|
||||
if (successName === null) return
|
||||
if (countdown === 0) {
|
||||
navigate('/saisir-code-unique')
|
||||
navigate('/connexion', { state: { registered: true } })
|
||||
return
|
||||
}
|
||||
const t = setTimeout(() => setCountdown((c) => c - 1), 1000)
|
||||
@@ -199,7 +199,7 @@ export default function Inscription() {
|
||||
Bienvenue {successName} !!
|
||||
</h2>
|
||||
<p className="text-gray-500 text-sm leading-relaxed">
|
||||
Votre compte a été créé avec succès. Vous serez redirigé vers l'étape suivante dans{' '}
|
||||
Votre compte a été créé avec succès. Un email de validation vous a été envoyé. Vous serez redirigé vers la connexion dans{' '}
|
||||
<span className="font-semibold text-[#006B6B]">{countdown}</span> secondes.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -1,32 +1,76 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { myGainsApi } from '../services/game'
|
||||
import UserNav from '../components/UserNav'
|
||||
import { useHandleAuthError } from '../hooks/useHandleAuthError'
|
||||
|
||||
function formatDate(dateStr) {
|
||||
return new Date(dateStr).toLocaleDateString('fr-FR', {
|
||||
day: '2-digit',
|
||||
month: '2-digit',
|
||||
year: 'numeric',
|
||||
})
|
||||
const date = new Date(dateStr)
|
||||
const dateLabel = date.toLocaleDateString('fr-FR', { day: '2-digit', month: 'long', year: 'numeric' })
|
||||
const timeLabel = date.toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' })
|
||||
return `${dateLabel} à ${timeLabel}`
|
||||
}
|
||||
|
||||
function timeAgo(dateStr) {
|
||||
const diff = Date.now() - new Date(dateStr).getTime()
|
||||
const minutes = Math.floor(diff / 60000)
|
||||
const hours = Math.floor(diff / 3600000)
|
||||
const days = Math.floor(diff / 86400000)
|
||||
if (minutes < 1) return "À l'instant"
|
||||
if (minutes < 60) return `Il y a ${minutes} min`
|
||||
if (hours < 24) return `Il y a ${hours}h`
|
||||
if (days < 7) return `Il y a ${days}j`
|
||||
return null
|
||||
}
|
||||
|
||||
const CLAIM_STATUS = {
|
||||
PENDING: { label: 'En attente de remise', classes: 'bg-yellow-100 text-yellow-700' },
|
||||
DELIVERED: { label: 'Lot remis', classes: 'bg-green-100 text-green-700' },
|
||||
CANCELLED: { label: 'Expiré', classes: 'bg-gray-100 text-gray-500' },
|
||||
}
|
||||
|
||||
export default function MesGains() {
|
||||
const [gains, setGains] = useState([])
|
||||
const handleAuthError = useHandleAuthError()
|
||||
const [gains, setGains] = useState([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [refreshing, setRefreshing] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
myGainsApi()
|
||||
.then((data) => setGains(data.gains))
|
||||
.catch((err) => setError(err.message))
|
||||
.finally(() => setLoading(false))
|
||||
}, [])
|
||||
const fetchGains = useCallback(async (isRefresh = false) => {
|
||||
if (isRefresh) setRefreshing(true)
|
||||
else setLoading(true)
|
||||
setError('')
|
||||
try {
|
||||
const data = await myGainsApi()
|
||||
setGains(data.gains)
|
||||
} catch (err) {
|
||||
if (!handleAuthError(err)) setError(err.message)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
setRefreshing(false)
|
||||
}
|
||||
}, [handleAuthError])
|
||||
|
||||
useEffect(() => { fetchGains() }, [fetchGains])
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-white max-w-sm mx-auto px-6 pt-6">
|
||||
<UserNav active="gains" />
|
||||
|
||||
{loading && <p className="text-center text-gray-400 text-sm mt-8">Chargement...</p>}
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="text-sm font-semibold text-gray-700">Historique de mes gains</h2>
|
||||
<button
|
||||
onClick={() => fetchGains(true)}
|
||||
disabled={refreshing}
|
||||
className="text-xs text-[#006B6B] hover:underline disabled:opacity-50 flex items-center gap-1"
|
||||
>
|
||||
<svg className={`w-3.5 h-3.5 ${refreshing ? 'animate-spin' : ''}`} fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M4 4v5h.582M20 20v-5h-.581M4.582 9A8 8 0 0120 15M19.418 15A8 8 0 014 9" />
|
||||
</svg>
|
||||
{refreshing ? 'Actualisation…' : 'Actualiser'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{loading && <p className="text-center text-gray-400 text-sm mt-8">Chargement…</p>}
|
||||
|
||||
{error && (
|
||||
<div className="px-4 py-3 rounded-lg bg-red-50 border border-red-200 text-red-600 text-sm">
|
||||
@@ -35,23 +79,50 @@ export default function MesGains() {
|
||||
)}
|
||||
|
||||
{!loading && !error && gains.length === 0 && (
|
||||
<p className="text-center text-gray-400 text-sm mt-8">Aucun gain pour le moment.</p>
|
||||
<div className="text-center mt-12">
|
||||
<p className="text-gray-400 text-sm">Aucun gain pour le moment.</p>
|
||||
<p className="text-gray-400 text-xs mt-1">Saisissez un code pour participer !</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="relative">
|
||||
{gains.map((gain, index) => (
|
||||
<div key={gain.participationId} className="flex gap-4">
|
||||
<div className="flex flex-col items-center">
|
||||
<div className="w-3 h-3 mt-1 rounded-full border-2 border-gray-400 flex-shrink-0" />
|
||||
{index < gains.length - 1 && <div className="w-px flex-1 bg-gray-200 my-1" />}
|
||||
{gains.map((gain, index) => {
|
||||
const statusCfg = CLAIM_STATUS[gain.claimStatus] ?? CLAIM_STATUS.PENDING
|
||||
return (
|
||||
<div key={gain.participationId} className="flex gap-4">
|
||||
<div className="flex flex-col items-center">
|
||||
<div className={`w-3 h-3 mt-1.5 rounded-full flex-shrink-0 border-2 ${
|
||||
gain.claimStatus === 'DELIVERED' ? 'border-[#006B6B] bg-[#006B6B]' : 'border-gray-300'
|
||||
}`} />
|
||||
{index < gains.length - 1 && <div className="w-px flex-1 bg-gray-200 my-1" />}
|
||||
</div>
|
||||
<div className={`flex-1 pb-6 ${index === 0 ? 'bg-gray-50 rounded-lg px-3 pt-2 -ml-1' : 'pt-1'}`}>
|
||||
<div className="flex items-start justify-between gap-2 flex-wrap">
|
||||
<p className="font-semibold text-gray-800 text-sm">{gain.lot}</p>
|
||||
<span className={`text-[10px] font-semibold px-2 py-0.5 rounded-full whitespace-nowrap ${statusCfg.classes}`}>
|
||||
{statusCfg.label}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-gray-500 text-xs mt-1 leading-relaxed">{gain.description}</p>
|
||||
{gain.value && (
|
||||
<p className="text-gray-400 text-xs mt-0.5">Valeur : {gain.value} €</p>
|
||||
)}
|
||||
<div className="flex items-center gap-2 mt-2 flex-wrap">
|
||||
<p className="text-[#006B6B] text-xs">Gagné le {formatDate(gain.wonAt)}</p>
|
||||
{timeAgo(gain.wonAt) && (
|
||||
<span className="text-[10px] font-medium text-white bg-[#006B6B]/70 px-1.5 py-0.5 rounded-full">
|
||||
{timeAgo(gain.wonAt)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-gray-400 text-[10px] mt-1">
|
||||
Code utilisé :{' '}
|
||||
<span className="font-mono tracking-widest text-gray-600">{gain.ticketCode}</span>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className={`flex-1 pb-6 ${index === 0 ? 'bg-gray-50 rounded-lg px-3 pt-1 -ml-1' : ''}`}>
|
||||
<p className="font-semibold text-gray-800 text-sm">{gain.lot}</p>
|
||||
<p className="text-gray-500 text-xs mt-1 leading-relaxed">{gain.description}</p>
|
||||
<p className="text-[#006B6B] text-xs mt-2">Gain obtenu le {formatDate(gain.wonAt)}</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -1,54 +1,150 @@
|
||||
import { useState } from 'react'
|
||||
import UserNav from '../components/UserNav'
|
||||
import { changePasswordApi } from '../services/auth'
|
||||
import { useHandleAuthError } from '../hooks/useHandleAuthError'
|
||||
|
||||
export default function Profile() {
|
||||
const user = JSON.parse(localStorage.getItem('user') || '{}')
|
||||
const initials = `${(user.firstname || '?')[0]}${(user.lastname || '?')[0]}`.toUpperCase()
|
||||
const handleAuthError = useHandleAuthError()
|
||||
|
||||
const handleSubmit = (e) => {
|
||||
const [pwForm, setPwForm] = useState({ currentPassword: '', newPassword: '', confirmPassword: '' })
|
||||
const [showPw, setShowPw] = useState({ current: false, new: false, confirm: false })
|
||||
const [pwLoading, setPwLoading] = useState(false)
|
||||
const [pwError, setPwError] = useState('')
|
||||
const [pwSuccess, setPwSuccess] = useState(false)
|
||||
|
||||
const handlePwChange = (e) => setPwForm({ ...pwForm, [e.target.name]: e.target.value })
|
||||
|
||||
const handlePwSubmit = async (e) => {
|
||||
e.preventDefault()
|
||||
// TODO: connecter au backend pour update profil
|
||||
alert('Modification du profil à venir')
|
||||
setPwError('')
|
||||
setPwSuccess(false)
|
||||
|
||||
if (pwForm.newPassword !== pwForm.confirmPassword) {
|
||||
setPwError('Les nouveaux mots de passe ne correspondent pas.')
|
||||
return
|
||||
}
|
||||
if (pwForm.newPassword.length < 8) {
|
||||
setPwError('Le nouveau mot de passe doit faire au moins 8 caractères.')
|
||||
return
|
||||
}
|
||||
|
||||
setPwLoading(true)
|
||||
try {
|
||||
await changePasswordApi({ currentPassword: pwForm.currentPassword, newPassword: pwForm.newPassword })
|
||||
setPwSuccess(true)
|
||||
setPwForm({ currentPassword: '', newPassword: '', confirmPassword: '' })
|
||||
} catch (err) {
|
||||
if (!handleAuthError(err)) setPwError(err.message)
|
||||
} finally {
|
||||
setPwLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const EyeIcon = ({ visible }) => (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">
|
||||
{visible
|
||||
? <><path strokeLinecap="round" strokeLinejoin="round" d="M2.036 12.322a1.012 1.012 0 010-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178z" /><path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" /></>
|
||||
: <path strokeLinecap="round" strokeLinejoin="round" d="M3.98 8.223A10.477 10.477 0 001.934 12C3.226 16.338 7.244 19.5 12 19.5c.993 0 1.953-.138 2.863-.395M6.228 6.228A10.45 10.45 0 0112 4.5c4.756 0 8.773 3.162 10.065 7.498a10.523 10.523 0 01-4.293 5.774M6.228 6.228L3 3m3.228 3.228l3.65 3.65m7.894 7.894L21 21m-3.228-3.228l-3.65-3.65m0 0a3 3 0 10-4.243-4.243m4.242 4.242L9.88 9.88" />
|
||||
}
|
||||
</svg>
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-white max-w-sm mx-auto px-6 pt-6">
|
||||
<div className="min-h-screen bg-white max-w-sm mx-auto px-6 pt-6 pb-10">
|
||||
<UserNav active="profile" />
|
||||
|
||||
{/* Avatar */}
|
||||
<div className="mb-6">
|
||||
<div className="w-14 h-14 rounded-full bg-[#006B6B] flex items-center justify-center text-white text-lg font-bold">
|
||||
{initials}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-5">
|
||||
{/* Infos du compte (lecture seule) */}
|
||||
<div className="space-y-4 mb-8">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-800 mb-1">Adresse email</label>
|
||||
<input
|
||||
type="email"
|
||||
readOnly
|
||||
value={user.email || ''}
|
||||
className="w-full border border-gray-200 rounded-lg px-4 py-3 text-sm text-gray-700 bg-gray-50 cursor-not-allowed"
|
||||
/>
|
||||
<label className="block text-xs font-medium text-gray-400 uppercase tracking-wider mb-1">Adresse email</label>
|
||||
<div className="w-full border border-gray-100 rounded-lg px-4 py-3 text-sm text-gray-400 bg-gray-50 cursor-not-allowed select-none">
|
||||
{user.email || '—'}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-800 mb-1">Nom</label>
|
||||
<div className="w-full border border-gray-200 rounded-lg px-4 py-3 text-sm text-gray-700 bg-gray-50">
|
||||
<label className="block text-xs font-medium text-gray-400 uppercase tracking-wider mb-1">Nom</label>
|
||||
<div className="w-full border border-gray-100 rounded-lg px-4 py-3 text-sm text-gray-500 bg-gray-50">
|
||||
{user.lastname || '—'}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-800 mb-1">Prénom</label>
|
||||
<div className="w-full border border-gray-200 rounded-lg px-4 py-3 text-sm text-gray-700 bg-gray-50">
|
||||
<label className="block text-xs font-medium text-gray-400 uppercase tracking-wider mb-1">Prénom</label>
|
||||
<div className="w-full border border-gray-100 rounded-lg px-4 py-3 text-sm text-gray-500 bg-gray-50">
|
||||
{user.firstname || '—'}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="submit"
|
||||
className="w-full bg-[#006B6B] hover:bg-[#005959] text-white font-medium py-3 rounded-lg transition-colors"
|
||||
>
|
||||
Modifier mon profil
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{/* Séparateur */}
|
||||
<div className="border-t border-gray-100 mb-6" />
|
||||
|
||||
{/* Section changement de mot de passe */}
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold text-gray-800 mb-4">Changer mon mot de passe</h2>
|
||||
|
||||
{pwSuccess && (
|
||||
<div className="mb-4 px-4 py-3 rounded-lg bg-green-50 border border-green-200 text-green-700 text-sm flex items-center gap-2">
|
||||
<svg className="w-4 h-4 flex-shrink-0" fill="none" stroke="currentColor" strokeWidth={2.5} viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
Mot de passe modifié avec succès.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{pwError && (
|
||||
<div className="mb-4 px-4 py-3 rounded-lg bg-red-50 border border-red-200 text-red-600 text-sm">
|
||||
{pwError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handlePwSubmit} className="space-y-4">
|
||||
{[
|
||||
{ name: 'currentPassword', label: 'Mot de passe actuel', key: 'current' },
|
||||
{ name: 'newPassword', label: 'Nouveau mot de passe', key: 'new' },
|
||||
{ name: 'confirmPassword', label: 'Confirmer le nouveau mot de passe', key: 'confirm' },
|
||||
].map(({ name, label, key }) => (
|
||||
<div key={name}>
|
||||
<label className="block text-sm font-medium text-gray-800 mb-1">{label}</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type={showPw[key] ? 'text' : 'password'}
|
||||
name={name}
|
||||
value={pwForm[name]}
|
||||
onChange={handlePwChange}
|
||||
required
|
||||
placeholder="••••••••"
|
||||
className="w-full border border-gray-200 rounded-lg px-4 py-3 pr-11 text-sm text-gray-700 placeholder-gray-300 focus:outline-none focus:ring-1 focus:ring-[#006B6B] focus:border-[#006B6B]"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPw((s) => ({ ...s, [key]: !s[key] }))}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
|
||||
aria-label="Afficher/masquer"
|
||||
>
|
||||
<EyeIcon visible={showPw[key]} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={pwLoading}
|
||||
className="w-full bg-[#006B6B] hover:bg-[#005959] disabled:opacity-50 text-white font-medium py-3 rounded-lg transition-colors text-sm"
|
||||
>
|
||||
{pwLoading ? 'Modification…' : 'Modifier le mot de passe'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2,12 +2,24 @@ import { useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { participateApi } from '../services/game'
|
||||
import UserNav from '../components/UserNav'
|
||||
import { useHandleAuthError } from '../hooks/useHandleAuthError'
|
||||
|
||||
function formatDateTime(date) {
|
||||
return date.toLocaleDateString('fr-FR', {
|
||||
day: '2-digit', month: 'long', year: 'numeric',
|
||||
hour: '2-digit', minute: '2-digit',
|
||||
})
|
||||
}
|
||||
|
||||
export default function SaisirCodeUnique() {
|
||||
const navigate = useNavigate()
|
||||
const [code, setCode] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [gain, setGain] = useState(null)
|
||||
const handleAuthError = useHandleAuthError()
|
||||
const [code, setCode] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [gain, setGain] = useState(null)
|
||||
const [claim, setClaim] = useState(null)
|
||||
const [wonAt, setWonAt] = useState(null)
|
||||
const [showDetail, setShowDetail] = useState(false)
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault()
|
||||
@@ -15,16 +27,27 @@ export default function SaisirCodeUnique() {
|
||||
try {
|
||||
const data = await participateApi(code.trim().toUpperCase())
|
||||
setGain(data.gain)
|
||||
setClaim(data.claim)
|
||||
setWonAt(new Date())
|
||||
} catch (err) {
|
||||
navigate('/perdu', { state: { message: err.message } })
|
||||
if (!handleAuthError(err)) {
|
||||
navigate('/perdu', { state: { message: err.message } })
|
||||
}
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleClose = () => {
|
||||
setGain(null)
|
||||
setClaim(null)
|
||||
setWonAt(null)
|
||||
setShowDetail(false)
|
||||
setCode('')
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 flex flex-col justify-center px-8 py-12 max-w-sm mx-auto">
|
||||
|
||||
<UserNav active="code" />
|
||||
|
||||
<div className="mb-8">
|
||||
@@ -42,7 +65,6 @@ export default function SaisirCodeUnique() {
|
||||
required
|
||||
className="w-full border border-gray-200 rounded-lg px-4 py-3 text-sm text-gray-700 placeholder-gray-300 bg-white focus:outline-none focus:ring-1 focus:ring-[#006B6B] focus:border-[#006B6B]"
|
||||
/>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading || code.length !== 10}
|
||||
@@ -52,8 +74,8 @@ export default function SaisirCodeUnique() {
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{/* Overlay Félicitation */}
|
||||
{gain && (
|
||||
{/* ── Overlay Félicitation ── */}
|
||||
{gain && !showDetail && (
|
||||
<div className="fixed inset-0 bg-black/60 flex flex-col items-center justify-between z-50 px-6 py-12">
|
||||
<div className="w-full max-w-sm">
|
||||
<h2 className="text-4xl font-bold italic font-serif text-white mb-1">Félicitation !</h2>
|
||||
@@ -61,13 +83,11 @@ export default function SaisirCodeUnique() {
|
||||
</div>
|
||||
|
||||
<div className="flex-1 flex items-center justify-center">
|
||||
{/* Code saisi */}
|
||||
<div className="bg-white/10 rounded-lg px-6 py-3 mb-6 text-white font-mono tracking-widest text-lg">
|
||||
<div className="bg-white/10 rounded-lg px-6 py-3 text-white font-mono tracking-widest text-lg">
|
||||
{code}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Icône décorative */}
|
||||
<div className="mb-8">
|
||||
<svg className="w-24 h-24 text-yellow-200" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M12 2l2.4 7.4H22l-6.2 4.5 2.4 7.4L12 17l-6.2 4.3 2.4-7.4L2 9.4h7.6z" />
|
||||
@@ -78,7 +98,7 @@ export default function SaisirCodeUnique() {
|
||||
<p className="text-white text-center font-semibold mb-1">{gain.name}</p>
|
||||
<p className="text-white/70 text-center text-sm mb-6">{gain.description}</p>
|
||||
<button
|
||||
onClick={() => navigate('/mes-gains')}
|
||||
onClick={() => setShowDetail(true)}
|
||||
className="w-full bg-[#006B6B] hover:bg-[#005959] text-white font-medium py-3 rounded-lg transition-colors"
|
||||
>
|
||||
Découvrir mon lot
|
||||
@@ -86,6 +106,102 @@ export default function SaisirCodeUnique() {
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── Modal détail du lot ── */}
|
||||
{gain && showDetail && (
|
||||
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 px-4">
|
||||
<div className="bg-white rounded-2xl w-full max-w-sm shadow-xl overflow-hidden">
|
||||
|
||||
{/* En-tête coloré */}
|
||||
<div className="bg-[#006B6B] px-6 py-5 relative">
|
||||
<button
|
||||
onClick={handleClose}
|
||||
className="absolute top-4 right-4 text-white/70 hover:text-white transition-colors"
|
||||
aria-label="Fermer"
|
||||
>
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-10 h-10 rounded-full bg-white/20 flex items-center justify-center">
|
||||
<svg className="w-5 h-5 text-yellow-200" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M12 2l2.4 7.4H22l-6.2 4.5 2.4 7.4L12 17l-6.2 4.3 2.4-7.4L2 9.4h7.6z" />
|
||||
</svg>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-white/70 text-xs">Votre lot</p>
|
||||
<p className="text-white font-bold text-base leading-tight">{gain.name}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Corps */}
|
||||
<div className="px-6 py-5 space-y-4">
|
||||
|
||||
{/* Description */}
|
||||
<p className="text-gray-600 text-sm leading-relaxed">{gain.description}</p>
|
||||
|
||||
{/* Valeur */}
|
||||
{gain.value && (
|
||||
<div className="flex items-center justify-between py-2 border-b border-gray-100">
|
||||
<span className="text-xs text-gray-400 uppercase tracking-wider">Valeur estimée</span>
|
||||
<span className="text-sm font-semibold text-[#006B6B]">{gain.value} €</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Code utilisé */}
|
||||
<div className="flex items-center justify-between py-2 border-b border-gray-100">
|
||||
<span className="text-xs text-gray-400 uppercase tracking-wider">Code utilisé</span>
|
||||
<span className="font-mono text-sm tracking-widest text-gray-700">{code}</span>
|
||||
</div>
|
||||
|
||||
{/* Date & heure */}
|
||||
{wonAt && (
|
||||
<div className="flex items-center justify-between py-2 border-b border-gray-100">
|
||||
<span className="text-xs text-gray-400 uppercase tracking-wider">Obtenu le</span>
|
||||
<span className="text-sm text-gray-700">{formatDateTime(wonAt)}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Statut */}
|
||||
<div className="flex items-center justify-between py-2">
|
||||
<span className="text-xs text-gray-400 uppercase tracking-wider">Statut</span>
|
||||
<span className="text-xs font-semibold px-2.5 py-1 rounded-full bg-yellow-100 text-yellow-700">
|
||||
En attente de remise
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Info remise */}
|
||||
<div className="bg-[#006B6B]/5 rounded-xl px-4 py-3 flex gap-3 items-start">
|
||||
<svg className="w-4 h-4 text-[#006B6B] flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<p className="text-xs text-[#006B6B] leading-relaxed">
|
||||
Présentez ce code en boutique Thé Tip Top pour récupérer votre lot.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="px-6 pb-6 space-y-2">
|
||||
<button
|
||||
onClick={() => navigate('/mes-gains')}
|
||||
className="w-full bg-[#006B6B] hover:bg-[#005959] text-white font-medium py-3 rounded-xl transition-colors text-sm"
|
||||
>
|
||||
Voir tout mon historique
|
||||
</button>
|
||||
<button
|
||||
onClick={handleClose}
|
||||
className="w-full border border-gray-200 text-gray-500 hover:bg-gray-50 font-medium py-2.5 rounded-xl transition-colors text-sm"
|
||||
>
|
||||
Retour
|
||||
</button>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -5,24 +5,30 @@ function authHeaders() {
|
||||
}
|
||||
}
|
||||
|
||||
function apiError(message, status) {
|
||||
const err = new Error(message)
|
||||
err.status = status
|
||||
return err
|
||||
}
|
||||
|
||||
export async function getStatsApi() {
|
||||
const res = await fetch('/api/admin/stats', { headers: authHeaders() })
|
||||
const data = await res.json()
|
||||
if (!res.ok) throw new Error(data.message || 'Erreur stats.')
|
||||
if (!res.ok) throw apiError(data.message || 'Erreur stats.', res.status)
|
||||
return data
|
||||
}
|
||||
|
||||
export async function getUsersApi() {
|
||||
const res = await fetch('/api/admin/users', { headers: authHeaders() })
|
||||
const data = await res.json()
|
||||
if (!res.ok) throw new Error(data.message || 'Erreur utilisateurs.')
|
||||
if (!res.ok) throw apiError(data.message || 'Erreur utilisateurs.', res.status)
|
||||
return data
|
||||
}
|
||||
|
||||
export async function drawWinnerApi() {
|
||||
const res = await fetch('/api/admin/draw', { method: 'POST', headers: authHeaders() })
|
||||
const data = await res.json()
|
||||
if (!res.ok) throw new Error(data.message || 'Erreur tirage.')
|
||||
if (!res.ok) throw apiError(data.message || 'Erreur tirage.', res.status)
|
||||
return data
|
||||
}
|
||||
|
||||
@@ -30,6 +36,6 @@ export async function getWinnerApi() {
|
||||
const res = await fetch('/api/admin/draw', { headers: authHeaders() })
|
||||
if (res.status === 404) return null
|
||||
const data = await res.json()
|
||||
if (!res.ok) throw new Error(data.message || 'Erreur gagnant.')
|
||||
if (!res.ok) throw apiError(data.message || 'Erreur gagnant.', res.status)
|
||||
return data
|
||||
}
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
const BASE = '/api/auth'
|
||||
|
||||
function apiError(message, status) {
|
||||
const err = new Error(message)
|
||||
err.status = status
|
||||
return err
|
||||
}
|
||||
|
||||
export async function loginApi({ email, password }) {
|
||||
const res = await fetch(`${BASE}/login`, {
|
||||
method: 'POST',
|
||||
@@ -7,7 +13,7 @@ export async function loginApi({ email, password }) {
|
||||
body: JSON.stringify({ email, password }),
|
||||
})
|
||||
const data = await res.json()
|
||||
if (!res.ok) throw new Error(data.message || 'Erreur de connexion.')
|
||||
if (!res.ok) throw apiError(data.message || 'Erreur de connexion.', res.status)
|
||||
return data
|
||||
}
|
||||
|
||||
@@ -18,6 +24,21 @@ export async function registerApi({ email, firstname, lastname, password }) {
|
||||
body: JSON.stringify({ email, firstname, lastname, password }),
|
||||
})
|
||||
const data = await res.json()
|
||||
if (!res.ok) throw new Error(data.message || "Erreur lors de l'inscription.")
|
||||
if (!res.ok) throw apiError(data.message || "Erreur lors de l'inscription.", res.status)
|
||||
return data
|
||||
}
|
||||
|
||||
export async function changePasswordApi({ currentPassword, newPassword }) {
|
||||
const token = localStorage.getItem('token')
|
||||
const res = await fetch(`${BASE}/change-password`, {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify({ currentPassword, newPassword }),
|
||||
})
|
||||
const data = await res.json()
|
||||
if (!res.ok) throw apiError(data.message || 'Erreur lors du changement de mot de passe.', res.status)
|
||||
return data
|
||||
}
|
||||
|
||||
31
frontend/src/services/employee.js
Normal file
31
frontend/src/services/employee.js
Normal file
@@ -0,0 +1,31 @@
|
||||
const BASE = '/api/employee'
|
||||
|
||||
function authHeaders() {
|
||||
const token = localStorage.getItem('token')
|
||||
return { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` }
|
||||
}
|
||||
|
||||
function apiError(message, status) {
|
||||
const err = new Error(message)
|
||||
err.status = status
|
||||
return err
|
||||
}
|
||||
|
||||
export async function searchTicketApi(code) {
|
||||
const res = await fetch(`${BASE}/ticket/${encodeURIComponent(code.toUpperCase())}`, {
|
||||
headers: authHeaders(),
|
||||
})
|
||||
const data = await res.json()
|
||||
if (!res.ok) throw apiError(data.message || 'Erreur lors de la recherche.', res.status)
|
||||
return data
|
||||
}
|
||||
|
||||
export async function deliverClaimApi(claimId) {
|
||||
const res = await fetch(`${BASE}/claim/${claimId}/deliver`, {
|
||||
method: 'PATCH',
|
||||
headers: authHeaders(),
|
||||
})
|
||||
const data = await res.json()
|
||||
if (!res.ok) throw apiError(data.message || 'Erreur lors de la remise.', res.status)
|
||||
return data
|
||||
}
|
||||
@@ -1,10 +1,16 @@
|
||||
function apiError(message, status) {
|
||||
const err = new Error(message)
|
||||
err.status = status
|
||||
return err
|
||||
}
|
||||
|
||||
export async function myGainsApi() {
|
||||
const token = localStorage.getItem('token')
|
||||
const res = await fetch('/api/game/my-gains', {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
const data = await res.json()
|
||||
if (!res.ok) throw new Error(data.message || 'Erreur lors de la récupération des gains.')
|
||||
if (!res.ok) throw apiError(data.message || 'Erreur lors de la récupération des gains.', res.status)
|
||||
return data
|
||||
}
|
||||
|
||||
@@ -19,6 +25,6 @@ export async function participateApi(code) {
|
||||
body: JSON.stringify({ code }),
|
||||
})
|
||||
const data = await res.json()
|
||||
if (!res.ok) throw new Error(data.message || 'Erreur lors de la participation.')
|
||||
if (!res.ok) throw apiError(data.message || 'Erreur lors de la participation.', res.status)
|
||||
return data
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user