Add store and marketplace deep links and coupon resale
Register bundle GUIDs at build time and return local store item URLs. Route marketplace item links to the requested coupon. Update vehicle and cosmetic prices from the marketplace snapshot and support selling coupons back to the system at the configured fee. Type checking, an isolated build, and local service checks passed. In-game acceptance is pending.
This commit is contained in:
1 parent
b6964658d7
commit
c01ee8ae5a
16 files changed
+588
-250
No files matched your search
@@ -14,7 +14,7 @@ import {
|
||||
type LocalizedItemDef,
|
||||
type MarketplaceListing,
|
||||
} from '../itemdef-types.ts';
|
||||
import type { MarketplaceTuning } from '../marketplace-tuning.ts';
|
||||
import { cosmeticCouponPrice, type MarketplaceTuning } from '../marketplace-tuning.ts';
|
||||
|
||||
const ICON_BY_KIND = {
|
||||
skin: '!#ui/gameuiskin#item_type_skin.svg',
|
||||
@@ -84,7 +84,7 @@ function buildSingleDecorCoupon(decor: MarketplaceDecorCoupon, tuning: Marketpla
|
||||
readonly action: CouponAction;
|
||||
readonly listing: MarketplaceListing;
|
||||
} {
|
||||
const { gjnCents, quality } = tuning.cosmeticCoupons[decor.kind];
|
||||
const { gjnCents, quality } = cosmeticCouponPrice(tuning, decor.kind, decor.resourceKey);
|
||||
const color = QUALITY_COLORS[quality] ?? '';
|
||||
const hashName = `${decor.kind}_${decor.itemdefId}`;
|
||||
const def = makeLocalizedItemDef(decor.itemdefId, {
|
||||
@@ -120,7 +120,7 @@ function buildSingleUnlockCoupon(unlock: MarketplaceUnlockCoupon, tuning: Market
|
||||
readonly action: CouponAction;
|
||||
readonly listing: MarketplaceListing;
|
||||
} {
|
||||
const { gjnCents, quality } = tuning.cosmeticCoupons.unlock;
|
||||
const { gjnCents, quality } = cosmeticCouponPrice(tuning, 'unlock', unlock.unlockId);
|
||||
const color = QUALITY_COLORS[quality] ?? '';
|
||||
const hashName = `unlock_${unlock.itemdefId}`;
|
||||
const def = makeLocalizedItemDef(unlock.itemdefId, {
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* Selling marketplace coupons back to the system (offline design, local verification): the player
|
||||
* gets the listing price minus `sellFeeRate` (tuning/marketplace.jsonc, default 15 % like the
|
||||
* official market's `market_fee`) credited as GJN; the coupons leave `extInventory`.
|
||||
*/
|
||||
import type { BlkBlock } from '@wto/blk';
|
||||
import { addGjnCents } from '../profile/profile-currency.ts';
|
||||
import { consumeExternalItem, externalInventoryItems } from '../profile/profile-external-inventory.ts';
|
||||
import type { InventoryCatalogue } from './itemdef-catalogue.ts';
|
||||
|
||||
export type MarketSellOutcome =
|
||||
| { readonly ok: true; readonly creditedCents: number }
|
||||
| { readonly ok: false; readonly reason: 'NOT_FOUND' | 'NOT_ENOUGH_ITEMS' };
|
||||
|
||||
/** GJN hundredths the player receives for one coupon of this price. */
|
||||
export function sellProceedsCents(priceCents: number, feeRate: number): number {
|
||||
return Math.floor(priceCents * (1 - feeRate));
|
||||
}
|
||||
|
||||
export function sellMarketplaceCoupon(
|
||||
profile: BlkBlock,
|
||||
catalogue: InventoryCatalogue,
|
||||
itemdefId: number,
|
||||
quantity: number,
|
||||
feeRate: number,
|
||||
): MarketSellOutcome {
|
||||
const listing = catalogue.marketplaceListing(itemdefId);
|
||||
if (!listing || !Number.isSafeInteger(quantity) || quantity < 1) return { ok: false, reason: 'NOT_FOUND' };
|
||||
const stacks = externalInventoryItems(profile).filter((item) => item.itemDefId === itemdefId);
|
||||
if (stacks.reduce((sum, item) => sum + item.quantity, 0) < quantity) return { ok: false, reason: 'NOT_ENOUGH_ITEMS' };
|
||||
|
||||
let remaining = quantity;
|
||||
for (const stack of stacks) {
|
||||
if (remaining === 0) break;
|
||||
const take = Math.min(stack.quantity, remaining);
|
||||
if (!consumeExternalItem(profile, stack.itemId, take)) return { ok: false, reason: 'NOT_ENOUGH_ITEMS' };
|
||||
remaining -= take;
|
||||
}
|
||||
const credited = sellProceedsCents(listing.gjnCostCents, feeRate) * quantity;
|
||||
addGjnCents(profile, credited);
|
||||
return { ok: true, creditedCents: credited };
|
||||
}
|
||||
@@ -24,6 +24,8 @@ import {
|
||||
import { buyFreeMarketplaceCoupon, buyMarketplaceCoupon } from './inventory-rules.ts';
|
||||
import type { InventoryCatalogue } from './itemdef-catalogue.ts';
|
||||
import type { MarketplaceListing } from './itemdef-types.ts';
|
||||
import { sellMarketplaceCoupon, sellProceedsCents, type MarketSellOutcome } from './marketplace-sell.ts';
|
||||
import type { MarketplaceTuning } from './marketplace-tuning.ts';
|
||||
|
||||
const MARKET_WEB = createStaticWebSite(new URL('./web/', import.meta.url));
|
||||
|
||||
@@ -34,19 +36,21 @@ export class MarketplaceService implements Service {
|
||||
readonly #catalogue: InventoryCatalogue;
|
||||
readonly #notifyInventoryChanged: () => void;
|
||||
readonly #maxPerPurchase: number;
|
||||
readonly #sellFeeRate: number;
|
||||
|
||||
constructor(
|
||||
accounts: AccountStore,
|
||||
profiles: PlayerProfiles,
|
||||
catalogue: InventoryCatalogue,
|
||||
notifyInventoryChanged: () => void,
|
||||
maxPerPurchase: number,
|
||||
tuning: Pick<MarketplaceTuning, 'maxPerPurchase' | 'sellFeeRate'>,
|
||||
) {
|
||||
this.#accounts = accounts;
|
||||
this.#profiles = profiles;
|
||||
this.#catalogue = catalogue;
|
||||
this.#notifyInventoryChanged = notifyInventoryChanged;
|
||||
this.#maxPerPurchase = maxPerPurchase;
|
||||
this.#maxPerPurchase = tuning.maxPerPurchase;
|
||||
this.#sellFeeRate = tuning.sellFeeRate;
|
||||
}
|
||||
|
||||
accepts(request: ServiceRequest): boolean {
|
||||
@@ -62,6 +66,7 @@ export class MarketplaceService implements Service {
|
||||
|
||||
if (subPath === '/api/state' && request.method === 'GET') return this.#state(request);
|
||||
if (subPath === '/api/buy' && request.method === 'POST') return this.#buy(request);
|
||||
if (subPath === '/api/sell' && request.method === 'POST') return this.#sell(request);
|
||||
|
||||
return MARKET_WEB.serve(subPath, `marketplace web (${request.query.get('n') ?? 'index'})`)
|
||||
?? { status: 404, headers: { 'content-type': 'text/plain; charset=utf-8' }, body: 'Not found', logNotes: { summary: `marketplace 404: ${subPath}` } };
|
||||
@@ -82,6 +87,7 @@ export class MarketplaceService implements Service {
|
||||
|
||||
const listings = this.#catalogue.marketplaceListings().map((listing) => ({
|
||||
...listing,
|
||||
sellCents: sellProceedsCents(listing.gjnCostCents, this.#sellFeeRate),
|
||||
couponCount: heldCounts.get(listing.itemdefId) ?? 0,
|
||||
alreadyActivated: profile ? isListingAlreadyActivated(profile, listing, unlockedSet) : false,
|
||||
}));
|
||||
@@ -90,10 +96,36 @@ export class MarketplaceService implements Service {
|
||||
accounts: this.#accounts.all().map((a) => ({ userId: a.userId, login: a.login, nick: a.nick })),
|
||||
currentUserId: account?.userId ?? '',
|
||||
balance,
|
||||
sellFeeRate: this.#sellFeeRate,
|
||||
listings,
|
||||
}, `marketplace state (${account?.userId ?? 'no-account'})`);
|
||||
}
|
||||
|
||||
#sell(request: ServiceRequest): ServiceResponse {
|
||||
const body = parseJsonBody(request.body);
|
||||
const account = requireWebActionAccount(this.#accounts, body.userId);
|
||||
if (!account) {
|
||||
return jsonResponse({ ok: false, message: { zh: '没有找到这个账号,请先在右上角选择账号。', en: 'Account not found. Pick an account at the top right first.' } }, 'marketplace sell: unknown account');
|
||||
}
|
||||
const itemdefId = Number(body.itemdefId ?? 0);
|
||||
const quantity = body.quantity === undefined ? 1 : Number(body.quantity);
|
||||
let outcome: MarketSellOutcome = { ok: false, reason: 'NOT_FOUND' };
|
||||
this.#profiles.updateWhen(account.userId, (saved) => {
|
||||
outcome = sellMarketplaceCoupon(saved, this.#catalogue, itemdefId, quantity, this.#sellFeeRate);
|
||||
return outcome.ok;
|
||||
});
|
||||
const result = outcome as MarketSellOutcome;
|
||||
if (!result.ok) {
|
||||
return jsonResponse({ ok: false, message: { zh: '库存里没有足够的这张兑换券。', en: 'Not enough of this coupon in your inventory.' } }, `marketplace sell ${itemdefId}: ${result.reason}`);
|
||||
}
|
||||
this.#notifyInventoryChanged();
|
||||
const amount = gjnText(result.creditedCents);
|
||||
return jsonResponse({
|
||||
ok: true,
|
||||
message: { zh: `已卖给系统 ×${quantity},到账 ${amount} GJN(已扣 ${Math.round(this.#sellFeeRate * 100)}% 手续费)。`, en: `Sold ${quantity} to the system for ${amount} GJN (after the ${Math.round(this.#sellFeeRate * 100)}% fee).` },
|
||||
}, `marketplace sell ${itemdefId} x${quantity} (+${amount} GJN)`);
|
||||
}
|
||||
|
||||
#buy(request: ServiceRequest): ServiceResponse {
|
||||
const body = parseJsonBody(request.body);
|
||||
const account = requireWebActionAccount(this.#accounts, body.userId);
|
||||
|
||||
@@ -15,10 +15,14 @@ interface RankTier<T> {
|
||||
|
||||
export interface MarketplaceTuning {
|
||||
readonly maxPerPurchase: number;
|
||||
/** Fraction kept by the system when a player sells a coupon back (0.15 = 15 %). */
|
||||
readonly sellFeeRate: number;
|
||||
readonly vehiclePriceByVehicle: ReadonlyMap<string, number>;
|
||||
readonly vehiclePriceByRank: readonly RankTier<number>[];
|
||||
readonly vehicleQualityByRank: readonly RankTier<number>[];
|
||||
readonly cosmeticCoupons: Readonly<Record<CosmeticCouponKind, CouponPrice>>;
|
||||
/** Per-resource GJN-hundredths overrides for decor / unlock coupons (official market snapshot). */
|
||||
readonly cosmeticPriceByResource: ReadonlyMap<string, number>;
|
||||
}
|
||||
|
||||
const COSMETIC_KINDS: readonly CosmeticCouponKind[] = ['skin', 'decal', 'attachable', 'unlock'];
|
||||
@@ -27,8 +31,10 @@ export function readMarketplaceTuning(file: TuningReader): MarketplaceTuning {
|
||||
const vehicles = file.object('vehicleCoupons');
|
||||
const prices = vehicles.object('byVehicle');
|
||||
const cosmetic = file.object('cosmeticCoupons');
|
||||
const byResource = cosmetic.object('byResource');
|
||||
return {
|
||||
maxPerPurchase: file.int('maxPerPurchase', { min: 1 }),
|
||||
sellFeeRate: file.number('sellFeeRate', { min: 0, max: 0.99 }),
|
||||
vehiclePriceByVehicle: new Map(prices.keys().map((name) => [name, prices.money(name, { min: 0.01 })])),
|
||||
vehiclePriceByRank: rankTiers(vehicles, 'byRank', (entry) => entry.money('gjn', { min: 0.01 })),
|
||||
vehicleQualityByRank: rankTiers(vehicles, 'qualityByRank', (entry) => entry.int('quality', { min: 1, max: 5 })),
|
||||
@@ -36,9 +42,16 @@ export function readMarketplaceTuning(file: TuningReader): MarketplaceTuning {
|
||||
const entry = cosmetic.object(kind);
|
||||
return [kind, { gjnCents: entry.money('gjn', { min: 0.01 }), quality: entry.int('quality', { min: 1, max: 5 }) }];
|
||||
})) as Record<CosmeticCouponKind, CouponPrice>,
|
||||
cosmeticPriceByResource: new Map(byResource.keys().map((key) => [key, byResource.money(key, { min: 0.01 })])),
|
||||
};
|
||||
}
|
||||
|
||||
/** A decor / unlock coupon's price: the per-resource snapshot price, else the kind's default. */
|
||||
export function cosmeticCouponPrice(tuning: MarketplaceTuning, kind: CosmeticCouponKind, resource: string): CouponPrice {
|
||||
const base = tuning.cosmeticCoupons[kind];
|
||||
return { gjnCents: tuning.cosmeticPriceByResource.get(resource) ?? base.gjnCents, quality: base.quality };
|
||||
}
|
||||
|
||||
/** A vehicle coupon's price in GJN hundredths and its quality. */
|
||||
export function vehicleCouponPrice(tuning: MarketplaceTuning, vehicle: string, rank: number): CouponPrice {
|
||||
return {
|
||||
|
||||
@@ -77,7 +77,7 @@ export async function startLocalService(options: LocalServiceOptions): Promise<R
|
||||
const labels = datasets.load(uiLabels);
|
||||
const { profiles, research, equipment } = setUpProfiles(options.dataFolder, gameFiles, datasets, tuning, { accounts, clans }, vehicles);
|
||||
const { clanEconomy: squadronEconomy, ...catalogues } = loadDomainCatalogues(datasets, tuning, vehicles, labels);
|
||||
const webUi = new WebUiService(datasets.load(webIcons), labels);
|
||||
const webUi = new WebUiService(datasets.load(webIcons), labels, options.dataFolder);
|
||||
gameFiles.releasePacks();
|
||||
|
||||
let matching: MatchingService | undefined;
|
||||
@@ -85,8 +85,8 @@ export async function startLocalService(options: LocalServiceOptions): Promise<R
|
||||
|
||||
const router = new Router([
|
||||
webUi,
|
||||
new StoreService(accounts, profiles, catalogues.store, tuning.redeemCodes),
|
||||
new MarketplaceService(accounts, profiles, catalogues.inventory, notifyInventoryChanged, tuning.marketplace.maxPerPurchase),
|
||||
new StoreService(accounts, profiles, catalogues.store, tuning.redeemCodes, options.port),
|
||||
new MarketplaceService(accounts, profiles, catalogues.inventory, notifyInventoryChanged, tuning.marketplace),
|
||||
new InventoryService(accounts, profiles, catalogues.inventory),
|
||||
new LoginService(accounts),
|
||||
new CharService(actionTable({
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
* Pure domain catalogue: protocol-layer DataBlock serialization for `cln_get_entitlements_price_ex`
|
||||
* lives in `char/actions/store-actions.ts`.
|
||||
*/
|
||||
import { singleVehiclePackId, stableGuid } from '@wto/blk';
|
||||
import type { StoreBundleGuids } from '../game-data/datasets/store-bundles.ts';
|
||||
import type { UiLabels } from '../game-data/datasets/ui-labels.ts';
|
||||
import type { LocalizedText, UnitNamesMap } from '../game-data/datasets/unit-names.ts';
|
||||
@@ -148,6 +149,7 @@ function buildVehiclePackProducts(
|
||||
});
|
||||
return {
|
||||
id: pack.id,
|
||||
guid: stableGuid(pack.id),
|
||||
kind: 'vehicle-pack',
|
||||
chapter: 'bonuses',
|
||||
title: resolveMultiPackTitle(pack.id, pack.naming, packVehicles[0]!, names, labels),
|
||||
@@ -165,8 +167,10 @@ function buildVehiclePackProducts(
|
||||
.map((vehicle) => {
|
||||
const content = vehiclePackContent(tuning, vehicle.name, vehicle.rank);
|
||||
const unitLabel = names[vehicle.name] ?? { en: vehicle.name, zh: vehicle.name };
|
||||
const id = singleVehiclePackId(vehicle.name);
|
||||
return {
|
||||
id: `wto_pack_${vehicle.name}`,
|
||||
id,
|
||||
guid: stableGuid(id),
|
||||
kind: 'vehicle-pack',
|
||||
chapter: 'bonuses',
|
||||
title: { en: `${unitLabel.en} Pack`, zh: `${unitLabel.zh} 礼包` },
|
||||
|
||||
@@ -22,8 +22,8 @@ export class StoreService implements Service {
|
||||
readonly #yuplay: YuplayStoreApi;
|
||||
readonly #web: StoreWebApi;
|
||||
|
||||
constructor(accounts: AccountStore, profiles: PlayerProfiles, catalogue: StoreCatalogue, redeemCodes: RedeemTuning) {
|
||||
this.#yuplay = new YuplayStoreApi(accounts, profiles, catalogue, redeemCodes);
|
||||
constructor(accounts: AccountStore, profiles: PlayerProfiles, catalogue: StoreCatalogue, redeemCodes: RedeemTuning, port: number) {
|
||||
this.#yuplay = new YuplayStoreApi(accounts, profiles, catalogue, redeemCodes, `http://127.0.0.1:${port}${PAGE_PREFIX}`);
|
||||
this.#web = new StoreWebApi(accounts, profiles, catalogue, redeemCodes);
|
||||
}
|
||||
|
||||
|
||||
@@ -123,6 +123,7 @@ function webProduct(product: StoreProduct, owned: boolean): Record<string, unkno
|
||||
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 } : {}),
|
||||
kind: product.kind,
|
||||
title: product.title,
|
||||
gjnCostCents: product.gjnCostCents,
|
||||
|
||||
@@ -25,8 +25,11 @@ export class YuplayStoreApi {
|
||||
readonly #profiles: PlayerProfiles;
|
||||
readonly #catalogue: StoreCatalogue;
|
||||
readonly #redeemCodes: RedeemTuning;
|
||||
/** Base of the local store page, e.g. http://127.0.0.1:47115/store; item_info.php `url` points into it. */
|
||||
readonly #storePageBase: string;
|
||||
|
||||
constructor(accounts: AccountStore, profiles: PlayerProfiles, catalogue: StoreCatalogue, redeemCodes: RedeemTuning) {
|
||||
constructor(accounts: AccountStore, profiles: PlayerProfiles, catalogue: StoreCatalogue, redeemCodes: RedeemTuning, storePageBase: string) {
|
||||
this.#storePageBase = storePageBase;
|
||||
this.#accounts = accounts;
|
||||
this.#profiles = profiles;
|
||||
this.#catalogue = catalogue;
|
||||
@@ -58,7 +61,9 @@ export class YuplayStoreApi {
|
||||
discount_mul: 1.0,
|
||||
discount_till: 0,
|
||||
title: product.title.en,
|
||||
url: '',
|
||||
// The game opens this page for the pack's own store entry (onlineShopModel.nut
|
||||
// doBrowserPurchaseByGuid → get_url_for_purchase → yu_itemInfo.cpp `url`).
|
||||
url: `${this.#storePageBase}?item=${encodeURIComponent(guid)}`,
|
||||
short_desc: product.title.en,
|
||||
shop_price_curr: 'gjn',
|
||||
multi_purch: product.kind !== 'vehicle-pack',
|
||||
|
||||
Reference in new issue
Block a user