diff --git a/packages/shared/src/CosmeticSchemas.ts b/packages/shared/src/CosmeticSchemas.ts index 24c74f0560f..8d6b0d8b3ff 100644 --- a/packages/shared/src/CosmeticSchemas.ts +++ b/packages/shared/src/CosmeticSchemas.ts @@ -89,12 +89,31 @@ 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(), + // 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; + 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 +505,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 +578,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 8e3318fcdf8..5cab71d1134 100644 --- a/resources/lang/en.json +++ b/resources/lang/en.json @@ -2430,6 +2430,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.", @@ -2443,6 +2450,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.", @@ -2466,7 +2474,16 @@ "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", + "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/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 431ab56aec5..580abf1c977 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 @@ -577,8 +581,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")); @@ -707,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 @@ -726,6 +754,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")); @@ -733,7 +762,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, }); @@ -745,14 +774,20 @@ async function purchasePack( await showInGameAlert(debtMessage(-balance)); return; } - if (balance < pack.priceHard) { + if (balance < price) { return insufficient(balance); } 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(); @@ -769,7 +804,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; @@ -841,6 +876,39 @@ function simpleHash(str: string): string { return hash.toString(36); } +/** + * 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() + ); +} + /** * 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 @@ -851,6 +919,48 @@ 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 + * 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 @@ -885,6 +995,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..6b95253c94f 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,17 +23,23 @@ 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, + refreshStaleCosmetics, findPackItem, groupCosmeticVariants, ownedPackItems, purchaseCosmetic, resolveCosmetics, + saleHasEnded, ResolvedCosmetic, } from "./Cosmetics"; import { matchesStoreItem } from "./EquippedCosmetics"; @@ -62,7 +69,9 @@ type StoreTab = | "subscriptions" | "tribes"; -const COSMETICS_SUB_TABS = ["patterns", "flags", "crowns"] as const; +// "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]; /** Sub-tab holding the catalog item a store deep link points at. */ @@ -82,6 +91,76 @@ 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; + +/** 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, + ); +} + +/** 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"; @@ -176,12 +255,20 @@ 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; + /** 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; - this.cosmetics = await fetchCosmetics(); + await this.loadCatalog(); this.selectVisible(this.groupsForTab(this.activeTab)); await this.refresh(); } @@ -221,21 +308,34 @@ 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") { + // 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, + ); } private groupsForTab(tab: string): readonly (readonly ResolvedCosmetic[])[] { @@ -252,6 +352,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") { @@ -345,6 +452,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)); @@ -442,6 +555,9 @@ export class StoreModal extends BaseModal { product?: Product | null; priceHard?: number; priceSoft?: number; + listPriceHard?: number; + listPriceSoft?: number; + promotion?: { endsAt: string }; rarity?: string; } | null; const isPurchasable = resolved.relationship === "purchasable"; @@ -459,8 +575,13 @@ 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; + // 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) @@ -490,6 +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 + } .rarity=${priced?.rarity ?? "common"} .itemName=${cosmeticSelectionLabel(resolved)} .dollarLabelKey=${ @@ -558,6 +689,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" @@ -566,28 +702,97 @@ 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)} + ${(() => { + // 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, + }) + } `; } + /** + * 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. @@ -670,8 +875,236 @@ 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(), + ); + 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`
+ ${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 + * 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; + void this.refetchAfterSaleEnd(0); + }, 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 + * 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 this.loadCatalog(); + // Closed (and maybe reopened) since: that open's own fetch wins. + if (!this.isModalOpen || generation !== this.saleRefetchGeneration) return; + this.selectVisible(this.groupsForTab(this.activeTab)); + this.requestUpdate(); + if ( + (fresh === null || hasEndedSale(this.cosmetics)) && + 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()} + return html`${this.renderHeader()} ${this.renderSaleBanner()} ${ this.previewingCosmetic ? html` — would float over // the play page after Escape closes the store. Close it explicitly. 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/CosmeticPackPurchase.test.ts b/tests/client/CosmeticPackPurchase.test.ts index 43c384d376e..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)); @@ -122,6 +145,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)) 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/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..1b2604f34d5 100644 --- a/tests/client/PurchaseButton.test.ts +++ b/tests/client/PurchaseButton.test.ts @@ -81,6 +81,29 @@ describe("PurchaseButton", () => { } }); + it("strikes through the list price 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")!; + // 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(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(); + }); + 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/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 fc6a4868655..60b34706480 100644 --- a/tests/client/StoreModal.test.ts +++ b/tests/client/StoreModal.test.ts @@ -2,26 +2,38 @@ 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, + refreshStaleCosmetics, 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, 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()), fetchCosmetics: vi.fn(), purchaseCosmetic: vi.fn(), + refreshStaleCosmetics: vi.fn(() => false), resolveCosmetics: vi.fn(), })); @@ -347,6 +359,530 @@ 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({ + patterns: {}, + flags: {}, + 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); + const promotion = { id: "1", name: "Weekend Sale", percentOff: 25, endsAt }; + resolvedCatalog = [ + { + ...red, + cosmetic: { + ...pattern, + priceHard: 90, + listPriceHard: 120, + promotion, + } 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("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, + }); + 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; + // 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 () => { + 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("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("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 { + 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 = [ + { + ...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()); + await vi.waitFor(() => + expect(modal.querySelector("[data-store-sale-banner]")).toBeNull(), + ); + 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 = { + patterns: {}, + flags: {}, + 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(); + } + }); + + 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 = { + patterns: {}, + flags: {}, + 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("refetches on reopen when the kept catalog still has an ended sale", async () => { + const ended = { + patterns: {}, + flags: {}, + 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 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(); + const button = modal.querySelector("purchase-button")!; + 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("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(); + 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 () => { const modal = await openStoreOnCosmetic("patterns"); expect(card(modal, red.key)?.activeVariantKey).toBe(red.key);