sokko-g/website/src/features/cards/admin/ExpeditionSettings.jsx
Shinuwa 4d05d812c5 Split the Guild administration into tabs and sell Éclats and openings by quantity in the shop
The Guild administration now has a tab per quest. The expedition settings sit behind a status band (open or close, today's activity) and four themed tabs, with units inside the fields, the default value shown, and one sticky apply bar that lists every change before confirming.

The Pont des Veilleurs leaves the expedition page and becomes the « Éclats d’étoile » shop item, priced from Administration › Boutique. Openings and Éclats are bought by quantity: a number field capped by the stardust the player actually has, and a full-width button that shows the total cost. Stardust and Éclats get their own SVG icons, aligned with the text around them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 15:39:45 +01:00

232 lines
16 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Rôle : règle les Expéditions depuis Administration › Guilde › Expéditions : bandeau d'état (ouverture et suivi du jour),
// puis les réglages rangés en onglets thématiques, avec un seul brouillon et une barre d'application commune.
import { useState } from "react";
import { Tabs } from "../../../components/Tabs.jsx";
import { ConfirmModal } from "../../../components/ToolboxModals.jsx";
import { cancelExpedition, updateExpeditionSettings } from "../cardsApi.js";
import { DATE_FORMATTER } from "./adminFormat.js";
import { inRange, parse } from "./adminSettings.js";
import { EXPEDITION_OPEN_PATH, EXPEDITION_SETTING_GROUPS, EXPEDITION_SETTING_THEMES, expeditionSettingLabel, formatSettingValue } from "./expeditionSettingFields.js";
const DESTINATION_WEIGHT = { min: 0, max: 100 };
const readPath = (source, path) => path.split(".").reduce((value, key) => value?.[key], source);
function writePath(target, path, value) {
const keys = path.split(".");
keys.slice(0, -1).reduce((node, key) => node[key], target)[keys.at(-1)] = value;
}
const same = (left, right) => JSON.stringify(left) === JSON.stringify(right);
const toDraft = (value) => (typeof value === "boolean" ? value : Array.isArray(value) ? value.map(String) : String(value));
const fromDraft = (value) => (typeof value === "boolean" ? value : Array.isArray(value) ? value.map(parse) : parse(value));
const validValue = (field, value) => (field.kind === "bool" ? typeof value === "boolean" : (Array.isArray(value) ? value : [value]).every((item) => inRange(item, field.min, field.max)));
const withUnit = (value, unit) => (unit ? `${value} ${unit}` : String(value));
const formatDefault = (value, unit) => (typeof value === "boolean" ? (value ? "oui" : "non") : Array.isArray(value) ? value.map((item) => withUnit(item, unit)).join(" / ") : withUnit(value, unit));
// Tous les réglages modifiables ici : ceux des groupes rangés dans un onglet (bornes du schéma) et ceux de chaque destination.
// L'ouverture (bandeau d'état) et le prix d'un Éclat (Boutique) se règlent ailleurs.
function editableFields(schema, destinations) {
const fromGroups = EXPEDITION_SETTING_GROUPS.filter((group) => PANEL_THEME.has(group.id)).flatMap((group) => group.fields
.map((field) => ({ ...field, ...schema.find((item) => item.path === field.path), panel: group.id })));
const fromDestinations = destinations.flatMap((destination) => [
{ path: `destinations.${destination.id}.active`, kind: "bool", panel: "destinations" },
{ path: `destinations.${destination.id}.weight`, kind: "int", ...DESTINATION_WEIGHT, panel: "destinations" }
]);
return [...fromGroups, ...fromDestinations];
}
const PANEL_THEME = new Map(EXPEDITION_SETTING_THEMES.flatMap((theme) => theme.panels.map((panel) => [panel, theme.id])));
// Brouillon commun à tous les onglets : seules les valeurs touchées y figurent, le reste se lit dans les réglages enregistrés.
function useSettingsDraft(settings, fields) {
const [draft, setDraft] = useState({});
const value = (path) => (path in draft ? fromDraft(draft[path]) : readPath(settings, path));
const raw = (path) => (path in draft ? draft[path] : toDraft(readPath(settings, path)));
const touched = fields.filter((field) => field.path in draft);
const invalid = touched.filter((field) => !validValue(field, value(field.path)));
const changes = touched.filter((field) => validValue(field, value(field.path)) && !same(value(field.path), readPath(settings, field.path)));
const set = (path, next) => setDraft((current) => ({ ...current, [path]: next }));
const reset = () => setDraft({});
return { value, raw, invalid, changes, set, reset };
}
function DefaultHint({ field, value, defaults, busy, onReset }) {
const fallback = readPath(defaults, field.path);
if (fallback === undefined || same(value, fallback)) return null;
return <button className="nebula-admin-setting-default" type="button" disabled={busy} title="Rétablir la valeur par défaut" onClick={onReset}>
Défaut : {formatDefault(fallback, field.unit)} <span aria-hidden="true">↺</span>
</button>;
}
function NumberInput({ field, value, label, busy, onChange }) {
return <span className="nebula-admin-setting-input" data-unit={field.unit || undefined}>
<input className="nds-input" type="number" inputMode="numeric" min={field.min} max={field.max} step="1" value={value} disabled={busy} aria-label={label} aria-invalid={!inRange(parse(value), field.min, field.max) || undefined} onChange={(event) => onChange(event.target.value)} />
{field.unit && <span aria-hidden="true">{field.unit}</span>}
</span>;
}
// Un réglage : interrupteur, nombre ou suite de nombres, avec son état (modifié, invalide) et la valeur par défaut s'il s'en écarte.
function SettingField({ field, draft, settings, defaults, busy }) {
const value = draft.value(field.path);
const raw = draft.raw(field.path);
const changed = !same(value, readPath(settings, field.path));
const invalid = !validValue(field, value);
const label = field.unit ? `${field.label} (${field.unit})` : field.label;
const state = { "data-changed": changed || undefined, "data-invalid": invalid || undefined };
const hint = <DefaultHint field={field} value={value} defaults={defaults} busy={busy} onReset={() => draft.set(field.path, toDraft(readPath(defaults, field.path)))} />;
const error = invalid && <small role="alert">Entier de {field.min.toLocaleString("fr-FR")} à {field.max.toLocaleString("fr-FR")}</small>;
if (field.kind === "bool") return <div className="nebula-admin-expedition-field" {...state}>
<span className="nebula-admin-setting-label">{field.label}</span>
<button className="nds-button" data-size="sm" data-variant={raw ? "primary" : "secondary"} type="button" aria-pressed={raw} aria-label={field.label} disabled={busy} onClick={() => draft.set(field.path, !raw)}>{raw ? "Oui" : "Non"}</button>
{hint}
</div>;
if (Array.isArray(raw)) return <fieldset className="nebula-admin-expedition-field" {...state}>
<legend>{field.label}</legend>
<div className="nebula-admin-expedition-items">{raw.map((item, index) => <label key={index}><span>{field.items?.[index] ?? index + 1}</span>
<NumberInput field={field} value={item} label={`${label} · ${field.items?.[index] ?? index + 1}`} busy={busy} onChange={(next) => draft.set(field.path, raw.map((current, position) => (position === index ? next : current)))} />
</label>)}</div>
{error}{hint}
</fieldset>;
return <label className="nebula-admin-expedition-field" {...state}><span className="nebula-admin-setting-label">{field.label}</span>
<NumberInput field={field} value={raw} label={label} busy={busy} onChange={(next) => draft.set(field.path, next)} />
{error}{hint}
</label>;
}
function SettingsGroup({ group, fields, ...props }) {
return <section className="nds-panel nebula-admin-shop nebula-admin-expedition-group" aria-labelledby={`nebula-admin-expedition-${group.id}`}>
<div className="nds-section-heading nebula-admin-panel-heading"><h3 id={`nebula-admin-expedition-${group.id}`}>{group.title}</h3></div>
<p className="nebula-form-help">{group.help}</p>
<div className="nebula-admin-expedition-fields">{fields.map((field) => <SettingField key={field.path} field={field} {...props} />)}</div>
</section>;
}
// Destinations : proposées ou non, et poids dans le tirage du jour. Leurs textes vivent dans le fichier du serveur.
function DestinationSettings({ destinations, draft, settings, defaults, busy }) {
return <section className="nds-panel nebula-admin-shop nebula-admin-expedition-group" aria-labelledby="nebula-admin-expedition-destinations">
<div className="nds-section-heading nebula-admin-panel-heading"><h3 id="nebula-admin-expedition-destinations">Destinations</h3></div>
<p className="nebula-form-help">Une destination retirée n’est plus tirée ; le poids règle sa fréquence parmi les destinations proposées. Les destinations cachées ne sont jamais tirées. Le changement vaut pour les prochains tirages : celles déjà proposées aujourd’hui restent jusqu’à minuit.</p>
<ul className="nebula-admin-expedition-destinations">{destinations.map((destination) => {
const activePath = `destinations.${destination.id}.active`;
const weightField = { path: `destinations.${destination.id}.weight`, ...DESTINATION_WEIGHT };
const active = draft.raw(activePath);
const weight = draft.raw(weightField.path);
const changed = !same(draft.value(activePath), readPath(settings, activePath)) || !same(draft.value(weightField.path), readPath(settings, weightField.path));
return <li key={destination.id} className="nds-list-row" data-changed={changed || undefined}>
<strong>{destination.name}{destination.hidden && <span className="nds-badge" data-variant="neutral">Cachée</span>}</strong>
<button className="nds-button" data-size="sm" data-variant={active ? "primary" : "secondary"} type="button" aria-pressed={active} aria-label={`${destination.name} proposée`} disabled={busy} onClick={() => draft.set(activePath, !active)}>{active ? "Proposée" : "Retirée"}</button>
<label><span>Poids</span><NumberInput field={weightField} value={weight} label={`Poids de ${destination.name}`} busy={busy} onChange={(next) => draft.set(weightField.path, next)} /></label>
<DefaultHint field={weightField} value={draft.value(weightField.path)} defaults={defaults} busy={busy} onReset={() => draft.set(weightField.path, toDraft(readPath(defaults, weightField.path)))} />
</li>;
})}</ul>
</section>;
}
// Bandeau d'état : ouverture (appliquée tout de suite, sans toucher au brouillon) et activité du jour, avec l'annulation d'une expédition.
function ExpeditionsStatus({ enabled, today, destinations, busy, onToggle, onCancel }) {
const [confirming, setConfirming] = useState(null);
const name = (id) => destinations.find((destination) => destination.id === id)?.name || id;
return <section className="nds-panel nebula-admin-shop nebula-admin-expedition-status" data-open={enabled} aria-labelledby="nebula-admin-expedition-status-title">
<div className="nebula-admin-expedition-status-head">
<div>
<h3 id="nebula-admin-expedition-status-title">Expéditions <span className="nds-badge" data-variant={enabled ? "success" : "neutral"}>{enabled ? "Ouvertes aux joueurs" : "Fermées aux joueurs"}</span></h3>
<p className="nebula-admin-guild-today">Aujourd’hui : <strong>{today.launches}</strong> départ{today.launches > 1 ? "s" : ""} · <strong>{today.running}</strong> en route · <strong>{today.returnedUnclaimed}</strong> butin{today.returnedUnclaimed > 1 ? "s" : ""} à récupérer.</p>
</div>
<button className="nds-button" data-size="sm" data-variant={enabled ? "secondary" : "primary"} type="button" disabled={busy} onClick={() => setConfirming("toggle")}>{enabled ? "Fermer les Expéditions" : "Ouvrir les Expéditions"}</button>
</div>
{today.runningList.length > 0 && <ul className="nebula-admin-expedition-destinations">{today.runningList.map((expedition) => <li key={expedition.id} className="nds-list-row">
<strong>{name(expedition.destinationId)} · {"★".repeat(expedition.stars)}</strong>
<span>{expedition.creatorName} · retour le {DATE_FORMATTER.format(expedition.returnsAt)}</span>
<button className="nds-button" data-size="sm" data-variant="secondary" type="button" disabled={busy} onClick={() => setConfirming(expedition)}>Annuler</button>
</li>)}</ul>}
{confirming === "toggle" && <ConfirmModal
title={enabled ? "Fermer les Expéditions ?" : "Ouvrir les Expéditions ?"}
message={enabled
? "Plus aucun départ ni inscription à un groupe. Les expéditions en route reviennent normalement et leur butin reste à récupérer."
: "La tuile des Expéditions apparaît dans la Guilde et les joueurs peuvent partir dès maintenant."}
confirmLabel={enabled ? "Fermer" : "Ouvrir"}
onClose={async (confirmed) => {
setConfirming(null);
if (confirmed) await onToggle(!enabled);
}}
/>}
{confirming && confirming !== "toggle" && <ConfirmModal
title="Annuler cette expédition ?"
message={`L’expédition vers ${name(confirming.destinationId)} de ${confirming.creatorName} s’arrête : les cartes sont libérées, sans butin.`}
confirmLabel="Annuler l’expédition"
onClose={async (confirmed) => {
const target = confirming;
setConfirming(null);
if (confirmed) await onCancel(target.id);
}}
/>}
</section>;
}
// Barre commune : nombre de réglages modifiés ou invalides, puis confirmation avec la liste des changements.
function ApplyBar({ draft, settings, destinations, busy, onApply }) {
const [confirming, setConfirming] = useState(false);
const { changes, invalid } = draft;
if (!changes.length && !invalid.length) return null;
const count = (total, word) => `${total} réglage${total > 1 ? "s" : ""} ${word}${total > 1 ? "s" : ""}`;
return <div className="nds-panel nebula-admin-apply-bar" role="region" aria-label="Modifications en attente">
<p role="status">{[changes.length && count(changes.length, "modifié"), invalid.length && count(invalid.length, "invalide")].filter(Boolean).join(" · ")}</p>
<div className="nds-toolbar">
<button className="nds-button" data-size="sm" data-variant="secondary" type="button" disabled={busy} aria-label="Annuler les modifications" onClick={draft.reset}>Annuler</button>
<button className="nds-button" data-size="sm" data-variant="primary" type="button" disabled={busy || !changes.length || invalid.length > 0} onClick={() => setConfirming(true)}>Appliquer</button>
</div>
{confirming && <ConfirmModal
title={`Appliquer ${count(changes.length, "modifié")} ?`}
message="Les nouveaux réglages s’appliquent aux prochains départs. Les expéditions en route gardent ceux de leur départ."
confirmLabel="Appliquer"
onClose={async (confirmed) => {
setConfirming(false);
if (confirmed) await onApply();
}}
>
<ul className="nebula-admin-apply-changes">{changes.map((field) => <li key={field.path}>
<span>{expeditionSettingLabel(field.path, destinations)}</span> : {formatSettingValue(readPath(settings, field.path))} → <strong>{formatSettingValue(draft.value(field.path))}</strong>
</li>)}</ul>
</ConfirmModal>}
</div>;
}
export function ExpeditionSettings({ dashboard, busy, runMutation, refreshDashboard }) {
const { settings, defaults, schema, destinations } = dashboard.expeditionSettings;
const [themeId, setThemeId] = useState(EXPEDITION_SETTING_THEMES[0].id);
const fields = editableFields(schema, destinations);
const draft = useSettingsDraft(settings, fields);
const save = async (apply) => {
const next = structuredClone(settings);
apply(next);
const saved = await runMutation(() => updateExpeditionSettings(next));
if (saved) await refreshDashboard();
return saved;
};
const apply = async () => {
if (await save((next) => draft.changes.forEach((field) => writePath(next, field.path, draft.value(field.path))))) draft.reset();
};
const cancel = async (id) => {
if (await runMutation(() => cancelExpedition(id))) await refreshDashboard();
};
const pendingIn = (theme) => [...draft.changes, ...draft.invalid].filter((field) => PANEL_THEME.get(field.panel) === theme.id).length;
const theme = EXPEDITION_SETTING_THEMES.find((item) => item.id === themeId);
const props = { draft, settings, defaults, busy };
return <div className="nebula-admin-expeditions">
<ExpeditionsStatus enabled={settings[EXPEDITION_OPEN_PATH]} today={dashboard.expeditionsToday} destinations={destinations} busy={busy} onToggle={(open) => save((next) => { next[EXPEDITION_OPEN_PATH] = open; })} onCancel={cancel} />
<Tabs
className="nebula-admin-expedition-themes"
tabs={EXPEDITION_SETTING_THEMES.map((item) => {
const pending = pendingIn(item);
return { id: item.id, label: pending ? `${item.title} (${pending})` : item.title };
})}
activeTab={themeId}
onChange={setThemeId}
/>
{theme.panels.map((panel) => (panel === "destinations"
? <DestinationSettings key={panel} destinations={destinations} {...props} />
: <SettingsGroup key={panel} group={EXPEDITION_SETTING_GROUPS.find((group) => group.id === panel)} fields={fields.filter((field) => field.panel === panel)} {...props} />))}
<ApplyBar draft={draft} settings={settings} destinations={destinations} busy={busy} onApply={apply} />
</div>;
}