Compare commits
21 Commits
1450c0b4c9
...
release-1.
| Author | SHA1 | Date | |
|---|---|---|---|
| d56b91479f | |||
| 7c1e4cf3e2 | |||
| 3a5eed6b96 | |||
| e8080be405 | |||
| 82d3daf20f | |||
| 13584d2b0f | |||
| 9bf038278a | |||
| 10cffd77cb | |||
| 25fcd9974a | |||
| 536faaefd5 | |||
| 9edb3255e8 | |||
| b96c0b50ab | |||
| 8dce8b238c | |||
| abd14b713e | |||
| a7cafd1400 | |||
| 6e65c0392c | |||
| e257da41b0 | |||
| 89e49bc56d | |||
| a0869f6f65 | |||
| 4c2849611f | |||
| 279a071a15 |
16
Jenkinsfile
vendored
16
Jenkinsfile
vendored
@@ -83,12 +83,17 @@ pipeline {
|
|||||||
env.FRONTEND_API_URL = ''
|
env.FRONTEND_API_URL = ''
|
||||||
env.FRONTEND_GA_ID = ""
|
env.FRONTEND_GA_ID = ""
|
||||||
}
|
}
|
||||||
|
env.TURNSTILE_SITE_KEY = sh(
|
||||||
|
script: "grep '^TURNSTILE_SITE_KEY=' /opt/furious-ducks/secrets/tiptop-mail.env | cut -d= -f2-",
|
||||||
|
returnStdout: true
|
||||||
|
).trim()
|
||||||
|
|
||||||
echo "Branche : ${env.BRANCH_NAME}"
|
echo "Branche : ${env.BRANCH_NAME}"
|
||||||
echo "Tag Docker : ${env.IMAGE_TAG}"
|
echo "Tag Docker : ${env.IMAGE_TAG}"
|
||||||
echo "Environnement : ${env.DEPLOY_ENV}"
|
echo "Environnement : ${env.DEPLOY_ENV}"
|
||||||
echo "Déploiement activé : ${env.DEPLOY_ENABLED}"
|
echo "Déploiement activé : ${env.DEPLOY_ENABLED}"
|
||||||
echo "API frontend : ${env.FRONTEND_API_URL}"
|
echo "API frontend : ${env.FRONTEND_API_URL}"
|
||||||
|
echo "Turnstile : ${env.TURNSTILE_SITE_KEY ? '[SET]' : '[EMPTY]'}"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -219,8 +224,8 @@ pipeline {
|
|||||||
docker run --rm \
|
docker run --rm \
|
||||||
--volumes-from furious-jenkins \
|
--volumes-from furious-jenkins \
|
||||||
-v tiptop-npm-cache-frontend:/npm-cache \
|
-v tiptop-npm-cache-frontend:/npm-cache \
|
||||||
--user "$(id -u):$(id -g)" \
|
|
||||||
-e HOME=/tmp \
|
-e HOME=/tmp \
|
||||||
|
-e CHROMIUM_PATH=/usr/bin/chromium \
|
||||||
-e NODE_OPTIONS=--dns-result-order=ipv4first \
|
-e NODE_OPTIONS=--dns-result-order=ipv4first \
|
||||||
-e NPM_CONFIG_CACHE=/npm-cache \
|
-e NPM_CONFIG_CACHE=/npm-cache \
|
||||||
-e NPM_CONFIG_FETCH_RETRIES=5 \
|
-e NPM_CONFIG_FETCH_RETRIES=5 \
|
||||||
@@ -230,6 +235,8 @@ pipeline {
|
|||||||
-w "${WORKSPACE}/frontend" \
|
-w "${WORKSPACE}/frontend" \
|
||||||
node:22-alpine \
|
node:22-alpine \
|
||||||
sh -c "
|
sh -c "
|
||||||
|
apk add --no-cache chromium nss freetype harfbuzz ca-certificates ttf-freefont &&
|
||||||
|
export CHROMIUM_PATH=/usr/bin/chromium &&
|
||||||
npm ci --prefer-offline --no-audit --no-fund &&
|
npm ci --prefer-offline --no-audit --no-fund &&
|
||||||
npm run lint &&
|
npm run lint &&
|
||||||
npm run test:coverage &&
|
npm run test:coverage &&
|
||||||
@@ -327,6 +334,13 @@ stage('SonarQube Quality Gate') {
|
|||||||
|
|
||||||
steps {
|
steps {
|
||||||
sh '''
|
sh '''
|
||||||
|
set -a
|
||||||
|
. /opt/furious-ducks/secrets/tiptop-mail.env
|
||||||
|
set +a
|
||||||
|
|
||||||
|
test -n "${TURNSTILE_SITE_KEY}"
|
||||||
|
echo "Turnstile site key chargée (longueur: ${#TURNSTILE_SITE_KEY})"
|
||||||
|
|
||||||
docker build \
|
docker build \
|
||||||
-t "${BACKEND_IMAGE}:${IMAGE_TAG}" \
|
-t "${BACKEND_IMAGE}:${IMAGE_TAG}" \
|
||||||
backend
|
backend
|
||||||
|
|||||||
@@ -42,12 +42,12 @@ services:
|
|||||||
|
|
||||||
# Injectés par le pipeline, jamais commités. Vides, les routes de
|
# Injectés par le pipeline, jamais commités. Vides, les routes de
|
||||||
# connexion externe répondent 503 sans bloquer le démarrage.
|
# connexion externe répondent 503 sans bloquer le démarrage.
|
||||||
GOOGLE_CLIENT_ID: "${GOOGLE_CLIENT_ID:-}"
|
GOOGLE_CLIENT_ID: "${GOOGLE_CLIENT_ID}"
|
||||||
GOOGLE_CLIENT_SECRET: "${GOOGLE_CLIENT_SECRET:-}"
|
GOOGLE_CLIENT_SECRET: "${GOOGLE_CLIENT_SECRET}"
|
||||||
FACEBOOK_APP_ID: "${FACEBOOK_APP_ID:-}"
|
FACEBOOK_APP_ID: "${FACEBOOK_APP_ID}"
|
||||||
FACEBOOK_APP_SECRET: "${FACEBOOK_APP_SECRET:-}"
|
FACEBOOK_APP_SECRET: "${FACEBOOK_APP_SECRET}"
|
||||||
# Vide, la vérification anti-robot Turnstile est désactivée.
|
# Vide, la vérification anti-robot Turnstile est désactivée.
|
||||||
TURNSTILE_SECRET_KEY: "${TURNSTILE_SECRET_KEY:-}"
|
TURNSTILE_SECRET_KEY: "${TURNSTILE_SECRET_KEY}"
|
||||||
|
|
||||||
command: >
|
command: >
|
||||||
sh -c "
|
sh -c "
|
||||||
|
|||||||
@@ -42,12 +42,12 @@ services:
|
|||||||
|
|
||||||
# Injectés par le pipeline, jamais commités. Vides, les routes de
|
# Injectés par le pipeline, jamais commités. Vides, les routes de
|
||||||
# connexion externe répondent 503 sans bloquer le démarrage.
|
# connexion externe répondent 503 sans bloquer le démarrage.
|
||||||
GOOGLE_CLIENT_ID: "${GOOGLE_CLIENT_ID:-}"
|
GOOGLE_CLIENT_ID: "${GOOGLE_CLIENT_ID}"
|
||||||
GOOGLE_CLIENT_SECRET: "${GOOGLE_CLIENT_SECRET:-}"
|
GOOGLE_CLIENT_SECRET: "${GOOGLE_CLIENT_SECRET}"
|
||||||
FACEBOOK_APP_ID: "${FACEBOOK_APP_ID:-}"
|
FACEBOOK_APP_ID: "${FACEBOOK_APP_ID}"
|
||||||
FACEBOOK_APP_SECRET: "${FACEBOOK_APP_SECRET:-}"
|
FACEBOOK_APP_SECRET: "${FACEBOOK_APP_SECRET}"
|
||||||
# Vide, la vérification anti-robot Turnstile est désactivée.
|
# Vide, la vérification anti-robot Turnstile est désactivée.
|
||||||
TURNSTILE_SECRET_KEY: "${TURNSTILE_SECRET_KEY:-}"
|
TURNSTILE_SECRET_KEY: "${TURNSTILE_SECRET_KEY}"
|
||||||
|
|
||||||
command: >
|
command: >
|
||||||
sh -c "
|
sh -c "
|
||||||
|
|||||||
@@ -42,12 +42,12 @@ services:
|
|||||||
|
|
||||||
# Injectés par le pipeline, jamais commités. Vides, les routes de
|
# Injectés par le pipeline, jamais commités. Vides, les routes de
|
||||||
# connexion externe répondent 503 sans bloquer le démarrage.
|
# connexion externe répondent 503 sans bloquer le démarrage.
|
||||||
GOOGLE_CLIENT_ID: "${GOOGLE_CLIENT_ID:-}"
|
GOOGLE_CLIENT_ID: "${GOOGLE_CLIENT_ID}"
|
||||||
GOOGLE_CLIENT_SECRET: "${GOOGLE_CLIENT_SECRET:-}"
|
GOOGLE_CLIENT_SECRET: "${GOOGLE_CLIENT_SECRET}"
|
||||||
FACEBOOK_APP_ID: "${FACEBOOK_APP_ID:-}"
|
FACEBOOK_APP_ID: "${FACEBOOK_APP_ID}"
|
||||||
FACEBOOK_APP_SECRET: "${FACEBOOK_APP_SECRET:-}"
|
FACEBOOK_APP_SECRET: "${FACEBOOK_APP_SECRET}"
|
||||||
# Vide, la vérification anti-robot Turnstile est désactivée.
|
# Vide, la vérification anti-robot Turnstile est désactivée.
|
||||||
TURNSTILE_SECRET_KEY: "${TURNSTILE_SECRET_KEY:-}"
|
TURNSTILE_SECRET_KEY: "${TURNSTILE_SECRET_KEY}"
|
||||||
|
|
||||||
command: >
|
command: >
|
||||||
sh -c "
|
sh -c "
|
||||||
|
|||||||
@@ -30,7 +30,10 @@ async function main() {
|
|||||||
const server = await preview({ root, preview: { port: 4173, strictPort: false } })
|
const server = await preview({ root, preview: { port: 4173, strictPort: false } })
|
||||||
const base = server.resolvedUrls.local[0].replace(/\/$/, '')
|
const base = server.resolvedUrls.local[0].replace(/\/$/, '')
|
||||||
|
|
||||||
const browser = await chromium.launch()
|
const browser = await chromium.launch({
|
||||||
|
executablePath: process.env.CHROMIUM_PATH || chromium.executablePath(),
|
||||||
|
headless: true,
|
||||||
|
})
|
||||||
const page = await browser.newPage()
|
const page = await browser.newPage()
|
||||||
|
|
||||||
for (const route of ROUTES) {
|
for (const route of ROUTES) {
|
||||||
|
|||||||
@@ -1,19 +1,124 @@
|
|||||||
import { Turnstile } from '@marsidev/react-turnstile'
|
import { useEffect, useRef } from 'react'
|
||||||
import { CAPTCHA_ENABLED, TURNSTILE_SITE_KEY } from '../config/captcha'
|
import { CAPTCHA_ENABLED, TURNSTILE_SITE_KEY } from '../config/captcha'
|
||||||
|
|
||||||
// `ref` expose reset() : un jeton Turnstile n'est valable qu'une fois, il faut
|
const TURNSTILE_SCRIPT_ID = 'cf-turnstile-script'
|
||||||
// en redemander un après chaque envoi refusé.
|
const TURNSTILE_SCRIPT_URL =
|
||||||
export default function Captcha({ ref, onToken }) {
|
'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit'
|
||||||
if (!CAPTCHA_ENABLED) return null
|
|
||||||
|
export default function Captcha({ onToken }) {
|
||||||
|
const containerRef = useRef(null)
|
||||||
|
const widgetIdRef = useRef(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!CAPTCHA_ENABLED || !TURNSTILE_SITE_KEY || !containerRef.current) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
let cancelled = false
|
||||||
|
|
||||||
|
const renderWidget = () => {
|
||||||
|
if (
|
||||||
|
cancelled ||
|
||||||
|
!containerRef.current ||
|
||||||
|
!window.turnstile
|
||||||
|
) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (widgetIdRef.current !== null) {
|
||||||
|
try {
|
||||||
|
window.turnstile.remove(widgetIdRef.current)
|
||||||
|
} catch {
|
||||||
|
// Widget déjà supprimé
|
||||||
|
}
|
||||||
|
|
||||||
|
widgetIdRef.current = null
|
||||||
|
}
|
||||||
|
|
||||||
|
containerRef.current.innerHTML = ''
|
||||||
|
|
||||||
|
widgetIdRef.current = window.turnstile.render(
|
||||||
|
containerRef.current,
|
||||||
|
{
|
||||||
|
sitekey: TURNSTILE_SITE_KEY,
|
||||||
|
language: 'fr',
|
||||||
|
size: 'flexible',
|
||||||
|
appearance: 'always',
|
||||||
|
|
||||||
|
callback: (token) => {
|
||||||
|
onToken(token)
|
||||||
|
},
|
||||||
|
|
||||||
|
'expired-callback': () => {
|
||||||
|
onToken('')
|
||||||
|
},
|
||||||
|
|
||||||
|
'error-callback': () => {
|
||||||
|
onToken('')
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const existingScript = document.getElementById(
|
||||||
|
TURNSTILE_SCRIPT_ID
|
||||||
|
)
|
||||||
|
|
||||||
|
if (window.turnstile) {
|
||||||
|
renderWidget()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (existingScript) {
|
||||||
|
existingScript.addEventListener('load', renderWidget, {
|
||||||
|
once: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
cancelled = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const script = document.createElement('script')
|
||||||
|
|
||||||
|
script.id = TURNSTILE_SCRIPT_ID
|
||||||
|
script.src = TURNSTILE_SCRIPT_URL
|
||||||
|
script.async = true
|
||||||
|
script.defer = true
|
||||||
|
|
||||||
|
script.addEventListener('load', renderWidget, {
|
||||||
|
once: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
document.head.appendChild(script)
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
cancelled = true
|
||||||
|
|
||||||
|
if (
|
||||||
|
widgetIdRef.current !== null &&
|
||||||
|
window.turnstile
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
window.turnstile.remove(widgetIdRef.current)
|
||||||
|
} catch {
|
||||||
|
// Widget déjà supprimé
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
widgetIdRef.current = null
|
||||||
|
}
|
||||||
|
}, [onToken])
|
||||||
|
|
||||||
|
if (!CAPTCHA_ENABLED || !TURNSTILE_SITE_KEY) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Turnstile
|
<div
|
||||||
ref={ref}
|
ref={containerRef}
|
||||||
siteKey={TURNSTILE_SITE_KEY}
|
id="turnstile-captcha"
|
||||||
options={{ language: 'fr', size: 'flexible' }}
|
className="w-full min-h-[65px] flex justify-center"
|
||||||
onSuccess={onToken}
|
|
||||||
onExpire={() => onToken('')}
|
|
||||||
onError={() => onToken('')}
|
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,37 +1,36 @@
|
|||||||
import { useEffect } from 'react'
|
import { useEffect } from 'react'
|
||||||
import { useLocation } from 'react-router-dom'
|
import { useLocation } from 'react-router-dom'
|
||||||
|
|
||||||
// Domaine de production, utilisé pour construire des URLs absolues
|
|
||||||
// (canonical, og:url) à partir du chemin de la route courante.
|
|
||||||
const SITE_URL = 'https://www.dsp5-archi-o24a-4-5-g4.fr'
|
const SITE_URL = 'https://www.dsp5-archi-o24a-4-5-g4.fr'
|
||||||
|
|
||||||
// Change la valeur d'un attribut sur le premier élément trouvé par le
|
|
||||||
// sélecteur, et retourne de quoi la restaurer plus tard. N'écrit rien si
|
|
||||||
// l'élément est absent du <head> (les balises de base vivent dans
|
|
||||||
// index.html ; ce hook ne fait que les mettre à jour, jamais les créer).
|
|
||||||
function setAttr(selector, attr, value) {
|
function setAttr(selector, attr, value) {
|
||||||
if (value == null) return null
|
if (value == null) return null
|
||||||
|
|
||||||
const el = document.querySelector(selector)
|
const el = document.querySelector(selector)
|
||||||
if (!el) return null
|
if (!el) return null
|
||||||
|
|
||||||
const previous = el.getAttribute(attr)
|
const previous = el.getAttribute(attr)
|
||||||
el.setAttribute(attr, value)
|
el.setAttribute(attr, value)
|
||||||
return () => el.setAttribute(attr, previous ?? '')
|
|
||||||
|
return () => {
|
||||||
|
if (previous == null) {
|
||||||
|
el.removeAttribute(attr)
|
||||||
|
} else {
|
||||||
|
el.setAttribute(attr, previous)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Permet à une page de définir son propre <title>, sa meta description, son
|
|
||||||
// URL canonique et ses balises Open Graph/Twitter le temps qu'elle est
|
|
||||||
// affichée. La SPA n'a qu'un seul index.html : sans ce hook, toutes les
|
|
||||||
// routes partagent les mêmes balises. Les valeurs précédentes sont
|
|
||||||
// restaurées au démontage, donc quitter la page revient à l'état d'avant
|
|
||||||
// (celui d'index.html, ou celui d'une page parente si elles s'enchaînent).
|
|
||||||
export default function usePageMeta({ title, description, image } = {}) {
|
export default function usePageMeta({ title, description, image } = {}) {
|
||||||
const { pathname } = useLocation()
|
const { pathname } = useLocation()
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const previousTitle = document.title
|
if (title) {
|
||||||
if (title) document.title = title
|
document.title = title
|
||||||
|
}
|
||||||
|
|
||||||
const url = `${SITE_URL}${pathname}`
|
const url = `${SITE_URL}${pathname}`
|
||||||
|
|
||||||
const restores = [
|
const restores = [
|
||||||
setAttr('meta[name="description"]', 'content', description),
|
setAttr('meta[name="description"]', 'content', description),
|
||||||
setAttr('link[rel="canonical"]', 'href', url),
|
setAttr('link[rel="canonical"]', 'href', url),
|
||||||
@@ -45,7 +44,6 @@ export default function usePageMeta({ title, description, image } = {}) {
|
|||||||
].filter(Boolean)
|
].filter(Boolean)
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
document.title = previousTitle
|
|
||||||
restores.forEach((restore) => restore())
|
restores.forEach((restore) => restore())
|
||||||
}
|
}
|
||||||
}, [title, description, image, pathname])
|
}, [title, description, image, pathname])
|
||||||
|
|||||||
@@ -236,8 +236,11 @@ export default function Admin() {
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<form onSubmit={handleSaveGameSettings} className="mt-4 pt-4 border-t border-gray-200 flex flex-wrap items-end gap-3">
|
<form
|
||||||
<div className="flex-1 min-w-[220px]">
|
onSubmit={handleSaveGameSettings}
|
||||||
|
className="mt-4 pt-4 border-t border-gray-200 flex flex-col sm:flex-row sm:items-end gap-3"
|
||||||
|
>
|
||||||
|
<div className="w-full sm:flex-1 sm:min-w-[220px]">
|
||||||
<label htmlFor="game-start" className="block text-xs font-medium text-gray-700 mb-1">
|
<label htmlFor="game-start" className="block text-xs font-medium text-gray-700 mb-1">
|
||||||
{stats.gameWindow.configured ? 'Corriger la date de début' : 'Date de début du jeu-concours'}
|
{stats.gameWindow.configured ? 'Corriger la date de début' : 'Date de début du jeu-concours'}
|
||||||
</label>
|
</label>
|
||||||
@@ -253,7 +256,7 @@ export default function Admin() {
|
|||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
disabled={settingsSaving || !startDateInput}
|
disabled={settingsSaving || !startDateInput}
|
||||||
className="bg-[#006B6B] hover:bg-[#005959] disabled:opacity-50 text-white font-semibold px-4 py-2 rounded-lg transition-colors text-xs sm:text-sm"
|
className="w-full sm:w-auto bg-[#006B6B] hover:bg-[#005959] disabled:opacity-50 text-white font-semibold px-4 py-2 rounded-lg transition-colors text-xs sm:text-sm whitespace-nowrap"
|
||||||
>
|
>
|
||||||
{settingsSaving ? 'Enregistrement…' : stats.gameWindow.configured ? 'Mettre à jour' : 'Lancer le jeu'}
|
{settingsSaving ? 'Enregistrement…' : stats.gameWindow.configured ? 'Mettre à jour' : 'Lancer le jeu'}
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import UserNav from '../components/UserNav'
|
|||||||
import {
|
import {
|
||||||
changePasswordApi,
|
changePasswordApi,
|
||||||
meApi,
|
meApi,
|
||||||
forgotPasswordApi,
|
|
||||||
sendPasswordSetupLinkApi,
|
sendPasswordSetupLinkApi,
|
||||||
} from '../services/auth'
|
} from '../services/auth'
|
||||||
import { useHandleAuthError } from '../hooks/useHandleAuthError'
|
import { useHandleAuthError } from '../hooks/useHandleAuthError'
|
||||||
|
|||||||
@@ -25,7 +25,9 @@ describe('Accueil - dates du jeu-concours', () => {
|
|||||||
expect(await screen.findByText('Du 15 novembre au 14 décembre 2026')).toBeInTheDocument()
|
expect(await screen.findByText('Du 15 novembre au 14 décembre 2026')).toBeInTheDocument()
|
||||||
expect(screen.getByText(/ouverte du 15 novembre au 14 décembre 2026 inclus/)).toBeInTheDocument()
|
expect(screen.getByText(/ouverte du 15 novembre au 14 décembre 2026 inclus/)).toBeInTheDocument()
|
||||||
expect(screen.getByText(/retirer jusqu'au 13 janvier 2027/)).toBeInTheDocument()
|
expect(screen.getByText(/retirer jusqu'au 13 janvier 2027/)).toBeInTheDocument()
|
||||||
expect(document.title).toBe('Jeu-concours 100 % Gagnant du 15 novembre au 14 décembre | Thé Tip Top')
|
await vi.waitFor(() => {
|
||||||
|
expect(document.title).toBe('Jeu-concours 100 % Gagnant du 15 novembre au 14 décembre | Thé Tip Top')
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
it("affiche les dates par défaut (2 → 31 octobre 2026) si l'API ne répond pas", async () => {
|
it("affiche les dates par défaut (2 → 31 octobre 2026) si l'API ne répond pas", async () => {
|
||||||
|
|||||||
161
frontend/src/test/unit/admin.service.test.js
Normal file
161
frontend/src/test/unit/admin.service.test.js
Normal file
@@ -0,0 +1,161 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
import {
|
||||||
|
getStatsApi,
|
||||||
|
getUsersApi,
|
||||||
|
drawWinnerApi,
|
||||||
|
getEmailingContactsApi,
|
||||||
|
getWinnerApi,
|
||||||
|
getEmployeesApi,
|
||||||
|
getEmployeeDeliveriesApi,
|
||||||
|
getDeliveryByTicketCodeApi,
|
||||||
|
createEmployeeApi,
|
||||||
|
} from '../../services/admin'
|
||||||
|
|
||||||
|
describe('admin service', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
localStorage.clear()
|
||||||
|
localStorage.setItem('token', 'test-token')
|
||||||
|
vi.restoreAllMocks()
|
||||||
|
})
|
||||||
|
|
||||||
|
function mockFetch(data, ok = true, status = 200) {
|
||||||
|
vi.stubGlobal(
|
||||||
|
'fetch',
|
||||||
|
vi.fn().mockResolvedValue({
|
||||||
|
ok,
|
||||||
|
status,
|
||||||
|
json: vi.fn().mockResolvedValue(data),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
it('getStatsApi retourne les statistiques', async () => {
|
||||||
|
mockFetch({ users: 10 })
|
||||||
|
|
||||||
|
const result = await getStatsApi()
|
||||||
|
|
||||||
|
expect(result).toEqual({ users: 10 })
|
||||||
|
expect(fetch).toHaveBeenCalledWith(
|
||||||
|
'/api/admin/stats',
|
||||||
|
expect.objectContaining({
|
||||||
|
headers: expect.objectContaining({
|
||||||
|
Authorization: 'Bearer test-token',
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('getUsersApi retourne les utilisateurs', async () => {
|
||||||
|
mockFetch({ users: [{ id: 1 }] })
|
||||||
|
|
||||||
|
await expect(getUsersApi()).resolves.toEqual({
|
||||||
|
users: [{ id: 1 }],
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('drawWinnerApi effectue un POST', async () => {
|
||||||
|
mockFetch({ winner: { id: 1 } })
|
||||||
|
|
||||||
|
const result = await drawWinnerApi()
|
||||||
|
|
||||||
|
expect(result).toEqual({ winner: { id: 1 } })
|
||||||
|
expect(fetch).toHaveBeenCalledWith(
|
||||||
|
'/api/admin/draw',
|
||||||
|
expect.objectContaining({
|
||||||
|
method: 'POST',
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('getEmailingContactsApi retourne les contacts', async () => {
|
||||||
|
mockFetch({ contacts: ['test@example.com'] })
|
||||||
|
|
||||||
|
await expect(getEmailingContactsApi()).resolves.toEqual({
|
||||||
|
contacts: ['test@example.com'],
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('getWinnerApi retourne null si aucun gagnant', async () => {
|
||||||
|
mockFetch({}, false, 404)
|
||||||
|
|
||||||
|
await expect(getWinnerApi()).resolves.toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('getWinnerApi retourne le gagnant', async () => {
|
||||||
|
mockFetch({ winner: { id: 5 } })
|
||||||
|
|
||||||
|
await expect(getWinnerApi()).resolves.toEqual({
|
||||||
|
winner: { id: 5 },
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('getEmployeesApi retourne les employés', async () => {
|
||||||
|
mockFetch({ employees: [{ id: 10 }] })
|
||||||
|
|
||||||
|
await expect(getEmployeesApi()).resolves.toEqual({
|
||||||
|
employees: [{ id: 10 }],
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('getEmployeeDeliveriesApi retourne les remises', async () => {
|
||||||
|
mockFetch({
|
||||||
|
employee: { id: 10 },
|
||||||
|
deliveries: [],
|
||||||
|
})
|
||||||
|
|
||||||
|
await expect(getEmployeeDeliveriesApi(10)).resolves.toEqual({
|
||||||
|
employee: { id: 10 },
|
||||||
|
deliveries: [],
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('getDeliveryByTicketCodeApi encode le code du ticket', async () => {
|
||||||
|
mockFetch({ delivery: { id: 1 } })
|
||||||
|
|
||||||
|
await getDeliveryByTicketCodeApi(' ABC 123 ')
|
||||||
|
|
||||||
|
expect(fetch).toHaveBeenCalledWith(
|
||||||
|
'/api/admin/deliveries/ABC%20123',
|
||||||
|
expect.anything(),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('createEmployeeApi crée un employé', async () => {
|
||||||
|
mockFetch({ employee: { id: 20 } })
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
createEmployeeApi({
|
||||||
|
firstname: 'Jean',
|
||||||
|
lastname: 'Dupont',
|
||||||
|
email: 'jean@example.com',
|
||||||
|
}),
|
||||||
|
).resolves.toEqual({
|
||||||
|
employee: { id: 20 },
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(fetch).toHaveBeenCalledWith(
|
||||||
|
'/api/admin/employees',
|
||||||
|
expect.objectContaining({
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({
|
||||||
|
firstname: 'Jean',
|
||||||
|
lastname: 'Dupont',
|
||||||
|
email: 'jean@example.com',
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('transforme les erreurs API en Error', async () => {
|
||||||
|
mockFetch(
|
||||||
|
{ message: 'Erreur serveur' },
|
||||||
|
false,
|
||||||
|
500,
|
||||||
|
)
|
||||||
|
|
||||||
|
await expect(getStatsApi()).rejects.toMatchObject({
|
||||||
|
message: 'Erreur serveur',
|
||||||
|
status: 500,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -25,6 +25,14 @@ export default defineConfig({
|
|||||||
provider: 'v8',
|
provider: 'v8',
|
||||||
reporter: ['text', 'html', 'lcov'],
|
reporter: ['text', 'html', 'lcov'],
|
||||||
reportsDirectory: './coverage',
|
reportsDirectory: './coverage',
|
||||||
|
exclude: [
|
||||||
|
'**/*.webp',
|
||||||
|
'**/*.png',
|
||||||
|
'**/*.jpg',
|
||||||
|
'**/*.jpeg',
|
||||||
|
'**/*.gif',
|
||||||
|
'**/*.svg',
|
||||||
|
],
|
||||||
},
|
},
|
||||||
|
|
||||||
// Le widget Turnstile ne doit pas bloquer les tests jsdom.
|
// Le widget Turnstile ne doit pas bloquer les tests jsdom.
|
||||||
|
|||||||
Reference in New Issue
Block a user