From b68f321b84730424ce5b135db421437f80159e26 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Wed, 25 Nov 2026 08:26:11 +0800 Subject: [PATCH] refactor(server): separate inventory, squadron, and web logic Split inventory definition generation by category and select chest contents deterministically. Move squadron queries, membership, and lifecycle into focused modules and enforce role permissions. Serve store and marketplace pages as static files with shared web helpers. Share profile field readers and keep response encoding in the protocol modules. Restrict cloud settings to registered blocks. Type checking and the save CLI ran successfully. In-game acceptance is pending. --- packages/build/src/index.ts | 2 +- packages/build/src/main-pack.ts | 2 + packages/build/src/network/login-overrides.ts | 11 +- .../src/char/actions/action-table.ts | 22 +- .../src/char/actions/clan-actions.ts | 290 ++------ .../char/actions/clan-moderation-actions.ts | 120 ++++ .../src/char/actions/inventory-actions.ts | 31 +- .../src/char/actions/player-card-actions.ts | 102 +-- .../char/actions/squadron-research-actions.ts | 55 ++ .../src/char/actions/store-actions.ts | 43 +- packages/local-service/src/clans/clan-blk.ts | 230 +++--- .../local-service/src/clans/clan-lifecycle.ts | 270 ++++++++ .../src/clans/clan-membership.ts | 265 +++++++ .../local-service/src/clans/clan-queries.ts | 82 +++ .../local-service/src/clans/clan-seeds.ts | 2 +- .../local-service/src/clans/clan-store.ts | 655 +++--------------- .../cloud-settings/cloud-settings-store.ts | 10 +- .../local-service/src/inventory/chest-defs.ts | 178 +++++ .../src/inventory/coupons/cosmetic-coupons.ts | 154 ++++ .../src/inventory/coupons/vehicle-coupons.ts | 120 ++++ .../src/inventory/inventory-rules.ts | 51 +- .../src/inventory/inventory-service.ts | 37 +- .../src/inventory/itemdef-catalogue.ts | 548 ++------------- .../src/inventory/itemdef-types.ts | 79 ++- .../src/inventory/marketplace-page.ts | 300 -------- .../src/inventory/marketplace-service.ts | 73 +- .../src/inventory/recycling-defs.ts | 157 +++++ .../src/inventory/trophy-catalogue.ts | 139 ++-- .../local-service/src/inventory/web/app.js | 138 ++++ .../src/inventory/web/index.html | 49 ++ .../src/inventory/web/styles.css | 109 +++ .../local-service/src/profile/blk-fields.ts | 29 + .../local-service/src/profile/profile-clan.ts | 36 +- .../src/profile/profile-currency.ts | 27 +- .../src/profile/profile-entitlements.ts | 20 +- .../src/profile/profile-external-inventory.ts | 35 +- .../src/profile/profile-trophies-log.ts | 7 +- .../local-service/src/research/price-table.ts | 44 +- .../src/store/store-catalogue.ts | 203 +++--- .../local-service/src/store/store-service.ts | 66 +- .../src/store/{store-page.ts => web/app.js} | 177 +---- .../local-service/src/store/web/index.html | 51 ++ .../local-service/src/store/web/styles.css | 128 ++++ .../local-service/src/web-ui/web-helpers.ts | 79 +++ 44 files changed, 2793 insertions(+), 2433 deletions(-) create mode 100644 packages/local-service/src/char/actions/clan-moderation-actions.ts create mode 100644 packages/local-service/src/char/actions/squadron-research-actions.ts create mode 100644 packages/local-service/src/clans/clan-lifecycle.ts create mode 100644 packages/local-service/src/clans/clan-membership.ts create mode 100644 packages/local-service/src/clans/clan-queries.ts create mode 100644 packages/local-service/src/inventory/chest-defs.ts create mode 100644 packages/local-service/src/inventory/coupons/cosmetic-coupons.ts create mode 100644 packages/local-service/src/inventory/coupons/vehicle-coupons.ts delete mode 100644 packages/local-service/src/inventory/marketplace-page.ts create mode 100644 packages/local-service/src/inventory/recycling-defs.ts create mode 100644 packages/local-service/src/inventory/web/app.js create mode 100644 packages/local-service/src/inventory/web/index.html create mode 100644 packages/local-service/src/inventory/web/styles.css create mode 100644 packages/local-service/src/profile/blk-fields.ts rename packages/local-service/src/store/{store-page.ts => web/app.js} (50%) create mode 100644 packages/local-service/src/store/web/index.html create mode 100644 packages/local-service/src/store/web/styles.css create mode 100644 packages/local-service/src/web-ui/web-helpers.ts diff --git a/packages/build/src/index.ts b/packages/build/src/index.ts index 77965e4..a894d00 100644 --- a/packages/build/src/index.ts +++ b/packages/build/src/index.ts @@ -7,7 +7,7 @@ export { NETWORK_CONFIG_PATH, rebuildCharPack, type CharPackResult } from './cha export { patchExecutable, type ExecutableResult } from './executable.ts'; export { assertWritableCopy, GAME_FILES } from './game-copy.ts'; export { loadGuiPatches, rebuildGuiPack, type GuiPackResult, type GuiScriptPatch } from './gui-pack.ts'; -export { ENGINE_SETTINGS_PATH, EXTRA_STORE_BUNDLE_GUIDS, rebuildMainPack, type MainPackResult } from './main-pack.ts'; +export { ENGINE_SETTINGS_PATH, EXTRA_STORE_BUNDLE_GUID_MAP, EXTRA_STORE_BUNDLE_GUIDS, rebuildMainPack, type MainPackResult } from './main-pack.ts'; export { redirectAddresses, type AddressChange } from './network/address-rewrite.ts'; export { hostPort, localEndpoint, localUrl, type LocalEndpoint } from './network/local-endpoint.ts'; export { redirectNetworkConfig, type NetworkRedirectReport } from './network/redirect-network-config.ts'; diff --git a/packages/build/src/main-pack.ts b/packages/build/src/main-pack.ts index 99897da..1bf1d8d 100644 --- a/packages/build/src/main-pack.ts +++ b/packages/build/src/main-pack.ts @@ -32,6 +32,8 @@ export const EXTRA_STORE_BUNDLE_GUIDS: ReadonlyArray> = Object.fromEntries(EXTRA_STORE_BUNDLE_GUIDS); + export interface MainPackResult { readonly pack: Uint8Array; readonly addresses: readonly AddressChange[]; diff --git a/packages/build/src/network/login-overrides.ts b/packages/build/src/network/login-overrides.ts index 2ec3f63..43e180a 100644 --- a/packages/build/src/network/login-overrides.ts +++ b/packages/build/src/network/login-overrides.ts @@ -7,11 +7,12 @@ * certain (https://auth.gaijinent.com/login.php); the others are matched by name to the * addresses in the executable's string table. * - * The host-only keys (authHost, ssoHost, storeApiHost, authFallbackHost) are intentionally not - * set: they replace only the host name and keep port 443, and turning the host into 127.0.0.1 - * would strip the original Host header and bypass wto_ws.dll's redirection. Leaving the Gaijin - * host names in place lets wto_ws.dll resolve them to 127.0.0.2 and route their TLS connections - * to the local service port with the original Host header intact. + * The host-only keys (authHost, ssoHost, storeApiHost, authFallbackHost) and `fallbackIP` are + * intentionally not set: the host keys replace only the host name while keeping port 443, and + * `fallbackIP` (yu_init.cpp) substitutes a bare IP literal on port 443 when DNS fails — both + * strip the original Host/SNI domain and bypass wto_ws.dll's DNS-based routing. Leaving the + * Gaijin host names in place lets wto_ws.dll resolve them to 127.0.0.2 and route their TLS + * connections to the local service port with the original Host and SNI intact. */ import { localUrl, type LocalEndpoint } from './local-endpoint.ts'; diff --git a/packages/local-service/src/char/actions/action-table.ts b/packages/local-service/src/char/actions/action-table.ts index 7d95e68..04eb6ee 100644 --- a/packages/local-service/src/char/actions/action-table.ts +++ b/packages/local-service/src/char/actions/action-table.ts @@ -7,14 +7,9 @@ import type { ResearchRules } from '../../research/research-rules.ts'; import type { CharActionHandler } from '../char-action.ts'; import { acceptEula } from './agreement-actions.ts'; import { - buyNotResearchedClanUnitAction, - clanAcceptCandidateAction, clanChangeInfoAction, - clanChangeMemberRoleAction, clanCreateAction, clanDisbandAction, - clanDismissMemberAction, - clanEditBlacklistAction, clanFindByPrefixAction, clanGetAction, clanGetLeaderboardAction, @@ -22,15 +17,24 @@ import { clanLeaveAction, clanMembershipRequestAction, clanMembersUpgradeAction, - clanRejectCandidateAction, clansListShortInfoAction, clanSetMembershipReqAction, clanSyncProfileAction, clanUpgradeAction, - flushClanExpToUnitAction, - setClanBestRewardsAction, - setResearchClanUnitAction, } from './clan-actions.ts'; +import { + clanAcceptCandidateAction, + clanChangeMemberRoleAction, + clanDismissMemberAction, + clanEditBlacklistAction, + clanRejectCandidateAction, + setClanBestRewardsAction, +} from './clan-moderation-actions.ts'; +import { + buyNotResearchedClanUnitAction, + flushClanExpToUnitAction, + setResearchClanUnitAction, +} from './squadron-research-actions.ts'; import { bulkSetGblkAction, getGeneralBlkAction, getMetaBlkAction, setGeneralBlkAction } from './cloud-settings-actions.ts'; import { bulkTrainCrews, trainCrew } from './crew-actions.ts'; import { buyUnlockAction } from './unlock-actions.ts'; diff --git a/packages/local-service/src/char/actions/clan-actions.ts b/packages/local-service/src/char/actions/clan-actions.ts index f551206..dde6a1f 100644 --- a/packages/local-service/src/char/actions/clan-actions.ts +++ b/packages/local-service/src/char/actions/clan-actions.ts @@ -1,9 +1,10 @@ /** - * Char action handlers for squadrons (clans) and squadron vehicle research - *. + * Char action handlers for squadron (clan) directory, creation, upgrades, and player + * membership requests. Officer moderation and squadron vehicle + * research live in `clan-moderation-actions.ts` and `squadron-research-actions.ts`. */ import { emptyBlock, findBlock, findParam, type BlkBlock } from '@wto/blk'; -import type { AccountStore } from '../../accounts/account-store.ts'; +import type { Account, AccountStore } from '../../accounts/account-store.ts'; import { toClanInfoBlk, toClanLeaderboardRowBlk, @@ -11,33 +12,27 @@ import { toClanShortInfoBlk, } from '../../clans/clan-blk.ts'; import type { ClanStore } from '../../clans/clan-store.ts'; -import type { ClanBestReward } from '../../clans/clan-types.ts'; import { clientProfile } from '../../profile/client-profile.ts'; import type { PlayerProfiles } from '../../profile/player-profiles.ts'; +import type { Price } from '../../profile/profile-currency.ts'; import type { ResearchRules } from '../../research/research-rules.ts'; import type { RuleOutcome } from '../../research/rule-outcome.ts'; -import { - buyNotResearchedSquadronUnit, - chooseSquadronResearchTarget, - flushSquadronExpToUnit, -} from '../../research/squadron-research.ts'; -import type { Price } from '../../profile/profile-currency.ts'; import type { CharActionContext, CharActionHandler } from '../char-action.ts'; import { withAccount } from './account-context.ts'; import { boolParam, intParam, stringParam } from './payload-params.ts'; -function priceFromPayload(payload: BlkBlock): Price { +export function priceFromClanPayload(payload: BlkBlock): Price { return { silverLions: intParam(payload, 'cost') ?? 0, goldenEagles: intParam(payload, 'costGold') ?? 0, }; } -function clanProfileRuleAction( +export function clanProfileRuleAction( profiles: PlayerProfiles, accounts: AccountStore, clans: ClanStore, - run: (context: CharActionContext, profile: BlkBlock, account: ReturnType & {}) => RuleOutcome, + run: (context: CharActionContext, profile: BlkBlock, account: Account) => RuleOutcome, ): CharActionHandler { return (context) => withAccount(context, accounts, (account) => { let outcome: RuleOutcome = { ok: false, refusal: 'BAD_PARAMS' }; @@ -51,11 +46,26 @@ function clanProfileRuleAction( }); } +export function clanParamOrHeader(context: CharActionContext, name: string): string | undefined { + return (context.payload ? stringParam(context.payload, name) : undefined) ?? context.headerParam(name); +} + +export function clanStrOrIntId(context: CharActionContext, name: string): string | undefined { + if (context.payload) { + const param = findParam(context.payload, name)?.value; + if (param?.type === 'string' && param.value !== '') return param.value; + if (param?.type === 'int64') return param.value.toString(); + if (param?.type === 'int') return String(param.value); + } + const hdr = context.headerParam(name); + return hdr && hdr !== '' ? hdr : undefined; +} + export function clanGetAction(accounts: AccountStore, clans: ClanStore): CharActionHandler { return (context) => withAccount(context, accounts, (account) => { - const clanId = strOrIntId(context, 'clanId') ?? strOrIntId(context, '_id'); - const clanName = paramOrHeader(context, 'clanName'); - const clanTag = paramOrHeader(context, 'clanTag'); + const clanId = clanStrOrIntId(context, 'clanId') ?? clanStrOrIntId(context, '_id'); + const clanName = clanParamOrHeader(context, 'clanName'); + const clanTag = clanParamOrHeader(context, 'clanTag'); const clan = (!clanId && !clanName && !clanTag) ? clans.clanOfUser(account.userId)?.clan : clans.findClan({ clanId, clanName, clanTag }); @@ -76,10 +86,7 @@ export function clanGetLeaderboardAction(clans: ClanStore): CharActionHandler { filterNotFull: payload ? stringParam(payload, 'filterNotFull') === 'on' : false, filterAutoAccept: payload ? stringParam(payload, 'filterAutoAccept') === 'on' : false, }); - return { - kind: 'data', - blk: { name: '', params: [], blocks: rows.map((r) => toClanLeaderboardRowBlk(r.clan, r.pos)) }, - }; + return { kind: 'data', blk: { name: '', params: [], blocks: rows.map((r) => toClanLeaderboardRowBlk(r.clan, r.pos)) } }; }; } @@ -96,10 +103,7 @@ export function clanFindByPrefixAction(clans: ClanStore): CharActionHandler { filterNotFull: payload ? stringParam(payload, 'filterNotFull') === 'on' : false, filterAutoAccept: payload ? stringParam(payload, 'filterAutoAccept') === 'on' : false, }); - return { - kind: 'data', - blk: { name: '', params: [], blocks: rows.map((r) => toClanLeaderboardRowBlk(r.clan, r.pos)) }, - }; + return { kind: 'data', blk: { name: '', params: [], blocks: rows.map((r) => toClanLeaderboardRowBlk(r.clan, r.pos)) } }; }; } @@ -119,7 +123,7 @@ export function clansListShortInfoAction(clans: ClanStore): CharActionHandler { export function clanGetLogAction(accounts: AccountStore, clans: ClanStore): CharActionHandler { return (context) => withAccount(context, accounts, (account) => { - const clanId = strOrIntId(context, '_id') ?? strOrIntId(context, 'clanId'); + const clanId = clanStrOrIntId(context, '_id') ?? clanStrOrIntId(context, 'clanId'); const clan = clanId && clanId !== '-1' ? clans.byId(clanId) : clans.clanOfUser(account.userId)?.clan; if (!clan) return { kind: 'data', blk: emptyBlock() }; const count = (context.payload && intParam(context.payload, 'count')) ?? 20; @@ -129,15 +133,10 @@ export function clanGetLogAction(accounts: AccountStore, clans: ClanStore): Char }); } -export function clanCreateAction( - profiles: PlayerProfiles, - accounts: AccountStore, - clans: ClanStore, - rules: ResearchRules, -): CharActionHandler { +export function clanCreateAction(profiles: PlayerProfiles, accounts: AccountStore, clans: ClanStore, rules: ResearchRules): CharActionHandler { return clanProfileRuleAction(profiles, accounts, clans, (context, profile, account) => { const payload = context.payload; - const offered = payload && priceFromPayload(payload); + const offered = payload && priceFromClanPayload(payload); if (!payload || !offered) return { ok: false, refusal: 'BAD_PARAMS' }; const rawType = stringParam(payload, 'type'); return clans.createClan(profile, account, rules.clanEconomy, { @@ -153,16 +152,11 @@ export function clanCreateAction( }); } -export function clanChangeInfoAction( - profiles: PlayerProfiles, - accounts: AccountStore, - clans: ClanStore, - rules: ResearchRules, -): CharActionHandler { +export function clanChangeInfoAction(profiles: PlayerProfiles, accounts: AccountStore, clans: ClanStore, rules: ResearchRules): CharActionHandler { return clanProfileRuleAction(profiles, accounts, clans, (context, profile, account) => { const payload = context.payload; if (!payload) return { ok: false, refusal: 'BAD_PARAMS' }; - const clanId = strOrIntId(context, '_id') ?? '-1'; + const clanId = clanStrOrIntId(context, '_id') ?? '-1'; const rawStatus = stringParam(payload, 'status'); return clans.editClanInfo(profile, account, rules.clanEconomy, clanId, { name: stringParam(payload, 'name'), @@ -176,16 +170,11 @@ export function clanChangeInfoAction( }); } -export function clanUpgradeAction( - profiles: PlayerProfiles, - accounts: AccountStore, - clans: ClanStore, - rules: ResearchRules, -): CharActionHandler { +export function clanUpgradeAction(profiles: PlayerProfiles, accounts: AccountStore, clans: ClanStore, rules: ResearchRules): CharActionHandler { return clanProfileRuleAction(profiles, accounts, clans, (context, profile, account) => { const payload = context.payload; if (!payload) return { ok: false, refusal: 'BAD_PARAMS' }; - const clanId = strOrIntId(context, '_id') ?? '-1'; + const clanId = clanStrOrIntId(context, '_id') ?? '-1'; return clans.upgradeClanToNormal(profile, account, rules.clanEconomy, clanId, { tag: stringParam(payload, 'tag') ?? '', desc: stringParam(payload, 'desc') ?? '', @@ -194,14 +183,9 @@ export function clanUpgradeAction( }); } -export function clanMembersUpgradeAction( - profiles: PlayerProfiles, - accounts: AccountStore, - clans: ClanStore, - rules: ResearchRules, -): CharActionHandler { +export function clanMembersUpgradeAction(profiles: PlayerProfiles, accounts: AccountStore, clans: ClanStore, rules: ResearchRules): CharActionHandler { return clanProfileRuleAction(profiles, accounts, clans, (context, profile, account) => { - const clanId = strOrIntId(context, '_id') ?? '-1'; + const clanId = clanStrOrIntId(context, '_id') ?? '-1'; return clans.upgradeMembersLimit(profile, account, rules.clanEconomy, clanId); }); } @@ -209,214 +193,40 @@ export function clanMembersUpgradeAction( export function clanSetMembershipReqAction(accounts: AccountStore, clans: ClanStore): CharActionHandler { return (context) => withAccount(context, accounts, (account) => { const payload = context.payload; - const clanId = strOrIntId(context, '_id') ?? '-1'; + const clanId = clanStrOrIntId(context, '_id') ?? '-1'; const reqBlk = payload && findBlock(payload, 'membership_req'); const autoaccept = (payload && boolParam(payload, 'autoaccept')) ?? false; - clans.setMembershipRequirements(clanId, account, reqBlk, autoaccept); + if (!clans.setMembershipRequirements(clanId, account, reqBlk, autoaccept)) { + return { kind: 'error', code: 'NOT_AVAILABLE' }; + } return { kind: 'done' }; }); } -export function clanMembershipRequestAction( - profiles: PlayerProfiles, - accounts: AccountStore, - clans: ClanStore, -): CharActionHandler { +export function clanMembershipRequestAction(profiles: PlayerProfiles, accounts: AccountStore, clans: ClanStore): CharActionHandler { return clanProfileRuleAction(profiles, accounts, clans, (context, profile, account) => { - const clanId = strOrIntId(context, '_id') ?? strOrIntId(context, 'requestedClanId'); - const clanName = paramOrHeader(context, 'name'); - const clanTag = paramOrHeader(context, 'tag'); + const clanId = clanStrOrIntId(context, '_id') ?? clanStrOrIntId(context, 'requestedClanId'); + const clanName = clanParamOrHeader(context, 'name'); + const clanTag = clanParamOrHeader(context, 'tag'); const cancel = (context.payload && boolParam(context.payload, 'cancelRequest')) ?? false; - const comment = paramOrHeader(context, 'comments'); + const comment = clanParamOrHeader(context, 'comments'); return clans.requestOrCancelMembership(profile, account, { clanId, clanName, clanTag, cancel, comment }); }); } -export function clanLeaveAction( - profiles: PlayerProfiles, - accounts: AccountStore, - clans: ClanStore, -): CharActionHandler { +export function clanLeaveAction(profiles: PlayerProfiles, accounts: AccountStore, clans: ClanStore): CharActionHandler { return clanProfileRuleAction(profiles, accounts, clans, (_context, profile, account) => clans.leaveClan(profile, account)); } -export function clanDisbandAction( - profiles: PlayerProfiles, - accounts: AccountStore, - clans: ClanStore, -): CharActionHandler { +export function clanDisbandAction(profiles: PlayerProfiles, accounts: AccountStore, clans: ClanStore): CharActionHandler { return clanProfileRuleAction(profiles, accounts, clans, (context, profile, account) => - clans.disbandClan(profile, account, strOrIntId(context, 'requestedClanId') ?? strOrIntId(context, '_id'))); + clans.disbandClan(profile, account, clanStrOrIntId(context, 'requestedClanId') ?? clanStrOrIntId(context, '_id'))); } -export function clanSyncProfileAction( - profiles: PlayerProfiles, - accounts: AccountStore, - clans: ClanStore, -): CharActionHandler { +export function clanSyncProfileAction(profiles: PlayerProfiles, accounts: AccountStore, clans: ClanStore): CharActionHandler { return (context) => withAccount(context, accounts, (account) => { const updated = profiles.update(account.userId, (saved) => clans.syncProfile(saved, account)); return { kind: 'data', blk: clientProfile(updated, account, clans) }; }); } - -export function clanAcceptCandidateAction( - profiles: PlayerProfiles, - accounts: AccountStore, - clans: ClanStore, -): CharActionHandler { - return (context) => withAccount(context, accounts, (account) => { - const targetUid = strOrIntId(context, 'userid') ?? ''; - const clanId = strOrIntId(context, '_id'); - const role = (context.payload && intParam(context.payload, 'role')) ?? 3; - const targetAccount = accounts.byUserId(targetUid); - if (!targetUid || !clans.acceptCandidate(account, clanId, targetUid, targetAccount?.nick ?? `Pilot_${targetUid}`, role)) { - return { kind: 'error', code: 'NOT_AVAILABLE' }; - } - if (targetAccount) { - profiles.update(targetAccount.userId, (saved) => clans.syncProfile(saved, targetAccount)); - } - return { kind: 'done' }; - }); -} - -export function clanRejectCandidateAction( - profiles: PlayerProfiles, - accounts: AccountStore, - clans: ClanStore, -): CharActionHandler { - return (context) => withAccount(context, accounts, (account) => { - const targetUid = strOrIntId(context, 'userid') ?? ''; - const clanId = strOrIntId(context, '_id'); - const comments = paramOrHeader(context, 'comments') ?? ''; - if (!targetUid || !clans.rejectCandidate(account, clanId, targetUid, comments)) { - return { kind: 'error', code: 'NOT_AVAILABLE' }; - } - const targetAccount = accounts.byUserId(targetUid); - if (targetAccount) { - profiles.update(targetAccount.userId, (saved) => clans.syncProfile(saved, targetAccount)); - } - return { kind: 'done' }; - }); -} - -export function clanDismissMemberAction( - profiles: PlayerProfiles, - accounts: AccountStore, - clans: ClanStore, -): CharActionHandler { - return (context) => withAccount(context, accounts, (account) => { - const targetUid = strOrIntId(context, 'userid') ?? ''; - const comments = paramOrHeader(context, 'comments') ?? ''; - if (!targetUid || !clans.dismissMember(account, targetUid, comments)) { - return { kind: 'error', code: 'NOT_AVAILABLE' }; - } - const targetAccount = accounts.byUserId(targetUid); - if (targetAccount) { - profiles.update(targetAccount.userId, (saved) => clans.syncProfile(saved, targetAccount)); - } - return { kind: 'done' }; - }); -} - -export function clanChangeMemberRoleAction( - profiles: PlayerProfiles, - accounts: AccountStore, - clans: ClanStore, -): CharActionHandler { - return (context) => withAccount(context, accounts, (account) => { - const targetUid = strOrIntId(context, 'userid') ?? ''; - const newRole = (context.payload && intParam(context.payload, 'role')) ?? 0; - if (!targetUid || !newRole || !clans.changeMemberRole(account, targetUid, newRole)) { - return { kind: 'error', code: 'NOT_AVAILABLE' }; - } - const targetAccount = accounts.byUserId(targetUid); - if (targetAccount) { - profiles.update(targetAccount.userId, (saved) => clans.syncProfile(saved, targetAccount)); - } - return { kind: 'done' }; - }); -} - -export function clanEditBlacklistAction(accounts: AccountStore, clans: ClanStore): CharActionHandler { - return (context) => withAccount(context, accounts, (account) => { - const targetUid = strOrIntId(context, 'userid') ?? ''; - const clanId = strOrIntId(context, '_id'); - const mode = paramOrHeader(context, 'mode') ?? 'addToBlackList'; - const comments = paramOrHeader(context, 'comments') ?? ''; - const targetNick = accounts.byUserId(targetUid)?.nick ?? ''; - if (!targetUid || !clans.editBlacklist(account, clanId, targetUid, targetNick, mode === 'addToBlackList', comments)) { - return { kind: 'error', code: 'NOT_AVAILABLE' }; - } - return { kind: 'done' }; - }); -} - -export function setClanBestRewardsAction(accounts: AccountStore, clans: ClanStore): CharActionHandler { - return (context) => withAccount(context, accounts, (account) => { - try { - const parsed = JSON.parse(context.rawText || '{}') as { clanId?: string; bestRewards?: ClanBestReward[] }; - const clanId = parsed.clanId ?? clans.clanOfUser(account.userId)?.clan.id; - if (clanId && Array.isArray(parsed.bestRewards)) { - clans.setBestRewards(clanId, parsed.bestRewards); - } - } catch { - // Ignore malformed optional JSON - } - return { kind: 'done' }; - }); -} - -export function setResearchClanUnitAction( - profiles: PlayerProfiles, - accounts: AccountStore, - clans: ClanStore, - rules: ResearchRules, -): CharActionHandler { - return clanProfileRuleAction(profiles, accounts, clans, (context, profile, account) => { - const unit = context.payload && stringParam(context.payload, 'unit'); - if (!unit) return { ok: false, refusal: 'BAD_PARAMS' }; - const auto = (context.payload && boolParam(context.payload, 'auto')) ?? false; - return chooseSquadronResearchTarget(profile, rules, unit, auto, clans.earnedSquadronExpOf(account.userId)); - }); -} - -export function flushClanExpToUnitAction( - profiles: PlayerProfiles, - accounts: AccountStore, - clans: ClanStore, - rules: ResearchRules, -): CharActionHandler { - return clanProfileRuleAction(profiles, accounts, clans, (_context, profile, account) => - flushSquadronExpToUnit(profile, rules, clans.earnedSquadronExpOf(account.userId))); -} - -export function buyNotResearchedClanUnitAction( - profiles: PlayerProfiles, - accounts: AccountStore, - clans: ClanStore, - rules: ResearchRules, -): CharActionHandler { - return clanProfileRuleAction(profiles, accounts, clans, (context, profile) => { - const unit = context.payload && stringParam(context.payload, 'unit'); - const offered = context.payload && priceFromPayload(context.payload); - if (!unit || !offered) return { ok: false, refusal: 'BAD_PARAMS' }; - return buyNotResearchedSquadronUnit(profile, rules, unit, offered); - }); -} - -function paramOrHeader(context: CharActionContext, name: string): string | undefined { - return (context.payload ? stringParam(context.payload, name) : undefined) ?? context.headerParam(name); -} - -function strOrIntId(context: CharActionContext, name: string): string | undefined { - if (context.payload) { - const param = findParam(context.payload, name)?.value; - if (param?.type === 'string' && param.value !== '') return param.value; - if (param?.type === 'int64') return param.value.toString(); - if (param?.type === 'int') return String(param.value); - } - const hdr = context.headerParam(name); - return hdr && hdr !== '' ? hdr : undefined; -} diff --git a/packages/local-service/src/char/actions/clan-moderation-actions.ts b/packages/local-service/src/char/actions/clan-moderation-actions.ts new file mode 100644 index 0000000..b59ef37 --- /dev/null +++ b/packages/local-service/src/char/actions/clan-moderation-actions.ts @@ -0,0 +1,120 @@ +/** + * Char action handlers for squadron officer moderation, blacklist, and best-rewards metadata + * (`ano_clan_*`, `cln_set_clan_best_rewards`; implementation notes). + */ +import type { AccountStore } from '../../accounts/account-store.ts'; +import type { ClanStore } from '../../clans/clan-store.ts'; +import type { ClanBestReward } from '../../clans/clan-types.ts'; +import type { PlayerProfiles } from '../../profile/player-profiles.ts'; +import type { CharActionHandler } from '../char-action.ts'; +import { withAccount } from './account-context.ts'; +import { clanParamOrHeader, clanStrOrIntId } from './clan-actions.ts'; +import { intParam } from './payload-params.ts'; + +export function clanAcceptCandidateAction( + profiles: PlayerProfiles, + accounts: AccountStore, + clans: ClanStore, +): CharActionHandler { + return (context) => withAccount(context, accounts, (account) => { + const targetUid = clanStrOrIntId(context, 'userid') ?? ''; + const clanId = clanStrOrIntId(context, '_id'); + const role = (context.payload && intParam(context.payload, 'role')) ?? 3; + const targetAccount = accounts.byUserId(targetUid); + if (!targetUid || !clans.acceptCandidate(account, clanId, targetUid, targetAccount?.nick ?? `Pilot_${targetUid}`, role)) { + return { kind: 'error', code: 'NOT_AVAILABLE' }; + } + if (targetAccount) { + profiles.update(targetAccount.userId, (saved) => clans.syncProfile(saved, targetAccount)); + } + return { kind: 'done' }; + }); +} + +export function clanRejectCandidateAction( + profiles: PlayerProfiles, + accounts: AccountStore, + clans: ClanStore, +): CharActionHandler { + return (context) => withAccount(context, accounts, (account) => { + const targetUid = clanStrOrIntId(context, 'userid') ?? ''; + const clanId = clanStrOrIntId(context, '_id'); + const comments = clanParamOrHeader(context, 'comments') ?? ''; + if (!targetUid || !clans.rejectCandidate(account, clanId, targetUid, comments)) { + return { kind: 'error', code: 'NOT_AVAILABLE' }; + } + const targetAccount = accounts.byUserId(targetUid); + if (targetAccount) { + profiles.update(targetAccount.userId, (saved) => clans.syncProfile(saved, targetAccount)); + } + return { kind: 'done' }; + }); +} + +export function clanDismissMemberAction( + profiles: PlayerProfiles, + accounts: AccountStore, + clans: ClanStore, +): CharActionHandler { + return (context) => withAccount(context, accounts, (account) => { + const targetUid = clanStrOrIntId(context, 'userid') ?? ''; + const comments = clanParamOrHeader(context, 'comments') ?? ''; + if (!targetUid || !clans.dismissMember(account, targetUid, comments)) { + return { kind: 'error', code: 'NOT_AVAILABLE' }; + } + const targetAccount = accounts.byUserId(targetUid); + if (targetAccount) { + profiles.update(targetAccount.userId, (saved) => clans.syncProfile(saved, targetAccount)); + } + return { kind: 'done' }; + }); +} + +export function clanChangeMemberRoleAction( + profiles: PlayerProfiles, + accounts: AccountStore, + clans: ClanStore, +): CharActionHandler { + return (context) => withAccount(context, accounts, (account) => { + const targetUid = clanStrOrIntId(context, 'userid') ?? ''; + const newRole = (context.payload && intParam(context.payload, 'role')) ?? 0; + if (!targetUid || !newRole || !clans.changeMemberRole(account, targetUid, newRole)) { + return { kind: 'error', code: 'NOT_AVAILABLE' }; + } + const targetAccount = accounts.byUserId(targetUid); + if (targetAccount) { + profiles.update(targetAccount.userId, (saved) => clans.syncProfile(saved, targetAccount)); + } + return { kind: 'done' }; + }); +} + +export function clanEditBlacklistAction(accounts: AccountStore, clans: ClanStore): CharActionHandler { + return (context) => withAccount(context, accounts, (account) => { + const targetUid = clanStrOrIntId(context, 'userid') ?? ''; + const clanId = clanStrOrIntId(context, '_id'); + const mode = clanParamOrHeader(context, 'mode') ?? 'addToBlackList'; + const comments = clanParamOrHeader(context, 'comments') ?? ''; + const targetNick = accounts.byUserId(targetUid)?.nick ?? ''; + if (!targetUid || !clans.editBlacklist(account, clanId, targetUid, targetNick, mode === 'addToBlackList', comments)) { + return { kind: 'error', code: 'NOT_AVAILABLE' }; + } + return { kind: 'done' }; + }); +} + +export function setClanBestRewardsAction(accounts: AccountStore, clans: ClanStore): CharActionHandler { + return (context) => withAccount(context, accounts, (account) => { + let parsed: { clanId?: string; bestRewards?: ClanBestReward[] }; + try { + parsed = JSON.parse(context.rawText || '{}') as { clanId?: string; bestRewards?: ClanBestReward[] }; + } catch { + return { kind: 'error', code: 'BAD_JSON' }; + } + const clanId = parsed.clanId ?? clans.clanOfUser(account.userId)?.clan.id; + if (!clanId || !Array.isArray(parsed.bestRewards) || !clans.setBestRewards(clanId, account.userId, parsed.bestRewards)) { + return { kind: 'error', code: 'NOT_AVAILABLE' }; + } + return { kind: 'done' }; + }); +} diff --git a/packages/local-service/src/char/actions/inventory-actions.ts b/packages/local-service/src/char/actions/inventory-actions.ts index 7254bae..6ec3fdb 100644 --- a/packages/local-service/src/char/actions/inventory-actions.ts +++ b/packages/local-service/src/char/actions/inventory-actions.ts @@ -14,9 +14,9 @@ import { consumeInventoryCoupon, exchangeInventoryItems, multiConsumeInventoryItems, + parseExchangeItemsRequest, purchaseExternalInventoryItem, recycleClassicItems, - type ExchangeMaterialInput, } from '../../inventory/inventory-rules.ts'; import { buyTrophy } from '../../inventory/trophy-catalogue.ts'; import { clientProfile } from '../../profile/client-profile.ts'; @@ -125,29 +125,20 @@ export function inventoryExchangeAction( rules: ResearchRules, ): CharActionHandler { return (context) => withAccount(context, accounts, (account) => { - let parsed: Record; - try { - parsed = JSON.parse(context.rawText) as Record; - } catch { - return { kind: 'error', code: 'BAD_JSON' }; - } - const outputItemDefId = Number(parsed.outputitemdefid ?? 0); - const quantity = Number(parsed.quantity ?? 1); - const rawMaterials = Array.isArray(parsed.materials) ? parsed.materials : []; - const materials: ExchangeMaterialInput[] = rawMaterials.flatMap((m) => { - if (typeof m !== 'object' || m === null) return []; - const rec = m as Record; - return [{ - itemid: String(rec.itemid ?? ''), - itemdefid: Number(rec.itemdefid ?? 0), - quantity: Number(rec.quantity ?? 0), - }]; - }); + const parsed = parseExchangeItemsRequest(context.rawText); + if (!parsed) return { kind: 'error', code: 'BAD_JSON' }; let delta: unknown[] | undefined; let errorCode = 'EXCHANGE_FAILED'; profiles.updateWhen(account.userId, (saved) => { - const res = exchangeInventoryItems(saved, account.userId, rules.inventory, outputItemDefId, quantity, materials); + const res = exchangeInventoryItems( + saved, + account.userId, + rules.inventory, + parsed.outputItemDefId, + parsed.quantity, + parsed.materials, + ); if (!res.ok) { errorCode = res.code; return false; diff --git a/packages/local-service/src/char/actions/player-card-actions.ts b/packages/local-service/src/char/actions/player-card-actions.ts index 26911d6..b97740c 100644 --- a/packages/local-service/src/char/actions/player-card-actions.ts +++ b/packages/local-service/src/char/actions/player-card-actions.ts @@ -11,18 +11,20 @@ * user/profileShowcasesData.nut, charRequestBlk): every saved showcase (showcase-rules.ts). */ import type { BlkBlock, BlkParam } from '@wto/blk'; -import type { AccountStore } from '../../accounts/account-store.ts'; +import type { Account, AccountStore } from '../../accounts/account-store.ts'; import type { ClanStore } from '../../clans/clan-store.ts'; +import type { ClanMemberRecord, ClanRecord } from '../../clans/clan-types.ts'; import { chooseTitle, saveAppearance } from '../../player-card/player-card-rules.ts'; import { currentShowcaseView, saveShowcase, showcasesAnswer } from '../../player-card/showcase-rules.ts'; -import type { ResearchRules } from '../../research/research-rules.ts'; import { appearance, chosenTitle } from '../../profile/profile-appearance.ts'; import { clanMembershipOf } from '../../profile/profile-clan.ts'; import type { PlayerProfiles } from '../../profile/player-profiles.ts'; +import type { ResearchRules } from '../../research/research-rules.ts'; +import type { TechTree } from '../../research/tech-tree.ts'; import type { CharActionHandler } from '../char-action.ts'; +import { withAccount } from './account-context.ts'; import { stringParam } from './payload-params.ts'; import { ruleAction } from './rule-answer.ts'; -import { withAccount } from './account-context.ts'; export function selectTitleAction(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler { return ruleAction(profiles, accounts, (payload) => { @@ -54,50 +56,58 @@ export function usersTerseInfoAction(profiles: PlayerProfiles, accounts: Account if (list === undefined) return { kind: 'error', code: 'BAD_PARAMS' }; const blocks = list.split(';').filter((uid) => uid !== '').map((uid): BlkBlock => { const account = accounts.byUserId(uid); - if (!account) { - const npc = clans?.npcMemberByUid(uid); - if (!npc) return { name: uid, params: [{ name: 'failed', value: { type: 'bool', value: true } }], blocks: [] }; - const npcFields: [string, string][] = [ - ['nick', npc.member.nick], - ['pilotIcon', npc.member.npcPilotIcon ?? 'cardicon_default'], - ['title', npc.member.npcTitle ?? ''], - ['clanTag', npc.clan.tag], - ['clanName', npc.clan.name], - ['background', ''], - ['frame', npc.member.npcFrame ?? ''], - ['shcType', npc.member.npcShowcaseUnit ? 'favorite_unit' : 'none'], - ]; - const npcBlocks: BlkBlock[] = npc.member.npcShowcaseUnit - ? [{ - name: 'showcase', - params: [{ name: 'unit', value: { type: 'string', value: npc.member.npcShowcaseUnit } }], - blocks: [], - }] - : [{ name: 'showcase', params: [], blocks: [] }]; - return { - name: uid, - params: npcFields.map(([name, value]): BlkParam => ({ name, value: { type: 'string', value } })), - blocks: npcBlocks, - }; - } - const profile = profiles.profileOf(account.userId); - clans?.syncProfile(profile, account); - const clanInfo = clanMembershipOf(profile); - const inClan = clanInfo.clanId !== '-1'; - const looks = appearance(profile); - const fields: [string, string][] = [ - ['nick', account.nick], - ['pilotIcon', looks.pilotIcon ?? ''], - ['title', chosenTitle(profile)], - ['clanTag', inClan ? clanInfo.clanTag : ''], - ['clanName', inClan ? clanInfo.clanName : ''], - ['background', looks.background ?? ''], - ['frame', looks.frame ?? ''], - ]; - const { type, showcase } = currentShowcaseView(profile, rules.techTree); - fields.push(['shcType', type]); - return { name: uid, params: fields.map(([name, value]): BlkParam => ({ name, value: { type: 'string', value } })), blocks: [showcase] }; + if (account) return accountTerseInfoBlk(uid, account, profiles, rules.techTree, clans); + const npc = clans?.npcMemberByUid(uid); + if (npc) return npcTerseInfoBlk(uid, npc.clan, npc.member); + return { name: uid, params: [{ name: 'failed', value: { type: 'bool', value: true } }], blocks: [] }; }); return { kind: 'data', blk: { name: '', params: [], blocks } }; }); } + +function accountTerseInfoBlk( + uid: string, + account: Account, + profiles: PlayerProfiles, + techTree: TechTree, + clans?: ClanStore, +): BlkBlock { + const profile = profiles.profileOf(account.userId); + clans?.syncProfile(profile, account); + const clanInfo = clanMembershipOf(profile); + const inClan = clanInfo.clanId !== '-1'; + const looks = appearance(profile); + const { type, showcase } = currentShowcaseView(profile, techTree); + const fields: ReadonlyArray = [ + ['nick', account.nick], + ['pilotIcon', looks.pilotIcon ?? ''], + ['title', chosenTitle(profile)], + ['clanTag', inClan ? clanInfo.clanTag : ''], + ['clanName', inClan ? clanInfo.clanName : ''], + ['background', looks.background ?? ''], + ['frame', looks.frame ?? ''], + ['shcType', type], + ]; + return { name: uid, params: toStringParams(fields), blocks: [showcase] }; +} + +function npcTerseInfoBlk(uid: string, clan: ClanRecord, member: ClanMemberRecord): BlkBlock { + const fields: ReadonlyArray = [ + ['nick', member.nick], + ['pilotIcon', member.npcPilotIcon ?? 'cardicon_default'], + ['title', member.npcTitle ?? ''], + ['clanTag', clan.tag], + ['clanName', clan.name], + ['background', ''], + ['frame', member.npcFrame ?? ''], + ['shcType', member.npcShowcaseUnit ? 'favorite_unit' : 'none'], + ]; + const showcase: BlkBlock = member.npcShowcaseUnit + ? { name: 'showcase', params: [{ name: 'unit', value: { type: 'string', value: member.npcShowcaseUnit } }], blocks: [] } + : { name: 'showcase', params: [], blocks: [] }; + return { name: uid, params: toStringParams(fields), blocks: [showcase] }; +} + +function toStringParams(fields: ReadonlyArray): BlkParam[] { + return fields.map(([name, value]) => ({ name, value: { type: 'string', value } })); +} diff --git a/packages/local-service/src/char/actions/squadron-research-actions.ts b/packages/local-service/src/char/actions/squadron-research-actions.ts new file mode 100644 index 0000000..2e24163 --- /dev/null +++ b/packages/local-service/src/char/actions/squadron-research-actions.ts @@ -0,0 +1,55 @@ +/** + * Char action handlers for squadron (clan) vehicle research and Golden-Eagle buyout + * (`cln_set_research_clan_unit`, `cln_flush_clan_exp_to_unit`, `cln_buy_not_researched_clans_unit`; + * implementation notes). + */ +import type { AccountStore } from '../../accounts/account-store.ts'; +import type { ClanStore } from '../../clans/clan-store.ts'; +import type { PlayerProfiles } from '../../profile/player-profiles.ts'; +import type { ResearchRules } from '../../research/research-rules.ts'; +import { + buyNotResearchedSquadronUnit, + chooseSquadronResearchTarget, + flushSquadronExpToUnit, +} from '../../research/squadron-research.ts'; +import type { CharActionHandler } from '../char-action.ts'; +import { clanProfileRuleAction, priceFromClanPayload } from './clan-actions.ts'; +import { boolParam, stringParam } from './payload-params.ts'; + +export function setResearchClanUnitAction( + profiles: PlayerProfiles, + accounts: AccountStore, + clans: ClanStore, + rules: ResearchRules, +): CharActionHandler { + return clanProfileRuleAction(profiles, accounts, clans, (context, profile, account) => { + const unit = context.payload && stringParam(context.payload, 'unit'); + if (!unit) return { ok: false, refusal: 'BAD_PARAMS' }; + const auto = (context.payload && boolParam(context.payload, 'auto')) ?? false; + return chooseSquadronResearchTarget(profile, rules, unit, auto, clans.earnedSquadronExpOf(account.userId)); + }); +} + +export function flushClanExpToUnitAction( + profiles: PlayerProfiles, + accounts: AccountStore, + clans: ClanStore, + rules: ResearchRules, +): CharActionHandler { + return clanProfileRuleAction(profiles, accounts, clans, (_context, profile, account) => + flushSquadronExpToUnit(profile, rules, clans.earnedSquadronExpOf(account.userId))); +} + +export function buyNotResearchedClanUnitAction( + profiles: PlayerProfiles, + accounts: AccountStore, + clans: ClanStore, + rules: ResearchRules, +): CharActionHandler { + return clanProfileRuleAction(profiles, accounts, clans, (context, profile) => { + const unit = context.payload && stringParam(context.payload, 'unit'); + const offered = context.payload && priceFromClanPayload(context.payload); + if (!unit || !offered) return { ok: false, refusal: 'BAD_PARAMS' }; + return buyNotResearchedSquadronUnit(profile, rules, unit, offered); + }); +} diff --git a/packages/local-service/src/char/actions/store-actions.ts b/packages/local-service/src/char/actions/store-actions.ts index 6c99314..33089e6 100644 --- a/packages/local-service/src/char/actions/store-actions.ts +++ b/packages/local-service/src/char/actions/store-actions.ts @@ -1,24 +1,26 @@ /** * Store char actions: - * - cln_get_entitlements_price_ex: returns the store catalogue BLK; + * - cln_get_entitlements_price_ex: encodes the store catalogue into Gaijin's entitlements BLK; * - cln_buy_entitlement: Golden-Eagle entitlement purchase (aces.exe 0x17a0f50 -> 0x2a1240 * sends `entitlement` and `costGold` in the HTTP headers, job type 5, answer applied as a * full profile update). Note: `cln_buy_entitlement_and_get_reward_for_day` is not referenced * anywhere in 2.61.0.37 GUI scripts and is intentionally not registered. */ +import { emptyBlock, setParam, type BlkBlock } from '@wto/blk'; import type { AccountStore } from '../../accounts/account-store.ts'; import { clientProfile } from '../../profile/client-profile.ts'; import type { PlayerProfiles } from '../../profile/player-profiles.ts'; import { serverTimeNow } from '../../profile/server-time.ts'; import type { ResearchRules } from '../../research/research-rules.ts'; import type { RuleOutcome } from '../../research/rule-outcome.ts'; +import type { StoreProduct } from '../../store/store-catalogue.ts'; import { buyGoldEntitlement } from '../../store/store-purchase.ts'; import type { CharActionHandler } from '../char-action.ts'; import { withAccount } from './account-context.ts'; import { intParam, stringParam } from './payload-params.ts'; export function entitlementsPriceEx(rules: ResearchRules): CharActionHandler { - const table = rules.store.entitlementsPriceBlk(); + const table = buildEntitlementsPriceBlk(rules.store.allProducts()); return () => ({ kind: 'data', blk: table }); } @@ -41,3 +43,40 @@ export function buyEntitlementAction(profiles: PlayerProfiles, accounts: Account return { kind: 'error', code: outcome.ok ? 'BAD_PARAMS' : outcome.refusal }; }); } + +function buildEntitlementsPriceBlk(products: readonly StoreProduct[]): BlkBlock { + const root = emptyBlock(); + for (const product of products) { + const block = emptyBlock(product.id); + setParam(block, 'chapter', { type: 'string', value: product.chapter }); + + if (product.kind === 'eagles') { + setParam(block, 'onlinePurchase', { type: 'bool', value: true }); + setParam(block, 'group', { type: 'string', value: 'eagles100' }); + setParam(block, 'useGroupAmount', { type: 'bool', value: true }); + setParam(block, 'goldIncome', { type: 'int', value: product.goldIncome! }); + } else if (product.kind === 'warpoints') { + setParam(block, 'group', { type: 'string', value: '1KWP' }); + setParam(block, 'useGroupAmount', { type: 'bool', value: true }); + setParam(block, 'wpIncome', { type: 'int', value: product.silverIncome! }); + setParam(block, 'goldCost', { type: 'int', value: product.goldCost! }); + } else if (product.kind === 'premium-gold') { + setParam(block, 'alias', { type: 'string', value: 'PremiumAccount' }); + setParam(block, 'group', { type: 'string', value: 'PremiumAccount' }); + setParam(block, 'ttl', { type: 'int', value: product.premiumDays! }); + setParam(block, 'goldCost', { type: 'int', value: product.goldCost! }); + } else if (product.kind === 'premium-gjn') { + setParam(block, 'onlinePurchase', { type: 'bool', value: true }); + setParam(block, 'alias', { type: 'string', value: 'PremiumAccount' }); + setParam(block, 'group', { type: 'string', value: 'PremiumAccount' }); + setParam(block, 'ttl', { type: 'int', value: product.premiumDays! }); + } else if (product.kind === 'vehicle-pack' && product.vehicle) { + setParam(block, 'onlinePurchase', { type: 'bool', value: true }); + setParam(block, 'aircraftGift', { type: 'string', value: product.vehicle.name }); + if (product.goldIncome) setParam(block, 'goldIncome', { type: 'int', value: product.goldIncome }); + } + + root.blocks.push(block); + } + return root; +} diff --git a/packages/local-service/src/clans/clan-blk.ts b/packages/local-service/src/clans/clan-blk.ts index b4234b6..3130d8f 100644 --- a/packages/local-service/src/clans/clan-blk.ts +++ b/packages/local-service/src/clans/clan-blk.ts @@ -7,13 +7,25 @@ * - `cln_clan_get_log` paginated clan event log (`clanRequests.nut`) */ import type { BlkBlock, BlkParam } from '@wto/blk'; -import type { ClanLogEntry, ClanMemberRecord, ClanRecord } from './clan-types.ts'; +import type { ClanLogEntry, ClanMemberRecord, ClanRecord, ClanStats } from './clan-types.ts'; export const MAX_ACTIVITY_PER_PERIOD = 360; export const MAX_CLAN_ACTIVITY = 20000; export const REWARD_PERIOD_DAYS = 3; export const HISTORY_DEPTH_DAYS = 14; +const CLAN_STAT_KEYS: ReadonlyArray = [ + 'dr_era5_arc', 'dr_era5_hist', 'dr_era5_sim', + 'akills_arc', 'akills_hist', 'akills_sim', + 'gkills_arc', 'gkills_hist', 'gkills_sim', + 'deaths_arc', 'deaths_hist', 'deaths_sim', + 'ftime_arc', 'ftime_hist', 'ftime_sim', +]; + +const OPTIONAL_LOG_STRING_KEYS: ReadonlyArray> = [ + 'uid', 'nick', 'role', 'old', 'new', 'name', 'type', 'tag', 'desc', 'slogan', 'region', 'announcement', 'status', 'comments', +]; + export function totalPeriodActivityOf(clan: ClanRecord): number { const sum = clan.members.reduce((acc, m) => acc + m.curActivity, 0); return Math.min(MAX_CLAN_ACTIVITY * 5, sum * 10); @@ -21,73 +33,6 @@ export function totalPeriodActivityOf(clan: ClanRecord): number { export function toClanInfoBlk(clan: ClanRecord, nowSec = Math.floor(Date.now() / 1000)): BlkBlock { const todayDay = Math.floor(nowSec / 86400); - const astat = buildAstatBlock(clan); - - const memberBlocks: BlkBlock[] = clan.members.map((m) => ({ - name: 'members', - params: [ - str('uid', m.uid), - str('nick', m.nick), - int('role', m.role), - int('date', m.joinDateSec), - ], - blocks: [], - })); - - const memberRatingsBlock: BlkBlock = { - name: 'member_ratings', - params: [], - blocks: clan.members.map((m) => ({ - name: m.uid, - params: [ - int('dr_era5_arc', m.ratingArc), - int('dr_era5_hist', m.ratingHist), - int('dr_era5_sim', m.ratingSim), - ], - blocks: [], - })), - }; - - const activityBlock: BlkBlock = { - name: 'activity', - params: [], - blocks: clan.members.map((m) => buildMemberActivityBlock(m, todayDay)), - }; - - const candidateBlocks: BlkBlock[] = clan.candidates.map((c) => ({ - name: 'candidates', - params: [ - str('uid', c.uid), - str('nick', c.nick), - str('comment', c.comment), - int('date', c.dateSec), - ], - blocks: [], - })); - - const blacklistBlocks: BlkBlock[] = clan.blacklist.map((b) => ({ - name: 'blacklist', - params: [ - str('uid', b.uid), - str('nick', b.nick), - str('initiator_uid', b.initiatorUid), - str('initiator_nick', b.initiatorNick), - str('comments', b.comments), - int('date', b.dateSec), - ], - blocks: [], - })); - - const bestRewardBlocks: BlkBlock[] = clan.bestRewards.map((r) => ({ - name: 'clanBestRewards', - params: [str('seasonName', r.seasonName), str('title', r.title)], - blocks: [], - })); - - const membershipReq = clan.membershipReqBlk - ? { ...structuredClone(clan.membershipReqBlk), name: 'membership_req' } - : { name: 'membership_req', params: [], blocks: [] }; - return { name: '', params: [ @@ -117,25 +62,36 @@ export function toClanInfoBlk(clan: ClanRecord, nowSec = Math.floor(Date.now() / int('nextRewardDayId', todayDay + REWARD_PERIOD_DAYS), ], blocks: [ - astat, - membershipReq, - ...memberBlocks, - memberRatingsBlock, - activityBlock, - ...candidateBlocks, - ...blacklistBlocks, - ...bestRewardBlocks, + buildAstatBlock(clan), + buildMembershipReqBlock(clan), + ...clan.members.map(memberToBlk), + buildMemberRatingsBlock(clan), + { name: 'activity', params: [], blocks: clan.members.map((m) => buildMemberActivityBlock(m, todayDay)) }, + ...clan.candidates.map((c) => ({ + name: 'candidates', + params: [str('uid', c.uid), str('nick', c.nick), str('comment', c.comment), int('date', c.dateSec)], + blocks: [], + })), + ...clan.blacklist.map((b) => ({ + name: 'blacklist', + params: [ + str('uid', b.uid), str('nick', b.nick), + str('initiator_uid', b.initiatorUid), str('initiator_nick', b.initiatorNick), + str('comments', b.comments), int('date', b.dateSec), + ], + blocks: [], + })), + ...clan.bestRewards.map((r) => ({ + name: 'clanBestRewards', + params: [str('seasonName', r.seasonName), str('title', r.title)], + blocks: [], + })), ], }; } export function toClanLeaderboardRowBlk(clan: ClanRecord, pos: number): BlkBlock { const periodAct = totalPeriodActivityOf(clan); - const astat = buildAstatBlock(clan); - const membershipReq = clan.membershipReqBlk - ? { ...structuredClone(clan.membershipReqBlk), name: 'membership_req' } - : { name: 'membership_req', params: [], blocks: [] }; - return { name: 'clan', params: [ @@ -153,23 +109,9 @@ export function toClanLeaderboardRowBlk(clan: ClanRecord, pos: number): BlkBlock int('pos', pos), int('activity', periodAct), int('clan_activity_by_periods', periodAct), - int('dr_era5_arc', clan.stats.dr_era5_arc), - int('dr_era5_hist', clan.stats.dr_era5_hist), - int('dr_era5_sim', clan.stats.dr_era5_sim), - int('akills_arc', clan.stats.akills_arc), - int('akills_hist', clan.stats.akills_hist), - int('akills_sim', clan.stats.akills_sim), - int('gkills_arc', clan.stats.gkills_arc), - int('gkills_hist', clan.stats.gkills_hist), - int('gkills_sim', clan.stats.gkills_sim), - int('deaths_arc', clan.stats.deaths_arc), - int('deaths_hist', clan.stats.deaths_hist), - int('deaths_sim', clan.stats.deaths_sim), - int('ftime_arc', clan.stats.ftime_arc), - int('ftime_hist', clan.stats.ftime_hist), - int('ftime_sim', clan.stats.ftime_sim), + ...statParams(clan.stats), ], - blocks: [astat, membershipReq], + blocks: [buildAstatBlock(clan), buildMembershipReqBlock(clan)], }; } @@ -208,17 +150,39 @@ export function toClanLogBlk( const page = sorted.slice(0, Math.max(1, count)); const nextMark = sorted.length > page.length ? String(page[page.length - 1]!.id) : ''; - - const params: BlkParam[] = []; - if (nextMark) params.push(str('lastMark', nextMark)); - return { name: '', - params, + params: nextMark ? [str('lastMark', nextMark)] : [], blocks: page.map(logEntryToBlk), }; } +function memberToBlk(m: ClanMemberRecord): BlkBlock { + return { + name: 'members', + params: [str('uid', m.uid), str('nick', m.nick), int('role', m.role), int('date', m.joinDateSec)], + blocks: [], + }; +} + +function buildMemberRatingsBlock(clan: ClanRecord): BlkBlock { + return { + name: 'member_ratings', + params: [], + blocks: clan.members.map((m) => ({ + name: m.uid, + params: [int('dr_era5_arc', m.ratingArc), int('dr_era5_hist', m.ratingHist), int('dr_era5_sim', m.ratingSim)], + blocks: [], + })), + }; +} + +function buildMembershipReqBlock(clan: ClanRecord): BlkBlock { + return clan.membershipReqBlk + ? { ...structuredClone(clan.membershipReqBlk), name: 'membership_req' } + : { name: 'membership_req', params: [], blocks: [] }; +} + function logEntryToBlk(entry: ClanLogEntry): BlkBlock { const params: BlkParam[] = [ str('ev', entry.ev), @@ -226,20 +190,10 @@ function logEntryToBlk(entry: ClanLogEntry): BlkBlock { str('uId', entry.uId), str('uN', entry.uN), ]; - if (entry.uid !== undefined) params.push(str('uid', entry.uid)); - if (entry.nick !== undefined) params.push(str('nick', entry.nick)); - if (entry.role !== undefined) params.push(str('role', entry.role)); - if (entry.old !== undefined) params.push(str('old', entry.old)); - if (entry.new !== undefined) params.push(str('new', entry.new)); - if (entry.name !== undefined) params.push(str('name', entry.name)); - if (entry.type !== undefined) params.push(str('type', entry.type)); - if (entry.tag !== undefined) params.push(str('tag', entry.tag)); - if (entry.desc !== undefined) params.push(str('desc', entry.desc)); - if (entry.slogan !== undefined) params.push(str('slogan', entry.slogan)); - if (entry.region !== undefined) params.push(str('region', entry.region)); - if (entry.announcement !== undefined) params.push(str('announcement', entry.announcement)); - if (entry.status !== undefined) params.push(str('status', entry.status)); - if (entry.comments !== undefined) params.push(str('comments', entry.comments)); + for (const key of OPTIONAL_LOG_STRING_KEYS) { + const val = entry[key]; + if (val !== undefined) params.push(str(key, val)); + } return { name: 'log', params, blocks: [] }; } @@ -250,43 +204,21 @@ function buildAstatBlock(clan: ClanRecord): BlkBlock { params: [ int('activity', periodAct), int('clan_activity_by_periods', periodAct), - int('dr_era5_arc', clan.stats.dr_era5_arc), - int('dr_era5_hist', clan.stats.dr_era5_hist), - int('dr_era5_sim', clan.stats.dr_era5_sim), - int('akills_arc', clan.stats.akills_arc), - int('akills_hist', clan.stats.akills_hist), - int('akills_sim', clan.stats.akills_sim), - int('gkills_arc', clan.stats.gkills_arc), - int('gkills_hist', clan.stats.gkills_hist), - int('gkills_sim', clan.stats.gkills_sim), - int('deaths_arc', clan.stats.deaths_arc), - int('deaths_hist', clan.stats.deaths_hist), - int('deaths_sim', clan.stats.deaths_sim), - int('ftime_arc', clan.stats.ftime_arc), - int('ftime_hist', clan.stats.ftime_hist), - int('ftime_sim', clan.stats.ftime_sim), + ...statParams(clan.stats), ], blocks: [], }; } +function statParams(stats: ClanStats): BlkParam[] { + return CLAN_STAT_KEYS.map((key) => int(key, stats[key])); +} + function buildMemberActivityBlock(member: ClanMemberRecord, todayDay: number): BlkBlock { const periods = member.periods.length > 0 ? member.periods : [{ day: todayDay, activity: member.curActivity, exp: 20000 }]; - const historyParams: BlkParam[] = periods.map((p) => int(String(p.day), p.activity)); - const expActivityBlocks: BlkBlock[] = periods.map((p) => ({ - name: String(p.day), - params: [ - int('activity', p.activity), - int('exp', p.exp), - int('expRewardBase', p.exp), - int('expBoost', 0), - ], - blocks: [], - })); - return { name: member.uid, params: [ @@ -296,8 +228,16 @@ function buildMemberActivityBlock(member: ClanMemberRecord, todayDay: number): B int('exp', member.earnedSquadronExp), ], blocks: [ - { name: 'history', params: historyParams, blocks: [] }, - { name: 'expActivity', params: [], blocks: expActivityBlocks }, + { name: 'history', params: periods.map((p) => int(String(p.day), p.activity)), blocks: [] }, + { + name: 'expActivity', + params: [], + blocks: periods.map((p) => ({ + name: String(p.day), + params: [int('activity', p.activity), int('exp', p.exp), int('expRewardBase', p.exp), int('expBoost', 0)], + blocks: [], + })), + }, ], }; } diff --git a/packages/local-service/src/clans/clan-lifecycle.ts b/packages/local-service/src/clans/clan-lifecycle.ts new file mode 100644 index 0000000..3110b1c --- /dev/null +++ b/packages/local-service/src/clans/clan-lifecycle.ts @@ -0,0 +1,270 @@ +/** + * Squadron lifecycle rules: creation, info editing, upgrading from training battalion to + * full squadron, member-limit expansion, and disbanding. + */ +import type { BlkBlock } from '@wto/blk'; +import type { Account } from '../accounts/account-store.ts'; +import type { ClanEconomy } from '../game-data/datasets/clan-economy.ts'; +import type { ClanKind } from '../profile/profile-clan.ts'; +import { canAfford, pay, type Price } from '../profile/profile-currency.ts'; +import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts'; +import { appendClanLog, clearCandidateEverywhere, hasClanManageRight } from './clan-membership.ts'; +import { buildDefaultPeriods } from './clan-seeds.ts'; +import { ClanRole, type ClanMemberRecord, type ClanRecord } from './clan-types.ts'; + +export interface StoredClansState { + nextClanId: number; + clans: ClanRecord[]; +} + +export interface CreateClanInput { + readonly name: string; + readonly tag: string; + readonly slogan: string; + readonly region: string; + readonly desc: string; + readonly announcement: string; + readonly type: ClanKind; + readonly offered: Price; +} + +export interface ClanInfoChanges { + readonly name?: string | undefined; + readonly tag?: string | undefined; + readonly desc?: string | undefined; + readonly slogan?: string | undefined; + readonly announcement?: string | undefined; + readonly region?: string | undefined; + readonly status?: 'open' | 'closed' | undefined; +} + +export function stripClanDecorators(tag: string): string { + return tag.replace(/^[\[\-\.\=\^\*]+|[\]\-\.\=\^\*]+$/g, ''); +} + +export function createClanInState( + state: StoredClansState, + profile: BlkBlock, + account: Account, + economy: ClanEconomy, + input: CreateClanInput, + nowSec: number, +): RuleOutcome { + if (state.clans.some((c) => c.members.some((m) => m.uid === account.userId))) return refused('NOT_AVAILABLE'); + const name = input.name.trim(); + const tag = input.tag.trim(); + if (!name || !tag) return refused('BAD_PARAMS'); + + const coreTag = stripClanDecorators(tag).toLowerCase(); + if (state.clans.some((c) => c.name.toLowerCase() === name.toLowerCase() || stripClanDecorators(c.tag).toLowerCase() === coreTag)) { + return refused('NOT_AVAILABLE'); + } + + const expectedPrice: Price = input.type === 'battalion' + ? { silverLions: economy.battalionCreateSilver, goldenEagles: economy.battalionCreateGold } + : { silverLions: economy.normalCreateSilver, goldenEagles: economy.normalCreateGold }; + + if (input.offered.silverLions !== expectedPrice.silverLions || input.offered.goldenEagles !== expectedPrice.goldenEagles) { + return refused('PRICE_CHANGED'); + } + if (!canAfford(profile, expectedPrice)) return refused('NOT_ENOUGH_MONEY'); + + clearCandidateEverywhere(state.clans, account.userId); + pay(profile, expectedPrice); + + const id = String(state.nextClanId++); + const created = buildCreatedClanRecord(id, account, name, tag, input, nowSec); + state.clans.unshift(created); + return ACCEPTED; +} + +export function editClanInfoInState( + clan: ClanRecord | undefined, + profile: BlkBlock, + account: Account, + economy: ClanEconomy, + changes: ClanInfoChanges, + nowSec: number, +): RuleOutcome { + if (!clan || !hasClanManageRight(clan, account.userId)) return refused('NOT_AVAILABLE'); + + if (clan.type === 'battalion') { + const isNameChanged = changes.name !== undefined && changes.name !== clan.name; + const isCoreTagChanged = changes.tag !== undefined && stripClanDecorators(changes.tag) !== stripClanDecorators(clan.tag); + if (isNameChanged || isCoreTagChanged) { + const editCost: Price = { silverLions: economy.battalionPrimaryEditSilver, goldenEagles: economy.battalionPrimaryEditGold }; + if (!canAfford(profile, editCost)) return refused('NOT_ENOUGH_MONEY'); + pay(profile, editCost); + } + } + + if (changes.name !== undefined && changes.name.trim()) clan.name = changes.name.trim(); + if (changes.tag !== undefined && changes.tag.trim()) { + clan.tag = changes.tag.trim(); + clan.lastPaidTag = clan.tag; + } + if (changes.desc !== undefined) clan.desc = changes.desc; + if (changes.slogan !== undefined) clan.slogan = changes.slogan; + if (changes.announcement !== undefined) clan.announcement = changes.announcement; + if (changes.region !== undefined && changes.region !== clan.region) { + clan.region = changes.region; + clan.regionLastUpdatedSec = nowSec; + } + if (changes.status !== undefined) clan.status = changes.status; + + clan.changedByUid = account.userId; + clan.changedByNick = account.nick; + clan.changedTimeSec = nowSec; + appendClanLog(clan, { + ev: 'info', + timeSec: nowSec, + uId: account.userId, + uN: account.nick, + name: clan.name, + tag: clan.tag, + desc: clan.desc, + slogan: clan.slogan, + region: clan.region, + announcement: clan.announcement, + status: clan.status, + }); + return ACCEPTED; +} + +export function upgradeClanToNormalInState( + clan: ClanRecord | undefined, + profile: BlkBlock, + account: Account, + economy: ClanEconomy, + input: { readonly tag: string; readonly desc: string; readonly announcement: string }, + nowSec: number, +): RuleOutcome { + if (!clan || clan.type !== 'battalion' || !hasClanManageRight(clan, account.userId)) return refused('NOT_AVAILABLE'); + + const goldCost = Math.max(0, economy.upgradeBattalionToNormalGold - clan.mspent); + const price: Price = { silverLions: economy.upgradeBattalionToNormalSilver, goldenEagles: goldCost }; + if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY'); + + pay(profile, price); + clan.type = 'normal'; + clan.mlimit = 128; + if (input.tag.trim()) { + clan.tag = input.tag.trim(); + clan.lastPaidTag = clan.tag; + } + clan.desc = input.desc; + clan.announcement = input.announcement; + clan.changedByUid = account.userId; + clan.changedByNick = account.nick; + clan.changedTimeSec = nowSec; + + appendClanLog(clan, { + ev: 'upgrade', + timeSec: nowSec, + uId: account.userId, + uN: account.nick, + type: 'normal', + tag: clan.tag, + desc: clan.desc, + }); + return ACCEPTED; +} + +export function upgradeMembersLimitInState( + clan: ClanRecord | undefined, + profile: BlkBlock, + account: Account, + economy: ClanEconomy, + nowSec: number, +): RuleOutcome { + if (!clan || clan.type !== 'battalion' || !hasClanManageRight(clan, account.userId)) return refused('NOT_AVAILABLE'); + if (clan.mlimit >= economy.battalionMembersUpgradeLimit) return refused('NOT_AVAILABLE'); + + const price: Price = { silverLions: 0, goldenEagles: economy.battalionMembersUpgradeGold }; + if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY'); + + const oldLimit = clan.mlimit; + pay(profile, price); + clan.mlimit = Math.min(economy.battalionMembersUpgradeLimit, clan.mlimit + economy.battalionMembersUpgradeStep); + clan.mspent += economy.battalionMembersUpgradeGold; + + appendClanLog(clan, { + ev: 'upgrade_members', + timeSec: nowSec, + uId: account.userId, + uN: account.nick, + old: String(oldLimit), + new: String(clan.mlimit), + }); + return ACCEPTED; +} + +function buildCreatedClanRecord( + id: string, + account: Account, + name: string, + tag: string, + input: CreateClanInput, + nowSec: number, +): ClanRecord { + const periods = buildDefaultPeriods(Math.floor(nowSec / 86400), 360); + const leaderMember: ClanMemberRecord = { + uid: account.userId, + nick: account.nick, + role: ClanRole.LEADER, + joinDateSec: nowSec, + curActivity: 360, + totalActivity: periods.reduce((s, p) => s + p.activity, 0), + earnedSquadronExp: periods.reduce((s, p) => s + p.exp, 0), + ratingArc: 1500, + ratingHist: 1500, + ratingSim: 1500, + periods, + }; + const desc = input.type === 'normal' ? input.desc : ''; + return { + id, + name, + tag, + lastPaidTag: tag, + type: input.type, + slogan: input.slogan, + desc, + announcement: input.announcement, + region: input.region, + status: 'open', + autoaccept: true, + mlimit: input.type === 'battalion' ? 10 : 128, + mspent: 0, + cdateSec: nowSec, + changedByUid: account.userId, + changedByNick: account.nick, + changedTimeSec: nowSec, + regionLastUpdatedSec: input.region ? nowSec : 0, + stats: { + dr_era5_arc: 1500, dr_era5_hist: 1500, dr_era5_sim: 1500, + akills_arc: 0, akills_hist: 0, akills_sim: 0, + gkills_arc: 0, gkills_hist: 0, gkills_sim: 0, + deaths_arc: 0, deaths_hist: 0, deaths_sim: 0, + ftime_arc: 0, ftime_hist: 0, ftime_sim: 0, + }, + members: [leaderMember], + candidates: [], + blacklist: [], + logs: [{ + id: 1, + ev: 'create', + timeSec: nowSec, + uId: account.userId, + uN: account.nick, + name, + type: input.type, + tag, + desc, + slogan: input.slogan, + region: input.region, + announcement: input.announcement, + }], + bestRewards: [], + }; +} diff --git a/packages/local-service/src/clans/clan-membership.ts b/packages/local-service/src/clans/clan-membership.ts new file mode 100644 index 0000000..b06d2b4 --- /dev/null +++ b/packages/local-service/src/clans/clan-membership.ts @@ -0,0 +1,265 @@ +/** + * Squadron membership, candidate moderation, role changes, blacklist, and event-log helpers + *. + */ +import type { Account } from '../accounts/account-store.ts'; +import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts'; +import { buildDefaultPeriods } from './clan-seeds.ts'; +import { ClanRole, roleNameOf, type ClanLogEntry, type ClanRecord } from './clan-types.ts'; + +export interface MembershipRequestQuery { + readonly clanId?: string | undefined; + readonly clanName?: string | undefined; + readonly clanTag?: string | undefined; + readonly cancel?: boolean | undefined; + readonly comment?: string | undefined; +} + +export function hasClanManageRight(clan: ClanRecord, userId: string): boolean { + const role = clan.members.find((m) => m.uid === userId)?.role; + return role === ClanRole.LEADER || role === ClanRole.DEPUTY || role === ClanRole.CLANADMIN; +} + +export function hasClanOfficerRight(clan: ClanRecord, userId: string): boolean { + const role = clan.members.find((m) => m.uid === userId)?.role; + return role === ClanRole.LEADER || role === ClanRole.DEPUTY || role === ClanRole.OFFICER || role === ClanRole.CLANADMIN; +} + +export function appendClanLog(clan: ClanRecord, entry: Omit): void { + const nextId = clan.logs.reduce((max, item) => Math.max(max, item.id), 0) + 1; + clan.logs.push({ id: nextId, ...entry }); +} + +export function clearCandidateEverywhere(clans: readonly ClanRecord[], userId: string): void { + for (const clan of clans) { + clan.candidates = clan.candidates.filter((c) => c.uid !== userId); + } +} + +export function addMemberToClan( + clan: ClanRecord, + uid: string, + nick: string, + role: number, + initiatorUid: string, + initiatorNick: string, + nowSec: number, +): void { + if (clan.members.some((m) => m.uid === uid)) return; + const periods = buildDefaultPeriods(Math.floor(nowSec / 86400), 360); + clan.members.push({ + uid, + nick, + role, + joinDateSec: nowSec, + curActivity: 360, + totalActivity: periods.reduce((s, p) => s + p.activity, 0), + earnedSquadronExp: periods.reduce((s, p) => s + p.exp, 0), + ratingArc: 1450, + ratingHist: 1500, + ratingSim: 1400, + periods, + }); + appendClanLog(clan, { + ev: 'add', + timeSec: nowSec, + uId: initiatorUid, + uN: initiatorNick, + uid, + nick, + role: roleNameOf(role), + }); +} + +export function requestOrCancelMembershipInState( + clans: readonly ClanRecord[], + targetClan: ClanRecord | undefined, + alreadyInClan: boolean, + account: Account, + query: MembershipRequestQuery, + nowSec: number, +): { readonly outcome: RuleOutcome; readonly mutated: boolean } { + if (query.cancel || (!query.clanId && !query.clanName && !query.clanTag) || query.clanId === '-1') { + clearCandidateEverywhere(clans, account.userId); + return { outcome: ACCEPTED, mutated: true }; + } + if (alreadyInClan) return { outcome: refused('NOT_AVAILABLE'), mutated: false }; + if (!targetClan || targetClan.status === 'closed' || targetClan.members.length >= targetClan.mlimit) { + return { outcome: refused('NOT_AVAILABLE'), mutated: false }; + } + if (targetClan.blacklist.some((b) => b.uid === account.userId)) { + return { outcome: refused('NOT_AVAILABLE'), mutated: false }; + } + + clearCandidateEverywhere(clans, account.userId); + if (targetClan.autoaccept) { + addMemberToClan(targetClan, account.userId, account.nick, ClanRole.REGULAR, account.userId, account.nick, nowSec); + } else { + targetClan.candidates.push({ + uid: account.userId, + nick: account.nick, + comment: query.comment ?? '', + dateSec: nowSec, + }); + } + return { outcome: ACCEPTED, mutated: true }; +} + +export function leaveClanInState( + clans: ClanRecord[], + clan: ClanRecord | undefined, + account: Account, + nowSec: number, +): { readonly outcome: RuleOutcome; readonly nextClans: ClanRecord[] } { + if (!clan) return { outcome: refused('NOT_AVAILABLE'), nextClans: clans }; + clan.members = clan.members.filter((m) => m.uid !== account.userId); + if (clan.members.length === 0) { + return { outcome: ACCEPTED, nextClans: clans.filter((c) => c.id !== clan.id) }; + } + if (!clan.members.some((m) => m.role === ClanRole.LEADER)) { + clan.members[0] = { ...clan.members[0]!, role: ClanRole.LEADER }; + } + appendClanLog(clan, { + ev: 'rem', + timeSec: nowSec, + uId: account.userId, + uN: account.nick, + uid: account.userId, + nick: account.nick, + }); + return { outcome: ACCEPTED, nextClans: clans }; +} + +export function acceptCandidateOnClan( + clan: ClanRecord | undefined, + initiator: Account, + targetUid: string, + targetNick: string, + role: number, + nowSec: number, +): boolean { + if (!clan || !hasClanOfficerRight(clan, initiator.userId) || clan.members.length >= clan.mlimit) return false; + const cand = clan.candidates.find((c) => c.uid === targetUid); + clan.candidates = clan.candidates.filter((c) => c.uid !== targetUid); + addMemberToClan(clan, targetUid, cand?.nick ?? targetNick, role || ClanRole.REGULAR, initiator.userId, initiator.nick, nowSec); + return true; +} + +export function rejectCandidateOnClan( + clan: ClanRecord | undefined, + initiator: Account, + targetUid: string, + comments: string, + nowSec: number, +): boolean { + if (!clan || !hasClanOfficerRight(clan, initiator.userId)) return false; + const cand = clan.candidates.find((c) => c.uid === targetUid); + if (!cand) return false; + clan.candidates = clan.candidates.filter((c) => c.uid !== targetUid); + appendClanLog(clan, { + ev: 'reject_candidate', + timeSec: nowSec, + uId: initiator.userId, + uN: initiator.nick, + uid: cand.uid, + nick: cand.nick, + comments, + }); + return true; +} + +export function dismissMemberOnClan( + clan: ClanRecord | undefined, + initiator: Account, + targetUid: string, + comments: string, + nowSec: number, +): boolean { + if (!clan || !hasClanOfficerRight(clan, initiator.userId) || targetUid === initiator.userId) return false; + const member = clan.members.find((m) => m.uid === targetUid); + if (!member || member.role === ClanRole.LEADER) return false; + clan.members = clan.members.filter((m) => m.uid !== targetUid); + appendClanLog(clan, { + ev: 'rem', + timeSec: nowSec, + uId: initiator.userId, + uN: initiator.nick, + uid: member.uid, + nick: member.nick, + comments, + }); + return true; +} + +export function changeMemberRoleOnClan( + clan: ClanRecord | undefined, + initiator: Account, + targetUid: string, + newRole: number, + nowSec: number, +): boolean { + if (!clan || !hasClanManageRight(clan, initiator.userId) || targetUid === initiator.userId) return false; + const idx = clan.members.findIndex((m) => m.uid === targetUid); + if (idx < 0) return false; + const prev = clan.members[idx]!; + clan.members[idx] = { ...prev, role: newRole }; + appendClanLog(clan, { + ev: 'role', + timeSec: nowSec, + uId: initiator.userId, + uN: initiator.nick, + uid: prev.uid, + nick: prev.nick, + old: roleNameOf(prev.role), + new: roleNameOf(newRole), + }); + return true; +} + +export function editBlacklistOnClan( + clan: ClanRecord | undefined, + initiator: Account, + targetUid: string, + targetNick: string, + add: boolean, + comments: string, + nowSec: number, +): boolean { + if (!clan || !hasClanOfficerRight(clan, initiator.userId)) return false; + if (add) { + clan.candidates = clan.candidates.filter((c) => c.uid !== targetUid); + const resolvedNick = targetNick || `Pilot_${targetUid}`; + if (!clan.blacklist.some((b) => b.uid === targetUid)) { + clan.blacklist.push({ + uid: targetUid, + nick: resolvedNick, + initiatorUid: initiator.userId, + initiatorNick: initiator.nick, + comments, + dateSec: nowSec, + }); + } + appendClanLog(clan, { + ev: 'add_to_blacklist', + timeSec: nowSec, + uId: initiator.userId, + uN: initiator.nick, + uid: targetUid, + nick: resolvedNick, + comments, + }); + } else { + const existing = clan.blacklist.find((b) => b.uid === targetUid); + clan.blacklist = clan.blacklist.filter((b) => b.uid !== targetUid); + appendClanLog(clan, { + ev: 'remove_from_blacklist', + timeSec: nowSec, + uId: initiator.userId, + uN: initiator.nick, + uid: targetUid, + nick: existing?.nick ?? targetNick, + comments, + }); + } + return true; +} diff --git a/packages/local-service/src/clans/clan-queries.ts b/packages/local-service/src/clans/clan-queries.ts new file mode 100644 index 0000000..c1aece6 --- /dev/null +++ b/packages/local-service/src/clans/clan-queries.ts @@ -0,0 +1,82 @@ +/** + * Read-only search and leaderboard queries over the local squadron directory + *. + */ +import { totalPeriodActivityOf } from './clan-blk.ts'; +import { stripClanDecorators } from './clan-lifecycle.ts'; +import type { ClanRecord } from './clan-types.ts'; + +export interface LeaderboardQuery { + readonly start: number; + readonly count: number; + readonly sortField: string; + readonly clanId?: string | undefined; + readonly prefix?: string | undefined; + readonly filterOpen?: boolean | undefined; + readonly filterNotFull?: boolean | undefined; + readonly filterAutoAccept?: boolean | undefined; +} + +export function findClanInList( + clans: readonly ClanRecord[], + query: { readonly clanId?: string | undefined; readonly clanName?: string | undefined; readonly clanTag?: string | undefined }, +): ClanRecord | undefined { + if (query.clanId && query.clanId !== '-1') { + const byId = clans.find((c) => c.id === query.clanId); + if (byId) return byId; + } + if (query.clanName) { + const lower = query.clanName.toLowerCase(); + const byName = clans.find((c) => c.name.toLowerCase() === lower); + if (byName) return byName; + } + if (query.clanTag) { + const lower = query.clanTag.toLowerCase(); + const byTag = clans.find((c) => c.tag.toLowerCase() === lower); + if (byTag) return byTag; + } + return undefined; +} + +export function queryClanLeaderboard( + clans: readonly ClanRecord[], + query: LeaderboardQuery, +): ReadonlyArray<{ readonly clan: ClanRecord; readonly pos: number }> { + const sorted = [...clans].sort((a, b) => metricOf(b, query.sortField) - metricOf(a, query.sortField)); + const withPos = sorted.map((clan, index) => ({ clan, pos: index })); + if (query.clanId && query.clanId !== '-1') return withPos.filter((entry) => entry.clan.id === query.clanId); + + const prefix = query.prefix?.trim().toLowerCase() ?? ''; + const filtered = withPos.filter(({ clan }) => { + if (query.filterOpen && clan.status === 'closed') return false; + if (query.filterNotFull && clan.members.length >= clan.mlimit) return false; + if (query.filterAutoAccept && !clan.autoaccept) return false; + if (prefix) { + const strippedTag = stripClanDecorators(clan.tag).toLowerCase(); + if (!clan.name.toLowerCase().includes(prefix) && !clan.tag.toLowerCase().includes(prefix) && !strippedTag.includes(prefix)) { + return false; + } + } + return true; + }); + const start = Math.max(0, query.start); + const count = query.count > 0 ? query.count : 20; + return filtered.slice(start, start + count); +} + +function metricOf(clan: ClanRecord, sortField: string): number { + switch (sortField) { + case 'activity': + case 'clan_activity_by_periods': + return totalPeriodActivityOf(clan); + case 'members_cnt': + return clan.members.length; + case 'dr_era5_arc': + return clan.stats.dr_era5_arc; + case 'dr_era5_sim': + return clan.stats.dr_era5_sim; + case 'dr_era5_hist': + default: + return clan.stats.dr_era5_hist; + } +} diff --git a/packages/local-service/src/clans/clan-seeds.ts b/packages/local-service/src/clans/clan-seeds.ts index 9479a8d..04444ef 100644 --- a/packages/local-service/src/clans/clan-seeds.ts +++ b/packages/local-service/src/clans/clan-seeds.ts @@ -32,7 +32,7 @@ export function createDefaultClans(nowSec = Math.floor(Date.now() / 1000)): Clan { uid: '900001002', nick: 'Elena_Valkyrie', role: ClanRole.DEPUTY, title: 'title_ace', icon: 'cardicon_fem_01', unit: 'su_27sm', activity: 360 }, { uid: '900001003', nick: 'iron_tiger_88', role: ClanRole.OFFICER, title: 'title_tank_destroyer', icon: 'cardicon_14', unit: 'germ_leopard_2a7v', activity: 360 }, { uid: '900001004', nick: 'Tomcat_Actual', role: ClanRole.OFFICER, title: 'title_jet_powered', icon: 'cardicon_07', unit: 'f_14b', activity: 345 }, - { uid: '900001005', nick: ' Kuroshio_DD', role: ClanRole.SERGEANT, title: 'title_sea_wolf', icon: 'cardicon_19', unit: 'jp_destroyer_shimakaze', activity: 330 }, + { uid: '900001005', nick: 'Kuroshio_DD', role: ClanRole.SERGEANT, title: 'title_sea_wolf', icon: 'cardicon_19', unit: 'jp_destroyer_shimakaze', activity: 330 }, { uid: '900001006', nick: 'Northern_Fox', role: ClanRole.REGULAR, title: 'title_sniper', icon: 'cardicon_11', unit: 'sw_strv_122b_plus', activity: 310 }, ], }), diff --git a/packages/local-service/src/clans/clan-store.ts b/packages/local-service/src/clans/clan-store.ts index ac65430..cfd64d7 100644 --- a/packages/local-service/src/clans/clan-store.ts +++ b/packages/local-service/src/clans/clan-store.ts @@ -1,99 +1,81 @@ /** * Persistent local squadron (clan) directory & state store (`/clans.json`), - * backing search, leaderboards, creation, membership, roles, activity, and logs - * (implementation notes; implementation notes section I). + * delegating queries, lifecycle, and membership rules to `clan-queries.ts`, + * `clan-lifecycle.ts`, and `clan-membership.ts` (implementation notes; implementation notes I). */ import { existsSync, readFileSync } from 'node:fs'; import { join } from 'node:path'; import type { BlkBlock } from '@wto/blk'; import type { Account } from '../accounts/account-store.ts'; import type { ClanEconomy } from '../game-data/datasets/clan-economy.ts'; -import { canAfford, pay, type Price } from '../profile/profile-currency.ts'; import { clanMembershipOf, clearClanMembership, setClanMembership, setPendingClanRequest, syncStoredClanEarnedExp, - type ClanKind, } from '../profile/profile-clan.ts'; import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts'; import { writeFileAtomic } from '../storage/atomic-file.ts'; -import { totalPeriodActivityOf } from './clan-blk.ts'; -import { buildDefaultPeriods, createDefaultClans } from './clan-seeds.ts'; import { - ClanRole, - roleNameOf, - type ClanBestReward, - type ClanLogEntry, - type ClanMemberRecord, - type ClanRecord, -} from './clan-types.ts'; + createClanInState, + editClanInfoInState, + upgradeClanToNormalInState, + upgradeMembersLimitInState, + type ClanInfoChanges, + type CreateClanInput, + type StoredClansState, +} from './clan-lifecycle.ts'; +import { + acceptCandidateOnClan, + changeMemberRoleOnClan, + dismissMemberOnClan, + editBlacklistOnClan, + hasClanManageRight, + leaveClanInState, + rejectCandidateOnClan, + requestOrCancelMembershipInState, + type MembershipRequestQuery, +} from './clan-membership.ts'; +import { findClanInList, queryClanLeaderboard, type LeaderboardQuery } from './clan-queries.ts'; +import { createDefaultClans } from './clan-seeds.ts'; +import { ClanRole, type ClanBestReward, type ClanMemberRecord, type ClanRecord } from './clan-types.ts'; -interface StoredClansFile { - nextClanId: number; - clans: ClanRecord[]; -} - -export interface LeaderboardQuery { - readonly start: number; - readonly count: number; - readonly sortField: string; - readonly clanId?: string | undefined; - readonly prefix?: string | undefined; - readonly filterOpen?: boolean | undefined; - readonly filterNotFull?: boolean | undefined; - readonly filterAutoAccept?: boolean | undefined; -} +export type { LeaderboardQuery }; export class ClanStore { readonly #filePath: string; - #state: StoredClansFile; + #state: StoredClansState; constructor(dataFolder: string) { this.#filePath = join(dataFolder, 'clans.json'); this.#state = this.#loadOrSeed(); } - #loadOrSeed(): StoredClansFile { + #loadOrSeed(): StoredClansState { if (existsSync(this.#filePath)) { - const parsed = JSON.parse(readFileSync(this.#filePath, 'utf8')) as StoredClansFile; - if (Array.isArray(parsed.clans) && typeof parsed.nextClanId === 'number') { - return parsed; - } + const parsed = JSON.parse(readFileSync(this.#filePath, 'utf8')) as StoredClansState; + if (Array.isArray(parsed.clans) && typeof parsed.nextClanId === 'number') return parsed; } - const seeded: StoredClansFile = { - nextClanId: 600001, - clans: createDefaultClans(), - }; + const seeded: StoredClansState = { nextClanId: 600001, clans: createDefaultClans() }; this.#save(seeded); return seeded; } - #save(state: StoredClansFile = this.#state): void { + #save(state: StoredClansState = this.#state): void { writeFileAtomic(this.#filePath, JSON.stringify(state, null, 2)); } + #resolveClan(clanId: string | undefined, userId: string): ClanRecord | undefined { + return clanId && clanId !== '-1' ? this.byId(clanId) : this.clanOfUser(userId)?.clan; + } + byId(clanId: string): ClanRecord | undefined { return this.#state.clans.find((c) => c.id === clanId); } findClan(query: { readonly clanId?: string | undefined; readonly clanName?: string | undefined; readonly clanTag?: string | undefined }): ClanRecord | undefined { - if (query.clanId && query.clanId !== '-1') { - const byId = this.byId(query.clanId); - if (byId) return byId; - } - if (query.clanName) { - const lower = query.clanName.toLowerCase(); - const byName = this.#state.clans.find((c) => c.name.toLowerCase() === lower); - if (byName) return byName; - } - if (query.clanTag) { - const lower = query.clanTag.toLowerCase(); - const byTag = this.#state.clans.find((c) => c.tag.toLowerCase() === lower); - if (byTag) return byTag; - } - return undefined; + return findClanInList(this.#state.clans, query); } clanOfUser(userId: string): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined { @@ -120,7 +102,6 @@ export class ClanStore { return undefined; } - /** Keep a player's profile top-level clan fields and earned squadron RP aligned with `clans.json`. */ syncProfile(profile: BlkBlock, account: Account): void { const found = this.clanOfUser(account.userId); if (found) { @@ -132,13 +113,7 @@ export class ClanStore { this.#save(); } } - setClanMembership(profile, { - clanId: clan.id, - clanTag: clan.tag, - clanName: clan.name, - clanType: clan.type, - role: member.role, - }); + setClanMembership(profile, { clanId: clan.id, clanTag: clan.tag, clanName: clan.name, clanType: clan.type, role: member.role }); syncStoredClanEarnedExp(profile, member.earnedSquadronExp); return; } @@ -152,216 +127,25 @@ export class ClanStore { } queryLeaderboard(query: LeaderboardQuery): ReadonlyArray<{ readonly clan: ClanRecord; readonly pos: number }> { - const sorted = [...this.#state.clans].sort((a, b) => metricOf(b, query.sortField) - metricOf(a, query.sortField)); - const withPos = sorted.map((clan, index) => ({ clan, pos: index })); - - if (query.clanId && query.clanId !== '-1') { - return withPos.filter((entry) => entry.clan.id === query.clanId); - } - - const prefix = query.prefix?.trim().toLowerCase() ?? ''; - const filtered = withPos.filter(({ clan }) => { - if (query.filterOpen && clan.status === 'closed') return false; - if (query.filterNotFull && clan.members.length >= clan.mlimit) return false; - if (query.filterAutoAccept && !clan.autoaccept) return false; - if (prefix) { - const strippedTag = stripDecorators(clan.tag).toLowerCase(); - const matchName = clan.name.toLowerCase().includes(prefix); - const matchTag = clan.tag.toLowerCase().includes(prefix) || strippedTag.includes(prefix); - if (!matchName && !matchTag) return false; - } - return true; - }); - - const start = Math.max(0, query.start); - const count = query.count > 0 ? query.count : 20; - return filtered.slice(start, start + count); + return queryClanLeaderboard(this.#state.clans, query); } - createClan( - profile: BlkBlock, - account: Account, - economy: ClanEconomy, - input: { - readonly name: string; - readonly tag: string; - readonly slogan: string; - readonly region: string; - readonly desc: string; - readonly announcement: string; - readonly type: ClanKind; - readonly offered: Price; - }, - nowSec = Math.floor(Date.now() / 1000), - ): RuleOutcome { - if (this.clanOfUser(account.userId)) return refused('NOT_AVAILABLE'); - const name = input.name.trim(); - const tag = input.tag.trim(); - if (!name || !tag) return refused('BAD_PARAMS'); - - if (this.#state.clans.some((c) => c.name.toLowerCase() === name.toLowerCase() || stripDecorators(c.tag).toLowerCase() === stripDecorators(tag).toLowerCase())) { - return refused('NOT_AVAILABLE'); + createClan(profile: BlkBlock, account: Account, economy: ClanEconomy, input: CreateClanInput, nowSec = nowSeconds()): RuleOutcome { + const outcome = createClanInState(this.#state, profile, account, economy, input, nowSec); + if (outcome.ok) { + this.#save(); + this.syncProfile(profile, account); } - - const expectedPrice: Price = input.type === 'battalion' - ? { silverLions: economy.battalionCreateSilver, goldenEagles: economy.battalionCreateGold } - : { silverLions: economy.normalCreateSilver, goldenEagles: economy.normalCreateGold }; - - if (input.offered.silverLions !== expectedPrice.silverLions || input.offered.goldenEagles !== expectedPrice.goldenEagles) { - return refused('PRICE_CHANGED'); - } - if (!canAfford(profile, expectedPrice)) return refused('NOT_ENOUGH_MONEY'); - - this.#clearCandidateEverywhere(account.userId); - pay(profile, expectedPrice); - - const id = String(this.#state.nextClanId++); - const todayDay = Math.floor(nowSec / 86400); - const periods = buildDefaultPeriods(todayDay, 360); - const earnedSquadronExp = periods.reduce((s, p) => s + p.exp, 0); - - const leaderMember: ClanMemberRecord = { - uid: account.userId, - nick: account.nick, - role: ClanRole.LEADER, - joinDateSec: nowSec, - curActivity: 360, - totalActivity: periods.reduce((s, p) => s + p.activity, 0), - earnedSquadronExp, - ratingArc: 1500, - ratingHist: 1500, - ratingSim: 1500, - periods, - }; - - const created: ClanRecord = { - id, - name, - tag, - lastPaidTag: tag, - type: input.type, - slogan: input.slogan, - desc: input.type === 'normal' ? input.desc : '', - announcement: input.announcement, - region: input.region, - status: 'open', - autoaccept: true, - mlimit: input.type === 'battalion' ? 10 : 128, - mspent: 0, - cdateSec: nowSec, - changedByUid: account.userId, - changedByNick: account.nick, - changedTimeSec: nowSec, - regionLastUpdatedSec: input.region ? nowSec : 0, - stats: { - dr_era5_arc: 1500, - dr_era5_hist: 1500, - dr_era5_sim: 1500, - akills_arc: 0, - akills_hist: 0, - akills_sim: 0, - gkills_arc: 0, - gkills_hist: 0, - gkills_sim: 0, - deaths_arc: 0, - deaths_hist: 0, - deaths_sim: 0, - ftime_arc: 0, - ftime_hist: 0, - ftime_sim: 0, - }, - members: [leaderMember], - candidates: [], - blacklist: [], - logs: [ - { - id: 1, - ev: 'create', - timeSec: nowSec, - uId: account.userId, - uN: account.nick, - name, - type: input.type, - tag, - desc: input.type === 'normal' ? input.desc : '', - slogan: input.slogan, - region: input.region, - announcement: input.announcement, - }, - ], - bestRewards: [], - }; - - this.#state.clans.unshift(created); - this.#save(); - this.syncProfile(profile, account); - return ACCEPTED; + return outcome; } - editClanInfo( - profile: BlkBlock, - account: Account, - economy: ClanEconomy, - clanId: string, - changes: { - readonly name?: string | undefined; - readonly tag?: string | undefined; - readonly desc?: string | undefined; - readonly slogan?: string | undefined; - readonly announcement?: string | undefined; - readonly region?: string | undefined; - readonly status?: 'open' | 'closed' | undefined; - }, - nowSec = Math.floor(Date.now() / 1000), - ): RuleOutcome { - const clan = clanId && clanId !== '-1' ? this.byId(clanId) : this.clanOfUser(account.userId)?.clan; - if (!clan) return refused('NOT_AVAILABLE'); - - const changedPrimary = (changes.name !== undefined && changes.name !== clan.name) - || (changes.tag !== undefined && changes.tag !== clan.tag); - if (changedPrimary && clan.type === 'battalion') { - const isNameChanged = changes.name !== undefined && changes.name !== clan.name; - const isCoreTagChanged = changes.tag !== undefined && stripDecorators(changes.tag) !== stripDecorators(clan.tag); - if (isNameChanged || isCoreTagChanged) { - const editCost: Price = { silverLions: economy.battalionPrimaryEditSilver, goldenEagles: economy.battalionPrimaryEditGold }; - if (!canAfford(profile, editCost)) return refused('NOT_ENOUGH_MONEY'); - pay(profile, editCost); - } + editClanInfo(profile: BlkBlock, account: Account, economy: ClanEconomy, clanId: string, changes: ClanInfoChanges, nowSec = nowSeconds()): RuleOutcome { + const outcome = editClanInfoInState(this.#resolveClan(clanId, account.userId), profile, account, economy, changes, nowSec); + if (outcome.ok) { + this.#save(); + this.syncProfile(profile, account); } - - if (changes.name !== undefined && changes.name.trim()) clan.name = changes.name.trim(); - if (changes.tag !== undefined && changes.tag.trim()) { - clan.tag = changes.tag.trim(); - clan.lastPaidTag = clan.tag; - } - if (changes.desc !== undefined) clan.desc = changes.desc; - if (changes.slogan !== undefined) clan.slogan = changes.slogan; - if (changes.announcement !== undefined) clan.announcement = changes.announcement; - if (changes.region !== undefined && changes.region !== clan.region) { - clan.region = changes.region; - clan.regionLastUpdatedSec = nowSec; - } - if (changes.status !== undefined) clan.status = changes.status; - - clan.changedByUid = account.userId; - clan.changedByNick = account.nick; - clan.changedTimeSec = nowSec; - this.#appendLog(clan, { - ev: 'info', - timeSec: nowSec, - uId: account.userId, - uN: account.nick, - name: clan.name, - tag: clan.tag, - desc: clan.desc, - slogan: clan.slogan, - region: clan.region, - announcement: clan.announcement, - status: clan.status, - }); - this.#save(); - this.syncProfile(profile, account); - return ACCEPTED; + return outcome; } upgradeClanToNormal( @@ -370,350 +154,103 @@ export class ClanStore { economy: ClanEconomy, clanId: string, input: { readonly tag: string; readonly desc: string; readonly announcement: string }, - nowSec = Math.floor(Date.now() / 1000), + nowSec = nowSeconds(), ): RuleOutcome { - const clan = clanId && clanId !== '-1' ? this.byId(clanId) : this.clanOfUser(account.userId)?.clan; - if (!clan || clan.type !== 'battalion') return refused('NOT_AVAILABLE'); - - const goldCost = Math.max(0, economy.upgradeBattalionToNormalGold - clan.mspent); - const price: Price = { silverLions: economy.upgradeBattalionToNormalSilver, goldenEagles: goldCost }; - if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY'); - - pay(profile, price); - clan.type = 'normal'; - clan.mlimit = 128; - if (input.tag.trim()) { - clan.tag = input.tag.trim(); - clan.lastPaidTag = clan.tag; + const outcome = upgradeClanToNormalInState(this.#resolveClan(clanId, account.userId), profile, account, economy, input, nowSec); + if (outcome.ok) { + this.#save(); + this.syncProfile(profile, account); } - clan.desc = input.desc; - clan.announcement = input.announcement; - clan.changedByUid = account.userId; - clan.changedByNick = account.nick; - clan.changedTimeSec = nowSec; - - this.#appendLog(clan, { - ev: 'upgrade', - timeSec: nowSec, - uId: account.userId, - uN: account.nick, - type: 'normal', - tag: clan.tag, - desc: clan.desc, - }); - this.#save(); - this.syncProfile(profile, account); - return ACCEPTED; + return outcome; } - upgradeMembersLimit( - profile: BlkBlock, - account: Account, - economy: ClanEconomy, - clanId: string, - nowSec = Math.floor(Date.now() / 1000), - ): RuleOutcome { - const clan = clanId && clanId !== '-1' ? this.byId(clanId) : this.clanOfUser(account.userId)?.clan; - if (!clan || clan.type !== 'battalion') return refused('NOT_AVAILABLE'); - if (clan.mlimit >= economy.battalionMembersUpgradeLimit) return refused('NOT_AVAILABLE'); - - const price: Price = { silverLions: 0, goldenEagles: economy.battalionMembersUpgradeGold }; - if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY'); - - const oldLimit = clan.mlimit; - pay(profile, price); - clan.mlimit = Math.min(economy.battalionMembersUpgradeLimit, clan.mlimit + economy.battalionMembersUpgradeStep); - clan.mspent += economy.battalionMembersUpgradeGold; - - this.#appendLog(clan, { - ev: 'upgrade_members', - timeSec: nowSec, - uId: account.userId, - uN: account.nick, - old: String(oldLimit), - new: String(clan.mlimit), - }); - this.#save(); - this.syncProfile(profile, account); - return ACCEPTED; + upgradeMembersLimit(profile: BlkBlock, account: Account, economy: ClanEconomy, clanId: string, nowSec = nowSeconds()): RuleOutcome { + const outcome = upgradeMembersLimitInState(this.#resolveClan(clanId, account.userId), profile, account, economy, nowSec); + if (outcome.ok) { + this.#save(); + this.syncProfile(profile, account); + } + return outcome; } - setMembershipRequirements(clanId: string, account: Account, reqBlk: BlkBlock | undefined, autoaccept: boolean): void { - const clan = clanId && clanId !== '-1' ? this.byId(clanId) : this.clanOfUser(account.userId)?.clan; - if (!clan) return; + setMembershipRequirements(clanId: string, account: Account, reqBlk: BlkBlock | undefined, autoaccept: boolean): boolean { + const clan = this.#resolveClan(clanId, account.userId); + if (!clan || !hasClanManageRight(clan, account.userId)) return false; clan.autoaccept = autoaccept; if (reqBlk) clan.membershipReqBlk = structuredClone(reqBlk); else delete clan.membershipReqBlk; this.#save(); + return true; } - requestOrCancelMembership( - profile: BlkBlock, - account: Account, - query: { - readonly clanId?: string | undefined; - readonly clanName?: string | undefined; - readonly clanTag?: string | undefined; - readonly cancel?: boolean | undefined; - readonly comment?: string | undefined; - }, - nowSec = Math.floor(Date.now() / 1000), - ): RuleOutcome { - if (query.cancel || (!query.clanId && !query.clanName && !query.clanTag) || query.clanId === '-1') { - this.#clearCandidateEverywhere(account.userId); + requestOrCancelMembership(profile: BlkBlock, account: Account, query: MembershipRequestQuery, nowSec = nowSeconds()): RuleOutcome { + const res = requestOrCancelMembershipInState(this.#state.clans, this.findClan(query), Boolean(this.clanOfUser(account.userId)), account, query, nowSec); + if (res.mutated) { this.#save(); this.syncProfile(profile, account); - return ACCEPTED; } - - if (this.clanOfUser(account.userId)) return refused('NOT_AVAILABLE'); - const clan = this.findClan(query); - if (!clan || clan.status === 'closed' || clan.members.length >= clan.mlimit) return refused('NOT_AVAILABLE'); - if (clan.blacklist.some((b) => b.uid === account.userId)) return refused('NOT_AVAILABLE'); - - this.#clearCandidateEverywhere(account.userId); - - if (clan.autoaccept) { - this.#addMemberToClan(clan, account.userId, account.nick, ClanRole.REGULAR, account.userId, account.nick, nowSec); - } else { - clan.candidates.push({ - uid: account.userId, - nick: account.nick, - comment: query.comment ?? '', - dateSec: nowSec, - }); - } - this.#save(); - this.syncProfile(profile, account); - return ACCEPTED; + return res.outcome; } - leaveClan(profile: BlkBlock, account: Account, nowSec = Math.floor(Date.now() / 1000)): RuleOutcome { - const found = this.clanOfUser(account.userId); - if (!found) return refused('NOT_AVAILABLE'); - const { clan } = found; - - clan.members = clan.members.filter((m) => m.uid !== account.userId); - if (clan.members.length === 0) { - this.#state.clans = this.#state.clans.filter((c) => c.id !== clan.id); - } else { - if (!clan.members.some((m) => m.role === ClanRole.LEADER)) { - clan.members[0] = { ...clan.members[0]!, role: ClanRole.LEADER }; - } - this.#appendLog(clan, { - ev: 'rem', - timeSec: nowSec, - uId: account.userId, - uN: account.nick, - uid: account.userId, - nick: account.nick, - }); + leaveClan(profile: BlkBlock, account: Account, nowSec = nowSeconds()): RuleOutcome { + const res = leaveClanInState(this.#state.clans, this.clanOfUser(account.userId)?.clan, account, nowSec); + if (res.outcome.ok) { + this.#state.clans = res.nextClans; + this.#save(); + clearClanMembership(profile); } - this.#save(); - clearClanMembership(profile); - return ACCEPTED; + return res.outcome; } disbandClan(profile: BlkBlock, account: Account, clanId?: string): RuleOutcome { - const clan = clanId && clanId !== '-1' ? this.byId(clanId) : this.clanOfUser(account.userId)?.clan; - if (!clan) return refused('NOT_AVAILABLE'); + const clan = this.#resolveClan(clanId, account.userId); + const role = clan?.members.find((m) => m.uid === account.userId)?.role; + if (!clan || (role !== ClanRole.LEADER && role !== ClanRole.CLANADMIN)) return refused('NOT_AVAILABLE'); this.#state.clans = this.#state.clans.filter((c) => c.id !== clan.id); this.#save(); this.syncProfile(profile, account); return ACCEPTED; } - acceptCandidate(initiator: Account, clanId: string | undefined, targetUid: string, targetNick: string, role: number, nowSec = Math.floor(Date.now() / 1000)): boolean { - const clan = clanId && clanId !== '-1' ? this.byId(clanId) : this.clanOfUser(initiator.userId)?.clan; - if (!clan || clan.members.length >= clan.mlimit) return false; - const cand = clan.candidates.find((c) => c.uid === targetUid); - const nick = cand?.nick ?? targetNick; - clan.candidates = clan.candidates.filter((c) => c.uid !== targetUid); - this.#addMemberToClan(clan, targetUid, nick, role || ClanRole.REGULAR, initiator.userId, initiator.nick, nowSec); + acceptCandidate(initiator: Account, clanId: string | undefined, targetUid: string, targetNick: string, role: number, nowSec = nowSeconds()): boolean { + if (!acceptCandidateOnClan(this.#resolveClan(clanId, initiator.userId), initiator, targetUid, targetNick, role, nowSec)) return false; this.#save(); return true; } - rejectCandidate(initiator: Account, clanId: string | undefined, targetUid: string, comments: string, nowSec = Math.floor(Date.now() / 1000)): boolean { - const clan = clanId && clanId !== '-1' ? this.byId(clanId) : this.clanOfUser(initiator.userId)?.clan; - if (!clan) return false; - const cand = clan.candidates.find((c) => c.uid === targetUid); - if (!cand) return false; - clan.candidates = clan.candidates.filter((c) => c.uid !== targetUid); - this.#appendLog(clan, { - ev: 'reject_candidate', - timeSec: nowSec, - uId: initiator.userId, - uN: initiator.nick, - uid: cand.uid, - nick: cand.nick, - comments, - }); + rejectCandidate(initiator: Account, clanId: string | undefined, targetUid: string, comments: string, nowSec = nowSeconds()): boolean { + if (!rejectCandidateOnClan(this.#resolveClan(clanId, initiator.userId), initiator, targetUid, comments, nowSec)) return false; this.#save(); return true; } - dismissMember(initiator: Account, targetUid: string, comments: string, nowSec = Math.floor(Date.now() / 1000)): boolean { - const clan = this.clanOfUser(initiator.userId)?.clan; - if (!clan || targetUid === initiator.userId) return false; - const member = clan.members.find((m) => m.uid === targetUid); - if (!member) return false; - clan.members = clan.members.filter((m) => m.uid !== targetUid); - this.#appendLog(clan, { - ev: 'rem', - timeSec: nowSec, - uId: initiator.userId, - uN: initiator.nick, - uid: member.uid, - nick: member.nick, - comments, - }); + dismissMember(initiator: Account, targetUid: string, comments: string, nowSec = nowSeconds()): boolean { + if (!dismissMemberOnClan(this.clanOfUser(initiator.userId)?.clan, initiator, targetUid, comments, nowSec)) return false; this.#save(); return true; } - changeMemberRole(initiator: Account, targetUid: string, newRole: number, nowSec = Math.floor(Date.now() / 1000)): boolean { - const clan = this.clanOfUser(initiator.userId)?.clan; - if (!clan) return false; - const idx = clan.members.findIndex((m) => m.uid === targetUid); - if (idx < 0) return false; - const prev = clan.members[idx]!; - clan.members[idx] = { ...prev, role: newRole }; - this.#appendLog(clan, { - ev: 'role', - timeSec: nowSec, - uId: initiator.userId, - uN: initiator.nick, - uid: prev.uid, - nick: prev.nick, - old: roleNameOf(prev.role), - new: roleNameOf(newRole), - }); + changeMemberRole(initiator: Account, targetUid: string, newRole: number, nowSec = nowSeconds()): boolean { + if (!changeMemberRoleOnClan(this.clanOfUser(initiator.userId)?.clan, initiator, targetUid, newRole, nowSec)) return false; this.#save(); return true; } - editBlacklist( - initiator: Account, - clanId: string | undefined, - targetUid: string, - targetNick: string, - add: boolean, - comments: string, - nowSec = Math.floor(Date.now() / 1000), - ): boolean { - const clan = clanId && clanId !== '-1' ? this.byId(clanId) : this.clanOfUser(initiator.userId)?.clan; - if (!clan) return false; - if (add) { - clan.candidates = clan.candidates.filter((c) => c.uid !== targetUid); - if (!clan.blacklist.some((b) => b.uid === targetUid)) { - clan.blacklist.push({ - uid: targetUid, - nick: targetNick || `Pilot_${targetUid}`, - initiatorUid: initiator.userId, - initiatorNick: initiator.nick, - comments, - dateSec: nowSec, - }); - } - this.#appendLog(clan, { - ev: 'add_to_blacklist', - timeSec: nowSec, - uId: initiator.userId, - uN: initiator.nick, - uid: targetUid, - nick: targetNick || `Pilot_${targetUid}`, - comments, - }); - } else { - const existing = clan.blacklist.find((b) => b.uid === targetUid); - clan.blacklist = clan.blacklist.filter((b) => b.uid !== targetUid); - this.#appendLog(clan, { - ev: 'remove_from_blacklist', - timeSec: nowSec, - uId: initiator.userId, - uN: initiator.nick, - uid: targetUid, - nick: existing?.nick ?? targetNick, - comments, - }); - } + editBlacklist(initiator: Account, clanId: string | undefined, targetUid: string, targetNick: string, add: boolean, comments: string, nowSec = nowSeconds()): boolean { + if (!editBlacklistOnClan(this.#resolveClan(clanId, initiator.userId), initiator, targetUid, targetNick, add, comments, nowSec)) return false; this.#save(); return true; } - setBestRewards(clanId: string, rewards: readonly ClanBestReward[]): void { + setBestRewards(clanId: string, initiatorUserId: string, rewards: readonly ClanBestReward[]): boolean { const clan = this.byId(clanId); - if (!clan) return; + if (!clan || !hasClanManageRight(clan, initiatorUserId)) return false; clan.bestRewards = [...rewards]; this.#save(); - } - - #addMemberToClan( - clan: ClanRecord, - uid: string, - nick: string, - role: number, - initiatorUid: string, - initiatorNick: string, - nowSec: number, - ): void { - if (clan.members.some((m) => m.uid === uid)) return; - const todayDay = Math.floor(nowSec / 86400); - const periods = buildDefaultPeriods(todayDay, 360); - clan.members.push({ - uid, - nick, - role, - joinDateSec: nowSec, - curActivity: 360, - totalActivity: periods.reduce((s, p) => s + p.activity, 0), - earnedSquadronExp: periods.reduce((s, p) => s + p.exp, 0), - ratingArc: 1450, - ratingHist: 1500, - ratingSim: 1400, - periods, - }); - this.#appendLog(clan, { - ev: 'add', - timeSec: nowSec, - uId: initiatorUid, - uN: initiatorNick, - uid, - nick, - role: roleNameOf(role), - }); - } - - #clearCandidateEverywhere(userId: string): void { - for (const clan of this.#state.clans) { - clan.candidates = clan.candidates.filter((c) => c.uid !== userId); - } - } - - #appendLog(clan: ClanRecord, entry: Omit): void { - const nextId = clan.logs.reduce((max, item) => Math.max(max, item.id), 0) + 1; - clan.logs.push({ id: nextId, ...entry }); + return true; } } -function stripDecorators(tag: string): string { - return tag.replace(/^[\[\-\.\=\^\*]+|[\]\-\.\=\^\*]+$/g, ''); -} - -function metricOf(clan: ClanRecord, sortField: string): number { - switch (sortField) { - case 'activity': - case 'clan_activity_by_periods': - return totalPeriodActivityOf(clan); - case 'members_cnt': - return clan.members.length; - case 'dr_era5_arc': - return clan.stats.dr_era5_arc; - case 'dr_era5_sim': - return clan.stats.dr_era5_sim; - case 'dr_era5_hist': - default: - return clan.stats.dr_era5_hist; - } +function nowSeconds(): number { + return Math.floor(Date.now() / 1000); } diff --git a/packages/local-service/src/cloud-settings/cloud-settings-store.ts b/packages/local-service/src/cloud-settings/cloud-settings-store.ts index 45d9491..0d26e84 100644 --- a/packages/local-service/src/cloud-settings/cloud-settings-store.ts +++ b/packages/local-service/src/cloud-settings/cloud-settings-store.ts @@ -63,7 +63,7 @@ export class CloudSettingsStore { /** Load a stored `ContainerBlk` (`version:i` + `content { ... }`) for `cln_get_general_blk`. */ loadContainer(userId: string, blkType: string): BlkBlock | undefined { - if (!isValidUserId(userId) || !isValidBlkType(blkType)) return undefined; + if (!isValidUserId(userId) || !isSupportedGeneralBlkType(blkType)) return undefined; const blkPath = this.#blkPath(userId, blkType); if (!existsSync(blkPath)) return undefined; try { @@ -75,7 +75,7 @@ export class CloudSettingsStore { /** Persist a single uploaded `ContainerBlk` and update `meta.json` atomically. */ saveUpload(userId: string, upload: ParsedGblkUpload): boolean { - if (!isValidUserId(userId) || !isValidBlkType(upload.blkType)) return false; + if (!isValidUserId(userId) || !isSupportedGeneralBlkType(upload.blkType)) return false; const meta = this.#loadMeta(userId); const nextVersion = Math.max(1, Math.trunc(upload.version)); setParam(upload.container, 'version', { type: 'int', value: nextVersion }); @@ -126,10 +126,12 @@ export class CloudSettingsStore { } } +const SUPPORTED_BLK_TYPE_SET: ReadonlySet = new Set(GENERAL_BLK_TYPES); + function isValidUserId(userId: string): boolean { return /^\d+$/.test(userId); } -function isValidBlkType(blkType: string): boolean { - return /^[A-Za-z0-9_.-]{1,80}$/.test(blkType); +export function isSupportedGeneralBlkType(blkType: string): boolean { + return SUPPORTED_BLK_TYPE_SET.has(blkType); } diff --git a/packages/local-service/src/inventory/chest-defs.ts b/packages/local-service/src/inventory/chest-defs.ts new file mode 100644 index 0000000..c68bab9 --- /dev/null +++ b/packages/local-service/src/inventory/chest-defs.ts @@ -0,0 +1,178 @@ +/** + * External Silver-Lion supply chests (`910001`, `910002`) and their keyless open generators + * (`910101`, `910102`), using deterministic rank-and-country prize selection. + */ +import type { LocalizedText } from '../game-data/datasets/unit-names.ts'; +import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts'; +import { + makeLocalizedItemDef, + QUALITY_COLORS, + type ExternalItemPrice, + type GeneratorDefinition, + type GeneratorDrop, + type LocalizedItemDef, +} from './itemdef-types.ts'; + +export const TACTICAL_CHEST_ID = 910001; +export const COLLECTOR_CHEST_ID = 910002; +const TACTICAL_CHEST_GEN_ID = 910101; +const COLLECTOR_CHEST_GEN_ID = 910102; + +export interface SupplyChestSources { + readonly wrappersByPart: ReadonlyMap; + readonly skinCouponIds: readonly number[]; + readonly decalCouponIds: readonly number[]; + readonly attachableCouponIds: readonly number[]; + /** Sorted deterministically by (rank, country, name). */ + readonly sortedMarketVehicles: readonly CatalogueVehicle[]; +} + +export interface SupplyChestBuildResult { + readonly defs: readonly LocalizedItemDef[]; + readonly prices: readonly ExternalItemPrice[]; + readonly generators: readonly GeneratorDefinition[]; +} + +export function buildSupplyChests(sources: SupplyChestSources): SupplyChestBuildResult { + const commonWrappers = [ + ...(sources.wrappersByPart.get(299000) ?? []).slice(0, 3), + ...(sources.wrappersByPart.get(299001) ?? []).slice(0, 5), + ...(sources.wrappersByPart.get(299003) ?? []).slice(0, 2), + ]; + + const tacticalDecors = [ + ...sources.skinCouponIds.slice(0, 3), + ...sources.decalCouponIds.slice(0, 2), + ...sources.attachableCouponIds.slice(0, 3), + ]; + const collectorDecors = [ + ...sources.skinCouponIds.slice(3, 8), + ...sources.decalCouponIds.slice(2, 4), + ...sources.attachableCouponIds.slice(3, 8), + ]; + + const midTierVehicles = pickAcrossCountries( + sources.sortedMarketVehicles.filter((v) => v.rank <= 4), + 6, + ).map((v) => v.marketplaceItemdefId!); + const highTierVehicles = pickAcrossCountries( + sources.sortedMarketVehicles.filter((v) => v.rank >= 5), + 10, + ).map((v) => v.marketplaceItemdefId!); + + const tactical = createChestPair({ + chestId: TACTICAL_CHEST_ID, + genId: TACTICAL_CHEST_GEN_ID, + silverLions: 60_000, + quality: 2, + icon: '!#ui/images/chests/items_box2.avif', + title: { en: 'Tactical Supply Chest', zh: '战术物资补给箱' }, + desc: { + en: 'Silver-Lion supply chest containing boosters, universal backups, decorator coupons, and Rank I-IV vehicle coupons.', + zh: '银狮物资补给箱:内含加成卡、通用备用载具、涂装/贴花/挂件券及 I~IV 级市场载具兑换券(点击可查看各项精确掉率)。', + }, + drops: [ + ...commonWrappers.map((itemdefId) => ({ itemdefId, weight: 80 })), + ...tacticalDecors.map((itemdefId) => ({ itemdefId, weight: 18 })), + ...midTierVehicles.map((itemdefId) => ({ itemdefId, weight: 4 })), + ], + }); + + const collector = createChestPair({ + chestId: COLLECTOR_CHEST_ID, + genId: COLLECTOR_CHEST_GEN_ID, + silverLions: 250_000, + quality: 4, + icon: '!#ui/images/chests/items_box3.avif', + title: { en: "Collector's Supply Chest", zh: '典藏收藏家补给箱' }, + desc: { + en: 'High-tier Silver-Lion supply chest with elevated drop rates for Rank V+ marketplace vehicle and decorator coupons.', + zh: '高阶银狮补给箱:大幅提升 V 级以上稀有市场载具兑换券与 3D 装饰挂件/涂装券的掉落概率。', + }, + drops: [ + ...commonWrappers.slice(0, 5).map((itemdefId) => ({ itemdefId, weight: 45 })), + ...collectorDecors.map((itemdefId) => ({ itemdefId, weight: 22 })), + ...(highTierVehicles.length ? highTierVehicles : midTierVehicles).map((itemdefId) => ({ itemdefId, weight: 12 })), + ], + }); + + return { + defs: [...tactical.defs, ...collector.defs], + prices: [tactical.price, collector.price], + generators: [tactical.generator, collector.generator], + }; +} + +/** + * Deterministically select `limit` vehicles from an already `(rank, country, name)`-sorted list, + * rotating across distinct countries first so every major nation is represented before repeating. + */ +export function pickAcrossCountries(sorted: readonly CatalogueVehicle[], limit: number): CatalogueVehicle[] { + const picked: CatalogueVehicle[] = []; + const usedNames = new Set(); + const seenCountriesInPass = new Set(); + + while (picked.length < limit && picked.length < sorted.length) { + seenCountriesInPass.clear(); + let addedInPass = false; + for (const vehicle of sorted) { + if (usedNames.has(vehicle.name) || seenCountriesInPass.has(vehicle.country)) continue; + seenCountriesInPass.add(vehicle.country); + usedNames.add(vehicle.name); + picked.push(vehicle); + addedInPass = true; + if (picked.length >= limit) break; + } + if (!addedInPass) break; + } + return picked; +} + +function createChestPair(spec: { + readonly chestId: number; + readonly genId: number; + readonly silverLions: number; + readonly quality: number; + readonly icon: string; + readonly title: LocalizedText; + readonly desc: LocalizedText; + readonly drops: readonly GeneratorDrop[]; +}): { + readonly defs: readonly LocalizedItemDef[]; + readonly price: ExternalItemPrice; + readonly generator: GeneratorDefinition; +} { + const color = QUALITY_COLORS[spec.quality] ?? '45aacc'; + const chestDef = makeLocalizedItemDef(spec.chestId, { + type: 'item', + marketable: false, + item_quality: spec.quality, + name_color: color, + used_to_create: `${spec.genId}x1`, + tags: 'type:chest;showChances:yes;allowToBuyAmount:10;isAllowSkipOpeningAnim:yes;hideMarketablePropDesc:yes', + icon_url: spec.icon, + }, spec.title, spec.desc); + + const genDef = makeLocalizedItemDef(spec.genId, { + type: 'generator', + marketable: false, + item_quality: spec.quality, + name_color: color, + exchange: `${spec.chestId}x1`, + bundle: spec.drops.map((d) => `${d.itemdefId}x1`).join(';'), + tags: 'devItem:yes', + icon_url: spec.icon, + }, spec.title, { en: '', zh: '' }); + + return { + defs: [chestDef, genDef], + price: { itemdefId: spec.chestId, silverLions: spec.silverLions, goldenEagles: 0 }, + generator: { + itemdefId: spec.genId, + isChestGenerator: true, + chestItemdefId: spec.chestId, + recipes: [{ components: [{ itemdefId: spec.chestId, quantity: 1 }] }], + drops: spec.drops, + }, + }; +} diff --git a/packages/local-service/src/inventory/coupons/cosmetic-coupons.ts b/packages/local-service/src/inventory/coupons/cosmetic-coupons.ts new file mode 100644 index 0000000..5edc01c --- /dev/null +++ b/packages/local-service/src/inventory/coupons/cosmetic-coupons.ts @@ -0,0 +1,154 @@ +/** + * Decorator coupons (skins, decals, attachables), unlock/profile-icon coupons, and hidden + * workshop stub itemdefs. + */ +import type { + ExternalItemSources, + MarketplaceDecorCoupon, + MarketplaceUnlockCoupon, +} from '../../game-data/datasets/external-item-sources.ts'; +import { + makeLocalizedItemDef, + QUALITY_COLORS, + type CouponAction, + type LocalizedItemDef, + type MarketplaceListing, +} from '../itemdef-types.ts'; + +export const DECOR_COUPON_GJN = { skin: 5, decal: 3, attachable: 8 } as const; +export const UNLOCK_COUPON_GJN = 6; + +const ICON_BY_KIND = { + skin: '!#ui/gameuiskin#item_type_skin.svg', + decal: '!#ui/gameuiskin#item_type_decal.svg', + attachable: '!#ui/gameuiskin#item_type_attachable.svg', +} as const; + +const LABEL_ZH_BY_KIND = { + skin: '涂装兑换券', + decal: '贴花兑换券', + attachable: '3D 装饰挂件兑换券', +} as const; + +export interface CosmeticCouponBuildResult { + readonly defs: readonly LocalizedItemDef[]; + readonly coupons: ReadonlyArray; + readonly listings: readonly MarketplaceListing[]; + /** Sorted ascending by itemdefId per category for deterministic chest selection. */ + readonly skinCouponIds: readonly number[]; + readonly decalCouponIds: readonly number[]; + readonly attachableCouponIds: readonly number[]; + readonly workshopStubs: readonly LocalizedItemDef[]; +} + +export function buildCosmeticCoupons(sources: ExternalItemSources): CosmeticCouponBuildResult { + const defs: LocalizedItemDef[] = []; + const coupons: Array = []; + const listings: MarketplaceListing[] = []; + const skinCouponIds: number[] = []; + const decalCouponIds: number[] = []; + const attachableCouponIds: number[] = []; + + const sortedDecors = [...sources.decorCoupons].sort((a, b) => a.itemdefId - b.itemdefId); + for (const decor of sortedDecors) { + const built = buildSingleDecorCoupon(decor); + defs.push(built.def); + coupons.push([decor.itemdefId, built.action]); + listings.push(built.listing); + if (decor.kind === 'skin') skinCouponIds.push(decor.itemdefId); + else if (decor.kind === 'decal') decalCouponIds.push(decor.itemdefId); + else attachableCouponIds.push(decor.itemdefId); + } + + const sortedUnlocks = [...sources.unlockCoupons].sort((a, b) => a.itemdefId - b.itemdefId); + for (const unlock of sortedUnlocks) { + const built = buildSingleUnlockCoupon(unlock); + defs.push(built.def); + coupons.push([unlock.itemdefId, built.action]); + listings.push(built.listing); + } + + const workshopStubs = [...sources.workshopItemdefIds] + .sort((a, b) => a - b) + .map((workshopId) => makeLocalizedItemDef(workshopId, { + type: 'item', + marketable: false, + item_quality: 1, + tags: 'type:craft_part;devItem:yes;hideDesc:yes', + icon_url: '!#ui/gameuiskin#item_type_craftpart.svg', + }, { en: `Workshop Component #${workshopId}`, zh: `工坊组件 #${workshopId}` }, { en: '', zh: '' })); + + return { defs, coupons, listings, skinCouponIds, decalCouponIds, attachableCouponIds, workshopStubs }; +} + +function buildSingleDecorCoupon(decor: MarketplaceDecorCoupon): { + readonly def: LocalizedItemDef; + readonly action: CouponAction; + readonly listing: MarketplaceListing; +} { + const quality = decor.kind === 'attachable' ? 3 : 2; + const color = QUALITY_COLORS[quality] ?? '45aacc'; + const hashName = `${decor.kind}_${decor.itemdefId}`; + const def = makeLocalizedItemDef(decor.itemdefId, { + type: 'item', + marketable: true, + market_hash_name: hashName, + item_quality: quality, + name_color: color, + tags: `type:${decor.kind}`, + meta: `resource:t="${decor.resourceKey}"\nresourceType:t="${decor.kind}"`, + icon_url: ICON_BY_KIND[decor.kind], + }, decor.name, { + en: `Coupon for ${decor.kind}: ${decor.name.en}.`, + zh: `${LABEL_ZH_BY_KIND[decor.kind]}:${decor.name.zh}。`, + }); + const action: CouponAction = { kind: 'decor', decorKind: decor.kind, resourceKey: decor.resourceKey }; + const listing: MarketplaceListing = { + itemdefId: decor.itemdefId, + marketHashName: hashName, + category: decor.kind, + gjnCost: DECOR_COUPON_GJN[decor.kind], + quality, + nameColor: color, + title: decor.name, + subtitle: { en: `${decor.kind} coupon`, zh: LABEL_ZH_BY_KIND[decor.kind] }, + targetKey: decor.resourceKey, + }; + return { def, action, listing }; +} + +function buildSingleUnlockCoupon(unlock: MarketplaceUnlockCoupon): { + readonly def: LocalizedItemDef; + readonly action: CouponAction; + readonly listing: MarketplaceListing; +} { + const quality = 3; + const color = QUALITY_COLORS[quality] ?? '5599ff'; + const hashName = `unlock_${unlock.itemdefId}`; + const def = makeLocalizedItemDef(unlock.itemdefId, { + type: 'item', + marketable: true, + market_hash_name: hashName, + item_quality: quality, + name_color: color, + tags: 'type:unlock', + meta: `unlock:t="${unlock.unlockId}"`, + icon_url: '!#ui/gameuiskin#item_type_unlock.svg', + }, unlock.name, { + en: `Coupon for unlock: ${unlock.name.en}.`, + zh: `头像/收藏解锁兑换券:${unlock.name.zh}。`, + }); + const action: CouponAction = { kind: 'unlock', unlockId: unlock.unlockId }; + const listing: MarketplaceListing = { + itemdefId: unlock.itemdefId, + marketHashName: hashName, + category: 'unlock', + gjnCost: UNLOCK_COUPON_GJN, + quality, + nameColor: color, + title: unlock.name, + subtitle: { en: 'Profile icon / unlock coupon', zh: '头像与解锁兑换券' }, + targetKey: unlock.unlockId, + }; + return { def, action, listing }; +} diff --git a/packages/local-service/src/inventory/coupons/vehicle-coupons.ts b/packages/local-service/src/inventory/coupons/vehicle-coupons.ts new file mode 100644 index 0000000..1abff7b --- /dev/null +++ b/packages/local-service/src/inventory/coupons/vehicle-coupons.ts @@ -0,0 +1,120 @@ +/** + * Marketplace vehicle coupon definitions (`shop.blk` `marketplaceItemdefId`, 233 vehicles in + * 2.61.0.37; implementation notes). + */ +import type { LocalizedText } from '../../game-data/datasets/unit-names.ts'; +import type { CatalogueVehicle } from '../../game-data/datasets/vehicle-catalogue.ts'; +import { vehicleTypeOfClass } from '../../research/vehicle-types.ts'; +import { + makeLocalizedItemDef, + QUALITY_COLORS, + type CouponAction, + type LocalizedItemDef, + type MarketplaceListing, +} from '../itemdef-types.ts'; + +export const MARKET_VEHICLE_GJN_BY_RANK: Readonly> = { + 1: 8, + 2: 14, + 3: 22, + 4: 35, + 5: 48, + 6: 59, + 7: 69, + 8: 75, +}; + +export interface VehicleCouponBuildResult { + readonly defs: readonly LocalizedItemDef[]; + readonly coupons: ReadonlyArray; + readonly listings: readonly MarketplaceListing[]; + /** Marketplace vehicles sorted deterministically by (rank, country, name). */ + readonly sortedVehicles: readonly CatalogueVehicle[]; +} + +export function buildVehicleCoupons( + vehicles: readonly CatalogueVehicle[], + unitNames: Readonly>, +): VehicleCouponBuildResult { + const defs: LocalizedItemDef[] = []; + const coupons: Array = []; + const listings: MarketplaceListing[] = []; + + const sortedVehicles = vehicles + .filter((vehicle) => vehicle.marketplaceItemdefId !== undefined) + .sort((a, b) => (a.rank - b.rank) || a.country.localeCompare(b.country) || a.name.localeCompare(b.name)); + + for (const vehicle of sortedVehicles) { + const id = vehicle.marketplaceItemdefId!; + const unitTitle = unitNames[vehicle.name] ?? { en: vehicle.name, zh: vehicle.name }; + const quality = vehicle.rank >= 6 ? 4 : vehicle.rank >= 4 ? 3 : 2; + const color = QUALITY_COLORS[quality] ?? '45aacc'; + const gjnCost = MARKET_VEHICLE_GJN_BY_RANK[vehicle.rank] ?? 45; + const tagType = unitClassTag(vehicle.unitClass); + + defs.push(makeLocalizedItemDef(id, { + type: 'item', + marketable: true, + market_hash_name: vehicle.name, + item_quality: quality, + name_color: color, + tags: `type:${tagType}`, + meta: `unit:t="${vehicle.name}"`, + icon_url: '!#ui/gameuiskin#item_type_blueprints.svg', + icon_url_large: '!#ui/gameuiskin#item_type_blueprints.svg', + }, unitTitle, { + en: `Exchangeable coupon for ${unitTitle.en} (Rank ${vehicle.rank}).`, + zh: `可兑换载具券:${unitTitle.zh}(${vehicle.rank} 级)。`, + })); + coupons.push([id, { kind: 'vehicle', unitName: vehicle.name, parts: vehicle.parts }]); + listings.push({ + itemdefId: id, + marketHashName: vehicle.name, + category: 'vehicle', + gjnCost, + quality, + nameColor: color, + title: unitTitle, + subtitle: { en: `Rank ${vehicle.rank} ${tagType}`, zh: `${vehicle.rank} 级载具兑换券` }, + country: vehicle.country, + unitClass: marketUnitClassOf(vehicle.unitClass), + rank: vehicle.rank, + targetKey: vehicle.name, + }); + } + + return { defs, coupons, listings, sortedVehicles }; +} + +function unitClassTag(unitClass: string): string { + switch (vehicleTypeOfClass(unitClass)) { + case 'Aircraft': + return 'aircraft'; + case 'Helicopter': + return 'helicopter'; + case 'Tank': + return 'tank'; + case 'Ship': + case 'Boat': + return 'ship'; + default: + return 'tank'; + } +} + +function marketUnitClassOf(unitClass: string): string { + switch (vehicleTypeOfClass(unitClass)) { + case 'Aircraft': + return 'aircraft'; + case 'Helicopter': + return 'helicopter'; + case 'Tank': + return 'tank'; + case 'Ship': + return 'ship'; + case 'Boat': + return 'boat'; + default: + return 'tank'; + } +} diff --git a/packages/local-service/src/inventory/inventory-rules.ts b/packages/local-service/src/inventory/inventory-rules.ts index 00958e8..0a7c202 100644 --- a/packages/local-service/src/inventory/inventory-rules.ts +++ b/packages/local-service/src/inventory/inventory-rules.ts @@ -165,6 +165,45 @@ export interface ExchangeMaterialInput { readonly quantity: number; } +export interface ParsedExchangeRequest { + readonly outputItemDefId: number; + readonly quantity: number; + readonly materials: readonly ExchangeMaterialInput[]; +} + +export function parseExchangeItemsRequest(rawText: string): ParsedExchangeRequest | undefined { + let parsed: Record; + try { + const raw = JSON.parse(rawText) as Record; + parsed = typeof raw.data === 'object' && raw.data !== null ? (raw.data as Record) : raw; + } catch { + return undefined; + } + const outputItemDefId = Number(parsed.outputitemdefid ?? 0); + const quantity = Number(parsed.quantity ?? 1); + const rawMaterials = Array.isArray(parsed.materials) ? parsed.materials : []; + const materials: ExchangeMaterialInput[] = rawMaterials.flatMap((m) => { + if (typeof m !== 'object' || m === null) return []; + const rec = m as Record; + return [{ + itemid: String(rec.itemid ?? ''), + itemdefid: Number(rec.itemdefid ?? 0), + quantity: Number(rec.quantity ?? 0), + }]; + }); + return { outputItemDefId, quantity, materials }; +} + +export function pickWeighted(entries: readonly T[]): T { + const total = entries.reduce((sum, entry) => sum + entry.weight, 0); + let roll = Math.random() * total; + for (const entry of entries) { + roll -= entry.weight; + if (roll <= 0) return entry; + } + return entries[entries.length - 1]!; +} + export type ExchangeOutcome = | { readonly ok: true; readonly delta: InventoryItemJson[] } | { readonly ok: false; readonly code: string }; @@ -217,7 +256,7 @@ export function exchangeInventoryItems( } for (let i = 0; i < quantity; i += 1) { - const dropDefId = rollWeightedDrop(gen.drops); + const dropDefId = pickWeighted(gen.drops).itemdefId; const granted = grantExternalItem(profile, dropDefId, 1, nowIso); deltaByUid.set(granted.itemId, toInventoryJson(granted, accountId)); @@ -256,13 +295,3 @@ export function buyMarketplaceCoupon( const item = grantExternalItem(profile, itemdefId, quantity); return { ok: true, item }; } - -function rollWeightedDrop(drops: readonly GeneratorDrop[]): number { - const total = drops.reduce((sum, entry) => sum + entry.weight, 0); - let roll = Math.random() * total; - for (const entry of drops) { - roll -= entry.weight; - if (roll <= 0) return entry.itemdefId; - } - return drops[drops.length - 1]!.itemdefId; -} diff --git a/packages/local-service/src/inventory/inventory-service.ts b/packages/local-service/src/inventory/inventory-service.ts index 47354ee..ee3c520 100644 --- a/packages/local-service/src/inventory/inventory-service.ts +++ b/packages/local-service/src/inventory/inventory-service.ts @@ -9,7 +9,7 @@ import type { Account, AccountStore } from '../accounts/account-store.ts'; import { userIdFromToken } from '../login/session-credentials.ts'; import type { PlayerProfiles } from '../profile/player-profiles.ts'; import type { Service, ServiceRequest, ServiceResponse } from '../server/exchange.ts'; -import { exchangeInventoryItems, toInventoryJsonList, type ExchangeMaterialInput } from './inventory-rules.ts'; +import { exchangeInventoryItems, parseExchangeItemsRequest, toInventoryJsonList } from './inventory-rules.ts'; import type { InventoryCatalogue } from './itemdef-catalogue.ts'; const INVENTORY_HOST = /^inventory-proxy-[a-z0-9-]+\.gaijin\.net$/; @@ -85,31 +85,20 @@ export class InventoryService implements Service { const account = this.#resolveAccount(request); if (!account) return errorResponse('UNAUTHORIZED', 'ExchangeItems: unknown account'); - let parsed: Record; - try { - const raw = JSON.parse(request.body.toString('utf8')) as Record; - parsed = typeof raw.data === 'object' && raw.data !== null ? raw.data as Record : raw; - } catch { - return errorResponse('BAD_JSON', 'ExchangeItems: invalid JSON'); - } - - const outputItemDefId = Number(parsed.outputitemdefid ?? 0); - const quantity = Number(parsed.quantity ?? 1); - const rawMaterials = Array.isArray(parsed.materials) ? parsed.materials : []; - const materials: ExchangeMaterialInput[] = rawMaterials.flatMap((m) => { - if (typeof m !== 'object' || m === null) return []; - const rec = m as Record; - return [{ - itemid: String(rec.itemid ?? ''), - itemdefid: Number(rec.itemdefid ?? 0), - quantity: Number(rec.quantity ?? 0), - }]; - }); + const parsed = parseExchangeItemsRequest(request.body.toString('utf8')); + if (!parsed) return errorResponse('BAD_JSON', 'ExchangeItems: invalid JSON'); let delta: unknown[] | undefined; let errorCode = 'EXCHANGE_FAILED'; this.#profiles.updateWhen(account.userId, (saved) => { - const res = exchangeInventoryItems(saved, account.userId, this.#catalogue, outputItemDefId, quantity, materials); + const res = exchangeInventoryItems( + saved, + account.userId, + this.#catalogue, + parsed.outputItemDefId, + parsed.quantity, + parsed.materials, + ); if (!res.ok) { errorCode = res.code; return false; @@ -118,8 +107,8 @@ export class InventoryService implements Service { return true; }); - if (!delta) return errorResponse(errorCode, `ExchangeItems (${outputItemDefId}) -> ${errorCode}`); - return jsonResponse({ response: { item_json: delta } }, `ExchangeItems (${outputItemDefId} x${quantity}) -> ${delta.length} delta item(s)`); + if (!delta) return errorResponse(errorCode, `ExchangeItems (${parsed.outputItemDefId}) -> ${errorCode}`); + return jsonResponse({ response: { item_json: delta } }, `ExchangeItems (${parsed.outputItemDefId} x${parsed.quantity}) -> ${delta.length} delta item(s)`); } #resolveAccount(request: ServiceRequest): Account | undefined { diff --git a/packages/local-service/src/inventory/itemdef-catalogue.ts b/packages/local-service/src/inventory/itemdef-catalogue.ts index 82e369c..e5e9e48 100644 --- a/packages/local-service/src/inventory/itemdef-catalogue.ts +++ b/packages/local-service/src/inventory/itemdef-catalogue.ts @@ -1,68 +1,29 @@ /** - * Generated external inventory item definitions (`GetItemDefsClient`), item shop prices - * (`GetItemPrices`), generator drop tables (`GetItemDefChances` & `ExchangeItems`), and - * GJN marketplace listings. + * Lookup catalogue assembling generated external inventory item definitions (`GetItemDefsClient`), + * item shop prices (`GetItemPrices`), generator drop tables (`GetItemDefChances` & `ExchangeItems`), + * and GJN marketplace listings from category-specific builders. */ -import type { ExternalItemSources, MarketplaceDecorCoupon, MarketplaceUnlockCoupon } from '../game-data/datasets/external-item-sources.ts'; +import type { ExternalItemSources } from '../game-data/datasets/external-item-sources.ts'; import type { ItemDefinition } from '../game-data/datasets/item-catalogue.ts'; import type { LocalizedText } from '../game-data/datasets/unit-names.ts'; import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts'; -import { vehicleTypeOfClass } from '../research/vehicle-types.ts'; -import type { CouponAction, GeneratorDrop, ItemDefRecord, MarketplaceListing } from './itemdef-types.ts'; +import { buildSupplyChests, COLLECTOR_CHEST_ID, TACTICAL_CHEST_ID } from './chest-defs.ts'; +import { buildCosmeticCoupons } from './coupons/cosmetic-coupons.ts'; +import { buildVehicleCoupons } from './coupons/vehicle-coupons.ts'; +import { + DEFAULT_ITEMDEF_TIMESTAMP, + type CouponAction, + type ExternalItemPrice, + type GeneratorDefinition, + type GeneratorRecipe, + type ItemDefRecord, + type LocalizedItemDef, + type MarketplaceListing, +} from './itemdef-types.ts'; +import { buildRecyclingDefs } from './recycling-defs.ts'; -const DEFAULT_TIMESTAMP = '2026-01-01T00:00:00Z'; - -const RECYCLE_PART_IDS = [299000, 299001, 299002, 299003, 299004] as const; -const RECYCLE_SINGLE_OFFSET = 20; -const RECYCLE_GENERIC_GENERATOR_ID = 299030; - -export const TACTICAL_CHEST_ID = 910001; -export const COLLECTOR_CHEST_ID = 910002; -const TACTICAL_CHEST_GEN_ID = 910101; -const COLLECTOR_CHEST_GEN_ID = 910102; - -interface LocalizedItemDef { - readonly base: Omit; - readonly name: LocalizedText; - readonly description: LocalizedText; -} - -export interface ExternalItemPrice { - readonly itemdefId: number; - readonly silverLions: number; - readonly goldenEagles: number; -} - -export interface GeneratorRecipe { - readonly components: ReadonlyArray<{ readonly itemdefId: number; readonly quantity: number }>; -} - -export interface GeneratorDefinition { - readonly itemdefId: number; - readonly isChestGenerator: boolean; - readonly chestItemdefId?: number; - readonly recipes: readonly GeneratorRecipe[]; - readonly drops: readonly GeneratorDrop[]; -} - -const MARKET_VEHICLE_GJN_BY_RANK: Readonly> = { - 1: 8, - 2: 14, - 3: 22, - 4: 35, - 5: 48, - 6: 59, - 7: 69, - 8: 75, -}; - -const QUALITY_COLORS: Readonly> = { - 1: '', - 2: '45aacc', - 3: '5599ff', - 4: 'aa66ff', - 5: 'dd8833', -}; +export { COLLECTOR_CHEST_ID, TACTICAL_CHEST_ID }; +export type { ExternalItemPrice, GeneratorDefinition, GeneratorRecipe }; export class InventoryCatalogue { readonly #defs = new Map(); @@ -78,82 +39,35 @@ export class InventoryCatalogue { sources: ExternalItemSources, classicItems: readonly ItemDefinition[], ) { - const vehicleCouponIds: number[] = []; - const decorCouponIds: number[] = []; + const vehicleCoupons = buildVehicleCoupons(vehicles, unitNames); + const cosmeticCoupons = buildCosmeticCoupons(sources); + const recycling = buildRecyclingDefs(classicItems); + const chests = buildSupplyChests({ + wrappersByPart: recycling.wrappersByPart, + skinCouponIds: cosmeticCoupons.skinCouponIds, + decalCouponIds: cosmeticCoupons.decalCouponIds, + attachableCouponIds: cosmeticCoupons.attachableCouponIds, + sortedMarketVehicles: vehicleCoupons.sortedVehicles, + }); - // 1. 233 Marketplace vehicle coupons - for (const vehicle of vehicles) { - if (!vehicle.marketplaceItemdefId) continue; - const id = vehicle.marketplaceItemdefId; - const unitTitle = unitNames[vehicle.name] ?? { en: vehicle.name, zh: vehicle.name }; - const quality = vehicle.rank >= 6 ? 4 : vehicle.rank >= 4 ? 3 : 2; - const color = QUALITY_COLORS[quality] ?? '45aacc'; - const gjnCost = MARKET_VEHICLE_GJN_BY_RANK[vehicle.rank] ?? 45; - const tagType = unitClassTag(vehicle.unitClass); - const marketUnitClass = marketUnitClassOf(vehicle.unitClass); - - this.#addDef(id, { - type: 'item', - marketable: true, - market_hash_name: vehicle.name, - item_quality: quality, - name_color: color, - tags: `type:${tagType}`, - meta: `unit:t="${vehicle.name}"`, - icon_url: '!#ui/gameuiskin#item_type_blueprints.svg', - icon_url_large: '!#ui/gameuiskin#item_type_blueprints.svg', - }, unitTitle, { - en: `Exchangeable coupon for ${unitTitle.en} (Rank ${vehicle.rank}).`, - zh: `可兑换载具券:${unitTitle.zh}(${vehicle.rank} 级)。`, - }); - this.#coupons.set(id, { kind: 'vehicle', unitName: vehicle.name, parts: vehicle.parts }); - vehicleCouponIds.push(id); - this.#addMarketListing({ - itemdefId: id, - marketHashName: vehicle.name, - category: 'vehicle', - gjnCost, - quality, - nameColor: color, - title: unitTitle, - subtitle: { en: `Rank ${vehicle.rank} ${tagType}`, zh: `${vehicle.rank} 级载具兑换券` }, - country: vehicle.country, - unitClass: marketUnitClass, - rank: vehicle.rank, - targetKey: vehicle.name, - }); + for (const def of [...vehicleCoupons.defs, ...cosmeticCoupons.defs, ...recycling.defs, ...chests.defs]) { + this.#defs.set(def.itemdefId, def); } - - // 2. Decorator coupons (skins, decals, attachables) - for (const decor of sources.decorCoupons) { - this.#registerDecorCoupon(decor); - decorCouponIds.push(decor.itemdefId); + for (const stub of cosmeticCoupons.workshopStubs) { + if (!this.#defs.has(stub.itemdefId)) this.#defs.set(stub.itemdefId, stub); } - - // 3. Unlock / pilot-icon coupons - for (const unlock of sources.unlockCoupons) { - this.#registerUnlockCoupon(unlock); - decorCouponIds.push(unlock.itemdefId); + for (const [id, action] of [...vehicleCoupons.coupons, ...cosmeticCoupons.coupons, ...recycling.coupons]) { + this.#coupons.set(id, action); } - - // 4. Classic item wrappers (autoConsume internal_item) + recycle craft parts & generators - const classicWrapperIds = this.#registerClassicWrappers(classicItems); - this.#registerRecycleSystem(classicWrapperIds); - - // 5. External Silver-Lion supply chests & open generators - this.#registerSupplyChests(classicWrapperIds, decorCouponIds, vehicleCouponIds); - - // 6. Workshop config referenced IDs (hidden stubs so login itemdef requests succeed cleanly) - for (const workshopId of sources.workshopItemdefIds) { - if (this.#defs.has(workshopId)) continue; - this.#addDef(workshopId, { - type: 'item', - marketable: false, - item_quality: 1, - tags: 'type:craft_part;devItem:yes;hideDesc:yes', - icon_url: '!#ui/gameuiskin#item_type_craftpart.svg', - icon_url_large: '!#ui/gameuiskin#item_type_craftpart.svg', - }, { en: `Workshop Component #${workshopId}`, zh: `工坊组件 #${workshopId}` }, { en: '', zh: '' }); + for (const price of chests.prices) { + this.#prices.set(price.itemdefId, price); + } + for (const gen of [...recycling.generators, ...chests.generators]) { + this.#generators.set(gen.itemdefId, gen); + } + for (const listing of [...vehicleCoupons.listings, ...cosmeticCoupons.listings]) { + this.#marketListings.push(listing); + this.#marketById.set(listing.itemdefId, listing); } } @@ -213,376 +127,6 @@ export class InventoryCatalogue { hasItemDef(itemdefId: number): boolean { return this.#defs.has(itemdefId); } - - #registerDecorCoupon(decor: MarketplaceDecorCoupon): void { - const quality = decor.kind === 'attachable' ? 3 : 2; - const color = QUALITY_COLORS[quality] ?? '45aacc'; - const iconByKind = { - skin: '!#ui/gameuiskin#item_type_skin.svg', - decal: '!#ui/gameuiskin#item_type_decal.svg', - attachable: '!#ui/gameuiskin#item_type_attachable.svg', - } as const; - const gjnByKind = { skin: 5, decal: 3, attachable: 8 } as const; - const labelZh = { skin: '涂装兑换券', decal: '贴花兑换券', attachable: '3D 装饰挂件兑换券' } as const; - const hashName = `${decor.kind}_${decor.itemdefId}`; - - this.#addDef(decor.itemdefId, { - type: 'item', - marketable: true, - market_hash_name: hashName, - item_quality: quality, - name_color: color, - tags: `type:${decor.kind}`, - meta: `resource:t="${decor.resourceKey}"\nresourceType:t="${decor.kind}"`, - icon_url: iconByKind[decor.kind], - icon_url_large: iconByKind[decor.kind], - }, decor.name, { - en: `Coupon for ${decor.kind}: ${decor.name.en}.`, - zh: `${labelZh[decor.kind]}:${decor.name.zh}。`, - }); - this.#coupons.set(decor.itemdefId, { kind: 'decor', decorKind: decor.kind, resourceKey: decor.resourceKey }); - this.#addMarketListing({ - itemdefId: decor.itemdefId, - marketHashName: hashName, - category: decor.kind, - gjnCost: gjnByKind[decor.kind], - quality, - nameColor: color, - title: decor.name, - subtitle: { en: `${decor.kind} coupon`, zh: labelZh[decor.kind] }, - targetKey: decor.resourceKey, - }); - } - - #registerUnlockCoupon(unlock: MarketplaceUnlockCoupon): void { - const quality = 3; - const color = QUALITY_COLORS[quality] ?? '5599ff'; - const hashName = `unlock_${unlock.itemdefId}`; - this.#addDef(unlock.itemdefId, { - type: 'item', - marketable: true, - market_hash_name: hashName, - item_quality: quality, - name_color: color, - tags: 'type:unlock', - meta: `unlock:t="${unlock.unlockId}"`, - icon_url: '!#ui/gameuiskin#item_type_unlock.svg', - icon_url_large: '!#ui/gameuiskin#item_type_unlock.svg', - }, unlock.name, { - en: `Coupon for unlock: ${unlock.name.en}.`, - zh: `头像/收藏解锁兑换券:${unlock.name.zh}。`, - }); - this.#coupons.set(unlock.itemdefId, { kind: 'unlock', unlockId: unlock.unlockId }); - this.#addMarketListing({ - itemdefId: unlock.itemdefId, - marketHashName: hashName, - category: 'unlock', - gjnCost: 6, - quality, - nameColor: color, - title: unlock.name, - subtitle: { en: 'Profile icon / unlock coupon', zh: '头像与解锁兑换券' }, - targetKey: unlock.unlockId, - }); - } - - #registerClassicWrappers(classicItems: readonly ItemDefinition[]): ReadonlyMap { - // Group non-expired classic items by their recycleItemResult (299000..299004) so recycling - // and chest drops yield authentic boosters, universal spares, orders, and wagers. - const byRecyclePart = new Map(); - for (const partId of RECYCLE_PART_IDS) byRecyclePart.set(partId, []); - - const preferredByPart = new Map(); - for (const item of classicItems) { - if (item.expiresAt !== undefined) continue; - if (item.type === 'personalDiscounts') continue; - const partId = item.recycleItemResult ?? 299001; - let bucket = preferredByPart.get(partId); - if (!bucket) preferredByPart.set(partId, bucket = []); - if (bucket.length < 8) bucket.push(item); - } - - let nextWrapperId = 810001; - for (const [partId, defs] of preferredByPart) { - const targetList = byRecyclePart.get(partId) ?? []; - for (const def of defs) { - const wrapperId = nextWrapperId++; - const count = def.name === 'item_universal_spare' ? 3 : 1; - this.#addDef(wrapperId, { - type: 'item', - marketable: false, - item_quality: 1, - tags: 'type:internal_item;autoConsume:yes;showAsContentItem:yes;hideMarketablePropDesc:yes', - meta: `item:t="${def.name}"\ncount:i=${count}`, - icon_url: '!#ui/gameuiskin#item_type_trophies.svg', - icon_url_large: '!#ui/gameuiskin#item_type_trophies.svg', - }, { en: def.name, zh: def.name }, { en: '', zh: '' }); - this.#coupons.set(wrapperId, { kind: 'classic-item', itemName: def.name, count }); - targetList.push(wrapperId); - } - byRecyclePart.set(partId, targetList); - } - - // Part 299002 corresponds to personalDiscounts: route its single-part generator to boosters + spares. - const fallbackPool = [ - ...(byRecyclePart.get(299000) ?? []), - ...(byRecyclePart.get(299001) ?? []), - ]; - for (const partId of RECYCLE_PART_IDS) { - if ((byRecyclePart.get(partId)?.length ?? 0) === 0) { - byRecyclePart.set(partId, fallbackPool); - } - } - return byRecyclePart; - } - - #registerRecycleSystem(wrappersByPart: ReadonlyMap): void { - const partNames: Readonly> = { - 299000: { en: 'Spare Supply Fragment', zh: '备用载具回收组件' }, - 299001: { en: 'Booster Fragment', zh: '加成卡回收组件' }, - 299002: { en: 'Coupon Fragment', zh: '折扣券回收组件' }, - 299003: { en: 'Order Fragment', zh: '任务令回收组件' }, - 299004: { en: 'Wager Fragment', zh: '合同回收组件' }, - }; - - const allWrappers = [...new Set([...wrappersByPart.values()].flat())]; - const pairRecipes: GeneratorRecipe[] = []; - const pairStrings: string[] = []; - for (let i = 0; i < RECYCLE_PART_IDS.length; i += 1) { - for (let j = i + 1; j < RECYCLE_PART_IDS.length; j += 1) { - const a = RECYCLE_PART_IDS[i]!; - const b = RECYCLE_PART_IDS[j]!; - pairRecipes.push({ components: [{ itemdefId: a, quantity: 1 }, { itemdefId: b, quantity: 1 }] }); - pairStrings.push(`${a}x1,${b}x1`); - } - } - - for (const partId of RECYCLE_PART_IDS) { - const singleGenId = partId + RECYCLE_SINGLE_OFFSET; - const title = partNames[partId] ?? { en: `Recycled Part #${partId}`, zh: `回收组件 #${partId}` }; - this.#addDef(partId, { - type: 'item', - marketable: false, - item_quality: 1, - used_to_create: `${singleGenId}x1;${RECYCLE_GENERIC_GENERATOR_ID}x1`, - tags: 'type:craft_part;hideMarketablePropDesc:yes', - icon_url: '!#ui/gameuiskin#item_type_craftpart.svg', - icon_url_large: '!#ui/gameuiskin#item_type_craftpart.svg', - }, title, { - en: 'Obtained by recycling classic items; 2 fragments craft a new random tactical item.', - zh: '回收经典道具所得;每 2 个组件可重新合成 1 件随机道具。', - }); - - const pool = wrappersByPart.get(partId) ?? allWrappers; - const drops: GeneratorDrop[] = pool.map((id) => ({ itemdefId: id, weight: 10 })); - this.#addDef(singleGenId, { - type: 'generator', - marketable: false, - item_quality: 1, - exchange: `${partId}x2`, - bundle: pool.map((id) => `${id}x1`).join(';'), - tags: 'devItem:yes', - icon_url: '!#ui/gameuiskin#item_type_craftpart.svg', - icon_url_large: '!#ui/gameuiskin#item_type_craftpart.svg', - }, { en: 'Item Synthesizer', zh: '道具合成器' }, { en: '', zh: '' }); - this.#generators.set(singleGenId, { - itemdefId: singleGenId, - isChestGenerator: false, - recipes: [{ components: [{ itemdefId: partId, quantity: 2 }] }], - drops, - }); - } - - const genericDrops: GeneratorDrop[] = allWrappers.map((id) => ({ itemdefId: id, weight: 10 })); - this.#addDef(RECYCLE_GENERIC_GENERATOR_ID, { - type: 'generator', - marketable: false, - item_quality: 1, - exchange: pairStrings.join(';'), - bundle: allWrappers.map((id) => `${id}x1`).join(';'), - tags: 'devItem:yes', - icon_url: '!#ui/gameuiskin#item_type_craftpart.svg', - icon_url_large: '!#ui/gameuiskin#item_type_craftpart.svg', - }, { en: 'Mixed Item Synthesizer', zh: '混搭道具合成器' }, { en: '', zh: '' }); - this.#generators.set(RECYCLE_GENERIC_GENERATOR_ID, { - itemdefId: RECYCLE_GENERIC_GENERATOR_ID, - isChestGenerator: false, - recipes: pairRecipes, - drops: genericDrops, - }); - } - - #registerSupplyChests( - wrappersByPart: ReadonlyMap, - decorCouponIds: readonly number[], - vehicleCouponIds: readonly number[], - ): void { - const commonWrappers = [ - ...(wrappersByPart.get(299000) ?? []).slice(0, 3), - ...(wrappersByPart.get(299001) ?? []).slice(0, 5), - ...(wrappersByPart.get(299003) ?? []).slice(0, 2), - ]; - const sampleDecors = decorCouponIds.slice(0, 8); - const sampleVehicles = vehicleCouponIds.slice(0, 6); - const collectorVehicles = vehicleCouponIds.slice(6, 16); - - // Chest 1: Tactical Supply Chest (60,000 SL) - const tacticalDrops: GeneratorDrop[] = [ - ...commonWrappers.map((id) => ({ itemdefId: id, weight: 80 })), - ...sampleDecors.map((id) => ({ itemdefId: id, weight: 18 })), - ...sampleVehicles.map((id) => ({ itemdefId: id, weight: 4 })), - ]; - this.#registerChest( - TACTICAL_CHEST_ID, - TACTICAL_CHEST_GEN_ID, - 60000, - 2, - '!#ui/images/chests/items_box2.avif', - { en: 'Tactical Supply Chest', zh: '战术物资补给箱' }, - { - en: 'Silver-Lion supply chest containing boosters, universal backups, decorator coupons, and rare vehicle coupons.', - zh: '银狮物资补给箱:内含加成卡、通用备用载具、涂装/贴花/挂件券及稀有市场载具兑换券(点击可查看各项精确掉率)。', - }, - tacticalDrops, - ); - - // Chest 2: Collector's Supply Chest (250,000 SL) - const collectorDrops: GeneratorDrop[] = [ - ...commonWrappers.slice(0, 5).map((id) => ({ itemdefId: id, weight: 45 })), - ...decorCouponIds.slice(8, 20).map((id) => ({ itemdefId: id, weight: 22 })), - ...(collectorVehicles.length ? collectorVehicles : sampleVehicles).map((id) => ({ itemdefId: id, weight: 12 })), - ]; - this.#registerChest( - COLLECTOR_CHEST_ID, - COLLECTOR_CHEST_GEN_ID, - 250000, - 4, - '!#ui/images/chests/items_box3.avif', - { en: "Collector's Supply Chest", zh: '典藏收藏家补给箱' }, - { - en: 'High-tier Silver-Lion supply chest with elevated drop rates for marketplace vehicle and decorator coupons.', - zh: '高阶银狮补给箱:大幅提升稀有市场载具兑换券与 3D 装饰挂件/涂装券的掉落概率。', - }, - collectorDrops, - ); - } - - #registerChest( - chestId: number, - genId: number, - silverLions: number, - quality: number, - icon: string, - title: LocalizedText, - desc: LocalizedText, - drops: readonly GeneratorDrop[], - ): void { - const color = QUALITY_COLORS[quality] ?? '45aacc'; - this.#addDef(chestId, { - type: 'item', - marketable: false, - item_quality: quality, - name_color: color, - used_to_create: `${genId}x1`, - tags: 'type:chest;showChances:yes;allowToBuyAmount:10;isAllowSkipOpeningAnim:yes;hideMarketablePropDesc:yes', - icon_url: icon, - icon_url_large: icon, - }, title, desc); - this.#prices.set(chestId, { itemdefId: chestId, silverLions, goldenEagles: 0 }); - - const bundleStr = drops.map((d) => `${d.itemdefId}x1`).join(';'); - this.#addDef(genId, { - type: 'generator', - marketable: false, - item_quality: quality, - name_color: color, - exchange: `${chestId}x1`, - bundle: bundleStr, - tags: 'devItem:yes', - icon_url: icon, - icon_url_large: icon, - }, title, { en: '', zh: '' }); - this.#generators.set(genId, { - itemdefId: genId, - isChestGenerator: true, - chestItemdefId: chestId, - recipes: [{ components: [{ itemdefId: chestId, quantity: 1 }] }], - drops, - }); - } - - #addDef( - itemdefid: number, - partial: Partial> & { - readonly type: ItemDefRecord['type']; - readonly tags: string; - readonly icon_url: string; - }, - name: LocalizedText, - description: LocalizedText, - ): void { - this.#defs.set(itemdefid, { - base: { - itemdefid, - type: partial.type, - Timestamp: partial.Timestamp ?? DEFAULT_TIMESTAMP, - marketable: partial.marketable ?? false, - exchange: partial.exchange ?? '', - used_to_create: partial.used_to_create ?? '', - market_hash_name: partial.market_hash_name ?? '', - background_color: partial.background_color ?? '', - name_color: partial.name_color ?? '', - item_quality: partial.item_quality ?? 1, - meta: partial.meta ?? '', - tags: partial.tags, - icon_url: partial.icon_url, - icon_url_large: partial.icon_url_large ?? partial.icon_url, - bundle: partial.bundle ?? '', - name_english: name.en, - description_english: description.en, - }, - name, - description, - }); - } - - #addMarketListing(listing: MarketplaceListing): void { - this.#marketListings.push(listing); - this.#marketById.set(listing.itemdefId, listing); - } -} - -function unitClassTag(unitClass: string): string { - switch (vehicleTypeOfClass(unitClass)) { - case 'Aircraft': - return 'aircraft'; - case 'Helicopter': - return 'helicopter'; - case 'Tank': - return 'tank'; - case 'Ship': - case 'Boat': - return 'ship'; - default: - return 'tank'; - } -} - -function marketUnitClassOf(unitClass: string): string { - switch (vehicleTypeOfClass(unitClass)) { - case 'Aircraft': - return 'aircraft'; - case 'Helicopter': - return 'helicopter'; - case 'Tank': - return 'tank'; - case 'Ship': - return 'ship'; - case 'Boat': - return 'boat'; - default: - return 'tank'; - } } function isChineseLanguage(lang: string): boolean { @@ -594,7 +138,7 @@ function fallbackItemDef(itemdefid: number): ItemDefRecord { return { itemdefid, type: 'item', - Timestamp: DEFAULT_TIMESTAMP, + Timestamp: DEFAULT_ITEMDEF_TIMESTAMP, marketable: false, exchange: '', used_to_create: '', diff --git a/packages/local-service/src/inventory/itemdef-types.ts b/packages/local-service/src/inventory/itemdef-types.ts index ea70352..2e0c167 100644 --- a/packages/local-service/src/inventory/itemdef-types.ts +++ b/packages/local-service/src/inventory/itemdef-types.ts @@ -1,10 +1,20 @@ /** - * Types for the external inventory service (`inventory-proxy`), generated itemdefs, - * and the local GJN marketplace. + * Types and shared definition builder for the external inventory service (`inventory-proxy`), + * generated itemdefs, and the local GJN marketplace. */ import type { DecorKind } from '../game-data/datasets/decor-catalogue.ts'; import type { LocalizedText } from '../game-data/datasets/unit-names.ts'; +export const DEFAULT_ITEMDEF_TIMESTAMP = '2026-01-01T00:00:00Z'; + +export const QUALITY_COLORS: Readonly> = { + 1: '', + 2: '45aacc', + 3: '5599ff', + 4: 'aa66ff', + 5: 'dd8833', +}; + /** Exact schema validated by scripts/inventory/inventoryClient.nut `validateResponseData.item_json`. */ export interface InventoryItemJson { readonly itemid: string; @@ -38,6 +48,13 @@ export interface ItemDefRecord { readonly description_english: string; } +export interface LocalizedItemDef { + readonly itemdefId: number; + readonly base: Omit; + readonly name: LocalizedText; + readonly description: LocalizedText; +} + export type CouponAction = | { readonly kind: 'vehicle'; readonly unitName: string; readonly parts: readonly string[] } | { readonly kind: 'decor'; readonly decorKind: DecorKind; readonly resourceKey: string } @@ -65,3 +82,61 @@ export interface GeneratorDrop { readonly itemdefId: number; readonly weight: number; } + +export interface ExternalItemPrice { + readonly itemdefId: number; + readonly silverLions: number; + readonly goldenEagles: number; +} + +export interface GeneratorRecipe { + readonly components: ReadonlyArray<{ readonly itemdefId: number; readonly quantity: number }>; +} + +export interface GeneratorDefinition { + readonly itemdefId: number; + readonly isChestGenerator: boolean; + readonly chestItemdefId?: number; + readonly recipes: readonly GeneratorRecipe[]; + readonly drops: readonly GeneratorDrop[]; +} + +export type PartialItemDefFields = Partial< + Omit +> & { + readonly type: ItemDefRecord['type']; + readonly tags: string; + readonly icon_url: string; +}; + +export function makeLocalizedItemDef( + itemdefId: number, + partial: PartialItemDefFields, + name: LocalizedText, + description: LocalizedText, +): LocalizedItemDef { + return { + itemdefId, + base: { + itemdefid: itemdefId, + type: partial.type, + Timestamp: partial.Timestamp ?? DEFAULT_ITEMDEF_TIMESTAMP, + marketable: partial.marketable ?? false, + exchange: partial.exchange ?? '', + used_to_create: partial.used_to_create ?? '', + market_hash_name: partial.market_hash_name ?? '', + background_color: partial.background_color ?? '', + name_color: partial.name_color ?? '', + item_quality: partial.item_quality ?? 1, + meta: partial.meta ?? '', + tags: partial.tags, + icon_url: partial.icon_url, + icon_url_large: partial.icon_url_large ?? partial.icon_url, + bundle: partial.bundle ?? '', + name_english: name.en, + description_english: description.en, + }, + name, + description, + }; +} diff --git a/packages/local-service/src/inventory/marketplace-page.ts b/packages/local-service/src/inventory/marketplace-page.ts deleted file mode 100644 index 6dd7072..0000000 --- a/packages/local-service/src/inventory/marketplace-page.ts +++ /dev/null @@ -1,300 +0,0 @@ -/** - * Single-page HTML UI for the local GJN Marketplace (`/trade.gaijin.net`), supporting - * vehicle coupons (233), skin coupons (74), attachable coupons (114), decal coupons (19), - * and unlock/profile-icon coupons (26), including deep links `?viewitem&n=` - * opened from in-game "Find on Marketplace" buttons. - */ -export function renderMarketplacePageHtml(): string { - return ` - - - - -War Thunder Offline — 本地 GJN 交易所 - - - -
-
-

War Thunder Offline 本地交易所 (GJN Market)

-

购买的兑换券直接存入玩家外部库存并实时推送至游戏(机库 → 道具 → 库存中可直接使用兑换)

-
-
- 前往礼包与金鹰商店 - -
GJN 余额:0 GJN
-
金鹰:0
-
银狮:0
-
-
-
-
-
- - - - - - -
-
- - - -
-
-
- - -`; -} diff --git a/packages/local-service/src/inventory/marketplace-service.ts b/packages/local-service/src/inventory/marketplace-service.ts index 1b8fda0..caa2729 100644 --- a/packages/local-service/src/inventory/marketplace-service.ts +++ b/packages/local-service/src/inventory/marketplace-service.ts @@ -13,12 +13,18 @@ import { ownsVehicle } from '../profile/profile-hangar.ts'; import { ownsResource } from '../profile/profile-resources.ts'; import { earnedUnlocks } from '../profile/profile-unlocks.ts'; import type { Service, ServiceRequest, ServiceResponse } from '../server/exchange.ts'; +import { + createStaticWebSite, + jsonResponse, + parseJsonBody, + requireWebActionAccount, + selectWebViewAccount, +} from '../web-ui/web-helpers.ts'; import { buyMarketplaceCoupon } from './inventory-rules.ts'; import type { InventoryCatalogue } from './itemdef-catalogue.ts'; import type { MarketplaceListing } from './itemdef-types.ts'; -import { renderMarketplacePageHtml } from './marketplace-page.ts'; -const JSON_HEADERS = { 'content-type': 'application/json; charset=utf-8' }; +const MARKET_WEB = createStaticWebSite(new URL('./web/', import.meta.url)); export class MarketplaceService implements Service { readonly name = 'marketplace'; @@ -53,17 +59,12 @@ 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); - return { - status: 200, - headers: { 'content-type': 'text/html; charset=utf-8' }, - body: renderMarketplacePageHtml(), - logNotes: { summary: `marketplace web page (${request.query.get('n') ?? 'index'})` }, - }; + return MARKET_WEB.serve(subPath, `marketplace web (${request.query.get('n') ?? 'index'})`) + ?? MARKET_WEB.serve('/', `marketplace web (${request.query.get('n') ?? 'index'})`)!; } #state(request: ServiceRequest): ServiceResponse { - const requestedId = request.query.get('userId') ?? ''; - const account = requestedId ? this.#accounts.byUserId(requestedId) : this.#accounts.all()[0]; + const account = selectWebViewAccount(this.#accounts, request.query.get('userId')); const profile = account ? this.#profiles.profileOf(account.userId) : undefined; const balance = profile ? balanceOf(profile) : { silverLions: 0, goldenEagles: 0, gjn: 0 }; @@ -81,34 +82,25 @@ export class MarketplaceService implements Service { alreadyActivated: profile ? isListingAlreadyActivated(profile, listing, unlockedSet) : false, })); - return { - status: 200, - headers: JSON_HEADERS, - body: JSON.stringify({ - accounts: this.#accounts.all().map((a) => ({ userId: a.userId, login: a.login, nick: a.nick })), - currentUserId: account?.userId ?? '', - balance, - listings, - }), - logNotes: { summary: `marketplace state (${account?.userId ?? 'no-account'})` }, - }; + return jsonResponse({ + accounts: this.#accounts.all().map((a) => ({ userId: a.userId, login: a.login, nick: a.nick })), + currentUserId: account?.userId ?? '', + balance, + listings, + }, `marketplace state (${account?.userId ?? 'no-account'})`); } #buy(request: ServiceRequest): ServiceResponse { - let payload: { userId?: string; itemdefId?: number; quantity?: number }; - try { - payload = JSON.parse(request.body.toString('utf8')) as { userId?: string; itemdefId?: number; quantity?: number }; - } catch { - return jsonMessage(false, '请求格式无效', 'marketplace buy: bad json'); + const body = parseJsonBody(request.body); + const account = requireWebActionAccount(this.#accounts, body.userId); + if (!account) { + return jsonResponse({ ok: false, message: '未找到指定账号,请先在游戏客户端登录并在页面右上角选择账号。' }, 'marketplace buy: unknown account'); } - const account = payload.userId ? this.#accounts.byUserId(payload.userId) : undefined; - if (!account) return jsonMessage(false, '未找到指定账号,请先在游戏客户端登录并在页面右上角选择账号', 'marketplace buy: unknown account'); - - const itemdefId = Number(payload.itemdefId ?? 0); - const quantity = Math.max(1, Math.min(20, Number(payload.quantity ?? 1))); + const itemdefId = Number(body.itemdefId ?? 0); + const quantity = Math.max(1, Math.min(20, Math.trunc(Number(body.quantity ?? 1)))); const listing = this.#catalogue.marketplaceListing(itemdefId); - if (!listing) return jsonMessage(false, '未找到该兑换券商品', `marketplace buy: unknown ${itemdefId}`); + if (!listing) return jsonResponse({ ok: false, message: '未找到该兑换券商品。' }, `marketplace buy: unknown ${itemdefId}`); let errorReason: 'NOT_FOUND' | 'NOT_ENOUGH_GJN' | undefined; this.#profiles.updateWhen(account.userId, (saved) => { @@ -121,18 +113,17 @@ export class MarketplaceService implements Service { }); if (errorReason === 'NOT_ENOUGH_GJN') { - return jsonMessage(false, 'GJN 余额不足(可通过存档修改器或商店兑换码补充 GJN)', `marketplace buy ${itemdefId}: NOMONEY`); + return jsonResponse({ ok: false, message: 'GJN 余额不足(可通过存档修改器或商店兑换码补充 GJN)。' }, `marketplace buy ${itemdefId}: NOMONEY`); } if (errorReason) { - return jsonMessage(false, '购买失败', `marketplace buy ${itemdefId}: ${errorReason}`); + return jsonResponse({ ok: false, message: '购买失败。' }, `marketplace buy ${itemdefId}: ${errorReason}`); } this.#notifyInventoryChanged(); - return jsonMessage( - true, - `已购买「${listing.title.zh}」兑换券 x${quantity}!已同步至游戏库存,可在机库【道具 → 库存】中使用兑换。`, - `marketplace buy ${itemdefId} x${quantity} (${listing.gjnCost * quantity} GJN)`, - ); + return jsonResponse({ + ok: true, + message: `已购买「${listing.title.zh}」兑换券 x${quantity}!已同步至游戏库存,可在机库【道具 → 库存】中使用兑换。`, + }, `marketplace buy ${itemdefId} x${quantity} (${listing.gjnCost * quantity} GJN)`); } } @@ -148,7 +139,3 @@ function isListingAlreadyActivated(profile: BlkBlock, listing: MarketplaceListin return unlockedSet.has(listing.targetKey); } } - -function jsonMessage(ok: boolean, message: string, summary: string): ServiceResponse { - return { status: 200, headers: JSON_HEADERS, body: JSON.stringify({ ok, message }), logNotes: { summary } }; -} diff --git a/packages/local-service/src/inventory/recycling-defs.ts b/packages/local-service/src/inventory/recycling-defs.ts new file mode 100644 index 0000000..0b3009c --- /dev/null +++ b/packages/local-service/src/inventory/recycling-defs.ts @@ -0,0 +1,157 @@ +/** + * Classic-item `autoConsume` wrappers (`810001+`), recycled craft fragments (`299000..299004`), + * and re-synthesis generators (`299020..299024`, `299030`; implementation notes). + */ +import type { ItemDefinition } from '../game-data/datasets/item-catalogue.ts'; +import type { LocalizedText } from '../game-data/datasets/unit-names.ts'; +import { + makeLocalizedItemDef, + type CouponAction, + type GeneratorDefinition, + type GeneratorDrop, + type GeneratorRecipe, + type LocalizedItemDef, +} from './itemdef-types.ts'; + +export const RECYCLE_PART_IDS = [299000, 299001, 299002, 299003, 299004] as const; +const RECYCLE_SINGLE_OFFSET = 20; +const RECYCLE_GENERIC_GENERATOR_ID = 299030; + +const PART_NAMES: Readonly> = { + 299000: { en: 'Spare Supply Fragment', zh: '备用载具回收组件' }, + 299001: { en: 'Booster Fragment', zh: '加成卡回收组件' }, + 299002: { en: 'Coupon Fragment', zh: '折扣券回收组件' }, + 299003: { en: 'Order Fragment', zh: '任务令回收组件' }, + 299004: { en: 'Wager Fragment', zh: '合同回收组件' }, +}; + +export interface RecyclingBuildResult { + readonly defs: readonly LocalizedItemDef[]; + readonly coupons: ReadonlyArray; + readonly generators: readonly GeneratorDefinition[]; + readonly wrappersByPart: ReadonlyMap; +} + +export function buildRecyclingDefs(classicItems: readonly ItemDefinition[]): RecyclingBuildResult { + const defs: LocalizedItemDef[] = []; + const coupons: Array = []; + const generators: GeneratorDefinition[] = []; + + const wrappersByPart = buildClassicWrappers(classicItems, defs, coupons); + const allWrappers = [...new Set([...wrappersByPart.values()].flat())]; + const { pairRecipes, pairStrings } = buildPairRecipes(); + + for (const partId of RECYCLE_PART_IDS) { + const singleGenId = partId + RECYCLE_SINGLE_OFFSET; + const title = PART_NAMES[partId] ?? { en: `Recycled Part #${partId}`, zh: `回收组件 #${partId}` }; + defs.push(makeLocalizedItemDef(partId, { + type: 'item', + marketable: false, + item_quality: 1, + used_to_create: `${singleGenId}x1;${RECYCLE_GENERIC_GENERATOR_ID}x1`, + tags: 'type:craft_part;hideMarketablePropDesc:yes', + icon_url: '!#ui/gameuiskin#item_type_craftpart.svg', + }, title, { + en: 'Obtained by recycling classic items; 2 fragments craft a new random tactical item.', + zh: '回收经典道具所得;每 2 个组件可重新合成 1 件随机道具。', + })); + + const pool = wrappersByPart.get(partId) ?? allWrappers; + const drops: GeneratorDrop[] = pool.map((id) => ({ itemdefId: id, weight: 10 })); + defs.push(makeLocalizedItemDef(singleGenId, { + type: 'generator', + marketable: false, + item_quality: 1, + exchange: `${partId}x2`, + bundle: pool.map((id) => `${id}x1`).join(';'), + tags: 'devItem:yes', + icon_url: '!#ui/gameuiskin#item_type_craftpart.svg', + }, { en: 'Item Synthesizer', zh: '道具合成器' }, { en: '', zh: '' })); + generators.push({ + itemdefId: singleGenId, + isChestGenerator: false, + recipes: [{ components: [{ itemdefId: partId, quantity: 2 }] }], + drops, + }); + } + + defs.push(makeLocalizedItemDef(RECYCLE_GENERIC_GENERATOR_ID, { + type: 'generator', + marketable: false, + item_quality: 1, + exchange: pairStrings.join(';'), + bundle: allWrappers.map((id) => `${id}x1`).join(';'), + tags: 'devItem:yes', + icon_url: '!#ui/gameuiskin#item_type_craftpart.svg', + }, { en: 'Mixed Item Synthesizer', zh: '混搭道具合成器' }, { en: '', zh: '' })); + generators.push({ + itemdefId: RECYCLE_GENERIC_GENERATOR_ID, + isChestGenerator: false, + recipes: pairRecipes, + drops: allWrappers.map((id) => ({ itemdefId: id, weight: 10 })), + }); + + return { defs, coupons, generators, wrappersByPart }; +} + +function buildClassicWrappers( + classicItems: readonly ItemDefinition[], + defs: LocalizedItemDef[], + coupons: Array, +): ReadonlyMap { + const byRecyclePart = new Map(); + for (const partId of RECYCLE_PART_IDS) byRecyclePart.set(partId, []); + + // Sort deterministically by item id so wrapper IDs and drop pools do not depend on BLK order. + const sortedPermanent = classicItems + .filter((item) => item.expiresAt === undefined && item.type !== 'personalDiscounts') + .sort((a, b) => a.name.localeCompare(b.name)); + + const preferredByPart = new Map(); + for (const item of sortedPermanent) { + const partId = item.recycleItemResult ?? 299001; + let bucket = preferredByPart.get(partId); + if (!bucket) preferredByPart.set(partId, bucket = []); + if (bucket.length < 8) bucket.push(item); + } + + let nextWrapperId = 810001; + for (const partId of RECYCLE_PART_IDS) { + const targetList = byRecyclePart.get(partId) ?? []; + for (const def of preferredByPart.get(partId) ?? []) { + const wrapperId = nextWrapperId++; + const count = def.name === 'item_universal_spare' ? 3 : 1; + defs.push(makeLocalizedItemDef(wrapperId, { + type: 'item', + marketable: false, + item_quality: 1, + tags: 'type:internal_item;autoConsume:yes;showAsContentItem:yes;hideMarketablePropDesc:yes', + meta: `item:t="${def.name}"\ncount:i=${count}`, + icon_url: '!#ui/gameuiskin#item_type_trophies.svg', + }, { en: def.name, zh: def.name }, { en: '', zh: '' })); + coupons.push([wrapperId, { kind: 'classic-item', itemName: def.name, count }]); + targetList.push(wrapperId); + } + byRecyclePart.set(partId, targetList); + } + + const fallbackPool = [...(byRecyclePart.get(299000) ?? []), ...(byRecyclePart.get(299001) ?? [])]; + for (const partId of RECYCLE_PART_IDS) { + if ((byRecyclePart.get(partId)?.length ?? 0) === 0) byRecyclePart.set(partId, fallbackPool); + } + return byRecyclePart; +} + +function buildPairRecipes(): { readonly pairRecipes: readonly GeneratorRecipe[]; readonly pairStrings: readonly string[] } { + const pairRecipes: GeneratorRecipe[] = []; + const pairStrings: string[] = []; + for (let i = 0; i < RECYCLE_PART_IDS.length; i += 1) { + for (let j = i + 1; j < RECYCLE_PART_IDS.length; j += 1) { + const a = RECYCLE_PART_IDS[i]!; + const b = RECYCLE_PART_IDS[j]!; + pairRecipes.push({ components: [{ itemdefId: a, quantity: 1 }, { itemdefId: b, quantity: 1 }] }); + pairStrings.push(`${a}x1,${b}x1`); + } + } + return { pairRecipes, pairStrings }; +} diff --git a/packages/local-service/src/inventory/trophy-catalogue.ts b/packages/local-service/src/inventory/trophy-catalogue.ts index 0fddc94..0f2cc48 100644 --- a/packages/local-service/src/inventory/trophy-catalogue.ts +++ b/packages/local-service/src/inventory/trophy-catalogue.ts @@ -2,7 +2,7 @@ * Classic trophies (`cln_get_price_ex` top-level `trophy{}` + `Common/trophy/` prices) * and `cln_buy_trophy` rules (implementation notes; scripts/items/itemsClasses/itemTrophy.nut): * 1. Silver-Lion supply chests with native drop-chance display (`showChances:b=yes`, calculated - * by `calcTrophiesDropChance` at 0x1554dc0); + * by `calcTrophiesDropChance` at 0x1554dc0), using deterministic rank-and-country selection; * 2. Golden-Eagle direct-purchase prize-pool vehicles (`numTotal:i=1`, single `i{ unit:t }` prize, * disabled automatically by `isPrizeUnitBought()` once owned). */ @@ -16,6 +16,8 @@ import { addOwnedVehicle, ownsVehicle } from '../profile/profile-hangar.ts'; import { appendUserLog, EULT_OPEN_TROPHY, incrementTrophyOpenCount, trophyOpenCount } from '../profile/profile-trophies-log.ts'; import type { ServerTime } from '../profile/server-time.ts'; import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts'; +import { pickAcrossCountries } from './chest-defs.ts'; +import { pickWeighted } from './inventory-rules.ts'; export type TrophyPrize = | { readonly kind: 'warpoints'; readonly amount: number; readonly weight: number } @@ -37,7 +39,7 @@ export interface TrophyDefinition { readonly prizes: readonly TrophyPrize[]; } -const DIRECT_UNIT_GOLD_BY_RANK: Readonly> = { +export const DIRECT_UNIT_GOLD_BY_RANK: Readonly> = { 1: 850, 2: 1450, 3: 2600, @@ -57,57 +59,58 @@ export class TrophyCatalogue { const boosterIds = classicItems .filter((item) => item.type === 'rateBooster' && item.expiresAt === undefined) - .slice(0, 6) - .map((item) => item.name); + .map((item) => item.name) + .sort((a, b) => a.localeCompare(b)) + .slice(0, 6); const hasUniversalSpare = classicItems.some((item) => item.name === 'item_universal_spare'); - const eventVehicles = vehicles.filter( - (v) => v.event && !v.marketplaceItemdefId && !v.onlyShownWhenOwned && v.inTechTree, - ); - const rareChestUnits = eventVehicles.slice(0, 4); + const sortedEventVehicles = vehicles + .filter((v) => v.event && !v.marketplaceItemdefId && !v.onlyShownWhenOwned && v.inTechTree) + .sort((a, b) => (a.rank - b.rank) || a.country.localeCompare(b.country) || a.name.localeCompare(b.name)); + + const silverChestUnits = pickAcrossCountries(sortedEventVehicles.filter((v) => v.rank <= 3), 4); + const veteranChestUnits = pickAcrossCountries(sortedEventVehicles.filter((v) => v.rank >= 4), 6); - // 1. Classic Silver-Lion Supply Chest (50,000 SL, repeatable, probability disclosure enabled) trophies.push({ id: 'wto_silver_supply_trophy', iconStyle: 'small_wooden_box', - silverLions: 50000, + silverLions: 50_000, goldenEagles: 0, showChances: true, repeatable: true, instantOpening: false, numTotal: 0, prizes: [ - ...(rareChestUnits.map((v): TrophyPrize => ({ kind: 'unit', unitName: v.name, parts: v.parts, weight: 2 }))), - { kind: 'warpoints', amount: 250000, weight: 8 }, - { kind: 'warpoints', amount: 75000, weight: 20 }, - { kind: 'warpoints', amount: 25000, weight: 35 }, + ...silverChestUnits.map((v): TrophyPrize => ({ kind: 'unit', unitName: v.name, parts: v.parts, weight: 2 })), + { kind: 'warpoints', amount: 250_000, weight: 8 }, + { kind: 'warpoints', amount: 75_000, weight: 20 }, + { kind: 'warpoints', amount: 25_000, weight: 35 }, ...(hasUniversalSpare ? [{ kind: 'item', itemName: 'item_universal_spare', count: 3, weight: 25 } as const] : []), ...boosterIds.map((itemName): TrophyPrize => ({ kind: 'item', itemName, count: 1, weight: 20 })), ], }); - // 2. Classic Veteran Silver-Lion Supply Chest (150,000 SL, repeatable, higher rewards) trophies.push({ id: 'wto_veteran_supply_trophy', iconStyle: 'big_chest', - silverLions: 150000, + silverLions: 150_000, goldenEagles: 0, showChances: true, repeatable: true, instantOpening: false, numTotal: 0, prizes: [ - ...(eventVehicles.slice(4, 10).map((v): TrophyPrize => ({ kind: 'unit', unitName: v.name, parts: v.parts, weight: 4 }))), + ...(veteranChestUnits.length ? veteranChestUnits : silverChestUnits) + .map((v): TrophyPrize => ({ kind: 'unit', unitName: v.name, parts: v.parts, weight: 4 })), { kind: 'gold', amount: 150, weight: 10 }, - { kind: 'warpoints', amount: 500000, weight: 12 }, - { kind: 'warpoints', amount: 120000, weight: 28 }, + { kind: 'warpoints', amount: 500_000, weight: 12 }, + { kind: 'warpoints', amount: 120_000, weight: 28 }, ...(hasUniversalSpare ? [{ kind: 'item', itemName: 'item_universal_spare', count: 5, weight: 30 } as const] : []), ...boosterIds.slice(0, 4).map((itemName): TrophyPrize => ({ kind: 'item', itemName, count: 1, weight: 22 })), ], }); - // 3. Golden-Eagle Vehicle Prize-Pool Direct Purchase Trophies (one per event/special vehicle) - for (const vehicle of eventVehicles) { + for (const vehicle of sortedEventVehicles) { const gold = DIRECT_UNIT_GOLD_BY_RANK[vehicle.rank] ?? 6090; trophies.push({ id: `wto_prize_unit_${vehicle.name}`, @@ -134,15 +137,6 @@ export class TrophyCatalogue { byId(id: string): TrophyDefinition | undefined { return this.#byId.get(id); } - - /** Top-level `trophy{ ... }` definition block included in `cln_get_price_ex`. */ - definitionsBlk(): BlkBlock { - return { - name: 'trophy', - params: [], - blocks: this.#trophies.map(toTrophyDefinitionBlk), - }; - } } export function buyTrophy( @@ -160,8 +154,6 @@ export function buyTrophy( if (trophy.numTotal > 0 && !trophy.repeatable && trophyOpenCount(profile, trophy.id) >= trophy.numTotal) { return refused('NOT_AVAILABLE'); } - - // Direct single-unit trophy: refuse duplicate purchase if the unit is already owned. if (trophy.prizes.length === 1 && trophy.prizes[0]!.kind === 'unit' && ownsVehicle(profile, trophy.prizes[0]!.unitName)) { return refused('NOT_AVAILABLE'); } @@ -169,19 +161,28 @@ export function buyTrophy( const price = { silverLions: trophy.silverLions, goldenEagles: trophy.goldenEagles }; if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY'); - // Filter out already-owned vehicles when rolling a multi-prize chest; fall back to full list if all non-unit. const eligible = trophy.prizes.filter((prize) => prize.kind !== 'unit' || !ownsVehicle(profile, prize.unitName)); - const pool = eligible.length > 0 ? eligible : trophy.prizes; - const chosen = rollTrophyPrize(pool); + const chosen = pickWeighted(eligible.length > 0 ? eligible : trophy.prizes); pay(profile, price); const openSeq = incrementTrophyOpenCount(profile, trophy.id, 1); - const nowSec = Math.floor(Date.now() / 1000); + const logBody = applyTrophyPrize(profile, classicItems, trophy.id, openSeq, chosen, now); + appendUserLog(profile, { type: EULT_OPEN_TROPHY, timeSec: Math.floor(Date.now() / 1000), bodyParams: logBody }); + return ACCEPTED; +} + +function applyTrophyPrize( + profile: BlkBlock, + classicItems: ItemCatalogue, + trophyId: string, + openSeq: number, + chosen: TrophyPrize, + now: ServerTime, +): BlkParam[] { const logBody: BlkParam[] = [ - { name: 'id', value: { type: 'string', value: trophy.id } }, + { name: 'id', value: { type: 'string', value: trophyId } }, { name: 'trophyItemId', value: { type: 'int', value: openSeq } }, ]; - switch (chosen.kind) { case 'warpoints': addSilverLions(profile, chosen.amount); @@ -209,65 +210,5 @@ export function buyTrophy( ); break; } - - appendUserLog(profile, { type: EULT_OPEN_TROPHY, timeSec: nowSec, bodyParams: logBody }); - return ACCEPTED; -} - -function toTrophyDefinitionBlk(trophy: TrophyDefinition): BlkBlock { - const params: BlkParam[] = [ - { name: 'iconStyle', value: { type: 'string', value: trophy.iconStyle } }, - { name: 'showChances', value: { type: 'bool', value: trophy.showChances } }, - { name: 'repeatable', value: { type: 'bool', value: trophy.repeatable } }, - { name: 'instantOpening', value: { type: 'bool', value: trophy.instantOpening } }, - ]; - if (trophy.numTotal > 0) params.push({ name: 'numTotal', value: { type: 'int', value: trophy.numTotal } }); - if (trophy.countryFlag) params.push({ name: 'showCountryFlag', value: { type: 'string', value: trophy.countryFlag } }); - if (trophy.prizes.length === 1 && trophy.prizes[0]!.kind === 'unit') { - params.push({ name: 'showTypeInName', value: { type: 'bool', value: true } }); - } - - const prizeBlocks: BlkBlock[] = []; - for (const prize of trophy.prizes) { - // Repeat `i` entries proportionally for coarse weight or emit `weight` string + `prob` float - // so calcTrophiesDropChance (0x95a510) and prizeChance.nut both display accurate weights. - const weightTag = prize.weight >= 25 ? 'high' : prize.weight >= 10 ? 'medium' : 'low'; - const prizeParams: BlkParam[] = [ - { name: 'weight', value: { type: 'string', value: weightTag } }, - ]; - switch (prize.kind) { - case 'warpoints': - prizeParams.push({ name: 'warpoints', value: { type: 'int', value: prize.amount } }); - break; - case 'gold': - prizeParams.push({ name: 'gold', value: { type: 'int', value: prize.amount } }); - break; - case 'item': - prizeParams.push( - { name: 'item', value: { type: 'string', value: prize.itemName } }, - { name: 'count', value: { type: 'int', value: prize.count } }, - ); - break; - case 'unit': - prizeParams.push({ name: 'unit', value: { type: 'string', value: prize.unitName } }); - break; - } - prizeBlocks.push({ name: 'i', params: prizeParams, blocks: [] }); - } - - return { - name: trophy.id, - params, - blocks: [{ name: 'prizes', params: [], blocks: prizeBlocks }], - }; -} - -function rollTrophyPrize(prizes: readonly TrophyPrize[]): TrophyPrize { - const total = prizes.reduce((sum, p) => sum + p.weight, 0); - let roll = Math.random() * total; - for (const prize of prizes) { - roll -= prize.weight; - if (roll <= 0) return prize; - } - return prizes[prizes.length - 1]!; + return logBody; } diff --git a/packages/local-service/src/inventory/web/app.js b/packages/local-service/src/inventory/web/app.js new file mode 100644 index 0000000..f3665d0 --- /dev/null +++ b/packages/local-service/src/inventory/web/app.js @@ -0,0 +1,138 @@ +const COUNTRY_LABELS = { + country_usa: '美国', country_germany: '德国', country_ussr: '苏联', country_britain: '英国', + country_japan: '日本', country_china: '中国', country_italy: '意大利', country_france: '法国', + country_sweden: '瑞典', country_israel: '以色列' +}; + +let state = { accounts: [], currentUserId: '', balance: { gjn: 0, goldenEagles: 0, silverLions: 0 }, listings: [] }; +let activeCat = 'all'; +const initialParams = new URLSearchParams(location.search); +const targetHash = initialParams.get('n') || ''; +if (targetHash) { + document.getElementById('searchInput').value = targetHash; +} + +function showToast(msg, ok) { + const el = document.getElementById('toast'); + el.textContent = msg; + el.className = ok ? 'ok' : 'err'; +} + +async function loadState(userId) { + const q = userId ? '?userId=' + encodeURIComponent(userId) : ''; + const res = await fetch('/trade.gaijin.net/api/state' + q); + state = await res.json(); + renderHeader(); + populateCountries(); + renderGrid(); +} + +function renderHeader() { + const sel = document.getElementById('accountSelect'); + sel.innerHTML = ''; + for (const acc of state.accounts) { + const opt = document.createElement('option'); + opt.value = acc.userId; + opt.textContent = acc.nick + ' (' + acc.login + ')'; + if (acc.userId === state.currentUserId) opt.selected = true; + sel.appendChild(opt); + } + document.getElementById('balGjn').textContent = state.balance.gjn.toLocaleString(); + document.getElementById('balGold').textContent = state.balance.goldenEagles.toLocaleString(); + document.getElementById('balSilver').textContent = state.balance.silverLions.toLocaleString(); +} + +function populateCountries() { + const sel = document.getElementById('countryFilter'); + const prev = sel.value; + const countries = [...new Set(state.listings.map(l => l.country).filter(Boolean))]; + sel.innerHTML = ''; + for (const c of countries) { + const opt = document.createElement('option'); + opt.value = c; + opt.textContent = COUNTRY_LABELS[c] || c; + if (c === prev) opt.selected = true; + sel.appendChild(opt); + } +} + +function renderGrid() { + const grid = document.getElementById('grid'); + const country = document.getElementById('countryFilter').value; + const unitClass = document.getElementById('classFilter').value; + const q = document.getElementById('searchInput').value.trim().toLowerCase(); + + const filtered = state.listings.filter(item => { + if (activeCat !== 'all' && item.category !== activeCat) return false; + if (country && item.country !== country) return false; + if (unitClass && item.unitClass !== unitClass) return false; + if (q) { + const hay = (item.title.zh + ' ' + item.title.en + ' ' + item.marketHashName + ' ' + item.itemdefId).toLowerCase(); + if (!hay.includes(q)) return false; + } + return true; + }); + + grid.innerHTML = ''; + for (const item of filtered) { + const card = document.createElement('div'); + card.className = 'card' + (targetHash && item.marketHashName === targetHash ? ' highlight' : ''); + const titleColor = item.nameColor ? '#' + item.nameColor : '#e6edf5'; + const badges = []; + if (item.country) badges.push('' + (COUNTRY_LABELS[item.country] || item.country) + ''); + if (item.rank) badges.push('' + item.rank + ' 级'); + badges.push('#' + item.itemdefId + ''); + if (item.couponCount > 0) badges.push('库存持有 x' + item.couponCount + ''); + if (item.alreadyActivated) badges.push('已激活拥有'); + + card.innerHTML = + '
' + + '

' + escapeHtml(item.title.zh) + '

' + + '
' + escapeHtml(item.title.en) + ' · ' + escapeHtml(item.subtitle.zh) + '
' + + '
' + badges.join('') + '
' + + '
' + + '
' + + '' + item.gjnCost + ' GJN' + + '' + + '
'; + const btn = card.querySelector('button'); + if (!state.currentUserId) { + btn.textContent = '请先登录游戏'; + btn.disabled = true; + } else { + btn.textContent = '购买兑换券'; + btn.addEventListener('click', () => buyCoupon(item.itemdefId)); + } + grid.appendChild(card); + } +} + +async function buyCoupon(itemdefId) { + const res = await fetch('/trade.gaijin.net/api/buy', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ userId: state.currentUserId, itemdefId, quantity: 1 }) + }); + const data = await res.json(); + showToast(data.message, data.ok); + if (data.ok) await loadState(state.currentUserId); +} + +function escapeHtml(str) { + return String(str).replace(/[&<>"']/g, ch => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[ch])); +} + +document.getElementById('tabs').addEventListener('click', e => { + const btn = e.target.closest('.tab'); + if (!btn) return; + for (const el of document.querySelectorAll('.tab')) el.classList.remove('active'); + btn.classList.add('active'); + activeCat = btn.dataset.cat; + renderGrid(); +}); +document.getElementById('accountSelect').addEventListener('change', e => loadState(e.target.value)); +document.getElementById('countryFilter').addEventListener('change', renderGrid); +document.getElementById('classFilter').addEventListener('change', renderGrid); +document.getElementById('searchInput').addEventListener('input', renderGrid); + +loadState(''); diff --git a/packages/local-service/src/inventory/web/index.html b/packages/local-service/src/inventory/web/index.html new file mode 100644 index 0000000..810ea1f --- /dev/null +++ b/packages/local-service/src/inventory/web/index.html @@ -0,0 +1,49 @@ + + + + + + War Thunder Offline — 本地 GJN 交易所 + + + +
+
+

War Thunder Offline 本地交易所 (GJN Market)

+

购买的兑换券直接存入玩家外部库存并实时推送至游戏(机库 → 道具 → 库存中可直接使用兑换)

+
+
+ 前往礼包与金鹰商店 + +
GJN 余额:0 GJN
+
金鹰:0
+
银狮:0
+
+
+
+
+
+ + + + + + +
+
+ + + +
+
+
+ + + diff --git a/packages/local-service/src/inventory/web/styles.css b/packages/local-service/src/inventory/web/styles.css new file mode 100644 index 0000000..88f0752 --- /dev/null +++ b/packages/local-service/src/inventory/web/styles.css @@ -0,0 +1,109 @@ +:root { + --bg: #0f141b; + --panel: #17202b; + --panel-alt: #1e2a38; + --border: #2c3d52; + --text: #e6edf5; + --muted: #93a4b8; + --gjn: #4cd964; + --accent: #3b82f6; +} +* { box-sizing: border-box; } +body { + margin: 0; + font-family: "Segoe UI", "Microsoft YaHei", sans-serif; + background: var(--bg); + color: var(--text); +} +header { + position: sticky; + top: 0; + z-index: 10; + background: rgba(15, 20, 27, 0.96); + border-bottom: 1px solid var(--border); + padding: 14px 24px; + display: flex; + flex-wrap: wrap; + gap: 16px; + align-items: center; + justify-content: space-between; +} +.brand h1 { margin: 0; font-size: 19px; letter-spacing: 0.4px; } +.brand p { margin: 3px 0 0; font-size: 12px; color: var(--muted); } +.wallet { + display: flex; + flex-wrap: wrap; + gap: 12px; + align-items: center; +} +.pill { + background: var(--panel-alt); + border: 1px solid var(--border); + border-radius: 6px; + padding: 6px 12px; + font-size: 13px; +} +.pill strong.gjn { color: var(--gjn); font-size: 15px; } +select, input, button { + font-family: inherit; + font-size: 13px; + border-radius: 6px; + border: 1px solid var(--border); + background: var(--panel); + color: var(--text); + padding: 7px 11px; +} +button { + cursor: pointer; + background: var(--accent); + border-color: #2563eb; + font-weight: 600; +} +button:hover:not(:disabled) { filter: brightness(1.1); } +button:disabled { opacity: 0.45; cursor: not-allowed; } +main { max-width: 1320px; margin: 0 auto; padding: 20px 24px 60px; } +.tabs { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 14px; } +.tab { background: var(--panel); border: 1px solid var(--border); color: var(--muted); } +.tab.active { background: var(--accent); border-color: #2563eb; color: #fff; } +.filters { display: flex; gap: 10px; flex-wrap: wrap; margin-bottom: 16px; } +.filters input { min-width: 250px; } +#toast { + display: none; + margin-bottom: 14px; + padding: 10px 14px; + border-radius: 6px; + font-size: 13px; + border: 1px solid var(--border); +} +#toast.ok { display: block; background: rgba(22, 163, 74, 0.18); border-color: #16a34a; color: #86efac; } +#toast.err { display: block; background: rgba(239, 68, 68, 0.18); border-color: #ef4444; color: #fca5a5; } +.grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(275px, 1fr)); + gap: 12px; +} +.card { + background: var(--panel); + border: 1px solid var(--border); + border-radius: 8px; + padding: 14px; + display: flex; + flex-direction: column; + justify-content: space-between; + gap: 10px; +} +.card.highlight { border-color: var(--gjn); box-shadow: 0 0 0 1px var(--gjn); } +.card h3 { margin: 0 0 4px; font-size: 15px; } +.meta { font-size: 12px; color: var(--muted); } +.badges { display: flex; gap: 6px; flex-wrap: wrap; margin-top: 6px; } +.badge { font-size: 11px; padding: 2px 7px; border-radius: 4px; background: var(--panel-alt); color: var(--muted); } +.badge.owned { background: rgba(76, 217, 100, 0.16); color: var(--gjn); } +.card-foot { + display: flex; + align-items: center; + justify-content: space-between; + padding-top: 8px; + border-top: 1px solid rgba(255, 255, 255, 0.06); +} +.price { font-weight: 700; font-size: 15px; color: var(--gjn); } +.link-btn { text-decoration: none; color: var(--muted); font-size: 13px; padding: 6px 10px; border: 1px solid var(--border); border-radius: 6px; } diff --git a/packages/local-service/src/profile/blk-fields.ts b/packages/local-service/src/profile/blk-fields.ts new file mode 100644 index 0000000..91f43e4 --- /dev/null +++ b/packages/local-service/src/profile/blk-fields.ts @@ -0,0 +1,29 @@ +/** + * Shared typed field readers and mutators for profile DataBlocks. + */ +import { findParam, type BlkBlock } from '@wto/blk'; + +export const EMPTY_BLK: BlkBlock = { name: '', params: [], blocks: [] }; + +export function intField(block: BlkBlock | undefined, name: string, fallback = 0): number { + const value = block && findParam(block, name)?.value; + if (value?.type === 'int') return value.value; + if (value?.type === 'int64') return Number(value.value); + return fallback; +} + +export function int64Field(block: BlkBlock | undefined, name: string, fallback = 0n): bigint { + const value = block && findParam(block, name)?.value; + if (value?.type === 'int64') return value.value; + if (value?.type === 'int') return BigInt(value.value); + return fallback; +} + +export function stringField(block: BlkBlock | undefined, name: string, fallback = ''): string { + const value = block && findParam(block, name)?.value; + return value?.type === 'string' ? value.value : fallback; +} + +export function removeParam(block: BlkBlock, name: string): void { + block.params = block.params.filter((param) => param.name !== name); +} diff --git a/packages/local-service/src/profile/profile-clan.ts b/packages/local-service/src/profile/profile-clan.ts index 87d9149..65e13cf 100644 --- a/packages/local-service/src/profile/profile-clan.ts +++ b/packages/local-service/src/profile/profile-clan.ts @@ -2,11 +2,8 @@ * Squadron (clan) membership and squadron vehicle research fields in `profile.blk` * (implementation notes; aces.exe 0x91fa31..0x91fd00 and 0x906790..0x906ac5). */ -import { ensureBlock, findBlock, findParam, setParam, type BlkBlock } from '@wto/blk'; - -function removeParam(block: BlkBlock, name: string): void { - block.params = block.params.filter((param) => param.name !== name); -} +import { ensureBlock, findBlock, setParam, type BlkBlock } from '@wto/blk'; +import { int64Field, intField, removeParam, stringField } from './blk-fields.ts'; const CLAN_RESEARCH_BLOCK = 'clanResearchUnits'; @@ -29,21 +26,14 @@ export interface SquadronResearchState { } export function clanMembershipOf(profile: BlkBlock): ProfileClanMembership { - const clanIdVal = findParam(profile, 'clanId')?.value; - const clanIdNum = clanIdVal?.type === 'int64' ? clanIdVal.value : clanIdVal?.type === 'int' ? BigInt(clanIdVal.value) : -1n; - const reqVal = findParam(profile, 'storedRequestClanId')?.value; - const reqNum = reqVal?.type === 'int64' ? reqVal.value : reqVal?.type === 'int' ? BigInt(reqVal.value) : -1n; - const tagVal = findParam(profile, 'clanTag')?.value; - const nameVal = findParam(profile, 'clanName')?.value; - const typeVal = findParam(profile, 'clanType')?.value; - const roleVal = findParam(profile, 'clanMemberRole')?.value; - + const clanIdNum = int64Field(profile, 'clanId', -1n); + const reqNum = int64Field(profile, 'storedRequestClanId', -1n); return { clanId: clanIdNum > 0n ? clanIdNum.toString() : '-1', - clanTag: tagVal?.type === 'string' ? tagVal.value : '', - clanName: nameVal?.type === 'string' ? nameVal.value : '', - clanType: typeVal?.type === 'string' && typeVal.value === 'battalion' ? 'battalion' : 'normal', - role: roleVal?.type === 'int' ? roleVal.value : 0, + clanTag: stringField(profile, 'clanTag'), + clanName: stringField(profile, 'clanName'), + clanType: stringField(profile, 'clanType') === 'battalion' ? 'battalion' : 'normal', + role: intField(profile, 'clanMemberRole'), requestedClanId: clanIdNum <= 0n && reqNum > 0n ? reqNum.toString() : '-1', }; } @@ -82,9 +72,8 @@ export function setPendingClanRequest( export function squadronResearchOf(profile: BlkBlock): SquadronResearchState { const block = findBlock(profile, CLAN_RESEARCH_BLOCK); - const unitParam = block && findParam(block, 'researchUnitName')?.value; return { - researchUnitName: unitParam?.type === 'string' ? unitParam.value : '', + researchUnitName: stringField(block, 'researchUnitName'), spentExp: intField(block, 'spentExp'), adminExp: intField(block, 'adminExp'), storedLastEarnedExp: intField(block, 'storedLastEarnedExp'), @@ -145,10 +134,3 @@ function ensureClanResearchBlock(profile: BlkBlock): BlkBlock { setParam(block, 'storedLastEarnedExp', { type: 'int', value: 0 }); return block; } - -function intField(block: BlkBlock | undefined, name: string): number { - const val = block && findParam(block, name)?.value; - if (val?.type === 'int') return val.value; - if (val?.type === 'int64') return Number(val.value); - return 0; -} diff --git a/packages/local-service/src/profile/profile-currency.ts b/packages/local-service/src/profile/profile-currency.ts index cd631c7..3e4de2e 100644 --- a/packages/local-service/src/profile/profile-currency.ts +++ b/packages/local-service/src/profile/profile-currency.ts @@ -11,7 +11,8 @@ * The silver lion balance is warpointsPos - warpointsNeg; setting it keeps the amount spent * and adjusts the amount earned. */ -import { findParam, setParam, type BlkBlock } from '@wto/blk'; +import { setParam, type BlkBlock } from '@wto/blk'; +import { intField } from './blk-fields.ts'; const EARNED = 'warpointsPos'; const SPENT = 'warpointsNeg'; @@ -27,15 +28,15 @@ export interface Balance { export function balanceOf(profile: BlkBlock): Balance { return { - silverLions: numberParam(profile, EARNED) - numberParam(profile, SPENT), - goldenEagles: numberParam(profile, GOLD), - gjn: numberParam(profile, GJN), + silverLions: intField(profile, EARNED) - intField(profile, SPENT), + goldenEagles: intField(profile, GOLD), + gjn: intField(profile, GJN), }; } export function setSilverLions(profile: BlkBlock, amount: number): void { requireAmount(amount, Number.MAX_SAFE_INTEGER); - setParam(profile, EARNED, { type: 'int64', value: BigInt(amount + numberParam(profile, SPENT)) }); + setParam(profile, EARNED, { type: 'int64', value: BigInt(amount + intField(profile, SPENT)) }); } export function setGoldenEagles(profile: BlkBlock, amount: number): void { @@ -50,18 +51,18 @@ export function setGjn(profile: BlkBlock, amount: number): void { export function addGoldenEagles(profile: BlkBlock, amount: number): void { requireAmount(amount, MAX_GOLD); - const next = Math.min(MAX_GOLD, numberParam(profile, GOLD) + amount); + const next = Math.min(MAX_GOLD, intField(profile, GOLD) + amount); setGoldenEagles(profile, next); } export function addSilverLions(profile: BlkBlock, amount: number): void { requireAmount(amount, Number.MAX_SAFE_INTEGER); - setParam(profile, EARNED, { type: 'int64', value: BigInt(numberParam(profile, EARNED) + amount) }); + setParam(profile, EARNED, { type: 'int64', value: BigInt(intField(profile, EARNED) + amount) }); } export function payGjn(profile: BlkBlock, amount: number): void { requireAmount(amount, Number.MAX_SAFE_INTEGER); - const current = numberParam(profile, GJN); + const current = intField(profile, GJN); if (current < amount) throw new RangeError('the player cannot afford this GJN price'); setGjn(profile, current - amount); } @@ -82,14 +83,8 @@ export function pay(profile: BlkBlock, price: Price): void { requireAmount(price.silverLions, Number.MAX_SAFE_INTEGER); requireAmount(price.goldenEagles, MAX_GOLD); if (!canAfford(profile, price)) throw new RangeError('the player cannot afford this price'); - if (price.silverLions > 0) setParam(profile, SPENT, { type: 'int64', value: BigInt(numberParam(profile, SPENT) + price.silverLions) }); - if (price.goldenEagles > 0) setGoldenEagles(profile, numberParam(profile, GOLD) - price.goldenEagles); -} - -function numberParam(profile: BlkBlock, name: string): number { - const value = findParam(profile, name)?.value; - if (value?.type === 'int64') return Number(value.value); - return value?.type === 'int' ? value.value : 0; + if (price.silverLions > 0) setParam(profile, SPENT, { type: 'int64', value: BigInt(intField(profile, SPENT) + price.silverLions) }); + if (price.goldenEagles > 0) setGoldenEagles(profile, intField(profile, GOLD) - price.goldenEagles); } function requireAmount(amount: number, max: number): void { diff --git a/packages/local-service/src/profile/profile-entitlements.ts b/packages/local-service/src/profile/profile-entitlements.ts index 06a61c9..ce0be7a 100644 --- a/packages/local-service/src/profile/profile-entitlements.ts +++ b/packages/local-service/src/profile/profile-entitlements.ts @@ -12,7 +12,8 @@ * } * } */ -import { ensureBlock, findBlock, findParam, setParam, type BlkBlock } from '@wto/blk'; +import { ensureBlock, findBlock, setParam, type BlkBlock } from '@wto/blk'; +import { EMPTY_BLK, int64Field, intField } from './blk-fields.ts'; const ENTITLEMENTS_INFO = 'entitlementsInfo'; export const PREMIUM_ACCOUNT_ENTITLEMENT = 'PremiumAccount'; @@ -20,7 +21,7 @@ const TICKS_PER_SECOND = 10_000_000n; const TICKS_PER_DAY = 86_400n * TICKS_PER_SECOND; export function hasEntitlement(profile: BlkBlock, name: string, nowFiletime: bigint): boolean { - const entry = findBlock(findBlock(profile, ENTITLEMENTS_INFO) ?? emptyRef, name); + const entry = findBlock(findBlock(profile, ENTITLEMENTS_INFO) ?? EMPTY_BLK, name); if (!entry) return false; const count = intField(entry, 'count'); if (count <= 0) return false; @@ -46,22 +47,9 @@ export function extendPremiumAccount(profile: BlkBlock, days: number, nowFiletim /** Remaining whole days (rounded up) of Premium Account, or 0 when inactive. */ export function remainingPremiumDays(profile: BlkBlock, nowFiletime: bigint): number { - const entry = findBlock(findBlock(profile, ENTITLEMENTS_INFO) ?? emptyRef, PREMIUM_ACCOUNT_ENTITLEMENT); + const entry = findBlock(findBlock(profile, ENTITLEMENTS_INFO) ?? EMPTY_BLK, PREMIUM_ACCOUNT_ENTITLEMENT); if (!entry || intField(entry, 'count') <= 0) return 0; const expires = int64Field(entry, 'expiredTime'); if (expires <= nowFiletime) return 0; return Number((expires - nowFiletime + TICKS_PER_DAY - 1n) / TICKS_PER_DAY); } - -const emptyRef: BlkBlock = { name: '', params: [], blocks: [] }; - -function intField(block: BlkBlock, name: string): number { - const value = findParam(block, name)?.value; - return value?.type === 'int' ? value.value : 0; -} - -function int64Field(block: BlkBlock, name: string): bigint { - const value = findParam(block, name)?.value; - if (value?.type === 'int64') return value.value; - return value?.type === 'int' ? BigInt(value.value) : 0n; -} diff --git a/packages/local-service/src/profile/profile-external-inventory.ts b/packages/local-service/src/profile/profile-external-inventory.ts index 930e57f..532f3f8 100644 --- a/packages/local-service/src/profile/profile-external-inventory.ts +++ b/packages/local-service/src/profile/profile-external-inventory.ts @@ -9,7 +9,8 @@ * item{ itemId:t="1" itemDefId:i=50221 quantity:i=1 timestamp:t="2026-11-25T00:00:00Z" } * } */ -import { ensureBlock, findBlock, findParam, setParam, type BlkBlock } from '@wto/blk'; +import { ensureBlock, findBlock, setParam, type BlkBlock } from '@wto/blk'; +import { intField, stringField } from './blk-fields.ts'; const EXT_INVENTORY = 'extInventory'; const NEXT_ID = 'nextItemId'; @@ -28,10 +29,10 @@ export function externalInventoryItems(profile: BlkBlock): StoredExternalItem[] const items: StoredExternalItem[] = []; for (const child of root.blocks) { if (child.name !== ITEM_BLOCK) continue; - const itemId = stringOf(child, 'itemId'); - const itemDefId = intOf(child, 'itemDefId'); - const quantity = intOf(child, 'quantity'); - const timestamp = stringOf(child, 'timestamp') || new Date().toISOString(); + const itemId = stringField(child, 'itemId'); + const itemDefId = intField(child, 'itemDefId'); + const quantity = intField(child, 'quantity'); + const timestamp = stringField(child, 'timestamp') || new Date().toISOString(); if (itemId && itemDefId > 0 && quantity > 0) { items.push({ itemId, itemDefId, quantity, timestamp }); } @@ -54,14 +55,14 @@ export function grantExternalItem( nowIso = new Date().toISOString(), ): StoredExternalItem { const root = ensureBlock(profile, EXT_INVENTORY); - const existing = root.blocks.find((block) => block.name === ITEM_BLOCK && intOf(block, 'itemDefId') === itemDefId); + const existing = root.blocks.find((block) => block.name === ITEM_BLOCK && intField(block, 'itemDefId') === itemDefId); if (existing) { - const newQty = Math.max(0, intOf(existing, 'quantity')) + quantity; + const newQty = Math.max(0, intField(existing, 'quantity')) + quantity; setParam(existing, 'quantity', { type: 'int', value: newQty }); setParam(existing, 'timestamp', { type: 'string', value: nowIso }); - return { itemId: stringOf(existing, 'itemId'), itemDefId, quantity: newQty, timestamp: nowIso }; + return { itemId: stringField(existing, 'itemId'), itemDefId, quantity: newQty, timestamp: nowIso }; } - const nextId = Math.max(1, intOf(root, NEXT_ID) + 1); + const nextId = Math.max(1, intField(root, NEXT_ID) + 1); setParam(root, NEXT_ID, { type: 'int', value: nextId }); const itemId = String(nextId); root.blocks.push({ @@ -91,11 +92,11 @@ export function consumeExternalItem( if (quantity <= 0) return undefined; const root = findBlock(profile, EXT_INVENTORY); if (!root) return undefined; - const idx = root.blocks.findIndex((block) => block.name === ITEM_BLOCK && stringOf(block, 'itemId') === itemId); + const idx = root.blocks.findIndex((block) => block.name === ITEM_BLOCK && stringField(block, 'itemId') === itemId); if (idx < 0) return undefined; const target = root.blocks[idx]!; - const itemDefId = intOf(target, 'itemDefId'); - const current = intOf(target, 'quantity'); + const itemDefId = intField(target, 'itemDefId'); + const current = intField(target, 'quantity'); if (current < quantity) return undefined; const remaining = current - quantity; if (remaining === 0) { @@ -106,13 +107,3 @@ export function consumeExternalItem( } return { itemDefId, remaining, timestamp: nowIso }; } - -function stringOf(block: BlkBlock, name: string): string { - const param = findParam(block, name)?.value; - return param?.type === 'string' ? param.value : ''; -} - -function intOf(block: BlkBlock, name: string): number { - const param = findParam(block, name)?.value; - return param?.type === 'int' ? param.value : param?.type === 'int64' ? Number(param.value) : 0; -} diff --git a/packages/local-service/src/profile/profile-trophies-log.ts b/packages/local-service/src/profile/profile-trophies-log.ts index 7515cb8..50b2ca6 100644 --- a/packages/local-service/src/profile/profile-trophies-log.ts +++ b/packages/local-service/src/profile/profile-trophies-log.ts @@ -4,7 +4,8 @@ * - `userlogs{ <16-hex-id>{ type:i= time:i= roomId:i64=0 body{ ... } } }` * (UserLog::serialize 0x95f160, entry fields 0x95ec30; EULT_OPEN_TROPHY = 30 at 0x1a5599b). */ -import { ensureBlock, findBlock, findParam, setParam, type BlkBlock, type BlkParam } from '@wto/blk'; +import { ensureBlock, findBlock, setParam, type BlkBlock, type BlkParam } from '@wto/blk'; +import { intField } from './blk-fields.ts'; const TROPHIES = 'trophies'; const USERLOGS = 'userlogs'; @@ -15,9 +16,7 @@ export const EULT_BUY_TROPHY = 20; export function trophyOpenCount(profile: BlkBlock, trophyId: string): number { const trophies = findBlock(profile, TROPHIES); - const entry = trophies && findBlock(trophies, trophyId); - const param = entry && findParam(entry, 'count')?.value; - return param?.type === 'int' ? param.value : 0; + return intField(trophies && findBlock(trophies, trophyId), 'count'); } export function incrementTrophyOpenCount(profile: BlkBlock, trophyId: string, delta = 1): number { diff --git a/packages/local-service/src/research/price-table.ts b/packages/local-service/src/research/price-table.ts index 6656566..8b2426c 100644 --- a/packages/local-service/src/research/price-table.ts +++ b/packages/local-service/src/research/price-table.ts @@ -37,7 +37,7 @@ import type { BlkBlock, BlkParam } from '@wto/blk'; import type { CrewSkillCatalogue } from '../crew/crew-skill-rules.ts'; import type { DecorShop } from '../decor/decor-purchase.ts'; -import type { TrophyCatalogue } from '../inventory/trophy-catalogue.ts'; +import type { TrophyCatalogue, TrophyDefinition, TrophyPrize } from '../inventory/trophy-catalogue.ts'; import type { ItemCatalogue } from '../items/item-catalogue.ts'; import type { EquipmentCatalogue } from '../modifications/equipment-catalogue.ts'; import type { UnlockShop } from '../unlocks/unlock-purchase.ts'; @@ -64,7 +64,7 @@ export function priceTable(rules: ResearchRules): BlkBlock { trophyPriceSection(rules.trophies), ], }, - rules.trophies.definitionsBlk(), + trophyDefinitionsSection(rules.trophies), ], }; } @@ -136,3 +136,43 @@ function trophyPriceSection(trophies: TrophyCatalogue): BlkBlock { blocks: trophies.all().map((trophy) => ({ name: trophy.id, params: priceParams(trophy.silverLions, trophy.goldenEagles), blocks: [] })), }; } + +function trophyDefinitionsSection(trophies: TrophyCatalogue): BlkBlock { + return { + name: 'trophy', + params: [], + blocks: trophies.all().map(toTrophyDefinitionBlk), + }; +} + +function toTrophyDefinitionBlk(trophy: TrophyDefinition): BlkBlock { + const params: BlkParam[] = [ + { name: 'iconStyle', value: { type: 'string', value: trophy.iconStyle } }, + { name: 'showChances', value: { type: 'bool', value: trophy.showChances } }, + { name: 'repeatable', value: { type: 'bool', value: trophy.repeatable } }, + { name: 'instantOpening', value: { type: 'bool', value: trophy.instantOpening } }, + ]; + if (trophy.numTotal > 0) params.push(intParam('numTotal', trophy.numTotal)); + if (trophy.countryFlag) params.push({ name: 'showCountryFlag', value: { type: 'string', value: trophy.countryFlag } }); + if (trophy.prizes.length === 1 && trophy.prizes[0]!.kind === 'unit') { + params.push({ name: 'showTypeInName', value: { type: 'bool', value: true } }); + } + return { + name: trophy.id, + params, + blocks: [{ name: 'prizes', params: [], blocks: trophy.prizes.map(prizeToBlk) }], + }; +} + +function prizeToBlk(prize: TrophyPrize): BlkBlock { + const weightTag = prize.weight >= 25 ? 'high' : prize.weight >= 10 ? 'medium' : 'low'; + const params: BlkParam[] = [{ name: 'weight', value: { type: 'string', value: weightTag } }]; + if (prize.kind === 'warpoints') params.push(intParam('warpoints', prize.amount)); + else if (prize.kind === 'gold') params.push(intParam('gold', prize.amount)); + else if (prize.kind === 'item') { + params.push({ name: 'item', value: { type: 'string', value: prize.itemName } }, intParam('count', prize.count)); + } else { + params.push({ name: 'unit', value: { type: 'string', value: prize.unitName } }); + } + return { name: 'i', params, blocks: [] }; +} diff --git a/packages/local-service/src/store/store-catalogue.ts b/packages/local-service/src/store/store-catalogue.ts index 9c034c9..4ed50a0 100644 --- a/packages/local-service/src/store/store-catalogue.ts +++ b/packages/local-service/src/store/store-catalogue.ts @@ -1,12 +1,15 @@ /** - * Local store catalogue: Golden Eagles packs, Silver Lions packs, - * Premium Account durations (both Golden Eagles and GJN), and one vehicle pack per gift - * vehicle in the tech tree. + * Local store catalogue: Golden Eagles packs, Silver Lions + * packs, Premium Account durations (both Golden Eagles and GJN), and one vehicle pack per + * gift vehicle in the tech tree. + * + * Pure domain catalogue: protocol-layer DataBlock serialization for `cln_get_entitlements_price_ex` + * lives in `char/actions/store-actions.ts`. */ -import { emptyBlock, setParam, type BlkBlock } from '@wto/blk'; -import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts'; +import { EXTRA_STORE_BUNDLE_GUID_MAP } from '@wto/build'; import type { StoreBundleGuids } from '../game-data/datasets/store-bundles.ts'; import type { LocalizedText, UnitNamesMap } from '../game-data/datasets/unit-names.ts'; +import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts'; export type StoreProductKind = 'eagles' | 'warpoints' | 'premium-gold' | 'premium-gjn' | 'vehicle-pack'; @@ -61,10 +64,10 @@ const PREMIUM_GOLD_TIERS: ReadonlyArray<{ readonly id: string; readonly days: nu { id: 'prem_365d', days: 365, goldCost: 14_900 }, ]; -const PREMIUM_GJN_TIERS: ReadonlyArray<{ readonly id: string; readonly fallbackGuid: string; readonly days: number; readonly gjn: number }> = [ - { id: 'wto_prem_20d', fallbackGuid: 'A1E00020-5754-4F46-8F00-000000000020', days: 20, gjn: 8 }, - { id: 'wto_prem_60d', fallbackGuid: 'A1E00060-5754-4F46-8F00-000000000060', days: 60, gjn: 20 }, - { id: 'wto_prem_180d', fallbackGuid: 'A1E00180-5754-4F46-8F00-000000000180', days: 180, gjn: 40 }, +const PREMIUM_GJN_TIERS: ReadonlyArray<{ readonly id: string; readonly days: number; readonly gjn: number }> = [ + { id: 'wto_prem_20d', days: 20, gjn: 8 }, + { id: 'wto_prem_60d', days: 60, gjn: 20 }, + { id: 'wto_prem_180d', days: 180, gjn: 40 }, ]; interface PackTier { @@ -86,80 +89,20 @@ function packTierForRank(rank: number): PackTier { export class StoreCatalogue { readonly #byId = new Map(); readonly #byGuid = new Map(); - readonly #priceBlk: BlkBlock; constructor(vehicles: readonly CatalogueVehicle[], bundleGuids: StoreBundleGuids, names: UnitNamesMap) { - const products: StoreProduct[] = []; - - for (const pack of EAGLES_PACKS) { - const guid = bundleGuids[pack.id]; - products.push({ - id: pack.id, - kind: 'eagles', - chapter: 'eagles', - title: { en: `${pack.gold.toLocaleString('en-US')} Golden Eagles`, zh: `${pack.gold.toLocaleString('en-US')} 金鹰` }, - ...(guid ? { guid } : {}), - gjnCost: pack.gjn, - goldIncome: pack.gold, - }); - } - - for (const pack of SILVER_LIONS_PACKS) { - products.push({ - id: pack.id, - kind: 'warpoints', - chapter: 'warpoints', - title: { en: `${pack.silver.toLocaleString('en-US')} Silver Lions`, zh: `${pack.silver.toLocaleString('en-US')} 银狮` }, - goldCost: pack.goldCost, - silverIncome: pack.silver, - }); - } - - for (const tier of PREMIUM_GOLD_TIERS) { - products.push({ - id: tier.id, - kind: 'premium-gold', - chapter: 'premium', - title: { en: `Premium Account (${tier.days}d)`, zh: `高级账户(${tier.days} 天)` }, - goldCost: tier.goldCost, - premiumDays: tier.days, - }); - } - - for (const tier of PREMIUM_GJN_TIERS) { - const guid = bundleGuids[tier.id] ?? tier.fallbackGuid; - products.push({ - id: tier.id, - kind: 'premium-gjn', - chapter: 'premium', - title: { en: `Premium Account (${tier.days}d)`, zh: `高级账户(${tier.days} 天)` }, - guid, - gjnCost: tier.gjn, - premiumDays: tier.days, - }); - } - - for (const vehicle of vehicles) { - if (!isPackVehicle(vehicle)) continue; - const tier = packTierForRank(vehicle.rank); - const unitLabel = names[vehicle.name] ?? { en: vehicle.name, zh: vehicle.name }; - products.push({ - id: `wto_pack_${vehicle.name}`, - kind: 'vehicle-pack', - chapter: 'bonuses', - title: { en: `${unitLabel.en} Pack`, zh: `${unitLabel.zh} 礼包` }, - gjnCost: tier.gjn, - goldIncome: tier.bonusGold, - premiumDays: tier.bonusDays, - vehicle, - }); - } + const products: StoreProduct[] = [ + ...buildEaglesProducts(bundleGuids), + ...buildSilverProducts(), + ...buildPremiumGoldProducts(), + ...buildPremiumGjnProducts(bundleGuids), + ...buildVehiclePackProducts(vehicles, names), + ]; for (const product of products) { this.#byId.set(product.id, product); if (product.guid) this.#byGuid.set(product.guid.toUpperCase(), product); } - this.#priceBlk = buildEntitlementsPriceBlk(products); } allProducts(): readonly StoreProduct[] { @@ -173,10 +116,75 @@ export class StoreCatalogue { byGuid(guid: string): StoreProduct | undefined { return this.#byGuid.get(guid.trim().toUpperCase()); } +} - entitlementsPriceBlk(): BlkBlock { - return this.#priceBlk; - } +function buildEaglesProducts(bundleGuids: StoreBundleGuids): StoreProduct[] { + return EAGLES_PACKS.map((pack) => { + const guid = bundleGuids[pack.id]; + return { + id: pack.id, + kind: 'eagles', + chapter: 'eagles', + title: { en: `${pack.gold.toLocaleString('en-US')} Golden Eagles`, zh: `${pack.gold.toLocaleString('en-US')} 金鹰` }, + ...(guid ? { guid } : {}), + gjnCost: pack.gjn, + goldIncome: pack.gold, + }; + }); +} + +function buildSilverProducts(): StoreProduct[] { + return SILVER_LIONS_PACKS.map((pack) => ({ + id: pack.id, + kind: 'warpoints', + chapter: 'warpoints', + title: { en: `${pack.silver.toLocaleString('en-US')} Silver Lions`, zh: `${pack.silver.toLocaleString('en-US')} 银狮` }, + goldCost: pack.goldCost, + silverIncome: pack.silver, + })); +} + +function buildPremiumGoldProducts(): StoreProduct[] { + return PREMIUM_GOLD_TIERS.map((tier) => ({ + id: tier.id, + kind: 'premium-gold', + chapter: 'premium', + title: { en: `Premium Account (${tier.days}d)`, zh: `高级账户(${tier.days} 天)` }, + goldCost: tier.goldCost, + premiumDays: tier.days, + })); +} + +function buildPremiumGjnProducts(bundleGuids: StoreBundleGuids): StoreProduct[] { + return PREMIUM_GJN_TIERS.map((tier) => { + const guid = bundleGuids[tier.id] ?? EXTRA_STORE_BUNDLE_GUID_MAP[tier.id]; + return { + id: tier.id, + kind: 'premium-gjn', + chapter: 'premium', + title: { en: `Premium Account (${tier.days}d)`, zh: `高级账户(${tier.days} 天)` }, + ...(guid ? { guid } : {}), + gjnCost: tier.gjn, + premiumDays: tier.days, + }; + }); +} + +function buildVehiclePackProducts(vehicles: readonly CatalogueVehicle[], names: UnitNamesMap): StoreProduct[] { + return vehicles.filter(isPackVehicle).map((vehicle) => { + const tier = packTierForRank(vehicle.rank); + const unitLabel = names[vehicle.name] ?? { en: vehicle.name, zh: vehicle.name }; + return { + id: `wto_pack_${vehicle.name}`, + kind: 'vehicle-pack', + chapter: 'bonuses', + title: { en: `${unitLabel.en} Pack`, zh: `${unitLabel.zh} 礼包` }, + gjnCost: tier.gjn, + goldIncome: tier.bonusGold, + premiumDays: tier.bonusDays, + vehicle, + }; + }); } function isPackVehicle(vehicle: CatalogueVehicle): boolean { @@ -186,40 +194,3 @@ function isPackVehicle(vehicle: CatalogueVehicle): boolean { && vehicle.marketplaceItemdefId === undefined && !vehicle.onlyShownWhenOwned; } - -function buildEntitlementsPriceBlk(products: readonly StoreProduct[]): BlkBlock { - const root = emptyBlock(); - for (const product of products) { - const block = emptyBlock(product.id); - setParam(block, 'chapter', { type: 'string', value: product.chapter }); - - if (product.kind === 'eagles') { - setParam(block, 'onlinePurchase', { type: 'bool', value: true }); - setParam(block, 'group', { type: 'string', value: 'eagles100' }); - setParam(block, 'useGroupAmount', { type: 'bool', value: true }); - setParam(block, 'goldIncome', { type: 'int', value: product.goldIncome! }); - } else if (product.kind === 'warpoints') { - setParam(block, 'group', { type: 'string', value: '1KWP' }); - setParam(block, 'useGroupAmount', { type: 'bool', value: true }); - setParam(block, 'wpIncome', { type: 'int', value: product.silverIncome! }); - setParam(block, 'goldCost', { type: 'int', value: product.goldCost! }); - } else if (product.kind === 'premium-gold') { - setParam(block, 'alias', { type: 'string', value: 'PremiumAccount' }); - setParam(block, 'group', { type: 'string', value: 'PremiumAccount' }); - setParam(block, 'ttl', { type: 'int', value: product.premiumDays! }); - setParam(block, 'goldCost', { type: 'int', value: product.goldCost! }); - } else if (product.kind === 'premium-gjn') { - setParam(block, 'onlinePurchase', { type: 'bool', value: true }); - setParam(block, 'alias', { type: 'string', value: 'PremiumAccount' }); - setParam(block, 'group', { type: 'string', value: 'PremiumAccount' }); - setParam(block, 'ttl', { type: 'int', value: product.premiumDays! }); - } else if (product.kind === 'vehicle-pack' && product.vehicle) { - setParam(block, 'onlinePurchase', { type: 'bool', value: true }); - setParam(block, 'aircraftGift', { type: 'string', value: product.vehicle.name }); - if (product.goldIncome) setParam(block, 'goldIncome', { type: 'int', value: product.goldIncome }); - } - - root.blocks.push(block); - } - return root; -} diff --git a/packages/local-service/src/store/store-service.ts b/packages/local-service/src/store/store-service.ts index ef73429..4f70e54 100644 --- a/packages/local-service/src/store/store-service.ts +++ b/packages/local-service/src/store/store-service.ts @@ -16,12 +16,19 @@ import { balanceOf } from '../profile/profile-currency.ts'; import { remainingPremiumDays } from '../profile/profile-entitlements.ts'; import { serverTimeNow } from '../profile/server-time.ts'; import type { Service, ServiceRequest, ServiceResponse } from '../server/exchange.ts'; +import { + createStaticWebSite, + jsonResponse, + parseJsonBody, + requireWebActionAccount, + selectWebViewAccount, +} from '../web-ui/web-helpers.ts'; import { redeemStoreCode, type RedeemOutcome } from './redeem-codes.ts'; import type { StoreCatalogue, StoreProduct } from './store-catalogue.ts'; -import { renderStorePageHtml } from './store-page.ts'; import { buyGjnProduct, canBuyGjnProduct, type GjnPurchaseOutcome } from './store-purchase.ts'; const STORE_API_PATHS = new Set(['/item_info.php', '/item_purchase.php', '/redeem_code.php']); +const STORE_WEB = createStaticWebSite(new URL('./web/', import.meta.url)); export class StoreService implements Service { readonly name = 'store'; @@ -42,10 +49,9 @@ export class StoreService implements Service { } handle(request: ServiceRequest): ServiceResponse { - if (request.path === '/store' || request.path === '/store/') return this.#storePage(); - if (request.path === '/store/api/state' && request.method === 'GET') return this.#webState(request); - if (request.path === '/store/api/buy' && request.method === 'POST') return this.#webBuy(request); - if (request.path === '/store/api/redeem' && request.method === 'POST') return this.#webRedeem(request); + if (request.path === '/store' || request.path.startsWith('/store/')) { + return this.#handleWebRequest(request); + } const redacted = redactLoginForm(request.body); const apiResponse = request.method !== 'POST' @@ -58,6 +64,15 @@ export class StoreService implements Service { return { ...apiResponse, logNotes: { ...apiResponse.logNotes, redactedRequestBody: redacted, requestText: redacted } }; } + #handleWebRequest(request: ServiceRequest): ServiceResponse { + const subPath = request.path.slice('/store'.length) || '/'; + if (subPath === '/api/state' && request.method === 'GET') return this.#webState(request); + if (subPath === '/api/buy' && request.method === 'POST') return this.#webBuy(request); + if (subPath === '/api/redeem' && request.method === 'POST') return this.#webRedeem(request); + return STORE_WEB.serve(subPath, 'store web') + ?? { status: 404, headers: { 'content-type': 'text/plain; charset=utf-8' }, body: 'Not found', logNotes: { summary: `store 404: ${subPath}` } }; + } + #itemInfo(request: ServiceRequest): ServiceResponse { const form = new URLSearchParams(request.body.toString('utf8')); const guids = [...form.getAll('guids[]'), ...form.getAll('guids'), ...form.getAll('guid')].filter(Boolean); @@ -128,18 +143,8 @@ export class StoreService implements Service { return yuplayAnswer(outcome.reason === 'ALREADY_REDEEMED' ? 'ALREADY' : 'NOTFOUND', {}, `redeem_code ${code} -> ${outcome.reason}`); } - #storePage(): ServiceResponse { - return { - status: 200, - headers: { 'content-type': 'text/html; charset=utf-8' }, - body: renderStorePageHtml(), - logNotes: { summary: 'store web page' }, - }; - } - #webState(request: ServiceRequest): ServiceResponse { - const requestedId = request.query.get('userId') ?? ''; - const account = requestedId ? this.#accounts.byUserId(requestedId) : this.#accounts.all()[0]; + const account = selectWebViewAccount(this.#accounts, request.query.get('userId')); const now = serverTimeNow(); const profile = account ? this.#profiles.profileOf(account.userId) : undefined; const balance = profile ? balanceOf(profile) : { silverLions: 0, goldenEagles: 0, gjn: 0 }; @@ -160,12 +165,11 @@ export class StoreService implements Service { #webBuy(request: ServiceRequest): ServiceResponse { const body = parseJsonBody(request.body); - const userId = typeof body.userId === 'string' ? body.userId : ''; + const account = requireWebActionAccount(this.#accounts, body.userId); const productId = typeof body.productId === 'string' ? body.productId : ''; - const account = this.#accounts.byUserId(userId); const product = this.#catalogue.byId(productId); if (!account || !product || product.gjnCost === undefined) { - return jsonResponse({ ok: false, message: '未找到账号或商品。' }, 'store web buy: invalid request'); + return jsonResponse({ ok: false, message: '未找到指定账号或商品。' }, 'store web buy: invalid request'); } let outcome: GjnPurchaseOutcome = { ok: false, reason: 'NOT_FOUND' }; @@ -187,10 +191,9 @@ export class StoreService implements Service { #webRedeem(request: ServiceRequest): ServiceResponse { const body = parseJsonBody(request.body); - const userId = typeof body.userId === 'string' ? body.userId : ''; + const account = requireWebActionAccount(this.#accounts, body.userId); const code = typeof body.code === 'string' ? body.code : ''; - const account = this.#accounts.byUserId(userId); - if (!account) return jsonResponse({ ok: false, message: '请先在游戏内登录一个本地账号。' }, 'store web redeem: no account'); + if (!account) return jsonResponse({ ok: false, message: '请先在游戏内登录本地账号并在右上角选择账号。' }, 'store web redeem: unknown account'); let outcome: RedeemOutcome = { ok: false, reason: 'INVALID_CODE', message: { en: '', zh: '无效的兑换码。' } }; const now = serverTimeNow(); @@ -220,22 +223,3 @@ function toWebProduct(product: StoreProduct, owned: boolean): Record { - try { - const parsed = JSON.parse(raw.toString('utf8')) as unknown; - return parsed && typeof parsed === 'object' ? (parsed as Record) : {}; - } catch { - return {}; - } -} - -function jsonResponse(payload: unknown, summary: string): ServiceResponse { - const body = JSON.stringify(payload); - return { - status: 200, - headers: { 'content-type': 'application/json; charset=utf-8' }, - body, - logNotes: { summary, responseText: body }, - }; -} diff --git a/packages/local-service/src/store/store-page.ts b/packages/local-service/src/store/web/app.js similarity index 50% rename from packages/local-service/src/store/store-page.ts rename to packages/local-service/src/store/web/app.js index 715ce80..bfe0b54 100644 --- a/packages/local-service/src/store/store-page.ts +++ b/packages/local-service/src/store/web/app.js @@ -1,180 +1,9 @@ -/** - * Single-page HTML interface for the local web store (/store, implementation notes; - * implementation notes section G). All dynamic data comes from /store/api/* as JSON. - */ -export function renderStorePageHtml(): string { - return ` - - - - -War Thunder Offline — 本地商店 - - - -
-
WAR THUNDER OFFLINE 本地商店 · 切回游戏窗口自动同步档案
-
- -
GJN 余额 0
-
金鹰 0
-
银狮 0
-
高级账户 未激活
-
-
-
-
-
- - - - -
-
- - - -
-
- -
- - -`; -} diff --git a/packages/local-service/src/store/web/index.html b/packages/local-service/src/store/web/index.html new file mode 100644 index 0000000..614a216 --- /dev/null +++ b/packages/local-service/src/store/web/index.html @@ -0,0 +1,51 @@ + + + + + + War Thunder Offline — 本地商店 + + + +
+
WAR THUNDER OFFLINE 本地商店 · 切回游戏窗口自动同步档案
+
+ 前往本地交易所 + +
GJN 余额 0
+
金鹰 0
+
银狮 0
+
高级账户 未激活
+
+
+
+
+
+ + + + +
+
+ + + +
+
+ +
+ + + diff --git a/packages/local-service/src/store/web/styles.css b/packages/local-service/src/store/web/styles.css new file mode 100644 index 0000000..b7957c3 --- /dev/null +++ b/packages/local-service/src/store/web/styles.css @@ -0,0 +1,128 @@ +:root { + --bg: #11161c; + --panel: #19212b; + --panel-alt: #212b38; + --border: #2e3b4d; + --text: #e6edf5; + --muted: #93a3b5; + --accent: #e09f3e; + --accent-hover: #f0b354; + --ok: #3ea66b; + --err: #d9534f; +} +* { box-sizing: border-box; } +body { + margin: 0; + font-family: "Segoe UI", "Microsoft YaHei", system-ui, sans-serif; + background: var(--bg); + color: var(--text); +} +header { + background: var(--panel); + border-bottom: 1px solid var(--border); + padding: 14px 24px; + display: flex; + flex-wrap: wrap; + gap: 16px; + align-items: center; + justify-content: space-between; +} +.brand { font-size: 18px; font-weight: 700; letter-spacing: 0.3px; } +.brand span { color: var(--accent); font-size: 13px; margin-left: 8px; font-weight: 500; } +.wallet { + display: flex; + flex-wrap: wrap; + gap: 12px; + align-items: center; +} +.pill { + background: var(--panel-alt); + border: 1px solid var(--border); + padding: 6px 12px; + border-radius: 6px; + font-size: 13px; +} +.pill strong { color: var(--accent); font-size: 15px; margin-left: 4px; } +.link-btn { + text-decoration: none; + color: var(--muted); + font-size: 13px; + padding: 6px 10px; + border: 1px solid var(--border); + border-radius: 6px; +} +select, input { + background: var(--panel-alt); + color: var(--text); + border: 1px solid var(--border); + border-radius: 6px; + padding: 7px 11px; + font-size: 14px; +} +#searchInput { min-width: 220px; } +main { max-width: 1240px; margin: 0 auto; padding: 20px 24px 48px; } +.tabs { display: flex; gap: 8px; margin-bottom: 18px; flex-wrap: wrap; } +.tab { + background: var(--panel); + color: var(--muted); + border: 1px solid var(--border); + padding: 9px 16px; + border-radius: 6px; + cursor: pointer; + font-size: 14px; + font-weight: 600; +} +.tab.active { background: var(--accent); color: #11161c; border-color: var(--accent); } +.filters { display: flex; gap: 10px; margin-bottom: 16px; flex-wrap: wrap; } +.notice { + padding: 10px 14px; + border-radius: 6px; + margin-bottom: 16px; + font-size: 14px; + display: none; +} +.notice.ok { display: block; background: rgba(62, 166, 107, 0.18); border: 1px solid var(--ok); } +.notice.err { display: block; background: rgba(217, 83, 79, 0.18); border: 1px solid var(--err); } +.grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(265px, 1fr)); + gap: 14px; +} +.card { + background: var(--panel); + border: 1px solid var(--border); + border-radius: 8px; + padding: 15px; + display: flex; + flex-direction: column; + justify-content: space-between; + gap: 12px; +} +.card h3 { margin: 0 0 6px; font-size: 16px; } +.meta { color: var(--muted); font-size: 12.5px; line-height: 1.5; } +.card-foot { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-top: 4px; } +.price { font-size: 17px; font-weight: 700; color: var(--accent); } +button.buy { + background: var(--accent); + color: #11161c; + border: none; + border-radius: 6px; + padding: 8px 14px; + font-weight: 700; + cursor: pointer; + font-size: 13.5px; +} +button.buy:hover:not(:disabled) { background: var(--accent-hover); } +button.buy:disabled { background: var(--border); color: var(--muted); cursor: default; } +.redeem-box { + background: var(--panel); + border: 1px solid var(--border); + border-radius: 8px; + padding: 20px; + max-width: 600px; +} +.redeem-box h3 { margin-top: 0; } +.redeem-row { display: flex; gap: 10px; margin: 12px 0 16px; } +.redeem-row input { flex: 1; } +.hint { color: var(--muted); font-size: 13px; line-height: 1.6; } +code { background: var(--panel-alt); padding: 2px 6px; border-radius: 4px; color: var(--accent); } diff --git a/packages/local-service/src/web-ui/web-helpers.ts b/packages/local-service/src/web-ui/web-helpers.ts new file mode 100644 index 0000000..0f9126b --- /dev/null +++ b/packages/local-service/src/web-ui/web-helpers.ts @@ -0,0 +1,79 @@ +/** + * Shared static-asset server, JSON helpers, and explicit account resolution for local web UIs + * (`/store` and `/trade.gaijin.net`; implementation notes). + */ +import { readFileSync } from 'node:fs'; +import { extname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import type { Account, AccountStore } from '../accounts/account-store.ts'; +import type { ServiceResponse } from '../server/exchange.ts'; + +const CONTENT_TYPES: Readonly> = { + '.html': 'text/html; charset=utf-8', + '.css': 'text/css; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', +}; + +const ALLOWED_ASSETS = new Set(['index.html', 'styles.css', 'app.js']); + +export interface StaticWebSite { + serve(subPath: string, summaryPrefix: string): ServiceResponse | undefined; +} + +export function createStaticWebSite(folderUrl: URL): StaticWebSite { + const rootDir = fileURLToPath(folderUrl); + return { + serve(subPath: string, summaryPrefix: string): ServiceResponse | undefined { + const normalized = subPath === '' || subPath === '/' ? 'index.html' : subPath.replace(/^\/+/, ''); + if (!ALLOWED_ASSETS.has(normalized)) return undefined; + const contentType = CONTENT_TYPES[extname(normalized)] ?? 'application/octet-stream'; + const body = readFileSync(join(rootDir, normalized)); + return { + status: 200, + headers: { 'content-type': contentType, 'cache-control': 'no-cache' }, + body, + logNotes: { summary: `${summaryPrefix}: ${normalized}` }, + }; + }, + }; +} + +export function parseJsonBody(raw: Buffer): Record { + try { + const parsed = JSON.parse(raw.toString('utf8')) as unknown; + return parsed && typeof parsed === 'object' && !Array.isArray(parsed) + ? (parsed as Record) + : {}; + } catch { + return {}; + } +} + +export function jsonResponse(payload: unknown, summary: string): ServiceResponse { + const body = JSON.stringify(payload); + return { + status: 200, + headers: { 'content-type': 'application/json; charset=utf-8' }, + body, + logNotes: { summary, responseText: body.slice(0, 1200) }, + }; +} + +/** + * Select the account displayed in a read-only web state query: + * - when `requestedUserId` is provided, look up that exact account (never falling back to another); + * - when `requestedUserId` is omitted on initial page load, default the UI selector to the first registered account. + */ +export function selectWebViewAccount(accounts: AccountStore, requestedUserId: string | null): Account | undefined { + const trimmed = requestedUserId?.trim() ?? ''; + return trimmed ? accounts.byUserId(trimmed) : accounts.all()[0]; +} + +/** + * Require an explicit, valid `userId` on mutating web actions (buy, redeem); never fall back. + */ +export function requireWebActionAccount(accounts: AccountStore, rawUserId: unknown): Account | undefined { + if (typeof rawUserId !== 'string') return undefined; + const trimmed = rawUserId.trim(); + return trimmed ? accounts.byUserId(trimmed) : undefined; +}