From 2e2c4a5234b0a921f09af1c76ea47afa42d65bf4 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:47:33 +0800 Subject: [PATCH] Add local squadrons, activity, and squadron vehicle research --- .../src/char/actions/action-table.ts | 69 +- .../src/char/actions/clan-actions.ts | 422 ++++++++++ .../src/char/actions/online-init-actions.ts | 13 +- .../src/char/actions/player-card-actions.ts | 43 +- packages/local-service/src/clans/clan-blk.ts | 315 ++++++++ .../local-service/src/clans/clan-seeds.ts | 246 ++++++ .../local-service/src/clans/clan-store.ts | 719 ++++++++++++++++++ .../local-service/src/clans/clan-types.ts | 147 ++++ .../src/game-data/datasets/clan-economy.ts | 43 ++ .../game-data/datasets/vehicle-catalogue.ts | 8 +- packages/local-service/src/local-service.ts | 4 +- .../src/profile/client-profile.ts | 4 +- .../local-service/src/profile/profile-clan.ts | 154 ++++ .../src/research/research-rules.ts | 4 + .../src/research/squadron-research.ts | 116 +++ packages/local-service/src/save-cli.ts | 23 +- 16 files changed, 2307 insertions(+), 23 deletions(-) create mode 100644 packages/local-service/src/char/actions/clan-actions.ts create mode 100644 packages/local-service/src/clans/clan-blk.ts create mode 100644 packages/local-service/src/clans/clan-seeds.ts create mode 100644 packages/local-service/src/clans/clan-store.ts create mode 100644 packages/local-service/src/clans/clan-types.ts create mode 100644 packages/local-service/src/game-data/datasets/clan-economy.ts create mode 100644 packages/local-service/src/profile/profile-clan.ts create mode 100644 packages/local-service/src/research/squadron-research.ts diff --git a/packages/local-service/src/char/actions/action-table.ts b/packages/local-service/src/char/actions/action-table.ts index 5ab4aa4..cbc252d 100644 --- a/packages/local-service/src/char/actions/action-table.ts +++ b/packages/local-service/src/char/actions/action-table.ts @@ -1,9 +1,35 @@ /** Char action names mapped to their handlers (full list of names: research-data/char_actions_37.json). */ 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 type { CharActionHandler } from '../char-action.ts'; import { acceptEula } from './agreement-actions.ts'; +import { + buyNotResearchedClanUnitAction, + clanAcceptCandidateAction, + clanChangeInfoAction, + clanChangeMemberRoleAction, + clanCreateAction, + clanDisbandAction, + clanDismissMemberAction, + clanEditBlacklistAction, + clanFindByPrefixAction, + clanGetAction, + clanGetLeaderboardAction, + clanGetLogAction, + clanLeaveAction, + clanMembershipRequestAction, + clanMembersUpgradeAction, + clanRejectCandidateAction, + clansListShortInfoAction, + clanSetMembershipReqAction, + clanSyncProfileAction, + clanUpgradeAction, + flushClanExpToUnitAction, + setClanBestRewardsAction, + setResearchClanUnitAction, +} from './clan-actions.ts'; import { bulkTrainCrews, trainCrew } from './crew-actions.ts'; import { buyUnlockAction } from './unlock-actions.ts'; import { buyAllModificationsAction, buyModificationAction, buySparesAction, buyWeaponsAction, enableModificationsAction } from './modification-actions.ts'; @@ -31,15 +57,16 @@ export interface ActionDependencies { readonly profiles: PlayerProfiles; readonly accounts: AccountStore; readonly research: ResearchRules; + readonly clans?: ClanStore; readonly notifyInventoryChanged?: () => void; } export function actionTable(deps: ActionDependencies): ReadonlyMap { const notifyInventory = deps.notifyInventoryChanged ?? (() => {}); - return new Map([ + const entries: Array<[string, CharActionHandler]> = [ ['cln_get_initial_meta', initialMeta()], - ['cln_upd_entitlements_full', entitlementsFull(deps.profiles, deps.accounts)], - ['cln_legacy_get_userdata', legacyUserData(deps.profiles, deps.accounts)], + ['cln_upd_entitlements_full', entitlementsFull(deps.profiles, deps.accounts, deps.clans)], + ['cln_legacy_get_userdata', legacyUserData(deps.profiles, deps.accounts, deps.clans)], ['cln_accept_eula', acceptEula(deps.profiles, deps.accounts)], ['cln_set_starting_info', setStartingInfo(deps.profiles, deps.accounts)], ['cln_bulk_train_aircraft', bulkTrainCrews(deps.profiles, deps.accounts, deps.research)], @@ -61,7 +88,7 @@ export function actionTable(deps: ActionDependencies): ReadonlyMap(entries); } diff --git a/packages/local-service/src/char/actions/clan-actions.ts b/packages/local-service/src/char/actions/clan-actions.ts new file mode 100644 index 0000000..f551206 --- /dev/null +++ b/packages/local-service/src/char/actions/clan-actions.ts @@ -0,0 +1,422 @@ +/** + * Char action handlers for squadrons (clans) and squadron vehicle research + *. + */ +import { emptyBlock, findBlock, findParam, type BlkBlock } from '@wto/blk'; +import type { AccountStore } from '../../accounts/account-store.ts'; +import { + toClanInfoBlk, + toClanLeaderboardRowBlk, + toClanLogBlk, + 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 { 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 { + return { + silverLions: intParam(payload, 'cost') ?? 0, + goldenEagles: intParam(payload, 'costGold') ?? 0, + }; +} + +function clanProfileRuleAction( + profiles: PlayerProfiles, + accounts: AccountStore, + clans: ClanStore, + run: (context: CharActionContext, profile: BlkBlock, account: ReturnType & {}) => RuleOutcome, +): CharActionHandler { + return (context) => withAccount(context, accounts, (account) => { + let outcome: RuleOutcome = { ok: false, refusal: 'BAD_PARAMS' }; + const updated = profiles.updateWhen(account.userId, (saved) => { + clans.syncProfile(saved, account); + outcome = run(context, saved, account); + return outcome.ok; + }); + if (!updated) return { kind: 'error', code: outcome.ok ? 'BAD_PARAMS' : outcome.refusal }; + return { kind: 'data', blk: clientProfile(updated, account, clans) }; + }); +} + +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 clan = (!clanId && !clanName && !clanTag) + ? clans.clanOfUser(account.userId)?.clan + : clans.findClan({ clanId, clanName, clanTag }); + if (!clan) return { kind: 'error', code: 'CLAN_NOT_FOUND' }; + return { kind: 'data', blk: toClanInfoBlk(clan) }; + }); +} + +export function clanGetLeaderboardAction(clans: ClanStore): CharActionHandler { + return (context) => { + const payload = context.payload; + const rows = clans.queryLeaderboard({ + start: (payload && intParam(payload, 'start')) ?? 0, + count: (payload && intParam(payload, 'count')) ?? 20, + sortField: (payload && stringParam(payload, 'sortField')) ?? 'dr_era5_hist', + clanId: payload ? stringParam(payload, 'clanId') : undefined, + filterOpen: payload ? stringParam(payload, 'filterOpen') === 'on' : false, + 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)) }, + }; + }; +} + +export function clanFindByPrefixAction(clans: ClanStore): CharActionHandler { + return (context) => { + const payload = context.payload; + const prefix = (payload && (stringParam(payload, 'namePrefix') ?? stringParam(payload, 'tagPrefix'))) ?? ''; + const rows = clans.queryLeaderboard({ + start: (payload && intParam(payload, 'start')) ?? 0, + count: (payload && intParam(payload, 'count')) ?? 20, + sortField: 'activity', + prefix, + filterOpen: payload ? stringParam(payload, 'filterOpen') === 'on' : false, + 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)) }, + }; + }; +} + +export function clansListShortInfoAction(clans: ClanStore): CharActionHandler { + return (context) => { + const body = context.payload && findBlock(context.payload, 'body'); + const requestedIds = (body?.params ?? []) + .filter((p) => p.name === 'clanId' && p.value.type === 'string') + .map((p) => (p.value as { type: 'string'; value: string }).value); + const blocks = requestedIds.flatMap((id) => { + const clan = clans.byId(id); + return clan ? [toClanShortInfoBlk(clan)] : []; + }); + return { kind: 'data', blk: { name: '', params: [], blocks } }; + }; +} + +export function clanGetLogAction(accounts: AccountStore, clans: ClanStore): CharActionHandler { + return (context) => withAccount(context, accounts, (account) => { + const clanId = strOrIntId(context, '_id') ?? strOrIntId(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; + const events = context.payload ? stringParam(context.payload, 'events') : undefined; + const last = context.payload ? stringParam(context.payload, 'last') : undefined; + return { kind: 'data', blk: toClanLogBlk(clan, count, events, last) }; + }); +} + +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); + if (!payload || !offered) return { ok: false, refusal: 'BAD_PARAMS' }; + const rawType = stringParam(payload, 'type'); + return clans.createClan(profile, account, rules.clanEconomy, { + name: stringParam(payload, 'name') ?? '', + tag: stringParam(payload, 'tag') ?? '', + slogan: stringParam(payload, 'slogan') ?? '', + region: stringParam(payload, 'region') ?? '', + desc: stringParam(payload, 'desc') ?? '', + announcement: stringParam(payload, 'announcement') ?? '', + type: rawType === 'battalion' ? 'battalion' : 'normal', + offered, + }); + }); +} + +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 rawStatus = stringParam(payload, 'status'); + return clans.editClanInfo(profile, account, rules.clanEconomy, clanId, { + name: stringParam(payload, 'name'), + tag: stringParam(payload, 'tag'), + desc: stringParam(payload, 'desc'), + slogan: stringParam(payload, 'slogan'), + announcement: stringParam(payload, 'announcement'), + region: stringParam(payload, 'region'), + status: rawStatus === 'closed' ? 'closed' : rawStatus === 'open' ? 'open' : undefined, + }); + }); +} + +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'; + return clans.upgradeClanToNormal(profile, account, rules.clanEconomy, clanId, { + tag: stringParam(payload, 'tag') ?? '', + desc: stringParam(payload, 'desc') ?? '', + announcement: stringParam(payload, 'announcement') ?? '', + }); + }); +} + +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'; + return clans.upgradeMembersLimit(profile, account, rules.clanEconomy, clanId); + }); +} + +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 reqBlk = payload && findBlock(payload, 'membership_req'); + const autoaccept = (payload && boolParam(payload, 'autoaccept')) ?? false; + clans.setMembershipRequirements(clanId, account, reqBlk, autoaccept); + return { kind: 'done' }; + }); +} + +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 cancel = (context.payload && boolParam(context.payload, 'cancelRequest')) ?? false; + const comment = paramOrHeader(context, 'comments'); + return clans.requestOrCancelMembership(profile, account, { clanId, clanName, clanTag, cancel, comment }); + }); +} + +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 { + return clanProfileRuleAction(profiles, accounts, clans, (context, profile, account) => + clans.disbandClan(profile, account, strOrIntId(context, 'requestedClanId') ?? strOrIntId(context, '_id'))); +} + +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/online-init-actions.ts b/packages/local-service/src/char/actions/online-init-actions.ts index 7a9fa19..a83988c 100644 --- a/packages/local-service/src/char/actions/online-init-actions.ts +++ b/packages/local-service/src/char/actions/online-init-actions.ts @@ -4,6 +4,7 @@ */ import { emptyBlock } from '@wto/blk'; import type { AccountStore } from '../../accounts/account-store.ts'; +import type { ClanStore } from '../../clans/clan-store.ts'; import { clientProfile } from '../../profile/client-profile.ts'; import type { PlayerProfiles } from '../../profile/player-profiles.ts'; import type { CharActionHandler } from '../char-action.ts'; @@ -31,19 +32,19 @@ export function initialMeta(): CharActionHandler { * performAction (0x295ef0) reads it into the client's profile with the profile serializer * (0x917740) when it is not empty. */ -export function entitlementsFull(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler { - return profileAnswer(profiles, accounts); +export function entitlementsFull(profiles: PlayerProfiles, accounts: AccountStore, clans?: ClanStore): CharActionHandler { + return profileAnswer(profiles, accounts, clans); } /** cln_legacy_get_userdata: the whole profile (ClientEconomicState::loadOnline, aces.exe 0x2a23b0). */ -export function legacyUserData(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler { - return profileAnswer(profiles, accounts); +export function legacyUserData(profiles: PlayerProfiles, accounts: AccountStore, clans?: ClanStore): CharActionHandler { + return profileAnswer(profiles, accounts, clans); } -function profileAnswer(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler { +function profileAnswer(profiles: PlayerProfiles, accounts: AccountStore, clans?: ClanStore): CharActionHandler { return (context) => withAccount(context, accounts, (account) => ({ kind: 'data', - blk: clientProfile(profiles.profileOf(account.userId), account), + blk: clientProfile(profiles.profileOf(account.userId), account, clans), })); } 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 5b29b50..26911d6 100644 --- a/packages/local-service/src/char/actions/player-card-actions.ts +++ b/packages/local-service/src/char/actions/player-card-actions.ts @@ -12,10 +12,12 @@ */ import type { BlkBlock, BlkParam } from '@wto/blk'; import type { AccountStore } from '../../accounts/account-store.ts'; +import type { ClanStore } from '../../clans/clan-store.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 { CharActionHandler } from '../char-action.ts'; import { stringParam } from './payload-params.ts'; @@ -46,18 +48,51 @@ export function showcasesAction(profiles: PlayerProfiles, accounts: AccountStore ({ kind: 'data', blk: showcasesAnswer(profiles.profileOf(account.userId), rules.techTree) })); } -export function usersTerseInfoAction(profiles: PlayerProfiles, accounts: AccountStore, rules: ResearchRules): CharActionHandler { +export function usersTerseInfoAction(profiles: PlayerProfiles, accounts: AccountStore, rules: ResearchRules, clans?: ClanStore): CharActionHandler { return (context) => withAccount(context, accounts, () => { const list = (context.payload ? stringParam(context.payload, 'usersList') : undefined) ?? context.headerParam('usersList'); 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) return { name: uid, params: [{ name: 'failed', value: { type: 'bool', value: true } }], blocks: [] }; + 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)], - ['background', looks.background ?? ''], ['frame', looks.frame ?? ''], + ['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]); diff --git a/packages/local-service/src/clans/clan-blk.ts b/packages/local-service/src/clans/clan-blk.ts new file mode 100644 index 0000000..b4234b6 --- /dev/null +++ b/packages/local-service/src/clans/clan-blk.ts @@ -0,0 +1,315 @@ +/** + * DataBlock serializers for squadron (clan) char actions: + * - `cln_clan_get` full clan info (`clanInfoTable.nut` + `0xeb9f60`) + * - `cln_clan_get_leaderboard` / + * `cln_clan_find_by_prefix` leaderboard / search rows (`clansModalHandler.nut`) + * - `cln_clans_list_get_short_info` short info blocks (`clanInfo.nut`) + * - `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'; + +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; + +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); +} + +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: [ + str('_id', clan.id), + str('name', clan.name), + str('tag', clan.tag), + str('lastPaidTag', clan.lastPaidTag), + str('slogan', clan.slogan), + str('desc', clan.desc), + str('region', clan.region), + str('announcement', clan.announcement), + int('cdate', clan.cdateSec), + str('status', clan.status), + int('mlimit', clan.mlimit), + str('changed_by_nick', clan.changedByNick), + str('changed_by_uid', clan.changedByUid), + int('changed_time', clan.changedTimeSec), + int('mspent', clan.mspent), + int('region_last_updated', clan.regionLastUpdatedSec), + str('type', clan.type), + bool('autoaccept', clan.autoaccept), + int('maxActivityPerPeriod', MAX_ACTIVITY_PER_PERIOD), + int('maxClanActivity', MAX_CLAN_ACTIVITY), + int('rewardPeriodDays', REWARD_PERIOD_DAYS), + bool('expRewardEnabled', true), + int('historyDepth', HISTORY_DEPTH_DAYS), + int('nextRewardDayId', todayDay + REWARD_PERIOD_DAYS), + ], + blocks: [ + astat, + membershipReq, + ...memberBlocks, + memberRatingsBlock, + activityBlock, + ...candidateBlocks, + ...blacklistBlocks, + ...bestRewardBlocks, + ], + }; +} + +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: [ + str('_id', clan.id), + str('name', clan.name), + str('tag', clan.tag), + str('slogan', clan.slogan), + str('desc', clan.desc), + str('region', clan.region), + str('type', clan.type), + str('status', clan.status), + bool('autoaccept', clan.autoaccept), + int('mlimit', clan.mlimit), + int('members_cnt', clan.members.length), + 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), + ], + blocks: [astat, membershipReq], + }; +} + +export function toClanShortInfoBlk(clan: ClanRecord): BlkBlock { + return { + name: clan.id, + params: [ + str('_id', clan.id), + str('name', clan.name), + str('tag', clan.tag), + str('type', clan.type), + str('slogan', clan.slogan), + str('region', clan.region), + str('status', clan.status), + int('mlimit', clan.mlimit), + int('members_cnt', clan.members.length), + ], + blocks: [buildAstatBlock(clan)], + }; +} + +export function toClanLogBlk( + clan: ClanRecord, + count: number, + eventsFilter?: string, + lastMark?: string, +): BlkBlock { + const allowedEvents = eventsFilter + ? new Set(eventsFilter.split(';').map((s) => s.trim()).filter(Boolean)) + : undefined; + const maxId = lastMark && /^\d+$/.test(lastMark) ? Number(lastMark) : Number.MAX_SAFE_INTEGER; + + const sorted = [...clan.logs] + .filter((entry) => entry.id < maxId && (!allowedEvents || allowedEvents.has(entry.ev))) + .sort((a, b) => b.id - a.id); + + 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, + blocks: page.map(logEntryToBlk), + }; +} + +function logEntryToBlk(entry: ClanLogEntry): BlkBlock { + const params: BlkParam[] = [ + str('ev', entry.ev), + int('time', entry.timeSec), + 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)); + return { name: 'log', params, blocks: [] }; +} + +function buildAstatBlock(clan: ClanRecord): BlkBlock { + const periodAct = totalPeriodActivityOf(clan); + return { + name: 'astat', + 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), + ], + blocks: [], + }; +} + +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: [ + int('cur', member.curActivity), + int('total', member.totalActivity), + int('activity', member.curActivity), + int('exp', member.earnedSquadronExp), + ], + blocks: [ + { name: 'history', params: historyParams, blocks: [] }, + { name: 'expActivity', params: [], blocks: expActivityBlocks }, + ], + }; +} + +function str(name: string, value: string): BlkParam { + return { name, value: { type: 'string', value } }; +} + +function int(name: string, value: number): BlkParam { + return { name, value: { type: 'int', value: Math.trunc(value) } }; +} + +function bool(name: string, value: boolean): BlkParam { + return { name, value: { type: 'bool', value } }; +} diff --git a/packages/local-service/src/clans/clan-seeds.ts b/packages/local-service/src/clans/clan-seeds.ts new file mode 100644 index 0000000..9479a8d --- /dev/null +++ b/packages/local-service/src/clans/clan-seeds.ts @@ -0,0 +1,246 @@ +/** + * Default offline squadron directory seeded on first creation of `/clans.json` + * (implementation notes section I). Includes open auto-accept squadrons for instant offline + * joining, a manual-review squadron for testing candidate requests, a battalion squadron, + * and rich NPC member profiles so player cards work for every member. + */ +import { ClanRole, type ClanActivityPeriodEntry, type ClanMemberRecord, type ClanRecord } from './clan-types.ts'; + +export function createDefaultClans(nowSec = Math.floor(Date.now() / 1000)): ClanRecord[] { + const todayDay = Math.floor(nowSec / 86400); + const createdBase = nowSec - 180 * 86400; + + return [ + buildSeededClan({ + id: '500001', + tag: '[WTOF]', + name: 'War Thunder Offline Guard', + type: 'normal', + slogan: '离线天空与钢铁防线 · 自由研发全部联队载具', + desc: 'War Thunder Offline 官方预置主力联队。开启自动审批,加入即可获得完整联队活跃度与联队研发点支持。', + announcement: '欢迎加入 [WTOF]!可在联队页面右上角点击「联队载具」或「活跃度」查看研发进度。', + region: 'CN / Global', + autoaccept: true, + mlimit: 128, + cdateSec: createdBase, + todayDay, + eloArc: 1840, + eloHist: 2150, + eloSim: 1620, + npcs: [ + { uid: '900001001', nick: 'Lin_Wei', role: ClanRole.LEADER, title: 'title_marshall', icon: 'cardicon_28', unit: 'cn_ztz_99a', activity: 360 }, + { 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: '900001006', nick: 'Northern_Fox', role: ClanRole.REGULAR, title: 'title_sniper', icon: 'cardicon_11', unit: 'sw_strv_122b_plus', activity: 310 }, + ], + }), + buildSeededClan({ + id: '500002', + tag: '=PLAF=', + name: 'Red Falcon Aviation Wing', + type: 'normal', + slogan: '鹰击长空 · 现代喷气空战与陆空协同联队', + desc: '专注于高阶喷气机与现代主战坦克联合作战的离线联队,支持自动入队与高活跃度加成。', + announcement: '本期联队研发推荐:F-16A OCU、苏-33、豹 2PL、M1A1 AIM。', + region: 'Asia', + autoaccept: true, + mlimit: 128, + cdateSec: createdBase + 86400 * 12, + todayDay, + eloArc: 1690, + eloHist: 2040, + eloSim: 1780, + npcs: [ + { uid: '900002001', nick: 'SkyDragon_J20', role: ClanRole.LEADER, title: 'title_ace', icon: 'cardicon_25', unit: 'j_11a', activity: 360 }, + { uid: '900002002', nick: 'Thunderbolt_CN', role: ClanRole.DEPUTY, title: 'title_pilot', icon: 'cardicon_09', unit: 'jh_7a', activity: 360 }, + { uid: '900002003', nick: 'SteelWall_99', role: ClanRole.OFFICER, title: 'title_unstoppable', icon: 'cardicon_16', unit: 'cn_vt_4a1', activity: 350 }, + { uid: '900002004', nick: 'NightHawk_04', role: ClanRole.REGULAR, title: 'title_eagle', icon: 'cardicon_05', unit: 'f_15j_kai', activity: 300 }, + ], + }), + buildSeededClan({ + id: '500003', + tag: '-1STG-', + name: '1st Armored Guards Division', + type: 'normal', + slogan: 'Steel & Fire — Heavy Armor Historical Squadron', + desc: 'Classic and modern armored warfare squadron. Open auto-accept recruitment for all tank commanders.', + announcement: 'Squadron vehicles ready for research at full 20,000 RP per period.', + region: 'EU / Global', + autoaccept: true, + mlimit: 128, + cdateSec: createdBase + 86400 * 24, + todayDay, + eloArc: 1920, + eloHist: 1980, + eloSim: 1510, + npcs: [ + { uid: '900003001', nick: 'Kommissar_KVs', role: ClanRole.LEADER, title: 'title_hero', icon: 'cardicon_22', unit: 'ussr_t_90m', activity: 360 }, + { uid: '900003002', nick: 'PanzerMeyer_IV', role: ClanRole.OFFICER, title: 'title_tankman', icon: 'cardicon_12', unit: 'germ_pzkpfw_VI_ausf_h1_tiger', activity: 340 }, + { uid: '900003003', nick: 'DesertRat_UK', role: ClanRole.REGULAR, title: 'title_conqueror', icon: 'cardicon_18', unit: 'uk_challenger_2_black_night', activity: 290 }, + ], + }), + buildSeededClan({ + id: '500004', + tag: '^82AB^', + name: '82nd Combined Task Force', + type: 'normal', + slogan: 'All The Way — Air, Ground & Naval Task Force', + desc: '需要审批模式的示例联队(用于测试发送与撤回入队申请流程)。若想立即加入联队,请选择 [WTOF]、=PLAF= 或 -1STG-。', + announcement: 'Manual application review enabled for testing request/cancel workflow.', + region: 'NA', + autoaccept: false, + mlimit: 128, + cdateSec: createdBase + 86400 * 35, + todayDay, + eloArc: 1550, + eloHist: 1760, + eloSim: 1490, + npcs: [ + { uid: '900004001', nick: 'Major_Winters', role: ClanRole.LEADER, title: 'title_brother_in_arms', icon: 'cardicon_03', unit: 'us_m1a2_sep2_abrams', activity: 360 }, + { uid: '900004002', nick: 'Mustang_Lead', role: ClanRole.OFFICER, title: 'title_ace', icon: 'cardicon_08', unit: 'p-51d-30_usaaf_korea', activity: 315 }, + ], + }), + buildSeededClan({ + id: '500005', + tag: '**RCON**', + name: 'Reconnaissance Battalion Alpha', + type: 'battalion', + slogan: '轻量级战术分队 · 侦察与快速反应', + desc: '战斗群(Battalion)类型预置联队,开启自动加入,支持体验战斗群架构与联队扩编。', + announcement: '轻装侦察分队常驻开放。', + region: 'Global', + autoaccept: true, + mlimit: 10, + cdateSec: createdBase + 86400 * 48, + todayDay, + eloArc: 1410, + eloHist: 1610, + eloSim: 1320, + npcs: [ + { uid: '900005001', nick: 'Ghost_Scout', role: ClanRole.LEADER, title: 'title_scout', icon: 'cardicon_15', unit: 'us_hstvl', activity: 360 }, + { uid: '900005002', nick: 'Lynx_Spotter', role: ClanRole.REGULAR, title: 'title_sniper', icon: 'cardicon_20', unit: 'it_centauro_rgo_120', activity: 280 }, + ], + }), + ]; +} + +interface SeedSpec { + readonly id: string; + readonly tag: string; + readonly name: string; + readonly type: 'normal' | 'battalion'; + readonly slogan: string; + readonly desc: string; + readonly announcement: string; + readonly region: string; + readonly autoaccept: boolean; + readonly mlimit: number; + readonly cdateSec: number; + readonly todayDay: number; + readonly eloArc: number; + readonly eloHist: number; + readonly eloSim: number; + readonly npcs: ReadonlyArray<{ + readonly uid: string; + readonly nick: string; + readonly role: number; + readonly title: string; + readonly icon: string; + readonly unit: string; + readonly activity: number; + }>; +} + +function buildSeededClan(spec: SeedSpec): ClanRecord { + const members: ClanMemberRecord[] = spec.npcs.map((npc, idx) => { + const periods = buildDefaultPeriods(spec.todayDay, npc.activity); + return { + uid: npc.uid, + nick: npc.nick, + role: npc.role, + joinDateSec: spec.cdateSec + idx * 3600, + isNpc: true, + npcTitle: npc.title, + npcPilotIcon: npc.icon, + npcFrame: '', + npcShowcaseUnit: npc.unit, + curActivity: npc.activity, + totalActivity: periods.reduce((sum, p) => sum + p.activity, 0), + earnedSquadronExp: periods.reduce((sum, p) => sum + p.exp, 0), + ratingArc: Math.max(800, spec.eloArc - idx * 45), + ratingHist: Math.max(850, spec.eloHist - idx * 50), + ratingSim: Math.max(700, spec.eloSim - idx * 40), + periods, + }; + }); + + const leader = spec.npcs[0]!; + return { + id: spec.id, + name: spec.name, + tag: spec.tag, + lastPaidTag: spec.tag, + type: spec.type, + slogan: spec.slogan, + desc: spec.desc, + announcement: spec.announcement, + region: spec.region, + status: 'open', + autoaccept: spec.autoaccept, + mlimit: spec.mlimit, + mspent: 0, + cdateSec: spec.cdateSec, + changedByUid: leader.uid, + changedByNick: leader.nick, + changedTimeSec: spec.cdateSec, + regionLastUpdatedSec: 0, + stats: { + dr_era5_arc: spec.eloArc, + dr_era5_hist: spec.eloHist, + dr_era5_sim: spec.eloSim, + akills_arc: 4280, + akills_hist: 6150, + akills_sim: 1420, + gkills_arc: 7890, + gkills_hist: 11240, + gkills_sim: 2680, + deaths_arc: 5120, + deaths_hist: 6890, + deaths_sim: 1950, + ftime_arc: 18400, + ftime_hist: 32600, + ftime_sim: 8900, + }, + members, + candidates: [], + blacklist: [], + logs: [ + { + id: 1, + ev: 'create', + timeSec: spec.cdateSec, + uId: leader.uid, + uN: leader.nick, + name: spec.name, + type: spec.type, + tag: spec.tag, + desc: spec.desc, + slogan: spec.slogan, + region: spec.region, + announcement: spec.announcement, + }, + ], + bestRewards: [], + }; +} + +export function buildDefaultPeriods(todayDay: number, periodActivity = 360): ClanActivityPeriodEntry[] { + const expPerPeriod = Math.round((periodActivity / 360) * 20000); + return [ + { day: todayDay, activity: periodActivity, exp: expPerPeriod }, + { day: todayDay - 3, activity: periodActivity, exp: expPerPeriod }, + { day: todayDay - 6, activity: Math.max(180, periodActivity - 30), exp: Math.round((Math.max(180, periodActivity - 30) / 360) * 20000) }, + ]; +} diff --git a/packages/local-service/src/clans/clan-store.ts b/packages/local-service/src/clans/clan-store.ts new file mode 100644 index 0000000..ac65430 --- /dev/null +++ b/packages/local-service/src/clans/clan-store.ts @@ -0,0 +1,719 @@ +/** + * Persistent local squadron (clan) directory & state store (`/clans.json`), + * backing search, leaderboards, creation, membership, roles, activity, and logs + * (implementation notes; implementation notes section 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'; + +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 class ClanStore { + readonly #filePath: string; + #state: StoredClansFile; + + constructor(dataFolder: string) { + this.#filePath = join(dataFolder, 'clans.json'); + this.#state = this.#loadOrSeed(); + } + + #loadOrSeed(): StoredClansFile { + 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 seeded: StoredClansFile = { + nextClanId: 600001, + clans: createDefaultClans(), + }; + this.#save(seeded); + return seeded; + } + + #save(state: StoredClansFile = this.#state): void { + writeFileAtomic(this.#filePath, JSON.stringify(state, null, 2)); + } + + 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; + } + + clanOfUser(userId: string): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined { + for (const clan of this.#state.clans) { + const member = clan.members.find((m) => m.uid === userId); + if (member) return { clan, member }; + } + return undefined; + } + + pendingRequestOfUser(userId: string): ClanRecord | undefined { + return this.#state.clans.find((c) => c.candidates.some((cand) => cand.uid === userId)); + } + + earnedSquadronExpOf(userId: string): number { + return this.clanOfUser(userId)?.member.earnedSquadronExp ?? 0; + } + + npcMemberByUid(uid: string): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined { + for (const clan of this.#state.clans) { + const member = clan.members.find((m) => m.uid === uid && m.isNpc); + if (member) return { clan, member }; + } + 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) { + const { clan, member } = found; + if (member.nick !== account.nick) { + const idx = clan.members.findIndex((m) => m.uid === account.userId); + if (idx >= 0) { + clan.members[idx] = { ...member, nick: account.nick }; + this.#save(); + } + } + setClanMembership(profile, { + clanId: clan.id, + clanTag: clan.tag, + clanName: clan.name, + clanType: clan.type, + role: member.role, + }); + syncStoredClanEarnedExp(profile, member.earnedSquadronExp); + return; + } + + const pending = this.pendingRequestOfUser(account.userId); + if (pending) { + setPendingClanRequest(profile, { clanId: pending.id, clanTag: pending.tag, clanName: pending.name }); + } else if (clanMembershipOf(profile).clanId !== '-1' || clanMembershipOf(profile).requestedClanId !== '-1') { + clearClanMembership(profile); + } + } + + 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); + } + + 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'); + } + + 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; + } + + 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); + } + } + + 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; + } + + upgradeClanToNormal( + profile: BlkBlock, + account: Account, + economy: ClanEconomy, + clanId: string, + input: { readonly tag: string; readonly desc: string; readonly announcement: 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'); + + 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; + + 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; + } + + 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; + } + + 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; + clan.autoaccept = autoaccept; + if (reqBlk) clan.membershipReqBlk = structuredClone(reqBlk); + else delete clan.membershipReqBlk; + this.#save(); + } + + 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); + 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; + } + + 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, + }); + } + this.#save(); + clearClanMembership(profile); + return ACCEPTED; + } + + 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'); + 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); + 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, + }); + 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, + }); + 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), + }); + 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, + }); + } + this.#save(); + return true; + } + + setBestRewards(clanId: string, rewards: readonly ClanBestReward[]): void { + const clan = this.byId(clanId); + if (!clan) return; + 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 }); + } +} + +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; + } +} diff --git a/packages/local-service/src/clans/clan-types.ts b/packages/local-service/src/clans/clan-types.ts new file mode 100644 index 0000000..eeb1d8a --- /dev/null +++ b/packages/local-service/src/clans/clan-types.ts @@ -0,0 +1,147 @@ +/** + * Types and binary enum constants for the local squadron (clan) system + *. + */ +import type { BlkBlock } from '@wto/blk'; +import type { ClanKind } from '../profile/profile-clan.ts'; + +/** Exact `ECMR_*` role codes registered at aces.exe 0x2986a0..0x298802 (table 0x7ba87e8). */ +export const ClanRole = { + LEADER: 1, + OFFICER: 2, + REGULAR: 3, + CLANADMIN: 4, + DEPUTY: 5, + SERGEANT: 6, +} as const; + +export type ClanRoleCode = (typeof ClanRole)[keyof typeof ClanRole]; + +export function roleNameOf(role: number): string { + switch (role) { + case ClanRole.LEADER: + return 'LEADER'; + case ClanRole.DEPUTY: + return 'DEPUTY'; + case ClanRole.OFFICER: + return 'OFFICER'; + case ClanRole.SERGEANT: + return 'SERGEANT'; + default: + return 'REGULAR'; + } +} + +export interface ClanStats { + readonly dr_era5_arc: number; + readonly dr_era5_hist: number; + readonly dr_era5_sim: number; + readonly akills_arc: number; + readonly akills_hist: number; + readonly akills_sim: number; + readonly gkills_arc: number; + readonly gkills_hist: number; + readonly gkills_sim: number; + readonly deaths_arc: number; + readonly deaths_hist: number; + readonly deaths_sim: number; + readonly ftime_arc: number; + readonly ftime_hist: number; + readonly ftime_sim: number; +} + +export interface ClanActivityPeriodEntry { + readonly day: number; + readonly activity: number; + readonly exp: number; +} + +export interface ClanMemberRecord { + readonly uid: string; + readonly nick: string; + readonly role: number; + readonly joinDateSec: number; + readonly isNpc?: boolean; + readonly npcTitle?: string; + readonly npcPilotIcon?: string; + readonly npcFrame?: string; + readonly npcShowcaseUnit?: string; + readonly curActivity: number; + readonly totalActivity: number; + readonly earnedSquadronExp: number; + readonly ratingArc: number; + readonly ratingHist: number; + readonly ratingSim: number; + readonly periods: readonly ClanActivityPeriodEntry[]; +} + +export interface ClanCandidateRecord { + readonly uid: string; + readonly nick: string; + readonly comment: string; + readonly dateSec: number; +} + +export interface ClanBlacklistEntry { + readonly uid: string; + readonly nick: string; + readonly initiatorUid: string; + readonly initiatorNick: string; + readonly comments: string; + readonly dateSec: number; +} + +export interface ClanLogEntry { + readonly id: number; + readonly ev: 'create' | 'info' | 'upgrade' | 'add' | 'rem' | 'role' | 'upgrade_members' | 'reject_candidate' | 'add_to_blacklist' | 'remove_from_blacklist'; + readonly timeSec: number; + readonly uId: string; + readonly uN: string; + readonly uid?: string; + readonly nick?: string; + readonly role?: string; + readonly old?: string; + readonly new?: string; + readonly name?: string; + readonly type?: string; + readonly tag?: string; + readonly desc?: string; + readonly slogan?: string; + readonly region?: string; + readonly announcement?: string; + readonly status?: string; + readonly comments?: string; +} + +export interface ClanBestReward { + readonly seasonName: string; + readonly title: string; +} + +export interface ClanRecord { + id: string; + name: string; + tag: string; + lastPaidTag: string; + type: ClanKind; + slogan: string; + desc: string; + announcement: string; + region: string; + status: 'open' | 'closed'; + autoaccept: boolean; + mlimit: number; + mspent: number; + cdateSec: number; + changedByUid: string; + changedByNick: string; + changedTimeSec: number; + regionLastUpdatedSec: number; + stats: ClanStats; + members: ClanMemberRecord[]; + candidates: ClanCandidateRecord[]; + blacklist: ClanBlacklistEntry[]; + logs: ClanLogEntry[]; + bestRewards: ClanBestReward[]; + membershipReqBlk?: BlkBlock; +} diff --git a/packages/local-service/src/game-data/datasets/clan-economy.ts b/packages/local-service/src/game-data/datasets/clan-economy.ts new file mode 100644 index 0000000..769a1d1 --- /dev/null +++ b/packages/local-service/src/game-data/datasets/clan-economy.ts @@ -0,0 +1,43 @@ +/** + * Dataset: squadron creation, edit, member-limit upgrade, and battalion-to-normal upgrade + * prices from char.vromfs.bin config/warpoints.blk (implementation notes; scripts/clans/clanType.nut). + */ +import { numberField } from './blk-fields.ts'; +import type { Dataset } from './dataset.ts'; + +const WARPOINTS = 'config/warpoints.blk'; + +export interface ClanEconomy { + readonly normalCreateGold: number; + readonly normalCreateSilver: number; + readonly battalionCreateGold: number; + readonly battalionCreateSilver: number; + readonly battalionPrimaryEditGold: number; + readonly battalionPrimaryEditSilver: number; + readonly battalionMembersUpgradeGold: number; + readonly battalionMembersUpgradeStep: number; + readonly battalionMembersUpgradeLimit: number; + readonly upgradeBattalionToNormalGold: number; + readonly upgradeBattalionToNormalSilver: number; +} + +export const clanEconomy: Dataset = { + id: 'clan-economy', + version: 1, + extract: (source) => { + const wp = source.readBlk('char.vromfs.bin', WARPOINTS); + return { + normalCreateGold: numberField(wp, 'clanCreateGoldCost') ?? 2500, + normalCreateSilver: numberField(wp, 'clanCreateWPCost') ?? 0, + battalionCreateGold: numberField(wp, 'battalionCreateGoldCost') ?? 0, + battalionCreateSilver: numberField(wp, 'battalionCreateWPCost') ?? 1_000_000, + battalionPrimaryEditGold: numberField(wp, 'battalionCostGoldPrimaryInfo') ?? 0, + battalionPrimaryEditSilver: numberField(wp, 'battalionCostWPPrimaryInfo') ?? 1_000_000, + battalionMembersUpgradeGold: numberField(wp, 'battalionMembersUpgradeCost') ?? 225, + battalionMembersUpgradeStep: numberField(wp, 'battalionMembersUpgradeStep') ?? 10, + battalionMembersUpgradeLimit: numberField(wp, 'battalionMembersUpgradeLimit') ?? 110, + upgradeBattalionToNormalGold: numberField(wp, 'clanUpgradeCostGoldBattalionToNormal') ?? 2500, + upgradeBattalionToNormalSilver: numberField(wp, 'clanUpgradeCostWPBattalionToNormal') ?? 0, + }; + }, +}; diff --git a/packages/local-service/src/game-data/datasets/vehicle-catalogue.ts b/packages/local-service/src/game-data/datasets/vehicle-catalogue.ts index 2f459bd..38ccc0c 100644 --- a/packages/local-service/src/game-data/datasets/vehicle-catalogue.ts +++ b/packages/local-service/src/game-data/datasets/vehicle-catalogue.ts @@ -54,11 +54,15 @@ export interface CatalogueVehicle { readonly onlyShownWhenOwned: boolean; /** shop.blk marketplaceItemdefId (vehicles traded as coupons on the market, implementation notes). */ readonly marketplaceItemdefId?: number; + /** wpcost.blk openCostGold (early GE buyout price for squadron vehicles, implementation notes). */ + readonly openCostGold: number; + /** wpcost.blk minOpenCostGold (minimum GE buyout floor for squadron vehicles, implementation notes). */ + readonly minOpenCostGold: number; } export const vehicleCatalogue: Dataset = { id: 'vehicle-catalogue', - version: 3, + version: 4, extract: (source) => { const shopEntries = new Map(); for (const country of source.readBlk('char.vromfs.bin', SHOP).blocks) { @@ -91,6 +95,8 @@ function catalogueVehicle(vehicle: BlkBlock, shopEntry: BlkBlock | undefined): C parts: shopEntry ? shopEntry.params.flatMap((param) => (param.name === 'slaveUnit' && param.value.type === 'string' && param.value.value ? [param.value.value] : [])) : [], onlyShownWhenOwned: boolField(shopEntry, 'showOnlyWhenBought') ?? false, ...(marketplaceItemdefId !== undefined ? { marketplaceItemdefId } : {}), + openCostGold: numberField(vehicle, 'openCostGold') ?? 0, + minOpenCostGold: numberField(vehicle, 'minOpenCostGold') ?? 0, }; } diff --git a/packages/local-service/src/local-service.ts b/packages/local-service/src/local-service.ts index cfb2274..43cbfa3 100644 --- a/packages/local-service/src/local-service.ts +++ b/packages/local-service/src/local-service.ts @@ -6,6 +6,7 @@ import type { Server } from 'node:net'; import { AccountStore } from './accounts/account-store.ts'; import { actionTable } from './char/actions/action-table.ts'; import { CharService } from './char/char-service.ts'; +import { ClanStore } from './clans/clan-store.ts'; import { DownloadableContentService } from './downloadable-content/downloadable-content-service.ts'; import { DatasetCache } from './game-data/datasets/dataset-cache.ts'; import { multiplayerMissions } from './game-data/datasets/multiplayer-missions.ts'; @@ -52,6 +53,7 @@ export async function startLocalService(options: LocalServiceOptions): Promise matching?.broadcastNotify('mrpc.generic_notify', { from: 'inventory', func: 'changed' }); @@ -60,7 +62,7 @@ export async function startLocalService(options: LocalServiceOptions): Promise param.name !== name); +} + +const CLAN_RESEARCH_BLOCK = 'clanResearchUnits'; + +export type ClanKind = 'normal' | 'battalion'; + +export interface ProfileClanMembership { + readonly clanId: string; + readonly clanTag: string; + readonly clanName: string; + readonly clanType: ClanKind; + readonly role: number; + readonly requestedClanId: string; +} + +export interface SquadronResearchState { + readonly researchUnitName: string; + readonly spentExp: number; + readonly adminExp: number; + readonly storedLastEarnedExp: number; +} + +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; + + 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, + requestedClanId: clanIdNum <= 0n && reqNum > 0n ? reqNum.toString() : '-1', + }; +} + +export function setClanMembership( + profile: BlkBlock, + clan: { readonly clanId: string; readonly clanTag: string; readonly clanName: string; readonly clanType: ClanKind; readonly role: number }, +): void { + setParam(profile, 'clanId', { type: 'int64', value: BigInt(clan.clanId) }); + setParam(profile, 'clanMemberRole', { type: 'int', value: clan.role }); + setParam(profile, 'clanType', { type: 'string', value: clan.clanType }); + setParam(profile, 'clanTag', { type: 'string', value: clan.clanTag }); + setParam(profile, 'clanName', { type: 'string', value: clan.clanName }); + removeParam(profile, 'storedRequestClanId'); +} + +export function clearClanMembership(profile: BlkBlock): void { + removeParam(profile, 'clanId'); + removeParam(profile, 'clanMemberRole'); + removeParam(profile, 'clanType'); + removeParam(profile, 'clanTag'); + removeParam(profile, 'clanName'); + removeParam(profile, 'storedRequestClanId'); +} + +export function setPendingClanRequest( + profile: BlkBlock, + request: { readonly clanId: string; readonly clanTag: string; readonly clanName: string } | undefined, +): void { + clearClanMembership(profile); + if (!request) return; + setParam(profile, 'storedRequestClanId', { type: 'int64', value: BigInt(request.clanId) }); + setParam(profile, 'clanTag', { type: 'string', value: request.clanTag }); + setParam(profile, 'clanName', { type: 'string', value: request.clanName }); +} + +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 : '', + spentExp: intField(block, 'spentExp'), + adminExp: intField(block, 'adminExp'), + storedLastEarnedExp: intField(block, 'storedLastEarnedExp'), + }; +} + +/** Exact formula of `clan_get_exp` at aces.exe 0x1780ba0..0x1780be5. */ +export function availableSquadronRp(profile: BlkBlock, clanActivityEarnedExp = 0): number { + const state = squadronResearchOf(profile); + const earned = Math.max(clanActivityEarnedExp, state.storedLastEarnedExp); + return Math.max(0, earned + state.adminExp - state.spentExp); +} + +export function setSquadronResearchTarget(profile: BlkBlock, unitName: string): void { + const block = ensureClanResearchBlock(profile); + setParam(block, 'researchUnitName', { type: 'string', value: unitName }); +} + +export function syncStoredClanEarnedExp(profile: BlkBlock, clanEarnedExp: number): void { + if (clanEarnedExp <= 0) return; + const state = squadronResearchOf(profile); + if (clanEarnedExp > state.storedLastEarnedExp) { + const block = ensureClanResearchBlock(profile); + setParam(block, 'storedLastEarnedExp', { type: 'int', value: clanEarnedExp }); + } +} + +export function spendSquadronRp(profile: BlkBlock, amount: number): void { + if (amount <= 0) return; + const state = squadronResearchOf(profile); + const block = ensureClanResearchBlock(profile); + setParam(block, 'spentExp', { type: 'int', value: state.spentExp + amount }); +} + +/** Set the player's available squadron RP directly (for save-cli.ts / save editor). */ +export function setAvailableSquadronRp(profile: BlkBlock, desiredRp: number, clanActivityEarnedExp = 0): void { + const target = Math.max(0, Math.trunc(desiredRp)); + const state = squadronResearchOf(profile); + const block = ensureClanResearchBlock(profile); + const earnedBase = Math.max(clanActivityEarnedExp, state.storedLastEarnedExp); + if (earnedBase + state.adminExp - state.spentExp === target) return; + if (target >= earnedBase) { + setParam(block, 'spentExp', { type: 'int', value: 0 }); + setParam(block, 'adminExp', { type: 'int', value: target - earnedBase }); + } else { + setParam(block, 'adminExp', { type: 'int', value: 0 }); + setParam(block, 'spentExp', { type: 'int', value: earnedBase - target }); + } +} + +function ensureClanResearchBlock(profile: BlkBlock): BlkBlock { + const existing = findBlock(profile, CLAN_RESEARCH_BLOCK); + if (existing) return existing; + const block = ensureBlock(profile, CLAN_RESEARCH_BLOCK); + setParam(block, 'researchUnitName', { type: 'string', value: '' }); + setParam(block, 'spentExp', { type: 'int', value: 0 }); + setParam(block, 'adminExp', { type: 'int', value: 0 }); + 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/research/research-rules.ts b/packages/local-service/src/research/research-rules.ts index 2a42148..7fdafdd 100644 --- a/packages/local-service/src/research/research-rules.ts +++ b/packages/local-service/src/research/research-rules.ts @@ -15,6 +15,7 @@ import { vehicleUnlocks, type UnlockDefinition } from '../game-data/datasets/veh import { EquipmentCatalogue } from '../modifications/equipment-catalogue.ts'; import { unlockPrices } from '../game-data/datasets/unlock-prices.ts'; import { UnlockShop } from '../unlocks/unlock-purchase.ts'; +import { clanEconomy, type ClanEconomy } from '../game-data/datasets/clan-economy.ts'; import { itemCatalogue } from '../game-data/datasets/item-catalogue.ts'; import { externalItemSources } from '../game-data/datasets/external-item-sources.ts'; import { storeBundles } from '../game-data/datasets/store-bundles.ts'; @@ -47,6 +48,8 @@ export interface ResearchRules { readonly inventory: InventoryCatalogue; /** Classic trophies: SL supply chests and GE vehicle prize-pool direct purchases. */ readonly trophies: TrophyCatalogue; + /** Squadron creation, upgrade and member-limit economy from warpoints.blk. */ + readonly clanEconomy: ClanEconomy; } export function loadResearchRules(datasets: DatasetCache): ResearchRules { @@ -67,5 +70,6 @@ export function loadResearchRules(datasets: DatasetCache): ResearchRules { store: new StoreCatalogue(vehicles, datasets.load(storeBundles), localizedUnitNames), inventory: new InventoryCatalogue(vehicles, localizedUnitNames, datasets.load(externalItemSources), classicItemDefs), trophies: new TrophyCatalogue(vehicles, classicItemDefs), + clanEconomy: datasets.load(clanEconomy), }; } diff --git a/packages/local-service/src/research/squadron-research.ts b/packages/local-service/src/research/squadron-research.ts new file mode 100644 index 0000000..f63ab16 --- /dev/null +++ b/packages/local-service/src/research/squadron-research.ts @@ -0,0 +1,116 @@ +/** + * Squadron vehicle (`researchType:t="clanVehicle"`) research and Golden-Eagle early purchase + * rules (implementation notes; aces.exe 0xec0b70..0xec0c6f; scripts/unit/unitActions.nut). + */ +import type { BlkBlock } from '@wto/blk'; +import { canAfford, pay, type Price } from '../profile/profile-currency.ts'; +import { addOwnedVehicle } from '../profile/profile-hangar.ts'; +import { + availableSquadronRp, + setSquadronResearchTarget, + spendSquadronRp, + squadronResearchOf, +} from '../profile/profile-clan.ts'; +import { researchPointsOf, setResearchPoints } from '../profile/profile-vehicle-research.ts'; +import { currentStatus } from './research-state.ts'; +import type { ResearchRules } from './research-rules.ts'; +import { ACCEPTED, refused, type RuleOutcome } from './rule-outcome.ts'; +import type { TreeVehicle } from './tech-tree.ts'; +import { VehicleStatus } from './vehicle-status.ts'; + +/** + * Exact Golden-Eagle early purchase cost calculated by `clan_get_unit_open_cost_gold` + * (aces.exe 0x177dee0 -> 0xec0b70..0xec0c6f). + */ +export function squadronUnitOpenCostGold(profile: BlkBlock, vehicle: TreeVehicle): number { + if (vehicle.researchPoints <= 0 || vehicle.openCostGold <= 0) return 0; + const curExp = Math.min(researchPointsOf(profile, vehicle.name), vehicle.researchPoints); + const remainingExp = vehicle.researchPoints - curExp; + const scaled = Math.floor((remainingExp * vehicle.openCostGold) / vehicle.researchPoints); + return Math.max(vehicle.minOpenCostGold, scaled); +} + +/** `cln_set_research_clan_unit`: select a squadron vehicle for research (and optionally auto-invest RP). */ +export function chooseSquadronResearchTarget( + profile: BlkBlock, + rules: ResearchRules, + unitName: string, + autoFlush: boolean, + clanActivityEarnedExp = 0, +): RuleOutcome { + const vehicle = rules.techTree.vehicle(unitName); + if (!vehicle || vehicle.kind !== 'squadron') return refused('BAD_PARAMS'); + if (currentStatus(profile, rules, unitName) !== VehicleStatus.CAN_RESEARCH) return refused('NOT_AVAILABLE'); + + setSquadronResearchTarget(profile, vehicle.name); + if (autoFlush) { + investAvailableSquadronRp(profile, vehicle, clanActivityEarnedExp); + } + return ACCEPTED; +} + +/** `cln_flush_clan_exp_to_unit`: invest available squadron RP into the currently selected squadron vehicle. */ +export function flushSquadronExpToUnit( + profile: BlkBlock, + rules: ResearchRules, + clanActivityEarnedExp = 0, +): RuleOutcome { + const { researchUnitName } = squadronResearchOf(profile); + if (!researchUnitName) return ACCEPTED; + + const vehicle = rules.techTree.vehicle(researchUnitName); + if (!vehicle || vehicle.kind !== 'squadron') { + setSquadronResearchTarget(profile, ''); + return ACCEPTED; + } + if (currentStatus(profile, rules, vehicle.name) !== VehicleStatus.CAN_RESEARCH) { + setSquadronResearchTarget(profile, ''); + return ACCEPTED; + } + + investAvailableSquadronRp(profile, vehicle, clanActivityEarnedExp); + return ACCEPTED; +} + +/** `cln_buy_not_researched_clans_unit`: buy an unresearched squadron vehicle directly with Golden Eagles. */ +export function buyNotResearchedSquadronUnit( + profile: BlkBlock, + rules: ResearchRules, + unitName: string, + offered: Price, +): RuleOutcome { + const vehicle = rules.techTree.vehicle(unitName); + if (!vehicle || vehicle.kind !== 'squadron') return refused('BAD_PARAMS'); + if (currentStatus(profile, rules, unitName) !== VehicleStatus.CAN_RESEARCH) return refused('NOT_AVAILABLE'); + + const expectedGold = squadronUnitOpenCostGold(profile, vehicle); + if (expectedGold <= 0) return refused('NOT_AVAILABLE'); + if (offered.silverLions !== 0 || offered.goldenEagles !== expectedGold) return refused('PRICE_CHANGED'); + + const price: Price = { silverLions: 0, goldenEagles: expectedGold }; + if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY'); + + pay(profile, price); + addOwnedVehicle(profile, vehicle.name); + for (const part of vehicle.parts) addOwnedVehicle(profile, part); + if (squadronResearchOf(profile).researchUnitName === vehicle.name) { + setSquadronResearchTarget(profile, ''); + } + return ACCEPTED; +} + +function investAvailableSquadronRp(profile: BlkBlock, vehicle: TreeVehicle, clanActivityEarnedExp: number): void { + const available = availableSquadronRp(profile, clanActivityEarnedExp); + if (available <= 0) return; + + const curExp = researchPointsOf(profile, vehicle.name); + const needed = Math.max(0, vehicle.researchPoints - curExp); + const invest = Math.min(available, needed); + if (invest <= 0) return; + + spendSquadronRp(profile, invest); + setResearchPoints(profile, vehicle.name, curExp + invest); + if (curExp + invest >= vehicle.researchPoints) { + setSquadronResearchTarget(profile, ''); + } +} diff --git a/packages/local-service/src/save-cli.ts b/packages/local-service/src/save-cli.ts index a942f7e..9315150 100644 --- a/packages/local-service/src/save-cli.ts +++ b/packages/local-service/src/save-cli.ts @@ -13,10 +13,12 @@ */ import { parseArgs } from 'node:util'; import { AccountStore } from './accounts/account-store.ts'; +import { ClanStore } from './clans/clan-store.ts'; import { DatasetCache } from './game-data/datasets/dataset-cache.ts'; import { GameFiles } from './game-data/game-files.ts'; import type { ItemDefinition } from './game-data/datasets/item-catalogue.ts'; import { grantItem } from './items/item-grants.ts'; +import { availableSquadronRp, clanMembershipOf, setAvailableSquadronRp } from './profile/profile-clan.ts'; import { balanceOf, setGjn, setGoldenEagles, setSilverLions } from './profile/profile-currency.ts'; import { remainingPremiumDays } from './profile/profile-entitlements.ts'; import { externalInventoryItems, grantExternalItem } from './profile/profile-external-inventory.ts'; @@ -26,7 +28,8 @@ import { serverTimeNow } from './profile/server-time.ts'; import { setUpProfiles } from './profiles-setup.ts'; const USAGE = 'usage: save-cli.ts --game --data --player ' - + '[--silver ] [--gold ] [--gjn ] [--free-rp ] [--give-item [:]]... [--give-coupon [:]]...'; + + '[--silver ] [--gold ] [--gjn ] [--free-rp ] [--squadron-rp ] ' + + '[--give-item [:]]... [--give-coupon [:]]...'; function main(): number { const { values } = parseArgs({ @@ -38,6 +41,7 @@ function main(): number { gold: { type: 'string' }, gjn: { type: 'string' }, 'free-rp': { type: 'string' }, + 'squadron-rp': { type: 'string' }, 'give-item': { type: 'string', multiple: true }, 'give-coupon': { type: 'string', multiple: true }, }, @@ -50,8 +54,9 @@ function main(): number { const gold = optionalAmount(values.gold); const gjn = optionalAmount(values.gjn); const freeRp = optionalAmount(values['free-rp']); - if (silver === null || gold === null || gjn === null || freeRp === null) { - console.error('--silver, --gold, --gjn and --free-rp take a whole number of 0 or more'); + const squadronRp = optionalAmount(values['squadron-rp']); + if (silver === null || gold === null || gjn === null || freeRp === null || squadronRp === null) { + console.error('--silver, --gold, --gjn, --free-rp and --squadron-rp take a whole number of 0 or more'); return 2; } const accounts = new AccountStore(values.data); @@ -60,6 +65,7 @@ function main(): number { console.error(`no player "${values.player}" in ${values.data}`); return 1; } + const clans = new ClanStore(values.data); const gameFiles = new GameFiles(values.game); const datasets = new DatasetCache(values.data, gameFiles, () => {}); const { profiles, research } = setUpProfiles(values.data, gameFiles, datasets); @@ -85,22 +91,29 @@ function main(): number { } coupons.push({ itemdefId, quantity }); } - const changes = silver !== undefined || gold !== undefined || gjn !== undefined || freeRp !== undefined || gifts.length > 0 || coupons.length > 0; + const changes = silver !== undefined || gold !== undefined || gjn !== undefined || freeRp !== undefined || squadronRp !== undefined || gifts.length > 0 || coupons.length > 0; const now = serverTimeNow(); + const clanEarned = clans.earnedSquadronExpOf(account.userId); const profile = !changes ? profiles.profileOf(account.userId) : profiles.update(account.userId, (saved) => { + clans.syncProfile(saved, account); if (silver !== undefined) setSilverLions(saved, silver); if (gold !== undefined) setGoldenEagles(saved, gold); if (gjn !== undefined) setGjn(saved, gjn); if (freeRp !== undefined) setFreeResearchPoints(saved, freeRp); + if (squadronRp !== undefined) setAvailableSquadronRp(saved, squadronRp, clanEarned); for (const gift of gifts) grantItem(saved, gift.item, gift.pieces, now); for (const coupon of coupons) grantExternalItem(saved, coupon.itemdefId, coupon.quantity); }); + clans.syncProfile(profile, account); const balance = balanceOf(profile); const premiumDays = remainingPremiumDays(profile, now); const premiumNote = premiumDays > 0 ? `, premium: ${premiumDays}d` : ''; - console.log(`${account.login} (${account.userId}): ${balance.silverLions} silver lions, ${balance.goldenEagles} golden eagles, ${balance.gjn} GJN, ${freeResearchPoints(profile)} free research points${premiumNote}`); + const sqRp = availableSquadronRp(profile, clanEarned); + const clanInfo = clanMembershipOf(profile); + const clanNote = clanInfo.clanId !== '-1' ? `, clan: ${clanInfo.clanTag} ${clanInfo.clanName}` : ''; + console.log(`${account.login} (${account.userId}): ${balance.silverLions} silver lions, ${balance.goldenEagles} golden eagles, ${balance.gjn} GJN, ${freeResearchPoints(profile)} free research points, ${sqRp} squadron RP${premiumNote}${clanNote}`); const items = ownedItems(profile); if (items.length) console.log(`items: ${items.map((item) => `${item.id} x${item.count}`).join(', ')}`); const extItems = externalInventoryItems(profile);