Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions packages/shared/src/CosmeticSchemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof PromotionSchema>;

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
Expand Down Expand Up @@ -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()),
Expand Down Expand Up @@ -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(),
});

/**
Expand Down
17 changes: 17 additions & 0 deletions resources/lang/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand All @@ -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.",
Expand All @@ -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.",
Expand Down
15 changes: 13 additions & 2 deletions src/client/Api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
Expand Down Expand Up @@ -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" };
Expand Down
125 changes: 118 additions & 7 deletions src/client/Cosmetics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,10 @@ export const COSMETICS_FETCH_TIMEOUT_MS = 10_000;
let __cosmetics: Promise<Cosmetics | null> | 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
Expand Down Expand Up @@ -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;
Comment thread
Celant marked this conversation as resolved.
Resolved
const userMe = await getUserMe();
if (userMe === false) {
await showInGameAlert(translateText("store.login_required"));
Expand Down Expand Up @@ -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
Expand All @@ -726,14 +754,15 @@ 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"));
return;
}
const insufficient = (balance: number): InsufficientCurrency => ({
currency: translateText("cosmetics.hard"),
shortfall: pack.priceHard - balance,
shortfall: price - balance,
item: pack.displayName,
canTopUp: true,
});
Expand All @@ -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();
Expand All @@ -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;
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -885,6 +995,7 @@ export async function fetchCosmetics(): Promise<Cosmetics | null> {
const hashInput = patternKeys.join(",");
__cosmeticsHash = simpleHash(hashInput);
__cosmeticsCache = result.data;
__cosmeticsFetchedAt = Date.now();
return result.data;
} catch (error) {
console.warn("Error getting cosmetics:", error);
Expand Down
Loading
Loading