feat: 플레이 감사 장수 로그를 기수별로 조회

This commit is contained in:
2026-09-16 04:03:14 +00:00
parent 69a61b317c
commit 31c5927449
20 changed files with 437 additions and 21 deletions
@@ -59,7 +59,8 @@ const persistLogs = async (
logs: LogEntryDraft[],
year: number,
month: number,
at: Date
at: Date,
serverId: string | null
): Promise<void> => {
const data = logs.flatMap((entry) => {
const record = finalizeLogEntry(entry, { year, month, at });
@@ -68,6 +69,7 @@ const persistLogs = async (
}
return [
{
serverId,
scope: record.scope,
category: record.category,
subType: record.subType ?? null,
@@ -92,7 +94,8 @@ const persistEffects = async (
effects: GeneralActionEffect[],
year: number,
month: number,
at: Date
at: Date,
serverId: string | null
): Promise<void> => {
const logs: LogEntryDraft[] = [];
for (const effect of effects) {
@@ -122,7 +125,7 @@ const persistEffects = async (
logs.push(effect.entry);
}
}
await persistLogs(db, orderLegacyActionLoggerFlush(logs), year, month, at);
await persistLogs(db, orderLegacyActionLoggerFlush(logs), year, month, at, serverId);
};
const refreshFrontStates = async (db: DatabaseClient, mapName: string, nationIds: number[]): Promise<number[]> => {
@@ -187,11 +190,13 @@ export const respondToDiplomaticMessage = async (options: {
}
const world = await db.worldState.findFirst({
select: { currentYear: true, currentMonth: true, config: true },
select: { currentYear: true, currentMonth: true, config: true, meta: true },
});
if (!world) {
throw new TRPCError({ code: 'PRECONDITION_FAILED', message: '게임 상태가 없습니다.' });
}
const serverIdValue = asRecord(world.meta).serverId;
const serverId = typeof serverIdValue === 'string' && serverIdValue.trim() ? serverIdValue : null;
const now = (await loadCurrentGameTime(db)).now;
const action = parseAction(message.payload.option?.action);
if (message.msgType !== 'diplomacy' || !action || message.payload.option?.used) {
@@ -204,7 +209,8 @@ export const respondToDiplomaticMessage = async (options: {
buildFailureLog(actor.id, reason, actionName, response),
world.currentYear,
world.currentMonth,
now
now,
serverId
);
return {
result: false,
@@ -302,7 +308,8 @@ export const respondToDiplomaticMessage = async (options: {
[...actorLogger.flush(), ...proposerLogger.flush()],
world.currentYear,
world.currentMonth,
now
now,
serverId
);
await invalidateMessages(db, [message.id]);
return {
@@ -414,7 +421,7 @@ export const respondToDiplomaticMessage = async (options: {
...(action === 'noAggression' ? { treatyYear: treatyYear!, treatyMonth: treatyMonth! } : {}),
}
);
await persistEffects(db, resolution.effects, world.currentYear, world.currentMonth, now);
await persistEffects(db, resolution.effects, world.currentYear, world.currentMonth, now, serverId);
let affectedCityIds: number[] = [];
if (resolution.refreshFront) {
const worldConfig = asRecord(world.config);
@@ -1,5 +1,6 @@
import { nationSeries, zAuditNation } from './nationSeries.js';
import { cityDetail, generalDetail, generalTurns } from './details.js';
import { generalLogs } from './logs.js';
import { z } from 'zod';
import { canReadPlayAuditAccounts } from '@sammo-ts/common';
import { router } from '../../trpc.js';
@@ -22,6 +23,7 @@ import {
} from './projection.js';
export const playAuditRouter = router({
generalLogs,
cityDetail,
generalDetail,
generalTurns,
+60
View File
@@ -0,0 +1,60 @@
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { auditProcedure, monthOrdinal, readAudit, readAuditWorld } from './shared.js';
const categoryByType = {
generalHistory: 'HISTORY',
generalAction: 'ACTION',
battleResult: 'BATTLE_BRIEF',
battleDetail: 'BATTLE_DETAIL',
} as const;
export const generalLogs = auditProcedure
.input(
z
.object({
generalId: z.number().int().nonnegative(),
type: z.enum(['generalHistory', 'generalAction', 'battleResult', 'battleDetail']),
month: z
.object({ year: z.number().int().min(0).max(9999), month: z.number().int().min(1).max(12) })
.strict()
.optional(),
cursor: z.number().int().positive().optional(),
limit: z.number().int().min(1).max(200).default(50),
})
.strict()
)
.query(({ ctx, input }) =>
readAudit(ctx, async (tx) => {
const world = await readAuditWorld(tx);
if (
input.month &&
(input.month.year < world.startYear ||
monthOrdinal(input.month.year, input.month.month) > monthOrdinal(world.year, world.month))
) {
throw new TRPCError({ code: 'BAD_REQUEST', message: '현재 기수 안의 로그 월을 선택해 주세요.' });
}
const rows = world.serverId
? await tx.logEntry.findMany({
where: {
serverId: world.serverId,
generalId: input.generalId,
scope: 'GENERAL',
category: categoryByType[input.type],
id: input.cursor === undefined ? undefined : { lt: input.cursor },
year: input.month?.year,
month: input.month?.month,
},
orderBy: { id: 'desc' },
take: input.limit + 1,
select: { id: true, year: true, month: true, text: true, createdAt: true },
})
: [];
return {
...world,
type: input.type,
coverage: world.serverId ? ('IDENTIFIED_LOGS_ONLY' as const) : ('IDENTITY_MISSING' as const),
items: rows.slice(0, input.limit),
nextCursor: rows.length > input.limit ? rows[input.limit - 1]!.id : null,
};
})
);
+13
View File
@@ -1049,6 +1049,7 @@ describe('messages router missing-flow compatibility', () => {
findFirst: vi.fn(async () => ({
currentYear: 200,
currentMonth: 3,
meta: { serverId: 'diplomatic-response-audit' },
config: { environment: { mapName: 'che' } },
clockBaseTime: new Date('0200-03-01T00:00:00.000Z'),
clockTick: 1_000n,
@@ -1116,6 +1117,9 @@ describe('messages router missing-flow compatibility', () => {
cityIds: [],
});
expect(setup.diplomacyUpdate).toHaveBeenCalledTimes(2);
expect(setup.logCreateMany).toHaveBeenCalledWith({
data: expect.arrayContaining([expect.objectContaining({ serverId: 'diplomatic-response-audit' })]),
});
expect(setup.nationUpdate).toHaveBeenCalledWith(
expect.objectContaining({
where: { id: 2 },
@@ -1147,6 +1151,9 @@ describe('messages router missing-flow compatibility', () => {
expect(setup.diplomacyUpdate).not.toHaveBeenCalled();
expect(setup.messageUpdateMany).toHaveBeenCalledOnce();
expect(setup.logCreateMany).toHaveBeenCalledOnce();
expect(setup.logCreateMany).toHaveBeenCalledWith({
data: expect.arrayContaining([expect.objectContaining({ serverId: 'diplomatic-response-audit' })]),
});
});
it('permanently records rejection of an NPC aid-based non-aggression proposal', async () => {
@@ -1217,6 +1224,9 @@ describe('messages router missing-flow compatibility', () => {
expect(result).toEqual({ result: true, reason: 'success' });
expect(setup.diplomacyUpdate).toHaveBeenCalledTimes(2);
expect(setup.logCreateMany).toHaveBeenCalledWith({
data: expect.arrayContaining([expect.objectContaining({ serverId: 'diplomatic-response-audit' })]),
});
if (action === 'stopWar') {
expect(setup.cityUpdate).toHaveBeenCalledTimes(2);
expect(setup.cityUpdate).toHaveBeenCalledWith({
@@ -1255,6 +1265,9 @@ describe('messages router missing-flow compatibility', () => {
expect(setup.diplomacyUpdate).not.toHaveBeenCalled();
expect(setup.messageUpdateMany).not.toHaveBeenCalled();
expect(setup.logCreateMany).toHaveBeenCalledOnce();
expect(setup.logCreateMany).toHaveBeenCalledWith({
data: expect.arrayContaining([expect.objectContaining({ serverId: 'diplomatic-response-audit' })]),
});
});
it('does not let another nation process the diplomatic inbox row', async () => {
@@ -2238,6 +2238,87 @@ integration('game API security over HTTP transport', () => {
});
const admin = await token([`admin.playAudit.read:${profileName}`]);
const beforeInputs = await db.inputEvent.count();
const logGeneralId = 99129; // No live general: death must not hide retained records.
const ownLogs = await Promise.all(
['HISTORY', 'ACTION', 'BATTLE_BRIEF', 'BATTLE_DETAIL'].map((category) =>
db.logEntry.create({
data: {
serverId: seasonId,
generalId: logGeneralId,
scope: 'GENERAL',
category: category as 'HISTORY' | 'ACTION' | 'BATTLE_BRIEF' | 'BATTLE_DETAIL',
year: 190,
month: 1,
text: `${seasonId}:${category}`,
},
})
)
);
const latest = await db.logEntry.create({
data: {
serverId: seasonId,
generalId: logGeneralId,
scope: 'GENERAL',
category: 'HISTORY',
year: 190,
month: 2,
text: `${seasonId}:latest`,
},
});
await db.logEntry.createMany({
data: [null, `${seasonId}:previous`].map((serverId) => ({
serverId,
generalId: logGeneralId,
scope: 'GENERAL' as const,
category: 'HISTORY' as const,
year: 190,
month: 1,
text: `${seasonId}:excluded`,
})),
});
for (const [index, type] of ['generalHistory', 'generalAction', 'battleResult', 'battleDetail'].entries()) {
const result = await get('generalLogs', admin, {
generalId: logGeneralId,
type,
month: { year: 190, month: 1 },
});
expect(result.status).toBe(200);
expect(result.body).toMatchObject({
result: {
data: {
coverage: 'IDENTIFIED_LOGS_ONLY',
items: [{ id: ownLogs[index]!.id }],
nextCursor: null,
},
},
});
expect(JSON.stringify(result.body)).not.toContain(`${seasonId}:excluded`);
}
expect(
(await get('generalLogs', admin, { generalId: logGeneralId, type: 'generalHistory', limit: 1 })).body
).toMatchObject({ result: { data: { items: [{ id: latest.id }], nextCursor: latest.id } } });
expect(
(
await get('generalLogs', admin, {
generalId: logGeneralId,
type: 'generalHistory',
limit: 1,
cursor: latest.id,
})
).body
).toMatchObject({ result: { data: { items: [{ id: ownLogs[0]!.id }], nextCursor: null } } });
for (const invalid of [
{ limit: 201 },
{ cursor: 0 },
{ month: { year: 190, month: 3 } },
{ month: { year: 189, month: 12 } },
]) {
expect(
(await get('generalLogs', admin, { generalId: logGeneralId, type: 'generalHistory', ...invalid }))
.status
).toBe(400);
}
expect((await get('generalDetail', admin, { id: generalId })).body).toMatchObject({
result: { data: { collected: true, general: { id: generalId, name: current.name } } },
});
@@ -2512,6 +2593,7 @@ integration('game API security over HTTP transport', () => {
);
await expect.poll(async () => (await get('capabilities', admin)).status).toBe(401);
} finally {
await db.logEntry.deleteMany({ where: { text: { startsWith: `${seasonId}:` } } });
await db.playAuditMonth.deleteMany({ where: { serverId: seasonId } });
await db.generalTurn.deleteMany({ where: { generalId, turnIdx: { in: [9001, 9002] } } });
await db.nation.deleteMany({ where: { id: { in: [99121, 99122] } } });
@@ -338,7 +338,7 @@ integration('scenario 903 select pool through the durable turn daemon', () => {
).toBe(initial.name);
expect(
await db.logEntry.count({
where: { meta: { path: ['ownerUserId'], equals: userId } },
where: { serverId: profile, meta: { path: ['ownerUserId'], equals: userId } },
})
).toBe(2);
if (realtimeHub) {
@@ -432,7 +432,7 @@ integration('scenario 903 select pool through the durable turn daemon', () => {
).toBe(target.uniqueName);
expect(
await db.logEntry.count({
where: { meta: { path: ['ownerUserId'], equals: userId } },
where: { serverId: profile, meta: { path: ['ownerUserId'], equals: userId } },
})
).toBe(4);