From fd47514d81ae5eaac280e58f9ae45f3e84da7c61 Mon Sep 17 00:00:00 2001 From: Shinuwa Date: Sat, 21 Nov 2026 16:50:51 +0100 Subject: [PATCH] Freeze pack rates in a campaign when it is created A gifted pack using the pack's own rates was drawn with whatever rates were in force when the player opened it. Campaigns now copy those rates at creation (packRates), every pack of the code draws with them, and the reveal shows them. Older campaigns keep following the live rates. Co-Authored-By: Claude Opus 5.5 --- .beads/interactions.jsonl | 1 + docs/STORAGE_SCHEMA.md | 9 ++++-- services/cards/rewards.js | 7 +++-- services/cards/service.js | 5 +-- tests/nebula-cards.test.mjs | 40 ++++++++++++++++++++++++ website/src/features/cards/PackPanel.jsx | 2 +- 6 files changed, 57 insertions(+), 7 deletions(-) diff --git a/.beads/interactions.jsonl b/.beads/interactions.jsonl index c70a31a..0eac5c1 100644 --- a/.beads/interactions.jsonl +++ b/.beads/interactions.jsonl @@ -444,3 +444,4 @@ {"id":"int-0ca290cd706fed413576380e6e7b9501","kind":"field_change","created_at":"2026-11-21T11:22:57.988315482Z","actor":"Shinuwa","issue_id":"sokko-g-eecb.9","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"getState wraps its build in expeditions.withSettingsSnapshot: expedition settings read 7 -> 1, prepares 48 -> 42 on an empty account. Snapshot is scoped to the synchronous build, cleared on error; outside it every access rereads. Test added."}} {"id":"int-69217a57aeec202222623a728c687d53","kind":"field_change","created_at":"2026-11-21T12:00:30.441841462Z","actor":"Shinuwa","issue_id":"sokko-g-eecb.7","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Budgets split into transfer (home 1.75 MB, Aniimo 3 MB, CSS 100 kB gzip) and storage (per-file 1 MB, per-folder report, no total cap); npm run test:assets runs in check:full. Home dragons recompressed (-35 kB), home back to ~1.71-1.72 MB."}} {"id":"int-7df73fef6bd9c552de1b6e1883717bf0","kind":"field_change","created_at":"2026-11-21T12:01:09.432506407Z","actor":"Shinuwa","issue_id":"sokko-g-eecb","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Les 9 correctifs côté projet de l'audit du 2026-11-19 sont faits ; le découpage du CSS est suivi à part."}} +{"id":"int-9f1de441cc2470beb7af669a5f3368a5","kind":"field_change","created_at":"2026-11-21T15:49:39.069539167Z","actor":"Shinuwa","issue_id":"sokko-g-2td","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Already in place: pack items in campaign rewards, atomic claim limited to one per player and 20/min, idempotent opening that can be resumed. Added: pack rates copied into the campaign at creation (packRates), applied at opening and shown at reveal."}} diff --git a/docs/STORAGE_SCHEMA.md b/docs/STORAGE_SCHEMA.md index 762ac09..932266d 100644 --- a/docs/STORAGE_SCHEMA.md +++ b/docs/STORAGE_SCHEMA.md @@ -350,9 +350,13 @@ Distributions par codes : d'utilisations (`NULL` = sans limite). `reward_json` vaut `{ items: [élément, …] }` (1 à 50 éléments), chaque élément étant `{ type: "card", editionId, quantity: 1 }` (chaque carte au plus une fois) ou - `{ type: "pack", collectionId, rarityWeights | null, guarantee | null, quantity }`, + `{ type: "pack", collectionId, rarityWeights | null, packRates | null, guarantee | null, quantity }`, avec une quantité de 1 à 10 et `guarantee` = `{ type: "rarity", rarity, count }` (au moins `count` cartes de cette rareté ou mieux) ou `{ type: "edition", editionId }`. + Sans taux personnalisés, `packRates` copie les taux du paquet à la création de la + campagne : tous les joueurs du code tirent avec ces taux, même si l'administration + modifie ensuite ceux du paquet. Les campagnes plus anciennes n'ont pas `packRates` et + suivent les taux en vigueur à l'ouverture. La récompense est validée et normalisée par `services/cards/rewards.js`. `expires_at` est nul pour une campagne sans date d'expiration. - `campaign_claims(id, campaign_id, player_id, claimed_at)` : une ligne @@ -360,7 +364,8 @@ Distributions par codes : - `gift_packs(id, player_id, campaign_id, collection_id, options_json, created_at, opening_id, opened_at)` : paquets offerts en attente. Leur ouverture ne consomme pas la recharge, ignore la fermeture de la collection et applique les taux et la garantie de - `options_json` ; `opening_id` les marque comme ouverts. + `options_json` (`{ rarityWeights, packRates, guarantee }`, copiés de la campagne) ; + `opening_id` les marque comme ouverts. Le navigateur utilise une base IndexedDB distincte, `sokkog-nebula-cards`, avec un object store `snapshots`. Chaque entrée est indexée par l'identifiant interne diff --git a/services/cards/rewards.js b/services/cards/rewards.js index 4d88eb1..74ef50b 100644 --- a/services/cards/rewards.js +++ b/services/cards/rewards.js @@ -10,7 +10,9 @@ export const MAX_ITEM_QUANTITY = 10; // Une récompense est une liste d'éléments : { items: [élément, …] }, au plus 50 éléments. // Élément « carte » : { type: "card", editionId, quantity: 1 }, chaque carte au plus une fois -// Élément « paquet » : { type: "pack", collectionId, rarityWeights | null, guarantee | null, quantity } +// Élément « paquet » : { type: "pack", collectionId, rarityWeights | null, packRates | null, guarantee | null, quantity } +// packRates : sans taux personnalisés, copie des taux du paquet à la création de la campagne ; chaque joueur +// du code tire avec ces taux, même si l'administration modifie ensuite ceux du paquet. // guarantee : { type: "rarity", rarity, count (1 à 3) } ou { type: "edition", editionId } export function normalizeReward(reward, catalog) { const items = reward?.items; @@ -66,5 +68,6 @@ function normalizeItem(reward, catalog) { invalid("Garantie inconnue."); } if (!rarityWeights && !collection.dropWeights) invalid("Cette collection n’a pas de taux de tirage : définissez des taux personnalisés."); - return { type: "pack", collectionId: collection.id, rarityWeights, guarantee }; + const packRates = rarityWeights ? null : Object.fromEntries(catalog.rarities.map((rarity) => [rarity.id, collection.dropWeights[rarity.id] ?? 0])); + return { type: "pack", collectionId: collection.id, rarityWeights, packRates, guarantee }; } diff --git a/services/cards/service.js b/services/cards/service.js index 15dc7eb..5856aa7 100644 --- a/services/cards/service.js +++ b/services/cards/service.js @@ -762,7 +762,7 @@ export class CardsService { const gift = this.db.prepare("SELECT * FROM gift_packs WHERE id = ? AND player_id = ? AND opening_id IS NULL").get(giftPackId, playerId); if (!gift) fail(404, "GIFT_PACK_NOT_FOUND", "Ce paquet offert n'est plus disponible."); const options = JSON.parse(gift.options_json); - const { openingId, editionIds } = this.insertOpening(playerId, gift.collection_id, drawPack(this.catalog, gift.collection_id, this.random, { weights: options.rarityWeights, guarantee: options.guarantee, requireActive: false })); + const { openingId, editionIds } = this.insertOpening(playerId, gift.collection_id, drawPack(this.catalog, gift.collection_id, this.random, { weights: options.rarityWeights ?? options.packRates ?? null, guarantee: options.guarantee, requireActive: false })); this.db.prepare("UPDATE gift_packs SET opening_id = ?, opened_at = ? WHERE id = ?").run(openingId, this.now(), gift.id); this.audit(playerId, "gift_pack_opened", openingId, { collectionId: gift.collection_id, campaignId: gift.campaign_id, ...(gift.expedition_id ? { expeditionId: gift.expedition_id } : {}), cards: editionIds }); return openingId; @@ -1154,7 +1154,8 @@ export class CardsService { if (!edition) fail(409, "REWARD_UNAVAILABLE", "Une carte de cette récompense n’existe plus dans le catalogue."); this.addCard(playerId, edition.id); } else { - const options = { rarityWeights: item.rarityWeights, guarantee: item.guarantee }; + // Les campagnes créées avant packRates gardent null : leurs paquets suivent les taux en vigueur à l'ouverture. + const options = { rarityWeights: item.rarityWeights, packRates: item.packRates ?? null, guarantee: item.guarantee }; this.db.prepare("INSERT INTO gift_packs(id, player_id, campaign_id, collection_id, options_json, created_at) VALUES (?, ?, ?, ?, ?, ?)") .run(randomUUID(), playerId, row.id, item.collectionId, JSON.stringify(options), this.now()); } diff --git a/tests/nebula-cards.test.mjs b/tests/nebula-cards.test.mjs index 3408732..90b9a2c 100644 --- a/tests/nebula-cards.test.mjs +++ b/tests/nebula-cards.test.mjs @@ -1223,6 +1223,46 @@ test("gift packs apply custom rates and guarantees without spending recharge", ( database.close(); }); +test("campaign packs keep the pack rates in force when the campaign was created", () => { + const rarityOf = (id) => catalog.editions.find((edition) => edition.id === id).rarity; + const only = (rarity) => Object.fromEntries(catalog.rarities.map((item) => [item.id, item.id === rarity ? 1 : 0])); + const database = new CardsDatabase(":memory:"); + const service = new CardsService({ database, catalog: baseCatalog, now: () => 1_800_000_000_000, random: () => 0 }); + const admin = service.upsertPlayer({ discordId: "frozen-admin", displayName: "Admin", isAdmin: true }); + const early = service.upsertPlayer({ discordId: "frozen-early", displayName: "Early" }); + const late = service.upsertPlayer({ discordId: "frozen-late", displayName: "Late" }); + service.setDropRates(admin.id, "astral-genesis", only("legendary")); + const frozen = service.createCampaign(admin.id, { name: "Figée", code: "FROZEN-RATES", reward: { items: [{ type: "pack", collectionId: "astral-genesis" }] } }).campaign; + assert.deepEqual(frozen.reward.items[0].packRates, only("legendary")); + // Des taux personnalisés s'appliquent tels quels : rien à copier. + const custom = service.createCampaign(admin.id, { name: "Perso", code: "CUSTOM-RATES", reward: { items: [{ type: "pack", collectionId: "astral-genesis", rarityWeights: only("rare") }] } }).campaign; + assert.equal(custom.reward.items[0].packRates, null); + + // L'un reçoit son paquet avant le changement des taux, l'autre après : tous deux tirent avec les taux de la création. + const earlyGift = service.claimCampaign(early.id, "FROZEN-RATES").state.giftPacks[0]; + service.setDropRates(admin.id, "astral-genesis", only("common")); + const lateGift = service.claimCampaign(late.id, "FROZEN-RATES").state.giftPacks[0]; + for (const [player, gift] of [[early, earlyGift], [late, lateGift]]) { + const { opening } = service.openGiftPack(player.id, gift.id, `frozen-${player.id}`); + assert.deepEqual(opening.cards.map((card) => rarityOf(card.editionId)), ["legendary", "legendary", "legendary"]); + // La révélation affiche les taux réellement appliqués. + assert.deepEqual(opening.options.packRates, only("legendary")); + } + // Un nouveau paquet de la campagne personnalisée suit ses propres taux. + const customGift = service.claimCampaign(early.id, "CUSTOM-RATES").state.giftPacks[0]; + service.completeOpening(early.id, service.getState(early.id).pendingOpening.id); + assert.ok(service.openGiftPack(early.id, customGift.id, "custom-1").opening.cards.every((card) => rarityOf(card.editionId) === "rare")); + + // Une campagne créée avant la copie des taux garde le comportement d'origine : les taux en vigueur à l'ouverture. + const legacyReward = { items: [{ type: "pack", collectionId: "astral-genesis", rarityWeights: null, guarantee: null, quantity: 1 }] }; + database.db.prepare("UPDATE campaigns SET reward_json = ? WHERE id = ?").run(JSON.stringify(legacyReward), frozen.id); + const legacy = service.upsertPlayer({ discordId: "frozen-legacy", displayName: "Legacy" }); + const legacyGift = service.claimCampaign(legacy.id, "FROZEN-RATES").state.giftPacks[0]; + assert.equal(legacyGift.options.packRates, null); + assert.ok(service.openGiftPack(legacy.id, legacyGift.id, "legacy-1").opening.cards.every((card) => rarityOf(card.editionId) === "common")); + database.close(); +}); + test("traders list the same available duplicates as each collection, without reserved ones", () => { const database = new CardsDatabase(":memory:"); const service = new CardsService({ database, catalog: baseCatalog, now: () => 1_800_000_000_000, random: () => 0 }); diff --git a/website/src/features/cards/PackPanel.jsx b/website/src/features/cards/PackPanel.jsx index f9268ea..f9cee2f 100644 --- a/website/src/features/cards/PackPanel.jsx +++ b/website/src/features/cards/PackPanel.jsx @@ -115,7 +115,7 @@ function RedeemCode({ catalog, runMutation, busy, content }) { function OpeningOdds({ catalog, opening, collection, content, shopShare }) { // Un paquet offert peut avoir ses propres taux et une garantie : ce sont eux qui s'appliquent à ce tirage. - const weights = opening.options?.rarityWeights || collection?.dropWeights; + const weights = opening.options?.rarityWeights || opening.options?.packRates || collection?.dropWeights; const details = packDetails(opening.options, catalog); if (collection?.packCategory === "shop") details.push(`${shopShare} % ${content.shopShare} ${collection.name}`); return