// 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 ; } function NumberInput({ field, value, label, busy, onChange }) { return onChange(event.target.value)} /> {field.unit && } ; } // 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 = draft.set(field.path, toDraft(readPath(defaults, field.path)))} />; const error = invalid && Entier de {field.min.toLocaleString("fr-FR")} à {field.max.toLocaleString("fr-FR")}; if (field.kind === "bool") return
{field.label} {hint}
; if (Array.isArray(raw)) return
{field.label}
{raw.map((item, index) => )}
{error}{hint}
; return ; } function SettingsGroup({ group, fields, ...props }) { return

{group.title}

{group.help}

{fields.map((field) => )}
; } // 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

Destinations

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.

; } // 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

Expéditions {enabled ? "Ouvertes aux joueurs" : "Fermées aux joueurs"}

Aujourd’hui : {today.launches} départ{today.launches > 1 ? "s" : ""} · {today.running} en route · {today.returnedUnclaimed} butin{today.returnedUnclaimed > 1 ? "s" : ""} à récupérer.

{today.runningList.length > 0 && } {confirming === "toggle" && { setConfirming(null); if (confirmed) await onToggle(!enabled); }} />} {confirming && confirming !== "toggle" && { const target = confirming; setConfirming(null); if (confirmed) await onCancel(target.id); }} />}
; } // 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

{[changes.length && count(changes.length, "modifié"), invalid.length && count(invalid.length, "invalide")].filter(Boolean).join(" · ")}

{confirming && { setConfirming(false); if (confirmed) await onApply(); }} >
    {changes.map((field) =>
  • {expeditionSettingLabel(field.path, destinations)} : {formatSettingValue(readPath(settings, field.path))} → {formatSettingValue(draft.value(field.path))}
  • )}
}
; } 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
save((next) => { next[EXPEDITION_OPEN_PATH] = open; })} onCancel={cancel} /> { 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" ? : group.id === panel)} fields={fields.filter((field) => field.panel === panel)} {...props} />))}
; }