feat(engine): finalize unification archives atomically
This commit is contained in:
@@ -34,6 +34,8 @@ import type { DatabaseTurnDaemonLease } from '../lifecycle/databaseTurnDaemonLea
|
||||
import { calculateNationBettingRewards } from '../betting/nationBettingSettlement.js';
|
||||
import type { NationBettingCandidate, PendingNationBettingFinish, PendingNationBettingOpen } from './types.js';
|
||||
import { buildPersistedRankRows } from './rankData.js';
|
||||
import { persistUnificationFinalization } from './unificationPersistence.js';
|
||||
import { persistYearbookSnapshot } from './yearbookPersistence.js';
|
||||
|
||||
export interface DatabaseTurnHooks {
|
||||
hooks: TurnDaemonHooks;
|
||||
@@ -473,6 +475,7 @@ const buildNationUpdate = (
|
||||
chiefGeneralId: nation.chiefGeneralId,
|
||||
gold: nation.gold,
|
||||
rice: nation.rice,
|
||||
tech: typeof nation.meta.tech === 'number' && Number.isFinite(nation.meta.tech) ? Math.trunc(nation.meta.tech) : 0,
|
||||
level: nation.level,
|
||||
typeCode: nation.typeCode,
|
||||
meta: asJson({
|
||||
@@ -546,6 +549,7 @@ export const createDatabaseTurnHooks = async (
|
||||
databaseUrl: string,
|
||||
world: InMemoryTurnWorld,
|
||||
options?: {
|
||||
profileName?: string;
|
||||
reservedTurns?: InMemoryReservedTurnStore;
|
||||
turnDaemonLease?: DatabaseTurnDaemonLease;
|
||||
}
|
||||
@@ -584,6 +588,8 @@ export const createDatabaseTurnHooks = async (
|
||||
inheritancePointAdjustments,
|
||||
pendingNationBettingOpens,
|
||||
pendingNationBettingFinishes,
|
||||
pendingYearbookSnapshots,
|
||||
pendingUnificationFinalizations,
|
||||
} = changes;
|
||||
const reservedTurnChanges = options?.reservedTurns?.peekDirtyState();
|
||||
|
||||
@@ -952,6 +958,17 @@ export const createDatabaseTurnHooks = async (
|
||||
});
|
||||
}
|
||||
}
|
||||
for (const snapshot of pendingYearbookSnapshots) {
|
||||
await persistYearbookSnapshot(prisma, snapshot);
|
||||
}
|
||||
for (const finalization of pendingUnificationFinalizations) {
|
||||
if (options?.profileName && finalization.profileName !== options.profileName) {
|
||||
throw new Error(
|
||||
`Unification profile mismatch: pending=${finalization.profileName}, daemon=${options.profileName}.`
|
||||
);
|
||||
}
|
||||
await persistUnificationFinalization(prisma, finalization, world);
|
||||
}
|
||||
for (const message of messages) {
|
||||
await sendMessage(
|
||||
{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { asRecord, HALL_OF_FAME_TYPES, type HallOfFameType } from '@sammo-ts/common';
|
||||
import { asRecord, HALL_OF_FAME_TYPES, resolveLegacyTextColor, type HallOfFameType } from '@sammo-ts/common';
|
||||
import type { GamePrisma, InputJsonValue } from '@sammo-ts/infra';
|
||||
import { LogCategory, LogScope } from '@sammo-ts/logic';
|
||||
|
||||
@@ -205,13 +205,23 @@ const settleHall = async (
|
||||
name: event.before.name,
|
||||
nationName: nation?.name ?? '재야',
|
||||
bgColor: nation?.color ?? '#000000',
|
||||
fgColor: nation?.color ?? '#000000',
|
||||
fgColor: resolveLegacyTextColor(nation?.color ?? '#000000'),
|
||||
startTime: typeof worldMeta.starttime === 'string' ? worldMeta.starttime : null,
|
||||
unitedTime: new Date().toISOString(),
|
||||
ownerName: event.before.userId ?? null,
|
||||
ownerDisplayName:
|
||||
typeof asRecord(event.before.meta).ownerDisplayName === 'string'
|
||||
? asRecord(event.before.meta).ownerDisplayName
|
||||
: typeof asRecord(event.before.meta).owner_name === 'string'
|
||||
? asRecord(event.before.meta).owner_name
|
||||
: typeof asRecord(event.before.meta).ownerName === 'string'
|
||||
? asRecord(event.before.meta).ownerName
|
||||
: null,
|
||||
picture: event.before.picture ?? null,
|
||||
imgsvr: event.before.imageServer ?? 0,
|
||||
serverID: serverId,
|
||||
serverIdx: historyCount,
|
||||
scenarioName,
|
||||
serverName: typeof worldMeta.serverName === 'string' ? worldMeta.serverName : '',
|
||||
};
|
||||
|
||||
for (const type of HALL_OF_FAME_TYPES) {
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { TurnCheckpoint, TurnProcessor, TurnRunBudget, TurnRunResult } from
|
||||
import { getNextTickTime } from '../lifecycle/getNextTickTime.js';
|
||||
import type { InMemoryTurnWorld } from './inMemoryWorld.js';
|
||||
import type { TurnGeneral } from './types.js';
|
||||
import { asNumber, asRecord } from '@sammo-ts/common';
|
||||
|
||||
export interface InMemoryTurnProcessorOptions {
|
||||
tickMinutes?: number;
|
||||
@@ -24,6 +25,11 @@ const resolveTickMinutes = (world: InMemoryTurnWorld, override?: number): number
|
||||
return Math.max(1, Math.round(tickSeconds / 60));
|
||||
};
|
||||
|
||||
const isWorldUnited = (world: InMemoryTurnWorld): boolean => {
|
||||
const meta = asRecord(world.getState().meta);
|
||||
return asNumber(meta.isunited ?? meta.isUnited, 0) !== 0;
|
||||
};
|
||||
|
||||
export class InMemoryTurnProcessor implements TurnProcessor {
|
||||
// 인메모리 월드로 턴을 실행하고 월/연 갱신까지 처리한다.
|
||||
private readonly world: InMemoryTurnWorld;
|
||||
@@ -91,13 +97,16 @@ export class InMemoryTurnProcessor implements TurnProcessor {
|
||||
|
||||
if (!partial) {
|
||||
let nextTickTime = getNextTickTime(this.world.getState().lastTurnTime, this.tickMinutes);
|
||||
while (nextTickTime.getTime() <= targetTime.getTime()) {
|
||||
while (!isWorldUnited(this.world) && nextTickTime.getTime() <= targetTime.getTime()) {
|
||||
if (processedTurns >= budget.catchUpCap || isBudgetExpired()) {
|
||||
partial = true;
|
||||
break;
|
||||
}
|
||||
await this.world.advanceMonth(nextTickTime);
|
||||
processedTurns += 1;
|
||||
if (isWorldUnited(this.world)) {
|
||||
break;
|
||||
}
|
||||
nextTickTime = getNextTickTime(this.world.getState().lastTurnTime, this.tickMinutes);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,8 @@ import type {
|
||||
PendingNeutralAuction,
|
||||
PendingNationBettingFinish,
|
||||
PendingNationBettingOpen,
|
||||
PendingUnificationFinalization,
|
||||
PendingYearbookSnapshot,
|
||||
TurnDiplomacy,
|
||||
TurnEvent,
|
||||
TurnGeneral,
|
||||
@@ -126,6 +128,8 @@ export interface TurnWorldChanges {
|
||||
inheritancePointAdjustments: Array<{ userId: string; key: string; amount: number }>;
|
||||
pendingNationBettingOpens: PendingNationBettingOpen[];
|
||||
pendingNationBettingFinishes: PendingNationBettingFinish[];
|
||||
pendingYearbookSnapshots: PendingYearbookSnapshot[];
|
||||
pendingUnificationFinalizations: PendingUnificationFinalization[];
|
||||
}
|
||||
|
||||
export interface InMemoryTurnWorldStateSnapshot {
|
||||
@@ -160,6 +164,8 @@ export interface InMemoryTurnWorldStateSnapshot {
|
||||
inheritancePointAdjustments: Array<{ userId: string; key: string; amount: number }>;
|
||||
pendingNationBettingOpens: PendingNationBettingOpen[];
|
||||
pendingNationBettingFinishes: PendingNationBettingFinish[];
|
||||
pendingYearbookSnapshots: PendingYearbookSnapshot[];
|
||||
pendingUnificationFinalizations: PendingUnificationFinalization[];
|
||||
}
|
||||
|
||||
export interface InMemoryTurnWorldInspection {
|
||||
@@ -346,6 +352,8 @@ export class InMemoryTurnWorld {
|
||||
private readonly inheritancePointAdjustments: Array<{ userId: string; key: string; amount: number }> = [];
|
||||
private readonly pendingNationBettingOpens: PendingNationBettingOpen[] = [];
|
||||
private readonly pendingNationBettingFinishes: PendingNationBettingFinish[] = [];
|
||||
private readonly pendingYearbookSnapshots: PendingYearbookSnapshot[] = [];
|
||||
private readonly pendingUnificationFinalizations: PendingUnificationFinalization[] = [];
|
||||
private readonly scenarioConfig: ScenarioConfig;
|
||||
private readonly unitSet?: UnitSetDefinition;
|
||||
private checkpoint?: TurnCheckpoint;
|
||||
@@ -425,6 +433,8 @@ export class InMemoryTurnWorld {
|
||||
inheritancePointAdjustments: this.inheritancePointAdjustments,
|
||||
pendingNationBettingOpens: this.pendingNationBettingOpens,
|
||||
pendingNationBettingFinishes: this.pendingNationBettingFinishes,
|
||||
pendingYearbookSnapshots: this.pendingYearbookSnapshots,
|
||||
pendingUnificationFinalizations: this.pendingUnificationFinalizations,
|
||||
} satisfies InMemoryTurnWorldStateSnapshot);
|
||||
}
|
||||
|
||||
@@ -461,6 +471,8 @@ export class InMemoryTurnWorld {
|
||||
this.replaceArray(this.inheritancePointAdjustments, restored.inheritancePointAdjustments);
|
||||
this.replaceArray(this.pendingNationBettingOpens, restored.pendingNationBettingOpens);
|
||||
this.replaceArray(this.pendingNationBettingFinishes, restored.pendingNationBettingFinishes);
|
||||
this.replaceArray(this.pendingYearbookSnapshots, restored.pendingYearbookSnapshots);
|
||||
this.replaceArray(this.pendingUnificationFinalizations, restored.pendingUnificationFinalizations);
|
||||
}
|
||||
|
||||
inspectState(): InMemoryTurnWorldInspection {
|
||||
@@ -554,6 +566,14 @@ export class InMemoryTurnWorld {
|
||||
});
|
||||
}
|
||||
|
||||
queueYearbookSnapshot(snapshot: PendingYearbookSnapshot): void {
|
||||
this.pendingYearbookSnapshots.push(structuredClone(snapshot));
|
||||
}
|
||||
|
||||
queueUnificationFinalization(finalization: PendingUnificationFinalization): void {
|
||||
this.pendingUnificationFinalizations.push(structuredClone(finalization));
|
||||
}
|
||||
|
||||
getScenarioConfig(): ScenarioConfig {
|
||||
return this.scenarioConfig;
|
||||
}
|
||||
@@ -1192,6 +1212,8 @@ export class InMemoryTurnWorld {
|
||||
winnerNationIds: [...entry.winnerNationIds],
|
||||
turnTime: new Date(entry.turnTime.getTime()),
|
||||
}));
|
||||
const pendingYearbookSnapshots = structuredClone(this.pendingYearbookSnapshots);
|
||||
const pendingUnificationFinalizations = structuredClone(this.pendingUnificationFinalizations);
|
||||
|
||||
return {
|
||||
generals,
|
||||
@@ -1216,6 +1238,8 @@ export class InMemoryTurnWorld {
|
||||
inheritancePointAdjustments,
|
||||
pendingNationBettingOpens,
|
||||
pendingNationBettingFinishes,
|
||||
pendingYearbookSnapshots,
|
||||
pendingUnificationFinalizations,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1246,6 +1270,8 @@ export class InMemoryTurnWorld {
|
||||
this.inheritancePointAdjustments.splice(0, changes.inheritancePointAdjustments.length);
|
||||
this.pendingNationBettingOpens.splice(0, changes.pendingNationBettingOpens.length);
|
||||
this.pendingNationBettingFinishes.splice(0, changes.pendingNationBettingFinishes.length);
|
||||
this.pendingYearbookSnapshots.splice(0, changes.pendingYearbookSnapshots.length);
|
||||
this.pendingUnificationFinalizations.splice(0, changes.pendingUnificationFinalizations.length);
|
||||
}
|
||||
|
||||
consumeDirtyState(): TurnWorldChanges {
|
||||
|
||||
@@ -227,7 +227,6 @@ const createTurnDaemonRuntimeWithLease = async (
|
||||
const unification = options.calendarHandler
|
||||
? null
|
||||
: createUnificationHandler({
|
||||
databaseUrl: options.databaseUrl,
|
||||
profileName: options.profileName ?? options.profile,
|
||||
getWorld: () => worldRef,
|
||||
});
|
||||
@@ -459,7 +458,6 @@ const createTurnDaemonRuntimeWithLease = async (
|
||||
},
|
||||
});
|
||||
const yearbookHandler = createYearbookHandler({
|
||||
databaseUrl: options.databaseUrl,
|
||||
profileName: options.profileName ?? options.profile,
|
||||
getWorld: () => worldRef,
|
||||
});
|
||||
@@ -591,6 +589,7 @@ const createTurnDaemonRuntimeWithLease = async (
|
||||
}
|
||||
if (databaseFlushEnabled) {
|
||||
const dbHooks = await createDatabaseTurnHooks(options.databaseUrl, world, {
|
||||
profileName: options.profileName ?? options.profile,
|
||||
reservedTurns: reservedTurnStoreHandle?.store,
|
||||
turnDaemonLease: turnDaemonLease ?? undefined,
|
||||
});
|
||||
@@ -711,10 +710,6 @@ const createTurnDaemonRuntimeWithLease = async (
|
||||
close = async () => {
|
||||
await baseClose();
|
||||
await neutralAuctionRegistrar.close();
|
||||
if (unification) {
|
||||
await unification.close();
|
||||
}
|
||||
await yearbookHandler.close();
|
||||
if (redisConnector) {
|
||||
await redisConnector.disconnect();
|
||||
}
|
||||
|
||||
@@ -101,6 +101,25 @@ export interface PendingNationBettingFinish {
|
||||
turnTime: Date;
|
||||
}
|
||||
|
||||
export interface PendingYearbookSnapshot {
|
||||
serverId: string;
|
||||
sourceId: number;
|
||||
year: number;
|
||||
month: number;
|
||||
map: unknown;
|
||||
nations: unknown;
|
||||
}
|
||||
|
||||
export interface PendingUnificationFinalization {
|
||||
generationKey: string;
|
||||
serverId: string;
|
||||
profileName: string;
|
||||
winnerNationId: number;
|
||||
year: number;
|
||||
month: number;
|
||||
completedAt: Date;
|
||||
}
|
||||
|
||||
export interface TurnWorldSnapshot extends Omit<
|
||||
WorldSnapshot,
|
||||
'generals' | 'cities' | 'nations' | 'troops' | 'diplomacy'
|
||||
|
||||
@@ -1,794 +1,83 @@
|
||||
import { createGamePostgresConnector } from '@sammo-ts/infra';
|
||||
import { asRecord, HALL_OF_FAME_TYPES, type HallOfFameType } from '@sammo-ts/common';
|
||||
import type { LogEntryDraft } from '@sammo-ts/logic';
|
||||
import { LogCategory, LogFormat, LogScope } from '@sammo-ts/logic';
|
||||
import { asNumber, asRecord, JosaUtil } from '@sammo-ts/common';
|
||||
import { LogCategory, LogFormat, LogScope, type LogEntryDraft } from '@sammo-ts/logic';
|
||||
|
||||
import type { TurnCalendarHandler } from './inMemoryWorld.js';
|
||||
import type { InMemoryTurnWorld } from './inMemoryWorld.js';
|
||||
|
||||
const UNIFIER_POINT = 2000;
|
||||
|
||||
const readMetaNumber = (meta: Record<string, unknown>, key: string): number => {
|
||||
const value = meta[key];
|
||||
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
||||
return 0;
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
const readMetaNumberOrNull = (meta: Record<string, unknown>, key: string): number | null => {
|
||||
const value = meta[key];
|
||||
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||
return Math.floor(value);
|
||||
}
|
||||
if (typeof value === 'string') {
|
||||
const parsed = Number(value);
|
||||
if (Number.isFinite(parsed)) {
|
||||
return Math.floor(parsed);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const computeHallRate = (numerator: number, denominator: number): number => {
|
||||
if (denominator <= 0) {
|
||||
return 0;
|
||||
}
|
||||
return numerator / denominator;
|
||||
};
|
||||
|
||||
const computeDexPoint = (meta: Record<string, unknown>): number => {
|
||||
let total = 0;
|
||||
for (const [key, value] of Object.entries(meta)) {
|
||||
if (!key.startsWith('dex')) {
|
||||
continue;
|
||||
}
|
||||
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||
total += value;
|
||||
}
|
||||
}
|
||||
return total * 0.001;
|
||||
};
|
||||
import type { InMemoryTurnWorld, TurnCalendarHandler } from './inMemoryWorld.js';
|
||||
import { queueYearbookSnapshot } from './yearbookHandler.js';
|
||||
|
||||
const buildUnificationLog = (nationName: string): LogEntryDraft => ({
|
||||
scope: LogScope.SYSTEM,
|
||||
category: LogCategory.HISTORY,
|
||||
format: LogFormat.YEAR_MONTH,
|
||||
text: `<C>●</><Y><b>【통일】</b></><D><b>${nationName}</b></>이 전토를 통일하였습니다.`,
|
||||
text: `<C>●</><Y><b>【통일】</b></><D><b>${nationName}</b></>${JosaUtil.pick(nationName, '이')} 전토를 통일하였습니다.`,
|
||||
meta: {},
|
||||
});
|
||||
|
||||
const buildNationHistoryLog = (nationId: number, nationName: string): LogEntryDraft => ({
|
||||
scope: LogScope.NATION,
|
||||
category: LogCategory.HISTORY,
|
||||
format: LogFormat.YEAR_MONTH,
|
||||
nationId,
|
||||
text: `<D><b>${nationName}</b></>${JosaUtil.pick(nationName, '이')} 전토를 통일`,
|
||||
meta: {},
|
||||
});
|
||||
|
||||
const buildGeneralActionLog = (generalId: number, nationId: number, nationName: string): LogEntryDraft => ({
|
||||
scope: LogScope.GENERAL,
|
||||
category: LogCategory.ACTION,
|
||||
format: LogFormat.YEAR_MONTH,
|
||||
generalId,
|
||||
nationId,
|
||||
text: `<D><b>${nationName}</b></>${JosaUtil.pick(nationName, '이')} 전토를 통일하였습니다.`,
|
||||
meta: {},
|
||||
});
|
||||
|
||||
const resolveServerId = (world: InMemoryTurnWorld, fallback: string): string => {
|
||||
const serverId = world.getState().meta.serverId;
|
||||
return typeof serverId === 'string' && serverId.trim() ? serverId.trim() : fallback;
|
||||
};
|
||||
|
||||
export const createUnificationHandler = (options: {
|
||||
databaseUrl: string;
|
||||
profileName: string;
|
||||
getWorld: () => InMemoryTurnWorld | null;
|
||||
}): { handler: TurnCalendarHandler; close: () => Promise<void> } => {
|
||||
const connector = createGamePostgresConnector({ url: options.databaseUrl });
|
||||
const ready = connector.connect();
|
||||
|
||||
const settleInheritance = async (winnerNationId: number, year: number, month: number): Promise<void> => {
|
||||
await ready;
|
||||
const prisma = connector.prisma;
|
||||
|
||||
const generals = await prisma.general.findMany({
|
||||
where: {
|
||||
userId: { not: null },
|
||||
npcState: { lt: 2 },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
nationId: true,
|
||||
officerLevel: true,
|
||||
meta: true,
|
||||
},
|
||||
});
|
||||
|
||||
const userIds = Array.from(new Set(generals.map((general) => general.userId).filter(Boolean))) as string[];
|
||||
if (userIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const pointRows = await prisma.inheritancePoint.findMany({
|
||||
where: {
|
||||
userId: { in: userIds },
|
||||
},
|
||||
select: {
|
||||
userId: true,
|
||||
key: true,
|
||||
value: true,
|
||||
},
|
||||
});
|
||||
const pointMap = new Map<string, Map<string, number>>();
|
||||
for (const row of pointRows) {
|
||||
const bucket = pointMap.get(row.userId) ?? new Map();
|
||||
bucket.set(row.key, row.value);
|
||||
pointMap.set(row.userId, bucket);
|
||||
}
|
||||
|
||||
for (const general of generals) {
|
||||
if (!general.userId) {
|
||||
continue;
|
||||
}
|
||||
const meta = asRecord(general.meta);
|
||||
const livedMonth = readMetaNumber(meta, 'inherit_lived_month');
|
||||
const maxDomestic = readMetaNumber(meta, 'max_domestic_critical');
|
||||
const activeAction = readMetaNumber(meta, 'inherit_active_action');
|
||||
const combat = readMetaNumber(meta, 'rank_warnum') * 5;
|
||||
const sabotage = readMetaNumber(meta, 'firenum') * 20;
|
||||
const dex = computeDexPoint(meta);
|
||||
|
||||
const points = pointMap.get(general.userId) ?? new Map();
|
||||
const previous = points.get('previous') ?? 0;
|
||||
const unifier = points.get('unifier') ?? 0;
|
||||
const earned =
|
||||
livedMonth +
|
||||
maxDomestic +
|
||||
activeAction * 3 +
|
||||
combat +
|
||||
sabotage +
|
||||
dex +
|
||||
unifier +
|
||||
(general.nationId === winnerNationId && general.officerLevel > 4 ? UNIFIER_POINT : 0);
|
||||
|
||||
const total = previous + earned;
|
||||
|
||||
await prisma.inheritancePoint.upsert({
|
||||
where: {
|
||||
userId_key: {
|
||||
userId: general.userId,
|
||||
key: 'previous',
|
||||
},
|
||||
},
|
||||
update: { value: total },
|
||||
create: { userId: general.userId, key: 'previous', value: total },
|
||||
});
|
||||
|
||||
await prisma.inheritancePoint.deleteMany({
|
||||
where: {
|
||||
userId: general.userId,
|
||||
key: { not: 'previous' },
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.inheritanceResult.create({
|
||||
data: {
|
||||
serverId: options.profileName,
|
||||
owner: general.userId,
|
||||
generalId: general.id,
|
||||
year,
|
||||
month,
|
||||
value: {
|
||||
previous,
|
||||
lived_month: livedMonth,
|
||||
max_domestic_critical: maxDomestic,
|
||||
active_action: activeAction,
|
||||
combat,
|
||||
sabotage,
|
||||
dex,
|
||||
unifier,
|
||||
unifierAward:
|
||||
general.nationId === winnerNationId && general.officerLevel > 4 ? UNIFIER_POINT : 0,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.inheritanceLog.create({
|
||||
data: {
|
||||
userId: general.userId,
|
||||
year,
|
||||
month,
|
||||
text: `천하 통일 정산: ${Math.floor(total).toLocaleString()} 포인트`,
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const settleHallOfFame = async (winnerNationId: number): Promise<void> => {
|
||||
const world = options.getWorld();
|
||||
if (!world) {
|
||||
return;
|
||||
}
|
||||
await ready;
|
||||
const prisma = connector.prisma;
|
||||
const state = world.getState();
|
||||
const meta = asRecord(state.meta);
|
||||
|
||||
const serverId =
|
||||
typeof meta.serverId === 'string' && meta.serverId.trim() ? meta.serverId.trim() : options.profileName;
|
||||
const season = readMetaNumberOrNull(meta, 'season') ?? 1;
|
||||
const scenario = readMetaNumberOrNull(meta, 'scenarioId') ?? 0;
|
||||
const scenarioName =
|
||||
typeof asRecord(meta.scenarioMeta).title === 'string' ? String(asRecord(meta.scenarioMeta).title) : '';
|
||||
const startTime = typeof meta.starttime === 'string' ? meta.starttime : null;
|
||||
const unitedTime = new Date().toISOString();
|
||||
|
||||
const [serverCount, nationRows, generalRows, rankRows] = await Promise.all([
|
||||
prisma.gameHistory.count(),
|
||||
prisma.nation.findMany({ select: { id: true, name: true, color: true } }),
|
||||
prisma.general.findMany({
|
||||
where: { npcState: { lt: 2 } },
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
nationId: true,
|
||||
name: true,
|
||||
picture: true,
|
||||
imageServer: true,
|
||||
experience: true,
|
||||
dedication: true,
|
||||
},
|
||||
}),
|
||||
prisma.rankData.findMany({
|
||||
where: { generalId: { gt: 0 } },
|
||||
select: { generalId: true, type: true, value: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
const nationMap = new Map<number, { name: string; color: string }>();
|
||||
for (const nation of nationRows) {
|
||||
nationMap.set(nation.id, { name: nation.name, color: nation.color });
|
||||
}
|
||||
|
||||
const rankMap = new Map<number, Record<string, number>>();
|
||||
for (const row of rankRows) {
|
||||
const entry = rankMap.get(row.generalId) ?? {};
|
||||
entry[row.type] = row.value;
|
||||
rankMap.set(row.generalId, entry);
|
||||
}
|
||||
|
||||
const hallTypes: Array<[HallOfFameType, 'natural' | 'rank' | 'calc']> = HALL_OF_FAME_TYPES.map((type) => {
|
||||
if (type === 'experience' || type === 'dedication' || type.startsWith('dex')) {
|
||||
return [type, 'natural'];
|
||||
}
|
||||
if (type.endsWith('rate')) {
|
||||
return [type, 'calc'];
|
||||
}
|
||||
return [type, 'rank'];
|
||||
});
|
||||
|
||||
for (const general of generalRows) {
|
||||
const ranks = rankMap.get(general.id) ?? {};
|
||||
const warnum = ranks.warnum ?? 0;
|
||||
const killnum = ranks.killnum ?? 0;
|
||||
const killcrew = ranks.killcrew ?? 0;
|
||||
const deathcrew = ranks.deathcrew ?? 0;
|
||||
const killcrewPerson = ranks.killcrew_person ?? 0;
|
||||
const deathcrewPerson = ranks.deathcrew_person ?? 0;
|
||||
const ttw = ranks.ttw ?? 0;
|
||||
const ttd = ranks.ttd ?? 0;
|
||||
const ttl = ranks.ttl ?? 0;
|
||||
const tlw = ranks.tlw ?? 0;
|
||||
const tld = ranks.tld ?? 0;
|
||||
const tll = ranks.tll ?? 0;
|
||||
const tsw = ranks.tsw ?? 0;
|
||||
const tsd = ranks.tsd ?? 0;
|
||||
const tsl = ranks.tsl ?? 0;
|
||||
const tiw = ranks.tiw ?? 0;
|
||||
const tid = ranks.tid ?? 0;
|
||||
const til = ranks.til ?? 0;
|
||||
const betGold = ranks.betgold ?? 0;
|
||||
const betWinGold = ranks.betwingold ?? 0;
|
||||
|
||||
const ttTotal = ttw + ttd + ttl;
|
||||
const tlTotal = tlw + tld + tll;
|
||||
const tsTotal = tsw + tsd + tsl;
|
||||
const tiTotal = tiw + tid + til;
|
||||
|
||||
const calcValues: Record<string, number> = {
|
||||
winrate: computeHallRate(killnum, warnum),
|
||||
killrate: computeHallRate(killcrew, Math.max(1, deathcrew)),
|
||||
killrate_person: computeHallRate(killcrewPerson, Math.max(1, deathcrewPerson)),
|
||||
ttrate: computeHallRate(ttw, Math.max(1, ttTotal)),
|
||||
tlrate: computeHallRate(tlw, Math.max(1, tlTotal)),
|
||||
tsrate: computeHallRate(tsw, Math.max(1, tsTotal)),
|
||||
tirate: computeHallRate(tiw, Math.max(1, tiTotal)),
|
||||
betrate: computeHallRate(betWinGold, Math.max(1, betGold)),
|
||||
};
|
||||
|
||||
const nation = nationMap.get(general.nationId) ?? { name: '재야', color: '#000000' };
|
||||
const aux = {
|
||||
name: general.name,
|
||||
nationName: nation.name,
|
||||
bgColor: nation.color,
|
||||
fgColor: nation.color,
|
||||
picture: general.picture,
|
||||
imgsvr: general.imageServer,
|
||||
startTime,
|
||||
unitedTime,
|
||||
ownerName: general.userId ?? null,
|
||||
serverID: serverId,
|
||||
serverIdx: serverCount,
|
||||
serverName: options.profileName,
|
||||
scenarioName,
|
||||
};
|
||||
|
||||
for (const [typeName, valueType] of hallTypes) {
|
||||
const value =
|
||||
valueType === 'natural'
|
||||
? typeName === 'experience'
|
||||
? general.experience
|
||||
: typeName === 'dedication'
|
||||
? general.dedication
|
||||
: (ranks[typeName] ?? 0)
|
||||
: valueType === 'rank'
|
||||
? (ranks[typeName] ?? 0)
|
||||
: (calcValues[typeName] ?? 0);
|
||||
|
||||
if ((typeName === 'winrate' || typeName === 'killrate') && warnum < 10) {
|
||||
continue;
|
||||
}
|
||||
if (typeName === 'ttrate' && ttTotal < 50) {
|
||||
continue;
|
||||
}
|
||||
if (typeName === 'tlrate' && tlTotal < 50) {
|
||||
continue;
|
||||
}
|
||||
if (typeName === 'tsrate' && tsTotal < 50) {
|
||||
continue;
|
||||
}
|
||||
if (typeName === 'tirate' && tiTotal < 50) {
|
||||
continue;
|
||||
}
|
||||
if (typeName === 'betrate' && betGold < 1000) {
|
||||
continue;
|
||||
}
|
||||
if (value <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const existing = await prisma.hallOfFame.findUnique({
|
||||
where: {
|
||||
serverId_type_generalNo: {
|
||||
serverId,
|
||||
type: typeName,
|
||||
generalNo: general.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!existing) {
|
||||
await prisma.hallOfFame.create({
|
||||
data: {
|
||||
serverId,
|
||||
season,
|
||||
scenario,
|
||||
generalNo: general.id,
|
||||
type: typeName,
|
||||
value,
|
||||
owner: general.userId ?? null,
|
||||
aux,
|
||||
},
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (value > existing.value) {
|
||||
await prisma.hallOfFame.update({
|
||||
where: { id: existing.id },
|
||||
data: { value, aux },
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await prisma.gameHistory.update({
|
||||
where: { serverId },
|
||||
data: {
|
||||
winnerNation: winnerNationId,
|
||||
date: new Date(),
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const settleDynasty = async (winnerNationId: number): Promise<void> => {
|
||||
const world = options.getWorld();
|
||||
if (!world) {
|
||||
return;
|
||||
}
|
||||
await ready;
|
||||
const prisma = connector.prisma;
|
||||
const state = world.getState();
|
||||
const meta = asRecord(state.meta);
|
||||
|
||||
const serverId =
|
||||
typeof meta.serverId === 'string' && meta.serverId.trim() ? meta.serverId.trim() : options.profileName;
|
||||
const serverName =
|
||||
typeof meta.serverName === 'string' && meta.serverName.trim()
|
||||
? meta.serverName.trim()
|
||||
: options.profileName;
|
||||
|
||||
const [serverCount, nationRows, cityRows, generalRows, rankRows, historyRows, oldNationRows] =
|
||||
await Promise.all([
|
||||
prisma.gameHistory.count(),
|
||||
prisma.nation.findMany({
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
color: true,
|
||||
level: true,
|
||||
typeCode: true,
|
||||
gold: true,
|
||||
rice: true,
|
||||
meta: true,
|
||||
capitalCityId: true,
|
||||
},
|
||||
}),
|
||||
prisma.city.findMany({
|
||||
select: { nationId: true, population: true, populationMax: true },
|
||||
}),
|
||||
prisma.general.findMany({
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
name: true,
|
||||
nationId: true,
|
||||
dedication: true,
|
||||
officerLevel: true,
|
||||
picture: true,
|
||||
imageServer: true,
|
||||
leadership: true,
|
||||
strength: true,
|
||||
intel: true,
|
||||
experience: true,
|
||||
gold: true,
|
||||
rice: true,
|
||||
crew: true,
|
||||
crewTypeId: true,
|
||||
train: true,
|
||||
atmos: true,
|
||||
age: true,
|
||||
startAge: true,
|
||||
npcState: true,
|
||||
personalCode: true,
|
||||
specialCode: true,
|
||||
special2Code: true,
|
||||
cityId: true,
|
||||
troopId: true,
|
||||
turnTime: true,
|
||||
meta: true,
|
||||
},
|
||||
}),
|
||||
prisma.rankData.findMany({
|
||||
where: {
|
||||
nationId: winnerNationId,
|
||||
type: { in: ['killnum', 'firenum'] },
|
||||
},
|
||||
select: { generalId: true, type: true, value: true },
|
||||
}),
|
||||
prisma.logEntry.findMany({
|
||||
where: {
|
||||
nationId: winnerNationId,
|
||||
scope: LogScope.NATION,
|
||||
category: LogCategory.HISTORY,
|
||||
},
|
||||
orderBy: { id: 'asc' },
|
||||
select: { text: true },
|
||||
}),
|
||||
prisma.oldNation.findMany({
|
||||
where: { serverId },
|
||||
select: { data: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
const winnerNation = nationRows.find((nation) => nation.id === winnerNationId);
|
||||
if (!winnerNation) {
|
||||
return;
|
||||
}
|
||||
|
||||
const powerMap = new Map<number, number>();
|
||||
for (const nation of world.listNations()) {
|
||||
powerMap.set(nation.id, nation.power);
|
||||
}
|
||||
|
||||
const winnerGenerals = generalRows.filter((general) => general.nationId === winnerNationId);
|
||||
const winnerGeneralIds = winnerGenerals.map((general) => general.id);
|
||||
const noNationGenerals = generalRows.filter((general) => general.nationId === 0);
|
||||
|
||||
const cityCount = cityRows.filter((city) => city.nationId === winnerNationId).length;
|
||||
const popSum = cityRows
|
||||
.filter((city) => city.nationId === winnerNationId)
|
||||
.reduce((sum, city) => sum + city.population, 0);
|
||||
const popMaxSum = cityRows
|
||||
.filter((city) => city.nationId === winnerNationId)
|
||||
.reduce((sum, city) => sum + city.populationMax, 0);
|
||||
const popText = `${popSum} / ${popMaxSum}`;
|
||||
const popRate = popMaxSum > 0 ? `${Math.round((popSum / popMaxSum) * 10000) / 100} %` : '0 %';
|
||||
|
||||
const officerMap = new Map<number, { name: string; picture: string | null }>();
|
||||
for (const general of winnerGenerals) {
|
||||
if (general.officerLevel < 5) {
|
||||
continue;
|
||||
}
|
||||
if (!officerMap.has(general.officerLevel)) {
|
||||
officerMap.set(general.officerLevel, { name: general.name, picture: general.picture ?? null });
|
||||
}
|
||||
}
|
||||
|
||||
const generalNameMap = new Map<number, string>();
|
||||
for (const general of generalRows) {
|
||||
generalNameMap.set(general.id, general.name);
|
||||
}
|
||||
|
||||
const buildTopList = (type: 'killnum' | 'firenum', limit: number): string => {
|
||||
const rows = rankRows
|
||||
.filter((row) => row.type === type && row.value > 0)
|
||||
.sort((a, b) => b.value - a.value)
|
||||
.slice(0, limit);
|
||||
return rows
|
||||
.map((row) => `${generalNameMap.get(row.generalId) ?? '무명'}【${row.value.toLocaleString('ko-KR')}】`)
|
||||
.join(', ');
|
||||
};
|
||||
|
||||
const tiger = buildTopList('killnum', 5);
|
||||
const eagle = buildTopList('firenum', 7);
|
||||
|
||||
const gen = winnerGenerals
|
||||
.slice()
|
||||
.sort((a, b) => b.dedication - a.dedication)
|
||||
.map((general) => general.name)
|
||||
.join(', ');
|
||||
|
||||
const nationNames: string[] = [];
|
||||
const nationTypeCounts = new Map<string, number>();
|
||||
for (const row of oldNationRows) {
|
||||
const data = asRecord(row.data);
|
||||
const name = typeof data.name === 'string' ? data.name : '';
|
||||
const type = typeof data.type === 'string' ? data.type : '';
|
||||
if (name) {
|
||||
nationNames.push(name);
|
||||
}
|
||||
if (type) {
|
||||
nationTypeCounts.set(type, (nationTypeCounts.get(type) ?? 0) + 1);
|
||||
}
|
||||
}
|
||||
if (!nationNames.includes(winnerNation.name)) {
|
||||
nationNames.push(winnerNation.name);
|
||||
}
|
||||
if (winnerNation.typeCode) {
|
||||
nationTypeCounts.set(winnerNation.typeCode, (nationTypeCounts.get(winnerNation.typeCode) ?? 0) + 1);
|
||||
}
|
||||
const nationHist = Array.from(nationTypeCounts.entries())
|
||||
.map(([key, count]) => `${key}(${count})`)
|
||||
.join(', ');
|
||||
|
||||
const phase = `${serverName}${serverCount}기`;
|
||||
const nationCount = `${Math.max(1, nationRows.length)} / ${Math.max(1, nationRows.length)}`;
|
||||
const genCount = `${generalRows.length} / ${generalRows.length}`;
|
||||
|
||||
const history = historyRows.map((row) => row.text);
|
||||
|
||||
await prisma.oldNation.upsert({
|
||||
where: {
|
||||
serverId_nation_sourceId: {
|
||||
serverId,
|
||||
nation: winnerNationId,
|
||||
sourceId: 0,
|
||||
},
|
||||
},
|
||||
update: {
|
||||
data: {
|
||||
nation: winnerNationId,
|
||||
name: winnerNation.name,
|
||||
color: winnerNation.color,
|
||||
type: winnerNation.typeCode,
|
||||
level: winnerNation.level,
|
||||
gold: winnerNation.gold,
|
||||
rice: winnerNation.rice,
|
||||
power: powerMap.get(winnerNationId) ?? 0,
|
||||
capitalCityId: winnerNation.capitalCityId,
|
||||
generals: winnerGeneralIds,
|
||||
history,
|
||||
meta: winnerNation.meta ?? {},
|
||||
},
|
||||
date: new Date(),
|
||||
},
|
||||
create: {
|
||||
serverId,
|
||||
nation: winnerNationId,
|
||||
sourceId: 0,
|
||||
data: {
|
||||
nation: winnerNationId,
|
||||
name: winnerNation.name,
|
||||
color: winnerNation.color,
|
||||
type: winnerNation.typeCode,
|
||||
level: winnerNation.level,
|
||||
gold: winnerNation.gold,
|
||||
rice: winnerNation.rice,
|
||||
power: powerMap.get(winnerNationId) ?? 0,
|
||||
capitalCityId: winnerNation.capitalCityId,
|
||||
generals: winnerGeneralIds,
|
||||
history,
|
||||
meta: winnerNation.meta ?? {},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.oldNation.upsert({
|
||||
where: {
|
||||
serverId_nation_sourceId: {
|
||||
serverId,
|
||||
nation: 0,
|
||||
sourceId: 0,
|
||||
},
|
||||
},
|
||||
update: {
|
||||
data: {
|
||||
nation: 0,
|
||||
name: '재야',
|
||||
color: '#000000',
|
||||
type: 'neutral',
|
||||
level: 0,
|
||||
gold: 0,
|
||||
rice: 0,
|
||||
power: 0,
|
||||
capitalCityId: null,
|
||||
generals: noNationGenerals.map((general) => general.id),
|
||||
history: [],
|
||||
meta: {},
|
||||
},
|
||||
date: new Date(),
|
||||
},
|
||||
create: {
|
||||
serverId,
|
||||
nation: 0,
|
||||
sourceId: 0,
|
||||
data: {
|
||||
nation: 0,
|
||||
name: '재야',
|
||||
color: '#000000',
|
||||
type: 'neutral',
|
||||
level: 0,
|
||||
gold: 0,
|
||||
rice: 0,
|
||||
power: 0,
|
||||
capitalCityId: null,
|
||||
generals: noNationGenerals.map((general) => general.id),
|
||||
history: [],
|
||||
meta: {},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const oldGeneralTargets = generalRows.filter(
|
||||
(general) => general.nationId === 0 || general.nationId === winnerNationId
|
||||
);
|
||||
const generalHistoryRows = oldGeneralTargets.length
|
||||
? await prisma.logEntry.findMany({
|
||||
where: {
|
||||
generalId: { in: oldGeneralTargets.map((general) => general.id) },
|
||||
scope: LogScope.GENERAL,
|
||||
category: LogCategory.HISTORY,
|
||||
},
|
||||
orderBy: { id: 'desc' },
|
||||
select: { generalId: true, text: true },
|
||||
})
|
||||
: [];
|
||||
const historyByGeneral = new Map<number, string[]>();
|
||||
for (const row of generalHistoryRows) {
|
||||
if (row.generalId === null) {
|
||||
continue;
|
||||
}
|
||||
const history = historyByGeneral.get(row.generalId) ?? [];
|
||||
history.push(row.text);
|
||||
historyByGeneral.set(row.generalId, history);
|
||||
}
|
||||
await Promise.all(
|
||||
oldGeneralTargets.map((general) =>
|
||||
((snapshot) =>
|
||||
prisma.oldGeneral.upsert({
|
||||
where: {
|
||||
by_no: {
|
||||
serverId,
|
||||
generalNo: general.id,
|
||||
},
|
||||
},
|
||||
update: {
|
||||
owner: general.userId ?? null,
|
||||
name: general.name,
|
||||
lastYearMonth: state.currentYear * 100 + state.currentMonth,
|
||||
turnTime: general.turnTime,
|
||||
data: snapshot,
|
||||
},
|
||||
create: {
|
||||
serverId,
|
||||
generalNo: general.id,
|
||||
owner: general.userId ?? null,
|
||||
name: general.name,
|
||||
lastYearMonth: state.currentYear * 100 + state.currentMonth,
|
||||
turnTime: general.turnTime,
|
||||
data: snapshot,
|
||||
},
|
||||
}))({
|
||||
...general,
|
||||
turnTime: general.turnTime.toISOString(),
|
||||
history: historyByGeneral.get(general.id) ?? [],
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
await prisma.emperor.create({
|
||||
data: {
|
||||
serverId,
|
||||
phase,
|
||||
nationCount,
|
||||
nationName: nationNames.join(', '),
|
||||
nationHist,
|
||||
genCount,
|
||||
personalHist: '',
|
||||
specialHist: '',
|
||||
name: winnerNation.name,
|
||||
type: winnerNation.typeCode,
|
||||
color: winnerNation.color,
|
||||
year: state.currentYear,
|
||||
month: state.currentMonth,
|
||||
power: powerMap.get(winnerNationId) ?? 0,
|
||||
gennum: winnerGenerals.length,
|
||||
citynum: cityCount,
|
||||
pop: popText,
|
||||
poprate: popRate,
|
||||
gold: winnerNation.gold,
|
||||
rice: winnerNation.rice,
|
||||
l12name: officerMap.get(12)?.name ?? '',
|
||||
l12pic: officerMap.get(12)?.picture ?? '',
|
||||
l11name: officerMap.get(11)?.name ?? '',
|
||||
l11pic: officerMap.get(11)?.picture ?? '',
|
||||
l10name: officerMap.get(10)?.name ?? '',
|
||||
l10pic: officerMap.get(10)?.picture ?? '',
|
||||
l9name: officerMap.get(9)?.name ?? '',
|
||||
l9pic: officerMap.get(9)?.picture ?? '',
|
||||
l8name: officerMap.get(8)?.name ?? '',
|
||||
l8pic: officerMap.get(8)?.picture ?? '',
|
||||
l7name: officerMap.get(7)?.name ?? '',
|
||||
l7pic: officerMap.get(7)?.picture ?? '',
|
||||
l6name: officerMap.get(6)?.name ?? '',
|
||||
l6pic: officerMap.get(6)?.picture ?? '',
|
||||
l5name: officerMap.get(5)?.name ?? '',
|
||||
l5pic: officerMap.get(5)?.picture ?? '',
|
||||
tiger,
|
||||
eagle,
|
||||
gen,
|
||||
history,
|
||||
aux: {
|
||||
winnerNationId,
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const handler: TurnCalendarHandler = {
|
||||
}): { handler: TurnCalendarHandler } => ({
|
||||
handler: {
|
||||
onMonthChanged: (context) => {
|
||||
const world = options.getWorld();
|
||||
if (!world) {
|
||||
return;
|
||||
}
|
||||
if (!world) return;
|
||||
|
||||
const state = world.getState();
|
||||
const meta = asRecord(state.meta);
|
||||
if (typeof meta.isUnited === 'number' && meta.isUnited !== 0) {
|
||||
return;
|
||||
}
|
||||
if (asNumber(meta.isunited ?? meta.isUnited, 0) !== 0) return;
|
||||
|
||||
const activeNations = world.listNations().filter((nation) => nation.level > 0);
|
||||
if (activeNations.length !== 1) {
|
||||
return;
|
||||
}
|
||||
const winner = activeNations[0];
|
||||
if (activeNations.length !== 1) return;
|
||||
|
||||
const winner = activeNations[0]!;
|
||||
const cities = world.listCities();
|
||||
const ownedCount = cities.filter((city) => city.nationId === winner.id).length;
|
||||
if (ownedCount !== cities.length) {
|
||||
return;
|
||||
if (cities.length === 0 || cities.some((city) => city.nationId !== winner.id)) return;
|
||||
|
||||
const serverId = resolveServerId(world, options.profileName);
|
||||
world.updateWorldMeta({
|
||||
isUnited: 2,
|
||||
isunited: 2,
|
||||
refreshLimit: asNumber(meta.refreshLimit, 0) * 100,
|
||||
});
|
||||
world.pushLog(buildNationHistoryLog(winner.id, winner.name));
|
||||
for (const general of world.listGenerals().filter((entry) => entry.nationId === winner.id)) {
|
||||
world.pushLog(buildGeneralActionLog(general.id, winner.id, winner.name));
|
||||
}
|
||||
|
||||
world.updateWorldMeta({ isUnited: 2 });
|
||||
world.pushLog(buildUnificationLog(winner.name));
|
||||
void settleInheritance(winner.id, context.currentYear, context.currentMonth);
|
||||
void settleHallOfFame(winner.id);
|
||||
void settleDynasty(winner.id);
|
||||
|
||||
queueYearbookSnapshot(world, options.profileName, context.currentYear, context.currentMonth);
|
||||
world.queueUnificationFinalization({
|
||||
generationKey: `unification:${serverId}`,
|
||||
serverId,
|
||||
profileName: options.profileName,
|
||||
winnerNationId: winner.id,
|
||||
year: context.currentYear,
|
||||
month: context.currentMonth,
|
||||
completedAt: new Date(state.lastTurnTime.getTime()),
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
const close = async (): Promise<void> => {
|
||||
await ready;
|
||||
await connector.disconnect();
|
||||
};
|
||||
|
||||
return { handler, close };
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,500 @@
|
||||
import { asRecord, HALL_OF_FAME_TYPES, resolveLegacyTextColor, type HallOfFameType } from '@sammo-ts/common';
|
||||
import type { GamePrisma, InputJsonValue } from '@sammo-ts/infra';
|
||||
import { LogCategory, LogScope } from '@sammo-ts/logic';
|
||||
|
||||
import type { InMemoryTurnWorld } from './inMemoryWorld.js';
|
||||
|
||||
const UNIFIER_POINT = 2000;
|
||||
const asJson = (value: unknown): InputJsonValue => value as InputJsonValue;
|
||||
|
||||
export interface UnificationFinalizationInput {
|
||||
readonly generationKey: string;
|
||||
readonly serverId: string;
|
||||
readonly profileName: string;
|
||||
readonly winnerNationId: number;
|
||||
readonly year: number;
|
||||
readonly month: number;
|
||||
readonly completedAt: Date;
|
||||
}
|
||||
|
||||
export interface UnificationFinalizationResult {
|
||||
status: 'APPLIED' | 'ALREADY_APPLIED';
|
||||
generationKey: string;
|
||||
}
|
||||
|
||||
const readNumber = (value: unknown): number => (typeof value === 'number' && Number.isFinite(value) ? value : 0);
|
||||
|
||||
const readInteger = (value: unknown, fallback = 0): number => {
|
||||
const parsed = typeof value === 'string' ? Number(value) : value;
|
||||
return typeof parsed === 'number' && Number.isFinite(parsed) ? Math.floor(parsed) : fallback;
|
||||
};
|
||||
|
||||
const computeRate = (numerator: number, denominator: number): number => (denominator > 0 ? numerator / denominator : 0);
|
||||
|
||||
const ownerDisplayName = (meta: Record<string, unknown>): string | null => {
|
||||
for (const key of ['ownerDisplayName', 'owner_name', 'ownerName']) {
|
||||
const value = meta[key];
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
return value.trim();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const formatHistogram = (value: unknown): string =>
|
||||
Object.entries(asRecord(value))
|
||||
.filter((entry): entry is [string, number] => typeof entry[1] === 'number' && Number.isFinite(entry[1]))
|
||||
.sort(([left], [right]) => left.localeCompare(right))
|
||||
.map(([key, count]) => `${key}(${count})`)
|
||||
.join(', ');
|
||||
|
||||
const claimGeneration = async (
|
||||
transaction: GamePrisma.TransactionClient,
|
||||
input: UnificationFinalizationInput
|
||||
): Promise<'CLAIMED' | 'ALREADY_APPLIED'> => {
|
||||
await transaction.$executeRaw`
|
||||
SELECT pg_advisory_xact_lock(
|
||||
hashtext(${'unification-finalization'}),
|
||||
hashtext(${input.generationKey})
|
||||
)
|
||||
`;
|
||||
const existing = await transaction.unificationFinalization.findUnique({
|
||||
where: { generationKey: input.generationKey },
|
||||
});
|
||||
if (existing) {
|
||||
const matches =
|
||||
existing.serverId === input.serverId &&
|
||||
existing.profileName === input.profileName &&
|
||||
existing.winnerNation === input.winnerNationId &&
|
||||
existing.year === input.year &&
|
||||
existing.month === input.month &&
|
||||
existing.completedAt.getTime() === input.completedAt.getTime();
|
||||
if (!matches) {
|
||||
throw new Error(`Unification generation payload mismatch: ${input.generationKey}.`);
|
||||
}
|
||||
return 'ALREADY_APPLIED';
|
||||
}
|
||||
await transaction.unificationFinalization.create({
|
||||
data: {
|
||||
generationKey: input.generationKey,
|
||||
serverId: input.serverId,
|
||||
profileName: input.profileName,
|
||||
winnerNation: input.winnerNationId,
|
||||
year: input.year,
|
||||
month: input.month,
|
||||
completedAt: input.completedAt,
|
||||
},
|
||||
});
|
||||
return 'CLAIMED';
|
||||
};
|
||||
|
||||
export const persistUnificationFinalization = async (
|
||||
transaction: GamePrisma.TransactionClient,
|
||||
input: UnificationFinalizationInput,
|
||||
world: InMemoryTurnWorld
|
||||
): Promise<UnificationFinalizationResult> => {
|
||||
if (!input.generationKey.trim()) {
|
||||
throw new Error('Unification finalization requires a non-empty generationKey.');
|
||||
}
|
||||
const claim = await claimGeneration(transaction, input);
|
||||
if (claim === 'ALREADY_APPLIED') {
|
||||
return { status: 'ALREADY_APPLIED', generationKey: input.generationKey };
|
||||
}
|
||||
|
||||
const state = world.getState();
|
||||
if (state.currentYear !== input.year || state.currentMonth !== input.month) {
|
||||
throw new Error(
|
||||
`Unification snapshot date mismatch: input=${input.year}-${input.month}, world=${state.currentYear}-${state.currentMonth}.`
|
||||
);
|
||||
}
|
||||
|
||||
const winner = world.getNationById(input.winnerNationId);
|
||||
if (!winner) {
|
||||
throw new Error(`Unification winner nation does not exist: ${input.winnerNationId}.`);
|
||||
}
|
||||
|
||||
const meta = asRecord(state.meta);
|
||||
const snapshotServerId =
|
||||
typeof meta.serverId === 'string' && meta.serverId.trim() ? meta.serverId.trim() : input.profileName;
|
||||
if (snapshotServerId !== input.serverId) {
|
||||
throw new Error(`Unification snapshot server mismatch: input=${input.serverId}, world=${snapshotServerId}.`);
|
||||
}
|
||||
const serverId = input.serverId;
|
||||
const serverName =
|
||||
typeof meta.serverName === 'string' && meta.serverName.trim() ? meta.serverName.trim() : input.profileName;
|
||||
const generals = world.listGenerals();
|
||||
const cities = world.listCities();
|
||||
const nations = world.listNations();
|
||||
const eligibleGenerals = generals.filter((general) => general.userId && general.npcState < 2);
|
||||
|
||||
const pointRows = eligibleGenerals.length
|
||||
? await transaction.inheritancePoint.findMany({
|
||||
where: { userId: { in: eligibleGenerals.map((general) => general.userId!) } },
|
||||
select: { userId: true, key: true, value: true },
|
||||
})
|
||||
: [];
|
||||
const pointsByUser = new Map<string, Map<string, number>>();
|
||||
for (const row of pointRows) {
|
||||
const points = pointsByUser.get(row.userId) ?? new Map<string, number>();
|
||||
points.set(row.key, row.value);
|
||||
pointsByUser.set(row.userId, points);
|
||||
}
|
||||
|
||||
for (const general of eligibleGenerals) {
|
||||
const userId = general.userId!;
|
||||
const generalMeta = asRecord(general.meta);
|
||||
const currentPoints = pointsByUser.get(userId) ?? new Map<string, number>();
|
||||
const previous = currentPoints.get('previous') ?? 0;
|
||||
const livedMonth = readNumber(generalMeta.inherit_lived_month);
|
||||
const maxDomestic = readNumber(generalMeta.max_domestic_critical);
|
||||
const activeAction = readNumber(generalMeta.inherit_active_action);
|
||||
const combat = readNumber(generalMeta.rank_warnum) * 5;
|
||||
const sabotage = readNumber(generalMeta.firenum) * 20;
|
||||
const dex =
|
||||
Object.entries(generalMeta).reduce(
|
||||
(sum, [key, value]) => (key.startsWith('dex') ? sum + readNumber(value) : sum),
|
||||
0
|
||||
) * 0.001;
|
||||
const unifier = currentPoints.get('unifier') ?? 0;
|
||||
const unifierAward = general.nationId === input.winnerNationId && general.officerLevel > 4 ? UNIFIER_POINT : 0;
|
||||
const total = Math.floor(
|
||||
previous + livedMonth + maxDomestic + activeAction * 3 + combat + sabotage + dex + unifier + unifierAward
|
||||
);
|
||||
|
||||
await transaction.inheritancePoint.upsert({
|
||||
where: { userId_key: { userId, key: 'previous' } },
|
||||
update: { value: total },
|
||||
create: { userId, key: 'previous', value: total },
|
||||
});
|
||||
await transaction.inheritancePoint.deleteMany({ where: { userId, key: { not: 'previous' } } });
|
||||
await transaction.inheritanceResult.create({
|
||||
data: {
|
||||
serverId,
|
||||
owner: userId,
|
||||
generalId: general.id,
|
||||
year: input.year,
|
||||
month: input.month,
|
||||
value: {
|
||||
previous,
|
||||
lived_month: livedMonth,
|
||||
max_domestic_critical: maxDomestic,
|
||||
active_action: activeAction,
|
||||
combat,
|
||||
sabotage,
|
||||
dex,
|
||||
unifier,
|
||||
unifierAward,
|
||||
total,
|
||||
generationKey: input.generationKey,
|
||||
},
|
||||
},
|
||||
});
|
||||
await transaction.inheritanceLog.create({
|
||||
data: {
|
||||
userId,
|
||||
serverId,
|
||||
year: input.year,
|
||||
month: input.month,
|
||||
text: `천하 통일 정산: ${total.toLocaleString('ko-KR')} 포인트`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const rankRows = generals.length
|
||||
? await transaction.rankData.findMany({
|
||||
where: { generalId: { in: generals.map((general) => general.id) } },
|
||||
select: { generalId: true, type: true, value: true },
|
||||
})
|
||||
: [];
|
||||
const ranksByGeneral = new Map<number, Record<string, number>>();
|
||||
for (const row of rankRows) {
|
||||
const ranks = ranksByGeneral.get(row.generalId) ?? {};
|
||||
ranks[row.type] = row.value;
|
||||
ranksByGeneral.set(row.generalId, ranks);
|
||||
}
|
||||
const nationMap = new Map(nations.map((nation) => [nation.id, nation]));
|
||||
const season = readInteger(meta.season, 1);
|
||||
const scenario = readInteger(meta.scenarioId);
|
||||
const scenarioName = String(asRecord(meta.scenarioMeta).title ?? '');
|
||||
const startTime = typeof meta.starttime === 'string' ? meta.starttime : null;
|
||||
const unitedTime = input.completedAt.toISOString();
|
||||
const serverCount = await transaction.gameHistory.count();
|
||||
const minHallAge = readInteger(asRecord(world.getScenarioConfig().const).minPushHallAge, 30);
|
||||
|
||||
const hallTypes: Array<[HallOfFameType, 'natural' | 'rank' | 'calc']> = HALL_OF_FAME_TYPES.map((type) => {
|
||||
if (type === 'experience' || type === 'dedication' || type.startsWith('dex')) {
|
||||
return [type, 'natural'];
|
||||
}
|
||||
return [type, type.endsWith('rate') ? 'calc' : 'rank'];
|
||||
});
|
||||
for (const general of eligibleGenerals.filter((entry) => entry.age >= minHallAge)) {
|
||||
const ranks = ranksByGeneral.get(general.id) ?? {};
|
||||
const totals = {
|
||||
tt: (ranks.ttw ?? 0) + (ranks.ttd ?? 0) + (ranks.ttl ?? 0),
|
||||
tl: (ranks.tlw ?? 0) + (ranks.tld ?? 0) + (ranks.tll ?? 0),
|
||||
ts: (ranks.tsw ?? 0) + (ranks.tsd ?? 0) + (ranks.tsl ?? 0),
|
||||
ti: (ranks.tiw ?? 0) + (ranks.tid ?? 0) + (ranks.til ?? 0),
|
||||
};
|
||||
const calc: Record<string, number> = {
|
||||
winrate: computeRate(ranks.killnum ?? 0, ranks.warnum ?? 0),
|
||||
killrate: computeRate(ranks.killcrew ?? 0, Math.max(1, ranks.deathcrew ?? 0)),
|
||||
killrate_person: computeRate(ranks.killcrew_person ?? 0, Math.max(1, ranks.deathcrew_person ?? 0)),
|
||||
ttrate: computeRate(ranks.ttw ?? 0, totals.tt),
|
||||
tlrate: computeRate(ranks.tlw ?? 0, totals.tl),
|
||||
tsrate: computeRate(ranks.tsw ?? 0, totals.ts),
|
||||
tirate: computeRate(ranks.tiw ?? 0, totals.ti),
|
||||
betrate: computeRate(ranks.betwingold ?? 0, Math.max(1, ranks.betgold ?? 0)),
|
||||
};
|
||||
const generalMeta = asRecord(general.meta);
|
||||
const nation = nationMap.get(general.nationId);
|
||||
const background = nation?.color ?? '#000000';
|
||||
const aux = {
|
||||
name: general.name,
|
||||
nationName: nation?.name ?? '재야',
|
||||
bgColor: background,
|
||||
fgColor: resolveLegacyTextColor(background),
|
||||
picture: general.picture ?? null,
|
||||
imgsvr: general.imageServer ?? 0,
|
||||
startTime,
|
||||
unitedTime,
|
||||
ownerDisplayName: ownerDisplayName(generalMeta),
|
||||
serverID: serverId,
|
||||
serverIdx: serverCount,
|
||||
serverName,
|
||||
scenarioName,
|
||||
generationKey: input.generationKey,
|
||||
};
|
||||
|
||||
for (const [type, valueType] of hallTypes) {
|
||||
const value =
|
||||
valueType === 'calc'
|
||||
? (calc[type] ?? 0)
|
||||
: valueType === 'rank'
|
||||
? (ranks[type] ?? 0)
|
||||
: type === 'experience'
|
||||
? general.experience
|
||||
: type === 'dedication'
|
||||
? general.dedication
|
||||
: readNumber(generalMeta[type]);
|
||||
if ((type === 'winrate' || type === 'killrate') && (ranks.warnum ?? 0) < 10) continue;
|
||||
if (type === 'ttrate' && totals.tt < 50) continue;
|
||||
if (type === 'tlrate' && totals.tl < 50) continue;
|
||||
if (type === 'tsrate' && totals.ts < 50) continue;
|
||||
if (type === 'tirate' && totals.ti < 50) continue;
|
||||
if (type === 'betrate' && (ranks.betgold ?? 0) < 1000) continue;
|
||||
if (value <= 0) continue;
|
||||
|
||||
const existing = await transaction.hallOfFame.findFirst({
|
||||
where: {
|
||||
OR: [
|
||||
{ serverId, type, generalNo: general.id },
|
||||
{ serverId, type, owner: general.userId },
|
||||
],
|
||||
},
|
||||
});
|
||||
if (!existing) {
|
||||
await transaction.hallOfFame.create({
|
||||
data: {
|
||||
serverId,
|
||||
season,
|
||||
scenario,
|
||||
generalNo: general.id,
|
||||
type,
|
||||
value,
|
||||
owner: general.userId ?? null,
|
||||
aux,
|
||||
},
|
||||
});
|
||||
} else if (value > existing.value) {
|
||||
await transaction.hallOfFame.update({ where: { id: existing.id }, data: { value, aux } });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await transaction.gameHistory.update({
|
||||
where: { serverId },
|
||||
data: { winnerNation: input.winnerNationId, date: input.completedAt },
|
||||
});
|
||||
|
||||
const nationHistoryRows = await transaction.logEntry.findMany({
|
||||
where: { nationId: input.winnerNationId, scope: LogScope.NATION, category: LogCategory.HISTORY },
|
||||
orderBy: { id: 'asc' },
|
||||
select: { text: true },
|
||||
});
|
||||
const nationHistory = nationHistoryRows.map((row) => row.text);
|
||||
const winnerGenerals = generals.filter((general) => general.nationId === input.winnerNationId);
|
||||
const neutralGenerals = generals.filter((general) => general.nationId === 0);
|
||||
const cityCount = cities.filter((city) => city.nationId === input.winnerNationId).length;
|
||||
const totalPop = cities.reduce((sum, city) => sum + city.population, 0);
|
||||
const totalMaxPop = cities.reduce((sum, city) => sum + city.populationMax, 0);
|
||||
const winnerMeta = asRecord(winner.meta);
|
||||
const winnerData = {
|
||||
...winner,
|
||||
tech: readInteger(winnerMeta.tech),
|
||||
aux: {
|
||||
...asRecord(winnerMeta.aux),
|
||||
...asRecord(winnerMeta.max_power),
|
||||
},
|
||||
msg: String(asRecord(winnerMeta.nationNotice).msg ?? winnerMeta.msg ?? ''),
|
||||
scout_msg: String(winnerMeta.scout_msg ?? ''),
|
||||
generals: winnerGenerals.map((general) => general.id),
|
||||
history: nationHistory,
|
||||
generationKey: input.generationKey,
|
||||
};
|
||||
await transaction.oldNation.upsert({
|
||||
where: { serverId_nation_sourceId: { serverId, nation: input.winnerNationId, sourceId: 0 } },
|
||||
update: { data: asJson(winnerData), date: input.completedAt },
|
||||
create: {
|
||||
serverId,
|
||||
nation: input.winnerNationId,
|
||||
sourceId: 0,
|
||||
data: asJson(winnerData),
|
||||
date: input.completedAt,
|
||||
},
|
||||
});
|
||||
const neutralData = {
|
||||
nation: 0,
|
||||
name: '재야',
|
||||
generals: neutralGenerals.map((general) => general.id),
|
||||
generationKey: input.generationKey,
|
||||
};
|
||||
await transaction.oldNation.upsert({
|
||||
where: { serverId_nation_sourceId: { serverId, nation: 0, sourceId: 0 } },
|
||||
update: { data: neutralData, date: input.completedAt },
|
||||
create: { serverId, nation: 0, sourceId: 0, data: neutralData, date: input.completedAt },
|
||||
});
|
||||
|
||||
const archiveGenerals = [...neutralGenerals, ...winnerGenerals];
|
||||
const generalHistoryRows = archiveGenerals.length
|
||||
? await transaction.logEntry.findMany({
|
||||
where: {
|
||||
generalId: { in: archiveGenerals.map((general) => general.id) },
|
||||
scope: LogScope.GENERAL,
|
||||
category: LogCategory.HISTORY,
|
||||
},
|
||||
orderBy: { id: 'asc' },
|
||||
select: { generalId: true, text: true },
|
||||
})
|
||||
: [];
|
||||
const historyByGeneral = new Map<number, string[]>();
|
||||
for (const row of generalHistoryRows) {
|
||||
if (row.generalId === null) continue;
|
||||
const history = historyByGeneral.get(row.generalId) ?? [];
|
||||
history.push(row.text);
|
||||
historyByGeneral.set(row.generalId, history);
|
||||
}
|
||||
for (const general of archiveGenerals) {
|
||||
const data = {
|
||||
...general,
|
||||
turnTime: general.turnTime.toISOString(),
|
||||
history: historyByGeneral.get(general.id) ?? [],
|
||||
generationKey: input.generationKey,
|
||||
};
|
||||
await transaction.oldGeneral.upsert({
|
||||
where: { by_no: { serverId, generalNo: general.id } },
|
||||
update: {
|
||||
owner: general.userId ?? null,
|
||||
name: general.name,
|
||||
lastYearMonth: input.year * 100 + input.month,
|
||||
turnTime: general.turnTime,
|
||||
data: asJson(data),
|
||||
},
|
||||
create: {
|
||||
serverId,
|
||||
generalNo: general.id,
|
||||
owner: general.userId ?? null,
|
||||
name: general.name,
|
||||
lastYearMonth: input.year * 100 + input.month,
|
||||
turnTime: general.turnTime,
|
||||
data: asJson(data),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const officerMap = new Map(
|
||||
winnerGenerals
|
||||
.filter((general) => general.officerLevel >= 5)
|
||||
.map((general) => [general.officerLevel, general] as const)
|
||||
);
|
||||
const topList = (type: 'killnum' | 'firenum', limit: number): string =>
|
||||
rankRows
|
||||
.filter((row) => row.type === type && row.value > 0 && winnerGenerals.some((g) => g.id === row.generalId))
|
||||
.sort((left, right) => right.value - left.value)
|
||||
.slice(0, limit)
|
||||
.map(
|
||||
(row) =>
|
||||
`${generals.find((general) => general.id === row.generalId)?.name ?? '무명'}【${row.value.toLocaleString('ko-KR')}】`
|
||||
)
|
||||
.join(', ');
|
||||
const previousNationArchives = await transaction.oldNation.findMany({
|
||||
where: { serverId },
|
||||
select: { data: true },
|
||||
});
|
||||
const archivedNationNames = previousNationArchives
|
||||
.map((row) => asRecord(row.data).name)
|
||||
.filter((name): name is string => typeof name === 'string' && Boolean(name));
|
||||
if (!archivedNationNames.includes(winner.name)) archivedNationNames.push(winner.name);
|
||||
const statistics = asRecord(meta.dynastyStatistics);
|
||||
const nationCount = `1 / ${Math.max(1, readInteger(statistics.maxNationCount, 1))}`;
|
||||
const genCount = `${generals.length} / ${Math.max(generals.length, readInteger(statistics.maxGeneralCount))}`;
|
||||
const statisticNationNames = String(statistics.maxNationName ?? '').trim();
|
||||
const personalHist = formatHistogram(statistics.personalHist);
|
||||
const specialHist = [formatHistogram(statistics.specialHist), formatHistogram(statistics.special2Hist)]
|
||||
.filter(Boolean)
|
||||
.join(' // ');
|
||||
const population = `${totalPop} / ${totalMaxPop}`;
|
||||
const popRate = totalMaxPop > 0 ? `${Math.round((totalPop / totalMaxPop) * 10000) / 100} %` : '0 %';
|
||||
const officer = (level: number) => officerMap.get(level);
|
||||
|
||||
await transaction.emperor.create({
|
||||
data: {
|
||||
serverId,
|
||||
phase: `${serverName}${serverCount}기`,
|
||||
nationCount,
|
||||
nationName: statisticNationNames || archivedNationNames.join(', '),
|
||||
nationHist: formatHistogram(statistics.maxNationHist),
|
||||
genCount,
|
||||
personalHist,
|
||||
specialHist,
|
||||
name: winner.name,
|
||||
type: winner.typeCode,
|
||||
color: winner.color,
|
||||
year: input.year,
|
||||
month: input.month,
|
||||
power: winner.power,
|
||||
gennum: winnerGenerals.length,
|
||||
citynum: cityCount,
|
||||
pop: population,
|
||||
poprate: popRate,
|
||||
gold: winner.gold,
|
||||
rice: winner.rice,
|
||||
l12name: officer(12)?.name ?? '',
|
||||
l12pic: officer(12)?.picture ?? '',
|
||||
l11name: officer(11)?.name ?? '',
|
||||
l11pic: officer(11)?.picture ?? '',
|
||||
l10name: officer(10)?.name ?? '',
|
||||
l10pic: officer(10)?.picture ?? '',
|
||||
l9name: officer(9)?.name ?? '',
|
||||
l9pic: officer(9)?.picture ?? '',
|
||||
l8name: officer(8)?.name ?? '',
|
||||
l8pic: officer(8)?.picture ?? '',
|
||||
l7name: officer(7)?.name ?? '',
|
||||
l7pic: officer(7)?.picture ?? '',
|
||||
l6name: officer(6)?.name ?? '',
|
||||
l6pic: officer(6)?.picture ?? '',
|
||||
l5name: officer(5)?.name ?? '',
|
||||
l5pic: officer(5)?.picture ?? '',
|
||||
tiger: topList('killnum', 5),
|
||||
eagle: topList('firenum', 7),
|
||||
gen: winnerGenerals
|
||||
.slice()
|
||||
.sort((left, right) => right.dedication - left.dedication)
|
||||
.map((general) => general.name)
|
||||
.join(', '),
|
||||
history: nationHistory,
|
||||
aux: { winnerNationId: input.winnerNationId, generationKey: input.generationKey },
|
||||
},
|
||||
});
|
||||
|
||||
return { status: 'APPLIED', generationKey: input.generationKey };
|
||||
};
|
||||
@@ -1,6 +1,4 @@
|
||||
import { createHash } from 'crypto';
|
||||
import { asNumber, asRecord } from '@sammo-ts/common';
|
||||
import { createGamePostgresConnector } from '@sammo-ts/infra';
|
||||
|
||||
import type { TurnCalendarHandler } from './inMemoryWorld.js';
|
||||
import type { InMemoryTurnWorld } from './inMemoryWorld.js';
|
||||
@@ -29,6 +27,19 @@ type YearbookNation = {
|
||||
cities: string[];
|
||||
};
|
||||
|
||||
type DynastyStatistics = {
|
||||
maxNationCount: number;
|
||||
maxNationName: string;
|
||||
maxNationHist: Record<string, number>;
|
||||
maxGeneralCount: number;
|
||||
currentGeneralCount: number;
|
||||
userGeneralCount: number;
|
||||
npcGeneralCount: number;
|
||||
personalHist: Record<string, number>;
|
||||
specialHist: Record<string, number>;
|
||||
special2Hist: Record<string, number>;
|
||||
};
|
||||
|
||||
const readState = (meta: Record<string, unknown>): number => {
|
||||
const raw = meta.state;
|
||||
if (typeof raw === 'number' && Number.isFinite(raw)) {
|
||||
@@ -136,58 +147,92 @@ const buildNationSnapshot = (world: InMemoryTurnWorld): YearbookNation[] => {
|
||||
});
|
||||
};
|
||||
|
||||
const buildHash = (map: YearbookMap, nations: YearbookNation[]): string =>
|
||||
createHash('sha256').update(JSON.stringify({ map, nations })).digest('hex');
|
||||
const increment = (target: Record<string, number>, key: string): void => {
|
||||
target[key] = (target[key] ?? 0) + 1;
|
||||
};
|
||||
|
||||
const updateDynastyStatistics = (world: InMemoryTurnWorld): void => {
|
||||
const state = world.getState();
|
||||
const previous = asRecord(state.meta.dynastyStatistics);
|
||||
const activeNations = world
|
||||
.listNations()
|
||||
.filter((nation) => nation.level > 0)
|
||||
.sort((left, right) => right.power - left.power || left.id - right.id);
|
||||
const generals = world.listGenerals();
|
||||
const maxNationCount = Math.max(asNumber(previous.maxNationCount, 0), activeNations.length);
|
||||
const replaceNationMaximum = activeNations.length > asNumber(previous.maxNationCount, 0);
|
||||
const nationHist: Record<string, number> = {};
|
||||
for (const nation of activeNations) increment(nationHist, nation.typeCode || 'neutral');
|
||||
|
||||
const personalHist: Record<string, number> = {};
|
||||
const specialHist: Record<string, number> = {};
|
||||
const special2Hist: Record<string, number> = {};
|
||||
let userGeneralCount = 0;
|
||||
let npcGeneralCount = 0;
|
||||
for (const general of generals) {
|
||||
increment(personalHist, general.role.personality || 'None');
|
||||
increment(specialHist, general.role.specialDomestic || 'None');
|
||||
increment(special2Hist, general.role.specialWar || 'None');
|
||||
if (general.npcState < 2) userGeneralCount += 1;
|
||||
else npcGeneralCount += 1;
|
||||
}
|
||||
|
||||
const statistics: DynastyStatistics = {
|
||||
maxNationCount,
|
||||
maxNationName: replaceNationMaximum
|
||||
? activeNations.map((nation) => `${nation.name}(${nation.typeCode})`).join(', ')
|
||||
: typeof previous.maxNationName === 'string'
|
||||
? previous.maxNationName
|
||||
: '',
|
||||
maxNationHist: replaceNationMaximum
|
||||
? nationHist
|
||||
: Object.fromEntries(
|
||||
Object.entries(asRecord(previous.maxNationHist)).flatMap(([key, value]) =>
|
||||
typeof value === 'number' && Number.isFinite(value) ? [[key, value]] : []
|
||||
)
|
||||
),
|
||||
maxGeneralCount: Math.max(asNumber(previous.maxGeneralCount, 0), generals.length),
|
||||
currentGeneralCount: generals.length,
|
||||
userGeneralCount,
|
||||
npcGeneralCount,
|
||||
personalHist,
|
||||
specialHist,
|
||||
special2Hist,
|
||||
};
|
||||
world.updateWorldMeta({ dynastyStatistics: statistics });
|
||||
};
|
||||
|
||||
const resolveServerId = (world: InMemoryTurnWorld, fallback: string): string => {
|
||||
const serverId = world.getState().meta.serverId;
|
||||
return typeof serverId === 'string' && serverId.trim() ? serverId.trim() : fallback;
|
||||
};
|
||||
|
||||
export const queueYearbookSnapshot = (
|
||||
world: InMemoryTurnWorld,
|
||||
profileName: string,
|
||||
year: number,
|
||||
month: number
|
||||
): void => {
|
||||
world.queueYearbookSnapshot({
|
||||
serverId: resolveServerId(world, profileName),
|
||||
sourceId: 0,
|
||||
year,
|
||||
month,
|
||||
map: buildMapSnapshot(world, year, month),
|
||||
nations: buildNationSnapshot(world),
|
||||
});
|
||||
};
|
||||
|
||||
export const createYearbookHandler = (options: {
|
||||
databaseUrl: string;
|
||||
profileName: string;
|
||||
getWorld: () => InMemoryTurnWorld | null;
|
||||
}): { handler: TurnCalendarHandler; close: () => Promise<void> } => {
|
||||
const connector = createGamePostgresConnector({ url: options.databaseUrl });
|
||||
const ready = connector.connect();
|
||||
|
||||
const handler: TurnCalendarHandler = {
|
||||
beforeMonthChanged: async (context) => {
|
||||
}): { handler: TurnCalendarHandler } => ({
|
||||
handler: {
|
||||
beforeMonthChanged: (context) => {
|
||||
const world = options.getWorld();
|
||||
if (!world) {
|
||||
return;
|
||||
}
|
||||
await ready;
|
||||
const map = buildMapSnapshot(world, context.previousYear, context.previousMonth);
|
||||
const nations = buildNationSnapshot(world);
|
||||
const hash = buildHash(map, nations);
|
||||
|
||||
await connector.prisma.yearbookHistory.upsert({
|
||||
where: {
|
||||
profileName_year_month_sourceId: {
|
||||
profileName: options.profileName,
|
||||
year: context.previousYear,
|
||||
month: context.previousMonth,
|
||||
sourceId: 0,
|
||||
},
|
||||
},
|
||||
update: {
|
||||
map,
|
||||
nations,
|
||||
hash,
|
||||
},
|
||||
create: {
|
||||
profileName: options.profileName,
|
||||
sourceId: 0,
|
||||
year: context.previousYear,
|
||||
month: context.previousMonth,
|
||||
map,
|
||||
nations,
|
||||
hash,
|
||||
},
|
||||
});
|
||||
if (!world) return;
|
||||
updateDynastyStatistics(world);
|
||||
queueYearbookSnapshot(world, options.profileName, context.previousYear, context.previousMonth);
|
||||
},
|
||||
};
|
||||
|
||||
const close = async () => {
|
||||
await connector.disconnect();
|
||||
};
|
||||
|
||||
return { handler, close };
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
import type { GamePrisma, InputJsonValue } from '@sammo-ts/infra';
|
||||
import { LogCategory, LogScope } from '@sammo-ts/logic';
|
||||
|
||||
import type { PendingYearbookSnapshot } from './types.js';
|
||||
|
||||
const asJson = (value: unknown): InputJsonValue => value as InputJsonValue;
|
||||
|
||||
const computeHash = (payload: unknown): string => createHash('sha256').update(JSON.stringify(payload)).digest('hex');
|
||||
|
||||
export const persistYearbookSnapshot = async (
|
||||
transaction: GamePrisma.TransactionClient,
|
||||
snapshot: PendingYearbookSnapshot
|
||||
): Promise<void> => {
|
||||
const [historyRows, actionRows] = await Promise.all([
|
||||
transaction.logEntry.findMany({
|
||||
where: {
|
||||
scope: LogScope.SYSTEM,
|
||||
category: LogCategory.HISTORY,
|
||||
year: snapshot.year,
|
||||
month: snapshot.month,
|
||||
},
|
||||
orderBy: { id: 'desc' },
|
||||
select: { text: true },
|
||||
}),
|
||||
transaction.logEntry.findMany({
|
||||
where: {
|
||||
scope: LogScope.SYSTEM,
|
||||
category: LogCategory.ACTION,
|
||||
year: snapshot.year,
|
||||
month: snapshot.month,
|
||||
},
|
||||
orderBy: { id: 'desc' },
|
||||
select: { text: true },
|
||||
}),
|
||||
]);
|
||||
const globalHistory = historyRows.map((row) => row.text);
|
||||
const globalAction = actionRows.map((row) => row.text);
|
||||
const hash = computeHash({
|
||||
map: snapshot.map,
|
||||
nations: snapshot.nations,
|
||||
globalHistory,
|
||||
globalAction,
|
||||
});
|
||||
|
||||
await transaction.yearbookHistory.upsert({
|
||||
where: {
|
||||
profileName_year_month_sourceId: {
|
||||
profileName: snapshot.serverId,
|
||||
year: snapshot.year,
|
||||
month: snapshot.month,
|
||||
sourceId: snapshot.sourceId,
|
||||
},
|
||||
},
|
||||
update: {
|
||||
map: asJson(snapshot.map),
|
||||
nations: asJson(snapshot.nations),
|
||||
globalHistory: asJson(globalHistory),
|
||||
globalAction: asJson(globalAction),
|
||||
hash,
|
||||
},
|
||||
create: {
|
||||
profileName: snapshot.serverId,
|
||||
sourceId: snapshot.sourceId,
|
||||
year: snapshot.year,
|
||||
month: snapshot.month,
|
||||
map: asJson(snapshot.map),
|
||||
nations: asJson(snapshot.nations),
|
||||
globalHistory: asJson(globalHistory),
|
||||
globalAction: asJson(globalAction),
|
||||
hash,
|
||||
},
|
||||
});
|
||||
};
|
||||
Reference in New Issue
Block a user