Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : UQO Éval — Le Grand Défi Immobilier8 * File : apps/web/src/admin/Prizes.tsx9 * Module : admin10 * Repository : https://git.spboucher.ai/uqo-eval-jeux11 * Project Website : https://jeux.uqo-eval.app12 * Created : 2026-11-2513 * Last Modified : 2026-11-2514 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243/** Prix d'une compétition : seul élément de la configuration modifiable après publication. */44import { useId, useState } from "react";45import { formatMoney } from "@jeux/engine/format";46import { adminApi, errorMessage, type Competition, type CompetitionConfig, type Prizes } from "./lib";47import { Modal, useNotify } from "./ui";4849export const PRIZE_RULE =50 "Les prix vont aux meilleurs rangs parmi les étudiants des deux cours confondus (IMM1003 et IMM1033). Les participants hors cours n'y sont pas admissibles. Les ex æquo sont départagés par tirage au sort.";5152const DEFAULT_LABEL = "Carte-cadeau Amazon";53const DEFAULT_AMOUNTS = ["100", "50", "25"];54const MAX_RANKS = 10;5556export interface PrizeState {57 enabled: boolean;58 label: string;59 amounts: string[];60}6162export function prizeStateOf(prizes: Prizes | undefined): PrizeState {63 return prizes64 ? { enabled: true, label: prizes.label, amounts: prizes.amounts.map(String) }65 : { enabled: false, label: DEFAULT_LABEL, amounts: [...DEFAULT_AMOUNTS] };66}6768/** Valide la saisie ; `prizes` est absent quand la compétition n'offre pas de prix. */69export function parsePrizes(state: PrizeState): { prizes?: Prizes; problems: string[] } {70 if (!state.enabled) return { problems: [] };71 const problems: string[] = [];72 const label = state.label.trim();73 if (label.length < 2 || label.length > 60) problems.push("Le libellé du prix doit compter de 2 à 60 caractères.");74 const amounts = state.amounts.map((a) => Number(a.replace(/\s/g, "").replace(",", ".")));75 if (amounts.length < 1 || amounts.length > MAX_RANKS) problems.push(`Il faut de 1 à ${MAX_RANKS} rangs primés.`);76 if (amounts.some((a) => !Number.isInteger(a) || a < 1 || a > 10_000)) problems.push("Chaque montant doit être un nombre entier de 1 $ à 10 000 $.");77 return problems.length ? { problems } : { prizes: { amounts, label }, problems };78}7980function ordinalFr(rank: number): string {81 return rank === 1 ? "1er rang" : `${rank}e rang`;82}8384export function PrizeFields({ value, onChange }: { value: PrizeState; onChange: (next: PrizeState) => void }) {85 const uid = useId();86 const setAmount = (index: number, text: string): void => onChange({ ...value, amounts: value.amounts.map((a, i) => (i === index ? text : a)) });87 return (88 <div className="stack">89 <label className="adm-check adm-switch">90 <input type="checkbox" role="switch" checked={value.enabled} onChange={(e) => onChange({ ...value, enabled: e.target.checked })} />91 <span>Cette compétition offre des prix</span>92 </label>93 {value.enabled && (94 <>95 <div className="field adm-prize-label">96 <label htmlFor={`${uid}-libelle`}>Libellé du prix</label>97 <input id={`${uid}-libelle`} className="input" value={value.label} onChange={(e) => onChange({ ...value, label: e.target.value })} maxLength={60} autoComplete="off" />98 </div>99 <div>100 <p className="label" id={`${uid}-rangs`}>Montant par rang ($)</p>101 <ol role="list" className="adm-prize-rows" aria-labelledby={`${uid}-rangs`}>102 {value.amounts.map((amount, i) => (103 <li key={i}>104 <label htmlFor={`${uid}-rang-${i}`}>{ordinalFr(i + 1)}</label>105 <input id={`${uid}-rang-${i}`} className="input" type="number" inputMode="numeric" min={1} max={10000} step={1} value={amount} onChange={(e) => setAmount(i, e.target.value)} />106 <button type="button" className="adm-textbtn" onClick={() => onChange({ ...value, amounts: value.amounts.filter((_, j) => j !== i) })} disabled={value.amounts.length <= 1}>107 Retirer<span className="sr-only"> le {ordinalFr(i + 1)}</span>108 </button>109 </li>110 ))}111 </ol>112 <button type="button" className="btn btn-ghost" onClick={() => onChange({ ...value, amounts: [...value.amounts, ""] })} disabled={value.amounts.length >= MAX_RANKS}>113 Ajouter un rang114 </button>115 </div>116 <p className="small muted">{PRIZE_RULE}</p>117 </>118 )}119 </div>120 );121}122123export function PrizeSummary({ prizes }: { prizes: Prizes | undefined }) {124 if (!prizes) return <p className="adm-quiet">Cette compétition n'offre pas de prix.</p>;125 const total = prizes.amounts.reduce((acc, a) => acc + a, 0);126 return (127 <>128 <ol role="list" className="adm-prizes" aria-label="Prix par rang">129 {prizes.amounts.map((amount, i) => (130 <li key={i}>131 <span className="adm-prize-rank">{ordinalFr(i + 1)}</span>132 <span className="num adm-prize-amount">{formatMoney(amount)}</span>133 <span className="small muted">{prizes.label}</span>134 </li>135 ))}136 </ol>137 <p className="small muted">{prizes.amounts.length} rang{prizes.amounts.length > 1 ? "s" : ""} primé{prizes.amounts.length > 1 ? "s" : ""} · total {formatMoney(total)}</p>138 </>139 );140}141142/** Modifie les prix seuls : la configuration actuelle est renvoyée inchangée, sauf `prizes`. */143export function PrizesDialog({ competition, onClose, onSaved }: { competition: Competition; onClose: () => void; onSaved: () => void }) {144 const notify = useNotify();145 const formId = useId();146 const [state, setState] = useState<PrizeState>(() => prizeStateOf(competition.config.prizes));147 const [busy, setBusy] = useState(false);148 const [errors, setErrors] = useState<string[]>([]);149150 const submit = async (): Promise<void> => {151 if (busy) return;152 const { prizes, problems } = parsePrizes(state);153 setErrors(problems);154 if (problems.length) return;155 const { prizes: _old, distractorNonce: _nonce, ...core } = competition.config;156 const config: CompetitionConfig = prizes ? { ...core, prizes } : core;157 setBusy(true);158 try {159 await adminApi(`/competitions/${competition.id}`, { method: "PATCH", body: { config } });160 notify(prizes ? "Prix enregistrés." : "Prix retirés de la compétition.");161 onSaved();162 onClose();163 } catch (e) {164 setErrors([errorMessage(e)]);165 setBusy(false);166 }167 };168169 return (170 <Modal171 title="Modifier les prix"172 size="md"173 onClose={onClose}174 locked={busy}175 footer={176 <>177 <button type="button" className="btn btn-ghost" onClick={onClose} disabled={busy}>Annuler</button>178 <button type="submit" form={formId} className="btn btn-dark" disabled={busy}>{busy ? "Enregistrement…" : "Enregistrer les prix"}</button>179 </>180 }181 >182 <form183 id={formId}184 className="stack"185 noValidate186 onSubmit={(e) => {187 e.preventDefault();188 void submit();189 }}190 >191 {competition.status !== "draft" && <p className="small muted">Les prix sont le seul réglage modifiable après la publication : la banque de questions n'est pas touchée.</p>}192 <PrizeFields value={state} onChange={setState} />193 <div role="alert">194 {errors.length > 0 && <p className="error-text"><strong>À corriger.</strong> {errors.join(" ")}</p>}195 </div>196 </form>197 </Modal>198 );199}200