Put trading and giving up front and suggest the players who need each card
The Échanges et dons page now opens on two illustrated tiles, centred and 360 px wide at most: trade (L'Échange Écarlate) and give (the Dawn card, renamed Le Don de l'Aube with a gift story). Each counts the cards missing on either side and previews a few. In the composer, the most useful players come first in the list and as suggested chips, and missing duplicates lead with a badge; nothing is filtered, so owned duplicates stay tradeable for Awakenings. GET /api/cards/traders adds `wants`: which of the viewer's own duplicates each player lacks, and nothing else of their collection. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
2f3c371d7b
commit
17e5cd5e63
12 changed files with 302 additions and 46 deletions
|
|
@ -524,3 +524,4 @@
|
|||
{"id":"int-a989535f032bdd9bfef68d44c0f1fa5d","kind":"field_change","created_at":"2026-12-01T15:10:39.274660548Z","actor":"Shinuwa","issue_id":"sokko-g-2ni0","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"17 cartes au caractère marqué reçoivent un archétype existant ; 17 restent équilibrées avec un penchant léger tiré de leur texte, le Gecko garde le profil de la collection. Simulation et test d'équilibrage OK, guides à jour."}}
|
||||
{"id":"int-3057bc99910598e9893f56c3ada9c6ad","kind":"field_change","created_at":"2026-12-01T15:22:31.938418272Z","actor":"Shinuwa","issue_id":"sokko-g-ls6r","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"156 mixins et fonctions documentés en SassDoc, 10 mixins inutilisés supprimés (CSS produit identique), garde-fou dans tests/static-styles.test.mjs, convention dans website/AGENTS.md."}}
|
||||
{"id":"int-0fb1dce0186811918733b7c3d55135f5","kind":"field_change","created_at":"2026-12-01T15:34:42.418321329Z","actor":"Shinuwa","issue_id":"sokko-g-u82a","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Cliquet tests/function-docs.test.mjs (496 exceptions), en-tête // Rôle : vérifié sur toutes les feuilles, règles dans AGENTS.md racine, website, styles et tests."}}
|
||||
{"id":"int-356beb0be17346577690e6340f2a7c58","kind":"field_change","created_at":"2026-12-01T16:00:54.193910869Z","actor":"Shinuwa","issue_id":"sokko-g-1txt","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Tuiles illustrées centrées (Échange Écarlate, Don de l'Aube), joueurs suggérés, doublons manquants en tête sans filtre ; /traders expose wants (mes doublons qui leur manquent). L'Échange de l'Aube renommée Le Don de l'Aube."}}
|
||||
|
|
|
|||
|
|
@ -1203,8 +1203,15 @@ recyclables, l'encart sous le menu montre le solde, le nombre de doublons et le
|
|||
et « Voir les doublons » (active le filtre Possession). La confirmation de « Tout recycler » affiche le barème par rareté. Le recyclage carte par carte se fait depuis
|
||||
la fiche d'une carte. « Tout recycler » est suspendu tant qu'une ouverture attend d'être révélée. Échanges et dons s'ouvre sur « À traiter » (Accepter, Refuser), « Envoyées » (temps restant,
|
||||
Annuler) et « Terminées », repliées, avec les vraies cartes et leur rareté ; un `nds-badge` doré
|
||||
compte dans le menu les propositions à traiter. « Faire un don » et « Proposer un échange » ouvrent une
|
||||
même modale : joueur, doublon donné puis, pour un échange, doublon voulu, ceux qui manquent d'abord.
|
||||
compte dans le menu les propositions à traiter. En tête de page, deux grandes tuiles `nds-card`
|
||||
(`nebula-transfer-actions`, 360 px au plus, côte à côte dès 620 px de panneau et centrées, bandeau 2:1) : « Échanger un doublon » (bordure dorée, illustration de
|
||||
L'Échange Écarlate) et « Donner un doublon » (illustration du Don de l'Aube), chacune avec son bandeau fondu vers le texte,
|
||||
une phrase, un chiffre en or (« 4 cartes qui vous manquent chez 3 joueurs », « 12 de vos doublons manquent à 5 joueurs »,
|
||||
en blanc quand il n'y a rien), jusqu'à quatre de ces cartes en vignettes et son bouton (« Proposer un échange »,
|
||||
« Faire un don »). Les deux ouvrent une même modale : joueur, doublon donné puis, pour un échange, doublon voulu. Les
|
||||
joueurs les plus utiles passent d'abord, dans la liste (avec le détail sous le nom) et en `nds-chip` « Joueurs suggérés »
|
||||
(quatre au plus, avec le nombre de cartes) ; les doublons qui manquent passent d'abord avec un badge doré (« Vous ne
|
||||
l'avez pas », « Lui manque »). Rien n'est masqué : un doublon déjà possédé reste échangeable, pour les Éveils.
|
||||
Un don est immédiat ; la fiche d'une carte en double y mène avec « Donner » et « Échanger ». Dans Historique,
|
||||
une ouverture liste ses cartes en simples références textuelles (`nds-badge` :
|
||||
symbole de rareté à sa couleur, avec son nom en infobulle et pour les lecteurs
|
||||
|
|
|
|||
|
|
@ -54,7 +54,9 @@ Collections, ouvertures et transferts :
|
|||
chaque collection et s'ajoute à l'autre. La migration 3 annule les transferts encore
|
||||
en cours de l'ancien système à code ; `code`, `joined` et les colonnes de confirmation
|
||||
ne servent plus qu'à relire l'historique. `GET /api/cards/traders` n'expose des autres
|
||||
joueurs que leur identité publique et leurs doublons disponibles.
|
||||
joueurs que leur identité publique, leurs doublons disponibles et, dans `wants`, ceux des doublons
|
||||
du demandeur qu'ils ne possèdent pas (décision du 2026-12-01, pour suggérer les dons) ; rien d'autre
|
||||
de leur collection.
|
||||
- `cardFormats` : formats d'une variation mythique, qui multiplient les finitions générées
|
||||
(format × effet × palette). `cards[].fullImage` : illustration du format `full-art` ; une
|
||||
variation de ce format est refusée (`FULL_IMAGE_REQUIRED`) pour une carte qui n'en a pas.
|
||||
|
|
|
|||
|
|
@ -1210,7 +1210,10 @@ export class CardsService {
|
|||
return this.getState(playerId);
|
||||
}
|
||||
|
||||
/** Joueurs à qui donner ou proposer un échange : seuls leur identité publique et leurs doublons disponibles sont exposés, jamais leur collection. */
|
||||
/**
|
||||
* Joueurs à qui donner ou proposer un échange : leur identité publique, leurs doublons disponibles et, dans `wants`,
|
||||
* ceux des doublons du demandeur qu'ils ne possèdent pas. Le reste de leur collection n'est jamais exposé.
|
||||
*/
|
||||
listTraders(playerId) {
|
||||
this.expireTransfers();
|
||||
const rows = this.db.prepare("SELECT id, display_name, avatar_url FROM players WHERE id != ? AND deleted_at IS NULL ORDER BY display_name COLLATE NOCASE").all(playerId);
|
||||
|
|
@ -1227,12 +1230,20 @@ export class CardsService {
|
|||
if (!duplicates.has(row.player_id)) duplicates.set(row.player_id, []);
|
||||
duplicates.get(row.player_id).push({ editionId: row.edition_id, spare });
|
||||
}
|
||||
// Seules les cartes que le demandeur peut donner sont comparées : c'est tout ce qu'il apprend des autres collections.
|
||||
const mySpares = (duplicates.get(playerId) || []).map((entry) => entry.editionId);
|
||||
const owners = new Map(mySpares.map((editionId) => [editionId, new Set()]));
|
||||
if (mySpares.length) {
|
||||
for (const row of this.db.prepare(`SELECT player_id, edition_id FROM collection_cards
|
||||
WHERE quantity > 0 AND edition_id IN (SELECT value FROM json_each(?))`).all(JSON.stringify(mySpares))) owners.get(row.edition_id).add(row.player_id);
|
||||
}
|
||||
return {
|
||||
traders: rows.map((row) => ({
|
||||
id: row.id,
|
||||
displayName: row.display_name,
|
||||
avatarUrl: row.avatar_url,
|
||||
duplicates: duplicates.get(row.id) || []
|
||||
duplicates: duplicates.get(row.id) || [],
|
||||
wants: mySpares.filter((editionId) => !owners.get(editionId).has(row.id))
|
||||
}))
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -160,7 +160,21 @@ export function validateSiteContent(site) {
|
|||
"cards.transfers.inboxTitle",
|
||||
"cards.transfers.sentTitle",
|
||||
"cards.transfers.finishedTitle",
|
||||
"cards.transfers.empty",
|
||||
"cards.transfers.tradeTileImage",
|
||||
"cards.transfers.tradeTileTitle",
|
||||
"cards.transfers.tradeTileText",
|
||||
"cards.transfers.tradeTileHint",
|
||||
"cards.transfers.tradeTileNone",
|
||||
"cards.transfers.giftTileImage",
|
||||
"cards.transfers.giftTileTitle",
|
||||
"cards.transfers.giftTileText",
|
||||
"cards.transfers.giftTileHint",
|
||||
"cards.transfers.giftTileNone",
|
||||
"cards.transfers.suggestionsLabel",
|
||||
"cards.transfers.tradeMatchHint",
|
||||
"cards.transfers.giftMatchHint",
|
||||
"cards.transfers.giftLacksChosen",
|
||||
"cards.transfers.theyLackBadge",
|
||||
"cards.transfers.giftFrom",
|
||||
"cards.transfers.giftTo",
|
||||
"cards.transfers.tradeWith",
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ import { calculateRecharge, drawPack, drawShopPack } from "../services/cards/gam
|
|||
import { CardsService, DEV_DISCORD_ID } from "../services/cards/service.js";
|
||||
import { rarityPercentages } from "../website/src/features/cards/dropRates.js";
|
||||
import { visibleCollections } from "../website/src/features/cards/collectionState.js";
|
||||
import { matchTraders, rankMatches, summarizeMatches } from "../website/src/features/cards/transferSuggestions.js";
|
||||
import { availableTips, TIP_SECTION_VARIANTS, tipOfDay } from "../website/src/features/cards/dailyTips.js";
|
||||
import { backupCardsDatabase, restoreCardsDatabase, runScheduledBackup, verifyCardsDatabase } from "../services/cards/backup.js";
|
||||
|
||||
|
|
@ -718,11 +719,11 @@ test("trades and gifts move duplicates only and campaign claims add cards", () =
|
|||
assert.throws(() => service.createTransfer(admin.id, { type: "trade", recipientId: player.id, editionId: drawn, requestedEditionId: drawn }), /différentes/);
|
||||
assert.throws(() => service.createTransfer(admin.id, { type: "gift", recipientId: "inconnu", editionId: drawn }), /introuvable/);
|
||||
|
||||
// Seuls l'identité publique et les doublons disponibles des autres joueurs sont exposés.
|
||||
// Seuls l'identité publique, les doublons disponibles et ceux de mes doublons qui manquent aux autres joueurs sont exposés.
|
||||
const traders = service.listTraders(player.id).traders;
|
||||
assert.deepEqual(traders.map((trader) => trader.id).includes(player.id), false);
|
||||
const adminTrader = traders.find((trader) => trader.id === admin.id);
|
||||
assert.deepEqual(Object.keys(adminTrader).sort(), ["avatarUrl", "displayName", "duplicates", "id"]);
|
||||
assert.deepEqual(Object.keys(adminTrader).sort(), ["avatarUrl", "displayName", "duplicates", "id", "wants"]);
|
||||
assert.deepEqual(adminTrader.duplicates.find((entry) => entry.editionId === drawn), { editionId: drawn, spare: 2 });
|
||||
|
||||
// Don : le doublon arrive immédiatement, le donneur garde ses autres exemplaires et le journal cite la carte.
|
||||
|
|
@ -1579,6 +1580,31 @@ test("traders list the same available duplicates as each collection, without res
|
|||
assert.deepEqual(traders.find((trader) => trader.id === partner.id).duplicates, [{ editionId: "astral-booster-standard", spare: 1 }]);
|
||||
});
|
||||
|
||||
test("traders list which of the viewer's duplicates each player lacks, and nothing else of their collection", () => {
|
||||
const database = new CardsDatabase(":memory:");
|
||||
const service = new CardsService({ database, catalog: baseCatalog, now: () => 1_800_000_000_000, random: () => 0 });
|
||||
const viewer = service.upsertPlayer({ discordId: "viewer", displayName: "Viewer" });
|
||||
const owner = service.upsertPlayer({ discordId: "owner", displayName: "Owner" });
|
||||
const newcomer = service.upsertPlayer({ discordId: "newcomer", displayName: "Newcomer" });
|
||||
for (let copy = 0; copy < 2; copy += 1) {
|
||||
service.addCard(viewer.id, "aurora-wolf-standard");
|
||||
service.addCard(viewer.id, "astral-booster-standard");
|
||||
}
|
||||
service.addCard(owner.id, "aurora-wolf-standard");
|
||||
// Une carte que le demandeur n'a pas en double ne dit rien des autres collections.
|
||||
service.addCard(owner.id, "milky-way-panda-standard");
|
||||
service.addCard(owner.id, "milky-way-panda-standard");
|
||||
|
||||
const { traders } = service.listTraders(viewer.id);
|
||||
assert.deepEqual(traders.find((trader) => trader.id === owner.id).wants, ["astral-booster-standard"]);
|
||||
assert.deepEqual(traders.find((trader) => trader.id === newcomer.id).wants.toSorted(), ["astral-booster-standard", "aurora-wolf-standard"]);
|
||||
// Un doublon réservé par un échange en cours n'est plus à donner.
|
||||
service.createTransfer(viewer.id, { type: "trade", recipientId: owner.id, editionId: "astral-booster-standard", requestedEditionId: "milky-way-panda-standard" });
|
||||
assert.deepEqual(service.listTraders(viewer.id).traders.find((trader) => trader.id === newcomer.id).wants, ["aurora-wolf-standard"]);
|
||||
// Sans doublon, rien n'est comparé.
|
||||
assert.deepEqual(service.listTraders(newcomer.id).traders.map((trader) => trader.wants), [[], []]);
|
||||
});
|
||||
|
||||
test("new campaign codes need eight characters while existing short ones keep working", () => {
|
||||
const database = new CardsDatabase(":memory:");
|
||||
const service = new CardsService({ database, catalog: baseCatalog, now: () => 1_800_000_000_000, random: () => 0 });
|
||||
|
|
@ -1590,3 +1616,20 @@ test("new campaign codes need eight characters while existing short ones keep wo
|
|||
database.db.prepare("UPDATE campaigns SET code = 'OLD1' WHERE id = ?").run(campaign.id);
|
||||
assert.equal(service.claimCampaign(player.id, "old1").reward.items[0].editionId, "aurora-wolf-standard");
|
||||
});
|
||||
|
||||
test("transfer suggestions rank players by what is missing on each side without hiding anyone", () => {
|
||||
const traders = [
|
||||
{ id: "ana", duplicates: [{ editionId: "owned" }], wants: ["mine-a"] },
|
||||
{ id: "bob", duplicates: [{ editionId: "new-1" }, { editionId: "owned" }], wants: [] },
|
||||
{ id: "cid", duplicates: [{ editionId: "new-1" }], wants: ["mine-a", "mine-b", "stale"] }
|
||||
];
|
||||
const matches = matchTraders(traders, new Set(["owned", "mine-a", "mine-b"]), new Set(["mine-a", "mine-b"]));
|
||||
// Un doublon déjà possédé reste dans les doublons du joueur, seuls les manquants comptent ; un `wants` périmé est ignoré.
|
||||
assert.deepEqual(matches.map(({ forMe, forThem }) => [forMe, forThem]), [[[], ["mine-a"]], [["new-1"], []], [["new-1"], ["mine-a", "mine-b"]]]);
|
||||
assert.deepEqual(rankMatches(matches, { type: "trade" }).map((match) => match.trader.id), ["cid", "bob", "ana"]);
|
||||
assert.deepEqual(rankMatches(matches, { type: "gift" }).map((match) => match.trader.id), ["cid", "ana", "bob"]);
|
||||
// Un don préparé depuis la fiche d'une carte met d'abord ceux à qui elle manque.
|
||||
assert.deepEqual(rankMatches(matches, { type: "gift", editionId: "mine-a" }).map((match) => match.trader.id), ["cid", "ana", "bob"]);
|
||||
assert.deepEqual(rankMatches(matches, { type: "gift", editionId: "mine-b" }).map((match) => match.trader.id), ["cid", "ana", "bob"]);
|
||||
assert.deepEqual(summarizeMatches(matches, (a, b) => a.localeCompare(b)), { trade: { cards: ["new-1"], players: 2 }, gift: { cards: ["mine-a", "mine-b"], players: 2 } });
|
||||
});
|
||||
|
|
|
|||
|
|
@ -2541,8 +2541,8 @@
|
|||
{
|
||||
"id": "dawn-card-trade",
|
||||
"collectionId": "astral-genesis",
|
||||
"name": "L'Échange de l'Aube",
|
||||
"description": "Au lever du jour, le Capybara de l'Aube Solaire et le Panda de la Voie Lactée échangent une carte. Leur sourire vaut bien plus que sa rareté.",
|
||||
"name": "Le Don de l'Aube",
|
||||
"description": "Au lever du jour, le Capybara de l'Aube Solaire offre au Panda de la Voie Lactée la carte qui lui manquait. Il en avait un double ; ce sourire-là, il ne l'avait pas encore.",
|
||||
"image": "/static/img/cards/astral-genesis/epic/dawn_card_trade.webp",
|
||||
"expedition": {
|
||||
"tags": [
|
||||
|
|
|
|||
|
|
@ -95,7 +95,21 @@
|
|||
"inboxTitle": "À traiter",
|
||||
"sentTitle": "Envoyées",
|
||||
"finishedTitle": "Terminées",
|
||||
"empty": "Aucune proposition en cours. Donnez un doublon ou proposez un échange à un autre joueur.",
|
||||
"tradeTileImage": "/static/img/cards/astral-genesis/epic/crimson_card_trade.webp",
|
||||
"tradeTileTitle": "Échanger un doublon",
|
||||
"tradeTileText": "Votre doublon contre celui d’un autre joueur, s’il accepte.",
|
||||
"tradeTileHint": "{cards} carte{s} qui vous manque{nt} chez {players} joueur{ps}",
|
||||
"tradeTileNone": "Aucun doublon des autres joueurs ne vous manque pour l’instant, mais tous restent échangeables.",
|
||||
"giftTileImage": "/static/img/cards/astral-genesis/epic/dawn_card_trade.webp",
|
||||
"giftTileTitle": "Donner un doublon",
|
||||
"giftTileText": "Il arrive tout de suite chez l’autre joueur. Vous gardez toujours un exemplaire.",
|
||||
"giftTileHint": "{cards} de vos doublons manque{nt} à {players} joueur{ps}",
|
||||
"giftTileNone": "Tous les joueurs ont déjà vos doublons, mais vous pouvez toujours les donner.",
|
||||
"suggestionsLabel": "Joueurs suggérés",
|
||||
"tradeMatchHint": "Ses doublons qui vous manquent : {forMe} · Vos doublons qui lui manquent : {forThem}",
|
||||
"giftMatchHint": "Vos doublons qui lui manquent : {forThem}",
|
||||
"giftLacksChosen": "N’a pas {card}",
|
||||
"theyLackBadge": "Lui manque",
|
||||
"giftFrom": "Don de",
|
||||
"giftTo": "Don à",
|
||||
"tradeWith": "Échange avec",
|
||||
|
|
|
|||
|
|
@ -1,14 +1,19 @@
|
|||
/**
|
||||
* @file Crée un don immédiat ou une proposition d'échange en choisissant un joueur et les cartes affichées.
|
||||
* @file Crée un don immédiat ou une proposition d'échange en choisissant un joueur et les cartes affichées. Les
|
||||
* joueurs et les doublons qui manquent passent d'abord, sans qu'aucun doublon ne soit masqué.
|
||||
*/
|
||||
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { Modal } from "../../components/Modal.jsx";
|
||||
import { SelectDropdown } from "../../components/SelectDropdown.jsx";
|
||||
import { createTransfer, loadTraders } from "./cardsApi.js";
|
||||
import { createTransfer } from "./cardsApi.js";
|
||||
import { NebulaCard, RarityGlyph } from "./rendering/NebulaCard.jsx";
|
||||
import { fillTemplate } from "./textFormat.js";
|
||||
import { matchTraders, rankMatches } from "./transferSuggestions.js";
|
||||
|
||||
function DuplicatePicker({ catalog, label, entries, selectedId, onSelect, empty, newLabel }) {
|
||||
const SUGGESTED_PLAYERS = 4;
|
||||
|
||||
function DuplicatePicker({ catalog, label, entries, selectedId, onSelect, empty }) {
|
||||
const [search, setSearch] = useState("");
|
||||
const query = search.trim().toLocaleLowerCase("fr");
|
||||
const visible = entries.filter((entry) => !query || entry.card.name.toLocaleLowerCase("fr").includes(query));
|
||||
|
|
@ -25,40 +30,45 @@ function DuplicatePicker({ catalog, label, entries, selectedId, onSelect, empty,
|
|||
<NebulaCard catalog={catalog} entry={entry} size="sm" selected={selected} selectLabel={`${label} : ${entry.card.name}`} onSelect={() => onSelect(entry.editionId)} />
|
||||
<strong>{entry.card.name}</strong>
|
||||
<small><i className="nebula-history-rarity" aria-hidden="true"><RarityGlyph rarity={entry.edition.rarity} /></i>{rarity} · ×{entry.spare}</small>
|
||||
{entry.missing && <span className="nds-badge" data-variant="gold">{newLabel}</span>}
|
||||
{entry.badge && <span className="nds-badge" data-variant="gold">{entry.badge}</span>}
|
||||
</div>;
|
||||
})}</div>
|
||||
: <div className="nds-empty-state"><p>{empty}</p></div>}
|
||||
</section>;
|
||||
}
|
||||
|
||||
export function TransferComposer({ catalog, state, initial, content, runMutation, busy, onClose, onSent }) {
|
||||
/** `traders` : joueurs chargés par TransfersPanel (null pendant le chargement). */
|
||||
export function TransferComposer({ catalog, state, traders, loadError, initial, content, runMutation, busy, onClose, onSent }) {
|
||||
const [type, setType] = useState(initial.type);
|
||||
const [traders, setTraders] = useState(null);
|
||||
const [loadError, setLoadError] = useState("");
|
||||
const [recipientId, setRecipientId] = useState("");
|
||||
const [editionId, setEditionId] = useState(initial.editionId || "");
|
||||
const [requestedId, setRequestedId] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
loadTraders().then((result) => { if (active) setTraders(result.traders); }).catch((error) => { if (active) setLoadError(error.message); });
|
||||
return () => { active = false; };
|
||||
}, []);
|
||||
|
||||
const editions = useMemo(() => new Map(catalog.editions.map((edition) => [edition.id, edition])), [catalog.editions]);
|
||||
const cards = useMemo(() => new Map(catalog.cards.map((card) => [card.id, card])), [catalog.cards]);
|
||||
const ownedIds = new Set(state.collection.map((entry) => entry.editionId));
|
||||
const rarityRank = new Map(catalog.rarities.map((rarity, index) => [rarity.id, index]));
|
||||
const byRarity = (a, b) => (rarityRank.get(b.edition.rarity) ?? 0) - (rarityRank.get(a.edition.rarity) ?? 0) || a.card.name.localeCompare(b.card.name, "fr");
|
||||
const mine = state.collection.filter((entry) => entry.spare > 0 && entry.card).toSorted(byRarity);
|
||||
const recipient = traders?.find((trader) => trader.id === recipientId);
|
||||
// Les cartes qui manquent au joueur passent d'abord : ce sont celles qu'il cherche.
|
||||
const spares = state.collection.filter((entry) => entry.spare > 0 && entry.card);
|
||||
const matches = matchTraders(traders || [], ownedIds, new Set(spares.map((entry) => entry.editionId)));
|
||||
const ranked = rankMatches(matches, { type, editionId });
|
||||
const match = matches.find((item) => item.trader.id === recipientId);
|
||||
const recipient = match?.trader;
|
||||
const chosenName = cards.get(editions.get(editionId)?.cardId)?.name;
|
||||
const matchHint = (item) => (type === "gift" && editionId && item.forThem.includes(editionId)
|
||||
? fillTemplate(content.giftLacksChosen, { card: chosenName })
|
||||
: fillTemplate(type === "gift" ? content.giftMatchHint : content.tradeMatchHint, { forMe: item.forMe.length, forThem: item.forThem.length }));
|
||||
const useful = (item) => (type === "gift" ? item.forThem.length : item.forMe.length) > 0;
|
||||
const suggested = ranked.filter(useful).slice(0, SUGGESTED_PLAYERS);
|
||||
// Tous les doublons restent proposés (un doublon déjà possédé sert aux Éveils) ; ceux qui manquent passent d'abord.
|
||||
const firstMissing = (a, b) => Number(Boolean(b.badge)) - Number(Boolean(a.badge)) || byRarity(a, b);
|
||||
const mine = spares.map((entry) => ({ ...entry, badge: match?.forThem.includes(entry.editionId) ? content.theyLackBadge : "" })).toSorted(firstMissing);
|
||||
const theirs = (recipient?.duplicates || []).flatMap(({ editionId: id, spare }) => {
|
||||
const edition = editions.get(id);
|
||||
const card = edition && cards.get(edition.cardId);
|
||||
return card ? [{ editionId: id, spare, edition, card, missing: !ownedIds.has(id) }] : [];
|
||||
}).toSorted((a, b) => Number(b.missing) - Number(a.missing) || byRarity(a, b));
|
||||
return card ? [{ editionId: id, spare, edition, card, badge: ownedIds.has(id) ? "" : content.missingBadge }] : [];
|
||||
}).toSorted(firstMissing);
|
||||
const chooseRecipient = (value) => { setRecipientId(value); setRequestedId(""); };
|
||||
|
||||
const offered = mine.find((entry) => entry.editionId === editionId);
|
||||
const requested = theirs.find((entry) => entry.editionId === requestedId);
|
||||
|
|
@ -80,10 +90,19 @@ export function TransferComposer({ catalog, state, initial, content, runMutation
|
|||
{loadError && <p className="nds-inline-notice" data-variant="danger" role="alert">{loadError}</p>}
|
||||
{traders?.length === 0
|
||||
? <div className="nds-empty-state"><p>{content.noPlayers}</p></div>
|
||||
: <SelectDropdown label={content.playerLabel} value={recipientId} placeholder={traders ? content.playerPlaceholder : content.playerLoading} disabled={!traders} options={(traders || []).map((trader) => ({ value: trader.id, label: `${trader.displayName} (${trader.duplicates.reduce((total, entry) => total + entry.spare, 0)} ${content.duplicatesShort})` }))} onChange={(value) => { setRecipientId(value); setRequestedId(""); }} />}
|
||||
: <div className="nebula-trade-recipient">
|
||||
<SelectDropdown label={content.playerLabel} value={recipientId} placeholder={traders ? content.playerPlaceholder : content.playerLoading} disabled={!traders} options={ranked.map((item) => ({ value: item.trader.id, label: `${item.trader.displayName} (${item.trader.duplicates.reduce((total, entry) => total + entry.spare, 0)} ${content.duplicatesShort})`, hint: matchHint(item) }))} onChange={chooseRecipient} />
|
||||
{suggested.length > 0 && <div className="nebula-trade-suggestions" role="group" aria-label={content.suggestionsLabel}>
|
||||
<span>{content.suggestionsLabel}</span>
|
||||
{suggested.map((item) => <button key={item.trader.id} className="nds-chip" data-size="sm" type="button" aria-pressed={item.trader.id === recipientId} title={matchHint(item)} onClick={() => chooseRecipient(item.trader.id)}>
|
||||
{item.trader.displayName}
|
||||
<span className="nds-badge" data-variant="gold">{type === "gift" ? item.forThem.length : item.forMe.length}</span>
|
||||
</button>)}
|
||||
</div>}
|
||||
</div>}
|
||||
<div className="nebula-trade-columns" data-type={type}>
|
||||
<DuplicatePicker catalog={catalog} label={content.youGive} entries={mine} selectedId={editionId} onSelect={setEditionId} empty={content.noDuplicates} newLabel={content.missingBadge} />
|
||||
{type === "trade" && <DuplicatePicker catalog={catalog} label={content.youReceive} entries={theirs} selectedId={requestedId} onSelect={setRequestedId} empty={recipient ? content.playerNoDuplicates : content.choosePlayerFirst} newLabel={content.missingBadge} />}
|
||||
<DuplicatePicker catalog={catalog} label={content.youGive} entries={mine} selectedId={editionId} onSelect={setEditionId} empty={content.noDuplicates} />
|
||||
{type === "trade" && <DuplicatePicker catalog={catalog} label={content.youReceive} entries={theirs} selectedId={requestedId} onSelect={setRequestedId} empty={recipient ? content.playerNoDuplicates : content.choosePlayerFirst} />}
|
||||
</div>
|
||||
{sameCard && <p className="nds-inline-notice" data-variant="warning" role="alert">{content.sameCard}</p>}
|
||||
<p className="nebula-form-help">{type === "gift" ? content.giftHelp : content.tradeHelp}</p>
|
||||
|
|
|
|||
|
|
@ -1,13 +1,41 @@
|
|||
/**
|
||||
* @file Présente les propositions d'échange reçues et envoyées, les transferts terminés et l'accès à la
|
||||
* création d'un don ou d'un échange.
|
||||
* @file Présente les deux actions (échanger, donner) avec les cartes qui manquent de part et d'autre, puis les
|
||||
* propositions reçues et envoyées et les transferts terminés.
|
||||
*/
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { acceptTransfer, cancelTransfer, declineTransfer } from "./cardsApi.js";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { acceptTransfer, cancelTransfer, declineTransfer, loadTraders } from "./cardsApi.js";
|
||||
import { NebulaCard } from "./rendering/NebulaCard.jsx";
|
||||
import { TransferComposer } from "./TransferComposer.jsx";
|
||||
import { formatRelative } from "./admin/adminFormat.js";
|
||||
import { fillTemplate } from "./textFormat.js";
|
||||
import { matchTraders, summarizeMatches } from "./transferSuggestions.js";
|
||||
|
||||
const TILE_PREVIEW = 4;
|
||||
|
||||
/**
|
||||
* Grande tuile d'action : l'illustration de la carte qui la représente, ce qu'elle permet, combien de cartes et de
|
||||
* joueurs elle concerne, et quelques-unes de ces cartes.
|
||||
*/
|
||||
function ActionTile({ catalog, kind, image, title, text, hint, found, previews, action, variant, disabled, onClick }) {
|
||||
return <article className="nds-card nebula-transfer-action" data-kind={kind}>
|
||||
<img className="nebula-transfer-action-cover" src={image} alt="" loading="lazy" />
|
||||
<div className="nebula-transfer-action-body">
|
||||
<h3>{title}</h3>
|
||||
<p>{text}</p>
|
||||
{hint && <p className="nebula-transfer-action-hint" data-found={found || undefined}>{hint}</p>}
|
||||
{previews.length > 0 && <div className="nebula-transfer-action-cards" aria-hidden="true">
|
||||
{previews.map((entry) => <NebulaCard key={entry.editionId} catalog={catalog} entry={entry} size="sm" />)}
|
||||
</div>}
|
||||
<button className="nds-button" data-variant={variant} type="button" disabled={disabled} onClick={onClick}>{action}</button>
|
||||
</div>
|
||||
</article>;
|
||||
}
|
||||
|
||||
/** Accorde « {cards} carte{s} … {players} joueur{ps} ». */
|
||||
function countHint(template, { cards, players }) {
|
||||
return fillTemplate(template, { cards: cards.length, s: cards.length > 1 ? "s" : "", nt: cards.length > 1 ? "nt" : "", players, ps: players > 1 ? "s" : "" });
|
||||
}
|
||||
|
||||
function TransferSide({ catalog, label, entry }) {
|
||||
const rarity = catalog.rarities.find((item) => item.id === entry?.edition?.rarity)?.label;
|
||||
|
|
@ -56,6 +84,8 @@ export function TransfersPanel({ catalog, state, runMutation, busy, content, dra
|
|||
const [showFinished, setShowFinished] = useState(false);
|
||||
const [now] = useState(() => Date.now());
|
||||
const [notice, setNotice] = useState("");
|
||||
const [traders, setTraders] = useState(null);
|
||||
const [loadError, setLoadError] = useState("");
|
||||
const toProcess = state.transfers.filter((transfer) => transfer.status === "open" && transfer.direction === "received");
|
||||
const sent = state.transfers.filter((transfer) => transfer.status === "open" && transfer.direction === "sent");
|
||||
const finished = state.transfers.filter((transfer) => transfer.status !== "open");
|
||||
|
|
@ -64,21 +94,58 @@ export function TransfersPanel({ catalog, state, runMutation, busy, content, dra
|
|||
if (draft) onDraftUsed();
|
||||
}, [draft, onDraftUsed]);
|
||||
|
||||
// Rechargés après chaque don ou décision : les doublons des uns et des autres ont pu changer.
|
||||
const refreshTraders = useCallback(() => loadTraders()
|
||||
.then((result) => { setTraders(result.traders); setLoadError(""); })
|
||||
.catch((error) => setLoadError(error.message)), []);
|
||||
useEffect(() => { refreshTraders(); }, [refreshTraders]);
|
||||
|
||||
const lookup = useMemo(() => {
|
||||
const editions = new Map(catalog.editions.map((edition) => [edition.id, edition]));
|
||||
const cards = new Map(catalog.cards.map((card) => [card.id, card]));
|
||||
const rank = new Map(catalog.rarities.map((rarity, index) => [rarity.id, index]));
|
||||
const entryOf = (editionId) => {
|
||||
const edition = editions.get(editionId);
|
||||
const card = edition && cards.get(edition.cardId);
|
||||
return card ? { editionId, edition, card } : null;
|
||||
};
|
||||
const byRarity = (a, b) => (rank.get(editions.get(b)?.rarity) ?? 0) - (rank.get(editions.get(a)?.rarity) ?? 0);
|
||||
return { entryOf, byRarity };
|
||||
}, [catalog]);
|
||||
const spares = useMemo(() => state.collection.filter((entry) => entry.spare > 0 && entry.card), [state.collection]);
|
||||
const summary = useMemo(() => traders && summarizeMatches(
|
||||
matchTraders(traders, new Set(state.collection.map((entry) => entry.editionId)), new Set(spares.map((entry) => entry.editionId))),
|
||||
lookup.byRarity
|
||||
), [traders, state.collection, spares, lookup]);
|
||||
const previews = (ids) => ids.slice(0, TILE_PREVIEW).map(lookup.entryOf).filter(Boolean);
|
||||
const tradeHint = summary && (summary.trade.cards.length ? countHint(content.tradeTileHint, summary.trade) : content.tradeTileNone);
|
||||
const giftHint = !spares.length ? content.noDuplicates
|
||||
: summary && (summary.gift.cards.length ? countHint(content.giftTileHint, summary.gift) : content.giftTileNone);
|
||||
|
||||
async function decide(action, message) {
|
||||
setNotice("");
|
||||
const result = await runMutation(action);
|
||||
if (result) setNotice(message);
|
||||
if (result) {
|
||||
setNotice(message);
|
||||
refreshTraders();
|
||||
}
|
||||
}
|
||||
|
||||
return <div className="nebula-transfers">
|
||||
<div className="nds-section-heading nebula-section-heading">
|
||||
<div><p className="eyebrow">{content.eyebrow}</p><h2>{content.title}</h2></div>
|
||||
<div className="nds-toolbar">
|
||||
<button className="nds-button" data-variant="secondary" type="button" disabled={busy} onClick={() => setComposer({ type: "gift" })}>{content.newGift}</button>
|
||||
<button className="nds-button" data-variant="primary" type="button" disabled={busy} onClick={() => setComposer({ type: "trade" })}>{content.newTrade}</button>
|
||||
</div>
|
||||
</div>
|
||||
{notice && <p className="nds-inline-notice" data-variant="success" role="status">{notice}</p>}
|
||||
{loadError && <p className="nds-inline-notice" data-variant="danger" role="alert">{loadError}</p>}
|
||||
|
||||
<div className="nebula-transfer-actions">
|
||||
<ActionTile catalog={catalog} kind="trade" image={content.tradeTileImage} title={content.tradeTileTitle} text={content.tradeTileText} hint={tradeHint} found={Boolean(summary?.trade.cards.length)}
|
||||
previews={previews(summary?.trade.cards || [])}
|
||||
action={content.newTrade} variant="primary" disabled={busy} onClick={() => setComposer({ type: "trade" })} />
|
||||
<ActionTile catalog={catalog} kind="gift" image={content.giftTileImage} title={content.giftTileTitle} text={content.giftTileText} hint={giftHint} found={Boolean(spares.length && summary?.gift.cards.length)}
|
||||
previews={previews(summary?.gift.cards || [])}
|
||||
action={content.newGift} variant="secondary" disabled={busy} onClick={() => setComposer({ type: "gift" })} />
|
||||
</div>
|
||||
|
||||
{toProcess.length > 0 && <section aria-labelledby="nebula-transfers-inbox">
|
||||
<div className="nds-section-heading nebula-section-heading"><h3 id="nebula-transfers-inbox">{content.inboxTitle} <span className="nds-badge" data-variant="gold">{toProcess.length}</span></h3></div>
|
||||
|
|
@ -95,13 +162,11 @@ export function TransfersPanel({ catalog, state, runMutation, busy, content, dra
|
|||
</TransferCard>)}</div>
|
||||
</section>}
|
||||
|
||||
{!toProcess.length && !sent.length && <div className="nds-empty-state"><p>{content.empty}</p></div>}
|
||||
|
||||
{finished.length > 0 && <section aria-label={content.finishedTitle}>
|
||||
<button className="nds-button" data-size="sm" data-variant="secondary" type="button" aria-expanded={showFinished} onClick={() => setShowFinished(!showFinished)}>{content.finishedTitle} ({finished.length})</button>
|
||||
{showFinished && <div className="nebula-transfers-list nebula-transfers-finished">{finished.map((transfer) => <TransferCard key={transfer.id} catalog={catalog} transfer={transfer} content={content} now={now} />)}</div>}
|
||||
</section>}
|
||||
|
||||
{composer && <TransferComposer key={`${composer.type}-${composer.editionId || ""}`} catalog={catalog} state={state} initial={composer} content={content} runMutation={runMutation} busy={busy} onClose={() => setComposer(null)} onSent={(message) => { setNotice(message); setComposer(null); }} />}
|
||||
{composer && <TransferComposer key={`${composer.type}-${composer.editionId || ""}`} catalog={catalog} state={state} traders={traders} loadError={loadError} initial={composer} content={content} runMutation={runMutation} busy={busy} onClose={() => setComposer(null)} onSent={(message) => { setNotice(message); setComposer(null); refreshTraders(); }} />}
|
||||
</div>;
|
||||
}
|
||||
|
|
|
|||
58
website/src/features/cards/transferSuggestions.js
Normal file
58
website/src/features/cards/transferSuggestions.js
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
/**
|
||||
* @file Règles pures des suggestions d'Échanges et dons : quels joueurs ont un doublon qui me manque, à qui manquent
|
||||
* mes doublons, et dans quel ordre les proposer.
|
||||
*
|
||||
* Utilisé par : TransfersPanel.jsx (tuiles d'accueil) et TransferComposer.jsx (ordre des joueurs et des doublons).
|
||||
* Attention : ne filtre jamais. Un doublon déjà possédé reste échangeable (Éveils) ; les suggestions ne font que
|
||||
* remonter les cartes qui manquent. `wants` vient de GET /api/cards/traders : seuls mes doublons y sont comparés.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Ce que chaque joueur peut m'apporter et ce que je peux lui apporter.
|
||||
* @param {Array<{ id: string, duplicates: Array<{ editionId: string }>, wants?: string[] }>} traders Joueurs de l'API.
|
||||
* @param {Set<string>} ownedIds Variations de ma collection.
|
||||
* @param {Set<string>} spareIds Mes doublons disponibles, pour ignorer un `wants` périmé.
|
||||
* @returns {Array<{ trader: object, forMe: string[], forThem: string[] }>} Dans l'ordre reçu.
|
||||
*/
|
||||
export function matchTraders(traders, ownedIds, spareIds) {
|
||||
return traders.map((trader) => ({
|
||||
trader,
|
||||
forMe: trader.duplicates.map((entry) => entry.editionId).filter((id) => !ownedIds.has(id)),
|
||||
forThem: (trader.wants || []).filter((id) => spareIds.has(id))
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Trie les joueurs du plus intéressant au moins intéressant, sans en retirer. Échange : d'abord ceux qui ont des
|
||||
* doublons qui me manquent, puis ceux à qui les miens manquent (échange utile aux deux). Don : d'abord ceux à qui
|
||||
* manque la carte choisie, puis le plus de mes doublons. À égalité, l'ordre reçu (alphabétique) est conservé.
|
||||
* @param {ReturnType<typeof matchTraders>} matches Résultat de `matchTraders`.
|
||||
* @param {{ type: "trade" | "gift", editionId?: string }} options Type de proposition et doublon déjà choisi.
|
||||
* @returns {ReturnType<typeof matchTraders>} Une nouvelle liste triée.
|
||||
*/
|
||||
export function rankMatches(matches, { type, editionId = "" }) {
|
||||
const lacksChosen = (match) => Number(Boolean(editionId) && match.forThem.includes(editionId));
|
||||
const keys = type === "gift"
|
||||
? (match) => [lacksChosen(match), match.forThem.length]
|
||||
: (match) => [match.forMe.length, lacksChosen(match), match.forThem.length];
|
||||
return matches.toSorted((a, b) => {
|
||||
const left = keys(a);
|
||||
const right = keys(b);
|
||||
return left.reduce((order, value, index) => order || right[index] - value, 0);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Chiffres des tuiles d'accueil : cartes distinctes à trouver ou à offrir et joueurs concernés, plus quelques
|
||||
* variations à montrer (les plus rares d'abord).
|
||||
* @param {ReturnType<typeof matchTraders>} matches Résultat de `matchTraders`.
|
||||
* @param {(a: string, b: string) => number} byRarity Ordre des variations, les plus rares d'abord.
|
||||
* @returns {{ trade: { cards: string[], players: number }, gift: { cards: string[], players: number } }}
|
||||
*/
|
||||
export function summarizeMatches(matches, byRarity) {
|
||||
const side = (key) => ({
|
||||
cards: [...new Set(matches.flatMap((match) => match[key]))].toSorted(byRarity),
|
||||
players: matches.filter((match) => match[key].length).length
|
||||
});
|
||||
return { trade: side("forMe"), gift: side("forThem") };
|
||||
}
|
||||
|
|
@ -1034,9 +1034,27 @@ main:has(.nebula-dashboard) { overflow-x: clip; }
|
|||
.nebula-admin-layout h2 { margin-top: 0; }
|
||||
.nebula-form { display: grid; gap: var(--space-3); }
|
||||
.nebula-form-help { margin: 0; color: var(--color-text-muted); font-size: var(--font-size-xs); }
|
||||
.nebula-transfers { display: grid; gap: var(--space-5); min-width: 0; }
|
||||
.nebula-transfers { container: transfers / inline-size; display: grid; gap: var(--space-5); min-width: 0; }
|
||||
.nebula-transfers-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 360px), 1fr)); gap: var(--space-4); }
|
||||
.nebula-transfers-finished { margin-top: var(--space-3); }
|
||||
// Accueil des échanges : deux tuiles (échanger en or, donner) de 360 px au plus, côte à côte dès 620 px de panneau et
|
||||
// centrées, l'illustration de L'Échange Écarlate ou du Don de l'Aube en bandeau 2:1, fondue vers le texte. La largeur
|
||||
// est plafonnée pour que le bandeau garde les visages des personnages.
|
||||
.nebula-transfer-actions { display: grid; grid-template-columns: minmax(0, 360px); justify-content: center; gap: var(--space-4); }
|
||||
.nds-card.nebula-transfer-action { display: grid; grid-template-rows: auto 1fr; overflow: hidden; padding: 0; }
|
||||
.nds-card.nebula-transfer-action[data-kind="trade"] { border-color: rgba(246, 196, 83, 0.45); }
|
||||
.nebula-transfer-action-cover { width: 100%; aspect-ratio: 2 / 1; object-fit: cover; object-position: center 30%; mask-image: linear-gradient(to bottom, #000 60%, transparent); }
|
||||
.nebula-transfer-action-body { display: grid; grid-template-rows: auto auto 1fr auto; justify-items: start; gap: var(--space-2); padding: 0 var(--space-5) var(--space-5); }
|
||||
.nebula-transfer-action-body h3 { margin: 0; font-size: var(--font-size-lg); }
|
||||
.nebula-transfer-action-body p { margin: 0; color: var(--color-text-muted); font-size: var(--font-size-sm); }
|
||||
.nebula-transfer-action-body .nebula-transfer-action-hint { color: var(--color-text); font-weight: 600; }
|
||||
.nebula-transfer-action-body .nebula-transfer-action-hint[data-found] { color: var(--color-accent-gold); }
|
||||
.nebula-transfer-action-cards { display: flex; gap: var(--space-1); }
|
||||
.nebula-transfer-action-cards > .nebula-card { width: 44px; }
|
||||
.nebula-transfer-action-body > .nds-button { margin-top: var(--space-2); }
|
||||
@container transfers (min-width: 620px) {
|
||||
.nebula-transfer-actions { grid-template-columns: repeat(2, minmax(0, 360px)); }
|
||||
}
|
||||
.nds-card.nebula-transfer-card { display: grid; gap: var(--space-3); padding: var(--space-4); }
|
||||
.nebula-transfer-card header, .nebula-transfer-card footer { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: var(--space-2); }
|
||||
.nebula-transfer-card footer { justify-content: flex-end; }
|
||||
|
|
@ -1049,6 +1067,10 @@ main:has(.nebula-dashboard) { overflow-x: clip; }
|
|||
.nebula-trade-composer.nds-modal { box-sizing: border-box; display: grid; gap: var(--space-3); width: min(1040px, calc(100vw - 32px)); max-height: calc(100vh - 32px); overflow: auto; }
|
||||
.nebula-trade-composer h2 { margin: 0; }
|
||||
.nds-section-heading.nebula-section-heading:has(.nds-radio-button-group) { flex-wrap: wrap; margin-bottom: 0; }
|
||||
.nebula-trade-recipient { display: grid; gap: var(--space-2); }
|
||||
.nebula-trade-suggestions { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-2); }
|
||||
.nebula-trade-suggestions > span { color: var(--color-text-muted); font-size: var(--font-size-xs); }
|
||||
.nebula-trade-suggestions .nds-chip { grid-auto-flow: column; }
|
||||
.nebula-trade-columns { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--space-4); }
|
||||
.nebula-trade-columns[data-type="trade"] { grid-template-columns: repeat(auto-fit, minmax(min(100%, 340px), 1fr)); }
|
||||
.nebula-trade-picker { display: grid; align-content: start; gap: var(--space-2); min-width: 0; }
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue