feat: restore main record panels

This commit is contained in:
2026-07-26 08:55:06 +00:00
parent b9d22c75f5
commit 918d8f0e4c
9 changed files with 971 additions and 34 deletions
+62
View File
@@ -15,6 +15,18 @@ const zGeneralSettings = z.object({
});
const zGeneralLogType = z.enum(['generalHistory', 'battleDetail', 'battleResult', 'generalAction']);
const MAIN_RECORD_LIMIT = 15;
const trimRecentRecords = <Entry extends { id: number }>(entries: Entry[], cursor: number): Entry[] => {
if (entries.length === 0) {
return entries;
}
const result = [...entries];
if (result.at(-1)?.id === cursor || result.length > MAIN_RECORD_LIMIT) {
result.pop();
}
return result;
};
const readNumber = (value: unknown, fallback: number): number => {
if (typeof value === 'number' && Number.isFinite(value)) {
@@ -319,4 +331,54 @@ export const generalRouter = router({
})),
};
}),
getRecentRecords: authedProcedure
.input(
z.object({
lastGeneralRecordId: z.number().int().nonnegative().default(0),
lastWorldHistoryId: z.number().int().nonnegative().default(0),
})
)
.query(async ({ ctx, input }) => {
const me = await getMyGeneral(ctx);
const take = MAIN_RECORD_LIMIT + 1;
const [global, general, history] = await Promise.all([
ctx.db.logEntry.findMany({
where: {
scope: LogScope.SYSTEM,
category: LogCategory.SUMMARY,
id: { gte: input.lastGeneralRecordId },
},
orderBy: { id: 'desc' },
take,
select: { id: true, text: true },
}),
ctx.db.logEntry.findMany({
where: {
scope: LogScope.GENERAL,
category: LogCategory.ACTION,
generalId: me.id,
id: { gte: input.lastGeneralRecordId },
},
orderBy: { id: 'desc' },
take,
select: { id: true, text: true },
}),
ctx.db.logEntry.findMany({
where: {
scope: LogScope.SYSTEM,
category: LogCategory.HISTORY,
id: { gte: input.lastWorldHistoryId },
},
orderBy: { id: 'desc' },
take,
select: { id: true, text: true },
}),
]);
return {
global: trimRecentRecords(global, input.lastGeneralRecordId),
general: trimRecentRecords(general, input.lastGeneralRecordId),
history: trimRecentRecords(history, input.lastWorldHistoryId),
};
}),
});
+133
View File
@@ -0,0 +1,133 @@
import { describe, expect, it, vi } from 'vitest';
import type { GameSessionTokenPayload } from '@sammo-ts/common/auth/gameToken';
import { LogCategory, LogScope } from '@sammo-ts/infra';
import type { DatabaseClient, GameApiContext } from '../src/context.js';
import { appRouter } from '../src/router.js';
const auth: GameSessionTokenPayload = {
version: 1,
profile: 'che:default',
issuedAt: '2026-07-26T00:00:00.000Z',
expiresAt: '2026-07-27T00:00:00.000Z',
sessionId: 'session-owner',
user: {
id: 'owner',
username: 'owner',
displayName: 'Owner',
roles: [],
},
sanctions: {},
};
type LogQuery = {
where: {
scope: LogScope;
category: LogCategory;
generalId?: number;
id: { gte: number };
};
orderBy: { id: 'desc' };
take: number;
select: { id: true; text: true };
};
const buildContext = (findMany: (query: LogQuery) => Promise<Array<{ id: number; text: string }>>) =>
({
auth,
db: {
general: {
findFirst: vi.fn(async ({ where }: { where: { userId: string } }) => ({
id: 7,
userId: where.userId,
})),
},
logEntry: { findMany },
} as unknown as DatabaseClient,
}) as GameApiContext;
describe('general.getRecentRecords', () => {
it('derives the general and maps all three legacy dashboard buckets', async () => {
const findMany = vi.fn(async (query: LogQuery) => {
if (query.where.scope === LogScope.GENERAL) {
return [
{ id: 31, text: '개인 최신' },
{ id: 20, text: '개인 cursor' },
];
}
if (query.where.category === LogCategory.SUMMARY) {
return [
{ id: 32, text: '장수 최신' },
{ id: 20, text: '장수 cursor' },
];
}
return [
{ id: 42, text: '중원 최신' },
{ id: 40, text: '중원 cursor' },
];
});
const caller = appRouter.createCaller(buildContext(findMany));
const result = await caller.general.getRecentRecords({
lastGeneralRecordId: 20,
lastWorldHistoryId: 40,
});
expect(result).toEqual({
global: [{ id: 32, text: '장수 최신' }],
general: [{ id: 31, text: '개인 최신' }],
history: [{ id: 42, text: '중원 최신' }],
});
expect(findMany).toHaveBeenCalledTimes(3);
expect(findMany).toHaveBeenCalledWith({
where: {
scope: LogScope.GENERAL,
category: LogCategory.ACTION,
generalId: 7,
id: { gte: 20 },
},
orderBy: { id: 'desc' },
take: 16,
select: { id: true, text: true },
});
});
it('caps an initial bucket at the legacy 15-row limit', async () => {
const rows = Array.from({ length: 16 }, (_, index) => ({
id: 100 - index,
text: `기록 ${index}`,
}));
const caller = appRouter.createCaller(buildContext(async () => rows));
const result = await caller.general.getRecentRecords({
lastGeneralRecordId: 0,
lastWorldHistoryId: 0,
});
expect(result.global).toHaveLength(15);
expect(result.general).toHaveLength(15);
expect(result.history).toHaveLength(15);
expect(result.global.at(-1)?.id).toBe(86);
});
it('rejects an authenticated user without an in-game general', async () => {
const context = buildContext(async () => []);
context.db = {
general: {
findFirst: vi.fn(async () => null),
},
logEntry: {
findMany: vi.fn(async () => []),
},
} as unknown as DatabaseClient;
const caller = appRouter.createCaller(context);
await expect(
caller.general.getRecentRecords({
lastGeneralRecordId: 0,
lastWorldHistoryId: 0,
})
).rejects.toMatchObject({ code: 'NOT_FOUND' });
});
});
@@ -0,0 +1,41 @@
<script setup lang="ts">
defineProps<{
title: string;
}>();
</script>
<template>
<section class="record-panel">
<h2 class="record-title">{{ title }}</h2>
<div class="record-body">
<slot />
</div>
</section>
</template>
<style scoped>
.record-panel {
min-width: 0;
color: #fff;
font-size: 14px;
font-weight: 400;
line-height: 21px;
}
.record-title {
box-sizing: border-box;
height: 23px;
margin: 0;
border-top: 1px solid gray;
border-bottom: 1px solid gray;
background-color: #14241b;
background-image: url('/image/game/back_green.jpg');
color: #fff;
font: inherit;
text-align: center;
}
.record-body {
padding: 0;
}
</style>
+56 -1
View File
@@ -26,9 +26,11 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => {
type MessageContacts = Awaited<ReturnType<typeof trpc.messages.getContacts.query>>;
type BoardAccess = Awaited<ReturnType<typeof trpc.board.getAccess.query>>;
type ReservedTurnView = Awaited<ReturnType<typeof trpc.turns.reserved.getGeneral.query>>[number];
type RecentRecord = Awaited<ReturnType<typeof trpc.general.getRecentRecords.query>>['global'][number];
const loading = ref(false);
const error = ref<string | null>(null);
const recordsError = ref<string | null>(null);
const realtimeEnabled = ref(true);
const realtimeStatus = ref<'idle' | 'connected' | 'paused'>('idle');
@@ -42,6 +44,12 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => {
const boardAccess = ref<BoardAccess | null>(null);
const reservedGeneralTurns = ref<ReservedTurnView[] | null>(null);
const reservedNationTurns = ref<ReservedTurnView[] | null>(null);
const globalRecords = ref<RecentRecord[]>([]);
const generalRecords = ref<RecentRecord[]>([]);
const worldHistory = ref<RecentRecord[]>([]);
let lastGeneralRecordId = 0;
let lastWorldHistoryId = 0;
let recordGeneralId: number | null = null;
const messageDraftText = ref('');
const targetMailbox = ref<number>(MESSAGE_MAILBOX_PUBLIC);
@@ -191,12 +199,30 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => {
}
};
const mergeRecentRecords = (current: RecentRecord[], incoming: RecentRecord[]): RecentRecord[] => {
const merged = new Map(current.map((entry) => [entry.id, entry]));
for (const entry of incoming) {
merged.set(entry.id, entry);
}
return [...merged.values()].sort((left, right) => right.id - left.id).slice(0, 15);
};
const resetRecentRecords = (id: number | null) => {
globalRecords.value = [];
generalRecords.value = [];
worldHistory.value = [];
lastGeneralRecordId = 0;
lastWorldHistoryId = 0;
recordGeneralId = id;
};
const loadMainData = async () => {
if (loading.value) {
return;
}
loading.value = true;
error.value = null;
recordsError.value = null;
try {
const context = await trpc.general.me.query();
@@ -206,18 +232,31 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => {
reservedGeneralTurns.value = null;
reservedNationTurns.value = null;
boardAccess.value = null;
resetRecentRecords(null);
loading.value = false;
return;
}
const id = context.general.id;
if (recordGeneralId !== id) {
resetRecentRecords(id);
}
const layoutPromise = mapLayout.value ? Promise.resolve(mapLayout.value) : trpc.world.getMapLayout.query();
const generalTurnsPromise = trpc.turns.reserved.getGeneral.query({ generalId: id });
const nationTurnsPromise =
context.general.nationId > 0 && context.general.officerLevel >= 5
? trpc.turns.reserved.getNation.query({ generalId: id })
: Promise.resolve(null);
const [layout, lobby, map, commands, messageData, contacts, access, generalTurns, nationTurns] =
const recordsPromise = trpc.general.getRecentRecords
.query({
lastGeneralRecordId,
lastWorldHistoryId,
})
.catch((err: unknown) => {
recordsError.value = resolveErrorMessage(err);
return null;
});
const [layout, lobby, map, commands, messageData, contacts, access, generalTurns, nationTurns, records] =
await Promise.all([
layoutPromise,
trpc.lobby.info.query(),
@@ -228,6 +267,7 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => {
trpc.board.getAccess.query(),
generalTurnsPromise,
nationTurnsPromise,
recordsPromise,
]);
mapLayout.value = layout;
@@ -239,6 +279,17 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => {
boardAccess.value = access;
reservedGeneralTurns.value = generalTurns;
reservedNationTurns.value = nationTurns;
if (records) {
globalRecords.value = mergeRecentRecords(globalRecords.value, records.global);
generalRecords.value = mergeRecentRecords(generalRecords.value, records.general);
worldHistory.value = mergeRecentRecords(worldHistory.value, records.history);
lastGeneralRecordId = Math.max(
lastGeneralRecordId,
records.global[0]?.id ?? 0,
records.general[0]?.id ?? 0
);
lastWorldHistoryId = Math.max(lastWorldHistoryId, records.history[0]?.id ?? 0);
}
if (initializedMailboxGeneralId !== id) {
targetMailbox.value = MESSAGE_MAILBOX_NATIONAL_BASE + context.general.nationId;
initializedMailboxGeneralId = id;
@@ -587,6 +638,7 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => {
return {
loading,
error,
recordsError,
realtimeEnabled,
realtimeStatus,
generalContext,
@@ -603,6 +655,9 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => {
boardAccess,
reservedGeneralTurns,
reservedNationTurns,
globalRecords,
generalRecords,
worldHistory,
messageDraftText,
targetMailbox,
mailboxGroups,
+128 -33
View File
@@ -11,13 +11,15 @@ import CityBasicCard from '../components/main/CityBasicCard.vue';
import NationBasicCard from '../components/main/NationBasicCard.vue';
import MessagePanel from '../components/main/MessagePanel.vue';
import SelectedCityPanel from '../components/main/SelectedCityPanel.vue';
import RecordPanel from '../components/main/RecordPanel.vue';
import { formatLog } from '../utils/formatLog';
import { useSessionStore } from '../stores/session';
import { useMainDashboardStore } from '../stores/mainDashboard';
import { trpc } from '../utils/trpc';
const session = useSessionStore();
const dashboard = useMainDashboardStore();
const isMobile = useMediaQuery('(max-width: 1024px)');
const isMobile = useMediaQuery('(max-width: 991px)');
const mobileTabs = [
{ key: 'map', label: '지도' },
@@ -35,11 +37,11 @@ const tournamentStage = ref(0);
const {
loading,
error,
recordsError,
realtimeEnabled,
general,
city,
nation,
lobbyInfo,
worldMap,
mapLayout,
selectedCity,
@@ -48,6 +50,9 @@ const {
boardAccess,
reservedGeneralTurns,
reservedNationTurns,
globalRecords,
generalRecords,
worldHistory,
messageDraftText,
targetMailbox,
mailboxGroups,
@@ -203,23 +208,49 @@ watch(
</PanelCard>
</div>
<div v-if="mobileTab === 'world'" class="mobile-panel">
<PanelCard title="장수 동향">
<div v-if="mobileTab === 'world'" class="mobile-panel record-zone-mobile">
<RecordPanel title="장수 동향">
<SkeletonLines v-if="loading" :lines="4" />
<div v-else class="placeholder">장수 동향은 실시간 스트림으로 연결 예정</div>
</PanelCard>
<PanelCard title="개인 기록">
<SkeletonLines v-if="loading" :lines="4" />
<div v-else class="placeholder">개인 기록 영역</div>
</PanelCard>
<PanelCard title="중원 정세">
<SkeletonLines v-if="loading" :lines="4" />
<div v-else class="placeholder">
<div>유저 {{ lobbyInfo?.userCnt ?? '-' }} / {{ lobbyInfo?.maxUserCnt ?? '-' }}</div>
<div>NPC {{ lobbyInfo?.npcCnt ?? '-' }}</div>
<div>세력 {{ lobbyInfo?.nationCnt ?? '-' }}</div>
<div v-else-if="recordsError" class="record-error" role="alert">{{ recordsError }}</div>
<div v-else class="record-list" data-record-bucket="global">
<!-- eslint-disable-next-line vue/no-v-html -->
<div
v-for="entry in globalRecords"
:key="entry.id"
class="record-line"
v-html="formatLog(entry.text)"
/>
<div v-if="globalRecords.length === 0" class="record-empty">기록이 없습니다.</div>
</div>
</PanelCard>
</RecordPanel>
<RecordPanel title="개인 기록">
<SkeletonLines v-if="loading" :lines="4" />
<div v-else-if="recordsError" class="record-error" role="alert">{{ recordsError }}</div>
<div v-else class="record-list" data-record-bucket="general">
<!-- eslint-disable-next-line vue/no-v-html -->
<div
v-for="entry in generalRecords"
:key="entry.id"
class="record-line"
v-html="formatLog(entry.text)"
/>
<div v-if="generalRecords.length === 0" class="record-empty">기록이 없습니다.</div>
</div>
</RecordPanel>
<RecordPanel title="중원 정세">
<SkeletonLines v-if="loading" :lines="4" />
<div v-else-if="recordsError" class="record-error" role="alert">{{ recordsError }}</div>
<div v-else class="record-list" data-record-bucket="history">
<!-- eslint-disable-next-line vue/no-v-html -->
<div
v-for="entry in worldHistory"
:key="entry.id"
class="record-line"
v-html="formatLog(entry.text)"
/>
<div v-if="worldHistory.length === 0" class="record-empty">기록이 없습니다.</div>
</div>
</RecordPanel>
</div>
<div v-if="mobileTab === 'messages'" class="mobile-panel">
@@ -254,14 +285,6 @@ watch(
<PanelCard title="선택 도시">
<SelectedCityPanel :city="selectedCity" :loading="loading" />
</PanelCard>
<PanelCard title="중원 정세">
<SkeletonLines v-if="loading" :lines="3" />
<div v-else class="placeholder">
<div>유저 {{ lobbyInfo?.userCnt ?? '-' }} / {{ lobbyInfo?.maxUserCnt ?? '-' }}</div>
<div>NPC {{ lobbyInfo?.npcCnt ?? '-' }}</div>
<div>세력 {{ lobbyInfo?.nationCnt ?? '-' }}</div>
</div>
</PanelCard>
</div>
<div class="stack">
@@ -282,21 +305,57 @@ watch(
<PanelCard title="장수 스탯">
<GeneralBasicCard :general="general" :loading="loading" />
</PanelCard>
<PanelCard title="장수 동향">
<SkeletonLines v-if="loading" :lines="4" />
<div v-else class="placeholder">장수 동향은 실시간 스트림으로 연결 예정</div>
</PanelCard>
<PanelCard title="도시 정보">
<CityBasicCard :city="city" :loading="loading" />
</PanelCard>
<PanelCard title="국가 정보">
<NationBasicCard :nation="nation" :loading="loading" />
</PanelCard>
<PanelCard title="개인 기록">
<SkeletonLines v-if="loading" :lines="4" />
<div v-else class="placeholder">개인 기록 영역</div>
</PanelCard>
</div>
<section class="record-zone">
<RecordPanel title="장수 동향">
<SkeletonLines v-if="loading" :lines="4" />
<div v-else-if="recordsError" class="record-error" role="alert">{{ recordsError }}</div>
<div v-else class="record-list" data-record-bucket="global">
<!-- eslint-disable-next-line vue/no-v-html -->
<div
v-for="entry in globalRecords"
:key="entry.id"
class="record-line"
v-html="formatLog(entry.text)"
/>
<div v-if="globalRecords.length === 0" class="record-empty">기록이 없습니다.</div>
</div>
</RecordPanel>
<RecordPanel title="개인 기록">
<SkeletonLines v-if="loading" :lines="4" />
<div v-else-if="recordsError" class="record-error" role="alert">{{ recordsError }}</div>
<div v-else class="record-list" data-record-bucket="general">
<!-- eslint-disable-next-line vue/no-v-html -->
<div
v-for="entry in generalRecords"
:key="entry.id"
class="record-line"
v-html="formatLog(entry.text)"
/>
<div v-if="generalRecords.length === 0" class="record-empty">기록이 없습니다.</div>
</div>
</RecordPanel>
<RecordPanel class="world-history-panel" title="중원 정세">
<SkeletonLines v-if="loading" :lines="4" />
<div v-else-if="recordsError" class="record-error" role="alert">{{ recordsError }}</div>
<div v-else class="record-list" data-record-bucket="history">
<!-- eslint-disable-next-line vue/no-v-html -->
<div
v-for="entry in worldHistory"
:key="entry.id"
class="record-line"
v-html="formatLog(entry.text)"
/>
<div v-if="worldHistory.length === 0" class="record-empty">기록이 없습니다.</div>
</div>
</RecordPanel>
</section>
<MessagePanel
class="desktop-message-panel"
:messages="messages"
@@ -415,6 +474,42 @@ button {
grid-column: 1 / -1;
}
.record-zone {
grid-column: 1 / -1;
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0;
width: calc(100% + 48px);
margin-left: -24px;
}
.world-history-panel {
grid-column: 1 / -1;
}
.record-list {
min-height: 21px;
line-height: 21px;
}
.record-line {
overflow-wrap: anywhere;
}
.record-empty {
color: #aaa;
}
.record-error {
color: #ff8a80;
}
.record-zone-mobile {
width: 100vw;
margin-left: -24px;
gap: 0;
}
.mobile-message-panel {
width: 100vw;
min-width: 0;