From e0967ef95b7457ebd9750420def0b9f978a51240 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 30 Oct 2026 13:39:09 +0000 Subject: [PATCH 01/13] feat(store): show running sales with list prices and a sale banner cosmetics.json now carries sales: while one covers an item, priceHard/ priceSoft are the sale price and listPriceHard/listPriceSoft the price before it, plus a top-level promotions list. The store shows the list price struck through with the discount on each buy button, and a banner per running sale with its end time. The store refetches a catalog older than a minute when it opens, so a sale that started or ended since the page loaded is priced as the server will charge it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019Wbkiw3pQDRGxxLWZXKXUL --- packages/shared/src/CosmeticSchemas.ts | 20 +++++++++ resources/lang/en.json | 2 + src/client/Cosmetics.ts | 23 ++++++++++ src/client/Store.ts | 38 +++++++++++++++- src/client/components/PurchaseButton.ts | 26 +++++++++++ tests/client/CosmeticsStaleRefresh.test.ts | 51 ++++++++++++++++++++++ tests/client/PurchaseButton.test.ts | 21 +++++++++ tests/client/StoreModal.test.ts | 44 +++++++++++++++++++ 8 files changed, 224 insertions(+), 1 deletion(-) create mode 100644 tests/client/CosmeticsStaleRefresh.test.ts diff --git a/packages/shared/src/CosmeticSchemas.ts b/packages/shared/src/CosmeticSchemas.ts index 24c74f0560f..8e833279826 100644 --- a/packages/shared/src/CosmeticSchemas.ts +++ b/packages/shared/src/CosmeticSchemas.ts @@ -89,12 +89,26 @@ export const ColorPaletteSchema = z.object({ secondaryColor: z.string(), }); +// A store sale. While one covers an item, the item's priceHard/priceSoft are +// already the sale price (what the purchase endpoints charge); listPriceHard/ +// listPriceSoft carry the price before it, and `promotion` names the sale. +export const PromotionSchema = z.object({ + id: z.string(), + name: z.string(), + percentOff: z.number(), + endsAt: z.string(), +}); +export type Promotion = z.infer; + const CosmeticSchema = z.object({ name: CosmeticNameSchema, affiliateCode: z.string().nullable().optional(), product: ProductSchema.nullable(), priceSoft: z.number().optional(), priceHard: z.number().optional(), + listPriceSoft: z.number().optional(), + listPriceHard: z.number().optional(), + promotion: PromotionSchema.optional(), artist: z.string().optional(), // Whether the artist declared they used generative AI making this. Present only when they // actually answered: the catalogue omits the field for everything nobody was asked about, so @@ -486,6 +500,9 @@ export const CosmeticPackSchema = z.object({ displayName: z.string(), description: z.string(), priceHard: z.number(), + // Present only while a sale covers the pack; priceHard is then the sale price. + listPriceHard: z.number().optional(), + promotion: PromotionSchema.optional(), rarity: z .enum(["common", "uncommon", "rare", "epic", "legendary"]) .or(z.string()), @@ -556,6 +573,9 @@ export const CosmeticsSchema = z.object({ // Price to put a listed lobby in the public queue (host modal's Queue // button). Optional like tribeNames; the button hides when absent. lobbyQueue: z.object({ priceHard: z.number() }).optional(), + // Every sale running when the catalog was served, for the store banner. + // Optional: an older cosmetics.json has none. + promotions: PromotionSchema.array().optional(), }); /** diff --git a/resources/lang/en.json b/resources/lang/en.json index 235a3354c88..ddf70429cc9 100644 --- a/resources/lang/en.json +++ b/resources/lang/en.json @@ -2438,6 +2438,8 @@ "purchase_pending": "Your purchase is still being processed. It will appear in your account shortly — check your order history if it doesn't.", "purchase_success": "Purchase succeeded: {name}", "purchase_tribe_button": "Purchase", + "sale_banner": "{name}: {percent}% off. Ends {ends}.", + "sale_percent_off": "-{percent}%", "steam_browser_approval": "Steam has opened the purchase in your browser. Approve it there, then come back here. It will show up once Steam confirms it.", "steam_licence_required": "This subscription is only for players who own OpenFront on Steam.", "steam_overlay_cancelled": "Purchase cancelled. You haven't been charged.", diff --git a/src/client/Cosmetics.ts b/src/client/Cosmetics.ts index 8d503ed0e57..7fd2fe3fe76 100644 --- a/src/client/Cosmetics.ts +++ b/src/client/Cosmetics.ts @@ -60,6 +60,10 @@ export const COSMETICS_FETCH_TIMEOUT_MS = 10_000; let __cosmetics: Promise | null = null; let __cosmeticsHash: string | null = null; let __cosmeticsCache: Cosmetics | null = null; +let __cosmeticsFetchedAt = 0; + +/** How long a fetched catalog is trusted before the store refetches it. */ +export const COSMETICS_STALE_MS = 60_000; /** * Synchronous accessor for the most recently resolved cosmetics. Returns null @@ -849,6 +853,24 @@ export function invalidateCosmetics(): void { __cosmetics = null; } +/** + * Drops a catalog fetched more than COSMETICS_STALE_MS ago, so the next + * fetchCosmetics() refetches it. Sale prices start and end on the server's + * clock; the API serves cosmetics.json from a one-minute cache, so this keeps + * the store within about two minutes of what a purchase is charged. Returns + * whether it dropped the catalog. + */ +export function refreshStaleCosmetics(now: number = Date.now()): boolean { + if ( + __cosmeticsCache === null || + now - __cosmeticsFetchedAt <= COSMETICS_STALE_MS + ) { + return false; + } + invalidateCosmetics(); + return true; +} + export type TierListingRail = "steam" | "web"; // cosmetics.json lists subscription tiers per rail: the one this device checks @@ -883,6 +905,7 @@ export async function fetchCosmetics(): Promise { const hashInput = patternKeys.join(","); __cosmeticsHash = simpleHash(hashInput); __cosmeticsCache = result.data; + __cosmeticsFetchedAt = Date.now(); return result.data; } catch (error) { console.warn("Error getting cosmetics:", error); diff --git a/src/client/Store.ts b/src/client/Store.ts index 7972fbcda09..302cddff04a 100644 --- a/src/client/Store.ts +++ b/src/client/Store.ts @@ -28,6 +28,7 @@ import "./components/TribesPanel"; import { modalHeader } from "./components/ui/ModalHeader"; import { fetchCosmetics, + refreshStaleCosmetics, findPackItem, groupCosmeticVariants, ownedPackItems, @@ -442,6 +443,8 @@ export class StoreModal extends BaseModal { product?: Product | null; priceHard?: number; priceSoft?: number; + listPriceHard?: number; + listPriceSoft?: number; rarity?: string; } | null; const isPurchasable = resolved.relationship === "purchasable"; @@ -490,6 +493,8 @@ export class StoreModal extends BaseModal { .inlineCheckout=${inlineCheckout} .priceHard=${priceHard ?? null} .priceSoft=${priceSoft ?? null} + .listPriceHard=${priceHard !== undefined ? (priced?.listPriceHard ?? null) : null} + .listPriceSoft=${priceSoft !== undefined ? (priced?.listPriceSoft ?? null) : null} .rarity=${priced?.rarity ?? "common"} .itemName=${cosmeticSelectionLabel(resolved)} .dollarLabelKey=${ @@ -670,8 +675,36 @@ export class StoreModal extends BaseModal { }); } + /** One line per running sale, under the header. */ + private renderSaleBanner(): TemplateResult | string { + const sales = (this.cosmetics?.promotions ?? []).filter( + (sale) => new Date(sale.endsAt).getTime() > Date.now(), + ); + if (sales.length === 0) return ""; + return html`
+ ${sales.map( + (sale) => + html`
+ ${translateText("store.sale_banner", { + name: sale.name, + percent: sale.percentOff, + ends: new Date(sale.endsAt).toLocaleString(undefined, { + dateStyle: "medium", + timeStyle: "short", + }), + })} +
`, + )} +
`; + } + protected renderHeaderSlot() { - return html`${this.renderHeader()} + return html`${this.renderHeader()} ${this.renderSaleBanner()} ${ this.previewingCosmetic ? html` + ${listPrice.toLocaleString()} + ${translateText("store.sale_percent_off", { percent: percentOff })} + `; +} + @customElement("purchase-button") export class PurchaseButton extends LitElement { @property({ type: Object }) @@ -225,6 +240,15 @@ export class PurchaseButton extends LitElement { @property({ type: Number }) priceSoft: number | null = null; + /** Price before a running sale, shown struck through beside priceHard. + * Null (or not above priceHard) means the item isn't on sale. */ + @property({ type: Number }) + listPriceHard: number | null = null; + + /** Price before a running sale, shown struck through beside priceSoft. */ + @property({ type: Number }) + listPriceSoft: number | null = null; + @property({ type: String }) rarity: string = "common"; @@ -385,6 +409,7 @@ export class PurchaseButton extends LitElement { > ${this.priceHard!.toLocaleString()} + ${renderSaleTag(this.priceHard!, this.listPriceHard)} `; } @@ -402,6 +427,7 @@ export class PurchaseButton extends LitElement { > ${this.priceSoft!.toLocaleString()} + ${renderSaleTag(this.priceSoft!, this.listPriceSoft)} `; } diff --git a/tests/client/CosmeticsStaleRefresh.test.ts b/tests/client/CosmeticsStaleRefresh.test.ts new file mode 100644 index 00000000000..86bb1a9dd54 --- /dev/null +++ b/tests/client/CosmeticsStaleRefresh.test.ts @@ -0,0 +1,51 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + COSMETICS_STALE_MS, + fetchCosmetics, + invalidateCosmetics, + refreshStaleCosmetics, +} from "../../src/client/Cosmetics"; + +vi.mock("../../src/client/Api", async (importOriginal) => ({ + ...(await importOriginal()), + getApiBase: () => "https://api.test", +})); + +// Sale prices start and end on the server, so the store refetches a catalog +// older than COSMETICS_STALE_MS when it opens. +describe("refreshStaleCosmetics", () => { + let fetchMock: ReturnType; + + beforeEach(() => { + invalidateCosmetics(); + fetchMock = vi.fn(async () => ({ + ok: true, + status: 200, + json: async () => ({ patterns: {}, flags: {} }), + })); + vi.stubGlobal("fetch", fetchMock); + }); + + afterEach(() => { + invalidateCosmetics(); + vi.unstubAllGlobals(); + }); + + it("keeps a fresh catalog", async () => { + await fetchCosmetics(); + expect(refreshStaleCosmetics(Date.now() + COSMETICS_STALE_MS - 1000)).toBe( + false, + ); + await fetchCosmetics(); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it("refetches a catalog older than the stale window", async () => { + await fetchCosmetics(); + expect(refreshStaleCosmetics(Date.now() + COSMETICS_STALE_MS + 1000)).toBe( + true, + ); + await fetchCosmetics(); + expect(fetchMock).toHaveBeenCalledTimes(2); + }); +}); diff --git a/tests/client/PurchaseButton.test.ts b/tests/client/PurchaseButton.test.ts index 5bf8afe34a2..f2c2d17787f 100644 --- a/tests/client/PurchaseButton.test.ts +++ b/tests/client/PurchaseButton.test.ts @@ -81,6 +81,27 @@ describe("PurchaseButton", () => { } }); + it("strikes through the list price and shows the discount during a sale", async () => { + button = document.createElement("purchase-button") as PurchaseButton; + button.priceHard = 75; + button.listPriceHard = 100; + button.priceSoft = 500; + button.listPriceSoft = 500; + button.onPurchaseHard = vi.fn(async () => undefined); + button.onPurchaseSoft = vi.fn(async () => undefined); + document.body.appendChild(button); + await button.updateComplete; + + const hard = button.querySelector(".purchase-sparkle-btn-hard")!; + expect(hard.querySelector("s")?.textContent?.trim()).toBe("100"); + expect(hard.querySelector("[data-sale-tag]")?.textContent).toContain( + "store.sale_percent_off", + ); + // A list price not above the price is no sale. + const soft = button.querySelector(".purchase-sparkle-btn-soft")!; + expect(soft.querySelector("[data-sale-tag]")).toBeNull(); + }); + it("clears busy state and reports a synchronous purchase throw", async () => { vi.mocked(showInGameAlert).mockClear(); vi.spyOn(console, "error").mockImplementation(() => undefined); diff --git a/tests/client/StoreModal.test.ts b/tests/client/StoreModal.test.ts index fc6a4868655..ef9564c3071 100644 --- a/tests/client/StoreModal.test.ts +++ b/tests/client/StoreModal.test.ts @@ -347,6 +347,50 @@ describe("StoreModal cosmetic browser", () => { localStorage.clear(); }); + it("shows a running sale: banner, struck list price and discount", async () => { + const endsAt = new Date(Date.now() + 3_600_000).toISOString(); + vi.mocked(fetchCosmetics).mockResolvedValue({ + promotions: [ + { id: "1", name: "Weekend Sale", percentOff: 25, endsAt }, + // Already over: the banner drops it even before the catalog refetches. + { + id: "2", + name: "Old Sale", + percentOff: 50, + endsAt: new Date(Date.now() - 1000).toISOString(), + }, + ], + } as unknown as Cosmetics); + resolvedCatalog = [ + { + ...red, + cosmetic: { ...pattern, priceHard: 90, listPriceHard: 120 } as never, + }, + ]; + const modal = await openStoreOnCosmetic("patterns"); + await vi.waitFor(() => + expect(modal.querySelector("[data-store-sale-banner]")).toBeTruthy(), + ); + + const banner = modal.querySelector("[data-store-sale-banner]")!; + expect(banner.children).toHaveLength(1); + expect(banner.textContent).toContain("store.sale_banner"); + const button = modal.querySelector("purchase-button")!; + expect(button.listPriceHard).toBe(120); + await button.updateComplete; + const tag = button.querySelector("[data-sale-tag]")!; + expect(tag.querySelector("s")?.textContent?.trim()).toBe("120"); + }); + + it("shows no banner or list price without a sale", async () => { + const modal = await openStoreOnCosmetic("patterns"); + expect(modal.querySelector("[data-store-sale-banner]")).toBeNull(); + const button = modal.querySelector("purchase-button")!; + await button.updateComplete; + expect(button.listPriceHard).toBeNull(); + expect(button.querySelector("[data-sale-tag]")).toBeNull(); + }); + it("selects the first visible item and purchases the selected variant", async () => { const modal = await openStoreOnCosmetic("patterns"); expect(card(modal, red.key)?.activeVariantKey).toBe(red.key); From 73f8fef7097ec74eaf17a30988dae00d411cd499 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 30 Oct 2026 14:19:01 +0000 Subject: [PATCH 02/13] fix(store): keep the shown catalog when a stale refetch fails A store reopened after the one-minute stale window dropped its catalog before refetching, so a failed refetch (offline, timeout, bad response) left it empty. It now keeps the catalog it already had unless the refetch succeeds. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019Wbkiw3pQDRGxxLWZXKXUL --- src/client/Store.ts | 6 +++++- tests/client/StoreModal.test.ts | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/client/Store.ts b/src/client/Store.ts index 302cddff04a..b8b904d3ad1 100644 --- a/src/client/Store.ts +++ b/src/client/Store.ts @@ -770,7 +770,11 @@ export class StoreModal extends BaseModal { } // Prices change when a sale starts or ends, so a catalog fetched more than // a minute ago is refetched rather than shown with stale prices. - if (refreshStaleCosmetics()) this.cosmetics = null; + // A failed refetch keeps the catalog already shown rather than emptying + // the store; the purchase endpoint charges the live price either way. + if (refreshStaleCosmetics()) { + this.cosmetics = (await fetchCosmetics()) ?? this.cosmetics; + } this.cosmetics ??= await fetchCosmetics(); this.selectVisible(this.groupsForTab(this.activeTab)); await this.refresh(); diff --git a/tests/client/StoreModal.test.ts b/tests/client/StoreModal.test.ts index ef9564c3071..2aaa360debd 100644 --- a/tests/client/StoreModal.test.ts +++ b/tests/client/StoreModal.test.ts @@ -8,6 +8,7 @@ import type { PurchaseButton } from "../../src/client/components/PurchaseButton" import { fetchCosmetics, purchaseCosmetic, + refreshStaleCosmetics, resolveCosmetics, type ResolvedCosmetic, } from "../../src/client/Cosmetics"; @@ -22,6 +23,7 @@ vi.mock("../../src/client/Cosmetics", async (importOriginal) => ({ ...(await importOriginal()), fetchCosmetics: vi.fn(), purchaseCosmetic: vi.fn(), + refreshStaleCosmetics: vi.fn(() => false), resolveCosmetics: vi.fn(), })); @@ -382,6 +384,23 @@ describe("StoreModal cosmetic browser", () => { expect(tag.querySelector("s")?.textContent?.trim()).toBe("120"); }); + it("keeps the shown catalog when a stale refetch fails", async () => { + const shown = { promotions: [] } as unknown as Cosmetics; + vi.mocked(fetchCosmetics).mockResolvedValue(shown); + const modal = await openStoreOnCosmetic("patterns"); + modal.close(); + + vi.mocked(refreshStaleCosmetics).mockReturnValueOnce(true); + vi.mocked(fetchCosmetics).mockReset(); + vi.mocked(fetchCosmetics).mockResolvedValue(null); + modal.open({ tab: "cosmetics" }); + await vi.waitFor(() => expect(fetchCosmetics).toHaveBeenCalled()); + await new Promise((resolve) => setTimeout(resolve, 0)); + + expect((modal as unknown as { cosmetics: unknown }).cosmetics).toBe(shown); + expect(modal.querySelector("cosmetic-card")).toBeTruthy(); + }); + it("shows no banner or list price without a sale", async () => { const modal = await openStoreOnCosmetic("patterns"); expect(modal.querySelector("[data-store-sale-banner]")).toBeNull(); From 72658c3c5553f1fcf5b2fbc70eec689da11f6ab2 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 30 Oct 2026 14:38:59 +0000 Subject: [PATCH 03/13] fix(store): refetch prices when a sale ends; keep catalog on failed sign-in fetch An open store kept showing an ended sale's banner and prices until the player touched it: it now refetches the catalog when the soonest running sale ends. onUserMe overwrote the shown catalog with null when its fetch failed (e.g. a stale refetch that failed); it now keeps the catalog, as onOpen does. Tests also assert the discount and banner arguments passed to translateText. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019Wbkiw3pQDRGxxLWZXKXUL --- src/client/Store.ts | 33 +++++++++++++++- tests/client/PurchaseButton.test.ts | 11 ++++++ tests/client/StoreModal.test.ts | 60 +++++++++++++++++++++++++++++ 3 files changed, 103 insertions(+), 1 deletion(-) diff --git a/src/client/Store.ts b/src/client/Store.ts index b8b904d3ad1..21edc2c6a85 100644 --- a/src/client/Store.ts +++ b/src/client/Store.ts @@ -28,6 +28,7 @@ import "./components/TribesPanel"; import { modalHeader } from "./components/ui/ModalHeader"; import { fetchCosmetics, + invalidateCosmetics, refreshStaleCosmetics, findPackItem, groupCosmeticVariants, @@ -177,12 +178,15 @@ export class StoreModal extends BaseModal { }; private rowObserver: ResizeObserver | null = null; + /** Fires when the soonest running sale ends, to refetch its prices. */ + private saleEndTimer: ReturnType | null = null; private alignFrame: number | null = null; async onUserMe(userMeResponse: UserMeResponse | false) { this.userMeResponse = userMeResponse; this.authSettled = true; - this.cosmetics = await fetchCosmetics(); + // A failed fetch keeps the catalog already shown (see onOpen). + this.cosmetics = (await fetchCosmetics()) ?? this.cosmetics; this.selectVisible(this.groupsForTab(this.activeTab)); await this.refresh(); } @@ -680,6 +684,7 @@ export class StoreModal extends BaseModal { const sales = (this.cosmetics?.promotions ?? []).filter( (sale) => new Date(sale.endsAt).getTime() > Date.now(), ); + this.scheduleSaleEnd(sales); if (sales.length === 0) return ""; return html`
`; } + /** + * When the soonest running sale ends, refetch the catalog so its items go + * back to list price and its banner drops, even if the player never touches + * the open store. Rescheduled on every render; cleared on close. + */ + private scheduleSaleEnd(sales: readonly { endsAt: string }[]): void { + if (this.saleEndTimer !== null) clearTimeout(this.saleEndTimer); + this.saleEndTimer = null; + if (sales.length === 0 || !this.isModalOpen) return; + const nextEnd = Math.min(...sales.map((s) => new Date(s.endsAt).getTime())); + // setTimeout overflows past ~24.8 days; a later end is rescheduled by a + // later render. + const delay = Math.min(Math.max(nextEnd - Date.now(), 0), 2 ** 31 - 1); + this.saleEndTimer = setTimeout(() => { + this.saleEndTimer = null; + invalidateCosmetics(); + void fetchCosmetics().then((fresh) => { + this.cosmetics = fresh ?? this.cosmetics; + this.selectVisible(this.groupsForTab(this.activeTab)); + this.requestUpdate(); + }); + }, delay); + } + protected renderHeaderSlot() { return html`${this.renderHeader()} ${this.renderSaleBanner()} ${ @@ -781,6 +810,8 @@ export class StoreModal extends BaseModal { } protected onClose(): void { + if (this.saleEndTimer !== null) clearTimeout(this.saleEndTimer); + this.saleEndTimer = null; // The store hides via CSS (inline modal), so the tiles never disconnect // and an open card-payment modal — portaled to — would float over // the play page after Escape closes the store. Close it explicitly. diff --git a/tests/client/PurchaseButton.test.ts b/tests/client/PurchaseButton.test.ts index f2c2d17787f..40544b8558f 100644 --- a/tests/client/PurchaseButton.test.ts +++ b/tests/client/PurchaseButton.test.ts @@ -7,7 +7,14 @@ vi.mock("../../src/client/InGameModal", () => ({ showInGameConfirm: vi.fn().mockResolvedValue(true), })); +vi.mock("../../src/client/Utils", async (importOriginal) => { + const actual = + await importOriginal(); + return { ...actual, translateText: vi.fn(actual.translateText) }; +}); + const { showInGameAlert } = await import("../../src/client/InGameModal"); +const { translateText } = await import("../../src/client/Utils"); describe("PurchaseButton", () => { let button: PurchaseButton | undefined; @@ -82,6 +89,7 @@ describe("PurchaseButton", () => { }); it("strikes through the list price and shows the discount during a sale", async () => { + vi.mocked(translateText).mockClear(); button = document.createElement("purchase-button") as PurchaseButton; button.priceHard = 75; button.listPriceHard = 100; @@ -97,6 +105,9 @@ describe("PurchaseButton", () => { expect(hard.querySelector("[data-sale-tag]")?.textContent).toContain( "store.sale_percent_off", ); + expect(translateText).toHaveBeenCalledWith("store.sale_percent_off", { + percent: 25, + }); // A list price not above the price is no sale. const soft = button.querySelector(".purchase-sparkle-btn-soft")!; expect(soft.querySelector("[data-sale-tag]")).toBeNull(); diff --git a/tests/client/StoreModal.test.ts b/tests/client/StoreModal.test.ts index 2aaa360debd..12651027bdf 100644 --- a/tests/client/StoreModal.test.ts +++ b/tests/client/StoreModal.test.ts @@ -18,6 +18,13 @@ import { PATTERN_KEY, UserSettings, } from "../../src/client/UserSettings"; +import { translateText } from "../../src/client/Utils"; + +vi.mock("../../src/client/Utils", async (importOriginal) => { + const actual = + await importOriginal(); + return { ...actual, translateText: vi.fn(actual.translateText) }; +}); vi.mock("../../src/client/Cosmetics", async (importOriginal) => ({ ...(await importOriginal()), @@ -377,6 +384,18 @@ describe("StoreModal cosmetic browser", () => { const banner = modal.querySelector("[data-store-sale-banner]")!; expect(banner.children).toHaveLength(1); expect(banner.textContent).toContain("store.sale_banner"); + expect(translateText).toHaveBeenCalledWith("store.sale_banner", { + name: "Weekend Sale", + percent: 25, + ends: new Date(endsAt).toLocaleString(undefined, { + dateStyle: "medium", + timeStyle: "short", + }), + }); + expect(translateText).not.toHaveBeenCalledWith( + "store.sale_banner", + expect.objectContaining({ name: "Old Sale" }), + ); const button = modal.querySelector("purchase-button")!; expect(button.listPriceHard).toBe(120); await button.updateComplete; @@ -401,6 +420,47 @@ describe("StoreModal cosmetic browser", () => { expect(modal.querySelector("cosmetic-card")).toBeTruthy(); }); + it("keeps the shown catalog when the sign-in refetch fails", async () => { + const shown = { promotions: [] } as unknown as Cosmetics; + vi.mocked(fetchCosmetics).mockResolvedValue(shown); + const modal = await openStoreOnCosmetic("patterns"); + + vi.mocked(fetchCosmetics).mockResolvedValue(null); + await modal.onUserMe(false); + + expect((modal as unknown as { cosmetics: unknown }).cosmetics).toBe(shown); + expect(modal.querySelector("cosmetic-card")).toBeTruthy(); + }); + + it("refetches prices when a sale ends while the store is open", async () => { + vi.useFakeTimers({ shouldAdvanceTime: true }); + try { + const endsAt = new Date(Date.now() + 60_000).toISOString(); + vi.mocked(fetchCosmetics).mockResolvedValue({ + promotions: [{ id: "1", name: "Flash", percentOff: 10, endsAt }], + } as unknown as Cosmetics); + const modal = await openStoreOnCosmetic("patterns"); + await vi.waitFor(() => + expect(modal.querySelector("[data-store-sale-banner]")).toBeTruthy(), + ); + + const after = { promotions: [] } as unknown as Cosmetics; + vi.mocked(fetchCosmetics).mockClear(); + vi.mocked(fetchCosmetics).mockResolvedValue(after); + await vi.advanceTimersByTimeAsync(61_000); + + await vi.waitFor(() => expect(fetchCosmetics).toHaveBeenCalled()); + await vi.waitFor(() => + expect(modal.querySelector("[data-store-sale-banner]")).toBeNull(), + ); + expect((modal as unknown as { cosmetics: unknown }).cosmetics).toBe( + after, + ); + } finally { + vi.useRealTimers(); + } + }); + it("shows no banner or list price without a sale", async () => { const modal = await openStoreOnCosmetic("patterns"); expect(modal.querySelector("[data-store-sale-banner]")).toBeNull(); From 9430bb6a40233b6d640c65a78bc9d66e40739552 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 30 Oct 2026 14:45:39 +0000 Subject: [PATCH 04/13] fix(store): retry the sale-end refetch while the API still serves the sale The API caches cosmetics.json for a minute, so a refetch at the exact end of a sale usually got the catalog that still carried its prices; the banner dropped but the buttons kept the struck list price and discount. The store now refetches every 15s, for up to two minutes, until the catalog no longer lists an ended sale. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019Wbkiw3pQDRGxxLWZXKXUL --- src/client/Store.ts | 41 ++++++++++++++++++++++++++++----- tests/client/StoreModal.test.ts | 40 ++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 6 deletions(-) diff --git a/src/client/Store.ts b/src/client/Store.ts index 21edc2c6a85..480a0244fd3 100644 --- a/src/client/Store.ts +++ b/src/client/Store.ts @@ -84,6 +84,11 @@ interface StoreBrowserOptions { emptyClass?: string; } +// After a sale ends, how often and how many times the store refetches while +// the API's one-minute-cached catalog still lists it (8 x 15s = 2 minutes). +const SALE_END_RETRY_MS = 15_000; +const SALE_END_RETRIES = 8; + @customElement("store-modal") export class StoreModal extends BaseModal { protected routerName = "store"; @@ -180,6 +185,8 @@ export class StoreModal extends BaseModal { private rowObserver: ResizeObserver | null = null; /** Fires when the soonest running sale ends, to refetch its prices. */ private saleEndTimer: ReturnType | null = null; + /** Retries that refetch while the API's cached catalog still has the sale. */ + private saleRetryTimer: ReturnType | null = null; private alignFrame: number | null = null; async onUserMe(userMeResponse: UserMeResponse | false) { @@ -723,15 +730,35 @@ export class StoreModal extends BaseModal { const delay = Math.min(Math.max(nextEnd - Date.now(), 0), 2 ** 31 - 1); this.saleEndTimer = setTimeout(() => { this.saleEndTimer = null; - invalidateCosmetics(); - void fetchCosmetics().then((fresh) => { - this.cosmetics = fresh ?? this.cosmetics; - this.selectVisible(this.groupsForTab(this.activeTab)); - this.requestUpdate(); - }); + void this.refetchAfterSaleEnd(0); }, delay); } + /** + * Refetches the catalog after a sale ends. The API serves cosmetics.json + * from a one-minute cache, so the first answer may still carry the ended + * sale's prices; while it does, try again, for up to two minutes. + */ + private async refetchAfterSaleEnd(attempt: number): Promise { + invalidateCosmetics(); + const fresh = await fetchCosmetics(); + if (!this.isModalOpen) return; + this.cosmetics = fresh ?? this.cosmetics; + this.selectVisible(this.groupsForTab(this.activeTab)); + this.requestUpdate(); + const now = Date.now(); + const stillHasEnded = (fresh?.promotions ?? []).some( + (sale) => new Date(sale.endsAt).getTime() <= now, + ); + if ((fresh === null || stillHasEnded) && attempt < SALE_END_RETRIES) { + if (this.saleRetryTimer !== null) clearTimeout(this.saleRetryTimer); + this.saleRetryTimer = setTimeout(() => { + this.saleRetryTimer = null; + void this.refetchAfterSaleEnd(attempt + 1); + }, SALE_END_RETRY_MS); + } + } + protected renderHeaderSlot() { return html`${this.renderHeader()} ${this.renderSaleBanner()} ${ @@ -812,6 +839,8 @@ export class StoreModal extends BaseModal { protected onClose(): void { if (this.saleEndTimer !== null) clearTimeout(this.saleEndTimer); this.saleEndTimer = null; + if (this.saleRetryTimer !== null) clearTimeout(this.saleRetryTimer); + this.saleRetryTimer = null; // The store hides via CSS (inline modal), so the tiles never disconnect // and an open card-payment modal — portaled to — would float over // the play page after Escape closes the store. Close it explicitly. diff --git a/tests/client/StoreModal.test.ts b/tests/client/StoreModal.test.ts index 12651027bdf..267224abe37 100644 --- a/tests/client/StoreModal.test.ts +++ b/tests/client/StoreModal.test.ts @@ -461,6 +461,46 @@ describe("StoreModal cosmetic browser", () => { } }); + it("keeps refetching after a sale ends while the API still serves it", async () => { + vi.useFakeTimers({ shouldAdvanceTime: true }); + try { + const sale = { + id: "1", + name: "Flash", + percentOff: 10, + endsAt: new Date(Date.now() + 60_000).toISOString(), + }; + const during = { promotions: [sale] } as unknown as Cosmetics; + vi.mocked(fetchCosmetics).mockResolvedValue(during); + const modal = await openStoreOnCosmetic("patterns"); + await vi.waitFor(() => + expect(modal.querySelector("[data-store-sale-banner]")).toBeTruthy(), + ); + + // The API's cached catalog still lists the sale just after it ends. + const after = { promotions: [] } as unknown as Cosmetics; + vi.mocked(fetchCosmetics).mockClear(); + vi.mocked(fetchCosmetics) + .mockResolvedValueOnce(during) + .mockResolvedValue(after); + await vi.advanceTimersByTimeAsync(61_000); + await vi.waitFor(() => expect(fetchCosmetics).toHaveBeenCalledTimes(1)); + expect((modal as unknown as { cosmetics: unknown }).cosmetics).toBe( + during, + ); + + await vi.advanceTimersByTimeAsync(16_000); + await vi.waitFor(() => expect(fetchCosmetics).toHaveBeenCalledTimes(2)); + await vi.waitFor(() => + expect((modal as unknown as { cosmetics: unknown }).cosmetics).toBe( + after, + ), + ); + } finally { + vi.useRealTimers(); + } + }); + it("shows no banner or list price without a sale", async () => { const modal = await openStoreOnCosmetic("patterns"); expect(modal.querySelector("[data-store-sale-banner]")).toBeNull(); From 57ab46fea6b92ec21d3ac360ffbc37de86592570 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 30 Oct 2026 14:53:01 +0000 Subject: [PATCH 05/13] fix(store): drop a sale-end refetch that lands after the store reopened A sale-end refetch still in flight when the store closed could resolve after it reopened and replace the newer catalog that open had loaded. A generation counter bumped on close now drops it. The sale-end test also checks that the buy button returns to its list price. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019Wbkiw3pQDRGxxLWZXKXUL --- src/client/Store.ts | 7 ++++- tests/client/StoreModal.test.ts | 53 +++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 1 deletion(-) diff --git a/src/client/Store.ts b/src/client/Store.ts index 480a0244fd3..aceb2a5f5e1 100644 --- a/src/client/Store.ts +++ b/src/client/Store.ts @@ -187,6 +187,8 @@ export class StoreModal extends BaseModal { private saleEndTimer: ReturnType | null = null; /** Retries that refetch while the API's cached catalog still has the sale. */ private saleRetryTimer: ReturnType | null = null; + /** Bumped on close, so a sale-end refetch still in flight then is dropped. */ + private saleRefetchGeneration = 0; private alignFrame: number | null = null; async onUserMe(userMeResponse: UserMeResponse | false) { @@ -740,9 +742,11 @@ export class StoreModal extends BaseModal { * sale's prices; while it does, try again, for up to two minutes. */ private async refetchAfterSaleEnd(attempt: number): Promise { + const generation = this.saleRefetchGeneration; invalidateCosmetics(); const fresh = await fetchCosmetics(); - if (!this.isModalOpen) return; + // Closed (and maybe reopened) since: that open's own fetch wins. + if (!this.isModalOpen || generation !== this.saleRefetchGeneration) return; this.cosmetics = fresh ?? this.cosmetics; this.selectVisible(this.groupsForTab(this.activeTab)); this.requestUpdate(); @@ -841,6 +845,7 @@ export class StoreModal extends BaseModal { this.saleEndTimer = null; if (this.saleRetryTimer !== null) clearTimeout(this.saleRetryTimer); this.saleRetryTimer = null; + this.saleRefetchGeneration++; // The store hides via CSS (inline modal), so the tiles never disconnect // and an open card-payment modal — portaled to — would float over // the play page after Escape closes the store. Close it explicitly. diff --git a/tests/client/StoreModal.test.ts b/tests/client/StoreModal.test.ts index 267224abe37..30f435cf3aa 100644 --- a/tests/client/StoreModal.test.ts +++ b/tests/client/StoreModal.test.ts @@ -439,14 +439,24 @@ describe("StoreModal cosmetic browser", () => { vi.mocked(fetchCosmetics).mockResolvedValue({ promotions: [{ id: "1", name: "Flash", percentOff: 10, endsAt }], } as unknown as Cosmetics); + resolvedCatalog = [ + { + ...red, + cosmetic: { ...pattern, priceHard: 108, listPriceHard: 120 } as never, + }, + ]; const modal = await openStoreOnCosmetic("patterns"); await vi.waitFor(() => expect(modal.querySelector("[data-store-sale-banner]")).toBeTruthy(), ); + expect( + modal.querySelector("purchase-button")!.listPriceHard, + ).toBe(120); const after = { promotions: [] } as unknown as Cosmetics; vi.mocked(fetchCosmetics).mockClear(); vi.mocked(fetchCosmetics).mockResolvedValue(after); + resolvedCatalog = [red]; await vi.advanceTimersByTimeAsync(61_000); await vi.waitFor(() => expect(fetchCosmetics).toHaveBeenCalled()); @@ -456,6 +466,49 @@ describe("StoreModal cosmetic browser", () => { expect((modal as unknown as { cosmetics: unknown }).cosmetics).toBe( after, ); + const button = modal.querySelector("purchase-button")!; + expect(button.priceHard).toBe(120); + expect(button.listPriceHard).toBeNull(); + } finally { + vi.useRealTimers(); + } + }); + + it("drops a sale-end refetch that lands after the store was closed and reopened", async () => { + vi.useFakeTimers({ shouldAdvanceTime: true }); + try { + const endsAt = new Date(Date.now() + 60_000).toISOString(); + const during = { + promotions: [{ id: "1", name: "Flash", percentOff: 10, endsAt }], + } as unknown as Cosmetics; + vi.mocked(fetchCosmetics).mockResolvedValue(during); + const modal = await openStoreOnCosmetic("patterns"); + + let resolveLate: (c: Cosmetics) => void = () => {}; + vi.mocked(fetchCosmetics).mockReturnValueOnce( + new Promise((resolve) => { + resolveLate = resolve; + }) as never, + ); + await vi.advanceTimersByTimeAsync(61_000); + await vi.waitFor(() => expect(fetchCosmetics).toHaveBeenCalled()); + + modal.close(); + const reopened = { promotions: [] } as unknown as Cosmetics; + vi.mocked(refreshStaleCosmetics).mockReturnValueOnce(true); + vi.mocked(fetchCosmetics).mockResolvedValue(reopened); + modal.open({ tab: "cosmetics" }); + await vi.waitFor(() => + expect((modal as unknown as { cosmetics: unknown }).cosmetics).toBe( + reopened, + ), + ); + + resolveLate({ promotions: [] } as unknown as Cosmetics); + await vi.advanceTimersByTimeAsync(0); + expect((modal as unknown as { cosmetics: unknown }).cosmetics).toBe( + reopened, + ); } finally { vi.useRealTimers(); } From e762e51e933dd6f210440861ac5f7bd11a236474 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 30 Oct 2026 15:04:13 +0000 Subject: [PATCH 06/13] fix(store): refetch on reopen when the kept catalog has an ended sale Closing the store stops the sale-end retries. Reopened inside the one-minute stale window, it kept a catalog that still carried an ended sale, so its items showed the sale prices with no banner and nothing scheduled to fix them. The store now starts the sale-end refetch on open whenever the catalog it shows still lists a sale whose end time has passed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019Wbkiw3pQDRGxxLWZXKXUL --- src/client/Store.ts | 18 +++++++++++++----- tests/client/StoreModal.test.ts | 28 ++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 5 deletions(-) diff --git a/src/client/Store.ts b/src/client/Store.ts index aceb2a5f5e1..c24b072c950 100644 --- a/src/client/Store.ts +++ b/src/client/Store.ts @@ -89,6 +89,14 @@ interface StoreBrowserOptions { const SALE_END_RETRY_MS = 15_000; const SALE_END_RETRIES = 8; +/** Whether the catalog still lists a sale whose end time has passed. */ +function hasEndedSale(cosmetics: Cosmetics | null): boolean { + const now = Date.now(); + return (cosmetics?.promotions ?? []).some( + (sale) => new Date(sale.endsAt).getTime() <= now, + ); +} + @customElement("store-modal") export class StoreModal extends BaseModal { protected routerName = "store"; @@ -750,11 +758,7 @@ export class StoreModal extends BaseModal { this.cosmetics = fresh ?? this.cosmetics; this.selectVisible(this.groupsForTab(this.activeTab)); this.requestUpdate(); - const now = Date.now(); - const stillHasEnded = (fresh?.promotions ?? []).some( - (sale) => new Date(sale.endsAt).getTime() <= now, - ); - if ((fresh === null || stillHasEnded) && attempt < SALE_END_RETRIES) { + if ((fresh === null || hasEndedSale(fresh)) && attempt < SALE_END_RETRIES) { if (this.saleRetryTimer !== null) clearTimeout(this.saleRetryTimer); this.saleRetryTimer = setTimeout(() => { this.saleRetryTimer = null; @@ -838,6 +842,10 @@ export class StoreModal extends BaseModal { this.cosmetics ??= await fetchCosmetics(); this.selectVisible(this.groupsForTab(this.activeTab)); await this.refresh(); + // A catalog still carrying a sale that has ended (the store was closed + // while the sale-end refetch was retrying, then reopened within the + // stale window) would show its prices with no banner: refetch it. + if (hasEndedSale(this.cosmetics)) void this.refetchAfterSaleEnd(0); } protected onClose(): void { diff --git a/tests/client/StoreModal.test.ts b/tests/client/StoreModal.test.ts index 30f435cf3aa..37952cbbdc2 100644 --- a/tests/client/StoreModal.test.ts +++ b/tests/client/StoreModal.test.ts @@ -554,6 +554,34 @@ describe("StoreModal cosmetic browser", () => { } }); + it("refetches on reopen when the kept catalog still has an ended sale", async () => { + const ended = { + promotions: [ + { + id: "1", + name: "Flash", + percentOff: 10, + endsAt: new Date(Date.now() - 1000).toISOString(), + }, + ], + } as unknown as Cosmetics; + vi.mocked(fetchCosmetics).mockResolvedValue(ended); + const modal = await openStoreOnCosmetic("patterns"); + modal.close(); + + const after = { promotions: [] } as unknown as Cosmetics; + vi.mocked(fetchCosmetics).mockClear(); + vi.mocked(fetchCosmetics).mockResolvedValue(after); + modal.open({ tab: "cosmetics" }); + + await vi.waitFor(() => + expect((modal as unknown as { cosmetics: unknown }).cosmetics).toBe( + after, + ), + ); + expect(fetchCosmetics).toHaveBeenCalled(); + }); + it("shows no banner or list price without a sale", async () => { const modal = await openStoreOnCosmetic("patterns"); expect(modal.querySelector("[data-store-sale-banner]")).toBeNull(); From f3889b033c65e2fa72e672426e808de577e7b36c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 30 Oct 2026 15:17:00 +0000 Subject: [PATCH 07/13] fix(store): show an item's list price once its own sale has ended The buy buttons trusted whatever catalog the store held, so a catalog that still carried an ended sale (a fetch landing after the sale-end refetch, or the API still serving it when the retries ran out) kept the sale price on them. Each item carries its sale's endsAt: once it has passed, the button shows the item's list price with no discount tag, which is what the server charges after the sale ends. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019Wbkiw3pQDRGxxLWZXKXUL --- src/client/Store.ts | 23 +++++++++++++++++++---- tests/client/StoreModal.test.ts | 26 ++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 4 deletions(-) diff --git a/src/client/Store.ts b/src/client/Store.ts index c24b072c950..846f44be97b 100644 --- a/src/client/Store.ts +++ b/src/client/Store.ts @@ -466,6 +466,7 @@ export class StoreModal extends BaseModal { priceSoft?: number; listPriceHard?: number; listPriceSoft?: number; + promotion?: { endsAt: string }; rarity?: string; } | null; const isPurchasable = resolved.relationship === "purchasable"; @@ -483,8 +484,22 @@ export class StoreModal extends BaseModal { isPurchasable && resolved.type === "subscription" && product === null ? formatUsdCents((resolved.cosmetic as Subscription).priceMonthly) : ""; - const priceHard = isPurchasable ? priced?.priceHard : undefined; - const priceSoft = isPurchasable ? priced?.priceSoft : undefined; + // Once the item's own sale has ended, show its list price (what the + // server charges now) even if the catalog in hand predates the end: a + // refetch that lands late, or never, can't leave a sale price showing. + const saleEnded = + priced?.promotion !== undefined && + new Date(priced.promotion.endsAt).getTime() <= Date.now(); + const priceHard = isPurchasable + ? saleEnded + ? (priced?.listPriceHard ?? priced?.priceHard) + : priced?.priceHard + : undefined; + const priceSoft = isPurchasable + ? saleEnded + ? (priced?.listPriceSoft ?? priced?.priceSoft) + : priced?.priceSoft + : undefined; const purchase = (method: "dollar" | "hard" | "soft") => purchaseCosmetic(resolved, method); // Currency packs check out inline (wallet button / in-page card form) @@ -514,8 +529,8 @@ export class StoreModal extends BaseModal { .inlineCheckout=${inlineCheckout} .priceHard=${priceHard ?? null} .priceSoft=${priceSoft ?? null} - .listPriceHard=${priceHard !== undefined ? (priced?.listPriceHard ?? null) : null} - .listPriceSoft=${priceSoft !== undefined ? (priced?.listPriceSoft ?? null) : null} + .listPriceHard=${priceHard !== undefined && !saleEnded ? (priced?.listPriceHard ?? null) : null} + .listPriceSoft=${priceSoft !== undefined && !saleEnded ? (priced?.listPriceSoft ?? null) : null} .rarity=${priced?.rarity ?? "common"} .itemName=${cosmeticSelectionLabel(resolved)} .dollarLabelKey=${ diff --git a/tests/client/StoreModal.test.ts b/tests/client/StoreModal.test.ts index 37952cbbdc2..0922e099457 100644 --- a/tests/client/StoreModal.test.ts +++ b/tests/client/StoreModal.test.ts @@ -582,6 +582,32 @@ describe("StoreModal cosmetic browser", () => { expect(fetchCosmetics).toHaveBeenCalled(); }); + it("shows the list price once an item's sale has ended, whatever the catalog says", async () => { + resolvedCatalog = [ + { + ...red, + cosmetic: { + ...pattern, + priceHard: 90, + listPriceHard: 120, + promotion: { + id: "1", + name: "Flash", + percentOff: 25, + endsAt: new Date(Date.now() - 1000).toISOString(), + }, + } as never, + }, + ]; + const modal = await openStoreOnCosmetic("patterns"); + const button = modal.querySelector("purchase-button")!; + await button.updateComplete; + + expect(button.priceHard).toBe(120); + expect(button.listPriceHard).toBeNull(); + expect(button.querySelector("[data-sale-tag]")).toBeNull(); + }); + it("shows no banner or list price without a sale", async () => { const modal = await openStoreOnCosmetic("patterns"); expect(modal.querySelector("[data-store-sale-banner]")).toBeNull(); From ee090db5b06e904796f28f0bcaad1bcab4d7cb53 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 30 Oct 2026 15:34:21 +0000 Subject: [PATCH 08/13] fix(store): price the balance check the way the buy button shows it Once an item's sale had ended, the button showed its list price but the purchase path's balance pre-check and insufficient-funds shortfall still read the catalog's sale price. Both now read currentPrice() (Cosmetics.ts), the one rule for "price as the server charges it now": the catalog price while the item's own sale runs, its list price once that sale's endsAt has passed. The store's buttons use the same helper. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019Wbkiw3pQDRGxxLWZXKXUL --- src/client/Cosmetics.ts | 43 ++++++++++++++++--- src/client/Store.ts | 25 ++++-------- tests/client/CosmeticPackPurchase.test.ts | 50 +++++++++++++++++++++++ 3 files changed, 97 insertions(+), 21 deletions(-) diff --git a/src/client/Cosmetics.ts b/src/client/Cosmetics.ts index 7fd2fe3fe76..d6728314625 100644 --- a/src/client/Cosmetics.ts +++ b/src/client/Cosmetics.ts @@ -579,8 +579,7 @@ export async function purchaseCosmetic( // ResolvedCosmetic isn't a discriminated union, so the guard above doesn't // narrow cosmetic's type. Subscriptions are excluded by the runtime check. const priced = c as Pattern | Flag | Pack; - const price = - method === "hard" ? (priced.priceHard ?? 0) : (priced.priceSoft ?? 0); + const price = currentPrice(priced, method) ?? 0; const userMe = await getUserMe(); if (userMe === false) { await showInGameAlert(translateText("store.login_required")); @@ -728,6 +727,7 @@ async function purchasePack( console.error("purchaseCosmetic: packs are only sold for hard currency"); return; } + const price = currentPrice(pack, "hard") ?? pack.priceHard; const userMe = await getUserMe(); if (userMe === false) { await showInGameAlert(translateText("store.login_required")); @@ -735,7 +735,7 @@ async function purchasePack( } const insufficient = (balance: number): InsufficientCurrency => ({ currency: translateText("cosmetics.hard"), - shortfall: pack.priceHard - balance, + shortfall: price - balance, item: pack.displayName, canTopUp: true, }); @@ -747,7 +747,7 @@ async function purchasePack( await showInGameAlert(debtMessage(-balance)); return; } - if (balance < pack.priceHard) { + if (balance < price) { return insufficient(balance); } @@ -771,7 +771,7 @@ async function purchasePack( return; } const available = fresh.player.currency?.hard ?? 0; - const outcome = balanceOutcome(available, pack.priceHard); + const outcome = balanceOutcome(available, price); if (outcome === "debt") { await showInGameAlert(debtMessage(-available)); return; @@ -849,6 +849,39 @@ function simpleHash(str: string): string { * available" / "Tier not available"): the catalog the store rendered from no * longer matches what the rail sells. */ +/** + * An item's price in one currency as the store shows and the server charges + * it now. While the item's own sale runs that is the catalog price (the sale + * price); once the sale's endsAt has passed it is the list price, even if the + * catalog in hand predates the end. The store's buttons and the purchase + * balance check both read this, so they never disagree. + */ +export function currentPrice( + item: { + priceHard?: number; + priceSoft?: number; + listPriceHard?: number; + listPriceSoft?: number; + promotion?: { endsAt: string }; + }, + currency: "hard" | "soft", +): number | undefined { + const price = currency === "hard" ? item.priceHard : item.priceSoft; + const listPrice = + currency === "hard" ? item.listPriceHard : item.listPriceSoft; + return saleHasEnded(item) ? (listPrice ?? price) : price; +} + +/** Whether the item's own sale has ended (its endsAt has passed). */ +export function saleHasEnded(item: { + promotion?: { endsAt: string }; +}): boolean { + return ( + item.promotion !== undefined && + new Date(item.promotion.endsAt).getTime() <= Date.now() + ); +} + export function invalidateCosmetics(): void { __cosmetics = null; } diff --git a/src/client/Store.ts b/src/client/Store.ts index 846f44be97b..4034fdb0f2e 100644 --- a/src/client/Store.ts +++ b/src/client/Store.ts @@ -27,6 +27,7 @@ import { alignPurchaseRows } from "./components/PurchaseButton"; import "./components/TribesPanel"; import { modalHeader } from "./components/ui/ModalHeader"; import { + currentPrice, fetchCosmetics, invalidateCosmetics, refreshStaleCosmetics, @@ -35,6 +36,7 @@ import { ownedPackItems, purchaseCosmetic, resolveCosmetics, + saleHasEnded, ResolvedCosmetic, } from "./Cosmetics"; import { matchesStoreItem } from "./EquippedCosmetics"; @@ -484,22 +486,13 @@ export class StoreModal extends BaseModal { isPurchasable && resolved.type === "subscription" && product === null ? formatUsdCents((resolved.cosmetic as Subscription).priceMonthly) : ""; - // Once the item's own sale has ended, show its list price (what the - // server charges now) even if the catalog in hand predates the end: a - // refetch that lands late, or never, can't leave a sale price showing. - const saleEnded = - priced?.promotion !== undefined && - new Date(priced.promotion.endsAt).getTime() <= Date.now(); - const priceHard = isPurchasable - ? saleEnded - ? (priced?.listPriceHard ?? priced?.priceHard) - : priced?.priceHard - : undefined; - const priceSoft = isPurchasable - ? saleEnded - ? (priced?.listPriceSoft ?? priced?.priceSoft) - : priced?.priceSoft - : undefined; + // The price as the server charges it now: once the item's own sale has + // ended that is its list price, whatever the catalog in hand says. + const saleEnded = priced !== null && saleHasEnded(priced); + const priceHard = + isPurchasable && priced ? currentPrice(priced, "hard") : undefined; + const priceSoft = + isPurchasable && priced ? currentPrice(priced, "soft") : undefined; const purchase = (method: "dollar" | "hard" | "soft") => purchaseCosmetic(resolved, method); // Currency packs check out inline (wallet button / in-page card form) diff --git a/tests/client/CosmeticPackPurchase.test.ts b/tests/client/CosmeticPackPurchase.test.ts index 43c384d376e..7ae0107a501 100644 --- a/tests/client/CosmeticPackPurchase.test.ts +++ b/tests/client/CosmeticPackPurchase.test.ts @@ -122,6 +122,56 @@ describe("purchaseCosmetic for a cosmetic pack", () => { expect(purchaseCosmeticPack).not.toHaveBeenCalled(); }); + it("quotes the shortfall at the list price once the pack's sale has ended", async () => { + vi.mocked(getUserMe).mockResolvedValue(userWithHard(200)); + const endedSale: ResolvedCosmetic = { + ...starter, + cosmetic: { + ...(starter.cosmetic as object), + priceHard: 150, + listPriceHard: 250, + promotion: { + id: "1", + name: "Flash", + percentOff: 40, + endsAt: new Date(Date.now() - 1000).toISOString(), + }, + } as never, + }; + + const result = await purchaseCosmetic(endedSale, "hard"); + + expect(result).toEqual({ + currency: "plutonium", + shortfall: 50, + item: "Starter Pack", + canTopUp: true, + }); + expect(purchaseCosmeticPack).not.toHaveBeenCalled(); + }); + + it("uses the sale price while the pack's sale runs", async () => { + vi.mocked(getUserMe).mockResolvedValue(userWithHard(100)); + const runningSale: ResolvedCosmetic = { + ...starter, + cosmetic: { + ...(starter.cosmetic as object), + priceHard: 150, + listPriceHard: 250, + promotion: { + id: "1", + name: "Flash", + percentOff: 40, + endsAt: new Date(Date.now() + 60_000).toISOString(), + }, + } as never, + }; + + const result = await purchaseCosmetic(runningSale, "hard"); + + expect(result).toMatchObject({ shortfall: 50 }); + }); + it("re-reads the balance when the server rejects for insufficient funds", async () => { vi.mocked(getUserMe) .mockResolvedValueOnce(userWithHard(300)) From 019bf23062ddcdaf8d8f9f8802b320227c4704dd Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 30 Oct 2026 15:37:57 +0000 Subject: [PATCH 09/13] docs(store): keep invalidateCosmetics' doc comment on invalidateCosmetics The currentPrice/saleHasEnded helpers had been inserted between invalidateCosmetics and its JSDoc; move them above it. No code change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019Wbkiw3pQDRGxxLWZXKXUL --- src/client/Cosmetics.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/client/Cosmetics.ts b/src/client/Cosmetics.ts index d6728314625..b9a95b7ad15 100644 --- a/src/client/Cosmetics.ts +++ b/src/client/Cosmetics.ts @@ -843,12 +843,6 @@ function simpleHash(str: string): string { return hash.toString(36); } -/** - * Drops the cached cosmetics.json so the next fetchCosmetics() goes to the - * network. The remedy for a checkout rejected with a stale listing ("Pack not - * available" / "Tier not available"): the catalog the store rendered from no - * longer matches what the rail sells. - */ /** * An item's price in one currency as the store shows and the server charges * it now. While the item's own sale runs that is the catalog price (the sale @@ -882,6 +876,12 @@ export function saleHasEnded(item: { ); } +/** + * Drops the cached cosmetics.json so the next fetchCosmetics() goes to the + * network. The remedy for a checkout rejected with a stale listing ("Pack not + * available" / "Tier not available"): the catalog the store rendered from no + * longer matches what the rail sells. + */ export function invalidateCosmetics(): void { __cosmetics = null; } From 24915a9ed0392ffee8c8c22c025666b03327114a Mon Sep 17 00:00:00 2001 From: iamlewis Date: Fri, 30 Oct 2026 18:47:01 +0000 Subject: [PATCH 10/13] feat(store): restyle the sale UI and add flash sales - Sale banner in the brand palette (Deep Navy to Malibu Blue, Aquarius badge), with a live countdown; a flash sale rides along it as a slim row that opens the On sale tab. - A sale's discount as a band across the artwork's top-right corner; the "?" info button moves to the top-left to give it the corner. - Buy buttons centre the sale price, with the list price struck through beneath it; screen readers hear "now"/"was". - Discounted items sort first, and an On sale sub-tab lists them while a sale runs. - Flash sales (promotion kind "flash"): the item glows in the theme accent with a light running round its edge, and counts down at the foot of its artwork; the On sale tab leads with it. - Countdowns tick in their own element instead of re-rendering the store. Co-Authored-By: Claude Opus 5.5 --- packages/shared/src/CosmeticSchemas.ts | 5 + resources/lang/en.json | 16 +- src/client/Cosmetics.ts | 24 ++ src/client/Store.ts | 353 +++++++++++++++++++++--- src/client/components/CosmeticCard.ts | 112 +++++++- src/client/components/CosmeticInfo.ts | 11 +- src/client/components/PurchaseButton.ts | 86 ++++-- src/client/components/SaleCountdown.ts | 91 ++++++ tests/client/CosmeticCard.test.ts | 3 + tests/client/PurchaseButton.test.ts | 21 +- tests/client/StoreModal.test.ts | 214 ++++++++++++-- 11 files changed, 844 insertions(+), 92 deletions(-) create mode 100644 src/client/components/SaleCountdown.ts diff --git a/packages/shared/src/CosmeticSchemas.ts b/packages/shared/src/CosmeticSchemas.ts index 8e833279826..8d6b0d8b3ff 100644 --- a/packages/shared/src/CosmeticSchemas.ts +++ b/packages/shared/src/CosmeticSchemas.ts @@ -96,7 +96,12 @@ export const PromotionSchema = z.object({ id: z.string(), name: z.string(), percentOff: z.number(), + // For a flash sale, when the current item's discount ends and the next + // item's starts. endsAt: z.string(), + // A flash sale discounts one item at a time, the same for every player, + // a new one every slot. Absent on a store-wide or scoped sale. + kind: z.literal("flash").optional(), }); export type Promotion = z.infer; diff --git a/resources/lang/en.json b/resources/lang/en.json index ddf70429cc9..3c12afe3d29 100644 --- a/resources/lang/en.json +++ b/resources/lang/en.json @@ -2401,6 +2401,13 @@ "custom_currency_purchase_success": "Plutonium purchase successful!", "effects": "Effects", "flags": "Flags", + "flash_left": "left", + "flash_next_in": "Next item in", + "flash_sale": "Flash sale", + "flash_sale_banner": "{percent}% off one item. A new one when the timer runs out.", + "flash_sale_hero_body": "Only this item, only until the timer runs out. Then the deal moves to a different item.", + "flash_sale_hero_title": "{name}: {percent}% off", + "flash_sale_row": "{percent}% off one item", "insufficient_currency_body": "You need {amount, number} more {currency} to buy {item}.", "insufficient_currency_title": "Insufficient {currency}", "login_required": "You must be logged in to purchase with currency.", @@ -2414,6 +2421,7 @@ "no_skins": "No skins available. Check back later for new items.", "no_subscriptions": "No subscriptions available. Check back later for new items.", "no_tribes": "You haven't bought any tribe names yet.", + "on_sale": "On sale", "pack_already_owned": "You already own {items}. Nothing was charged.", "pack_debt": "Your Plutonium balance is {debt} in debt. Settle it before buying.", "pack_no_items": "None of this bundle's items are available right now.", @@ -2438,8 +2446,14 @@ "purchase_pending": "Your purchase is still being processed. It will appear in your account shortly — check your order history if it doesn't.", "purchase_success": "Purchase succeeded: {name}", "purchase_tribe_button": "Purchase", - "sale_banner": "{name}: {percent}% off. Ends {ends}.", + "sale_ends_in_days": "Ends in {days}d {hours}h", + "sale_ends_in_hours": "Ends in {hours}h {minutes}m", + "sale_ends_in_minutes": "Ends in {minutes}m", + "sale_now": "Now", "sale_percent_off": "-{percent}%", + "sale_selected_items": "{percent}% off selected items", + "sale_store_wide": "{percent}% off everything in the store", + "sale_was": "Was", "steam_browser_approval": "Steam has opened the purchase in your browser. Approve it there, then come back here. It will show up once Steam confirms it.", "steam_licence_required": "This subscription is only for players who own OpenFront on Steam.", "steam_overlay_cancelled": "Purchase cancelled. You haven't been charged.", diff --git a/src/client/Cosmetics.ts b/src/client/Cosmetics.ts index b9a95b7ad15..ef591b61c22 100644 --- a/src/client/Cosmetics.ts +++ b/src/client/Cosmetics.ts @@ -886,6 +886,30 @@ export function invalidateCosmetics(): void { __cosmetics = null; } +/** + * The running sale that discounts a catalog item, or null: it names a + * promotion that hasn't ended, and a list price above its price in at least + * one currency. + */ +export function activeSale( + cosmetic: unknown, + now: number = Date.now(), +): { percentOff: number; endsAt: string; kind?: "flash" } | null { + const priced = cosmetic as { + promotion?: { percentOff: number; endsAt: string; kind?: "flash" }; + priceHard?: number; + priceSoft?: number; + listPriceHard?: number; + listPriceSoft?: number; + } | null; + const promotion = priced?.promotion; + if (!promotion || new Date(promotion.endsAt).getTime() <= now) return null; + const discounted = + (priced.listPriceHard ?? 0) > (priced.priceHard ?? Infinity) || + (priced.listPriceSoft ?? 0) > (priced.priceSoft ?? Infinity); + return discounted ? promotion : null; +} + /** * Drops a catalog fetched more than COSMETICS_STALE_MS ago, so the next * fetchCosmetics() refetches it. Sale prices start and end on the server's diff --git a/src/client/Store.ts b/src/client/Store.ts index 4034fdb0f2e..5b6298769f8 100644 --- a/src/client/Store.ts +++ b/src/client/Store.ts @@ -6,10 +6,11 @@ import { CosmeticPack, Cosmetics, Product, + Promotion, Subscription, } from "@openfront/shared/CosmeticSchemas"; import type { PropertyValues, TemplateResult } from "lit"; -import { html } from "lit"; +import { html, nothing } from "lit"; import { customElement, state } from "lit/decorators.js"; import { BaseModal } from "./components/BaseModal"; import "./components/CosmeticCard"; @@ -22,11 +23,13 @@ import "./components/EffectsGrid"; import type { InlineCheckout } from "./components/InlineCheckout"; import "./components/NotLoggedInWarning"; import "./components/PackContentsDialog"; +import "./components/SaleCountdown"; import { ProgressiveList } from "./components/ProgressiveList"; import { alignPurchaseRows } from "./components/PurchaseButton"; import "./components/TribesPanel"; import { modalHeader } from "./components/ui/ModalHeader"; import { + activeSale, currentPrice, fetchCosmetics, invalidateCosmetics, @@ -66,7 +69,9 @@ type StoreTab = | "subscriptions" | "tribes"; -const COSMETICS_SUB_TABS = ["patterns", "flags", "crowns"] as const; +// "sale" lists every discounted skin, flag and crown; its tab shows only +// while a sale covers one of them. +const COSMETICS_SUB_TABS = ["sale", "patterns", "flags", "crowns"] as const; type CosmeticsSubTab = (typeof COSMETICS_SUB_TABS)[number]; /** Sub-tab holding the catalog item a store deep link points at. */ @@ -99,6 +104,63 @@ function hasEndedSale(cosmetics: Cosmetics | null): boolean { ); } +/** The running flash sale's item group, if one is among `groups`. */ +function flashGroup( + groups: readonly T[], +): T | undefined { + return groups.find((group) => + group.some((resolved) => activeSale(resolved.cosmetic)?.kind === "flash"), + ); +} + +/** Whether a running sale discounts any variant in a card's group. */ +function groupOnSale(group: readonly ResolvedCosmetic[]): boolean { + return group.some((resolved) => activeSale(resolved.cosmetic) !== null); +} + +/** The flash item, then the rest on sale, then everything else. */ +export function saleFirst( + groups: readonly T[], +): T[] { + const flash = flashGroup(groups); + const rest = groups.filter((group) => group !== flash); + return [ + ...(flash ? [flash] : []), + ...rest.filter(groupOnSale), + ...rest.filter((group) => !groupOnSale(group)), + ]; +} + +/** + * Whether a sale covers every priced item in the catalog, so the banner can + * say "store-wide" rather than "selected items". + */ +export function saleCoversEverything( + cosmetics: Cosmetics | null, + promotionId: string, +): boolean { + if (cosmetics === null) return false; + const items: { priceHard?: number; promotion?: { id: string } }[] = [ + ...Object.values(cosmetics.patterns), + ...Object.values(cosmetics.flags), + ...Object.values(cosmetics.crowns ?? {}), + ...Object.values(cosmetics.skins ?? {}), + ...Object.values(cosmetics.packs ?? {}), + ...Object.values(cosmetics.effects ?? {}).flatMap((byName) => + Object.values(byName ?? {}), + ), + ]; + const priced = items.filter( + (item) => + item.priceHard !== undefined || + (item as { priceSoft?: number }).priceSoft !== undefined, + ); + return ( + priced.length > 0 && + priced.every((item) => item.promotion?.id === promotionId) + ); +} + @customElement("store-modal") export class StoreModal extends BaseModal { protected routerName = "store"; @@ -245,21 +307,23 @@ export class StoreModal extends BaseModal { tab: CosmeticsSubTab, ): readonly (readonly ResolvedCosmetic[])[] { const items = this.resolvedPurchasables(); - if (tab === "flags") { - return items - .filter((resolved) => resolved.type === "flag") - .map((r) => [r]); - } - if (tab === "crowns") { - return items - .filter((resolved) => resolved.type === "crown") - .map((r) => [r]); - } - return groupCosmeticVariants( + const skins = groupCosmeticVariants( items.filter( (resolved) => resolved.type === "pattern" || resolved.type === "skin", ), ); + const flags = items + .filter((resolved) => resolved.type === "flag") + .map((r) => [r]); + const crowns = items + .filter((resolved) => resolved.type === "crown") + .map((r) => [r]); + if (tab === "sale") { + return saleFirst([...skins, ...flags, ...crowns].filter(groupOnSale)); + } + return saleFirst( + tab === "flags" ? flags : tab === "crowns" ? crowns : skins, + ); } private groupsForTab(tab: string): readonly (readonly ResolvedCosmetic[])[] { @@ -276,6 +340,13 @@ export class StoreModal extends BaseModal { ); } if (tab === "cosmetics") { + // The sale ended (or the catalog dropped it) while its tab was open. + if ( + this.cosmeticsSubTab === "sale" && + this.cosmeticsGroups("sale").length === 0 + ) { + this.cosmeticsSubTab = "patterns"; + } return this.cosmeticsGroups(this.cosmeticsSubTab); } if (tab === "effects") { @@ -369,6 +440,12 @@ export class StoreModal extends BaseModal { this.requestUpdate(); } + /** The sub-tabs to show: "On sale" only while something is discounted. */ + private visibleCosmeticsSubTabs(): CosmeticsSubTab[] { + const hasSale = this.cosmeticsGroups("sale").length > 0; + return COSMETICS_SUB_TABS.filter((tab) => tab !== "sale" || hasSale); + } + private setCosmeticsSubTab(tab: CosmeticsSubTab): void { this.cosmeticsSubTab = tab; this.selectVisible(this.cosmeticsGroups(tab)); @@ -592,6 +669,11 @@ export class StoreModal extends BaseModal { // Skins / Flags / Crowns grouped under one top-level tab; a sub-tab bar // (styled like effects-grid's) picks which grid shows. private renderCosmeticsPanel(): TemplateResult { + const subTabs = this.visibleCosmeticsSubTabs(); + const flash = + this.cosmeticsSubTab === "sale" + ? flashGroup(this.visibleGroups) + : undefined; const emptyKey = this.cosmeticsSubTab === "flags" ? "store.no_flags" @@ -600,28 +682,91 @@ export class StoreModal extends BaseModal { : "store.no_skins"; return html`
- ${COSMETICS_SUB_TABS.map((tab) => { + ${subTabs.map((tab) => { const active = this.cosmeticsSubTab === tab; return html``; })}
- ${this.renderBrowser(this.visibleGroups, { - emptyTranslationKey: emptyKey, - })} + ${ + flash + ? html`${this.renderFlashHero(flash)} + ${this.renderBrowser( + this.visibleGroups.filter((group) => group !== flash), + { emptyTranslationKey: emptyKey }, + )}` + : this.renderBrowser(this.visibleGroups, { + emptyTranslationKey: emptyKey, + }) + } `; } + /** + * The flash sale's item, leading the On sale tab: its card beside what the + * sale is and a clock to the next item. + */ + private renderFlashHero(group: readonly ResolvedCosmetic[]): TemplateResult { + const sale = group + .map((resolved) => activeSale(resolved.cosmetic)) + .find((found) => found !== null); + if (!sale) return html``; + return html`
+
+ ${this.renderCosmeticCards([group])} +
+
+ + ${translateText("store.flash_sale")} + + ${translateText("store.flash_sale_hero_title", { + name: cosmeticSelectionLabel(group[0]), + percent: sale.percentOff, + })} + ${translateText("store.flash_sale_hero_body")} + + ${translateText("store.flash_next_in")} + + +
+
`; + } + private renderEffectGrid(): TemplateResult { // A sub-tab per effectType (Boat Trail / Nuke Trail); each tab opens that // type's grid. Tabs are always present, even when a type has nothing to buy. @@ -711,28 +856,168 @@ export class StoreModal extends BaseModal { ); this.scheduleSaleEnd(sales); if (sales.length === 0) return ""; + // A flash sale rides along the first sale's strip as a slim row, rather + // than a second strip; alone, it takes the strip itself. + const flash = sales.find((sale) => sale.kind === "flash"); + const regular = sales.filter((sale) => sale.kind !== "flash"); + if (regular.length === 0 && flash) { + return html`
+ ${this.renderFlashBannerLine(flash)} +
`; + } return html`
- ${sales.map( - (sale) => - html`
- ${translateText("store.sale_banner", { - name: sale.name, - percent: sale.percentOff, - ends: new Date(sale.endsAt).toLocaleString(undefined, { + ${regular.map((sale, index) => { + const endingSoon = + new Date(sale.endsAt).getTime() - Date.now() < 86_400_000; + return html`
+
+ ${translateText("store.sale_percent_off", { + percent: sale.percentOff, + })} +
+ + + ${sale.name} + + ${translateText( + saleCoversEverything(this.cosmetics, sale.id) + ? "store.sale_store_wide" + : "store.sale_selected_items", + { percent: sale.percentOff }, + )} +
+ `, - )} + })} + > + + +
+ ${index === 0 && flash ? this.renderFlashBannerRow(flash) : nothing} +
`; + })}
`; } + /** + * A flash sale as a slim row under another sale's strip: what it is and a + * clock to the next item. It opens the On sale tab, where that item leads. + */ + private renderFlashBannerRow(sale: Promotion): TemplateResult { + return html``; + } + + /** + * A flash sale's line in the banner: one item at a time, with a clock to + * the next. It opens the On sale tab, where that item leads. + */ + private renderFlashBannerLine(sale: Promotion): TemplateResult { + return html``; + } + + /** Cosmetics → On sale, from the flash sale's banner line. */ + private openSaleTab(): void { + this.cosmeticsSubTab = "sale"; + if (this.activeTab === "cosmetics") { + this.setCosmeticsSubTab("sale"); + } else { + this.setActiveTab("cosmetics"); + } + } + /** * When the soonest running sale ends, refetch the catalog so its items go * back to list price and its banner drops, even if the player never touches diff --git a/src/client/components/CosmeticCard.ts b/src/client/components/CosmeticCard.ts index 89ab9288db6..934a82ffc23 100644 --- a/src/client/components/CosmeticCard.ts +++ b/src/client/components/CosmeticCard.ts @@ -1,7 +1,7 @@ import { Subscription } from "@openfront/shared/CosmeticSchemas"; import { html, LitElement, nothing, TemplateResult } from "lit"; import { customElement, property } from "lit/decorators.js"; -import { ResolvedCosmetic, translateCosmetic } from "../Cosmetics"; +import { activeSale, ResolvedCosmetic, translateCosmetic } from "../Cosmetics"; import { isDesktopShell } from "../DesktopShell"; import { translateText } from "../Utils"; import "./CosmeticInfo"; @@ -12,6 +12,7 @@ import { } from "./CosmeticPresentation"; import "./CosmeticPreview"; import "./CosmeticPreviewBubble"; +import "./SaleCountdown"; const COSMETIC_CARD_STYLE_ID = "cosmetic-card-styles"; if (!document.getElementById(COSMETIC_CARD_STYLE_ID)) { @@ -179,6 +180,56 @@ if (!document.getElementById(COSMETIC_CARD_STYLE_ID)) { /* No prefers-reduced-motion opt-out: these animations are the legendary treatment, and suppressing them left the card with a frozen gold wash and invisible (opacity: 0) sparkles rather than a calmer effect. */ + + /* A flash sale's item: the theme's accent (blue; orange under the + Halloween theme, which overrides --color-aquarius), pulsing all the + time (not only on hover), with a light running round the edge. Listed + after the rarity rules so it wins over a legendary card's hover pulse. */ + @keyframes cosmetic-card-flash-pulse { + 0%, 100% { box-shadow: 0 0 0 2px var(--color-aquarius), 0 0 8px color-mix(in srgb, var(--color-aquarius) 40%, transparent); } + 50% { box-shadow: 0 0 0 2px var(--color-aquarius), 0 0 30px color-mix(in srgb, var(--color-aquarius) 90%, transparent); } + } + @keyframes cosmetic-card-flash-spin { + to { transform: translate(-50%, -50%) rotate(360deg); } + } + cosmetic-card [data-cosmetic-shell][data-cosmetic-flash], + cosmetic-card:hover [data-cosmetic-shell][data-cosmetic-flash] { + border-color: var(--color-aquarius); + animation: cosmetic-card-flash-pulse 1.8s ease-in-out infinite; + } + [data-cosmetic-flash-ring] { + pointer-events: none; + position: absolute; + inset: -4px; + z-index: 8; + border-radius: 15px; + padding: 3px; + overflow: hidden; + -webkit-mask: linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0); + -webkit-mask-composite: xor; + mask-composite: exclude; + } + [data-cosmetic-flash-ring]::after { + content: ""; + position: absolute; + left: 50%; + top: 50%; + width: 250%; + aspect-ratio: 1; + background: conic-gradient(from 0deg, transparent 0 55%, var(--color-aquarius) 72%, #fff 80%, var(--color-aquarius) 88%, transparent 100%); + transform: translate(-50%, -50%); + animation: cosmetic-card-flash-spin 2.6s linear infinite; + } + /* Unlike the legendary hover, a flash item glows all the time, so it + calms to a steady outline rather than pulsing and spinning. */ + @media (prefers-reduced-motion: reduce) { + cosmetic-card [data-cosmetic-shell][data-cosmetic-flash], + cosmetic-card:hover [data-cosmetic-shell][data-cosmetic-flash] { + animation: none; + box-shadow: 0 0 0 2px var(--color-aquarius), 0 0 14px color-mix(in srgb, var(--color-aquarius) 60%, transparent); + } + [data-cosmetic-flash-ring] { display: none; } + } `; document.head.appendChild(style); } @@ -374,12 +425,64 @@ export class CosmeticCard extends LitElement { return perks; } + /** + * The sale's discount as a band across the artwork's top-right corner, + * while one runs; the same for a flash sale's item, which the card's glow + * and timer mark instead. The "?" moved to the top-left to give it the + * corner (CosmeticInfo). + */ + private renderSaleRibbon(active: ResolvedCosmetic) { + if (active.relationship !== "purchasable") return nothing; + const sale = activeSale(active.cosmetic); + if (sale === null) return nothing; + return html` + ${translateText("store.sale_percent_off", { + percent: sale.percentOff, + })} + `; + } + + /** A flash sale's item: the time left, fading up from the artwork's foot. */ + private renderFlashTimer(active: ResolvedCosmetic) { + const sale = this.flashSale(active); + if (sale === null) return nothing; + return html`
+ +
+ ${translateText("store.flash_left")} +
+
`; + } + + /** The running flash sale on this item, if it's one the player can buy. */ + private flashSale(active: ResolvedCosmetic) { + if (active.relationship !== "purchasable") return null; + const sale = activeSale(active.cosmetic); + return sale?.kind === "flash" ? sale : null; + } + render() { const active = this.activeResolved; const rarity = cosmeticRarity(active); const displayName = cosmeticDisplayName(active); const isFocused = this.state === "focused"; const isEquipped = this.state === "equipped"; + const isFlash = this.flashSale(active) !== null; const shellClass = `${this.rarityClass(rarity)} ${ isEquipped ? "ring-2 ring-emerald-400/70 shadow-[0_0_24px_rgba(52,211,153,0.45)]" @@ -410,6 +513,7 @@ export class CosmeticCard extends LitElement { size=${this.previewSize} >
+ ${this.renderSaleRibbon(active)} ${this.renderFlashTimer(active)} ${ isEquipped ? html` + ${ + isFlash + ? html`` + : nothing + } ${ rarity === "epic" || rarity === "legendary" ? html`` diff --git a/src/client/components/CosmeticInfo.ts b/src/client/components/CosmeticInfo.ts index d133bbed8b0..475049c09ca 100644 --- a/src/client/components/CosmeticInfo.ts +++ b/src/client/components/CosmeticInfo.ts @@ -46,13 +46,14 @@ export class CosmeticInfo extends LitElement { const aiLabelKey = cosmeticAiLabelKey(this.aiDisclosed, this.artist); const rarityColor = rarityColors[this.rarity ?? ""] ?? "text-white/70"; - // The strip spans the card so the bubble (right-aligned under the "?") + // The strip spans the card so the bubble (left-aligned under the "?") // can be capped at the card's width and wrap. Sized to its longest line, - // it used to run past the modal's left edge on first-column cards and - // get clipped. Only the button takes pointer events. + // it used to run past the modal's edge and get clipped. Only the button + // takes pointer events. The "?" sits top-left: a sale's band takes the + // artwork's top-right corner (CosmeticCard renderSaleRibbon). return html`
event.stopPropagation()} > `; } private renderSoftButton() { + const softOnSale = isOnSale(this.priceSoft!, this.listPriceSoft); return html` `; } diff --git a/src/client/components/SaleCountdown.ts b/src/client/components/SaleCountdown.ts new file mode 100644 index 00000000000..0aec29ea664 --- /dev/null +++ b/src/client/components/SaleCountdown.ts @@ -0,0 +1,91 @@ +import { html, LitElement } from "lit"; +import { customElement, property } from "lit/decorators.js"; +import { translateText } from "../Utils"; + +/** "Ends in 2d 5h", "Ends in 3h 12m" or "Ends in 8m" until a sale ends. */ +export function saleEndsIn(endsAt: string, now: number = Date.now()): string { + const totalMinutes = Math.max( + Math.ceil((new Date(endsAt).getTime() - now) / 60_000), + 1, + ); + const hours = Math.floor(totalMinutes / 60); + if (hours >= 24) { + return translateText("store.sale_ends_in_days", { + days: Math.floor(hours / 24), + hours: hours % 24, + }); + } + if (hours > 0) { + return translateText("store.sale_ends_in_hours", { + hours, + minutes: totalMinutes % 60, + }); + } + return translateText("store.sale_ends_in_minutes", { + minutes: totalMinutes, + }); +} + +/** "1:23:45" (or "23:45" under an hour) until `endsAt`; "0:00" once past. */ +export function clockUntil(endsAt: string, now: number = Date.now()): string { + const total = Math.max( + Math.ceil((new Date(endsAt).getTime() - now) / 1000), + 0, + ); + const hours = Math.floor(total / 3600); + const minutes = Math.floor((total % 3600) / 60); + const seconds = String(total % 60).padStart(2, "0"); + return hours > 0 + ? `${hours}:${String(minutes).padStart(2, "0")}:${seconds}` + : `${minutes}:${seconds}`; +} + +/** + * Time left on a sale, ticking on its own so the store around it doesn't + * re-render: "Ends in 2d 5h" every half minute, or a "1:23:45" clock every + * second for a flash sale's short slots. + */ +@customElement("sale-countdown") +export class SaleCountdown extends LitElement { + @property({ type: String }) + endsAt = ""; + + @property({ type: String }) + format: "ends-in" | "clock" = "ends-in"; + + private timer: ReturnType | null = null; + + createRenderRoot() { + return this; + } + + connectedCallback() { + super.connectedCallback(); + this.restartTimer(); + } + + disconnectedCallback() { + super.disconnectedCallback(); + if (this.timer !== null) clearInterval(this.timer); + this.timer = null; + } + + protected updated(changed: Map) { + if (changed.has("format")) this.restartTimer(); + } + + private restartTimer() { + if (this.timer !== null) clearInterval(this.timer); + this.timer = setInterval( + () => this.requestUpdate(), + this.format === "clock" ? 1000 : 30_000, + ); + } + + render() { + if (!this.endsAt) return html``; + return this.format === "clock" + ? clockUntil(this.endsAt) + : saleEndsIn(this.endsAt); + } +} diff --git a/tests/client/CosmeticCard.test.ts b/tests/client/CosmeticCard.test.ts index 10022c05bdc..f5eac555c94 100644 --- a/tests/client/CosmeticCard.test.ts +++ b/tests/client/CosmeticCard.test.ts @@ -222,6 +222,9 @@ describe("CosmeticCard", () => { // longest line, so on a first-column card it ran past the modal's left // edge and was clipped. Its strip spans the card and caps it there. expect(info.className).toContain("inset-x-2"); + // Top-left, leaving the artwork's top-right corner to a sale's band. + expect(info.className).toContain("justify-start"); + expect(bubble.className).toContain("left-0"); expect(bubble.className).toContain("max-w-full"); expect(bubble.className).not.toContain("whitespace-nowrap"); // The strip must not swallow clicks meant for the artwork beneath it. diff --git a/tests/client/PurchaseButton.test.ts b/tests/client/PurchaseButton.test.ts index 40544b8558f..1b2604f34d5 100644 --- a/tests/client/PurchaseButton.test.ts +++ b/tests/client/PurchaseButton.test.ts @@ -7,14 +7,7 @@ vi.mock("../../src/client/InGameModal", () => ({ showInGameConfirm: vi.fn().mockResolvedValue(true), })); -vi.mock("../../src/client/Utils", async (importOriginal) => { - const actual = - await importOriginal(); - return { ...actual, translateText: vi.fn(actual.translateText) }; -}); - const { showInGameAlert } = await import("../../src/client/InGameModal"); -const { translateText } = await import("../../src/client/Utils"); describe("PurchaseButton", () => { let button: PurchaseButton | undefined; @@ -88,8 +81,7 @@ describe("PurchaseButton", () => { } }); - it("strikes through the list price and shows the discount during a sale", async () => { - vi.mocked(translateText).mockClear(); + it("strikes through the list price during a sale", async () => { button = document.createElement("purchase-button") as PurchaseButton; button.priceHard = 75; button.listPriceHard = 100; @@ -101,13 +93,12 @@ describe("PurchaseButton", () => { await button.updateComplete; const hard = button.querySelector(".purchase-sparkle-btn-hard")!; - expect(hard.querySelector("s")?.textContent?.trim()).toBe("100"); - expect(hard.querySelector("[data-sale-tag]")?.textContent).toContain( - "store.sale_percent_off", + // The struck price, after its screen-reader "was" label. + const struck = hard.querySelector("s[data-sale-tag]")!; + expect(struck.querySelector(".sr-only")?.textContent).toContain( + "store.sale_was", ); - expect(translateText).toHaveBeenCalledWith("store.sale_percent_off", { - percent: 25, - }); + expect(struck.lastChild?.textContent?.trim()).toBe("100"); // A list price not above the price is no sale. const soft = button.querySelector(".purchase-sparkle-btn-soft")!; expect(soft.querySelector("[data-sale-tag]")).toBeNull(); diff --git a/tests/client/StoreModal.test.ts b/tests/client/StoreModal.test.ts index 0922e099457..9aef47a93fe 100644 --- a/tests/client/StoreModal.test.ts +++ b/tests/client/StoreModal.test.ts @@ -2,9 +2,12 @@ import type { Cosmetics, Effect } from "@openfront/shared/CosmeticSchemas"; import { nothing, type LitElement } from "lit"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { CosmeticCard } from "../../src/client/components/CosmeticCard"; -import "../../src/client/Store"; import type { EffectsGrid } from "../../src/client/components/EffectsGrid"; import type { PurchaseButton } from "../../src/client/components/PurchaseButton"; +import { + clockUntil, + saleEndsIn, +} from "../../src/client/components/SaleCountdown"; import { fetchCosmetics, purchaseCosmetic, @@ -12,7 +15,7 @@ import { resolveCosmetics, type ResolvedCosmetic, } from "../../src/client/Cosmetics"; -import type { StoreModal } from "../../src/client/Store"; +import { saleCoversEverything, type StoreModal } from "../../src/client/Store"; import { EFFECTS_KEY, PATTERN_KEY, @@ -359,6 +362,8 @@ describe("StoreModal cosmetic browser", () => { it("shows a running sale: banner, struck list price and discount", async () => { const endsAt = new Date(Date.now() + 3_600_000).toISOString(); vi.mocked(fetchCosmetics).mockResolvedValue({ + patterns: {}, + flags: {}, promotions: [ { id: "1", name: "Weekend Sale", percentOff: 25, endsAt }, // Already over: the banner drops it even before the catalog refetches. @@ -370,10 +375,16 @@ describe("StoreModal cosmetic browser", () => { }, ], } as unknown as Cosmetics); + const promotion = { id: "1", name: "Weekend Sale", percentOff: 25, endsAt }; resolvedCatalog = [ { ...red, - cosmetic: { ...pattern, priceHard: 90, listPriceHard: 120 } as never, + cosmetic: { + ...pattern, + priceHard: 90, + listPriceHard: 120, + promotion, + } as never, }, ]; const modal = await openStoreOnCosmetic("patterns"); @@ -383,24 +394,24 @@ describe("StoreModal cosmetic browser", () => { const banner = modal.querySelector("[data-store-sale-banner]")!; expect(banner.children).toHaveLength(1); - expect(banner.textContent).toContain("store.sale_banner"); - expect(translateText).toHaveBeenCalledWith("store.sale_banner", { - name: "Weekend Sale", + expect(banner.textContent).toContain("Weekend Sale"); + expect(banner.textContent).not.toContain("Old Sale"); + expect(banner.textContent).toContain("store.sale_ends_in_hours"); + expect(translateText).toHaveBeenCalledWith("store.sale_percent_off", { percent: 25, - ends: new Date(endsAt).toLocaleString(undefined, { - dateStyle: "medium", - timeStyle: "short", - }), }); - expect(translateText).not.toHaveBeenCalledWith( - "store.sale_banner", - expect.objectContaining({ name: "Old Sale" }), - ); + const saleCard = card(modal, red.key)!; + await saleCard.updateComplete; + expect(saleCard.querySelector("[data-cosmetic-sale]")).toBeTruthy(); const button = modal.querySelector("purchase-button")!; expect(button.listPriceHard).toBe(120); await button.updateComplete; - const tag = button.querySelector("[data-sale-tag]")!; - expect(tag.querySelector("s")?.textContent?.trim()).toBe("120"); + // The struck price, after its screen-reader "was" label. + const struck = button.querySelector("s[data-sale-tag]")!; + expect(struck.querySelector(".sr-only")?.textContent).toContain( + "store.sale_was", + ); + expect(struck.lastChild?.textContent?.trim()).toBe("120"); }); it("keeps the shown catalog when a stale refetch fails", async () => { @@ -437,6 +448,8 @@ describe("StoreModal cosmetic browser", () => { try { const endsAt = new Date(Date.now() + 60_000).toISOString(); vi.mocked(fetchCosmetics).mockResolvedValue({ + patterns: {}, + flags: {}, promotions: [{ id: "1", name: "Flash", percentOff: 10, endsAt }], } as unknown as Cosmetics); resolvedCatalog = [ @@ -523,7 +536,11 @@ describe("StoreModal cosmetic browser", () => { percentOff: 10, endsAt: new Date(Date.now() + 60_000).toISOString(), }; - const during = { promotions: [sale] } as unknown as Cosmetics; + const during = { + patterns: {}, + flags: {}, + promotions: [sale], + } as unknown as Cosmetics; vi.mocked(fetchCosmetics).mockResolvedValue(during); const modal = await openStoreOnCosmetic("patterns"); await vi.waitFor(() => @@ -615,6 +632,169 @@ describe("StoreModal cosmetic browser", () => { await button.updateComplete; expect(button.listPriceHard).toBeNull(); expect(button.querySelector("[data-sale-tag]")).toBeNull(); + expect(modal.querySelector("[data-cosmetic-sale]")).toBeNull(); + }); + + it("lists discounted items first and under an On sale tab", async () => { + const promotion = { + id: "1", + name: "Weekend Sale", + percentOff: 25, + endsAt: new Date(Date.now() + 3_600_000).toISOString(), + }; + const dots: ResolvedCosmetic = { + ...red, + cosmetic: { + ...pattern, + name: "dots", + priceHard: 90, + listPriceHard: 120, + promotion, + } as never, + key: "pattern:dots:red", + }; + const saleFlag: ResolvedCosmetic = { + ...flag, + cosmetic: { + ...(flag.cosmetic as object), + priceSoft: 400, + listPriceSoft: 500, + promotion, + } as never, + }; + resolvedCatalog = [red, blue, green, dots, saleFlag]; + const modal = await openStoreOnCosmetic("patterns"); + + // On sale first, ahead of the catalog order. + const keys = () => + [...modal.querySelectorAll("cosmetic-card")].map( + (c) => c.resolved.key, + ); + expect(keys()).toEqual([dots.key, red.key]); + + const saleTab = modal.querySelector( + '[data-store-subtab="sale"]', + )!; + expect(saleTab.textContent).toContain("store.on_sale"); + saleTab.click(); + await modal.updateComplete; + expect(keys()).toEqual([dots.key, saleFlag.key]); + }); + + it("leads On sale with the flash item, and its banner line opens it", async () => { + const endsAt = new Date(Date.now() + 3_600_000).toISOString(); + const flashSale = { + id: "9", + name: "Flash", + percentOff: 50, + endsAt, + kind: "flash" as const, + }; + vi.mocked(fetchCosmetics).mockResolvedValue({ + patterns: {}, + flags: {}, + promotions: [flashSale], + } as unknown as Cosmetics); + const zap: ResolvedCosmetic = { + ...red, + cosmetic: { + ...pattern, + name: "zap", + priceHard: 60, + listPriceHard: 120, + promotion: flashSale, + } as never, + key: "pattern:zap:red", + }; + resolvedCatalog = [red, blue, green, zap]; + const modal = await openStoreOnCosmetic("patterns"); + await vi.waitFor(() => + expect(modal.querySelector("[data-store-flash-banner]")).toBeTruthy(), + ); + // On the Skins tab the flash item sorts first, with a ribboned card. + expect( + modal.querySelector("cosmetic-card")!.resolved.key, + ).toBe(zap.key); + + // The flash item glows and counts down; regular sale items don't. + const flashCard = card(modal, zap.key)!; + await flashCard.updateComplete; + expect( + flashCard.querySelector("[data-cosmetic-shell][data-cosmetic-flash]"), + ).toBeTruthy(); + expect(flashCard.querySelector("[data-cosmetic-flash-ring]")).toBeTruthy(); + expect( + flashCard.querySelector("[data-cosmetic-flash-timer] sale-countdown"), + ).toBeTruthy(); + const plain = card(modal, red.key)!; + expect(plain.querySelector("[data-cosmetic-flash]")).toBeNull(); + expect(plain.querySelector("[data-cosmetic-flash-timer]")).toBeNull(); + + modal + .querySelector("[data-store-flash-banner]")! + .click(); + await modal.updateComplete; + const hero = modal.querySelector("[data-store-flash]")!; + expect(hero).toBeTruthy(); + expect( + hero.querySelector("cosmetic-card")!.resolved.key, + ).toBe(zap.key); + expect(hero.querySelector("sale-countdown")).toBeTruthy(); + // The flash item leads in the hero, not again in the grid below it. + const gridKeys = [ + ...modal.querySelectorAll( + "[data-store-grid] cosmetic-card", + ), + ].map((c) => c.resolved.key); + expect(gridKeys).not.toContain(zap.key); + }); + + it("hides the On sale tab without a sale", async () => { + const modal = await openStoreOnCosmetic("patterns"); + expect(modal.querySelector('[data-store-subtab="sale"]')).toBeNull(); + expect(modal.querySelector('[data-store-subtab="patterns"]')).toBeTruthy(); + }); + + it("tells a store-wide sale from one on selected items", () => { + const promotion = { id: "s", name: "Sale", percentOff: 20, endsAt: "" }; + const catalog = (secondOnSale: boolean) => + ({ + patterns: { + a: { priceHard: 80, listPriceHard: 100, promotion }, + }, + flags: { + b: secondOnSale + ? { priceSoft: 400, listPriceSoft: 500, promotion } + : { priceSoft: 500 }, + // Not for sale: doesn't count either way. + c: {}, + }, + }) as unknown as Cosmetics; + expect(saleCoversEverything(catalog(true), "s")).toBe(true); + expect(saleCoversEverything(catalog(false), "s")).toBe(false); + expect(saleCoversEverything(null, "s")).toBe(false); + }); + + it("shows a flash sale's clock with seconds", () => { + const now = Date.parse("2026-10-30T12:00:00Z"); + const at = (s: number) => new Date(now + s * 1000).toISOString(); + expect(clockUntil(at(3600 + 23 * 60 + 45), now)).toBe("1:23:45"); + expect(clockUntil(at(9 * 60 + 5), now)).toBe("9:05"); + expect(clockUntil(at(-5), now)).toBe("0:00"); + }); + + it("counts a sale's end down in days, hours or minutes", () => { + const now = Date.parse("2026-10-30T12:00:00Z"); + const at = (ms: number) => new Date(now + ms).toISOString(); + vi.mocked(translateText).mockClear(); + saleEndsIn(at((2 * 24 + 5) * 3_600_000), now); + saleEndsIn(at(3 * 3_600_000 + 12 * 60_000), now); + saleEndsIn(at(7 * 60_000 + 30_000), now); + expect(vi.mocked(translateText).mock.calls).toEqual([ + ["store.sale_ends_in_days", { days: 2, hours: 5 }], + ["store.sale_ends_in_hours", { hours: 3, minutes: 12 }], + ["store.sale_ends_in_minutes", { minutes: 8 }], + ]); }); it("selects the first visible item and purchases the selected variant", async () => { From 5afb579385ed44f1102a5bc9f86c44fd45f2b294 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 30 Oct 2026 18:57:38 +0000 Subject: [PATCH 11/13] fix(store): don't crash the sale banner on a catalog without patterns/flags saleCoversEverything() read Object.values(cosmetics.patterns/flags) with no fallback, so a catalog missing either threw while rendering the banner (the StoreModal tests' minimal catalogs did, failing CI with unhandled errors). Fall back to {} as it already does for crowns, skins, packs and effects. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019Wbkiw3pQDRGxxLWZXKXUL --- src/client/Store.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/client/Store.ts b/src/client/Store.ts index 5b6298769f8..4b14b19a79e 100644 --- a/src/client/Store.ts +++ b/src/client/Store.ts @@ -141,8 +141,8 @@ export function saleCoversEverything( ): boolean { if (cosmetics === null) return false; const items: { priceHard?: number; promotion?: { id: string } }[] = [ - ...Object.values(cosmetics.patterns), - ...Object.values(cosmetics.flags), + ...Object.values(cosmetics.patterns ?? {}), + ...Object.values(cosmetics.flags ?? {}), ...Object.values(cosmetics.crowns ?? {}), ...Object.values(cosmetics.skins ?? {}), ...Object.values(cosmetics.packs ?? {}), From c4877dceb4904783118cc4d249486f762d660eac Mon Sep 17 00:00:00 2001 From: iamlewis Date: Fri, 30 Oct 2026 21:40:21 +0000 Subject: [PATCH 12/13] fix(store): keep the newest catalog when fetches land out of order Sign-in, reopening and a sale ending each fetch the catalog, and an older answer landing last could replace a newer one. Every fetch now goes through loadCatalog, which keeps only the newest request's answer. Co-Authored-By: Claude Opus 5.5 --- src/client/Store.ts | 35 +++++++++++++++++++-------- tests/client/StoreModal.test.ts | 42 +++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+), 10 deletions(-) diff --git a/src/client/Store.ts b/src/client/Store.ts index 4b14b19a79e..7f2af54664f 100644 --- a/src/client/Store.ts +++ b/src/client/Store.ts @@ -261,13 +261,14 @@ export class StoreModal extends BaseModal { private saleRetryTimer: ReturnType | null = null; /** Bumped on close, so a sale-end refetch still in flight then is dropped. */ private saleRefetchGeneration = 0; + /** Bumped by every catalog fetch, so only the newest one's answer is kept. */ + private catalogRequest = 0; private alignFrame: number | null = null; async onUserMe(userMeResponse: UserMeResponse | false) { this.userMeResponse = userMeResponse; this.authSettled = true; - // A failed fetch keeps the catalog already shown (see onOpen). - this.cosmetics = (await fetchCosmetics()) ?? this.cosmetics; + await this.loadCatalog(); this.selectVisible(this.groupsForTab(this.activeTab)); await this.refresh(); } @@ -1037,6 +1038,21 @@ export class StoreModal extends BaseModal { }, delay); } + /** + * Fetches the catalog and shows it, unless a newer fetch started meanwhile + * (sign-in, reopening, a sale ending): an older answer landing last would + * otherwise replace a newer catalog. A failed fetch keeps the catalog + * already shown rather than emptying the store; the purchase endpoint + * charges the live price either way. Returns what this fetch got. + */ + private async loadCatalog(): Promise { + const request = ++this.catalogRequest; + const fresh = await fetchCosmetics(); + if (request === this.catalogRequest) + this.cosmetics = fresh ?? this.cosmetics; + return fresh; + } + /** * Refetches the catalog after a sale ends. The API serves cosmetics.json * from a one-minute cache, so the first answer may still carry the ended @@ -1045,13 +1061,15 @@ export class StoreModal extends BaseModal { private async refetchAfterSaleEnd(attempt: number): Promise { const generation = this.saleRefetchGeneration; invalidateCosmetics(); - const fresh = await fetchCosmetics(); + const fresh = await this.loadCatalog(); // Closed (and maybe reopened) since: that open's own fetch wins. if (!this.isModalOpen || generation !== this.saleRefetchGeneration) return; - this.cosmetics = fresh ?? this.cosmetics; this.selectVisible(this.groupsForTab(this.activeTab)); this.requestUpdate(); - if ((fresh === null || hasEndedSale(fresh)) && attempt < SALE_END_RETRIES) { + if ( + (fresh === null || hasEndedSale(this.cosmetics)) && + attempt < SALE_END_RETRIES + ) { if (this.saleRetryTimer !== null) clearTimeout(this.saleRetryTimer); this.saleRetryTimer = setTimeout(() => { this.saleRetryTimer = null; @@ -1127,12 +1145,9 @@ export class StoreModal extends BaseModal { } // Prices change when a sale starts or ends, so a catalog fetched more than // a minute ago is refetched rather than shown with stale prices. - // A failed refetch keeps the catalog already shown rather than emptying - // the store; the purchase endpoint charges the live price either way. - if (refreshStaleCosmetics()) { - this.cosmetics = (await fetchCosmetics()) ?? this.cosmetics; + if (refreshStaleCosmetics() || this.cosmetics === null) { + await this.loadCatalog(); } - this.cosmetics ??= await fetchCosmetics(); this.selectVisible(this.groupsForTab(this.activeTab)); await this.refresh(); // A catalog still carrying a sale that has ended (the store was closed diff --git a/tests/client/StoreModal.test.ts b/tests/client/StoreModal.test.ts index 9aef47a93fe..f875029071f 100644 --- a/tests/client/StoreModal.test.ts +++ b/tests/client/StoreModal.test.ts @@ -443,6 +443,44 @@ describe("StoreModal cosmetic browser", () => { expect(modal.querySelector("cosmetic-card")).toBeTruthy(); }); + it("keeps the newer catalog when an older fetch lands last", async () => { + vi.useFakeTimers({ shouldAdvanceTime: true }); + try { + const endsAt = new Date(Date.now() + 60_000).toISOString(); + vi.mocked(fetchCosmetics).mockResolvedValue({ + patterns: {}, + flags: {}, + promotions: [{ id: "1", name: "Sale", percentOff: 10, endsAt }], + } as unknown as Cosmetics); + const modal = await openStoreOnCosmetic("patterns"); + + // A sign-in refetch starts, then the sale ends and a newer one starts. + let resolveOlder: (c: Cosmetics) => void = () => {}; + vi.mocked(fetchCosmetics).mockReturnValueOnce( + new Promise((resolve) => { + resolveOlder = resolve; + }) as never, + ); + const signIn = modal.onUserMe(false); + const newer = { promotions: [] } as unknown as Cosmetics; + vi.mocked(fetchCosmetics).mockResolvedValue(newer); + await vi.advanceTimersByTimeAsync(61_000); + await vi.waitFor(() => + expect((modal as unknown as { cosmetics: unknown }).cosmetics).toBe( + newer, + ), + ); + + resolveOlder({ promotions: [] } as unknown as Cosmetics); + await signIn; + expect((modal as unknown as { cosmetics: unknown }).cosmetics).toBe( + newer, + ); + } finally { + vi.useRealTimers(); + } + }); + it("refetches prices when a sale ends while the store is open", async () => { vi.useFakeTimers({ shouldAdvanceTime: true }); try { @@ -492,6 +530,8 @@ describe("StoreModal cosmetic browser", () => { try { const endsAt = new Date(Date.now() + 60_000).toISOString(); const during = { + patterns: {}, + flags: {}, promotions: [{ id: "1", name: "Flash", percentOff: 10, endsAt }], } as unknown as Cosmetics; vi.mocked(fetchCosmetics).mockResolvedValue(during); @@ -573,6 +613,8 @@ describe("StoreModal cosmetic browser", () => { it("refetches on reopen when the kept catalog still has an ended sale", async () => { const ended = { + patterns: {}, + flags: {}, promotions: [ { id: "1", From e31b289ff65faf08d5055ac8504a53b7c576f755 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 13:49:38 +0000 Subject: [PATCH 13/13] fix(store): list every sale item under On sale, and say what a purchase cost - The On sale tab now includes discounted effects and bundles. A flash sale can pick one of those, and the banner, which opens On sale, then led to Skins with no sign of the item. - With the flash item the only thing on sale, its hero is the whole tab: no "No skins available" under it. - The server prices a purchase off its own clock, so a sale that started or ended since the store loaded (or a client clock that is off) can charge something other than the price shown. purchaseWithCurrency now returns the charged amount, and when it (or a pack's) differs from the shown price the success alert says what was taken and the catalog is dropped. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019Wbkiw3pQDRGxxLWZXKXUL --- resources/lang/en.json | 1 + src/client/Api.ts | 15 ++++++-- src/client/Cosmetics.ts | 35 ++++++++++++++++-- src/client/Store.ts | 43 +++++++++++++++++----- tests/client/CosmeticPackPurchase.test.ts | 23 ++++++++++++ tests/client/CosmeticPurchaseDebt.test.ts | 28 +++++++++++++++ tests/client/PurchaseCosmeticPack.test.ts | 13 ++++++- tests/client/StoreModal.test.ts | 44 +++++++++++++++++++++++ 8 files changed, 188 insertions(+), 14 deletions(-) diff --git a/resources/lang/en.json b/resources/lang/en.json index 69b08d97230..5cab71d1134 100644 --- a/resources/lang/en.json +++ b/resources/lang/en.json @@ -2474,6 +2474,7 @@ "purchase_failed": "Purchase failed. Please try again.", "purchase_pending": "Your purchase is still being processed. It will appear in your account shortly — check your order history if it doesn't.", "purchase_success": "Purchase succeeded: {name}", + "purchase_success_charged": "Purchase succeeded: {name}. The price changed since the store loaded, so you were charged {amount} {currency}.", "purchase_tribe_button": "Purchase", "sale_ends_in_days": "Ends in {days}d {hours}h", "sale_ends_in_hours": "Ends in {hours}h {minutes}m", diff --git a/src/client/Api.ts b/src/client/Api.ts index d6fcdfa2ff5..86c633d0055 100644 --- a/src/client/Api.ts +++ b/src/client/Api.ts @@ -1293,7 +1293,9 @@ export async function fetchTribeStats( } export type PurchaseWithCurrencyResult = - | { ok: true } + // `amount` is what was charged, when the response says so. It differs from + // the price the store showed when a sale started or ended in between. + | { ok: true; amount?: number } // 400 "Insufficient balance": the balance moved since the client's // pre-check. Nothing charged. | { ok: false; code: "insufficient_balance" } @@ -1363,7 +1365,16 @@ export async function purchaseWithCurrency( ); return { ok: false, code: "failed" }; } - return { ok: true }; + // The purchase went through: an unreadable body only loses the amount. + const body = await response.json().catch(() => null); + const amount = Number(body?.amount); + return { + ok: true, + amount: + typeof body?.amount === "string" && Number.isFinite(amount) + ? amount + : undefined, + }; } catch (e) { console.error("purchaseWithCurrency: request failed", e); return { ok: false, code: "failed" }; diff --git a/src/client/Cosmetics.ts b/src/client/Cosmetics.ts index 0358457f0f0..580abf1c977 100644 --- a/src/client/Cosmetics.ts +++ b/src/client/Cosmetics.ts @@ -710,12 +710,37 @@ export async function purchaseCosmetic( } } await showInGameAlert( - translateText("store.purchase_success", { name: c.name }), + purchaseSuccessMessage(c.name, price, result.amount, method), ); invalidateUserMe(); window.location.reload(); } +/** + * The success alert. The server prices off its own clock, so a sale that + * started or ended since the store loaded (or a client clock that is off) + * can charge something other than the price shown: say what was taken, and + * drop the catalog that showed the wrong price. + */ +function purchaseSuccessMessage( + name: string, + shownPrice: number, + charged: number | undefined, + method: "hard" | "soft", +): string { + if (charged === undefined || charged === shownPrice) { + return translateText("store.purchase_success", { name }); + } + invalidateCosmetics(); + return translateText("store.purchase_success_charged", { + name, + amount: charged, + currency: translateText( + method === "hard" ? "cosmetics.hard" : "cosmetics.soft", + ), + }); +} + /** * Buys a cosmetic pack (plutonium only). Mirrors the single-cosmetic currency * flow: a local balance pre-check surfaces the insufficient-funds dialog @@ -755,8 +780,14 @@ async function purchasePack( const result = await purchaseCosmeticPack(pack.name); if (result.ok) { + const charged = Number(result.data.amount); await showInGameAlert( - translateText("store.purchase_success", { name: pack.displayName }), + purchaseSuccessMessage( + pack.displayName, + price, + Number.isFinite(charged) ? charged : undefined, + "hard", + ), ); invalidateUserMe(); window.location.reload(); diff --git a/src/client/Store.ts b/src/client/Store.ts index 7f2af54664f..6b95253c94f 100644 --- a/src/client/Store.ts +++ b/src/client/Store.ts @@ -69,8 +69,8 @@ type StoreTab = | "subscriptions" | "tribes"; -// "sale" lists every discounted skin, flag and crown; its tab shows only -// while a sale covers one of them. +// "sale" lists every discounted skin, flag, crown, effect and bundle; its tab +// shows only while a sale covers one of them. const COSMETICS_SUB_TABS = ["sale", "patterns", "flags", "crowns"] as const; type CosmeticsSubTab = (typeof COSMETICS_SUB_TABS)[number]; @@ -320,7 +320,18 @@ export class StoreModal extends BaseModal { .filter((resolved) => resolved.type === "crown") .map((r) => [r]); if (tab === "sale") { - return saleFirst([...skins, ...flags, ...crowns].filter(groupOnSale)); + // A sale (a flash sale's pick included) can land on an effect or a + // bundle too, and those live on other tabs; list them here as well so + // the banner's "On sale" always leads to the item. + const others = items + .filter( + (resolved) => + resolved.type === "effect" || resolved.type === "cosmeticPack", + ) + .map((r) => [r]); + return saleFirst( + [...skins, ...flags, ...crowns, ...others].filter(groupOnSale), + ); } return saleFirst( tab === "flags" ? flags : tab === "crowns" ? crowns : skins, @@ -600,8 +611,16 @@ export class StoreModal extends BaseModal { .inlineCheckout=${inlineCheckout} .priceHard=${priceHard ?? null} .priceSoft=${priceSoft ?? null} - .listPriceHard=${priceHard !== undefined && !saleEnded ? (priced?.listPriceHard ?? null) : null} - .listPriceSoft=${priceSoft !== undefined && !saleEnded ? (priced?.listPriceSoft ?? null) : null} + .listPriceHard=${ + priceHard !== undefined && !saleEnded + ? (priced?.listPriceHard ?? null) + : null + } + .listPriceSoft=${ + priceSoft !== undefined && !saleEnded + ? (priced?.listPriceSoft ?? null) + : null + } .rarity=${priced?.rarity ?? "common"} .itemName=${cosmeticSelectionLabel(resolved)} .dollarLabelKey=${ @@ -710,10 +729,16 @@ export class StoreModal extends BaseModal { ${ flash ? html`${this.renderFlashHero(flash)} - ${this.renderBrowser( - this.visibleGroups.filter((group) => group !== flash), - { emptyTranslationKey: emptyKey }, - )}` + ${(() => { + // With the flash item the only thing on sale, the hero is the + // whole tab: no "No skins available" under it. + const rest = this.visibleGroups.filter( + (group) => group !== flash, + ); + return rest.length > 0 + ? this.renderBrowser(rest, { emptyTranslationKey: emptyKey }) + : nothing; + })()}` : this.renderBrowser(this.visibleGroups, { emptyTranslationKey: emptyKey, }) diff --git a/tests/client/CosmeticPackPurchase.test.ts b/tests/client/CosmeticPackPurchase.test.ts index 7ae0107a501..efe3563873e 100644 --- a/tests/client/CosmeticPackPurchase.test.ts +++ b/tests/client/CosmeticPackPurchase.test.ts @@ -31,6 +31,7 @@ const translations = { "store.pack_unavailable": "gone", "store.purchase_failed": "failed", "store.purchase_success": "bought {name}", + "store.purchase_success_charged": "bought {name} for {amount} {currency}", }; const starter: ResolvedCosmetic = { @@ -108,6 +109,28 @@ describe("purchaseCosmetic for a cosmetic pack", () => { expect(reloadMock).toHaveBeenCalled(); }); + it("says what was charged when the server's price differs from the shown one", async () => { + // A sale ended between loading the store and buying: the server charged + // the list price, not the 250 the card showed. + vi.mocked(getUserMe).mockResolvedValue(userWithHard(600)); + vi.mocked(purchaseCosmeticPack).mockResolvedValue({ + ok: true, + data: { + packName: "starter", + currencyType: "hard", + amount: "500", + flareNames: ["pattern:camo", "flag:pirate"], + }, + }); + + await purchaseCosmetic(starter, "hard"); + + expect(showInGameAlert).toHaveBeenCalledWith( + "bought Starter Pack for 500 plutonium", + ); + expect(reloadMock).toHaveBeenCalled(); + }); + it("reports the shortfall before any request when the balance is short", async () => { vi.mocked(getUserMe).mockResolvedValue(userWithHard(100)); diff --git a/tests/client/CosmeticPurchaseDebt.test.ts b/tests/client/CosmeticPurchaseDebt.test.ts index 98a2f989f78..b4cb04cf966 100644 --- a/tests/client/CosmeticPurchaseDebt.test.ts +++ b/tests/client/CosmeticPurchaseDebt.test.ts @@ -38,6 +38,7 @@ const translations = { "store.already_owned": "already owned", "store.purchase_failed": "failed", "store.purchase_success": "bought {name}", + "store.purchase_success_charged": "bought {name} for {amount} {currency}", }; const pirateFlag: ResolvedCosmetic = { @@ -302,6 +303,33 @@ describe("purchaseCosmetic when the wallet is in debt", () => { expect(reloadMock).not.toHaveBeenCalled(); }); + it("says what was charged when it isn't the price shown", async () => { + // The card showed 100 plutonium; a flash slot turned over before the + // request landed and the server charged the list price. + vi.mocked(purchaseWithCurrency).mockResolvedValue({ + ok: true, + amount: 200, + }); + + await purchaseCosmetic(pirateFlag, "hard"); + + expect(showInGameAlert).toHaveBeenCalledWith( + "bought pirate for 200 plutonium", + ); + expect(reloadMock).toHaveBeenCalled(); + }); + + it("keeps the plain success message when the charge matches", async () => { + vi.mocked(purchaseWithCurrency).mockResolvedValue({ + ok: true, + amount: 400, + }); + + await purchaseCosmetic(pirateFlag, "soft"); + + expect(showInGameAlert).toHaveBeenCalledWith("bought pirate"); + }); + it("still grants and reloads on success", async () => { vi.mocked(purchaseWithCurrency).mockResolvedValue({ ok: true }); diff --git a/tests/client/PurchaseCosmeticPack.test.ts b/tests/client/PurchaseCosmeticPack.test.ts index 83cc658c3f4..e537e890c20 100644 --- a/tests/client/PurchaseCosmeticPack.test.ts +++ b/tests/client/PurchaseCosmeticPack.test.ts @@ -224,7 +224,18 @@ describe("purchaseWithCurrency", () => { cosmeticName: "pirate", currencyType: "hard", }); - expect(result).toEqual({ ok: true }); + // What was charged, so the caller can tell a changed price from the + // one it showed. + expect(result).toEqual({ ok: true, amount: 100 }); + }); + + it("still reports success when the body carries no amount", async () => { + respond(200, {}); + + expect(await purchaseWithCurrency("flag", "pirate", "hard")).toEqual({ + ok: true, + amount: undefined, + }); }); it("reports the debt and its amount", async () => { diff --git a/tests/client/StoreModal.test.ts b/tests/client/StoreModal.test.ts index f875029071f..60b34706480 100644 --- a/tests/client/StoreModal.test.ts +++ b/tests/client/StoreModal.test.ts @@ -791,6 +791,50 @@ describe("StoreModal cosmetic browser", () => { expect(gridKeys).not.toContain(zap.key); }); + it("lists a flash effect under On sale, with no empty-tab line under it", async () => { + const endsAt = new Date(Date.now() + 3_600_000).toISOString(); + const flashSale = { + id: "9", + name: "Flash", + percentOff: 50, + endsAt, + kind: "flash" as const, + }; + vi.mocked(fetchCosmetics).mockResolvedValue({ + patterns: {}, + flags: {}, + promotions: [flashSale], + } as unknown as Cosmetics); + const base = trail("comet"); + const comet: ResolvedCosmetic = { + ...base, + cosmetic: { + ...(base.cosmetic as object), + priceHard: 40, + listPriceHard: 80, + promotion: flashSale, + } as never, + }; + // The flash pick is an effect, which lives on the Effects tab, and it is + // the only thing on sale. + resolvedCatalog = [red, blue, comet]; + const modal = await openStoreOnCosmetic("patterns"); + await vi.waitFor(() => + expect(modal.querySelector("[data-store-flash-banner]")).toBeTruthy(), + ); + + modal + .querySelector("[data-store-flash-banner]")! + .click(); + await modal.updateComplete; + expect(modal.querySelector('[data-store-subtab="sale"]')).toBeTruthy(); + const hero = modal.querySelector("[data-store-flash]")!; + expect( + hero.querySelector("cosmetic-card")!.resolved.key, + ).toBe(comet.key); + expect(modal.textContent).not.toContain("store.no_skins"); + }); + it("hides the On sale tab without a sale", async () => { const modal = await openStoreOnCosmetic("patterns"); expect(modal.querySelector('[data-store-subtab="sale"]')).toBeNull();