Files
WT-Offline/apps/server/src/clans/clan-store.ts
T
N0VAN0M4LY 429c5eec12 fix(clans): fix squadron timestamps, 20k RP cap, and configurable initial RP
Fix two 1970 squadron timestamps by sending nextRewardDayId as a 64-bit Unix timestamp in seconds and emitting dynamic bi-monthly season fields (clanDuelNextReward, clanSeasonStart, clanSeasonOrdinal, clanSeasonInYear) in clientProfile. Backfill preset normal squadrons to 58-60 deterministic NPC members so the client activity reward cap reaches 20,000, default startingPeriods and startingActivity to 0 in tuning/clans.jsonc, remove the hardcoded 20,000 empty-history fallback, and wire battle RP into squadron activity accumulation and period settlement.
2026-12-04 19:55:04 +08:00

421 lines
16 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`.
*/
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 { backfillPresetClanMembers, createDefaultClans } from './clan-seeds.ts';
import type { ClanTuning } from './clan-tuning.ts';
import type { ClanBestReward, ClanMemberRecord, ClanRecord } from './clan-types.ts';
const SECONDS_PER_DAY = 86400;
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, nowSec = nowSeconds()) {
this.#filePath = join(dataFolder, 'clans.json');
this.tuning = tuning;
this.#state = this.#loadOrSeed(nowSec);
}
#loadOrSeed(nowSec: number): StoredClansState {
const todayDay = Math.floor(nowSec / SECONDS_PER_DAY);
if (existsSync(this.#filePath)) {
const parsed = JSON.parse(readFileSync(this.#filePath, 'utf8')) as StoredClansState;
if (Array.isArray(parsed.clans) && typeof parsed.nextClanId === 'number') {
let mutated = false;
for (let i = 0; i < this.tuning.presetClans.clans.length; i++) {
const spec = this.tuning.presetClans.clans[i]!;
const existing = parsed.clans.find((c) => c.id === spec.id);
if (existing && backfillPresetClanMembers(existing, spec, i, todayDay, this.tuning)) {
mutated = true;
}
}
for (const clan of parsed.clans) {
if (clan.lastRewardDay === undefined) {
clan.lastRewardDay = todayDay;
mutated = true;
}
}
if (mutated) this.#save(parsed);
return parsed;
}
}
const seeded: StoredClansState = { nextClanId: this.tuning.firstNewClanId, clans: createDefaultClans(this.tuning, nowSec) };
this.#save(seeded);
return seeded;
}
#save(state: StoredClansState = this.#state): void {
writeFileAtomic(this.#filePath, JSON.stringify(state, null, 2));
}
#findUserClan(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;
}
#resolveClan(clanId: string | undefined, userId: string): ClanRecord | undefined {
return clanId && clanId !== '-1'
? this.#state.clans.find((c) => c.id === clanId)
: this.#findUserClan(userId)?.clan;
}
/**
* Lazily settles expired activity reward periods for all squadrons using the stock
* client formula (`clanAverageActivityModal.nut:44-54`):
* `myExp = min(min(1, myPercent / clanPercent) * clanActivity, maxClanActivity)`
* Player members' current-period activity resets to 0 for the new period while NPC
* members keep their active roster contribution.
*/
settleExpiredPeriods(nowSec = nowSeconds()): boolean {
const todayDay = Math.floor(nowSec / SECONDS_PER_DAY);
const {
maxPerPeriod,
squadronRpPerFullPeriod: maxClanActivity,
rewardPeriodDays,
historyDepthDays,
} = this.tuning.activity;
let mutated = false;
for (const clan of this.#state.clans) {
if (clan.lastRewardDay === undefined) {
clan.lastRewardDay = todayDay;
mutated = true;
continue;
}
const elapsedDays = todayDay - clan.lastRewardDay;
if (elapsedDays < rewardPeriodDays) continue;
const anchorDay = clan.lastRewardDay;
const periodsPassed = Math.floor(elapsedDays / rewardPeriodDays);
const settlementDay = anchorDay + rewardPeriodDays;
const nextAnchorDay = anchorDay + periodsPassed * rewardPeriodDays;
const clanActivity = clan.members.reduce((sum, m) => sum + Math.max(0, m.curActivity), 0);
const maxActivity = maxPerPeriod * clan.members.length;
const clanPercent = maxActivity > 0 ? clanActivity / maxActivity : 0;
const minKeptDay = settlementDay - historyDepthDays;
clan.members = clan.members.map((member) => {
const myActivity = Math.max(0, member.curActivity);
const myPercent = maxPerPeriod > 0 ? myActivity / maxPerPeriod : 0;
const myExp = (myPercent > 0 && clanPercent > 0)
? Math.min(maxClanActivity, Math.round(Math.min(1, myPercent / clanPercent) * clanActivity))
: 0;
const pastSettled = member.periods.filter((p) => !(p.exp === 0 && p.day >= anchorDay && p.day <= settlementDay));
const settledEntry = (myActivity > 0 || myExp > 0)
? [{ day: settlementDay, activity: myActivity, exp: myExp }]
: [];
const nextPeriods = [...settledEntry, ...pastSettled].filter((p) => p.day >= minKeptDay);
if (member.isNpc) {
return {
...member,
totalActivity: member.totalActivity + myActivity,
earnedSquadronExp: member.earnedSquadronExp + myExp,
periods: nextPeriods,
};
}
return {
...member,
curActivity: 0,
earnedSquadronExp: member.earnedSquadronExp + myExp,
periods: nextPeriods,
};
});
clan.lastRewardDay = nextAnchorDay;
mutated = true;
}
if (mutated) this.#save();
return mutated;
}
/**
* Accumulates current-period squadron activity from battle base vehicle RP
* (`floor(baseVehicleRp / rpPerActivityPoint)`, capped at `maxPerPeriod`).
* Returns the activity points actually added.
*/
recordBattleActivity(userId: string, baseVehicleRp: number, nowSec = nowSeconds()): number {
this.settleExpiredPeriods(nowSec);
if (!Number.isFinite(baseVehicleRp) || baseVehicleRp <= 0) return 0;
const found = this.#findUserClan(userId);
if (!found) return 0;
const { maxPerPeriod, rpPerActivityPoint } = this.tuning.activity;
const rawGain = Math.floor(baseVehicleRp / rpPerActivityPoint);
if (rawGain <= 0) return 0;
const { clan, member } = found;
const remaining = Math.max(0, maxPerPeriod - member.curActivity);
const added = Math.min(rawGain, remaining);
if (added <= 0) return 0;
const todayDay = Math.floor(nowSec / SECONDS_PER_DAY);
const periodStartDay = clan.lastRewardDay ?? todayDay;
const nextCurActivity = member.curActivity + added;
const nextTotalActivity = member.totalActivity + added;
const existingInProgressIdx = member.periods.findIndex((p) => p.exp === 0 && p.day >= periodStartDay);
const nextPeriods = existingInProgressIdx >= 0
? member.periods.map((p, idx) => (idx === existingInProgressIdx ? { day: todayDay, activity: nextCurActivity, exp: 0 } : p))
: [{ day: todayDay, activity: nextCurActivity, exp: 0 }, ...member.periods];
const memberIdx = clan.members.findIndex((m) => m.uid === userId);
if (memberIdx < 0) return 0;
clan.members[memberIdx] = {
...member,
curActivity: nextCurActivity,
totalActivity: nextTotalActivity,
periods: nextPeriods,
};
this.#save();
return added;
}
byId(clanId: string, nowSec = nowSeconds()): ClanRecord | undefined {
this.settleExpiredPeriods(nowSec);
return this.#state.clans.find((c) => c.id === clanId);
}
findClan(
query: { readonly clanId?: string | undefined; readonly clanName?: string | undefined; readonly clanTag?: string | undefined },
nowSec = nowSeconds(),
): ClanRecord | undefined {
this.settleExpiredPeriods(nowSec);
return findClanInList(this.#state.clans, query);
}
clanOfUser(userId: string, nowSec = nowSeconds()): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined {
this.settleExpiredPeriods(nowSec);
return this.#findUserClan(userId);
}
pendingRequestOfUser(userId: string): ClanRecord | undefined {
return this.#state.clans.find((c) => c.candidates.some((cand) => cand.uid === userId));
}
earnedSquadronExpOf(userId: string, nowSec = nowSeconds()): number {
return this.clanOfUser(userId, nowSec)?.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, nowSec = nowSeconds()): void {
const found = this.clanOfUser(account.userId, nowSec);
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, nowSec = nowSeconds()): ReadonlyArray<{ readonly clan: ClanRecord; readonly pos: number }> {
this.settleExpiredPeriods(nowSec);
return queryClanLeaderboard(this.#state.clans, query, this.tuning);
}
createClan(profile: BlkBlock, account: Account, economy: ClanEconomy, input: CreateClanInput, nowSec = nowSeconds()): RuleOutcome {
this.settleExpiredPeriods(nowSec);
const outcome = createClanInState(this.#state, profile, account, economy, this.tuning, input, nowSec);
if (outcome.ok) {
const created = this.#state.clans[0];
if (created) {
created.lastRewardDay = Math.floor(nowSec / SECONDS_PER_DAY);
const founder = created.members[0];
if (founder && founder.uid === account.userId) {
const curActivity = Math.min(this.tuning.activity.maxPerPeriod, this.tuning.activity.startingActivity);
const periodActivitySum = founder.periods.reduce((s, p) => s + p.activity, 0);
created.members[0] = {
...founder,
curActivity,
totalActivity: founder.periods.length > 0 ? periodActivitySum : curActivity,
};
}
}
this.#save();
this.syncProfile(profile, account, nowSec);
}
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 {
this.settleExpiredPeriods(nowSec);
const res = requestOrCancelMembershipInState(this.#state.clans, findClanInList(this.#state.clans, query), Boolean(this.#findUserClan(account.userId)), account, query, nowSec, this.tuning);
if (res.mutated) {
this.#save();
this.syncProfile(profile, account, nowSec);
}
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);
}