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.
This commit is contained in:
N0VAN0M4LY committed 2026-12-04 19:55:04 +08:00
1 parent b3211b89cd
commit 429c5eec12
11 files changed
+528 -60

No files matched your search

+187 -27
View File
@@ -39,10 +39,12 @@ import {
type MembershipRequestQuery,
} from './clan-membership.ts';
import { findClanInList, queryClanLeaderboard, type LeaderboardQuery } from './clan-queries.ts';
import { createDefaultClans } from './clan-seeds.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 {
@@ -51,18 +53,36 @@ export class ClanStore {
readonly tuning: ClanTuning;
#state: StoredClansState;
constructor(dataFolder: string, tuning: ClanTuning) {
constructor(dataFolder: string, tuning: ClanTuning, nowSec = nowSeconds()) {
this.#filePath = join(dataFolder, 'clans.json');
this.tuning = tuning;
this.#state = this.#loadOrSeed();
this.#state = this.#loadOrSeed(nowSec);
}
#loadOrSeed(): StoredClansState {
#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') return parsed;
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) };
const seeded: StoredClansState = { nextClanId: this.tuning.firstNewClanId, clans: createDefaultClans(this.tuning, nowSec) };
this.#save(seeded);
return seeded;
}
@@ -71,19 +91,7 @@ export class ClanStore {
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 {
#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 };
@@ -91,12 +99,147 @@ export class ClanStore {
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): number {
return this.clanOfUser(userId)?.member.earnedSquadronExp ?? 0;
earnedSquadronExpOf(userId: string, nowSec = nowSeconds()): number {
return this.clanOfUser(userId, nowSec)?.member.earnedSquadronExp ?? 0;
}
npcMemberByUid(uid: string): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined {
@@ -107,8 +250,8 @@ export class ClanStore {
return undefined;
}
syncProfile(profile: BlkBlock, account: Account): void {
const found = this.clanOfUser(account.userId);
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) {
@@ -131,15 +274,31 @@ export class ClanStore {
}
}
queryLeaderboard(query: LeaderboardQuery): ReadonlyArray<{ readonly clan: ClanRecord; readonly pos: number }> {
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);
this.syncProfile(profile, account, nowSec);
}
return outcome;
}
@@ -189,10 +348,11 @@ export class ClanStore {
}
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);
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);
this.syncProfile(profile, account, nowSec);
}
return res.outcome;
}