Files
WT-Offline/packages/local-service/src/store/store-web-api.ts
T
N0VAN0M4LY 81e3add520 Add a shopping cart and refresh the local storefront
Save carts per account and settle each order in one profile update. Add featured packs, a screenshot and video gallery, and premium artwork from the game files.
2026-11-26 19:07:48 +08:00

259 lines
13 KiB
TypeScript

/**
* The JSON requests of the local store page (/store, shown in the game's built-in browser;
* implementation notes):
* GET /store/api/state?userId= balances, products and redeem code help for one account
* POST /store/api/buy { userId, productId }
* POST /store/api/cart { userId, productId, action }
* POST /store/api/checkout { userId, productIds, payMethod }
* POST /store/api/redeem { userId, code }
* Texts for the player come in both page languages ({ en, zh }); the page picks one.
*/
import type { AccountStore } from '../accounts/account-store.ts';
import type { LocalizedText } from '../game-data/datasets/unit-names.ts';
import type { PlayerProfiles } from '../profile/player-profiles.ts';
import { balanceOf } from '../profile/profile-currency.ts';
import { remainingPremiumDays } from '../profile/profile-entitlements.ts';
import { clearStoreCart, setStoreCart, storeCartIds } from '../profile/profile-store-cart.ts';
import { serverTimeNow } from '../profile/server-time.ts';
import type { ServiceRequest, ServiceResponse } from '../server/exchange.ts';
import { jsonResponse, parseJsonBody, requireWebActionAccount, selectWebViewAccount } from '../web-ui/web-helpers.ts';
import { describeRedeemCodes, gjnText, redeemStoreCode, type RedeemOutcome } from './redeem-codes.ts';
import type { RedeemTuning } from './redeem-tuning.ts';
import type { StoreCatalogue, StoreProduct } from './store-catalogue.ts';
import { buyFreeStoreProduct, buyGjnProduct, buyStoreCart, canBuyGjnProduct, type GjnPurchaseOutcome, type StoreCheckoutOutcome } from './store-purchase.ts';
const NO_ACCOUNT: LocalizedText = { zh: '没有找到这个账号,请先在右上角选择账号。', en: 'Account not found. Pick an account at the top right first.' };
const NO_PRODUCT: LocalizedText = { zh: '没有找到这个商品。', en: 'Product not found.' };
const CART_CHANGED: LocalizedText = { zh: '购物车内容已变化,请核对后再结算。', en: 'Your cart has changed. Review it before checking out.' };
export class StoreWebApi {
readonly #accounts: AccountStore;
readonly #profiles: PlayerProfiles;
readonly #catalogue: StoreCatalogue;
readonly #redeemCodes: RedeemTuning;
constructor(accounts: AccountStore, profiles: PlayerProfiles, catalogue: StoreCatalogue, redeemCodes: RedeemTuning) {
this.#accounts = accounts;
this.#profiles = profiles;
this.#catalogue = catalogue;
this.#redeemCodes = redeemCodes;
}
/** The answer for /store/api/<name>, or undefined when it is not an API request. */
handle(apiPath: string, request: ServiceRequest): ServiceResponse | undefined {
if (apiPath === '/api/state' && request.method === 'GET') return this.#state(request);
if (apiPath === '/api/buy' && request.method === 'POST') return this.#buy(request);
if (apiPath === '/api/cart' && request.method === 'POST') return this.#cart(request);
if (apiPath === '/api/checkout' && request.method === 'POST') return this.#checkout(request);
if (apiPath === '/api/redeem' && request.method === 'POST') return this.#redeem(request);
return undefined;
}
#state(request: ServiceRequest): ServiceResponse {
const account = selectWebViewAccount(this.#accounts, request.query.get('userId'));
const now = serverTimeNow();
const profile = account ? this.#profiles.profileOf(account.userId) : undefined;
const products = this.#catalogue.allProducts()
.filter((product) => product.gjnCostCents !== undefined)
.map((product) => webProduct(product, profile ? !canBuyGjnProduct(profile, product, now) : false));
return jsonResponse({
accounts: this.#accounts.all().map((entry) => ({ userId: entry.userId, login: entry.login, nick: entry.nick })),
activeUserId: account?.userId ?? '',
balance: profile ? balanceOf(profile) : { silverLions: 0, goldenEagles: 0, gjnCents: 0 },
premiumDays: profile ? remainingPremiumDays(profile, now) : 0,
products,
cartProductIds: profile ? storeCartIds(profile) : [],
redeemHelp: describeRedeemCodes(this.#redeemCodes),
}, `store web state (${account?.userId ?? 'no account'})`);
}
#buy(request: ServiceRequest): ServiceResponse {
const body = parseJsonBody(request.body);
const account = requireWebActionAccount(this.#accounts, body.userId);
const product = typeof body.productId === 'string' ? this.#catalogue.byId(body.productId) : undefined;
if (!account) return jsonResponse({ ok: false, message: NO_ACCOUNT }, 'store web buy: unknown account');
if (!product || product.gjnCostCents === undefined) {
return jsonResponse({ ok: false, message: NO_PRODUCT }, 'store web buy: unknown product');
}
if (body.payMethod !== undefined && body.payMethod !== 'gjn' && body.payMethod !== 'free') {
return jsonResponse({ ok: false, message: { zh: '不支持这种支付方式。', en: 'Unsupported payment method.' } }, 'store web buy: bad payMethod');
}
const isFree = body.payMethod === 'free';
let outcome: GjnPurchaseOutcome = { ok: false, reason: 'NOT_FOUND' };
let cartProductIds: readonly string[] = [];
const now = serverTimeNow();
this.#profiles.updateWhen(account.userId, (saved) => {
outcome = isFree ? buyFreeStoreProduct(saved, product, now) : buyGjnProduct(saved, product, now);
cartProductIds = storeCartIds(saved);
if (!outcome.ok) return false;
if (cartProductIds.includes(product.id)) {
cartProductIds = cartProductIds.filter((id) => id !== product.id);
setStoreCart(saved, cartProductIds);
}
return true;
});
const modeTag = isFree ? 'free' : 'gjn';
return jsonResponse({ ok: outcome.ok, cartProductIds, message: purchaseMessage(outcome, product, isFree) }, `store web buy ${product.id} (${modeTag}): ${outcome.ok ? 'OK' : outcome.reason}`);
}
#cart(request: ServiceRequest): ServiceResponse {
const body = parseJsonBody(request.body);
const account = requireWebActionAccount(this.#accounts, body.userId);
if (!account) return jsonResponse({ ok: false, message: NO_ACCOUNT }, 'store cart: unknown account');
const { action, productId } = body;
if ((action !== 'add' && action !== 'remove') || typeof productId !== 'string' || !productId) {
return jsonResponse({ ok: false }, 'store cart: invalid action');
}
const product = this.#catalogue.byId(productId);
let cartProductIds: readonly string[] = [];
let message: LocalizedText | undefined;
const now = serverTimeNow();
this.#profiles.updateWhen(account.userId, (saved) => {
const previous = storeCartIds(saved);
cartProductIds = previous;
if (action === 'add') {
if (!product || product.gjnCostCents === undefined) {
message = NO_PRODUCT;
return false;
}
if (!canBuyGjnProduct(saved, product, now)) {
message = alreadyBoughtMessage(product);
return false;
}
if (previous.includes(productId)) return false;
cartProductIds = [...previous, productId];
} else {
if (!previous.includes(productId)) return false;
cartProductIds = previous.filter((id) => id !== productId);
}
setStoreCart(saved, cartProductIds);
return true;
});
return jsonResponse({ ok: !message, cartProductIds, message }, `store cart ${action} ${productId}`);
}
#checkout(request: ServiceRequest): ServiceResponse {
const body = parseJsonBody(request.body);
const account = requireWebActionAccount(this.#accounts, body.userId);
if (!account) return jsonResponse({ ok: false, message: NO_ACCOUNT }, 'store checkout: unknown account');
const { productIds, payMethod } = body;
if (!Array.isArray(productIds) || productIds.length === 0 || (payMethod !== 'gjn' && payMethod !== 'free')) {
return jsonResponse({ ok: false, message: CART_CHANGED }, 'store checkout: invalid order');
}
const now = serverTimeNow();
let cartProductIds: readonly string[] = [];
let message = CART_CHANGED;
const saved = this.#profiles.updateWhen(account.userId, (profile) => {
cartProductIds = storeCartIds(profile);
if (cartProductIds.length !== productIds.length || cartProductIds.some((id, i) => id !== productIds[i])) return false;
const products = cartProductIds.map((id) => this.#catalogue.byId(id));
if (!products.every((product): product is StoreProduct => product !== undefined)) {
message = NO_PRODUCT;
return false;
}
const outcome = buyStoreCart(profile, products, payMethod, now);
message = checkoutMessage(outcome, products, payMethod);
if (!outcome.ok) return false;
clearStoreCart(profile);
cartProductIds = [];
return true;
});
return jsonResponse({ ok: !!saved, cartProductIds, message }, `store checkout (${payMethod}): ${saved ? 'OK' : 'refused'}`);
}
#redeem(request: ServiceRequest): ServiceResponse {
const body = parseJsonBody(request.body);
const account = requireWebActionAccount(this.#accounts, body.userId);
if (!account) return jsonResponse({ ok: false, message: NO_ACCOUNT }, 'store web redeem: unknown account');
const code = typeof body.code === 'string' ? body.code : '';
let outcome: RedeemOutcome | undefined;
const now = serverTimeNow();
this.#profiles.updateWhen(account.userId, (saved) => {
outcome = redeemStoreCode(saved, code, now, this.#redeemCodes);
return outcome.ok;
});
return jsonResponse({ ok: outcome?.ok ?? false, message: outcome?.message }, `store web redeem ${code.trim() || '(empty)'}`);
}
}
function purchaseMessage(outcome: GjnPurchaseOutcome, product: StoreProduct, isFree: boolean): LocalizedText {
const cost = gjnText(product.gjnCostCents ?? 0);
if (outcome.ok) {
return isFree
? {
zh: `老福爷付过了!已直接获得「${product.title.zh}」。关闭商店窗口后机库会自动刷新。`,
en: `Paid by 老福爷! Claimed "${product.title.en}". Close the store window to refresh the hangar.`,
}
: {
zh: `已购买「${product.title.zh}」,花费 ${cost} GJN。关闭商店窗口后机库会自动刷新。`,
en: `Bought "${product.title.en}" for ${cost} GJN. Close the store window to refresh the hangar.`,
};
}
if (outcome.reason === 'NOT_ENOUGH_GJN') {
return { zh: `GJN 不够:需要 ${cost} GJN。可直接点「老福爷付过了」,或在"兑换码"页用 GJN 充值码补充。`, en: `Not enough GJN: ${cost} GJN needed. Use "老福爷付过了" or a GJN code on the Redeem tab.` };
}
if (outcome.reason === 'ALREADY_BOUGHT') return alreadyBoughtMessage(product);
return { zh: '这个商品现在买不了。', en: 'This product cannot be bought right now.' };
}
function alreadyBoughtMessage(product: StoreProduct): LocalizedText {
return {
zh: `你已经拥有「${product.title.zh}」中的载具。`,
en: `You already own the vehicles in "${product.title.en}".`,
};
}
function checkoutMessage(
outcome: StoreCheckoutOutcome,
products: readonly StoreProduct[],
payMethod: 'gjn' | 'free',
): LocalizedText {
if (outcome.ok) {
const count = products.length;
const cost = gjnText(outcome.costCents);
return payMethod === 'free'
? { zh: `老福爷付过了!已领取 ${count} 件商品。关闭商城窗口后机库会自动刷新。`,
en: `Paid by 老福爷! Claimed ${count} items. Close the store to refresh the hangar.` }
: { zh: `已购买 ${count} 件商品,花费 ${cost} GJN。关闭商城窗口后机库会自动刷新。`,
en: `Bought ${count} items for ${cost} GJN. Close the store to refresh the hangar.` };
}
if (outcome.reason === 'NOT_ENOUGH_GJN') {
const cost = gjnText(outcome.costCents);
return { zh: `购物车共需 ${cost} GJN,当前余额不足。`, en: `Your cart costs ${cost} GJN. Your balance is too low.` };
}
const product = products.find((item) => item.id === outcome.productId);
return outcome.reason === 'ALREADY_BOUGHT' && product ? alreadyBoughtMessage(product) : NO_PRODUCT;
}
function webProduct(product: StoreProduct, owned: boolean): Record<string, unknown> {
const vehicles = product.vehicles;
const firstVehicle = vehicles?.[0];
const ranks = vehicles ? [...new Set(vehicles.map((vehicle) => vehicle.rank))].sort((a, b) => a - b) : undefined;
return {
id: product.id,
...(product.guid ? { guid: product.guid } : {}),
...(product.artworkGroup ? { artworkGroup: product.artworkGroup } : {}),
kind: product.kind,
title: product.title,
gjnCostCents: product.gjnCostCents,
...(product.goldIncome ? { goldIncome: product.goldIncome } : {}),
...(product.silverIncome ? { silverIncome: product.silverIncome } : {}),
...(product.premiumDays ? { premiumDays: product.premiumDays } : {}),
...(firstVehicle && vehicles ? {
unitName: firstVehicle.name,
country: firstVehicle.country,
rank: ranks![ranks!.length - 1]!,
ranks,
vehicles: vehicles.map((vehicle, index) => ({
unitName: vehicle.name,
country: vehicle.country,
rank: vehicle.rank,
title: product.vehicleTitles?.[index] ?? { en: vehicle.name, zh: vehicle.name },
})),
} : {}),
owned,
};
}