Files
WT-Offline/packages/local-service/src/clans/clan-store.ts
T
N0VAN0M4LY d609188acc Open store pages in-game and centralize economy tuning
Use the native embedded browser and pass the game language through
auto_local. Share web assets and extract vehicle icons, flags, and
localized names from the installed client.

Load and validate per-domain JSONC tuning and merge local overrides
by field. Use official store USD prices for GJN products, keep GJN
balances in integer cents, and split the native and web store
handlers by protocol. Multi-vehicle packs are still listed as single
vehicles at this point.

Type checking, patch checks, and configuration loading passed.
In-game acceptance is pending.
2026-11-25 11:01:05 +08:00

261 lines
10 KiB
TypeScript

/**
* Persistent local squadron (clan) directory & state store (`<data>/clans.json`),
* delegating queries, lifecycle, and membership rules to `clan-queries.ts`,
* `clan-lifecycle.ts`, and `clan-membership.ts` (implementation notes; implementation notes I).
*/
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import type { BlkBlock } from '@wto/blk';
import type { Account } from '../accounts/account-store.ts';
import type { ClanEconomy } from '../game-data/datasets/clan-economy.ts';
import {
clanMembershipOf,
clearClanMembership,
setClanMembership,
setPendingClanRequest,
syncStoredClanEarnedExp,
} from '../profile/profile-clan.ts';
import type { RuleOutcome } from '../research/rule-outcome.ts';
import { writeFileAtomic } from '../storage/atomic-file.ts';
import {
createClanInState,
disbandClanInState,
editClanInfoInState,
upgradeClanToNormalInState,
upgradeMembersLimitInState,
type ClanInfoChanges,
type CreateClanInput,
type StoredClansState,
} from './clan-lifecycle.ts';
import {
acceptCandidateOnClan,
changeMemberRoleOnClan,
dismissMemberOnClan,
editBlacklistOnClan,
hasClanManageRight,
leaveClanInState,
rejectCandidateOnClan,
requestOrCancelMembershipInState,
type MembershipRequestQuery,
} from './clan-membership.ts';
import { findClanInList, queryClanLeaderboard, type LeaderboardQuery } from './clan-queries.ts';
import { createDefaultClans } from './clan-seeds.ts';
import type { ClanTuning } from './clan-tuning.ts';
import type { ClanBestReward, ClanMemberRecord, ClanRecord } from './clan-types.ts';
export type { LeaderboardQuery };
export class ClanStore {
readonly #filePath: string;
/** tuning/clans.jsonc; the clan actions serialize clan info with it too. */
readonly tuning: ClanTuning;
#state: StoredClansState;
constructor(dataFolder: string, tuning: ClanTuning) {
this.#filePath = join(dataFolder, 'clans.json');
this.tuning = tuning;
this.#state = this.#loadOrSeed();
}
#loadOrSeed(): StoredClansState {
if (existsSync(this.#filePath)) {
const parsed = JSON.parse(readFileSync(this.#filePath, 'utf8')) as StoredClansState;
if (Array.isArray(parsed.clans) && typeof parsed.nextClanId === 'number') return parsed;
}
const seeded: StoredClansState = { nextClanId: this.tuning.firstNewClanId, clans: createDefaultClans(this.tuning) };
this.#save(seeded);
return seeded;
}
#save(state: StoredClansState = this.#state): void {
writeFileAtomic(this.#filePath, JSON.stringify(state, null, 2));
}
#resolveClan(clanId: string | undefined, userId: string): ClanRecord | undefined {
return clanId && clanId !== '-1' ? this.byId(clanId) : this.clanOfUser(userId)?.clan;
}
byId(clanId: string): ClanRecord | undefined {
return this.#state.clans.find((c) => c.id === clanId);
}
findClan(query: { readonly clanId?: string | undefined; readonly clanName?: string | undefined; readonly clanTag?: string | undefined }): ClanRecord | undefined {
return findClanInList(this.#state.clans, query);
}
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;
}
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 }> {
return queryClanLeaderboard(this.#state.clans, query, this.tuning);
}
createClan(profile: BlkBlock, account: Account, economy: ClanEconomy, input: CreateClanInput, nowSec = nowSeconds()): RuleOutcome {
const outcome = createClanInState(this.#state, profile, account, economy, this.tuning, input, nowSec);
if (outcome.ok) {
this.#save();
this.syncProfile(profile, account);
}
return outcome;
}
editClanInfo(profile: BlkBlock, account: Account, economy: ClanEconomy, clanId: string, changes: ClanInfoChanges, nowSec = nowSeconds()): RuleOutcome {
const outcome = editClanInfoInState(this.#state.clans, this.#resolveClan(clanId, account.userId), profile, account, economy, changes, nowSec);
if (outcome.ok) {
this.#save();
this.syncProfile(profile, account);
}
return outcome;
}
upgradeClanToNormal(
profile: BlkBlock,
account: Account,
economy: ClanEconomy,
clanId: string,
input: { readonly tag: string; readonly desc: string; readonly announcement: string },
nowSec = nowSeconds(),
): RuleOutcome {
const outcome = upgradeClanToNormalInState(this.#state.clans, this.#resolveClan(clanId, account.userId), profile, account, economy, this.tuning, input, nowSec);
if (outcome.ok) {
this.#save();
this.syncProfile(profile, account);
}
return outcome;
}
upgradeMembersLimit(profile: BlkBlock, account: Account, economy: ClanEconomy, clanId: string, nowSec = nowSeconds()): RuleOutcome {
const outcome = upgradeMembersLimitInState(this.#resolveClan(clanId, account.userId), profile, account, economy, nowSec);
if (outcome.ok) {
this.#save();
this.syncProfile(profile, account);
}
return outcome;
}
setMembershipRequirements(clanId: string, account: Account, reqBlk: BlkBlock | undefined, autoaccept: boolean): boolean {
const clan = this.#resolveClan(clanId, account.userId);
if (!clan || !hasClanManageRight(clan, account.userId)) return false;
clan.autoaccept = autoaccept;
if (reqBlk) clan.membershipReqBlk = structuredClone(reqBlk);
else delete clan.membershipReqBlk;
this.#save();
return true;
}
requestOrCancelMembership(profile: BlkBlock, account: Account, query: MembershipRequestQuery, nowSec = nowSeconds()): RuleOutcome {
const res = requestOrCancelMembershipInState(this.#state.clans, this.findClan(query), Boolean(this.clanOfUser(account.userId)), account, query, nowSec, this.tuning);
if (res.mutated) {
this.#save();
this.syncProfile(profile, account);
}
return res.outcome;
}
leaveClan(profile: BlkBlock, account: Account, nowSec = nowSeconds()): RuleOutcome {
const res = leaveClanInState(this.#state.clans, this.clanOfUser(account.userId)?.clan, account, nowSec);
if (res.outcome.ok) {
this.#state.clans = res.nextClans;
this.#save();
clearClanMembership(profile);
}
return res.outcome;
}
disbandClan(profile: BlkBlock, account: Account, clanId?: string): RuleOutcome {
const outcome = disbandClanInState(this.#state, this.#resolveClan(clanId, account.userId), account);
if (outcome.ok) {
this.#save();
this.syncProfile(profile, account);
}
return outcome;
}
acceptCandidate(initiator: Account, clanId: string | undefined, targetUid: string, targetNick: string, role: number, nowSec = nowSeconds()): boolean {
if (!acceptCandidateOnClan(this.#state.clans, this.#resolveClan(clanId, initiator.userId), initiator, targetUid, targetNick, role, nowSec, this.tuning)) return false;
this.#save();
return true;
}
rejectCandidate(initiator: Account, clanId: string | undefined, targetUid: string, comments: string, nowSec = nowSeconds()): boolean {
if (!rejectCandidateOnClan(this.#resolveClan(clanId, initiator.userId), initiator, targetUid, comments, nowSec)) return false;
this.#save();
return true;
}
dismissMember(initiator: Account, targetUid: string, comments: string, nowSec = nowSeconds()): boolean {
if (!dismissMemberOnClan(this.clanOfUser(initiator.userId)?.clan, initiator, targetUid, comments, nowSec)) return false;
this.#save();
return true;
}
changeMemberRole(initiator: Account, targetUid: string, newRole: number, nowSec = nowSeconds()): boolean {
if (!changeMemberRoleOnClan(this.clanOfUser(initiator.userId)?.clan, initiator, targetUid, newRole, nowSec)) return false;
this.#save();
return true;
}
editBlacklist(initiator: Account, clanId: string | undefined, targetUid: string, targetNick: string, add: boolean, comments: string, nowSec = nowSeconds()): boolean {
if (!editBlacklistOnClan(this.#resolveClan(clanId, initiator.userId), initiator, targetUid, targetNick, add, comments, nowSec)) return false;
this.#save();
return true;
}
setBestRewards(clanId: string, initiatorUserId: string, rewards: readonly ClanBestReward[]): boolean {
const clan = this.byId(clanId);
if (!clan || !hasClanManageRight(clan, initiatorUserId)) return false;
clan.bestRewards = [...rewards];
this.#save();
return true;
}
}
function nowSeconds(): number {
return Math.floor(Date.now() / 1000);
}