Add the Sokko TCG collectible card mini-game
Add the server-backed card game: Discord login, recharging pack openings, album, trades, gifts, stardust shop, campaign codes and its administration, stored in SQLite and disabled in production until configured. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
243465720f
commit
5ce35cd7ba
193 changed files with 12159 additions and 28 deletions
398
website/src/features/cards/admin/AdminDistributions.jsx
Normal file
398
website/src/features/cards/admin/AdminDistributions.jsx
Normal file
|
|
@ -0,0 +1,398 @@
|
|||
// Rôle : crée des campagnes (un code à annoncer, des cartes et paquets offerts) et suit leurs utilisations.
|
||||
import { Tooltip } from "../../../components/Tooltip.jsx";
|
||||
import { SelectDropdown } from "../../../components/SelectDropdown.jsx";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { ConfirmModal } from "../../../components/ToolboxModals.jsx";
|
||||
import { createCampaign, extendCampaign, loadCampaignDetail, revokeCampaign } from "../cardsApi.js";
|
||||
import { formatPercent, rarityPercentages, recommendedWeights } from "../dropRates.js";
|
||||
import { NebulaCard } from "../NebulaCard.jsx";
|
||||
import { describeReward, summarizeReward } from "../rewardText.js";
|
||||
import { DATE_FORMATTER, toDateTimeLocal } from "./adminFormat.js";
|
||||
import { ExpiryField } from "./ExpiryField.jsx";
|
||||
import { DateValue } from "./DateValue.jsx";
|
||||
|
||||
const DEFAULT_DURATION_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
const plural = (count, singular, pluralForm = `${singular}s`) => `${count.toLocaleString("fr-FR")} ${count > 1 ? pluralForm : singular}`;
|
||||
|
||||
const isExpired = (campaign, now) => campaign.expiresAt != null && campaign.expiresAt <= now;
|
||||
|
||||
function campaignStatus(campaign, now) {
|
||||
if (campaign.revokedAt) return ["Révoquée", "neutral"];
|
||||
if (isExpired(campaign, now)) return ["Expirée", "neutral"];
|
||||
if (campaign.maxClaims != null && campaign.claimedCount >= campaign.maxClaims) return ["Épuisée", "gold"];
|
||||
return ["Active", "success"];
|
||||
}
|
||||
|
||||
function editionGroups(catalog, lookup, collectionId) {
|
||||
return catalog.rarities.map((rarity) => ({
|
||||
rarity,
|
||||
editions: catalog.editions.filter((edition) => edition.rarity === rarity.id && lookup.cards.get(edition.cardId)?.collectionId === collectionId)
|
||||
})).filter((group) => group.editions.length);
|
||||
}
|
||||
|
||||
const describeEdition = (lookup, edition) => `${lookup.cards.get(edition.cardId)?.name} — ${lookup.rarityLabel(edition.rarity)}${edition.finishIds[0] !== "standard" ? ` · ${lookup.finishLabel(edition)}` : ""}`;
|
||||
|
||||
// Grille visuelle des cartes d'une collection en format sm, filtrable par rareté et par nom.
|
||||
// Sert au choix d'une carte unique (garantie) comme à la sélection multiple des cartes offertes.
|
||||
function CardPicker({ catalog, lookup, collectionId, isSelected, onPick, label, status, statusEmpty, verb }) {
|
||||
const [rarity, setRarity] = useState("all");
|
||||
const [search, setSearch] = useState("");
|
||||
const groups = editionGroups(catalog, lookup, collectionId);
|
||||
const query = search.trim().toLocaleLowerCase("fr");
|
||||
const visible = groups.filter((group) => rarity === "all" || group.rarity.id === rarity)
|
||||
.flatMap((group) => group.editions)
|
||||
.filter((edition) => !query || lookup.cards.get(edition.cardId)?.name.toLocaleLowerCase("fr").includes(query));
|
||||
|
||||
return <div className="nebula-admin-card-picker" role="group" aria-label={label}>
|
||||
<div className="nebula-admin-card-picker-head">
|
||||
<span className="nebula-admin-option-label">{label}</span>
|
||||
<span className={`nebula-admin-card-picker-choice${statusEmpty ? " is-empty" : ""}`} role="status">{status}</span>
|
||||
</div>
|
||||
<div className="nds-filter-panel nebula-admin-card-picker-filters" data-variant="horizontal-compact">
|
||||
<label className="nds-filter-search"><span className="sr-only">{`Rechercher — ${label}`}</span><input className="nds-input" data-size="sm" type="search" placeholder="Rechercher..." value={search} onChange={(event) => setSearch(event.target.value)} /></label>
|
||||
<ChoiceGroup label={`Rareté — ${label}`} value={rarity} options={[["all", "Toutes"], ...groups.map((group) => [group.rarity.id, group.rarity.label])]} onChange={setRarity} />
|
||||
</div>
|
||||
{visible.length ? <div className="nebula-admin-card-picker-grid">{visible.map((edition) => <div key={edition.id} className="nebula-admin-card-picker-item" data-selected={isSelected(edition.id) || undefined}>
|
||||
<NebulaCard catalog={catalog} entry={{ edition, card: lookup.cards.get(edition.cardId) }} size="sm" onSelect={() => onPick(edition.id)} selected={isSelected(edition.id)} selectLabel={`${verb} ${describeEdition(lookup, edition)}`} />
|
||||
{isSelected(edition.id) && <span className="nebula-admin-card-picker-check" aria-hidden="true"><span className="ui-icon ui-icon-check" /></span>}
|
||||
</div>)}</div> : <div className="nds-empty-state"><p>Aucune carte ne correspond.</p></div>}
|
||||
</div>;
|
||||
}
|
||||
|
||||
function ChoiceGroup({ label, value, options, onChange }) {
|
||||
return <div className="nds-radio-button-group nebula-admin-choice" role="radiogroup" aria-label={label}>
|
||||
{options.map(([id, text]) => <button key={id} type="button" role="radio" aria-checked={value === id} className={value === id ? "active" : ""} onClick={() => onChange(id)}>{text}</button>)}
|
||||
</div>;
|
||||
}
|
||||
|
||||
const MAX_PACKS = 10;
|
||||
let nextPackKey = 0;
|
||||
|
||||
function newPack(catalog) {
|
||||
return {
|
||||
key: `pack-${nextPackKey++}`, quantity: 1, collectionId: catalog.collections[0]?.id || "",
|
||||
customRates: false, weights: Object.fromEntries(Object.entries(recommendedWeights(catalog.rarities)).map(([id, weight]) => [id, String(weight)])),
|
||||
guaranteeType: "none", guaranteeCount: 1, guaranteeRarity: "legendary", guaranteeEditionId: ""
|
||||
};
|
||||
}
|
||||
|
||||
// Ce qu'il manque à un paquet pour être offert ; vide quand il est prêt.
|
||||
function packIssues(pack, index, lookup) {
|
||||
const label = `paquet ${index + 1}`;
|
||||
const issues = [];
|
||||
if (pack.customRates) {
|
||||
const values = Object.values(pack.weights);
|
||||
if (!values.every((value) => /^\d+$/.test(value)) || !values.some((value) => Number(value) > 0)) issues.push(`des taux personnalisés valides (${label})`);
|
||||
} else if (!lookup.collections.get(pack.collectionId)?.dropWeights) {
|
||||
issues.push(`des taux personnalisés (${label} : la collection n’a pas de taux)`);
|
||||
}
|
||||
if (pack.guaranteeType === "edition" && !pack.guaranteeEditionId) issues.push(`la carte garantie (${label})`);
|
||||
return issues;
|
||||
}
|
||||
|
||||
function buildPack(pack) {
|
||||
return {
|
||||
type: "pack",
|
||||
collectionId: pack.collectionId,
|
||||
rarityWeights: pack.customRates ? Object.fromEntries(Object.entries(pack.weights).map(([id, value]) => [id, /^\d+$/.test(value) ? Number(value) : NaN])) : null,
|
||||
guarantee: pack.guaranteeType === "rarity" ? { type: "rarity", rarity: pack.guaranteeRarity, count: pack.guaranteeCount }
|
||||
: pack.guaranteeType === "edition" ? { type: "edition", editionId: pack.guaranteeEditionId } : null,
|
||||
quantity: pack.quantity
|
||||
};
|
||||
}
|
||||
|
||||
const clampQuantity = (value) => Math.min(10, Math.max(1, Number(value) || 1));
|
||||
|
||||
// Cartes offertes : un clic coche ou décoche une carte ; chaque carte cochée est offerte en un exemplaire.
|
||||
function CardsSection({ catalog, lookup, cards, setCards, onRemove }) {
|
||||
const [collectionId, setCollectionId] = useState(catalog.collections[0]?.id || "");
|
||||
const selectedIds = new Set(cards.map((card) => card.editionId));
|
||||
const toggle = (editionId) => setCards(selectedIds.has(editionId) ? cards.filter((card) => card.editionId !== editionId) : [...cards, { editionId }]);
|
||||
|
||||
return <section className="nds-card nebula-admin-reward-block" aria-labelledby="nebula-admin-reward-cards-title">
|
||||
<header className="nebula-admin-reward-item-head">
|
||||
<h4 id="nebula-admin-reward-cards-title">Cartes offertes</h4>
|
||||
<Tooltip as="button" className="nds-icon-button" content="Retirer les cartes" data-size="sm" data-variant="danger" type="button" aria-label="Retirer les cartes offertes" onClick={onRemove}><span className="ui-icon ui-icon-trash" aria-hidden="true" /></Tooltip>
|
||||
</header>
|
||||
<p className="nebula-form-help">Cliquez sur les cartes pour les cocher ; vous pouvez changer de collection, les cartes cochées restent sélectionnées. Elles arrivent directement dans la collection du joueur.</p>
|
||||
<SelectDropdown className="nebula-admin-reward-collection" label="Collection affichée" value={collectionId} options={catalog.collections.map((entry) => ({ value: entry.id, label: entry.name }))} onChange={setCollectionId} />
|
||||
<CardPicker key={collectionId} catalog={catalog} lookup={lookup} collectionId={collectionId} isSelected={(id) => selectedIds.has(id)} onPick={toggle} verb="Sélectionner" label="Cartes à offrir"
|
||||
status={cards.length ? plural(cards.length, "carte cochée", "cartes cochées") : "Aucune carte cochée."} statusEmpty={!cards.length} />
|
||||
{cards.length > 0 && <ul className="nebula-admin-selected-cards" aria-label="Cartes cochées">{cards.map((card) => {
|
||||
const edition = lookup.editions.get(card.editionId);
|
||||
return <li key={card.editionId} className="nds-list-row">
|
||||
<span>{describeEdition(lookup, edition)}<small>{lookup.collections.get(lookup.cards.get(edition.cardId)?.collectionId)?.name}</small></span>
|
||||
<Tooltip as="button" className="nds-icon-button" content="Décocher" data-size="sm" data-variant="danger" type="button" aria-label={`Décocher ${describeEdition(lookup, edition)}`} onClick={() => toggle(card.editionId)}><span className="ui-icon ui-icon-trash" aria-hidden="true" /></Tooltip>
|
||||
</li>;
|
||||
})}</ul>}
|
||||
</section>;
|
||||
}
|
||||
|
||||
function PackEditor({ catalog, lookup, pack, index, onChange, onRemove }) {
|
||||
const update = (patch) => onChange({ ...pack, ...patch });
|
||||
const collection = lookup.collections.get(pack.collectionId);
|
||||
const guaranteed = lookup.editions.get(pack.guaranteeEditionId);
|
||||
const weights = Object.fromEntries(catalog.rarities.map((rarity) => [rarity.id, /^\d+$/.test(pack.weights[rarity.id]) ? Number(pack.weights[rarity.id]) : 0]));
|
||||
const label = `Paquet ${index + 1}`;
|
||||
|
||||
return <article className="nds-card nebula-admin-reward-item" role="group" aria-label={label}>
|
||||
<header className="nebula-admin-reward-item-head">
|
||||
<strong>{label}</strong>
|
||||
<div className="nebula-admin-reward-quantity"><span aria-hidden="true">Quantité</span><span className="nds-quantity-stepper" data-size="sm">
|
||||
<button type="button" aria-label="Retirer un paquet" disabled={pack.quantity <= 1} onClick={() => update({ quantity: clampQuantity(pack.quantity - 1) })}><span aria-hidden="true">-</span></button>
|
||||
<span className="nds-quantity-stepper-value"><input className="nds-quantity-stepper-input" type="number" min="1" max="10" aria-label="Quantité" value={pack.quantity} onChange={(event) => update({ quantity: clampQuantity(event.target.value) })} /></span>
|
||||
<button type="button" aria-label="Ajouter un paquet" disabled={pack.quantity >= 10} onClick={() => update({ quantity: clampQuantity(pack.quantity + 1) })}><span aria-hidden="true">+</span></button>
|
||||
</span></div>
|
||||
<Tooltip as="button" className="nds-icon-button" content="Retirer" data-size="sm" data-variant="danger" type="button" aria-label={`Retirer ${label}`} onClick={onRemove}><span className="ui-icon ui-icon-trash" aria-hidden="true" /></Tooltip>
|
||||
</header>
|
||||
<div className="nebula-form">
|
||||
<SelectDropdown className="nebula-admin-reward-collection" label="Collection" value={pack.collectionId} options={catalog.collections.filter((entry) => entry.packCategory !== "shop").map((entry) => ({ value: entry.id, label: `${entry.name}${entry.active ? "" : " (fermée)"}` }))} onChange={(collectionId) => update({ collectionId, guaranteeEditionId: "" })} />
|
||||
<div className="nebula-admin-option">
|
||||
<span className="nebula-admin-option-label">Taux de tirage</span>
|
||||
<ChoiceGroup label={`Taux de tirage — ${label}`} value={pack.customRates ? "custom" : "pack"} options={[["pack", "Ceux du paquet"], ["custom", "Personnalisés"]]} onChange={(value) => update({ customRates: value === "custom" })} />
|
||||
{!pack.customRates && <small className="nebula-admin-option-help">{collection?.dropWeights ? rarityPercentages(catalog.rarities, collection.dropWeights).map(({ rarity, percent }) => `${rarity.label} ${formatPercent(percent)}`).join(" · ") : "Ce paquet n’a pas de taux : choisissez des taux personnalisés."}</small>}
|
||||
{pack.customRates && <div className="nebula-admin-custom-rates">
|
||||
{rarityPercentages(catalog.rarities, weights).map(({ rarity, percent }) => <label key={rarity.id} data-rarity={rarity.id}><span>{rarity.label}</span><input className="nds-input" data-size="sm" type="number" min="0" step="1" aria-label={`Poids ${rarity.label}`} value={pack.weights[rarity.id]} onChange={(event) => update({ weights: { ...pack.weights, [rarity.id]: event.target.value } })} /><small>{formatPercent(percent)}</small></label>)}
|
||||
<button className="nds-button" data-size="sm" data-variant="secondary" type="button" onClick={() => update({ weights: Object.fromEntries(Object.entries(recommendedWeights(catalog.rarities)).map(([id, weight]) => [id, String(weight)])) })}>Taux recommandés</button>
|
||||
</div>}
|
||||
</div>
|
||||
<div className="nebula-admin-option">
|
||||
<span className="nebula-admin-option-label">Garantie</span>
|
||||
<ChoiceGroup label={`Garantie — ${label}`} value={pack.guaranteeType} options={[["none", "Aucune"], ["rarity", "Une rareté minimum"], ["edition", "Une carte précise"]]} onChange={(guaranteeType) => update({ guaranteeType })} />
|
||||
{pack.guaranteeType === "none" && <small className="nebula-admin-option-help">Un tirage normal de trois cartes.</small>}
|
||||
{pack.guaranteeType === "rarity" && <div className="nebula-admin-inline-fields">
|
||||
<span>Au moins</span>
|
||||
<SelectDropdown className="nebula-admin-inline-select" label="Nombre de cartes garanties" hideLabel size="sm" value={pack.guaranteeCount} options={[1, 2, 3].map((count) => ({ value: count, label: String(count) }))} onChange={(guaranteeCount) => update({ guaranteeCount })} />
|
||||
<span>carte(s)</span>
|
||||
<SelectDropdown className="nebula-admin-inline-select" label="Rareté garantie" hideLabel size="sm" value={pack.guaranteeRarity} options={catalog.rarities.slice(1).map((rarity) => ({ value: rarity.id, label: rarity.label }))} onChange={(guaranteeRarity) => update({ guaranteeRarity })} />
|
||||
<span>ou mieux</span>
|
||||
</div>}
|
||||
{pack.guaranteeType === "edition" && <CardPicker key={pack.collectionId} catalog={catalog} lookup={lookup} collectionId={pack.collectionId} isSelected={(id) => id === pack.guaranteeEditionId} onPick={(guaranteeEditionId) => update({ guaranteeEditionId })} verb="Choisir" label="Carte garantie dans le paquet"
|
||||
status={guaranteed ? describeEdition(lookup, guaranteed) : "Cliquez sur une carte pour la choisir."} statusEmpty={!guaranteed} />}
|
||||
</div>
|
||||
</div>
|
||||
</article>;
|
||||
}
|
||||
|
||||
function RewardFields({ catalog, lookup, draft, update }) {
|
||||
const setPacks = (packs) => update({ packs });
|
||||
const empty = !draft.cardsOpen && !draft.packs.length;
|
||||
return <fieldset className="nebula-admin-campaign-step">
|
||||
<legend><span className="nebula-admin-step-number">2</span>Ce que reçoit le joueur</legend>
|
||||
<p className="nebula-form-help">Offrez des cartes, des paquets, ou les deux. Les cartes arrivent directement dans la collection ; les paquets sont mis de côté dans « Paquets offerts » et s’ouvrent quand le joueur veut, sans utiliser ses ouvertures, même si la collection est fermée.</p>
|
||||
{empty && <p className="nds-empty-state nebula-admin-reward-empty">Rien pour l’instant : ajoutez des cartes ou un paquet.</p>}
|
||||
{draft.cardsOpen && <CardsSection catalog={catalog} lookup={lookup} cards={draft.cards} setCards={(cards) => update({ cards })}
|
||||
onRemove={() => update({ cardsOpen: false, cards: [] })} />}
|
||||
{draft.packs.length > 0 && <div className="nebula-admin-reward-items">{draft.packs.map((pack, index) => <PackEditor key={pack.key} catalog={catalog} lookup={lookup} pack={pack} index={index}
|
||||
onChange={(next) => setPacks(draft.packs.map((entry) => entry.key === pack.key ? next : entry))}
|
||||
onRemove={() => setPacks(draft.packs.filter((entry) => entry.key !== pack.key))} />)}</div>}
|
||||
<div className="nds-toolbar nebula-admin-actions">
|
||||
{!draft.cardsOpen && <button className="nds-button" data-size="sm" data-variant="secondary" type="button" onClick={() => update({ cardsOpen: true })}>+ Ajouter des cartes</button>}
|
||||
<button className="nds-button" data-size="sm" data-variant="secondary" type="button" disabled={draft.packs.length >= MAX_PACKS} onClick={() => setPacks([...draft.packs, newPack(catalog)])}>+ Ajouter un paquet</button>
|
||||
</div>
|
||||
</fieldset>;
|
||||
}
|
||||
|
||||
// Code aléatoire lisible « XXXX-XXXX », sans caractères ambigus (0/O, 1/I/L), différent des codes existants.
|
||||
const CODE_ALPHABET = "23456789ABCDEFGHJKMNPQRSTUVWXYZ";
|
||||
function randomCode(taken) {
|
||||
for (;;) {
|
||||
const values = crypto.getRandomValues(new Uint32Array(8));
|
||||
const chars = Array.from(values, (value) => CODE_ALPHABET[value % CODE_ALPHABET.length]);
|
||||
const code = `${chars.slice(0, 4).join("")}-${chars.slice(4).join("")}`;
|
||||
if (!taken.has(code)) return code;
|
||||
}
|
||||
}
|
||||
|
||||
function initialDraft() {
|
||||
return {
|
||||
name: "", cardsOpen: false, cards: [], packs: [], code: "", maxClaims: "10", unlimited: true,
|
||||
noExpiry: true, expiresAt: toDateTimeLocal(Date.now() + DEFAULT_DURATION_MS)
|
||||
};
|
||||
}
|
||||
|
||||
function CampaignForm({ catalog, lookup, campaigns, mutateCampaigns, busy, now, onCreated, onCancel }) {
|
||||
const [draft, setDraft] = useState(initialDraft);
|
||||
const update = (patch) => setDraft((current) => ({ ...current, ...patch }));
|
||||
const reward = { items: [
|
||||
...draft.cards.map((card) => ({ type: "card", editionId: card.editionId, quantity: 1 })),
|
||||
...draft.packs.map(buildPack)
|
||||
] };
|
||||
const packProblems = draft.packs.flatMap((pack, index) => packIssues(pack, index, lookup));
|
||||
const rewardReady = reward.items.length > 0 && !packProblems.length;
|
||||
const unlimited = draft.unlimited;
|
||||
const limit = unlimited ? null : Number(draft.maxClaims);
|
||||
const expiry = draft.noExpiry ? null : new Date(draft.expiresAt).getTime();
|
||||
const code = draft.code.trim().toUpperCase();
|
||||
const limitReady = unlimited || (Number.isInteger(limit) && limit >= 1 && limit <= 100_000);
|
||||
const codeReady = /^[A-Z0-9][A-Z0-9-]{3,23}$/.test(code);
|
||||
const expiryReady = expiry === null || expiry > now;
|
||||
// Tout ce qui empêche la création, affiché sous le bouton pour ne jamais laisser un bouton désactivé sans explication.
|
||||
const missing = [
|
||||
!draft.name.trim() && "le nom de la campagne",
|
||||
!reward.items.length && "au moins une carte ou un paquet",
|
||||
...packProblems,
|
||||
!codeReady && "un code de 4 à 24 caractères (lettres, chiffres, tirets)",
|
||||
!limitReady && "un nombre d’utilisations entre 1 et 100 000, ou « Sans limite »",
|
||||
!expiryReady && "une date d’expiration dans le futur, ou « Sans date d’expiration »"
|
||||
].filter(Boolean);
|
||||
const ready = !missing.length;
|
||||
const shownLimit = Number.isInteger(limit) ? limit : 0;
|
||||
|
||||
return <form className="nds-panel nebula-admin-campaign-form" aria-labelledby="nebula-admin-create-title" onSubmit={async (event) => {
|
||||
event.preventDefault();
|
||||
const result = await mutateCampaigns(() => createCampaign({ name: draft.name, reward, code, maxClaims: limit, expiresAt: expiry }));
|
||||
if (result?.campaign) {
|
||||
onCreated(result.campaign);
|
||||
setDraft(initialDraft());
|
||||
}
|
||||
}}>
|
||||
<div className="nds-section-heading nebula-admin-panel-heading">
|
||||
<h3 id="nebula-admin-create-title">Nouvelle campagne</h3>
|
||||
<button className="nds-button" data-size="sm" data-variant="secondary" type="button" onClick={onCancel}>Annuler</button>
|
||||
</div>
|
||||
<fieldset className="nebula-admin-campaign-step">
|
||||
<legend><span className="nebula-admin-step-number">1</span>La campagne</legend>
|
||||
<div className="nebula-admin-campaign-identity">
|
||||
<label><span>Nom de la campagne, visible par les joueurs</span><input className="nds-input" value={draft.name} maxLength="80" placeholder="Ex. Live de lancement" onChange={(event) => update({ name: event.target.value })} required /></label>
|
||||
<div className="nebula-admin-code-field">
|
||||
<label><span>Code à annoncer (4 à 24 caractères)</span><input className="nds-input nebula-admin-code-input" value={draft.code} maxLength="24" placeholder="Ex. NEBULA-2026" onChange={(event) => update({ code: event.target.value.toUpperCase().replace(/\s+/g, "-").replace(/[^A-Z0-9-]/g, "") })} required /></label>
|
||||
<Tooltip as="button" className="nds-button" content="Générer un code aléatoire" data-variant="secondary" type="button" onClick={() => update({ code: randomCode(new Set(campaigns.map((campaign) => campaign.code))) })}>Générer</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
<div className="nebula-admin-campaign-limits">
|
||||
<div className="nebula-admin-campaign-limit">
|
||||
<label className="nebula-admin-check"><input className="nds-checkbox" type="checkbox" checked={draft.unlimited} onChange={(event) => update({ unlimited: event.target.checked })} /><span>Sans limite d’utilisations</span></label>
|
||||
{!unlimited && <input className="nds-input" data-size="sm" type="number" min="1" max="100000" aria-label="Utilisations maximum" value={draft.maxClaims} onChange={(event) => update({ maxClaims: event.target.value })} required />}
|
||||
</div>
|
||||
<div className="nebula-admin-campaign-limit">
|
||||
<label className="nebula-admin-check"><input className="nds-checkbox" type="checkbox" checked={draft.noExpiry} onChange={(event) => update({ noExpiry: event.target.checked })} /><span>Sans date d’expiration</span></label>
|
||||
{!draft.noExpiry && <ExpiryField label="Valable jusqu’au" value={draft.expiresAt} now={now} onChange={(expiresAt) => update({ expiresAt })} />}
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
<RewardFields catalog={catalog} lookup={lookup} draft={draft} update={update} />
|
||||
<fieldset className="nebula-admin-campaign-step">
|
||||
<legend><span className="nebula-admin-step-number">3</span>Récapitulatif</legend>
|
||||
<p className="nebula-admin-campaign-summary" role="status">{rewardReady
|
||||
? <>Chaque joueur qui utilise un code reçoit : <strong>{describeReward(reward, catalog)}</strong>. {`Le code ${code || "…"}, utilisable ${unlimited ? "sans limite" : plural(shownLimit, "fois", "fois")}`}, {expiry === null ? "sans date d’expiration" : <>jusqu’au {Number.isFinite(expiry) ? DATE_FORMATTER.format(expiry) : "…"}</>}. Un joueur ne peut profiter qu’une fois d’une campagne.</>
|
||||
: reward.items.length ? "Complétez les paquets pour voir le récapitulatif." : "Ajoutez des cartes ou un paquet pour voir le récapitulatif."}</p>
|
||||
{!ready && <p className="nds-inline-notice nebula-admin-campaign-missing" data-variant="warning" role="status">Pour créer la campagne, il manque : {missing.join(" ; ")}.</p>}
|
||||
<button className="nds-button" data-variant="primary" type="submit" disabled={busy || !ready}>Créer la campagne</button>
|
||||
</fieldset>
|
||||
</form>;
|
||||
}
|
||||
|
||||
function CopyCodeButton({ code }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
return <button className="nds-button" data-size="sm" data-variant="secondary" type="button" onClick={async () => { await navigator.clipboard?.writeText(code); setCopied(true); }}>{copied ? "Copié" : "Copier le code"}</button>;
|
||||
}
|
||||
|
||||
// Confirmation compacte après création : le code à annoncer, prêt à copier.
|
||||
function CreatedCampaign({ campaign, onClose }) {
|
||||
const panelRef = useRef(null);
|
||||
// Amène la confirmation à l'écran une seule fois, à la création de la campagne.
|
||||
useEffect(() => { panelRef.current?.scrollIntoView({ block: "nearest" }); }, []);
|
||||
return <section ref={panelRef} className="nds-panel nebula-admin-generated" aria-labelledby="nebula-admin-generated-title">
|
||||
<span className="nebula-admin-generated-icon" aria-hidden="true"><span className="ui-icon ui-icon-check" /></span>
|
||||
<div className="nebula-admin-generated-copy">
|
||||
<h3 id="nebula-admin-generated-title">Campagne « {campaign.name} » créée</h3>
|
||||
<p>Code à annoncer : <strong className="nebula-admin-generated-code">{campaign.code}</strong></p>
|
||||
</div>
|
||||
<CopyCodeButton code={campaign.code} />
|
||||
<button className="nds-button" data-size="sm" data-variant="secondary" type="button" onClick={onClose}>Fermer</button>
|
||||
</section>;
|
||||
}
|
||||
|
||||
function CampaignDetail({ catalog, campaign, busy, mutateCampaigns, now }) {
|
||||
const [detail, setDetail] = useState(null);
|
||||
const [error, setError] = useState("");
|
||||
const [expiresAt, setExpiresAt] = useState(() => toDateTimeLocal(Math.max(campaign.expiresAt ?? 0, Date.now() + DEFAULT_DURATION_MS)));
|
||||
const [noExpiry, setNoExpiry] = useState(campaign.expiresAt == null);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
loadCampaignDetail(campaign.id)
|
||||
.then((result) => { if (active) setDetail(result); })
|
||||
.catch((loadError) => { if (active) setError(loadError.message); });
|
||||
return () => { active = false; };
|
||||
}, [campaign.id]);
|
||||
|
||||
if (error) return <p className="nds-inline-notice" data-variant="danger" role="alert">{error}</p>;
|
||||
if (!detail) return <p className="nebula-admin-empty" aria-busy="true">Chargement des utilisations…</p>;
|
||||
|
||||
return <div className="nebula-admin-campaign-detail">
|
||||
{campaign.reward.items.length > 3 && <p className="nebula-admin-campaign-reward"><strong>Récompense :</strong> {describeReward(campaign.reward, catalog)}</p>}
|
||||
{!campaign.revokedAt && <div className="nebula-admin-extend">
|
||||
{!noExpiry && <ExpiryField label="Nouvelle date d’expiration" value={expiresAt} now={now} onChange={setExpiresAt} />}
|
||||
<label className="nebula-admin-check"><input className="nds-checkbox" type="checkbox" checked={noExpiry} onChange={(event) => setNoExpiry(event.target.checked)} /><span>Sans expiration</span></label>
|
||||
<button className="nds-button" data-size="sm" data-variant="secondary" type="button" disabled={busy || (!noExpiry && !(new Date(expiresAt).getTime() > now))} onClick={() => mutateCampaigns(() => extendCampaign(campaign.id, noExpiry ? null : new Date(expiresAt).getTime()))}>Changer l’expiration</button>
|
||||
</div>}
|
||||
{detail.claims.length
|
||||
? <table className="nebula-admin-claims-table">
|
||||
<caption className="sr-only">Joueurs ayant utilisé le code {campaign.code}</caption>
|
||||
<thead><tr><th scope="col">Joueur</th><th scope="col">Utilisé le</th></tr></thead>
|
||||
<tbody>{detail.claims.map((claim) => <tr key={`${claim.playerName}-${claim.claimedAt}`}><td>{claim.playerName}</td><td><DateValue value={claim.claimedAt} /></td></tr>)}</tbody>
|
||||
</table>
|
||||
: <div className="nds-empty-state"><p>Personne n’a encore utilisé ce code.</p></div>}
|
||||
</div>;
|
||||
}
|
||||
|
||||
export function AdminDistributions({ catalog, lookup, dashboard, mutateCampaigns, busy, now }) {
|
||||
const campaigns = dashboard?.campaigns || [];
|
||||
const [creating, setCreating] = useState(false);
|
||||
const [created, setCreated] = useState(null);
|
||||
const [openId, setOpenId] = useState(null);
|
||||
const [pendingRevoke, setPendingRevoke] = useState(null);
|
||||
|
||||
// La liste d'abord ; le formulaire s'ouvre à la demande et se referme après la création.
|
||||
return <>
|
||||
<div className="nds-section-heading nebula-admin-section-heading nebula-admin-distributions-heading">
|
||||
<h3 id="nebula-campaign-list-title">Campagnes <span className="nds-badge" data-variant="neutral">{campaigns.length}</span></h3>
|
||||
{!creating && <button className="nds-button" data-size="sm" data-variant="primary" type="button" onClick={() => { setCreating(true); setCreated(null); }}>+ Nouvelle campagne</button>}
|
||||
</div>
|
||||
{created && <CreatedCampaign key={created.id} campaign={created} onClose={() => setCreated(null)} />}
|
||||
{creating && <CampaignForm catalog={catalog} lookup={lookup} campaigns={campaigns} mutateCampaigns={mutateCampaigns} busy={busy} now={now} onCancel={() => setCreating(false)} onCreated={(campaign) => { setCreating(false); setCreated(campaign); }} />}
|
||||
<section aria-labelledby="nebula-campaign-list-title">
|
||||
{campaigns.length ? <div className="nebula-campaign-list">{campaigns.map((campaign) => {
|
||||
const [statusLabel, statusVariant] = campaignStatus(campaign, now);
|
||||
const isOpen = openId === campaign.id;
|
||||
return <article key={campaign.id} className="nds-card nebula-campaign-card" data-open={isOpen || undefined} aria-label={campaign.name}>
|
||||
<div className="nebula-campaign-head">
|
||||
<div className="nebula-campaign-copy">
|
||||
<strong>{campaign.name}</strong>
|
||||
<span>{summarizeReward(campaign.reward, catalog)}</span>
|
||||
<small>Code <code>{campaign.code}</code> · créée le <DateValue value={campaign.createdAt} dateOnly />{campaign.expiresAt == null ? " · sans expiration" : <> · expire le <DateValue value={campaign.expiresAt} /></>}</small>
|
||||
</div>
|
||||
<div className="nebula-campaign-progress">
|
||||
{campaign.maxClaims == null
|
||||
? <span>{plural(campaign.claimedCount, "utilisation")} · sans limite</span>
|
||||
: <>
|
||||
<span>{campaign.claimedCount.toLocaleString("fr-FR")} / {campaign.maxClaims.toLocaleString("fr-FR")} utilisés</span>
|
||||
<div className="nds-progress" role="progressbar" aria-label={`Utilisations de ${campaign.name}`} aria-valuemin="0" aria-valuemax={campaign.maxClaims} aria-valuenow={campaign.claimedCount}><span style={{ width: `${Math.min(100, campaign.claimedCount / campaign.maxClaims * 100)}%` }} /></div>
|
||||
</>}
|
||||
</div>
|
||||
<span className="nds-badge" data-variant={statusVariant}>{statusLabel}</span>
|
||||
<div className="nds-toolbar nebula-campaign-actions">
|
||||
<button className="nds-button" data-size="sm" data-variant="secondary" type="button" aria-expanded={isOpen} onClick={() => setOpenId(isOpen ? null : campaign.id)}>{isOpen ? "Masquer" : "Détails"}</button>
|
||||
{!campaign.revokedAt && !isExpired(campaign, now) && <CopyCodeButton code={campaign.code} />}
|
||||
{!campaign.revokedAt && !isExpired(campaign, now) && <button className="nds-button" data-size="sm" data-variant="danger" type="button" disabled={busy} onClick={() => setPendingRevoke(campaign)}>Révoquer</button>}
|
||||
</div>
|
||||
</div>
|
||||
{isOpen && <CampaignDetail key={`${campaign.id}-${campaign.claimedCount}-${campaign.expiresAt}-${campaign.revokedAt}`} catalog={catalog} campaign={campaign} busy={busy} mutateCampaigns={mutateCampaigns} now={now} />}
|
||||
</article>;
|
||||
})}</div> : dashboard ? <div className="nds-empty-state"><p>Aucune campagne pour l’instant.</p></div> : <p className="nebula-admin-empty" aria-busy="true">Chargement des campagnes…</p>}
|
||||
</section>
|
||||
{pendingRevoke && <ConfirmModal
|
||||
title={`Révoquer « ${pendingRevoke.name} » ?`}
|
||||
message="Le code deviendra invalide. Les cartes et paquets déjà reçus restent aux joueurs. Cette action est définitive."
|
||||
confirmLabel="Révoquer la campagne"
|
||||
danger
|
||||
onClose={async (confirmed) => {
|
||||
const campaign = pendingRevoke;
|
||||
setPendingRevoke(null);
|
||||
if (confirmed) await mutateCampaigns(() => revokeCampaign(campaign.id));
|
||||
}}
|
||||
/>}
|
||||
</>;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue