From 0127fd501a36c47764ec538bb0f2e4998a9de0ae Mon Sep 17 00:00:00 2001 From: hided62 Date: Sun, 26 Jul 2026 05:20:32 +0000 Subject: [PATCH 01/16] Complete legacy-compatible in-game information menus --- app/game-api/src/router/general/index.ts | 39 +- .../router/nation/endpoints/getGeneralList.ts | 317 +++++- app/game-api/src/router/nation/index.ts | 3 +- app/game-api/src/router/public/index.ts | 117 ++ .../test/inGameMenuPermissions.test.ts | 257 +++++ .../test/nationGeneralSecretRouter.test.ts | 209 ++++ app/game-api/test/publicTraffic.test.ts | 115 ++ .../src/turn/worldCommandHandler.ts | 77 +- .../test/myInformationCommands.test.ts | 179 +++ app/game-frontend/e2e/inGameMenus.spec.ts | 314 +++++ app/game-frontend/e2e/playwright.config.mjs | 2 +- app/game-frontend/src/router/index.ts | 20 +- .../src/views/BattleCenterView.vue | 236 +++- app/game-frontend/src/views/MainView.vue | 7 +- app/game-frontend/src/views/MyPageView.vue | 1010 +++++++++-------- .../src/views/NationGeneralsView.vue | 538 ++++----- .../src/views/NationSecretView.vue | 250 ++++ app/game-frontend/src/views/PublicView.vue | 1 + app/game-frontend/src/views/TrafficView.vue | 343 ++++++ .../reference-ingame-menus.mjs | 175 +++ 20 files changed, 3269 insertions(+), 940 deletions(-) create mode 100644 app/game-api/test/inGameMenuPermissions.test.ts create mode 100644 app/game-api/test/nationGeneralSecretRouter.test.ts create mode 100644 app/game-api/test/publicTraffic.test.ts create mode 100644 app/game-engine/test/myInformationCommands.test.ts create mode 100644 app/game-frontend/e2e/inGameMenus.spec.ts create mode 100644 app/game-frontend/src/views/NationSecretView.vue create mode 100644 app/game-frontend/src/views/TrafficView.vue create mode 100644 tools/frontend-legacy-parity/reference-ingame-menus.mjs diff --git a/app/game-api/src/router/general/index.ts b/app/game-api/src/router/general/index.ts index 97a0bf9..4405b25 100644 --- a/app/game-api/src/router/general/index.ts +++ b/app/game-api/src/router/general/index.ts @@ -37,15 +37,19 @@ const normalizeItemCode = (value: string | null): string | null => { }; const resolveUserSettings = (meta: Record) => { - const settings = asRecord(meta.userSettings); - const mysetRaw = settings.myset; + // The legacy general columns are persisted at the top level of General.meta. + // Keep reading the short-lived nested shape for installations that ran the + // initial rewrite implementation before this compatibility fix. + const nestedSettings = asRecord(meta.userSettings); + const readSetting = (key: string): unknown => meta[key] ?? nestedSettings[key]; + const mysetRaw = readSetting('myset'); const myset = typeof mysetRaw === 'number' && Number.isFinite(mysetRaw) ? mysetRaw : null; return { - tnmt: readNumber(settings.tnmt, 1), - defence_train: readNumber(settings.defence_train, 80), - use_treatment: readNumber(settings.use_treatment, 10), - use_auto_nation_turn: readNumber(settings.use_auto_nation_turn, 1), + tnmt: readNumber(readSetting('tnmt'), 1), + defence_train: readNumber(readSetting('defence_train'), 80), + use_treatment: readNumber(readSetting('use_treatment'), 10), + use_auto_nation_turn: readNumber(readSetting('use_auto_nation_turn'), 1), myset, }; }; @@ -262,29 +266,6 @@ export const generalRouter = router({ throw new TRPCError({ code: 'BAD_REQUEST', message: result.reason }); } - const metaRecord = asRecord(general.meta); - const prevSettings = asRecord(metaRecord.userSettings); - const prevMyset = typeof prevSettings.myset === 'number' && Number.isFinite(prevSettings.myset) - ? prevSettings.myset - : null; - const nextSettings = { - ...prevSettings, - ...input, - } as Record; - if (typeof prevMyset === 'number') { - nextSettings.myset = Math.max(0, prevMyset - 1); - } - - await ctx.db.general.update({ - where: { id: general.id }, - data: { - meta: { - ...metaRecord, - userSettings: nextSettings, - }, - } as any, - }); - return { ok: true }; }), dropItem: authedProcedure.input(z.object({ itemType: z.string() })).mutation(async ({ ctx, input }) => { diff --git a/app/game-api/src/router/nation/endpoints/getGeneralList.ts b/app/game-api/src/router/nation/endpoints/getGeneralList.ts index 8223e9b..171e452 100644 --- a/app/game-api/src/router/nation/endpoints/getGeneralList.ts +++ b/app/game-api/src/router/nation/endpoints/getGeneralList.ts @@ -1,84 +1,279 @@ import { TRPCError } from '@trpc/server'; +import { asRecord } from '@sammo-ts/common'; + +import type { GameApiContext } from '../../../context.js'; import { authedProcedure } from '../../../trpc.js'; import { getMyGeneral } from '../../shared/general.js'; -import { assertNationAccess, loadTraitNames, mapGeneralList, resolveChiefStatMin } from '../shared.js'; +import { + assertNationAccess, + loadTraitNames, + resolveNationPermission, + resolveOfficerCity, +} from '../shared.js'; -export const getGeneralList = authedProcedure.query(async ({ ctx }) => { - const general = await getMyGeneral(ctx); - assertNationAccess(general); +const MAX_DEDICATION_LEVEL = 10; - const [nation, cityRows, troopRows, generalRows, worldState] = await Promise.all([ - ctx.db.nation.findUnique({ - where: { id: general.nationId }, - select: { - id: true, - name: true, - color: true, - level: true, - typeCode: true, - capitalCityId: true, - meta: true, - }, - }), - ctx.db.city.findMany({ select: { id: true, name: true } }), - ctx.db.troop.findMany({ select: { troopLeaderId: true, name: true } }), - ctx.db.general.findMany({ - where: { nationId: general.nationId }, - select: { - id: true, - name: true, - npcState: true, - nationId: true, - cityId: true, - troopId: true, - picture: true, - imageServer: true, - officerLevel: true, - leadership: true, - strength: true, - intel: true, - experience: true, - dedication: true, - injury: true, - gold: true, - rice: true, - crew: true, - personalCode: true, - specialCode: true, - special2Code: true, - meta: true, - penalty: true, - }, - orderBy: { id: 'asc' }, - }), - ctx.db.worldState.findFirst(), - ]); +const readNumber = (record: Record, keys: string[], fallback = 0): number => { + for (const key of keys) { + const value = record[key]; + if (typeof value === 'number' && Number.isFinite(value)) { + return value; + } + } + return fallback; +}; +const experienceLevel = (experience: number): number => + Math.max(0, Math.min(100, experience < 1_000 ? Math.floor(experience / 100) : Math.floor(Math.sqrt(experience / 10)))); + +const dedicationLevel = (dedication: number): number => + Math.max(0, Math.min(MAX_DEDICATION_LEVEL, Math.ceil(Math.sqrt(Math.max(0, dedication)) / 10))); + +const dedicationLevelText = (level: number): string => + level === 0 ? '무품관' : `${MAX_DEDICATION_LEVEL - level + 1}품관`; + +const honorText = (experience: number): string => { + const levels: Array<[number, string]> = [ + [640, '전무'], + [2_560, '무명'], + [5_760, '신동'], + [10_240, '약간'], + [16_000, '평범'], + [23_040, '지역적'], + [31_360, '전국적'], + [40_960, '세계적'], + [45_000, '유명'], + [51_840, '명사'], + [55_000, '호걸'], + [64_000, '효웅'], + [77_440, '영웅'], + ]; + return levels.find(([limit]) => experience < limit)?.[1] ?? '구세주'; +}; + +const leadershipBonus = (officerLevel: number, nationLevel: number): number => { + if (officerLevel === 12) return nationLevel * 2; + if (officerLevel >= 5) return nationLevel; + return 0; +}; + +const woundedStat = (value: number, injury: number): number => + injury > 0 ? Math.floor((value * (100 - injury)) / 100) : value; + +const defenceTrainText = (value: number): string => { + if (value === 999) return '×'; + if (value >= 90) return '☆'; + if (value >= 80) return '◎'; + if (value >= 60) return '○'; + return '△'; +}; + +const loadNationGeneralData = async (ctx: GameApiContext) => { + const me = await getMyGeneral(ctx); + assertNationAccess(me); + + const nation = await ctx.db.nation.findUnique({ + where: { id: me.nationId }, + select: { + id: true, + name: true, + color: true, + level: true, + typeCode: true, + capitalCityId: true, + meta: true, + }, + }); if (!nation) { throw new TRPCError({ code: 'NOT_FOUND', message: 'Nation not found' }); } + const viewerPermission = resolveNationPermission(me, nation.meta, true); - const cityNameMap = new Map(cityRows.map((city) => [city.id, city.name])); - const troopNameMap = new Map(troopRows.map((troop) => [troop.troopLeaderId, troop.name])); - const list = await mapGeneralList(generalRows, cityNameMap, troopNameMap); - const nationTrait = (await loadTraitNames([nation.typeCode], 'nation')).get(nation.typeCode); + const [cityRows, troopRows, generalRows] = await Promise.all([ + ctx.db.city.findMany({ select: { id: true, name: true } }), + ctx.db.troop.findMany({ + where: { nationId: me.nationId }, + select: { troopLeaderId: true, name: true }, + }), + ctx.db.general.findMany({ + where: { nationId: me.nationId }, + orderBy: [{ turnTime: 'asc' }, { id: 'asc' }], + }), + ]); + const generalIds = generalRows.map((general) => general.id); + const [accessRows, turnRows] = await Promise.all([ + ctx.db.generalAccessLog.findMany({ + where: { generalId: { in: generalIds } }, + select: { generalId: true, refreshScore: true, refreshScoreTotal: true }, + }), + viewerPermission >= 1 + ? ctx.db.generalTurn.findMany({ + where: { generalId: { in: generalIds }, turnIdx: { lt: 5 } }, + select: { generalId: true, turnIdx: true, actionCode: true }, + orderBy: [{ generalId: 'asc' }, { turnIdx: 'asc' }], + }) + : Promise.resolve([]), + ]); + + const cityNames = new Map(cityRows.map((city) => [city.id, city.name])); + const troopNames = new Map(troopRows.map((troop) => [troop.troopLeaderId, troop.name])); + const accessByGeneral = new Map(accessRows.map((row) => [row.generalId, row])); + const turnsByGeneral = new Map(); + for (const turn of turnRows) { + const turns = turnsByGeneral.get(turn.generalId) ?? []; + turns[turn.turnIdx] = turn.actionCode; + turnsByGeneral.set(turn.generalId, turns); + } + + const [personalityMap, domesticMap, warMap] = await Promise.all([ + loadTraitNames(generalRows.map((general) => general.personalCode), 'personality'), + loadTraitNames(generalRows.map((general) => general.specialCode), 'domestic'), + loadTraitNames(generalRows.map((general) => general.special2Code), 'war'), + ]); + + const generals = generalRows.map((general) => { + const meta = asRecord(general.meta); + const officerCity = resolveOfficerCity(meta); + const access = accessByGeneral.get(general.id); + const dedLevel = dedicationLevel(general.dedication); + const actualOfficerLevel = general.officerLevel; + const visibleOfficerLevel = + viewerPermission >= 1 || actualOfficerLevel >= 5 ? actualOfficerLevel : Math.min(1, actualOfficerLevel); + const bonus = leadershipBonus(actualOfficerLevel, nation.level); + const detail = + viewerPermission >= 1 + ? { + officerLevel: actualOfficerLevel, + officerCity, + officerCityName: officerCity > 0 ? (cityNames.get(officerCity) ?? null) : null, + cityId: general.cityId, + cityName: cityNames.get(general.cityId) ?? null, + troopId: general.troopId, + troopName: troopNames.get(general.troopId) ?? null, + defenceTrain: readNumber(meta, ['defenceTrain', 'defence_train'], 80), + crewTypeId: general.crewTypeId, + crew: general.crew, + train: general.train, + atmos: general.atmos, + experience: general.experience, + dedication: general.dedication, + turnTime: general.turnTime.toISOString(), + recentWarTime: general.recentWarTime?.toISOString() ?? null, + killTurn: readNumber(meta, ['killturn', 'killTurn']), + refreshScore: access?.refreshScore ?? 0, + reservedCommands: general.npcState < 2 ? (turnsByGeneral.get(general.id) ?? []) : [], + } + : null; + + return { + id: general.id, + name: general.name, + npcState: general.npcState, + picture: general.picture, + imageServer: general.imageServer, + injury: general.injury, + stats: { + leadership: woundedStat(general.leadership, general.injury), + strength: woundedStat(general.strength, general.injury), + intelligence: woundedStat(general.intel, general.injury), + }, + leadershipBonus: bonus, + officerLevel: visibleOfficerLevel, + experienceLevel: experienceLevel(general.experience), + honorText: honorText(general.experience), + dedicationLevel: dedLevel, + dedicationLevelText: dedicationLevelText(dedLevel), + bill: dedLevel * 200 + 400, + gold: general.gold, + rice: general.rice, + age: general.age, + belong: readNumber(meta, ['belong']), + refreshScoreTotal: access?.refreshScoreTotal ?? 0, + personality: general.personalCode === 'None' ? null : (personalityMap.get(general.personalCode) ?? null), + specialDomestic: + general.specialCode === 'None' ? null : (domesticMap.get(general.specialCode) ?? null), + specialWar: general.special2Code === 'None' ? null : (warMap.get(general.special2Code) ?? null), + detail, + }; + }); return { + me, nation: { id: nation.id, name: nation.name, color: nation.color, level: nation.level, typeCode: nation.typeCode, - type: { - key: nation.typeCode, - name: nationTrait?.name ?? nation.typeCode, - info: nationTrait?.info ?? '', - }, capitalCityId: nation.capitalCityId ?? 0, }, - chiefStatMin: resolveChiefStatMin(worldState), - generals: list, + viewerPermission, + generals, + }; +}; + +export const getGeneralList = authedProcedure.query(async ({ ctx }) => { + const data = await loadNationGeneralData(ctx); + return { + nation: data.nation, + viewer: { generalId: data.me.id, permission: data.viewerPermission }, + generals: data.generals, + }; +}); + +export const getSecretGeneralList = authedProcedure.query(async ({ ctx }) => { + const data = await loadNationGeneralData(ctx); + if (data.viewerPermission < 1) { + throw new TRPCError({ + code: 'FORBIDDEN', + message: '권한이 부족합니다. 수뇌부가 아니거나 사관년도가 부족합니다.', + }); + } + + const visibleGenerals = data.generals.filter((general) => general.npcState !== 5); + const summaryBase = visibleGenerals.reduce( + (summary, general) => { + const detail = general.detail; + if (!detail) return summary; + summary.gold += general.gold; + summary.rice += general.rice; + summary.crew += detail.crew; + if (detail.crew > 0) { + for (const threshold of [90, 80, 60] as const) { + if (detail.train >= threshold && detail.atmos >= threshold) { + summary.readiness[threshold].crew += detail.crew; + summary.readiness[threshold].generals += 1; + } + } + } + return summary; + }, + { + gold: 0, + rice: 0, + crew: 0, + readiness: { + 90: { crew: 0, generals: 0 }, + 80: { crew: 0, generals: 0 }, + 60: { crew: 0, generals: 0 }, + }, + } + ); + const generalCount = visibleGenerals.length; + + return { + nation: data.nation, + viewer: { generalId: data.me.id, permission: data.viewerPermission }, + summary: { + ...summaryBase, + generalCount, + averageGold: generalCount ? summaryBase.gold / generalCount : 0, + averageRice: generalCount ? summaryBase.rice / generalCount : 0, + }, + generals: data.generals.map((general) => ({ + ...general, + defenceTrainText: defenceTrainText(general.detail?.defenceTrain ?? 0), + })), }; }); diff --git a/app/game-api/src/router/nation/index.ts b/app/game-api/src/router/nation/index.ts index e810b96..4fece4a 100644 --- a/app/game-api/src/router/nation/index.ts +++ b/app/game-api/src/router/nation/index.ts @@ -4,7 +4,7 @@ import { changePermission } from './endpoints/changePermission.js'; import { getBattleCenter } from './endpoints/getBattleCenter.js'; import { getChiefCenter } from './endpoints/getChiefCenter.js'; import { getCityOverview } from './endpoints/getCityOverview.js'; -import { getGeneralList } from './endpoints/getGeneralList.js'; +import { getGeneralList, getSecretGeneralList } from './endpoints/getGeneralList.js'; import { getGeneralLog } from './endpoints/getGeneralLog.js'; import { getNationInfo } from './endpoints/getNationInfo.js'; import { getPersonnelInfo } from './endpoints/getPersonnelInfo.js'; @@ -21,6 +21,7 @@ import { setSecretLimit } from './endpoints/setSecretLimit.js'; export const nationRouter = router({ getNationInfo, getGeneralList, + getSecretGeneralList, getCityOverview, getPersonnelInfo, getStratFinan, diff --git a/app/game-api/src/router/public/index.ts b/app/game-api/src/router/public/index.ts index e7a0f59..f4ef4d8 100644 --- a/app/game-api/src/router/public/index.ts +++ b/app/game-api/src/router/public/index.ts @@ -42,6 +42,14 @@ type NationCountRow = { type NpcListSort = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8; +type TrafficHistoryItem = { + year: number; + month: number; + refresh: number; + online: number; + date: string; +}; + const PUBLIC_CACHE_TTL_SECONDS = 600; const buildPublicCacheKey = (ctx: GameApiContext, key: string): string => @@ -163,6 +171,26 @@ const readFiniteMetaNumber = (meta: Record, key: string): numbe return typeof value === 'number' && Number.isFinite(value) ? value : 0; }; +const parseTrafficHistory = (value: unknown): TrafficHistoryItem[] => { + if (!Array.isArray(value)) { + return []; + } + + const result: TrafficHistoryItem[] = []; + for (const item of value) { + const row = asRecord(item); + const year = readFiniteMetaNumber(row, 'year'); + const month = readFiniteMetaNumber(row, 'month'); + const refresh = readFiniteMetaNumber(row, 'refresh'); + const online = readFiniteMetaNumber(row, 'online'); + const date = typeof row.date === 'string' ? row.date : ''; + if (year > 0 && month > 0 && date) { + result.push({ year, month, refresh, online, date }); + } + } + return result; +}; + const compareString = (left: string, right: string): number => { if (left === right) { return 0; @@ -222,6 +250,95 @@ export const publicRouter = router({ getNationList: procedure.query(async ({ ctx }) => { return loadCachedNationList(ctx); }), + getTraffic: procedure.query(async ({ ctx }) => { + const worldState = await ctx.db.worldState.findFirst(); + if (!worldState) { + throw new TRPCError({ + code: 'PRECONDITION_FAILED', + message: 'World state is not initialized.', + }); + } + + const meta = asRecord(worldState.meta); + const rawOnlineSince = meta.lastTurnTime ?? meta.turntime; + const parsedOnlineSince = + typeof rawOnlineSince === 'string' || rawOnlineSince instanceof Date + ? new Date(rawOnlineSince) + : null; + const onlineSince = + parsedOnlineSince && Number.isFinite(parsedOnlineSince.getTime()) + ? parsedOnlineSince + : new Date(Date.now() - worldState.tickSeconds * 1_000); + const [accessTotal, currentOnline, topAccess] = await Promise.all([ + ctx.db.generalAccessLog.aggregate({ + _sum: { + refresh: true, + refreshScoreTotal: true, + }, + }), + ctx.db.generalAccessLog.count({ + where: { + lastRefresh: { + gte: onlineSince, + }, + }, + }), + ctx.db.generalAccessLog.findMany({ + orderBy: [{ refresh: 'desc' }, { generalId: 'asc' }], + take: 5, + select: { + generalId: true, + refresh: true, + refreshScoreTotal: true, + }, + }), + ]); + + const generalIds = topAccess.map((entry) => entry.generalId); + const generalRows = + generalIds.length > 0 + ? await ctx.db.general.findMany({ + where: { id: { in: generalIds } }, + select: { id: true, name: true }, + }) + : []; + const generalName = new Map(generalRows.map((general) => [general.id, general.name])); + const totalRefresh = accessTotal._sum.refresh ?? 0; + const totalRefreshScore = accessTotal._sum.refreshScoreTotal ?? 0; + const currentRefresh = Math.max(readFiniteMetaNumber(meta, 'refresh'), totalRefresh); + const history = parseTrafficHistory(meta.recentTraffic); + history.push({ + year: worldState.currentYear, + month: worldState.currentMonth, + refresh: currentRefresh, + online: currentOnline, + date: new Date().toISOString(), + }); + + return { + history, + maxRefresh: Math.max( + 1, + readFiniteMetaNumber(meta, 'maxrefresh'), + ...history.map((entry) => entry.refresh) + ), + maxOnline: Math.max(1, readFiniteMetaNumber(meta, 'maxonline'), ...history.map((entry) => entry.online)), + suspects: [ + { + generalId: null, + name: '접속자 총합', + refresh: totalRefresh, + refreshScoreTotal: totalRefreshScore, + }, + ...topAccess.map((entry) => ({ + generalId: entry.generalId, + name: generalName.get(entry.generalId) ?? `장수 ${entry.generalId}`, + refresh: entry.refresh, + refreshScoreTotal: entry.refreshScoreTotal, + })), + ], + }; + }), getGeneralList: procedure.query(async ({ ctx }) => { const [generals, nations] = await Promise.all([ ctx.db.general.findMany({ diff --git a/app/game-api/test/inGameMenuPermissions.test.ts b/app/game-api/test/inGameMenuPermissions.test.ts new file mode 100644 index 0000000..ea2263c --- /dev/null +++ b/app/game-api/test/inGameMenuPermissions.test.ts @@ -0,0 +1,257 @@ +import { describe, expect, it, vi } from 'vitest'; + +import type { GameSessionTokenPayload } from '@sammo-ts/common/auth/gameToken'; +import type { RedisConnector } from '@sammo-ts/infra'; + +import { RedisAccessTokenStore } from '../src/auth/accessTokenStore.js'; +import { InMemoryFlushStore } from '../src/auth/flushStore.js'; +import type { DatabaseClient, GameApiContext, GeneralRow } from '../src/context.js'; +import type { TurnDaemonTransport } from '../src/daemon/transport.js'; +import { appRouter } from '../src/router.js'; + +const now = new Date('2026-01-01T00:00:00.000Z'); +const buildGeneral = (overrides: Partial = {}): GeneralRow => ({ + id: 7, + userId: 'user-7', + name: '검증장수', + nationId: 1, + cityId: 1, + troopId: 0, + npcState: 0, + affinity: null, + bornYear: 180, + deadYear: 300, + picture: 'default.jpg', + imageServer: 0, + leadership: 70, + strength: 60, + intel: 50, + injury: 0, + experience: 10, + dedication: 20, + officerLevel: 1, + gold: 1_000, + rice: 1_000, + crew: 100, + crewTypeId: 0, + train: 80, + atmos: 80, + weaponCode: 'None', + bookCode: 'None', + horseCode: 'None', + itemCode: 'None', + turnTime: now, + recentWarTime: null, + age: 20, + startAge: 20, + personalCode: 'None', + specialCode: 'None', + special2Code: 'None', + lastTurn: {}, + meta: { + belong: 1, + permission: 'normal', + myset: 3, + tnmt: 0, + defence_train: 80, + use_treatment: 21, + use_auto_nation_turn: 1, + }, + penalty: {}, + createdAt: now, + updatedAt: now, + ...overrides, +}); + +const auth: GameSessionTokenPayload = { + version: 1, + profile: 'che:default', + issuedAt: now.toISOString(), + expiresAt: new Date(now.getTime() + 86_400_000).toISOString(), + sessionId: 'session-7', + user: { id: 'user-7', username: 'tester', displayName: 'Tester', roles: [] }, + sanctions: {}, +}; + +const createContext = (options: { + me?: GeneralRow; + targets?: GeneralRow[]; + nationMeta?: Record; + requestCommand?: ReturnType; +}) => { + const me = options.me ?? buildGeneral(); + const targets = options.targets ?? [me]; + const requestCommand = + options.requestCommand ?? vi.fn(async () => ({ type: 'setMySetting', ok: true, generalId: me.id })); + const generalFindUnique = vi.fn( + async ({ where }: { where: { id: number } }) => targets.find((general) => general.id === where.id) ?? null + ); + const db = { + general: { + findFirst: vi.fn(async () => me), + findUnique: generalFindUnique, + findMany: vi.fn(async () => targets.filter((general) => general.nationId === me.nationId)), + update: vi.fn(), + }, + city: { findUnique: vi.fn(async () => null) }, + nation: { + findUnique: vi.fn(async () => ({ + id: 1, + name: '위', + color: '#777777', + level: 3, + gold: 10_000, + rice: 20_000, + tech: 100, + typeCode: 'che_법가', + capitalCityId: 1, + meta: options.nationMeta ?? { secretlimit: 3 }, + })), + }, + worldState: { + findFirst: vi.fn(async () => ({ + currentYear: 185, + currentMonth: 1, + tickSeconds: 600, + })), + }, + logEntry: { + groupBy: vi.fn(async () => []), + findMany: vi.fn(async () => [{ id: 1, text: '기록' }]), + }, + }; + const redisClient = { get: async () => null, set: async () => null }; + const context: GameApiContext = { + db: db as unknown as DatabaseClient, + redis: {} as RedisConnector['client'], + turnDaemon: { requestCommand } as unknown as TurnDaemonTransport, + battleSim: {} as GameApiContext['battleSim'], + profile: { id: 'che', scenario: 'default', name: 'che:default' }, + auth, + uploadDir: 'uploads', + uploadPath: '/uploads', + uploadPublicUrl: null, + accessTokenStore: new RedisAccessTokenStore(redisClient, 'che:default'), + flushStore: new InMemoryFlushStore(), + gameTokenSecret: 'test-secret', + }; + return { context, db, requestCommand }; +}; + +describe('in-game my information ownership', () => { + it('reads legacy top-level settings and dispatches only the session-owned general', async () => { + const requestCommand = vi.fn(async () => ({ type: 'setMySetting', ok: true, generalId: 7 })); + const fixture = createContext({ requestCommand }); + const caller = appRouter.createCaller(fixture.context); + + const me = await caller.general.me(); + expect(me?.settings).toEqual({ + tnmt: 0, + defence_train: 80, + use_treatment: 21, + use_auto_nation_turn: 1, + myset: 3, + }); + + await caller.general.setMySetting({ tnmt: 1, defence_train: 999 }); + expect(requestCommand).toHaveBeenCalledWith({ + type: 'setMySetting', + generalId: 7, + settings: { tnmt: 1, defence_train: 999 }, + }); + expect(fixture.db.general.update).not.toHaveBeenCalled(); + }); + + it('uses the authenticated user for both the page and its logs without accepting a target general id', async () => { + const otherUser = buildGeneral({ id: 8, userId: 'user-8', name: '타유저' }); + const fixture = createContext({ targets: [buildGeneral(), otherUser] }); + const caller = appRouter.createCaller(fixture.context); + + await expect(caller.general.me()).resolves.toMatchObject({ + general: { id: 7, name: '검증장수' }, + }); + await expect(caller.general.getMyLog({ type: 'generalAction' })).resolves.toMatchObject({ + type: 'generalAction', + logs: [{ id: 1 }], + }); + + expect(fixture.db.general.findFirst).toHaveBeenCalledWith( + expect.objectContaining({ + where: { userId: 'user-7' }, + }) + ); + expect(fixture.db.logEntry.findMany).toHaveBeenCalledWith( + expect.objectContaining({ + where: expect.objectContaining({ generalId: 7 }), + }) + ); + }); +}); + +describe('battle-center general and user permissions', () => { + it('distinguishes an ordinary member, a tenured member, and an auditor', async () => { + const ordinary = createContext({ + me: buildGeneral({ officerLevel: 1, meta: { belong: 1, permission: 'normal' } }), + nationMeta: { secretlimit: 3 }, + }); + await expect(appRouter.createCaller(ordinary.context).nation.getBattleCenter()).rejects.toMatchObject({ + code: 'FORBIDDEN', + }); + + const tenured = createContext({ + me: buildGeneral({ officerLevel: 1, meta: { belong: 3, permission: 'normal' } }), + nationMeta: { secretlimit: 3 }, + }); + await expect(appRouter.createCaller(tenured.context).nation.getBattleCenter()).resolves.toMatchObject({ + me: { id: 7, permissionLevel: 1 }, + }); + + const auditor = createContext({ + me: buildGeneral({ officerLevel: 1, meta: { belong: 0, permission: 'auditor' } }), + nationMeta: { secretlimit: 3 }, + }); + await expect(appRouter.createCaller(auditor.context).nation.getBattleCenter()).resolves.toMatchObject({ + me: { id: 7, permissionLevel: 3 }, + }); + }); + + it('redacts another user action log while allowing own, NPC, chief, and non-private logs', async () => { + const me = buildGeneral({ meta: { belong: 3, permission: 'normal' } }); + const otherUser = buildGeneral({ id: 8, userId: 'user-8', name: '타유저', npcState: 0 }); + const npc = buildGeneral({ id: 9, userId: null, name: 'NPC', npcState: 2 }); + const foreign = buildGeneral({ id: 10, userId: 'user-10', name: '타국', nationId: 2 }); + const memberFixture = createContext({ + me, + targets: [me, otherUser, npc, foreign], + nationMeta: { secretlimit: 3 }, + }); + const member = appRouter.createCaller(memberFixture.context); + + await expect(member.nation.getGeneralLog({ generalId: me.id, type: 'generalAction' })).resolves.toMatchObject({ + generalId: me.id, + }); + await expect( + member.nation.getGeneralLog({ generalId: otherUser.id, type: 'generalAction' }) + ).rejects.toMatchObject({ code: 'FORBIDDEN' }); + await expect( + member.nation.getGeneralLog({ generalId: otherUser.id, type: 'battleDetail' }) + ).resolves.toMatchObject({ generalId: otherUser.id }); + await expect(member.nation.getGeneralLog({ generalId: npc.id, type: 'generalAction' })).resolves.toMatchObject({ + generalId: npc.id, + }); + await expect( + member.nation.getGeneralLog({ generalId: foreign.id, type: 'battleDetail' }) + ).rejects.toMatchObject({ code: 'FORBIDDEN' }); + + const chiefFixture = createContext({ + me: buildGeneral({ officerLevel: 5 }), + targets: [buildGeneral({ officerLevel: 5 }), otherUser], + nationMeta: { secretlimit: 3 }, + }); + await expect( + appRouter + .createCaller(chiefFixture.context) + .nation.getGeneralLog({ generalId: otherUser.id, type: 'generalAction' }) + ).resolves.toMatchObject({ generalId: otherUser.id }); + }); +}); diff --git a/app/game-api/test/nationGeneralSecretRouter.test.ts b/app/game-api/test/nationGeneralSecretRouter.test.ts new file mode 100644 index 0000000..329ad5e --- /dev/null +++ b/app/game-api/test/nationGeneralSecretRouter.test.ts @@ -0,0 +1,209 @@ +import { describe, expect, it, vi } from 'vitest'; + +import type { GameSessionTokenPayload } from '@sammo-ts/common/auth/gameToken'; +import type { RedisConnector } from '@sammo-ts/infra'; + +import { RedisAccessTokenStore } from '../src/auth/accessTokenStore.js'; +import { InMemoryFlushStore } from '../src/auth/flushStore.js'; +import type { DatabaseClient, GameApiContext, GeneralRow } from '../src/context.js'; +import { appRouter } from '../src/router.js'; + +const now = new Date('2026-01-01T01:02:00.000Z'); +const buildGeneral = (overrides: Partial = {}): GeneralRow => ({ + id: 1, + userId: 'user-1', + name: '일반장수', + nationId: 1, + cityId: 1, + troopId: 0, + npcState: 0, + affinity: null, + bornYear: 180, + deadYear: 300, + picture: 'default.jpg', + imageServer: 0, + leadership: 70, + strength: 60, + intel: 50, + injury: 0, + experience: 900, + dedication: 100, + officerLevel: 1, + gold: 1_000, + rice: 2_000, + crew: 300, + crewTypeId: 1, + train: 90, + atmos: 90, + weaponCode: 'None', + bookCode: 'None', + horseCode: 'None', + itemCode: 'None', + turnTime: now, + recentWarTime: null, + age: 20, + startAge: 20, + personalCode: 'None', + specialCode: 'None', + special2Code: 'None', + lastTurn: {}, + meta: { belong: 1, defence_train: 80, killturn: 7 }, + penalty: {}, + createdAt: now, + updatedAt: now, + ...overrides, +}); + +const auth = (userId: string): GameSessionTokenPayload => ({ + version: 1, + profile: 'che:default', + issuedAt: now.toISOString(), + expiresAt: new Date(now.getTime() + 86_400_000).toISOString(), + sessionId: `session-${userId}`, + user: { id: userId, username: userId, displayName: userId, roles: [] }, + sanctions: {}, +}); + +const createContext = (options: { + sessionUserId?: string; + generals?: GeneralRow[]; + nationMeta?: Record; +}) => { + const sessionUserId = options.sessionUserId ?? 'user-1'; + const generals = options.generals ?? [buildGeneral()]; + const db = { + general: { + findFirst: vi.fn(async ({ where }: { where: { userId: string } }) => + generals.find((general) => general.userId === where.userId) + ), + findMany: vi.fn(async ({ where }: { where: { nationId: number } }) => + generals.filter((general) => general.nationId === where.nationId) + ), + }, + nation: { + findUnique: vi.fn(async () => ({ + id: 1, + name: '위', + color: '#008000', + level: 3, + typeCode: 'che_중립', + capitalCityId: 1, + meta: options.nationMeta ?? { secretlimit: 3 }, + })), + }, + city: { findMany: vi.fn(async () => [{ id: 1, name: '업' }]) }, + troop: { findMany: vi.fn(async () => [{ troopLeaderId: 2, name: '선봉대' }]) }, + generalAccessLog: { + findMany: vi.fn(async () => + generals.map((general) => ({ + generalId: general.id, + refreshScore: general.id, + refreshScoreTotal: general.id * 10, + })) + ), + }, + generalTurn: { + findMany: vi.fn(async () => [ + { generalId: 1, turnIdx: 0, actionCode: '징병' }, + { generalId: 1, turnIdx: 1, actionCode: '훈련' }, + ]), + }, + }; + const redis = { get: vi.fn(async () => null), set: vi.fn(async () => null) } as unknown as RedisConnector['client']; + return { + context: { + db: db as unknown as DatabaseClient, + redis, + turnDaemon: {} as GameApiContext['turnDaemon'], + battleSim: {} as GameApiContext['battleSim'], + profile: { id: 'che', scenario: 'default', name: 'che:default' }, + auth: auth(sessionUserId), + uploadDir: 'uploads', + uploadPath: '/uploads', + uploadPublicUrl: null, + accessTokenStore: new RedisAccessTokenStore(redis, 'che:default'), + flushStore: new InMemoryFlushStore(), + gameTokenSecret: 'test-secret', + } satisfies GameApiContext, + db, + }; +}; + +describe('nation general and secret-office permissions', () => { + it('redacts confidential columns for an ordinary member and denies the secret office', async () => { + const fixture = createContext({}); + const caller = appRouter.createCaller(fixture.context); + + const list = await caller.nation.getGeneralList(); + expect(list.viewer).toEqual({ generalId: 1, permission: 0 }); + expect(list.generals[0]).toMatchObject({ + officerLevel: 1, + gold: 1_000, + rice: 2_000, + detail: null, + }); + expect(fixture.db.generalTurn.findMany).not.toHaveBeenCalled(); + await expect(caller.nation.getSecretGeneralList()).rejects.toMatchObject({ code: 'FORBIDDEN' }); + }); + + it('allows a tenured member, scopes rows to the actor nation, and returns legacy summary and turns', async () => { + const me = buildGeneral({ meta: { belong: 3, defence_train: 90, killturn: 7 } }); + const ally = buildGeneral({ + id: 2, + userId: 'user-2', + name: '아군', + troopId: 2, + gold: 3_000, + rice: 4_000, + crew: 200, + train: 80, + atmos: 80, + }); + const hiddenNpc = buildGeneral({ id: 3, userId: null, name: '가상', npcState: 5, gold: 99_999 }); + const foreign = buildGeneral({ id: 4, userId: 'foreign', nationId: 2, gold: 88_888 }); + const fixture = createContext({ generals: [me, ally, hiddenNpc, foreign] }); + + const result = await appRouter.createCaller(fixture.context).nation.getSecretGeneralList(); + expect(result.viewer.permission).toBe(1); + expect(result.generals.map((general) => general.id)).toEqual([1, 2, 3]); + expect(result.generals[0]?.detail).toMatchObject({ + cityName: '업', + defenceTrain: 90, + killTurn: 7, + reservedCommands: ['징병', '훈련'], + }); + expect(result.generals[1]?.detail?.troopName).toBe('선봉대'); + expect(result.summary).toMatchObject({ + gold: 4_000, + rice: 6_000, + crew: 500, + generalCount: 2, + readiness: { + 90: { crew: 300, generals: 1 }, + 80: { crew: 500, generals: 2 }, + 60: { crew: 500, generals: 2 }, + }, + }); + expect(fixture.db.general.findMany).toHaveBeenCalledWith( + expect.objectContaining({ where: { nationId: 1 } }) + ); + }); + + it('derives the acting general from the authenticated user and applies that general permission', async () => { + const first = buildGeneral({ userId: 'user-1', meta: { belong: 1 } }); + const second = buildGeneral({ id: 2, userId: 'user-2', officerLevel: 5, meta: { belong: 1 } }); + const fixture = createContext({ sessionUserId: 'user-2', generals: [first, second] }); + + const result = await appRouter.createCaller(fixture.context).nation.getSecretGeneralList(); + expect(result.viewer).toEqual({ generalId: 2, permission: 2 }); + expect(fixture.db.general.findFirst).toHaveBeenCalledWith({ where: { userId: 'user-2' } }); + }); + + it('keeps penalty-based secret denial even for an otherwise qualified general', async () => { + const me = buildGeneral({ officerLevel: 5, penalty: { noChief: true } }); + const fixture = createContext({ generals: [me] }); + await expect(appRouter.createCaller(fixture.context).nation.getSecretGeneralList()).rejects.toMatchObject({ + code: 'FORBIDDEN', + }); + }); +}); diff --git a/app/game-api/test/publicTraffic.test.ts b/app/game-api/test/publicTraffic.test.ts new file mode 100644 index 0000000..78008d8 --- /dev/null +++ b/app/game-api/test/publicTraffic.test.ts @@ -0,0 +1,115 @@ +import { describe, expect, it } from 'vitest'; + +import type { RedisConnector } from '@sammo-ts/infra'; + +import { RedisAccessTokenStore } from '../src/auth/accessTokenStore.js'; +import { InMemoryFlushStore } from '../src/auth/flushStore.js'; +import { InMemoryBattleSimTransport } from '../src/battleSim/inMemoryTransport.js'; +import type { DatabaseClient, GameApiContext, GameProfile } from '../src/context.js'; +import { InMemoryTurnDaemonTransport } from '../src/daemon/inMemoryTransport.js'; +import { appRouter } from '../src/router.js'; + +const profile: GameProfile = { + id: 'che', + scenario: 'default', + name: 'che:default', +}; + +const buildContext = (): GameApiContext => { + const db = { + worldState: { + findFirst: async () => ({ + id: 1, + currentYear: 185, + currentMonth: 3, + tickSeconds: 600, + config: {}, + meta: { + lastTurnTime: '2026-07-26T03:00:00.000Z', + refresh: 12, + maxrefresh: 30, + maxonline: 5, + recentTraffic: [ + { + year: 185, + month: 2, + refresh: 30, + online: 5, + date: '2026-07-26 02:50:00', + }, + ], + }, + }), + }, + generalAccessLog: { + aggregate: async () => ({ + _sum: { + refresh: 12, + refreshScoreTotal: 21, + }, + }), + count: async (args: { where: { lastRefresh: { gte: Date } } }) => { + expect(args.where.lastRefresh.gte).toEqual(new Date('2026-07-26T03:00:00.000Z')); + return 2; + }, + findMany: async () => [ + { generalId: 7, refresh: 9, refreshScoreTotal: 15 }, + { generalId: 8, refresh: 3, refreshScoreTotal: 6 }, + ], + }, + general: { + findMany: async () => [ + { id: 7, name: '갑' }, + { id: 8, name: '을' }, + ], + }, + }; + const redis = { + get: async () => null, + set: async () => null, + } as unknown as RedisConnector['client']; + + return { + db: db as unknown as DatabaseClient, + turnDaemon: new InMemoryTurnDaemonTransport(), + battleSim: new InMemoryBattleSimTransport(), + profile, + auth: null, + uploadDir: 'uploads', + uploadPath: '/uploads', + uploadPublicUrl: null, + redis, + accessTokenStore: new RedisAccessTokenStore(redis, profile.name), + flushStore: new InMemoryFlushStore(), + gameTokenSecret: 'test-secret', + }; +}; + +describe('public.getTraffic', () => { + it('is public and returns only aggregate traffic plus allowlisted general names', async () => { + const result = await appRouter.createCaller(buildContext()).public.getTraffic(); + + expect(result.history).toHaveLength(2); + expect(result.history[0]).toEqual({ + year: 185, + month: 2, + refresh: 30, + online: 5, + date: '2026-07-26 02:50:00', + }); + expect(result.history[1]).toMatchObject({ + year: 185, + month: 3, + refresh: 12, + online: 2, + }); + expect(result.maxRefresh).toBe(30); + expect(result.maxOnline).toBe(5); + expect(result.suspects).toEqual([ + { generalId: null, name: '접속자 총합', refresh: 12, refreshScoreTotal: 21 }, + { generalId: 7, name: '갑', refresh: 9, refreshScoreTotal: 15 }, + { generalId: 8, name: '을', refresh: 3, refreshScoreTotal: 6 }, + ]); + expect(JSON.stringify(result)).not.toContain('userId'); + }); +}); diff --git a/app/game-engine/src/turn/worldCommandHandler.ts b/app/game-engine/src/turn/worldCommandHandler.ts index e358955..42efbb9 100644 --- a/app/game-engine/src/turn/worldCommandHandler.ts +++ b/app/game-engine/src/turn/worldCommandHandler.ts @@ -809,9 +809,35 @@ async function handleVacation( if (!general) { return { type: 'vacation', ok: false, generalId: command.generalId, reason: '장수 정보를 찾을 수 없습니다.' }; } + const autorunUser = asRecord(world.getState().meta.autorun_user); + if (autorunUser.limit_minutes) { + return { + type: 'vacation', + ok: false, + generalId: command.generalId, + reason: '자동 턴인 경우에는 휴가 명령이 불가능합니다.', + }; + } + const killturn = readMetaNumber(asRecord(world.getState().meta), 'killturn', 0); + world.updateGeneral(general.id, { + meta: { + ...general.meta, + killturn: killturn * 3, + }, + }); return { type: 'vacation', ok: true, generalId: command.generalId }; } +const normalizeDefenceTrain = (value: number): number => { + if (value <= 40) { + return 40; + } + if (value <= 90) { + return Math.round(value / 10) * 10; + } + return 999; +}; + async function handleSetMySetting( ctx: CommandHandlerContext, command: Extract @@ -826,11 +852,48 @@ async function handleSetMySetting( reason: '장수 정보를 찾을 수 없습니다.', }; } + + const settings = command.settings; + const previousDefenceTrain = readMetaNumber(general.meta, 'defence_train', 80); + const nextDefenceTrain = + settings.defence_train === undefined ? previousDefenceTrain : normalizeDefenceTrain(settings.defence_train); + const nextMeta = { ...general.meta }; + + if (settings.tnmt !== undefined) { + nextMeta.tnmt = settings.tnmt < 0 || settings.tnmt > 1 ? 1 : settings.tnmt; + } + if (settings.use_treatment !== undefined) { + nextMeta.use_treatment = Math.max(10, Math.min(100, settings.use_treatment)); + } + if (settings.use_auto_nation_turn !== undefined) { + nextMeta.use_auto_nation_turn = settings.use_auto_nation_turn; + } + + let nextTrain = general.train; + let nextAtmos = general.atmos; + if (nextDefenceTrain !== previousDefenceTrain) { + nextMeta.myset = readMetaNumber(general.meta, 'myset', 0) - 1; + nextMeta.defence_train = nextDefenceTrain; + if (nextDefenceTrain === 999) { + const scenarioEffect = world.getScenarioConfig().environment.scenarioEffect; + const ignoresPenalty = + scenarioEffect === 'event_UnlimitedDefenceThresholdChange' || + scenarioEffect === 'event_StrongAttacker' || + scenarioEffect === 'event_MoreEffect'; + const constValues = asRecord(world.getScenarioConfig().const); + const maxTrain = readMetaNumber(constValues, 'maxTrainByWar', 100); + const maxAtmos = readMetaNumber(constValues, 'maxAtmosByWar', 100); + const trainDelta = ignoresPenalty ? 0 : -3; + const atmosDelta = ignoresPenalty ? 0 : -6; + nextTrain = Math.max(20, Math.min(maxTrain, general.train + trainDelta)); + nextAtmos = Math.max(20, Math.min(maxAtmos, general.atmos + atmosDelta)); + } + } + world.updateGeneral(command.generalId, { - meta: { - ...general.meta, - ...command.settings, - }, + meta: nextMeta, + train: nextTrain, + atmos: nextAtmos, }); return { type: 'setMySetting', ok: true, generalId: command.generalId }; } @@ -844,10 +907,8 @@ async function handleDropItem( if (!general) { return { type: 'dropItem', ok: false, generalId: command.generalId, reason: '장수 정보를 찾을 수 없습니다.' }; } - const slot = (['horse', 'weapon', 'book', 'item'] as const).find( - (candidate) => general.role.items[candidate] === command.itemType - ); - if (!slot) { + const slot = (['horse', 'weapon', 'book', 'item'] as const).find((candidate) => candidate === command.itemType); + if (!slot || !general.role.items[slot]) { return { type: 'dropItem', ok: false, generalId: command.generalId, reason: '아이템을 가지고 있지 않습니다.' }; } const nextGeneral = { diff --git a/app/game-engine/test/myInformationCommands.test.ts b/app/game-engine/test/myInformationCommands.test.ts new file mode 100644 index 0000000..86c72b8 --- /dev/null +++ b/app/game-engine/test/myInformationCommands.test.ts @@ -0,0 +1,179 @@ +import { describe, expect, it } from 'vitest'; + +import type { TurnSchedule } from '@sammo-ts/logic'; + +import { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js'; +import type { TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js'; +import { createTurnDaemonCommandHandler } from '../src/turn/worldCommandHandler.js'; + +const schedule: TurnSchedule = { entries: [{ startMinute: 0, tickMinutes: 10 }] }; + +const buildGeneral = (overrides: Partial = {}): TurnGeneral => ({ + id: 7, + userId: 'user-7', + name: '테스트장수', + nationId: 1, + cityId: 1, + troopId: 0, + stats: { leadership: 70, strength: 60, intelligence: 50 }, + turnTime: new Date('0185-01-01T00:00:00Z'), + recentWarTime: null, + role: { + items: { horse: 'che_명마', weapon: null, book: null, item: null }, + personality: null, + specialDomestic: null, + specialWar: null, + }, + triggerState: { flags: {}, counters: {}, modifiers: {}, meta: {} }, + meta: { + killturn: 12, + myset: 3, + defence_train: 80, + tnmt: 0, + use_treatment: 10, + use_auto_nation_turn: 1, + }, + penalty: {}, + officerLevel: 1, + experience: 0, + dedication: 0, + injury: 0, + gold: 1_000, + rice: 1_000, + crew: 100, + crewTypeId: 0, + train: 90, + atmos: 90, + age: 20, + npcState: 0, + ...overrides, +}); + +const buildWorld = ( + general = buildGeneral(), + options: { autorunLimit?: boolean; scenarioEffect?: string | null } = {} +) => { + const state: TurnWorldState = { + id: 1, + currentYear: 185, + currentMonth: 1, + tickSeconds: 600, + lastTurnTime: new Date('0185-01-01T00:00:00Z'), + meta: { + killturn: 24, + autorun_user: options.autorunLimit ? { limit_minutes: 60 } : {}, + }, + }; + const snapshot: TurnWorldSnapshot = { + generals: [general], + cities: [], + nations: [], + troops: [], + diplomacy: [], + events: [], + initialEvents: [], + scenarioConfig: { + stat: { total: 300, min: 10, max: 100, npcTotal: 150, npcMax: 50, npcMin: 10, chiefMin: 65 }, + iconPath: '', + map: {}, + const: { maxTrainByWar: 100, maxAtmosByWar: 100 }, + environment: { + mapName: 'test', + unitSet: 'test', + ...(options.scenarioEffect !== undefined ? { scenarioEffect: options.scenarioEffect } : {}), + }, + }, + scenarioMeta: { + title: 'test', + startYear: 180, + life: null, + fiction: null, + history: [], + ignoreDefaultEvents: false, + }, + map: { + id: 'test', + name: 'test', + cities: [], + defaults: { trust: 50, trade: 100, supplyState: 1, frontState: 0 }, + }, + }; + const world = new InMemoryTurnWorld(state, snapshot, { schedule }); + return { world, handler: createTurnDaemonCommandHandler({ world }) }; +}; + +describe('my information world commands', () => { + it('normalizes legacy settings and charges myset only when defence mode changes', async () => { + const fixture = buildWorld(); + + await expect( + fixture.handler.handle({ + type: 'setMySetting', + generalId: 7, + settings: { + tnmt: 9, + defence_train: 94, + use_treatment: 200, + use_auto_nation_turn: 0, + }, + }) + ).resolves.toMatchObject({ ok: true }); + + expect(fixture.world.getGeneralById(7)).toMatchObject({ + train: 87, + atmos: 84, + meta: { + tnmt: 1, + defence_train: 999, + use_treatment: 100, + use_auto_nation_turn: 0, + myset: 2, + }, + }); + + await fixture.handler.handle({ + type: 'setMySetting', + generalId: 7, + settings: { tnmt: 0, defence_train: 999, use_treatment: 1 }, + }); + expect(fixture.world.getGeneralById(7)?.meta).toMatchObject({ + tnmt: 0, + use_treatment: 10, + myset: 2, + }); + }); + + it('preserves the event scenarios that waive the no-defence penalty', async () => { + const fixture = buildWorld(buildGeneral(), { scenarioEffect: 'event_StrongAttacker' }); + await fixture.handler.handle({ + type: 'setMySetting', + generalId: 7, + settings: { defence_train: 999 }, + }); + expect(fixture.world.getGeneralById(7)).toMatchObject({ train: 90, atmos: 90 }); + }); + + it('applies vacation killturn and rejects it in automatic-turn mode', async () => { + const allowed = buildWorld(); + await expect(allowed.handler.handle({ type: 'vacation', generalId: 7 })).resolves.toMatchObject({ ok: true }); + expect(allowed.world.getGeneralById(7)?.meta.killturn).toBe(72); + + const blocked = buildWorld(buildGeneral(), { autorunLimit: true }); + await expect(blocked.handler.handle({ type: 'vacation', generalId: 7 })).resolves.toMatchObject({ + ok: false, + reason: '자동 턴인 경우에는 휴가 명령이 불가능합니다.', + }); + expect(blocked.world.getGeneralById(7)?.meta.killturn).toBe(12); + }); + + it('drops only the authenticated command target slot and rejects an empty slot', async () => { + const fixture = buildWorld(); + await expect( + fixture.handler.handle({ type: 'dropItem', generalId: 7, itemType: 'weapon' }) + ).resolves.toMatchObject({ ok: false }); + await expect( + fixture.handler.handle({ type: 'dropItem', generalId: 7, itemType: 'horse' }) + ).resolves.toMatchObject({ ok: true }); + expect(fixture.world.getGeneralById(7)?.role.items.horse).toBeNull(); + }); +}); diff --git a/app/game-frontend/e2e/inGameMenus.spec.ts b/app/game-frontend/e2e/inGameMenus.spec.ts new file mode 100644 index 0000000..ca33b24 --- /dev/null +++ b/app/game-frontend/e2e/inGameMenus.spec.ts @@ -0,0 +1,314 @@ +import { mkdir, readFile, writeFile } from 'node:fs/promises'; +import { basename, resolve } from 'node:path'; +import { expect, test, type Page, type Route } from '@playwright/test'; + +const response = (data: unknown) => ({ result: { data } }); +const parityArtifactDir = process.env.MENU_PARITY_ARTIFACT_DIR; +const legacyImageRoot = process.env.LEGACY_IMAGE_ROOT; +const operationNames = (route: Route) => + decodeURIComponent(new URL(route.request().url()).pathname.split('/trpc/')[1] ?? '').split(','); + +const persistParityArtifact = async (page: Page, name: string, geometry: unknown) => { + if (!parityArtifactDir) { + return; + } + await mkdir(parityArtifactDir, { recursive: true }); + await Promise.all([ + page.screenshot({ path: resolve(parityArtifactDir, `${name}.png`), fullPage: true }), + writeFile(resolve(parityArtifactDir, `${name}.json`), `${JSON.stringify(geometry, null, 2)}\n`), + ]); +}; + +type FixtureState = { + permission: 'head' | 'member'; + myset: number; + settingMutations: Array>; +}; + +const myGeneral = (state: FixtureState) => ({ + general: { + id: 7, + name: '검증장수', + npcState: 0, + nationId: 1, + cityId: 1, + troopId: 0, + picture: null, + imageServer: 0, + officerLevel: state.permission === 'head' ? 5 : 1, + stats: { leadership: 70, strength: 60, intelligence: 50 }, + gold: 1_000, + rice: 2_000, + crew: 300, + train: 80, + atmos: 90, + injury: 0, + experience: 100, + dedication: 200, + items: { horse: 'che_명마', weapon: null, book: null, item: null }, + }, + city: { id: 1, name: '업', level: 8, nationId: 1 }, + nation: { id: 1, name: '위', color: '#777777', level: 3 }, + settings: { + tnmt: 0, + defence_train: 80, + use_treatment: 21, + use_auto_nation_turn: 1, + myset: state.myset, + }, + penalties: {}, +}); + +const battleCenter = (state: FixtureState) => ({ + me: { + id: 7, + officerLevel: state.permission === 'head' ? 5 : 1, + permissionLevel: state.permission === 'head' ? 2 : 0, + }, + nation: { id: 1, name: '위', color: '#777777', level: 3 }, + currentYear: 185, + currentMonth: 1, + turnTermMinutes: 10, + generals: [ + { + id: 7, + name: '검증장수', + npcState: 0, + officerLevel: state.permission === 'head' ? 5 : 1, + cityId: 1, + turnTime: '2026-01-01 00:10:00', + recentWar: '2026-01-01 00:00:00', + warnum: 3, + stats: { leadership: 70, strength: 60, intelligence: 50 }, + experience: 100, + dedication: 200, + injury: 0, + gold: 1_000, + rice: 2_000, + crew: 300, + train: 80, + atmos: 90, + }, + { + id: 8, + name: '다른장수', + npcState: 2, + officerLevel: 1, + cityId: 1, + turnTime: '2026-01-01 00:20:00', + recentWar: null, + warnum: 0, + stats: { leadership: 50, strength: 50, intelligence: 50 }, + experience: 0, + dedication: 0, + injury: 0, + gold: 500, + rice: 500, + crew: 100, + train: 60, + atmos: 60, + }, + ], +}); + +const install = async (page: Page, state: FixtureState) => { + await page.addInitScript(() => { + localStorage.setItem('sammo-game-token', 'menu-token'); + localStorage.setItem('sammo-game-profile', 'che:default'); + }); + await page.route('**/image/game/**', async (route) => { + const filename = basename(new URL(route.request().url()).pathname); + if (legacyImageRoot && ['back_walnut.jpg', 'back_green.jpg', 'back_blue.jpg'].includes(filename)) { + await route.fulfill({ + status: 200, + contentType: 'image/jpeg', + body: await readFile(resolve(legacyImageRoot, filename)), + }); + return; + } + await route.fulfill({ status: 200, contentType: 'image/jpeg', body: Buffer.from('') }); + }); + await page.route('**/che/api/trpc/**', async (route) => { + const operations = operationNames(route); + const results = operations.map((operation) => { + if (operation === 'lobby.info') return response({ myGeneral: { id: 7, name: '검증장수' } }); + if (operation === 'join.getConfig') return response({}); + if (operation === 'general.me') return response(myGeneral(state)); + if (operation === 'world.getState') + return response({ + currentYear: 185, + currentMonth: 1, + tickSeconds: 600, + config: { npcMode: 0, const: { availableInstantAction: {} } }, + meta: { + turntime: '2026-01-01T00:00:00.000Z', + opentime: '2025-12-01T00:00:00.000Z', + autorun_user: {}, + }, + }); + if (operation === 'general.getMyLog') + return response({ type: 'generalAction', logs: [{ id: 1, text: '기록' }] }); + if (operation === 'general.setMySetting') { + const raw = route.request().postDataJSON() as { input?: { json?: Record } }; + state.settingMutations.push(raw.input?.json ?? {}); + state.myset = Math.max(0, state.myset - 1); + return response({ ok: true }); + } + if (operation === 'nation.getBattleCenter') { + if (state.permission === 'member') { + return { + error: { + message: '권한이 부족합니다.', + code: -32000, + data: { code: 'FORBIDDEN', httpStatus: 403, path: operation }, + }, + }; + } + return response(battleCenter(state)); + } + if (operation === 'nation.getGeneralLog') { + const type = new URL(route.request().url()).searchParams.get('input')?.includes('generalAction') + ? 'generalAction' + : operation; + return response({ type, generalId: 7, logs: [{ id: 1, text: '감찰 기록' }] }); + } + return response({ ok: true }); + }); + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify(operations.length === 1 ? results[0] : results), + }); + }); +}; + +test('내 정보&설정 keeps the legacy 1000px/500px geometry and saves in place', async ({ page }) => { + const state: FixtureState = { permission: 'head', myset: 3, settingMutations: [] }; + await install(page, state); + await page.setViewportSize({ width: 1200, height: 900 }); + await page.goto('my-page'); + await expect(page.locator('.title-row')).toContainText('내 정 보'); + await expect(page.locator('#set_my_setting')).toBeVisible(); + + const desktop = await page.locator('#container').evaluate((element) => { + const rect = element.getBoundingClientRect(); + const title = element.querySelector('.title-row')!.getBoundingClientRect(); + const settings = element.querySelector('.settings-column')!.getBoundingClientRect(); + const saveButton = element.querySelector('#set_my_setting')!; + const save = saveButton.getBoundingClientRect(); + const customCss = element.querySelector('#custom_css')!.getBoundingClientRect(); + const columns = getComputedStyle(element.querySelector('.top-grid')!).gridTemplateColumns; + return { + width: rect.width, + minWidth: getComputedStyle(element).minWidth, + fontSize: getComputedStyle(element).fontSize, + columns, + titleHeight: title.height, + settingsOffset: settings.x - rect.x, + saveWidth: save.width, + saveHeight: save.height, + saveBackground: getComputedStyle(saveButton).backgroundColor, + customCssWidth: customCss.width, + customCssHeight: customCss.height, + backgroundImage: getComputedStyle(element).backgroundImage, + sectionBackgroundImage: getComputedStyle(element.querySelector('.section-title')!).backgroundImage, + }; + }); + expect(desktop.width).toBe(1000); + expect(desktop.minWidth).toBe('500px'); + expect(desktop.fontSize).toBe('14px'); + expect(desktop.columns.split(' ')).toHaveLength(2); + expect(desktop.titleHeight).toBeCloseTo(54, 0); + expect(desktop.settingsOffset).toBeCloseTo(500, 0); + expect(desktop.saveWidth).toBe(160); + expect(desktop.saveHeight).toBe(30); + expect(desktop.saveBackground).toBe('rgb(34, 85, 0)'); + expect(desktop.customCssWidth).toBe(420); + expect(desktop.customCssHeight).toBe(150); + expect(desktop.backgroundImage).toContain('back_walnut.jpg'); + expect(desktop.sectionBackgroundImage).toContain('back_green.jpg'); + await persistParityArtifact(page, 'core-my-page-desktop', desktop); + + await page + .locator('select') + .filter({ has: page.locator('option[value="999"]') }) + .selectOption('999'); + await page.locator('#set_my_setting').click(); + await expect.poll(() => state.settingMutations.length).toBe(1); + expect(state.settingMutations[0]).not.toHaveProperty('generalId'); + + await page.setViewportSize({ width: 500, height: 900 }); + await page.reload(); + const mobile = await page.locator('#container').evaluate((element) => { + const rect = element.getBoundingClientRect(); + const settings = element.querySelector('.settings-column')!.getBoundingClientRect(); + return { + width: rect.width, + scrollWidth: document.documentElement.scrollWidth, + columns: getComputedStyle(element.querySelector('.top-grid')!).gridTemplateColumns, + settingsOffset: settings.x - rect.x, + settingsWidth: settings.width, + }; + }); + expect(mobile).toMatchObject({ + width: 500, + scrollWidth: 500, + columns: '500px', + settingsOffset: 0, + settingsWidth: 500, + }); + await persistParityArtifact(page, 'core-my-page-mobile', mobile); +}); + +test('감찰부 keeps the selector interaction and shows the permission error path', async ({ page }) => { + const head: FixtureState = { permission: 'head', myset: 3, settingMutations: [] }; + await install(page, head); + await page.setViewportSize({ width: 1000, height: 900 }); + await page.goto('battle-center'); + await expect(page.getByRole('heading', { name: '감찰부' })).toBeVisible(); + await expect(page.locator('.selector-row select').nth(1)).toHaveValue('8'); + await page.getByRole('button', { name: '다음 ▶' }).click(); + await expect(page.locator('.selector-row select').nth(1)).toHaveValue('7'); + const geometry = await page.locator('.battle-page').evaluate((element) => { + const selector = element.querySelector('.selector-row')!; + const controls = [...selector.children].map((child) => (child as HTMLElement).getBoundingClientRect()); + const logBlock = element.querySelector('.log-block')!.getBoundingClientRect(); + return { + width: element.getBoundingClientRect().width, + fontSize: getComputedStyle(element).fontSize, + selectorColumns: getComputedStyle(selector).gridTemplateColumns, + selectorHeight: selector.getBoundingClientRect().height, + controlWidths: controls.map((control) => control.width), + logBlockWidth: logBlock.width, + backgroundImage: getComputedStyle(element).backgroundImage, + generalBackgroundImage: getComputedStyle(element.querySelector('.battle-general-card')!) + .backgroundImage, + }; + }); + expect(geometry.width).toBe(1000); + expect(geometry.fontSize).toBe('14px'); + expect(geometry.selectorColumns.split(' ')).toHaveLength(4); + expect(geometry.selectorHeight).toBeCloseTo(36, 0); + expect(geometry.controlWidths[0]).toBeCloseTo(83.33, 0); + expect(geometry.controlWidths[1]).toBeCloseTo(333.33, 0); + expect(geometry.logBlockWidth).toBeCloseTo(500, 0); + expect(geometry.backgroundImage).toContain('back_walnut.jpg'); + expect(geometry.generalBackgroundImage).toContain('back_blue.jpg'); + await persistParityArtifact(page, 'core-battle-center-desktop', geometry); + + await page.setViewportSize({ width: 500, height: 900 }); + const mobileGeometry = await page.locator('.selector-row').evaluate((element) => ({ + columns: getComputedStyle(element).gridTemplateColumns, + controlWidths: [...element.children].map((child) => (child as HTMLElement).getBoundingClientRect().width), + })); + expect(mobileGeometry.columns.split(' ')).toHaveLength(4); + expect(mobileGeometry.controlWidths[0]).toBeCloseTo(83.33, 0); + expect(mobileGeometry.controlWidths[1]).toBeCloseTo(125, 0); + await persistParityArtifact(page, 'core-battle-center-mobile', mobileGeometry); + + await page.unrouteAll({ behavior: 'wait' }); + const member: FixtureState = { permission: 'member', myset: 3, settingMutations: [] }; + await install(page, member); + await page.reload(); + await expect(page.locator('.error')).toContainText('권한이 부족합니다.'); +}); diff --git a/app/game-frontend/e2e/playwright.config.mjs b/app/game-frontend/e2e/playwright.config.mjs index ddee57a..b6090fe 100644 --- a/app/game-frontend/e2e/playwright.config.mjs +++ b/app/game-frontend/e2e/playwright.config.mjs @@ -8,7 +8,7 @@ const baseURL = `http://127.0.0.1:${port}/che/`; export default defineConfig({ testDir: '.', - testMatch: ['troop.spec.ts', 'board.spec.ts', 'inGameInfo.spec.ts', 'nationOffices.spec.ts'], + testMatch: ['troop.spec.ts', 'board.spec.ts', 'inGameInfo.spec.ts', 'inGameMenus.spec.ts', 'nationOffices.spec.ts'], fullyParallel: false, workers: 1, timeout: 30_000, diff --git a/app/game-frontend/src/router/index.ts b/app/game-frontend/src/router/index.ts index a412e4c..90532bf 100644 --- a/app/game-frontend/src/router/index.ts +++ b/app/game-frontend/src/router/index.ts @@ -10,6 +10,7 @@ import NationInfoView from '../views/NationInfoView.vue'; import GlobalInfoView from '../views/GlobalInfoView.vue'; import CurrentCityView from '../views/CurrentCityView.vue'; import NationGeneralsView from '../views/NationGeneralsView.vue'; +import NationSecretView from '../views/NationSecretView.vue'; import NationPersonnelView from '../views/NationPersonnelView.vue'; import NationStratFinanView from '../views/NationStratFinanView.vue'; import ChiefCenterView from '../views/ChiefCenterView.vue'; @@ -20,7 +21,6 @@ import NotFoundView from '../views/NotFoundView.vue'; import TournamentView from '../views/TournamentView.vue'; import BettingView from '../views/BettingView.vue'; import MyPageView from '../views/MyPageView.vue'; -import MySettingsView from '../views/MySettingsView.vue'; import BoardView from '../views/BoardView.vue'; import DiplomacyView from '../views/DiplomacyView.vue'; import BestGeneralView from '../views/BestGeneralView.vue'; @@ -32,6 +32,7 @@ import TroopView from '../views/TroopView.vue'; import YearbookView from '../views/YearbookView.vue'; import NationBettingView from '../views/NationBettingView.vue'; import NpcListView from '../views/NpcListView.vue'; +import TrafficView from '../views/TrafficView.vue'; import { useSessionStore } from '../stores/session'; const routes = [ @@ -148,6 +149,15 @@ const routes = [ requiresGeneral: true, }, }, + { + path: '/nation/secret', + name: 'nation-secret', + component: NationSecretView, + meta: { + requiresAuth: true, + requiresGeneral: true, + }, + }, { path: '/nation/personnel', name: 'nation-personnel', @@ -251,6 +261,11 @@ const routes = [ requiresGeneral: true, }, }, + { + path: '/traffic', + name: 'traffic', + component: TrafficView, + }, { path: '/npc-list', name: 'npc-list', @@ -276,8 +291,7 @@ const routes = [ }, { path: '/my-settings', - name: 'my-settings', - component: MySettingsView, + redirect: '/my-page', meta: { requiresAuth: true, requiresGeneral: true, diff --git a/app/game-frontend/src/views/BattleCenterView.vue b/app/game-frontend/src/views/BattleCenterView.vue index 1d3f0e6..8b48183 100644 --- a/app/game-frontend/src/views/BattleCenterView.vue +++ b/app/game-frontend/src/views/BattleCenterView.vue @@ -3,7 +3,6 @@ import { computed, onMounted, reactive, ref, watch } from 'vue'; import { useRoute } from 'vue-router'; import PanelCard from '../components/ui/PanelCard.vue'; import SkeletonLines from '../components/ui/SkeletonLines.vue'; -import GeneralBasicCard from '../components/main/GeneralBasicCard.vue'; import { trpc } from '../utils/trpc'; import { getNpcColor } from '../utils/npcColor'; import { formatLog } from '../utils/formatLog'; @@ -269,7 +268,26 @@ onMounted(() => { - + +
+
+ {{ selectedGeneral.name }} (관직 {{ selectedGeneral.officerLevel }}) +
+
+ 통솔{{ selectedGeneral.stats.leadership }} 무력{{ selectedGeneral.stats.strength }} 지력{{ selectedGeneral.stats.intelligence }} 자금{{ selectedGeneral.gold }} 군량{{ selectedGeneral.rice }} 병력{{ selectedGeneral.crew }} 훈련{{ selectedGeneral.train }} 사기{{ selectedGeneral.atmos }} 부상{{ selectedGeneral.injury }} 경험{{ selectedGeneral.experience }} 공헌{{ selectedGeneral.dedication }} 전투{{ selectedGeneral.warnum }}회 +
+
최근 턴: {{ selectedGeneral.turnTime ? selectedGeneral.turnTime.slice(-5) : '-' }}
최근 전투: {{ selectedGeneral.recentWar || '-' }}
@@ -286,12 +304,7 @@ onMounted(() => {
@@ -303,126 +316,237 @@ onMounted(() => { diff --git a/app/game-frontend/src/views/NationSecretView.vue b/app/game-frontend/src/views/NationSecretView.vue new file mode 100644 index 0000000..e622cbc --- /dev/null +++ b/app/game-frontend/src/views/NationSecretView.vue @@ -0,0 +1,250 @@ + + + + + diff --git a/app/game-frontend/src/views/PublicView.vue b/app/game-frontend/src/views/PublicView.vue index 6c3684a..1624fcf 100644 --- a/app/game-frontend/src/views/PublicView.vue +++ b/app/game-frontend/src/views/PublicView.vue @@ -108,6 +108,7 @@ onMounted(() => { 장수 생성/빙의 메인으로 빙의일람 + 접속량정보 diff --git a/app/game-frontend/src/views/TrafficView.vue b/app/game-frontend/src/views/TrafficView.vue new file mode 100644 index 0000000..58b5f30 --- /dev/null +++ b/app/game-frontend/src/views/TrafficView.vue @@ -0,0 +1,343 @@ + + + + + diff --git a/tools/frontend-legacy-parity/reference-ingame-menus.mjs b/tools/frontend-legacy-parity/reference-ingame-menus.mjs new file mode 100644 index 0000000..219dd75 --- /dev/null +++ b/tools/frontend-legacy-parity/reference-ingame-menus.mjs @@ -0,0 +1,175 @@ +import { chromium } from '@playwright/test'; +import { createHash } from 'node:crypto'; +import { mkdir, readFile, writeFile } from 'node:fs/promises'; +import { resolve } from 'node:path'; + +const baseUrl = process.env.REF_MENU_URL ?? 'http://127.0.0.1:3400/sam/'; +const username = process.env.REF_MENU_USER ?? 'refuser1'; +const passwordFile = process.env.REF_MENU_PASSWORD_FILE; +const artifactRoot = resolve(process.env.REF_MENU_ARTIFACT_DIR ?? 'test-results/reference-ingame-menus'); + +if (!passwordFile) { + throw new Error('REF_MENU_PASSWORD_FILE is required.'); +} + +const password = (await readFile(passwordFile, 'utf8')).trim(); +await mkdir(artifactRoot, { recursive: true }); + +const login = async (context, page) => { + await page.goto(baseUrl, { waitUntil: 'networkidle' }); + const globalSalt = await page.locator('#global_salt').inputValue(); + const passwordHash = createHash('sha512') + .update(globalSalt + password + globalSalt) + .digest('hex'); + const response = await context.request.post(new URL('api.php?path=Login/LoginByID', baseUrl).toString(), { + data: { username, password: passwordHash }, + }); + const result = await response.json(); + if (!response.ok() || result.result !== true) { + throw new Error('Reference login failed.'); + } +}; + +const rectAndStyle = (element) => { + const rect = element.getBoundingClientRect(); + const style = getComputedStyle(element); + return { + rect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height }, + style: { + display: style.display, + gridTemplateColumns: style.gridTemplateColumns, + fontFamily: style.fontFamily, + fontSize: style.fontSize, + lineHeight: style.lineHeight, + color: style.color, + backgroundColor: style.backgroundColor, + backgroundImage: style.backgroundImage, + borderTopColor: style.borderTopColor, + borderTopWidth: style.borderTopWidth, + padding: style.padding, + margin: style.margin, + cursor: style.cursor, + }, + }; +}; + +const measure = async (page, selectors) => + page.evaluate( + ({ selectors, measureSource }) => { + const measureElement = new Function(`return (${measureSource})`)(); + const result = {}; + for (const [name, selector] of Object.entries(selectors)) { + const element = document.querySelector(selector); + result[name] = element ? measureElement(element) : null; + } + return { + elements: result, + document: { + width: document.documentElement.scrollWidth, + height: document.documentElement.scrollHeight, + }, + }; + }, + { selectors, measureSource: rectAndStyle.toString() } + ); + +const browser = await chromium.launch({ headless: true }); +try { + const output = {}; + for (const viewport of [ + { name: 'desktop', width: 1000, height: 900 }, + { name: 'mobile', width: 500, height: 900 }, + ]) { + const context = await browser.newContext({ + viewport: { width: viewport.width, height: viewport.height }, + deviceScaleFactor: 1, + locale: 'ko-KR', + timezoneId: 'Asia/Seoul', + colorScheme: 'dark', + }); + const page = await context.newPage(); + const consoleErrors = []; + const failedResources = []; + page.on('console', (message) => { + if (message.type() === 'error') consoleErrors.push(message.text()); + }); + page.on('response', (response) => { + if (response.status() >= 400) failedResources.push(`${response.status()} ${response.url()}`); + }); + await login(context, page); + await page.goto(new URL('hwe/', baseUrl).toString(), { waitUntil: 'networkidle' }); + + await page.goto(new URL('hwe/b_myPage.php', baseUrl).toString(), { waitUntil: 'networkidle' }); + await page.locator('#container').waitFor(); + const myPage = await measure(page, { + body: 'body', + container: '#container', + title: '#container > .row:first-child', + infoColumn: '#container > .row:nth-child(2) > .col:first-child', + settingsColumn: '#container > .row:nth-child(2) > .col:nth-child(2)', + saveButton: '#set_my_setting', + firstSelect: 'select', + customCss: '#custom_css', + firstLogTitle: '#generalActionPlate', + }); + await page.screenshot({ path: resolve(artifactRoot, `ref-my-page-${viewport.name}.png`), fullPage: true }); + + await page.goto(new URL('hwe/a_traffic.php', baseUrl).toString(), { waitUntil: 'networkidle' }); + const traffic = await measure(page, { + body: 'body', + title: 'body > table:first-of-type', + chartLayout: 'body > table:nth-of-type(2)', + refreshChart: 'body > table:nth-of-type(2) > tbody > tr > td:first-child > table', + onlineChart: 'body > table:nth-of-type(2) > tbody > tr > td:nth-child(2) > table', + firstBigBar: '.big_bar', + suspectTable: 'body > table:nth-of-type(3)', + }); + await page.screenshot({ path: resolve(artifactRoot, `ref-traffic-${viewport.name}.png`), fullPage: true }); + + await page.goto(new URL('hwe/a_npcList.php', baseUrl).toString(), { waitUntil: 'networkidle' }); + const npcList = await measure(page, { + body: 'body', + title: 'body > table:first-of-type', + sortSelect: 'select[name="type"]', + list: 'body > table:nth-of-type(2)', + header: 'body > table:nth-of-type(2) tr:first-child', + footer: 'body > table:nth-of-type(3)', + }); + await page.screenshot({ path: resolve(artifactRoot, `ref-npc-list-${viewport.name}.png`), fullPage: true }); + + await page.goto(new URL('hwe/v_battleCenter.php', baseUrl).toString(), { waitUntil: 'networkidle' }); + try { + await page.locator('#container').waitFor({ timeout: 10_000 }); + } catch { + throw new Error( + `Reference battle center failed to mount: ${JSON.stringify({ + url: page.url(), + text: (await page.locator('body').innerText()).slice(0, 500), + html: (await page.content()).slice(-1_000), + consoleErrors, + failedResources, + })}` + ); + } + const battleCenter = await measure(page, { + body: 'body', + container: '#container', + topBar: '#container > :first-child', + selectorRow: '#container > .row:nth-child(2)', + previousButton: '#container > .row:nth-child(2) button:first-child', + firstSelect: '#container > .row:nth-child(2) select:first-of-type', + generalCard: '.header-cell', + firstLogHeader: '.header-cell:nth-of-type(1)', + }); + await page.screenshot({ + path: resolve(artifactRoot, `ref-battle-center-${viewport.name}.png`), + fullPage: true, + }); + output[viewport.name] = { myPage, traffic, npcList, battleCenter }; + await context.close(); + } + await writeFile(resolve(artifactRoot, 'computed-dom.json'), `${JSON.stringify(output, null, 2)}\n`); + process.stdout.write(`${JSON.stringify({ ok: true, artifactRoot, viewports: Object.keys(output) })}\n`); +} finally { + await browser.close(); +} From 7fc0850f83e722cdc9e074cba058c2700c87ce72 Mon Sep 17 00:00:00 2001 From: hided62 Date: Sun, 26 Jul 2026 05:22:30 +0000 Subject: [PATCH 02/16] Exclude concurrent public traffic work --- app/game-api/src/router/public/index.ts | 117 ------- app/game-api/test/publicTraffic.test.ts | 115 ------- app/game-frontend/src/router/index.ts | 6 - app/game-frontend/src/views/MainView.vue | 1 - app/game-frontend/src/views/PublicView.vue | 1 - app/game-frontend/src/views/TrafficView.vue | 343 -------------------- 6 files changed, 583 deletions(-) delete mode 100644 app/game-api/test/publicTraffic.test.ts delete mode 100644 app/game-frontend/src/views/TrafficView.vue diff --git a/app/game-api/src/router/public/index.ts b/app/game-api/src/router/public/index.ts index f4ef4d8..e7a0f59 100644 --- a/app/game-api/src/router/public/index.ts +++ b/app/game-api/src/router/public/index.ts @@ -42,14 +42,6 @@ type NationCountRow = { type NpcListSort = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8; -type TrafficHistoryItem = { - year: number; - month: number; - refresh: number; - online: number; - date: string; -}; - const PUBLIC_CACHE_TTL_SECONDS = 600; const buildPublicCacheKey = (ctx: GameApiContext, key: string): string => @@ -171,26 +163,6 @@ const readFiniteMetaNumber = (meta: Record, key: string): numbe return typeof value === 'number' && Number.isFinite(value) ? value : 0; }; -const parseTrafficHistory = (value: unknown): TrafficHistoryItem[] => { - if (!Array.isArray(value)) { - return []; - } - - const result: TrafficHistoryItem[] = []; - for (const item of value) { - const row = asRecord(item); - const year = readFiniteMetaNumber(row, 'year'); - const month = readFiniteMetaNumber(row, 'month'); - const refresh = readFiniteMetaNumber(row, 'refresh'); - const online = readFiniteMetaNumber(row, 'online'); - const date = typeof row.date === 'string' ? row.date : ''; - if (year > 0 && month > 0 && date) { - result.push({ year, month, refresh, online, date }); - } - } - return result; -}; - const compareString = (left: string, right: string): number => { if (left === right) { return 0; @@ -250,95 +222,6 @@ export const publicRouter = router({ getNationList: procedure.query(async ({ ctx }) => { return loadCachedNationList(ctx); }), - getTraffic: procedure.query(async ({ ctx }) => { - const worldState = await ctx.db.worldState.findFirst(); - if (!worldState) { - throw new TRPCError({ - code: 'PRECONDITION_FAILED', - message: 'World state is not initialized.', - }); - } - - const meta = asRecord(worldState.meta); - const rawOnlineSince = meta.lastTurnTime ?? meta.turntime; - const parsedOnlineSince = - typeof rawOnlineSince === 'string' || rawOnlineSince instanceof Date - ? new Date(rawOnlineSince) - : null; - const onlineSince = - parsedOnlineSince && Number.isFinite(parsedOnlineSince.getTime()) - ? parsedOnlineSince - : new Date(Date.now() - worldState.tickSeconds * 1_000); - const [accessTotal, currentOnline, topAccess] = await Promise.all([ - ctx.db.generalAccessLog.aggregate({ - _sum: { - refresh: true, - refreshScoreTotal: true, - }, - }), - ctx.db.generalAccessLog.count({ - where: { - lastRefresh: { - gte: onlineSince, - }, - }, - }), - ctx.db.generalAccessLog.findMany({ - orderBy: [{ refresh: 'desc' }, { generalId: 'asc' }], - take: 5, - select: { - generalId: true, - refresh: true, - refreshScoreTotal: true, - }, - }), - ]); - - const generalIds = topAccess.map((entry) => entry.generalId); - const generalRows = - generalIds.length > 0 - ? await ctx.db.general.findMany({ - where: { id: { in: generalIds } }, - select: { id: true, name: true }, - }) - : []; - const generalName = new Map(generalRows.map((general) => [general.id, general.name])); - const totalRefresh = accessTotal._sum.refresh ?? 0; - const totalRefreshScore = accessTotal._sum.refreshScoreTotal ?? 0; - const currentRefresh = Math.max(readFiniteMetaNumber(meta, 'refresh'), totalRefresh); - const history = parseTrafficHistory(meta.recentTraffic); - history.push({ - year: worldState.currentYear, - month: worldState.currentMonth, - refresh: currentRefresh, - online: currentOnline, - date: new Date().toISOString(), - }); - - return { - history, - maxRefresh: Math.max( - 1, - readFiniteMetaNumber(meta, 'maxrefresh'), - ...history.map((entry) => entry.refresh) - ), - maxOnline: Math.max(1, readFiniteMetaNumber(meta, 'maxonline'), ...history.map((entry) => entry.online)), - suspects: [ - { - generalId: null, - name: '접속자 총합', - refresh: totalRefresh, - refreshScoreTotal: totalRefreshScore, - }, - ...topAccess.map((entry) => ({ - generalId: entry.generalId, - name: generalName.get(entry.generalId) ?? `장수 ${entry.generalId}`, - refresh: entry.refresh, - refreshScoreTotal: entry.refreshScoreTotal, - })), - ], - }; - }), getGeneralList: procedure.query(async ({ ctx }) => { const [generals, nations] = await Promise.all([ ctx.db.general.findMany({ diff --git a/app/game-api/test/publicTraffic.test.ts b/app/game-api/test/publicTraffic.test.ts deleted file mode 100644 index 78008d8..0000000 --- a/app/game-api/test/publicTraffic.test.ts +++ /dev/null @@ -1,115 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -import type { RedisConnector } from '@sammo-ts/infra'; - -import { RedisAccessTokenStore } from '../src/auth/accessTokenStore.js'; -import { InMemoryFlushStore } from '../src/auth/flushStore.js'; -import { InMemoryBattleSimTransport } from '../src/battleSim/inMemoryTransport.js'; -import type { DatabaseClient, GameApiContext, GameProfile } from '../src/context.js'; -import { InMemoryTurnDaemonTransport } from '../src/daemon/inMemoryTransport.js'; -import { appRouter } from '../src/router.js'; - -const profile: GameProfile = { - id: 'che', - scenario: 'default', - name: 'che:default', -}; - -const buildContext = (): GameApiContext => { - const db = { - worldState: { - findFirst: async () => ({ - id: 1, - currentYear: 185, - currentMonth: 3, - tickSeconds: 600, - config: {}, - meta: { - lastTurnTime: '2026-07-26T03:00:00.000Z', - refresh: 12, - maxrefresh: 30, - maxonline: 5, - recentTraffic: [ - { - year: 185, - month: 2, - refresh: 30, - online: 5, - date: '2026-07-26 02:50:00', - }, - ], - }, - }), - }, - generalAccessLog: { - aggregate: async () => ({ - _sum: { - refresh: 12, - refreshScoreTotal: 21, - }, - }), - count: async (args: { where: { lastRefresh: { gte: Date } } }) => { - expect(args.where.lastRefresh.gte).toEqual(new Date('2026-07-26T03:00:00.000Z')); - return 2; - }, - findMany: async () => [ - { generalId: 7, refresh: 9, refreshScoreTotal: 15 }, - { generalId: 8, refresh: 3, refreshScoreTotal: 6 }, - ], - }, - general: { - findMany: async () => [ - { id: 7, name: '갑' }, - { id: 8, name: '을' }, - ], - }, - }; - const redis = { - get: async () => null, - set: async () => null, - } as unknown as RedisConnector['client']; - - return { - db: db as unknown as DatabaseClient, - turnDaemon: new InMemoryTurnDaemonTransport(), - battleSim: new InMemoryBattleSimTransport(), - profile, - auth: null, - uploadDir: 'uploads', - uploadPath: '/uploads', - uploadPublicUrl: null, - redis, - accessTokenStore: new RedisAccessTokenStore(redis, profile.name), - flushStore: new InMemoryFlushStore(), - gameTokenSecret: 'test-secret', - }; -}; - -describe('public.getTraffic', () => { - it('is public and returns only aggregate traffic plus allowlisted general names', async () => { - const result = await appRouter.createCaller(buildContext()).public.getTraffic(); - - expect(result.history).toHaveLength(2); - expect(result.history[0]).toEqual({ - year: 185, - month: 2, - refresh: 30, - online: 5, - date: '2026-07-26 02:50:00', - }); - expect(result.history[1]).toMatchObject({ - year: 185, - month: 3, - refresh: 12, - online: 2, - }); - expect(result.maxRefresh).toBe(30); - expect(result.maxOnline).toBe(5); - expect(result.suspects).toEqual([ - { generalId: null, name: '접속자 총합', refresh: 12, refreshScoreTotal: 21 }, - { generalId: 7, name: '갑', refresh: 9, refreshScoreTotal: 15 }, - { generalId: 8, name: '을', refresh: 3, refreshScoreTotal: 6 }, - ]); - expect(JSON.stringify(result)).not.toContain('userId'); - }); -}); diff --git a/app/game-frontend/src/router/index.ts b/app/game-frontend/src/router/index.ts index 63d0a16..ac0ccb2 100644 --- a/app/game-frontend/src/router/index.ts +++ b/app/game-frontend/src/router/index.ts @@ -32,7 +32,6 @@ import TroopView from '../views/TroopView.vue'; import YearbookView from '../views/YearbookView.vue'; import NationBettingView from '../views/NationBettingView.vue'; import NpcListView from '../views/NpcListView.vue'; -import TrafficView from '../views/TrafficView.vue'; import { useSessionStore } from '../stores/session'; const routes = [ @@ -258,11 +257,6 @@ const routes = [ requiresGeneral: true, }, }, - { - path: '/traffic', - name: 'traffic', - component: TrafficView, - }, { path: '/npc-list', name: 'npc-list', diff --git a/app/game-frontend/src/views/MainView.vue b/app/game-frontend/src/views/MainView.vue index 8459ebc..857e327 100644 --- a/app/game-frontend/src/views/MainView.vue +++ b/app/game-frontend/src/views/MainView.vue @@ -119,7 +119,6 @@ watch( 왕조일람 연감 천통국 베팅 - 접속량정보 빙의일람 게시판 전투 시뮬레이터 diff --git a/app/game-frontend/src/views/PublicView.vue b/app/game-frontend/src/views/PublicView.vue index 1624fcf..6c3684a 100644 --- a/app/game-frontend/src/views/PublicView.vue +++ b/app/game-frontend/src/views/PublicView.vue @@ -108,7 +108,6 @@ onMounted(() => { 장수 생성/빙의 메인으로 빙의일람 - 접속량정보 diff --git a/app/game-frontend/src/views/TrafficView.vue b/app/game-frontend/src/views/TrafficView.vue deleted file mode 100644 index 58b5f30..0000000 --- a/app/game-frontend/src/views/TrafficView.vue +++ /dev/null @@ -1,343 +0,0 @@ - - - - - From fa87f5565c9160b00aa640f3ff1b9dd5e4d36cab Mon Sep 17 00:00:00 2001 From: hided62 Date: Sun, 26 Jul 2026 05:23:25 +0000 Subject: [PATCH 03/16] Revert "Exclude concurrent public traffic work" This reverts commit 7fc0850f83e722cdc9e074cba058c2700c87ce72. --- app/game-api/src/router/public/index.ts | 117 +++++++ app/game-api/test/publicTraffic.test.ts | 115 +++++++ app/game-frontend/src/router/index.ts | 6 + app/game-frontend/src/views/MainView.vue | 1 + app/game-frontend/src/views/PublicView.vue | 1 + app/game-frontend/src/views/TrafficView.vue | 343 ++++++++++++++++++++ 6 files changed, 583 insertions(+) create mode 100644 app/game-api/test/publicTraffic.test.ts create mode 100644 app/game-frontend/src/views/TrafficView.vue diff --git a/app/game-api/src/router/public/index.ts b/app/game-api/src/router/public/index.ts index e7a0f59..f4ef4d8 100644 --- a/app/game-api/src/router/public/index.ts +++ b/app/game-api/src/router/public/index.ts @@ -42,6 +42,14 @@ type NationCountRow = { type NpcListSort = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8; +type TrafficHistoryItem = { + year: number; + month: number; + refresh: number; + online: number; + date: string; +}; + const PUBLIC_CACHE_TTL_SECONDS = 600; const buildPublicCacheKey = (ctx: GameApiContext, key: string): string => @@ -163,6 +171,26 @@ const readFiniteMetaNumber = (meta: Record, key: string): numbe return typeof value === 'number' && Number.isFinite(value) ? value : 0; }; +const parseTrafficHistory = (value: unknown): TrafficHistoryItem[] => { + if (!Array.isArray(value)) { + return []; + } + + const result: TrafficHistoryItem[] = []; + for (const item of value) { + const row = asRecord(item); + const year = readFiniteMetaNumber(row, 'year'); + const month = readFiniteMetaNumber(row, 'month'); + const refresh = readFiniteMetaNumber(row, 'refresh'); + const online = readFiniteMetaNumber(row, 'online'); + const date = typeof row.date === 'string' ? row.date : ''; + if (year > 0 && month > 0 && date) { + result.push({ year, month, refresh, online, date }); + } + } + return result; +}; + const compareString = (left: string, right: string): number => { if (left === right) { return 0; @@ -222,6 +250,95 @@ export const publicRouter = router({ getNationList: procedure.query(async ({ ctx }) => { return loadCachedNationList(ctx); }), + getTraffic: procedure.query(async ({ ctx }) => { + const worldState = await ctx.db.worldState.findFirst(); + if (!worldState) { + throw new TRPCError({ + code: 'PRECONDITION_FAILED', + message: 'World state is not initialized.', + }); + } + + const meta = asRecord(worldState.meta); + const rawOnlineSince = meta.lastTurnTime ?? meta.turntime; + const parsedOnlineSince = + typeof rawOnlineSince === 'string' || rawOnlineSince instanceof Date + ? new Date(rawOnlineSince) + : null; + const onlineSince = + parsedOnlineSince && Number.isFinite(parsedOnlineSince.getTime()) + ? parsedOnlineSince + : new Date(Date.now() - worldState.tickSeconds * 1_000); + const [accessTotal, currentOnline, topAccess] = await Promise.all([ + ctx.db.generalAccessLog.aggregate({ + _sum: { + refresh: true, + refreshScoreTotal: true, + }, + }), + ctx.db.generalAccessLog.count({ + where: { + lastRefresh: { + gte: onlineSince, + }, + }, + }), + ctx.db.generalAccessLog.findMany({ + orderBy: [{ refresh: 'desc' }, { generalId: 'asc' }], + take: 5, + select: { + generalId: true, + refresh: true, + refreshScoreTotal: true, + }, + }), + ]); + + const generalIds = topAccess.map((entry) => entry.generalId); + const generalRows = + generalIds.length > 0 + ? await ctx.db.general.findMany({ + where: { id: { in: generalIds } }, + select: { id: true, name: true }, + }) + : []; + const generalName = new Map(generalRows.map((general) => [general.id, general.name])); + const totalRefresh = accessTotal._sum.refresh ?? 0; + const totalRefreshScore = accessTotal._sum.refreshScoreTotal ?? 0; + const currentRefresh = Math.max(readFiniteMetaNumber(meta, 'refresh'), totalRefresh); + const history = parseTrafficHistory(meta.recentTraffic); + history.push({ + year: worldState.currentYear, + month: worldState.currentMonth, + refresh: currentRefresh, + online: currentOnline, + date: new Date().toISOString(), + }); + + return { + history, + maxRefresh: Math.max( + 1, + readFiniteMetaNumber(meta, 'maxrefresh'), + ...history.map((entry) => entry.refresh) + ), + maxOnline: Math.max(1, readFiniteMetaNumber(meta, 'maxonline'), ...history.map((entry) => entry.online)), + suspects: [ + { + generalId: null, + name: '접속자 총합', + refresh: totalRefresh, + refreshScoreTotal: totalRefreshScore, + }, + ...topAccess.map((entry) => ({ + generalId: entry.generalId, + name: generalName.get(entry.generalId) ?? `장수 ${entry.generalId}`, + refresh: entry.refresh, + refreshScoreTotal: entry.refreshScoreTotal, + })), + ], + }; + }), getGeneralList: procedure.query(async ({ ctx }) => { const [generals, nations] = await Promise.all([ ctx.db.general.findMany({ diff --git a/app/game-api/test/publicTraffic.test.ts b/app/game-api/test/publicTraffic.test.ts new file mode 100644 index 0000000..78008d8 --- /dev/null +++ b/app/game-api/test/publicTraffic.test.ts @@ -0,0 +1,115 @@ +import { describe, expect, it } from 'vitest'; + +import type { RedisConnector } from '@sammo-ts/infra'; + +import { RedisAccessTokenStore } from '../src/auth/accessTokenStore.js'; +import { InMemoryFlushStore } from '../src/auth/flushStore.js'; +import { InMemoryBattleSimTransport } from '../src/battleSim/inMemoryTransport.js'; +import type { DatabaseClient, GameApiContext, GameProfile } from '../src/context.js'; +import { InMemoryTurnDaemonTransport } from '../src/daemon/inMemoryTransport.js'; +import { appRouter } from '../src/router.js'; + +const profile: GameProfile = { + id: 'che', + scenario: 'default', + name: 'che:default', +}; + +const buildContext = (): GameApiContext => { + const db = { + worldState: { + findFirst: async () => ({ + id: 1, + currentYear: 185, + currentMonth: 3, + tickSeconds: 600, + config: {}, + meta: { + lastTurnTime: '2026-07-26T03:00:00.000Z', + refresh: 12, + maxrefresh: 30, + maxonline: 5, + recentTraffic: [ + { + year: 185, + month: 2, + refresh: 30, + online: 5, + date: '2026-07-26 02:50:00', + }, + ], + }, + }), + }, + generalAccessLog: { + aggregate: async () => ({ + _sum: { + refresh: 12, + refreshScoreTotal: 21, + }, + }), + count: async (args: { where: { lastRefresh: { gte: Date } } }) => { + expect(args.where.lastRefresh.gte).toEqual(new Date('2026-07-26T03:00:00.000Z')); + return 2; + }, + findMany: async () => [ + { generalId: 7, refresh: 9, refreshScoreTotal: 15 }, + { generalId: 8, refresh: 3, refreshScoreTotal: 6 }, + ], + }, + general: { + findMany: async () => [ + { id: 7, name: '갑' }, + { id: 8, name: '을' }, + ], + }, + }; + const redis = { + get: async () => null, + set: async () => null, + } as unknown as RedisConnector['client']; + + return { + db: db as unknown as DatabaseClient, + turnDaemon: new InMemoryTurnDaemonTransport(), + battleSim: new InMemoryBattleSimTransport(), + profile, + auth: null, + uploadDir: 'uploads', + uploadPath: '/uploads', + uploadPublicUrl: null, + redis, + accessTokenStore: new RedisAccessTokenStore(redis, profile.name), + flushStore: new InMemoryFlushStore(), + gameTokenSecret: 'test-secret', + }; +}; + +describe('public.getTraffic', () => { + it('is public and returns only aggregate traffic plus allowlisted general names', async () => { + const result = await appRouter.createCaller(buildContext()).public.getTraffic(); + + expect(result.history).toHaveLength(2); + expect(result.history[0]).toEqual({ + year: 185, + month: 2, + refresh: 30, + online: 5, + date: '2026-07-26 02:50:00', + }); + expect(result.history[1]).toMatchObject({ + year: 185, + month: 3, + refresh: 12, + online: 2, + }); + expect(result.maxRefresh).toBe(30); + expect(result.maxOnline).toBe(5); + expect(result.suspects).toEqual([ + { generalId: null, name: '접속자 총합', refresh: 12, refreshScoreTotal: 21 }, + { generalId: 7, name: '갑', refresh: 9, refreshScoreTotal: 15 }, + { generalId: 8, name: '을', refresh: 3, refreshScoreTotal: 6 }, + ]); + expect(JSON.stringify(result)).not.toContain('userId'); + }); +}); diff --git a/app/game-frontend/src/router/index.ts b/app/game-frontend/src/router/index.ts index ac0ccb2..63d0a16 100644 --- a/app/game-frontend/src/router/index.ts +++ b/app/game-frontend/src/router/index.ts @@ -32,6 +32,7 @@ import TroopView from '../views/TroopView.vue'; import YearbookView from '../views/YearbookView.vue'; import NationBettingView from '../views/NationBettingView.vue'; import NpcListView from '../views/NpcListView.vue'; +import TrafficView from '../views/TrafficView.vue'; import { useSessionStore } from '../stores/session'; const routes = [ @@ -257,6 +258,11 @@ const routes = [ requiresGeneral: true, }, }, + { + path: '/traffic', + name: 'traffic', + component: TrafficView, + }, { path: '/npc-list', name: 'npc-list', diff --git a/app/game-frontend/src/views/MainView.vue b/app/game-frontend/src/views/MainView.vue index 857e327..8459ebc 100644 --- a/app/game-frontend/src/views/MainView.vue +++ b/app/game-frontend/src/views/MainView.vue @@ -119,6 +119,7 @@ watch( 왕조일람 연감 천통국 베팅 + 접속량정보 빙의일람 게시판 전투 시뮬레이터 diff --git a/app/game-frontend/src/views/PublicView.vue b/app/game-frontend/src/views/PublicView.vue index 6c3684a..1624fcf 100644 --- a/app/game-frontend/src/views/PublicView.vue +++ b/app/game-frontend/src/views/PublicView.vue @@ -108,6 +108,7 @@ onMounted(() => { 장수 생성/빙의 메인으로 빙의일람 + 접속량정보 diff --git a/app/game-frontend/src/views/TrafficView.vue b/app/game-frontend/src/views/TrafficView.vue new file mode 100644 index 0000000..58b5f30 --- /dev/null +++ b/app/game-frontend/src/views/TrafficView.vue @@ -0,0 +1,343 @@ + + + + + From a77957aae346a9a3249474fc12e2bd3aed92c234 Mon Sep 17 00:00:00 2001 From: hided62 Date: Sun, 26 Jul 2026 05:24:00 +0000 Subject: [PATCH 04/16] feat: complete legacy ranking menu parity --- app/game-api/src/router/ranking/index.ts | 161 +++++--- app/game-api/test/rankingRouter.test.ts | 248 ++++++++++++ .../src/views/BestGeneralView.vue | 353 +++++++++++++++--- .../src/views/HallOfFameView.vue | 50 ++- docs/frontend-legacy-parity.md | 15 +- .../fixtures/canonical.ts | 76 ++++ .../reference-rankings.mjs | 155 ++++++++ .../visual-parity.spec.ts | 162 +++++++- 8 files changed, 1096 insertions(+), 124 deletions(-) create mode 100644 app/game-api/test/rankingRouter.test.ts create mode 100644 tools/frontend-legacy-parity/reference-rankings.mjs diff --git a/app/game-api/src/router/ranking/index.ts b/app/game-api/src/router/ranking/index.ts index e73f240..b170a83 100644 --- a/app/game-api/src/router/ranking/index.ts +++ b/app/game-api/src/router/ranking/index.ts @@ -2,8 +2,11 @@ import { z } from 'zod'; import { asRecord, HALL_OF_FAME_TYPES, type HallOfFameType } from '@sammo-ts/common'; import { ITEM_KEYS, ItemLoader, loadItemModules } from '@sammo-ts/logic/items/index.js'; +import type { ItemModule } from '@sammo-ts/logic/items/types.js'; +import { buildLegacyDefaultUniqueItemPool } from '@sammo-ts/logic/rewards/legacyUniqueItemPool.js'; +import { resolveUniqueConfig } from '@sammo-ts/logic/rewards/uniqueLottery.js'; -import { procedure, router } from '../../trpc.js'; +import { authedProcedure, procedure, router } from '../../trpc.js'; const DEFAULT_BG_COLOR = '#2b2b2b'; const DEFAULT_FG_COLOR = '#ffffff'; @@ -23,31 +26,31 @@ const readMetaNumber = (value: unknown): number => { const percentText = (value: number): string => `${(value * 100).toFixed(2)}%`; +const readOwnerDisplayName = (value: unknown): string | null => { + const meta = asRecord(value); + if (typeof meta.ownerName === 'string' && meta.ownerName.length > 0) { + return meta.ownerName; + } + if (typeof meta.owner_name === 'string' && meta.owner_name.length > 0) { + return meta.owner_name; + } + return null; +}; + const itemLoader = new ItemLoader(); -let cachedUniqueItems: Promise< - Array<{ key: string; name: string; slot: string; unique: boolean; buyable: boolean; info: string }> -> | null = null; +let cachedUniqueItems: Promise | null = null; const loadUniqueItems = () => { if (!cachedUniqueItems) { cachedUniqueItems = loadItemModules([...ITEM_KEYS], itemLoader).then((modules) => - modules - .filter((module) => module.unique && !module.buyable) - .map((module) => ({ - key: module.key, - name: module.name, - slot: module.slot, - unique: module.unique, - buyable: module.buyable, - info: module.info, - })) + modules.filter((module) => module.unique && !module.buyable) ); } return cachedUniqueItems; }; export const rankingRouter = router({ - getBestGeneral: procedure + getBestGeneral: authedProcedure .input( z .object({ @@ -57,7 +60,7 @@ export const rankingRouter = router({ ) .query(async ({ ctx, input }) => { const worldState = await ctx.db.worldState.findFirst({ - select: { meta: true }, + select: { meta: true, config: true }, }); const meta = asRecord(worldState?.meta); const isUnited = typeof meta.isUnited === 'number' && meta.isUnited !== 0; @@ -76,6 +79,7 @@ export const rankingRouter = router({ userId: true, picture: true, imageServer: true, + meta: true, experience: true, dedication: true, horseCode: true, @@ -185,7 +189,7 @@ export const rankingRouter = router({ let display = { id: general.id, name: general.name, - ownerName: general.userId ?? null, + ownerName: isUnited ? readOwnerDisplayName(general.meta) : null, nationName: nation?.name ?? '재야', bgColor: nation?.color ?? DEFAULT_BG_COLOR, fgColor: DEFAULT_FG_COLOR, @@ -217,46 +221,91 @@ export const rankingRouter = router({ }); const uniqueItems = await loadUniqueItems(); - const itemEntries = uniqueItems.map((item) => { - const owners = generals.filter((general) => { - if (item.slot === 'horse') { - return general.horseCode === item.key; + const itemRegistry = new Map(uniqueItems.map((item) => [item.key, item])); + const uniqueConfig = resolveUniqueConfig(asRecord(asRecord(worldState?.config).const)); + if (Object.keys(uniqueConfig.allItems).length === 0) { + uniqueConfig.allItems = buildLegacyDefaultUniqueItemPool(itemRegistry); + } + const activeAuctions = await ctx.db.auction.findMany({ + where: { + type: 'UNIQUE_ITEM', + status: { in: ['OPEN', 'FINALIZING'] }, + targetCode: { not: null }, + }, + select: { targetCode: true }, + }); + const auctionCounts = new Map(); + for (const auction of activeAuctions) { + if (auction.targetCode) { + auctionCounts.set(auction.targetCode, (auctionCounts.get(auction.targetCode) ?? 0) + 1); + } + } + const slotTitles = { + horse: '명 마', + weapon: '명 검', + book: '명 서', + item: '도 구', + } as const; + const itemEntries = (['horse', 'weapon', 'book', 'item'] as const).map((slot) => { + const configuredItems = Object.entries(uniqueConfig.allItems[slot] ?? {}).reverse(); + const entries = configuredItems.flatMap(([itemKey, rawCount]) => { + const item = itemRegistry.get(itemKey); + if (!item || item.buyable) { + return []; } - if (item.slot === 'weapon') { - return general.weaponCode === item.key; + const owners = generals + .filter((general) => { + if (slot === 'horse') { + return general.horseCode === itemKey; + } + if (slot === 'weapon') { + return general.weaponCode === itemKey; + } + if (slot === 'book') { + return general.bookCode === itemKey; + } + return general.itemCode === itemKey; + }) + .map((general) => { + const nation = nationMap.get(general.nationId) ?? null; + return { + id: general.id, + name: general.name, + nationName: nation?.name ?? '재야', + bgColor: nation?.color ?? DEFAULT_BG_COLOR, + fgColor: DEFAULT_FG_COLOR, + picture: general.picture ?? null, + imageServer: general.imageServer ?? 0, + }; + }); + for (let index = 0; index < (auctionCounts.get(itemKey) ?? 0); index += 1) { + owners.push({ + id: 0, + name: '경매중', + nationName: '-', + bgColor: '#00582c', + fgColor: '#ffffff', + picture: null, + imageServer: 0, + }); } - if (item.slot === 'book') { - return general.bookCode === item.key; - } - return general.itemCode === item.key; + const count = Math.max(0, Math.floor(rawCount)); + return Array.from({ length: count }, (_, index) => ({ + itemKey, + itemName: item.name, + itemInfo: item.info, + owner: owners[index] ?? { + id: 0, + name: '미발견', + nationName: '-', + bgColor: DEFAULT_BG_COLOR, + fgColor: DEFAULT_FG_COLOR, + picture: null, + imageServer: 0, + }, + })); }); - - const displayOwners = owners.length - ? owners.map((general) => { - const nation = nationMap.get(general.nationId) ?? null; - return { - id: general.id, - name: general.name, - nationName: nation?.name ?? '재야', - bgColor: nation?.color ?? DEFAULT_BG_COLOR, - fgColor: DEFAULT_FG_COLOR, - }; - }) - : [ - { - id: 0, - name: '미발견', - nationName: '-', - bgColor: DEFAULT_BG_COLOR, - fgColor: DEFAULT_FG_COLOR, - }, - ]; - - return { - title: item.name, - slot: item.slot, - owners: displayOwners, - }; + return { title: slotTitles[slot], slot, entries }; }); return { @@ -339,6 +388,10 @@ export const rankingRouter = router({ return { generalId: row.generalNo, name: String(aux.name ?? ''), + ownerName: + typeof aux.ownerDisplayName === 'string' && aux.ownerDisplayName.length > 0 + ? aux.ownerDisplayName + : null, nationName: String(aux.nationName ?? ''), bgColor: String(aux.bgColor ?? DEFAULT_BG_COLOR), fgColor: String(aux.fgColor ?? DEFAULT_FG_COLOR), diff --git a/app/game-api/test/rankingRouter.test.ts b/app/game-api/test/rankingRouter.test.ts new file mode 100644 index 0000000..7f897a6 --- /dev/null +++ b/app/game-api/test/rankingRouter.test.ts @@ -0,0 +1,248 @@ +import { describe, expect, it } from 'vitest'; + +import type { GameSessionTokenPayload } from '@sammo-ts/common/auth/gameToken'; +import type { RedisConnector } from '@sammo-ts/infra'; + +import { RedisAccessTokenStore } from '../src/auth/accessTokenStore.js'; +import { InMemoryFlushStore } from '../src/auth/flushStore.js'; +import { InMemoryBattleSimTransport } from '../src/battleSim/inMemoryTransport.js'; +import type { DatabaseClient, GameApiContext, GameProfile } from '../src/context.js'; +import { InMemoryTurnDaemonTransport } from '../src/daemon/inMemoryTransport.js'; +import { appRouter } from '../src/router.js'; + +const profile: GameProfile = { + id: 'che', + scenario: 'default', + name: 'che:default', +}; + +const auth: GameSessionTokenPayload = { + version: 1, + profile: 'che', + issuedAt: '2026-07-26T00:00:00.000Z', + expiresAt: '2026-07-27T00:00:00.000Z', + sessionId: 'ranking-session', + user: { + id: 'request-user-id', + username: 'ranking-user', + displayName: '조회자', + roles: [], + }, + sanctions: {}, +}; + +const generalRows = [ + { + id: 1, + name: '유비', + nationId: 1, + userId: 'private-user-id-1', + npcState: 0, + picture: '1.jpg', + imageServer: 0, + meta: { ownerName: '공개소유자' }, + experience: 1200, + dedication: 900, + horseCode: 'che_명마_15_적토마', + weaponCode: 'None', + bookCode: 'None', + itemCode: 'None', + }, + { + id: 2, + name: '빙의관우', + nationId: 1, + userId: 'private-user-id-2', + npcState: 1, + picture: null, + imageServer: 0, + meta: { owner_name: '빙의소유자' }, + experience: 1100, + dedication: 800, + horseCode: 'None', + weaponCode: 'None', + bookCode: 'None', + itemCode: 'None', + }, + { + id: 3, + name: 'NPC조조', + nationId: 2, + userId: null, + npcState: 2, + picture: null, + imageServer: 0, + meta: {}, + experience: 1300, + dedication: 1000, + horseCode: 'None', + weaponCode: 'None', + bookCode: 'None', + itemCode: 'None', + }, +] as const; + +const buildContext = (options?: { + authenticated?: boolean; + isUnited?: boolean; + includeOwnerDisplayName?: boolean; +}): GameApiContext => { + const db = { + worldState: { + findFirst: async () => ({ + meta: { isUnited: options?.isUnited ? 1 : 0 }, + config: { + const: { + allItems: { + horse: { che_명마_15_적토마: 2 }, + weapon: {}, + book: {}, + item: {}, + }, + }, + }, + }), + }, + nation: { + findMany: async () => [ + { id: 1, name: '촉', color: '#006400' }, + { id: 2, name: '위', color: '#8b0000' }, + ], + }, + general: { + findMany: async (args: { where: { npcState: { lt?: number; gte?: number } } }) => + generalRows.filter((general) => + args.where.npcState.gte !== undefined + ? general.npcState >= args.where.npcState.gte + : general.npcState < (args.where.npcState.lt ?? Number.POSITIVE_INFINITY) + ), + }, + rankData: { + findMany: async () => [ + { generalId: 1, type: 'firenum', value: 10 }, + { generalId: 2, type: 'firenum', value: 20 }, + { generalId: 3, type: 'firenum', value: 30 }, + ], + }, + auction: { + findMany: async () => [{ targetCode: 'che_명마_15_적토마' }], + }, + gameHistory: { + findMany: async () => [ + { season: 3, scenario: 22, scenarioName: '가상모드22' }, + { season: 3, scenario: 22, scenarioName: '가상모드22' }, + ], + }, + hallOfFame: { + findMany: async (args: { where: { type: string } }) => + args.where.type === 'experience' + ? [ + { + generalNo: 1, + value: 1200, + aux: { + name: '유비', + ownerName: 'private-hall-user-id', + ...(options?.includeOwnerDisplayName ? { ownerDisplayName: '공개소유자' } : {}), + nationName: '촉', + bgColor: '#006400', + fgColor: '#ffffff', + }, + }, + ] + : [], + }, + }; + const redis = { + get: async () => null, + set: async () => null, + } as unknown as RedisConnector['client']; + + return { + db: db as unknown as DatabaseClient, + turnDaemon: new InMemoryTurnDaemonTransport(), + battleSim: new InMemoryBattleSimTransport(), + profile, + auth: options?.authenticated === false ? null : auth, + uploadDir: 'uploads', + uploadPath: '/uploads', + uploadPublicUrl: null, + redis, + accessTokenStore: new RedisAccessTokenStore(redis, profile.name), + flushStore: new InMemoryFlushStore(), + gameTokenSecret: 'test-secret', + }; +}; + +describe('ranking.getBestGeneral', () => { + it('requires a game login even though the ranking is the same for every authenticated user', async () => { + await expect( + appRouter.createCaller(buildContext({ authenticated: false })).ranking.getBestGeneral({ view: 'user' }) + ).rejects.toMatchObject({ code: 'UNAUTHORIZED' }); + }); + + it('keeps possessed generals in the user view and redacts account identifiers before unification', async () => { + const result = await appRouter.createCaller(buildContext({ isUnited: false })).ranking.getBestGeneral({ + view: 'user', + }); + + expect(result.sections[0]?.entries.map((entry) => entry.id)).toEqual([1, 2]); + expect(result.sections[0]?.entries.map((entry) => entry.ownerName)).toEqual([null, null]); + expect(result.sections.find((section) => section.title === '계 략 성 공')?.entries).toEqual([ + expect.objectContaining({ id: 2, name: '???', nationName: '???', ownerName: null }), + expect.objectContaining({ id: 1, name: '???', nationName: '???', ownerName: null }), + ]); + expect(JSON.stringify(result)).not.toContain('private-user-id'); + }); + + it('uses display names only after unification and preserves configured item copies plus auctions', async () => { + const result = await appRouter.createCaller(buildContext({ isUnited: true })).ranking.getBestGeneral({ + view: 'user', + }); + + expect(result.sections[0]?.entries.map((entry) => entry.ownerName)).toEqual(['공개소유자', '빙의소유자']); + expect(result.uniqueItems.find((section) => section.slot === 'horse')?.entries).toEqual([ + expect.objectContaining({ + itemKey: 'che_명마_15_적토마', + owner: expect.objectContaining({ id: 1, name: '유비' }), + }), + expect.objectContaining({ + itemKey: 'che_명마_15_적토마', + owner: expect.objectContaining({ id: 0, name: '경매중' }), + }), + ]); + expect(JSON.stringify(result)).not.toContain('private-user-id'); + }); + + it('separates autonomous NPCs from users and possessed generals', async () => { + const result = await appRouter.createCaller(buildContext()).ranking.getBestGeneral({ view: 'npc' }); + expect(result.sections[0]?.entries.map((entry) => entry.id)).toEqual([3]); + }); +}); + +describe('ranking hall of fame', () => { + it('remains public and groups scenario counts', async () => { + const options = await appRouter + .createCaller(buildContext({ authenticated: false })) + .ranking.getHallOfFameOptions(); + expect(options).toEqual([ + { + season: 3, + scenarios: [{ id: 22, name: '가상모드22', count: 2 }], + }, + ]); + }); + + it('returns an explicit display name but never exposes the stored account identifier', async () => { + const result = await appRouter + .createCaller(buildContext({ authenticated: false, includeOwnerDisplayName: true })) + .ranking.getHallOfFame({ season: 3 }); + expect(result.sections[0]?.entries[0]?.ownerName).toBe('공개소유자'); + expect(JSON.stringify(result)).not.toContain('private-hall-user-id'); + + const redacted = await appRouter + .createCaller(buildContext({ authenticated: false })) + .ranking.getHallOfFame({ season: 3 }); + expect(redacted.sections[0]?.entries[0]?.ownerName).toBeNull(); + }); +}); diff --git a/app/game-frontend/src/views/BestGeneralView.vue b/app/game-frontend/src/views/BestGeneralView.vue index 63e2add..cf4345b 100644 --- a/app/game-frontend/src/views/BestGeneralView.vue +++ b/app/game-frontend/src/views/BestGeneralView.vue @@ -1,5 +1,7 @@ + + diff --git a/app/game-frontend/src/views/HallOfFameView.vue b/app/game-frontend/src/views/HallOfFameView.vue index 3ea0afa..f112db3 100644 --- a/app/game-frontend/src/views/HallOfFameView.vue +++ b/app/game-frontend/src/views/HallOfFameView.vue @@ -135,7 +135,7 @@ onMounted(async () => { -
{{ errorMessage }}
+
불러오는 중...
표시할 데이터가 없습니다.
@@ -171,6 +171,10 @@ onMounted(async () => {
+
+ 삼국지 모의전투 HiDCHe core2026 / KOEI의 이미지를 사용, 응용하였습니다 / 제작 : HideD / + Credit +
@@ -191,7 +195,7 @@ onMounted(async () => { .legacy-hall-title, .legacy-hall-bottom { - text-align: center; + text-align: left; } .legacy-hall-title { @@ -205,12 +209,33 @@ onMounted(async () => { } .scenario-search select { - min-width: 220px; + width: 189px; + height: 20px; border: 1px solid #555; background: #ddd; color: #303030; } +.legacy-button { + border: 0; + border-radius: 5.25px; + background: #375a7f; + padding: 5.25px 10.5px; + font-weight: 700; + line-height: 21px; +} + +.legacy-button:hover, +.legacy-button:focus, +.legacy-button:active { + background: #6b6b6b; +} + +.legacy-button:focus-visible { + outline: revert; + outline-offset: 0; +} + .legacy-message { border: 1px solid gray; padding: 12px; @@ -221,6 +246,15 @@ onMounted(async () => { color: #ff6b6b; } +.legacy-banner { + font-size: 13px; +} + +.legacy-banner a { + color: #fff; + text-decoration: underline; +} + .hall-sections { display: block; } @@ -235,7 +269,9 @@ onMounted(async () => { margin: 0; border-bottom: 1px solid gray; padding: 2px; - font-size: 1.17em; + font-size: calc(19px + 0.784615vw); + font-weight: 500; + line-height: 1.2; text-align: center; } @@ -275,7 +311,7 @@ onMounted(async () => { display: inline-block; width: 64px; height: 64px; - object-fit: cover; + object-fit: fill; } .hall-server, @@ -309,5 +345,9 @@ onMounted(async () => { .legacy-hall-page { width: 1000px; } + + .rankType { + font-size: 28px; + } } diff --git a/docs/frontend-legacy-parity.md b/docs/frontend-legacy-parity.md index 0162c50..252506f 100644 --- a/docs/frontend-legacy-parity.md +++ b/docs/frontend-legacy-parity.md @@ -19,6 +19,8 @@ tree instead of replacing images with layout-neutral placeholders. NPC list, including mutations and recoverable API failures. `tournament-betting.spec.ts` covers the separate tournament and tournament betting routes, including a recoverable failed bet. +`reference-rankings.mjs` records the authenticated PHP 명장일람 and public +명예의 전당 computed DOM without embedding the reference password. Run the suite from the core2026 repository root: @@ -50,7 +52,8 @@ storage, route guards, and image loading. | gateway OAuth join | `oauth_kakao/join.php` | 700px centered registration card, Kakao exchange/register success, retained-input API error, hover/focus | | game login hand-off | unauthenticated `hwe/index.php` redirect | `/che/login` delegates to `/gateway/` | | troop | `hwe/v_troop.php` | existing `app/game-frontend/e2e/troop.spec.ts` desktop/mobile geometry and interaction suite | -| hall of fame | `hwe/a_hallOfFame.php` | 500/1000px container, 100px ranking cells, 64px natural image, walnut/green textures, Pretendard, close-button focus | +| best general | `hwe/a_bestGeneral.php` | authenticated 500/1000px ranking and unique-item grids, user/NPC switch, 100/64px cell/image geometry, title/button computed styles, retained-data API error | +| hall of fame | `hwe/a_hallOfFame.php` | public 500/1000px container, 100px ranking cells, 64px natural image, title/button/select computed styles, scenario switch and retained-data API error | | yearbook | `hwe/v_history.php` | 1000px 700+300 desktop grid, 500px stacked grid, month navigation, legacy textures, success and API-error flows | | nation betting | `hwe/v_nationBetting.php` | 1000px/6-column desktop and 500px/3-column mobile grids, picked card style, payout table, success and retained-form error | | public NPC list | `hwe/a_npcList.php` | 1000px 12-column table with Chromium-expanded legacy widths, NPC color, eight sorts, retained table/sort after API error | @@ -85,6 +88,16 @@ Adding or changing a frontend route requires: Pixel snapshots may be added after these structural assertions pass. Dynamic regions must not be hidden merely to make a pixel threshold pass. +To refresh the PHP ranking evidence after building the ignored reference +webpack assets, run: + +```sh +REF_RANKING_URL=http://127.0.0.1:3400/sam/ \ +REF_RANKING_PASSWORD_FILE=/path/to/ignored/user1_password \ +REF_RANKING_ARTIFACT_DIR=/path/to/ignored/artifacts \ +node tools/frontend-legacy-parity/reference-rankings.mjs +``` + The nation office suite can be run independently: ```sh diff --git a/tools/frontend-legacy-parity/fixtures/canonical.ts b/tools/frontend-legacy-parity/fixtures/canonical.ts index 8d7d5cf..fd14ef8 100644 --- a/tools/frontend-legacy-parity/fixtures/canonical.ts +++ b/tools/frontend-legacy-parity/fixtures/canonical.ts @@ -75,6 +75,82 @@ export const canonicalFrontendFixture = { [2, '진', '#1976d2', 2], ], }, + bestGeneral: { + isUnited: true, + sections: [ + { + title: '명 성', + valueType: 'int', + entries: [ + { + id: 1, + name: '유비', + ownerName: '시각검증', + nationName: '촉', + bgColor: '#006400', + fgColor: '#ffffff', + picture: 'default.jpg', + imageServer: 0, + value: 12000, + printValue: '12,000', + }, + { + id: 2, + name: '조조', + ownerName: '검증계정', + nationName: '위', + bgColor: '#8b0000', + fgColor: '#ffffff', + picture: 'default.jpg', + imageServer: 0, + value: 11000, + printValue: '11,000', + }, + ], + }, + { + title: '계 급', + valueType: 'int', + entries: [], + }, + ], + uniqueItems: [ + { + title: '명 마', + slot: 'horse', + entries: [ + { + itemKey: 'che_명마_15_적토마', + itemName: '적토마', + itemInfo: '최고의 명마', + owner: { + id: 1, + name: '유비', + nationName: '촉', + bgColor: '#006400', + fgColor: '#ffffff', + picture: 'default.jpg', + imageServer: 0, + }, + }, + { + itemKey: 'che_명마_15_적토마', + itemName: '적토마', + itemInfo: '최고의 명마', + owner: { + id: 0, + name: '경매중', + nationName: '-', + bgColor: '#00582c', + fgColor: '#ffffff', + picture: null, + imageServer: 0, + }, + }, + ], + }, + ], + }, hallOptions: [ { season: 1, diff --git a/tools/frontend-legacy-parity/reference-rankings.mjs b/tools/frontend-legacy-parity/reference-rankings.mjs new file mode 100644 index 0000000..36e1a12 --- /dev/null +++ b/tools/frontend-legacy-parity/reference-rankings.mjs @@ -0,0 +1,155 @@ +import { chromium } from '@playwright/test'; +import { createHash } from 'node:crypto'; +import { mkdir, readFile, writeFile } from 'node:fs/promises'; +import { resolve } from 'node:path'; + +const baseUrl = process.env.REF_RANKING_URL ?? 'https://dev-sam-ref.hided.net/sam/'; +const username = process.env.REF_RANKING_USER ?? 'refuser1'; +const passwordFile = process.env.REF_RANKING_PASSWORD_FILE; +const artifactRoot = resolve(process.env.REF_RANKING_ARTIFACT_DIR ?? 'test-results/reference-rankings'); + +if (!passwordFile) { + throw new Error('REF_RANKING_PASSWORD_FILE is required.'); +} + +const password = (await readFile(passwordFile, 'utf8')).trim(); +await mkdir(artifactRoot, { recursive: true }); + +const login = async (context, page) => { + await page.goto(baseUrl, { waitUntil: 'networkidle', timeout: 60_000 }); + const globalSalt = await page.locator('#global_salt').inputValue(); + const passwordHash = createHash('sha512') + .update(globalSalt + password + globalSalt) + .digest('hex'); + const response = await context.request.post(new URL('api.php?path=Login/LoginByID', baseUrl).toString(), { + data: { username, password: passwordHash }, + }); + const result = await response.json(); + if (!response.ok() || result.result !== true) { + throw new Error('Reference login failed.'); + } +}; + +const measureRanking = async (page) => + page.evaluate(() => { + const pick = (selector) => { + const element = document.querySelector(selector); + if (!element) { + return null; + } + const rect = element.getBoundingClientRect(); + const style = getComputedStyle(element); + return { + rect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height }, + style: { + fontFamily: style.fontFamily, + fontSize: style.fontSize, + lineHeight: style.lineHeight, + backgroundImage: style.backgroundImage, + backgroundColor: style.backgroundColor, + color: style.color, + borderTopColor: style.borderTopColor, + borderTopWidth: style.borderTopWidth, + borderRadius: style.borderRadius, + padding: style.padding, + fontWeight: style.fontWeight, + cursor: style.cursor, + minHeight: style.minHeight, + objectFit: style.objectFit, + }, + }; + }; + const image = document.querySelector('.generalIcon'); + return { + title: document.title, + container: pick('#container'), + rankType: pick('.rankType'), + rankCell: pick('.rankView li'), + uniqueCell: pick('.rankView li.no_value'), + image: image + ? { + ...pick('.generalIcon'), + naturalWidth: image.naturalWidth, + naturalHeight: image.naturalHeight, + } + : null, + firstButton: pick('button, input[type="submit"], input[type="button"]'), + rankSectionCount: document.querySelectorAll('.rankView').length, + document: { + width: document.documentElement.scrollWidth, + height: document.documentElement.scrollHeight, + }, + }; + }); + +const browser = await chromium.launch({ headless: true }); +try { + const result = {}; + for (const viewport of [ + { name: 'desktop', width: 1365, height: 768 }, + { name: 'mobile', width: 390, height: 844 }, + ]) { + const context = await browser.newContext({ + viewport: { width: viewport.width, height: viewport.height }, + deviceScaleFactor: 1, + locale: 'ko-KR', + timezoneId: 'UTC', + colorScheme: 'dark', + ignoreHTTPSErrors: true, + }); + const page = await context.newPage(); + await login(context, page); + await page.goto(new URL('hwe/', baseUrl).toString(), { waitUntil: 'networkidle', timeout: 60_000 }); + + await page.goto(new URL('hwe/a_bestGeneral.php', baseUrl).toString(), { + waitUntil: 'networkidle', + timeout: 60_000, + }); + await page.locator('#container').waitFor(); + const bestGeneral = await measureRanking(page); + const userButton = page.getByRole('button', { name: '유저 보기' }); + await userButton.hover(); + bestGeneral.userButtonHover = await userButton.evaluate((element) => { + const style = getComputedStyle(element); + return { backgroundColor: style.backgroundColor, cursor: style.cursor }; + }); + await userButton.focus(); + bestGeneral.userButtonFocus = await userButton.evaluate((element) => getComputedStyle(element).outline); + await page.screenshot({ + path: resolve(artifactRoot, `ref-best-general-${viewport.name}.png`), + fullPage: true, + animations: 'disabled', + }); + + await page.goto(new URL('hwe/a_hallOfFame.php', baseUrl).toString(), { + waitUntil: 'networkidle', + timeout: 60_000, + }); + await page.locator('#container').waitFor(); + const hallOfFame = await measureRanking(page); + const scenario = page.locator('#by_scenario'); + hallOfFame.scenario = await scenario.evaluate((element) => { + const rect = element.getBoundingClientRect(); + const style = getComputedStyle(element); + return { + rect: { width: rect.width, height: rect.height }, + fontFamily: style.fontFamily, + fontSize: style.fontSize, + }; + }); + await scenario.focus(); + hallOfFame.scenarioFocus = await scenario.evaluate((element) => getComputedStyle(element).outline); + await page.screenshot({ + path: resolve(artifactRoot, `ref-hall-of-fame-${viewport.name}.png`), + fullPage: true, + animations: 'disabled', + }); + + result[viewport.name] = { bestGeneral, hallOfFame }; + await context.close(); + } + await writeFile(resolve(artifactRoot, 'computed-dom.json'), `${JSON.stringify(result, null, 2)}\n`); + process.stdout.write(`${JSON.stringify({ ok: true, artifactRoot, viewports: Object.keys(result) })}\n`); +} finally { + await browser.close(); +} diff --git a/tools/frontend-legacy-parity/visual-parity.spec.ts b/tools/frontend-legacy-parity/visual-parity.spec.ts index 85bba67..899a70a 100644 --- a/tools/frontend-legacy-parity/visual-parity.spec.ts +++ b/tools/frontend-legacy-parity/visual-parity.spec.ts @@ -139,6 +139,7 @@ const installAuthenticatedGameFixture = async (page: Page): Promise => { }; } if (operation === 'public.getMapLayout') return fixture.game.mapLayout; + if (operation === 'ranking.getBestGeneral') return fixture.game.bestGeneral; if (operation === 'yearbook.getRange') return fixture.game.yearbookRange; if (operation === 'yearbook.getHistory') return fixture.game.yearbook; if (operation === 'vote.getVoteList') return fixture.game.surveyList; @@ -387,6 +388,117 @@ test.describe('gateway legacy parity', () => { }); }); +test.describe('best general legacy parity', () => { + test.beforeEach(async ({ page }) => { + await installAuthenticatedGameFixture(page); + }); + + for (const viewport of [ + { name: 'desktop', width: 1365, height: 768, expectedWidth: 1000 }, + { name: 'mobile', width: 390, height: 844, expectedWidth: 500 }, + ]) { + test(`matches the ref fixed ranking grid on ${viewport.name}`, async ({ page }) => { + await page.setViewportSize(viewport); + await page.goto('http://127.0.0.1:15102/che/best-general'); + await expect(page.getByText('유비').first()).toBeVisible(); + await expect(page.locator('.rankView')).toHaveCount(3); + if (artifactRoot) { + await page.screenshot({ + path: resolve(artifactRoot, `best-general-core-${viewport.name}.png`), + fullPage: true, + animations: 'disabled', + }); + } + + const geometry = await page.evaluate(() => { + const container = document.querySelector('#best-general-container')!; + const item = document.querySelector('.rankView li')!; + const uniqueItem = document.querySelector('.rankView li.no-value')!; + const title = document.querySelector('.rankType')!; + const image = document.querySelector('.generalIcon')!; + return { + container: { + x: container.getBoundingClientRect().x, + width: container.getBoundingClientRect().width, + fontFamily: getComputedStyle(container).fontFamily, + fontSize: getComputedStyle(container).fontSize, + backgroundImage: getComputedStyle(container).backgroundImage, + }, + item: { + width: item.getBoundingClientRect().width, + minHeight: getComputedStyle(item).minHeight, + }, + uniqueItem: { + minHeight: getComputedStyle(uniqueItem).minHeight, + }, + title: { + fontSize: getComputedStyle(title).fontSize, + lineHeight: getComputedStyle(title).lineHeight, + backgroundImage: getComputedStyle(title).backgroundImage, + }, + image: { + width: image.getBoundingClientRect().width, + height: image.getBoundingClientRect().height, + naturalWidth: image.naturalWidth, + objectFit: getComputedStyle(image).objectFit, + }, + closeX: document + .querySelector('.legacy-ranking-title .legacy-button')! + .getBoundingClientRect().x, + }; + }); + + expect(geometry.container.width).toBe(viewport.expectedWidth); + expect(geometry.container.fontFamily).toContain('Pretendard'); + expect(geometry.container.fontSize).toBe('14px'); + expect(geometry.container.backgroundImage).toContain('back_walnut.jpg'); + expect(geometry.closeX).toBe(geometry.container.x); + expect(geometry.item).toEqual({ width: 100, minHeight: '149px' }); + expect(geometry.uniqueItem.minHeight).toBe('128px'); + expect(geometry.title).toMatchObject({ + fontSize: viewport.name === 'desktop' ? '28px' : '22.06px', + lineHeight: viewport.name === 'desktop' ? '33.6px' : '26.472px', + }); + expect(geometry.title.backgroundImage).toContain('back_green.jpg'); + expect(geometry.image).toMatchObject({ width: 64, height: 64, objectFit: 'fill' }); + expect(geometry.image.naturalWidth).toBeGreaterThan(0); + + const npcButton = page.getByRole('button', { name: 'NPC 보기' }); + await npcButton.hover(); + await expect(npcButton).toHaveCSS('background-color', 'rgb(107, 107, 107)'); + await npcButton.focus(); + await expect(npcButton).toBeFocused(); + await npcButton.click(); + await expect(npcButton).toHaveAttribute('aria-pressed', 'true'); + + const itemName = page.locator('.item-name').first(); + await itemName.hover(); + await expect(itemName).toHaveAttribute('title', '최고의 명마'); + }); + } + + test('keeps the current ranking and selected user type after an API error', async ({ page }) => { + await page.goto('http://127.0.0.1:15102/che/best-general'); + await expect(page.getByText('유비').first()).toBeVisible(); + await page.route('**/che/api/trpc/**', async (route) => { + if (operationNames(route).includes('ranking.getBestGeneral')) { + await route.fulfill({ + status: 500, + contentType: 'application/json', + body: JSON.stringify({ error: { message: '명장일람 조회에 실패했습니다.' } }), + }); + return; + } + await route.fallback(); + }); + const npcButton = page.getByRole('button', { name: 'NPC 보기' }); + await npcButton.click(); + await expect(page.getByRole('alert')).toBeVisible(); + await expect(page.getByText('유비').first()).toBeVisible(); + await expect(npcButton).toHaveAttribute('aria-pressed', 'true'); + }); +}); + test.describe('hall of fame legacy parity', () => { test.beforeEach(async ({ page }) => { await installHallFixture(page); @@ -401,6 +513,13 @@ test.describe('hall of fame legacy parity', () => { await page.goto('http://127.0.0.1:15102/che/hall-of-fame'); await expect(page.getByText('유비')).toBeVisible(); await expect(page.locator('.rankView')).toHaveCount(2); + if (artifactRoot) { + await page.screenshot({ + path: resolve(artifactRoot, `hall-of-fame-core-${viewport.name}.png`), + fullPage: true, + animations: 'disabled', + }); + } const geometry = await page.evaluate(() => { const container = document.querySelector('#container')!; @@ -409,7 +528,10 @@ test.describe('hall of fame legacy parity', () => { const titleStyle = getComputedStyle(document.querySelector('.rankType')!); const image = document.querySelector('.generalIcon')!; return { - container: container.getBoundingClientRect().width, + container: { + x: container.getBoundingClientRect().x, + width: container.getBoundingClientRect().width, + }, containerBackgroundImage: getComputedStyle(container).backgroundImage, item: { width: item.getBoundingClientRect().width, @@ -427,23 +549,57 @@ test.describe('hall of fame legacy parity', () => { naturalHeight: image.naturalHeight, objectFit: getComputedStyle(image).objectFit, }, + closeX: document + .querySelector('.legacy-hall-title .legacy-button')! + .getBoundingClientRect().x, }; }); - expect(geometry.container).toBe(viewport.expectedWidth); + expect(geometry.container.width).toBe(viewport.expectedWidth); + expect(geometry.closeX).toBe(geometry.container.x); expect(geometry.containerBackgroundImage).toContain('back_walnut.jpg'); expect(geometry.item.width).toBe(100); expect(geometry.title.fontFamily).toContain('Pretendard'); + expect(geometry.title.fontSize).toBe(viewport.name === 'desktop' ? '28px' : '22.06px'); expect(geometry.title.backgroundImage).toContain('back_green.jpg'); - expect(geometry.image).toMatchObject({ width: 64, height: 64, objectFit: 'cover' }); + expect(geometry.image).toMatchObject({ width: 64, height: 64, objectFit: 'fill' }); expect(geometry.image.naturalWidth).toBeGreaterThan(0); const close = page.getByRole('button', { name: '창 닫기' }).first(); await close.hover(); + await expect(close).toHaveCSS('background-color', 'rgb(107, 107, 107)'); await close.focus(); await expect(close).toBeFocused(); + + const scenario = page.getByLabel('시나리오 검색'); + await expect(scenario).toHaveCSS('width', '189px'); + await scenario.focus(); + await expect(scenario).toBeFocused(); + await scenario.selectOption('scenario:1:22'); + await expect(scenario).toHaveValue('scenario:1:22'); }); } + + test('keeps the selected scenario after a hall API error', async ({ page }) => { + await page.goto('http://127.0.0.1:15102/che/hall-of-fame'); + await expect(page.getByText('유비')).toBeVisible(); + await page.route('**/che/api/trpc/**', async (route) => { + if (operationNames(route).includes('ranking.getHallOfFame')) { + await route.fulfill({ + status: 500, + contentType: 'application/json', + body: JSON.stringify({ error: { message: '명예의 전당 조회에 실패했습니다.' } }), + }); + return; + } + await route.fallback(); + }); + const scenario = page.getByLabel('시나리오 검색'); + await scenario.selectOption('scenario:1:22'); + await expect(page.getByRole('alert')).toBeVisible(); + await expect(scenario).toHaveValue('scenario:1:22'); + await expect(page.getByText('유비')).toBeVisible(); + }); }); test('game login delegates to the gateway like the ref entry point', async ({ page }) => { From 48924428eed5c5a32f8a73cae9a510dbab506923 Mon Sep 17 00:00:00 2001 From: hided62 Date: Sun, 26 Jul 2026 05:24:31 +0000 Subject: [PATCH 05/16] Reapply "Exclude concurrent public traffic work" This reverts commit fa87f5565c9160b00aa640f3ff1b9dd5e4d36cab. --- app/game-api/src/router/public/index.ts | 117 ------- app/game-api/test/publicTraffic.test.ts | 115 ------- app/game-frontend/src/router/index.ts | 6 - app/game-frontend/src/views/MainView.vue | 1 - app/game-frontend/src/views/PublicView.vue | 1 - app/game-frontend/src/views/TrafficView.vue | 343 -------------------- 6 files changed, 583 deletions(-) delete mode 100644 app/game-api/test/publicTraffic.test.ts delete mode 100644 app/game-frontend/src/views/TrafficView.vue diff --git a/app/game-api/src/router/public/index.ts b/app/game-api/src/router/public/index.ts index f4ef4d8..e7a0f59 100644 --- a/app/game-api/src/router/public/index.ts +++ b/app/game-api/src/router/public/index.ts @@ -42,14 +42,6 @@ type NationCountRow = { type NpcListSort = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8; -type TrafficHistoryItem = { - year: number; - month: number; - refresh: number; - online: number; - date: string; -}; - const PUBLIC_CACHE_TTL_SECONDS = 600; const buildPublicCacheKey = (ctx: GameApiContext, key: string): string => @@ -171,26 +163,6 @@ const readFiniteMetaNumber = (meta: Record, key: string): numbe return typeof value === 'number' && Number.isFinite(value) ? value : 0; }; -const parseTrafficHistory = (value: unknown): TrafficHistoryItem[] => { - if (!Array.isArray(value)) { - return []; - } - - const result: TrafficHistoryItem[] = []; - for (const item of value) { - const row = asRecord(item); - const year = readFiniteMetaNumber(row, 'year'); - const month = readFiniteMetaNumber(row, 'month'); - const refresh = readFiniteMetaNumber(row, 'refresh'); - const online = readFiniteMetaNumber(row, 'online'); - const date = typeof row.date === 'string' ? row.date : ''; - if (year > 0 && month > 0 && date) { - result.push({ year, month, refresh, online, date }); - } - } - return result; -}; - const compareString = (left: string, right: string): number => { if (left === right) { return 0; @@ -250,95 +222,6 @@ export const publicRouter = router({ getNationList: procedure.query(async ({ ctx }) => { return loadCachedNationList(ctx); }), - getTraffic: procedure.query(async ({ ctx }) => { - const worldState = await ctx.db.worldState.findFirst(); - if (!worldState) { - throw new TRPCError({ - code: 'PRECONDITION_FAILED', - message: 'World state is not initialized.', - }); - } - - const meta = asRecord(worldState.meta); - const rawOnlineSince = meta.lastTurnTime ?? meta.turntime; - const parsedOnlineSince = - typeof rawOnlineSince === 'string' || rawOnlineSince instanceof Date - ? new Date(rawOnlineSince) - : null; - const onlineSince = - parsedOnlineSince && Number.isFinite(parsedOnlineSince.getTime()) - ? parsedOnlineSince - : new Date(Date.now() - worldState.tickSeconds * 1_000); - const [accessTotal, currentOnline, topAccess] = await Promise.all([ - ctx.db.generalAccessLog.aggregate({ - _sum: { - refresh: true, - refreshScoreTotal: true, - }, - }), - ctx.db.generalAccessLog.count({ - where: { - lastRefresh: { - gte: onlineSince, - }, - }, - }), - ctx.db.generalAccessLog.findMany({ - orderBy: [{ refresh: 'desc' }, { generalId: 'asc' }], - take: 5, - select: { - generalId: true, - refresh: true, - refreshScoreTotal: true, - }, - }), - ]); - - const generalIds = topAccess.map((entry) => entry.generalId); - const generalRows = - generalIds.length > 0 - ? await ctx.db.general.findMany({ - where: { id: { in: generalIds } }, - select: { id: true, name: true }, - }) - : []; - const generalName = new Map(generalRows.map((general) => [general.id, general.name])); - const totalRefresh = accessTotal._sum.refresh ?? 0; - const totalRefreshScore = accessTotal._sum.refreshScoreTotal ?? 0; - const currentRefresh = Math.max(readFiniteMetaNumber(meta, 'refresh'), totalRefresh); - const history = parseTrafficHistory(meta.recentTraffic); - history.push({ - year: worldState.currentYear, - month: worldState.currentMonth, - refresh: currentRefresh, - online: currentOnline, - date: new Date().toISOString(), - }); - - return { - history, - maxRefresh: Math.max( - 1, - readFiniteMetaNumber(meta, 'maxrefresh'), - ...history.map((entry) => entry.refresh) - ), - maxOnline: Math.max(1, readFiniteMetaNumber(meta, 'maxonline'), ...history.map((entry) => entry.online)), - suspects: [ - { - generalId: null, - name: '접속자 총합', - refresh: totalRefresh, - refreshScoreTotal: totalRefreshScore, - }, - ...topAccess.map((entry) => ({ - generalId: entry.generalId, - name: generalName.get(entry.generalId) ?? `장수 ${entry.generalId}`, - refresh: entry.refresh, - refreshScoreTotal: entry.refreshScoreTotal, - })), - ], - }; - }), getGeneralList: procedure.query(async ({ ctx }) => { const [generals, nations] = await Promise.all([ ctx.db.general.findMany({ diff --git a/app/game-api/test/publicTraffic.test.ts b/app/game-api/test/publicTraffic.test.ts deleted file mode 100644 index 78008d8..0000000 --- a/app/game-api/test/publicTraffic.test.ts +++ /dev/null @@ -1,115 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -import type { RedisConnector } from '@sammo-ts/infra'; - -import { RedisAccessTokenStore } from '../src/auth/accessTokenStore.js'; -import { InMemoryFlushStore } from '../src/auth/flushStore.js'; -import { InMemoryBattleSimTransport } from '../src/battleSim/inMemoryTransport.js'; -import type { DatabaseClient, GameApiContext, GameProfile } from '../src/context.js'; -import { InMemoryTurnDaemonTransport } from '../src/daemon/inMemoryTransport.js'; -import { appRouter } from '../src/router.js'; - -const profile: GameProfile = { - id: 'che', - scenario: 'default', - name: 'che:default', -}; - -const buildContext = (): GameApiContext => { - const db = { - worldState: { - findFirst: async () => ({ - id: 1, - currentYear: 185, - currentMonth: 3, - tickSeconds: 600, - config: {}, - meta: { - lastTurnTime: '2026-07-26T03:00:00.000Z', - refresh: 12, - maxrefresh: 30, - maxonline: 5, - recentTraffic: [ - { - year: 185, - month: 2, - refresh: 30, - online: 5, - date: '2026-07-26 02:50:00', - }, - ], - }, - }), - }, - generalAccessLog: { - aggregate: async () => ({ - _sum: { - refresh: 12, - refreshScoreTotal: 21, - }, - }), - count: async (args: { where: { lastRefresh: { gte: Date } } }) => { - expect(args.where.lastRefresh.gte).toEqual(new Date('2026-07-26T03:00:00.000Z')); - return 2; - }, - findMany: async () => [ - { generalId: 7, refresh: 9, refreshScoreTotal: 15 }, - { generalId: 8, refresh: 3, refreshScoreTotal: 6 }, - ], - }, - general: { - findMany: async () => [ - { id: 7, name: '갑' }, - { id: 8, name: '을' }, - ], - }, - }; - const redis = { - get: async () => null, - set: async () => null, - } as unknown as RedisConnector['client']; - - return { - db: db as unknown as DatabaseClient, - turnDaemon: new InMemoryTurnDaemonTransport(), - battleSim: new InMemoryBattleSimTransport(), - profile, - auth: null, - uploadDir: 'uploads', - uploadPath: '/uploads', - uploadPublicUrl: null, - redis, - accessTokenStore: new RedisAccessTokenStore(redis, profile.name), - flushStore: new InMemoryFlushStore(), - gameTokenSecret: 'test-secret', - }; -}; - -describe('public.getTraffic', () => { - it('is public and returns only aggregate traffic plus allowlisted general names', async () => { - const result = await appRouter.createCaller(buildContext()).public.getTraffic(); - - expect(result.history).toHaveLength(2); - expect(result.history[0]).toEqual({ - year: 185, - month: 2, - refresh: 30, - online: 5, - date: '2026-07-26 02:50:00', - }); - expect(result.history[1]).toMatchObject({ - year: 185, - month: 3, - refresh: 12, - online: 2, - }); - expect(result.maxRefresh).toBe(30); - expect(result.maxOnline).toBe(5); - expect(result.suspects).toEqual([ - { generalId: null, name: '접속자 총합', refresh: 12, refreshScoreTotal: 21 }, - { generalId: 7, name: '갑', refresh: 9, refreshScoreTotal: 15 }, - { generalId: 8, name: '을', refresh: 3, refreshScoreTotal: 6 }, - ]); - expect(JSON.stringify(result)).not.toContain('userId'); - }); -}); diff --git a/app/game-frontend/src/router/index.ts b/app/game-frontend/src/router/index.ts index 63d0a16..ac0ccb2 100644 --- a/app/game-frontend/src/router/index.ts +++ b/app/game-frontend/src/router/index.ts @@ -32,7 +32,6 @@ import TroopView from '../views/TroopView.vue'; import YearbookView from '../views/YearbookView.vue'; import NationBettingView from '../views/NationBettingView.vue'; import NpcListView from '../views/NpcListView.vue'; -import TrafficView from '../views/TrafficView.vue'; import { useSessionStore } from '../stores/session'; const routes = [ @@ -258,11 +257,6 @@ const routes = [ requiresGeneral: true, }, }, - { - path: '/traffic', - name: 'traffic', - component: TrafficView, - }, { path: '/npc-list', name: 'npc-list', diff --git a/app/game-frontend/src/views/MainView.vue b/app/game-frontend/src/views/MainView.vue index 8459ebc..857e327 100644 --- a/app/game-frontend/src/views/MainView.vue +++ b/app/game-frontend/src/views/MainView.vue @@ -119,7 +119,6 @@ watch( 왕조일람 연감 천통국 베팅 - 접속량정보 빙의일람 게시판 전투 시뮬레이터 diff --git a/app/game-frontend/src/views/PublicView.vue b/app/game-frontend/src/views/PublicView.vue index 1624fcf..6c3684a 100644 --- a/app/game-frontend/src/views/PublicView.vue +++ b/app/game-frontend/src/views/PublicView.vue @@ -108,7 +108,6 @@ onMounted(() => { 장수 생성/빙의 메인으로 빙의일람 - 접속량정보 diff --git a/app/game-frontend/src/views/TrafficView.vue b/app/game-frontend/src/views/TrafficView.vue deleted file mode 100644 index 58b5f30..0000000 --- a/app/game-frontend/src/views/TrafficView.vue +++ /dev/null @@ -1,343 +0,0 @@ - - - - - From d15ccb478f0208ca1b70cd91902a424e10e6424c Mon Sep 17 00:00:00 2001 From: hided62 Date: Sun, 26 Jul 2026 05:25:54 +0000 Subject: [PATCH 06/16] Revert "Reapply "Exclude concurrent public traffic work"" This reverts commit 48924428eed5c5a32f8a73cae9a510dbab506923. --- app/game-api/src/router/public/index.ts | 117 +++++++ app/game-api/test/publicTraffic.test.ts | 115 +++++++ app/game-frontend/src/router/index.ts | 6 + app/game-frontend/src/views/MainView.vue | 1 + app/game-frontend/src/views/PublicView.vue | 1 + app/game-frontend/src/views/TrafficView.vue | 343 ++++++++++++++++++++ 6 files changed, 583 insertions(+) create mode 100644 app/game-api/test/publicTraffic.test.ts create mode 100644 app/game-frontend/src/views/TrafficView.vue diff --git a/app/game-api/src/router/public/index.ts b/app/game-api/src/router/public/index.ts index e7a0f59..f4ef4d8 100644 --- a/app/game-api/src/router/public/index.ts +++ b/app/game-api/src/router/public/index.ts @@ -42,6 +42,14 @@ type NationCountRow = { type NpcListSort = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8; +type TrafficHistoryItem = { + year: number; + month: number; + refresh: number; + online: number; + date: string; +}; + const PUBLIC_CACHE_TTL_SECONDS = 600; const buildPublicCacheKey = (ctx: GameApiContext, key: string): string => @@ -163,6 +171,26 @@ const readFiniteMetaNumber = (meta: Record, key: string): numbe return typeof value === 'number' && Number.isFinite(value) ? value : 0; }; +const parseTrafficHistory = (value: unknown): TrafficHistoryItem[] => { + if (!Array.isArray(value)) { + return []; + } + + const result: TrafficHistoryItem[] = []; + for (const item of value) { + const row = asRecord(item); + const year = readFiniteMetaNumber(row, 'year'); + const month = readFiniteMetaNumber(row, 'month'); + const refresh = readFiniteMetaNumber(row, 'refresh'); + const online = readFiniteMetaNumber(row, 'online'); + const date = typeof row.date === 'string' ? row.date : ''; + if (year > 0 && month > 0 && date) { + result.push({ year, month, refresh, online, date }); + } + } + return result; +}; + const compareString = (left: string, right: string): number => { if (left === right) { return 0; @@ -222,6 +250,95 @@ export const publicRouter = router({ getNationList: procedure.query(async ({ ctx }) => { return loadCachedNationList(ctx); }), + getTraffic: procedure.query(async ({ ctx }) => { + const worldState = await ctx.db.worldState.findFirst(); + if (!worldState) { + throw new TRPCError({ + code: 'PRECONDITION_FAILED', + message: 'World state is not initialized.', + }); + } + + const meta = asRecord(worldState.meta); + const rawOnlineSince = meta.lastTurnTime ?? meta.turntime; + const parsedOnlineSince = + typeof rawOnlineSince === 'string' || rawOnlineSince instanceof Date + ? new Date(rawOnlineSince) + : null; + const onlineSince = + parsedOnlineSince && Number.isFinite(parsedOnlineSince.getTime()) + ? parsedOnlineSince + : new Date(Date.now() - worldState.tickSeconds * 1_000); + const [accessTotal, currentOnline, topAccess] = await Promise.all([ + ctx.db.generalAccessLog.aggregate({ + _sum: { + refresh: true, + refreshScoreTotal: true, + }, + }), + ctx.db.generalAccessLog.count({ + where: { + lastRefresh: { + gte: onlineSince, + }, + }, + }), + ctx.db.generalAccessLog.findMany({ + orderBy: [{ refresh: 'desc' }, { generalId: 'asc' }], + take: 5, + select: { + generalId: true, + refresh: true, + refreshScoreTotal: true, + }, + }), + ]); + + const generalIds = topAccess.map((entry) => entry.generalId); + const generalRows = + generalIds.length > 0 + ? await ctx.db.general.findMany({ + where: { id: { in: generalIds } }, + select: { id: true, name: true }, + }) + : []; + const generalName = new Map(generalRows.map((general) => [general.id, general.name])); + const totalRefresh = accessTotal._sum.refresh ?? 0; + const totalRefreshScore = accessTotal._sum.refreshScoreTotal ?? 0; + const currentRefresh = Math.max(readFiniteMetaNumber(meta, 'refresh'), totalRefresh); + const history = parseTrafficHistory(meta.recentTraffic); + history.push({ + year: worldState.currentYear, + month: worldState.currentMonth, + refresh: currentRefresh, + online: currentOnline, + date: new Date().toISOString(), + }); + + return { + history, + maxRefresh: Math.max( + 1, + readFiniteMetaNumber(meta, 'maxrefresh'), + ...history.map((entry) => entry.refresh) + ), + maxOnline: Math.max(1, readFiniteMetaNumber(meta, 'maxonline'), ...history.map((entry) => entry.online)), + suspects: [ + { + generalId: null, + name: '접속자 총합', + refresh: totalRefresh, + refreshScoreTotal: totalRefreshScore, + }, + ...topAccess.map((entry) => ({ + generalId: entry.generalId, + name: generalName.get(entry.generalId) ?? `장수 ${entry.generalId}`, + refresh: entry.refresh, + refreshScoreTotal: entry.refreshScoreTotal, + })), + ], + }; + }), getGeneralList: procedure.query(async ({ ctx }) => { const [generals, nations] = await Promise.all([ ctx.db.general.findMany({ diff --git a/app/game-api/test/publicTraffic.test.ts b/app/game-api/test/publicTraffic.test.ts new file mode 100644 index 0000000..78008d8 --- /dev/null +++ b/app/game-api/test/publicTraffic.test.ts @@ -0,0 +1,115 @@ +import { describe, expect, it } from 'vitest'; + +import type { RedisConnector } from '@sammo-ts/infra'; + +import { RedisAccessTokenStore } from '../src/auth/accessTokenStore.js'; +import { InMemoryFlushStore } from '../src/auth/flushStore.js'; +import { InMemoryBattleSimTransport } from '../src/battleSim/inMemoryTransport.js'; +import type { DatabaseClient, GameApiContext, GameProfile } from '../src/context.js'; +import { InMemoryTurnDaemonTransport } from '../src/daemon/inMemoryTransport.js'; +import { appRouter } from '../src/router.js'; + +const profile: GameProfile = { + id: 'che', + scenario: 'default', + name: 'che:default', +}; + +const buildContext = (): GameApiContext => { + const db = { + worldState: { + findFirst: async () => ({ + id: 1, + currentYear: 185, + currentMonth: 3, + tickSeconds: 600, + config: {}, + meta: { + lastTurnTime: '2026-07-26T03:00:00.000Z', + refresh: 12, + maxrefresh: 30, + maxonline: 5, + recentTraffic: [ + { + year: 185, + month: 2, + refresh: 30, + online: 5, + date: '2026-07-26 02:50:00', + }, + ], + }, + }), + }, + generalAccessLog: { + aggregate: async () => ({ + _sum: { + refresh: 12, + refreshScoreTotal: 21, + }, + }), + count: async (args: { where: { lastRefresh: { gte: Date } } }) => { + expect(args.where.lastRefresh.gte).toEqual(new Date('2026-07-26T03:00:00.000Z')); + return 2; + }, + findMany: async () => [ + { generalId: 7, refresh: 9, refreshScoreTotal: 15 }, + { generalId: 8, refresh: 3, refreshScoreTotal: 6 }, + ], + }, + general: { + findMany: async () => [ + { id: 7, name: '갑' }, + { id: 8, name: '을' }, + ], + }, + }; + const redis = { + get: async () => null, + set: async () => null, + } as unknown as RedisConnector['client']; + + return { + db: db as unknown as DatabaseClient, + turnDaemon: new InMemoryTurnDaemonTransport(), + battleSim: new InMemoryBattleSimTransport(), + profile, + auth: null, + uploadDir: 'uploads', + uploadPath: '/uploads', + uploadPublicUrl: null, + redis, + accessTokenStore: new RedisAccessTokenStore(redis, profile.name), + flushStore: new InMemoryFlushStore(), + gameTokenSecret: 'test-secret', + }; +}; + +describe('public.getTraffic', () => { + it('is public and returns only aggregate traffic plus allowlisted general names', async () => { + const result = await appRouter.createCaller(buildContext()).public.getTraffic(); + + expect(result.history).toHaveLength(2); + expect(result.history[0]).toEqual({ + year: 185, + month: 2, + refresh: 30, + online: 5, + date: '2026-07-26 02:50:00', + }); + expect(result.history[1]).toMatchObject({ + year: 185, + month: 3, + refresh: 12, + online: 2, + }); + expect(result.maxRefresh).toBe(30); + expect(result.maxOnline).toBe(5); + expect(result.suspects).toEqual([ + { generalId: null, name: '접속자 총합', refresh: 12, refreshScoreTotal: 21 }, + { generalId: 7, name: '갑', refresh: 9, refreshScoreTotal: 15 }, + { generalId: 8, name: '을', refresh: 3, refreshScoreTotal: 6 }, + ]); + expect(JSON.stringify(result)).not.toContain('userId'); + }); +}); diff --git a/app/game-frontend/src/router/index.ts b/app/game-frontend/src/router/index.ts index ac0ccb2..63d0a16 100644 --- a/app/game-frontend/src/router/index.ts +++ b/app/game-frontend/src/router/index.ts @@ -32,6 +32,7 @@ import TroopView from '../views/TroopView.vue'; import YearbookView from '../views/YearbookView.vue'; import NationBettingView from '../views/NationBettingView.vue'; import NpcListView from '../views/NpcListView.vue'; +import TrafficView from '../views/TrafficView.vue'; import { useSessionStore } from '../stores/session'; const routes = [ @@ -257,6 +258,11 @@ const routes = [ requiresGeneral: true, }, }, + { + path: '/traffic', + name: 'traffic', + component: TrafficView, + }, { path: '/npc-list', name: 'npc-list', diff --git a/app/game-frontend/src/views/MainView.vue b/app/game-frontend/src/views/MainView.vue index 857e327..8459ebc 100644 --- a/app/game-frontend/src/views/MainView.vue +++ b/app/game-frontend/src/views/MainView.vue @@ -119,6 +119,7 @@ watch( 왕조일람 연감 천통국 베팅 + 접속량정보 빙의일람 게시판 전투 시뮬레이터 diff --git a/app/game-frontend/src/views/PublicView.vue b/app/game-frontend/src/views/PublicView.vue index 6c3684a..1624fcf 100644 --- a/app/game-frontend/src/views/PublicView.vue +++ b/app/game-frontend/src/views/PublicView.vue @@ -108,6 +108,7 @@ onMounted(() => { 장수 생성/빙의 메인으로 빙의일람 + 접속량정보 diff --git a/app/game-frontend/src/views/TrafficView.vue b/app/game-frontend/src/views/TrafficView.vue new file mode 100644 index 0000000..58b5f30 --- /dev/null +++ b/app/game-frontend/src/views/TrafficView.vue @@ -0,0 +1,343 @@ + + + + + From 5fb2c109dd7003dc7811c1e9b952b47b66f79b6b Mon Sep 17 00:00:00 2001 From: hided62 Date: Sun, 26 Jul 2026 05:27:36 +0000 Subject: [PATCH 07/16] Verify traffic geometry in Chromium --- app/game-frontend/e2e/inGameMenus.spec.ts | 61 +++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/app/game-frontend/e2e/inGameMenus.spec.ts b/app/game-frontend/e2e/inGameMenus.spec.ts index ca33b24..8d7a3f2 100644 --- a/app/game-frontend/e2e/inGameMenus.spec.ts +++ b/app/game-frontend/e2e/inGameMenus.spec.ts @@ -146,6 +146,19 @@ const install = async (page: Page, state: FixtureState) => { autorun_user: {}, }, }); + if (operation === 'public.getTraffic') + return response({ + history: [ + { year: 185, month: 1, date: '2026-01-01T00:00:00.000Z', refresh: 120, online: 8 }, + { year: 185, month: 2, date: '2026-01-01T00:10:00.000Z', refresh: 240, online: 12 }, + ], + maxRefresh: 240, + maxOnline: 12, + suspects: [ + { generalId: null, name: '합계', refresh: 360, refreshScoreTotal: 36 }, + { generalId: 7, name: '검증장수', refresh: 240, refreshScoreTotal: 24 }, + ], + }); if (operation === 'general.getMyLog') return response({ type: 'generalAction', logs: [{ id: 1, text: '기록' }] }); if (operation === 'general.setMySetting') { @@ -182,6 +195,54 @@ const install = async (page: Page, state: FixtureState) => { }); }; +test('접속량정보 keeps the legacy public 1016px chart geometry', async ({ page }) => { + const state: FixtureState = { permission: 'member', myset: 0, settingMutations: [] }; + await install(page, state); + await page.setViewportSize({ width: 1200, height: 900 }); + await page.goto('traffic'); + await expect(page.locator('.chart-title').first()).toHaveText('접 속 량'); + + const geometry = await page.locator('#traffic-container').evaluate((element) => { + const rect = element.getBoundingClientRect(); + const title = element.querySelector('.title-table')!.getBoundingClientRect(); + const charts = [...element.querySelectorAll('.chart-table')].map((chart) => + chart.getBoundingClientRect() + ); + const row = element.querySelector('.chart-row')!.getBoundingClientRect(); + const bar = element.querySelector('.big-bar')!.getBoundingClientRect(); + const suspect = element.querySelector('.suspect-table')!.getBoundingClientRect(); + return { + width: rect.width, + minWidth: getComputedStyle(element).minWidth, + fontSize: getComputedStyle(element).fontSize, + fontFamily: getComputedStyle(element).fontFamily, + titleWidth: title.width, + chartWidths: charts.map((chart) => chart.width), + chartGap: charts[1]!.x - charts[0]!.right, + rowHeight: row.height, + barHeight: bar.height, + suspectWidth: suspect.width, + }; + }); + expect(geometry.width).toBe(1016); + expect(geometry.minWidth).toBe('1016px'); + expect(geometry.fontSize).toBe('14px'); + expect(geometry.fontFamily).toContain('Pretendard'); + expect(geometry.titleWidth).toBe(1000); + expect(geometry.chartWidths).toEqual([483, 483]); + expect(geometry.chartGap).toBe(26); + expect(geometry.rowHeight).toBe(31); + expect(geometry.barHeight).toBe(30); + expect(geometry.suspectWidth).toBeGreaterThanOrEqual(994); + await persistParityArtifact(page, 'traffic-desktop', geometry); + + await page.setViewportSize({ width: 500, height: 900 }); + const mobileWidth = await page + .locator('#traffic-container') + .evaluate((element) => element.getBoundingClientRect().width); + expect(mobileWidth).toBe(1016); +}); + test('내 정보&설정 keeps the legacy 1000px/500px geometry and saves in place', async ({ page }) => { const state: FixtureState = { permission: 'head', myset: 3, settingMutations: [] }; await install(page, state); From 6ee4c4d7252e85ecba7ba44162c761a869c11623 Mon Sep 17 00:00:00 2001 From: hided62 Date: Sun, 26 Jul 2026 05:28:29 +0000 Subject: [PATCH 08/16] test: resolve parity images from main checkout --- tools/frontend-legacy-parity/visual-parity.spec.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tools/frontend-legacy-parity/visual-parity.spec.ts b/tools/frontend-legacy-parity/visual-parity.spec.ts index 899a70a..1ad90f5 100644 --- a/tools/frontend-legacy-parity/visual-parity.spec.ts +++ b/tools/frontend-legacy-parity/visual-parity.spec.ts @@ -6,7 +6,7 @@ import { fileURLToPath } from 'node:url'; import { canonicalFrontendFixture as fixture } from './fixtures/canonical'; const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../..'); -const imageRoot = resolve(repositoryRoot, '../../image'); +const imageRoots = [resolve(repositoryRoot, '../image'), resolve(repositoryRoot, '../../image')]; const artifactRoot = process.env.FRONTEND_PARITY_ARTIFACT_DIR; const response = (data: unknown) => ({ result: { data } }); @@ -28,11 +28,11 @@ const installImages = async (page: Page): Promise => { await page.route('**/image/**', async (route) => { const pathname = decodeURIComponent(new URL(route.request().url()).pathname); const relative = pathname.replace(/^\/image\//, ''); - const candidates = [ + const candidates = imageRoots.flatMap((imageRoot) => [ resolve(imageRoot, relative), resolve(imageRoot, 'game', relative), resolve(imageRoot, 'icons', '22.jpg'), - ]; + ]); for (const candidate of candidates) { try { const body = await readFile(candidate); From 61b540384cc8336dc30a1e229434d21f87aca24f Mon Sep 17 00:00:00 2001 From: hided62 Date: Sun, 26 Jul 2026 05:30:28 +0000 Subject: [PATCH 09/16] feat(battle-sim): isolate authenticated worker lifecycle --- .../src/battleSim/inMemoryTransport.ts | 14 +- app/game-api/src/battleSim/redisTransport.ts | 39 +-- app/game-api/src/battleSim/transport.ts | 4 +- app/game-api/src/battleSim/types.ts | 1 + app/game-api/src/battleSim/worker.ts | 66 +++-- app/game-api/src/router/battle/index.ts | 18 +- app/game-api/src/trpc.ts | 34 ++- app/game-api/test/battleSimRouter.test.ts | 251 ++++++++++++++++-- app/game-api/test/battleSimTransport.test.ts | 69 +++++ .../test/battleSimWorker.integration.test.ts | 94 +++++++ app/gateway-api/src/adminRouter.ts | 1 + .../src/lobby/profileStatusService.ts | 7 +- .../src/orchestrator/gatewayOrchestrator.ts | 40 ++- .../test/orchestratorOperations.test.ts | 13 +- app/gateway-api/test/orchestratorPlan.test.ts | 11 + .../e2e/server-operations.spec.ts | 1 + app/gateway-frontend/src/views/AdminView.vue | 4 +- .../src/views/ServerOperationsView.vue | 15 +- 18 files changed, 583 insertions(+), 99 deletions(-) create mode 100644 app/game-api/test/battleSimTransport.test.ts create mode 100644 app/game-api/test/battleSimWorker.integration.test.ts diff --git a/app/game-api/src/battleSim/inMemoryTransport.ts b/app/game-api/src/battleSim/inMemoryTransport.ts index 6ad068d..efec98c 100644 --- a/app/game-api/src/battleSim/inMemoryTransport.ts +++ b/app/game-api/src/battleSim/inMemoryTransport.ts @@ -4,16 +4,20 @@ import type { BattleSimJobPayload, BattleSimResultPayload, BattleSimTransportRes import { processBattleSimJob } from './processor.js'; export class InMemoryBattleSimTransport { - private readonly results = new Map(); + private readonly results = new Map(); - public async simulate(payload: BattleSimJobPayload): Promise { + public async simulate(payload: BattleSimJobPayload, requesterUserId: string): Promise { const jobId = crypto.randomUUID(); const result = processBattleSimJob(payload); - this.results.set(jobId, result); + this.results.set(jobId, { requesterUserId, payload: result }); return { status: 'completed', jobId, payload: result }; } - public async getSimulationResult(jobId: string): Promise { - return this.results.get(jobId) ?? null; + public async getSimulationResult(jobId: string, requesterUserId: string): Promise { + const result = this.results.get(jobId); + if (!result || result.requesterUserId !== requesterUserId) { + return null; + } + return result.payload; } } diff --git a/app/game-api/src/battleSim/redisTransport.ts b/app/game-api/src/battleSim/redisTransport.ts index db7436e..295fcd2 100644 --- a/app/game-api/src/battleSim/redisTransport.ts +++ b/app/game-api/src/battleSim/redisTransport.ts @@ -44,16 +44,16 @@ export class RedisBattleSimTransport { this.resultTtlSeconds = options.resultTtlSeconds; } - private buildResultKey(jobId: string): string { - return `${this.keys.resultKeyPrefix}${jobId}`; + private buildResultKey(jobId: string, requesterUserId: string): string { + return `${this.keys.resultKeyPrefix}${encodeURIComponent(requesterUserId)}:${jobId}`; } - private buildNotifyKey(jobId: string): string { - return `${this.keys.notifyKeyPrefix}${jobId}`; + private buildNotifyKey(jobId: string, requesterUserId: string): string { + return `${this.keys.notifyKeyPrefix}${encodeURIComponent(requesterUserId)}:${jobId}`; } - private async readResult(jobId: string): Promise { - const raw = await this.client.get(this.buildResultKey(jobId)); + private async readResult(jobId: string, requesterUserId: string): Promise { + const raw = await this.client.get(this.buildResultKey(jobId, requesterUserId)); if (!raw) { return null; } @@ -64,44 +64,49 @@ export class RedisBattleSimTransport { } } - private async waitForResult(jobId: string, timeoutMs: number): Promise { - const existing = await this.readResult(jobId); + private async waitForResult( + jobId: string, + requesterUserId: string, + timeoutMs: number + ): Promise { + const existing = await this.readResult(jobId, requesterUserId); if (existing) { return existing; } - const notifyKey = this.buildNotifyKey(jobId); + const notifyKey = this.buildNotifyKey(jobId, requesterUserId); const timeoutSec = toTimeoutSeconds(timeoutMs); const signal = await this.client.blPop(notifyKey, timeoutSec); if (!parseBlPopValue(signal)) { return null; } - return this.readResult(jobId); + return this.readResult(jobId, requesterUserId); } - public async simulate(payload: BattleSimJobPayload): Promise { + public async simulate(payload: BattleSimJobPayload, requesterUserId: string): Promise { const jobId = crypto.randomUUID(); const job = { jobId, + requesterUserId, requestedAt: new Date().toISOString(), payload, }; await this.client.rPush(this.keys.queueKey, JSON.stringify(job)); - const result = await this.waitForResult(jobId, this.requestTimeoutMs); + const result = await this.waitForResult(jobId, requesterUserId, this.requestTimeoutMs); if (result) { return { status: 'completed', jobId, payload: result }; } return { status: 'queued', jobId }; } - public async getSimulationResult(jobId: string): Promise { - return this.readResult(jobId); + public async getSimulationResult(jobId: string, requesterUserId: string): Promise { + return this.readResult(jobId, requesterUserId); } - public async pushResult(jobId: string, payload: BattleSimResultPayload): Promise { - const resultKey = this.buildResultKey(jobId); - const notifyKey = this.buildNotifyKey(jobId); + public async pushResult(jobId: string, requesterUserId: string, payload: BattleSimResultPayload): Promise { + const resultKey = this.buildResultKey(jobId, requesterUserId); + const notifyKey = this.buildNotifyKey(jobId, requesterUserId); await this.client.set(resultKey, JSON.stringify(payload), { EX: this.resultTtlSeconds, }); diff --git a/app/game-api/src/battleSim/transport.ts b/app/game-api/src/battleSim/transport.ts index cd6592a..0932b81 100644 --- a/app/game-api/src/battleSim/transport.ts +++ b/app/game-api/src/battleSim/transport.ts @@ -1,6 +1,6 @@ import type { BattleSimJobPayload, BattleSimResultPayload, BattleSimTransportResponse } from './types.js'; export interface BattleSimTransport { - simulate(payload: BattleSimJobPayload): Promise; - getSimulationResult(jobId: string): Promise; + simulate(payload: BattleSimJobPayload, requesterUserId: string): Promise; + getSimulationResult(jobId: string, requesterUserId: string): Promise; } diff --git a/app/game-api/src/battleSim/types.ts b/app/game-api/src/battleSim/types.ts index 6850b20..41d522b 100644 --- a/app/game-api/src/battleSim/types.ts +++ b/app/game-api/src/battleSim/types.ts @@ -134,6 +134,7 @@ export interface BattleSimResultPayload { export interface BattleSimJob { jobId: string; + requesterUserId: string; requestedAt: string; payload: BattleSimJobPayload; } diff --git a/app/game-api/src/battleSim/worker.ts b/app/game-api/src/battleSim/worker.ts index 6829051..6c5a2ba 100644 --- a/app/game-api/src/battleSim/worker.ts +++ b/app/game-api/src/battleSim/worker.ts @@ -18,7 +18,11 @@ const parseBlPopValue = (result: RedisBlPopResult): string | null => { return result.element ?? null; }; -export const runBattleSimWorker = async (): Promise => { +export interface BattleSimWorkerOptions { + signal?: AbortSignal; +} + +export const runBattleSimWorker = async (options: BattleSimWorkerOptions = {}): Promise => { const config = resolveGameApiConfigFromEnv(); const redis = createRedisConnector(resolveRedisConfigFromEnv()); await redis.connect(); @@ -30,35 +34,49 @@ export const runBattleSimWorker = async (): Promise => { resultTtlSeconds: config.battleSimResultTtlSeconds, }); - const handleExit = async () => { - await redis.disconnect(); + let stopped = options.signal?.aborted ?? false; + const handleExit = () => { + stopped = true; + }; + const handleAbort = () => { + stopped = true; }; process.on('SIGINT', handleExit); process.on('SIGTERM', handleExit); + options.signal?.addEventListener('abort', handleAbort, { once: true }); - while (true) { - const item = await redis.client.blPop(keys.queueKey, 0); - const raw = parseBlPopValue(item); - if (!raw) { - continue; - } + try { + while (!stopped) { + // A finite block lets SIGTERM and test AbortSignal stop the worker without + // leaving a Redis operation or a detached lifecycle process behind. + const item = await redis.client.blPop(keys.queueKey, 1); + const raw = parseBlPopValue(item); + if (!raw) { + continue; + } - let job: BattleSimJob | null = null; - try { - job = JSON.parse(raw) as BattleSimJob; - } catch { - continue; - } + let job: BattleSimJob | null = null; + try { + job = JSON.parse(raw) as BattleSimJob; + } catch { + continue; + } - try { - const result = processBattleSimJob(job.payload); - await transport.pushResult(job.jobId, result); - } catch (error) { - const reason = error instanceof Error ? error.message : '전투 시뮬레이션 오류'; - await transport.pushResult(job.jobId, { - result: false, - reason, - }); + try { + const result = processBattleSimJob(job.payload); + await transport.pushResult(job.jobId, job.requesterUserId, result); + } catch (error) { + const reason = error instanceof Error ? error.message : '전투 시뮬레이션 오류'; + await transport.pushResult(job.jobId, job.requesterUserId, { + result: false, + reason, + }); + } } + } finally { + process.off('SIGINT', handleExit); + process.off('SIGTERM', handleExit); + options.signal?.removeEventListener('abort', handleAbort); + await redis.disconnect(); } }; diff --git a/app/game-api/src/router/battle/index.ts b/app/game-api/src/router/battle/index.ts index 172e595..f77da37 100644 --- a/app/game-api/src/router/battle/index.ts +++ b/app/game-api/src/router/battle/index.ts @@ -4,7 +4,7 @@ import { z } from 'zod'; import { asRecord } from '@sammo-ts/common'; import { getDexLevel } from '@sammo-ts/logic'; -import { authedProcedure, procedure, router } from '../../trpc.js'; +import { authedProcedure, readOnlyAuthedProcedure, router } from '../../trpc.js'; import { buildBattleSimEnvironment, buildBattleSimJobPayload } from '../../battleSim/environment.js'; import { zBattleSimJobId, zBattleSimRequest } from '../../battleSim/schema.js'; import { @@ -30,6 +30,14 @@ const normalizeOptionalKey = (value: string | null): string | null => { return value; }; +const getAuthenticatedUserId = (auth: { user: { id: string } } | null): string => { + const userId = auth?.user.id; + if (!userId) { + throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Unauthorized' }); + } + return userId; +}; + const resolveExpLevel = (meta: Record, experience: number): number => { const expLevel = meta.explevel ?? meta.expLevel; if (typeof expLevel === 'number' && Number.isFinite(expLevel)) { @@ -48,7 +56,7 @@ const resolveDexValue = (meta: Record, key: string): number => }; export const battleRouter = router({ - simulate: procedure.input(zBattleSimRequest).mutation(async ({ ctx, input }) => { + simulate: readOnlyAuthedProcedure.input(zBattleSimRequest).mutation(async ({ ctx, input }) => { const worldState = await ctx.db.worldState.findFirst(); if (!worldState) { throw new TRPCError({ @@ -58,10 +66,10 @@ export const battleRouter = router({ } const payload = await buildBattleSimJobPayload(worldState, input, ctx.profile.id); - return ctx.battleSim.simulate(payload); + return ctx.battleSim.simulate(payload, getAuthenticatedUserId(ctx.auth)); }), - getSimulation: procedure.input(zBattleSimJobId).query(async ({ ctx, input }) => { - const result = await ctx.battleSim.getSimulationResult(input.jobId); + getSimulation: readOnlyAuthedProcedure.input(zBattleSimJobId).query(async ({ ctx, input }) => { + const result = await ctx.battleSim.getSimulationResult(input.jobId, getAuthenticatedUserId(ctx.auth)); if (!result) { return { status: 'queued', jobId: input.jobId }; } diff --git a/app/game-api/src/trpc.ts b/app/game-api/src/trpc.ts index a8ce3e9..4a3e8dc 100644 --- a/app/game-api/src/trpc.ts +++ b/app/game-api/src/trpc.ts @@ -7,6 +7,21 @@ import { DuplicateInputEventError, executeInputEvent } from './inputEventBoundar const t = initTRPC.context().create(); +const requireAuthMiddleware = t.middleware(({ ctx, next }) => { + if (!ctx.auth) { + throw new TRPCError({ + code: 'UNAUTHORIZED', + message: 'Unauthorized', + }); + } + return next({ + ctx: { + ...ctx, + auth: ctx.auth, + }, + }); +}); + const inputEventMiddleware = t.middleware(async ({ ctx, type, path, next }) => { if (type !== 'mutation' || !ctx.db.$transaction) { return next(); @@ -46,17 +61,8 @@ const inputEventMiddleware = t.middleware(async ({ ctx, type, path, next }) => { export const router = t.router; export const procedure = t.procedure.use(inputEventMiddleware); -export const authedProcedure: typeof procedure = procedure.use(({ ctx, next }) => { - if (!ctx.auth) { - throw new TRPCError({ - code: 'UNAUTHORIZED', - message: 'Unauthorized', - }); - } - return next({ - ctx: { - ...ctx, - auth: ctx.auth, - }, - }); -}); +export const authedProcedure: typeof procedure = procedure.use(requireAuthMiddleware); + +// 시뮬레이터처럼 게임 상태를 변경하지 않는 계산은 input-event transaction과 +// 이벤트 원장을 만들지 않는다. 인증은 유지하되 lifecycle DB 경계 밖에서 실행한다. +export const readOnlyAuthedProcedure: typeof procedure = t.procedure.use(requireAuthMiddleware); diff --git a/app/game-api/test/battleSimRouter.test.ts b/app/game-api/test/battleSimRouter.test.ts index d0d0f49..3d7192d 100644 --- a/app/game-api/test/battleSimRouter.test.ts +++ b/app/game-api/test/battleSimRouter.test.ts @@ -19,19 +19,30 @@ const profile: GameProfile = { class QueuedBattleSimTransport implements BattleSimTransport { public simulateCalls = 0; public lastPayload: BattleSimJobPayload | null = null; + public lastRequesterUserId: string | null = null; + private readonly owners = new Map(); private readonly results = new Map(); - async simulate(payload: BattleSimJobPayload) { + async simulate(payload: BattleSimJobPayload, requesterUserId: string) { this.simulateCalls += 1; this.lastPayload = payload; - return { status: 'queued', jobId: 'job-1' } as const; + this.lastRequesterUserId = requesterUserId; + const jobId = `job-${this.simulateCalls}`; + this.owners.set(jobId, requesterUserId); + return { status: 'queued', jobId } as const; } - async getSimulationResult(jobId: string) { + async getSimulationResult(jobId: string, requesterUserId: string) { + if (this.owners.get(jobId) !== requesterUserId) { + return null; + } return this.results.get(jobId) ?? null; } - pushResult(jobId: string, payload: BattleSimResultPayload) { + pushResult(jobId: string, requesterUserId: string, payload: BattleSimResultPayload) { + if (this.owners.get(jobId) !== requesterUserId) { + throw new Error('requester mismatch'); + } this.results.set(jobId, payload); } } @@ -194,8 +205,13 @@ const buildBattleRequest = () => ({ }, }); -const buildContext = (options: { state: WorldStateRow; battleSim: BattleSimTransport }): GameApiContext => { - const db = { +const buildContext = (options: { + state: WorldStateRow; + battleSim: BattleSimTransport; + userId?: string | null; + db?: Partial; +}): GameApiContext => { + const db = options.db ?? { worldState: { findFirst: async () => options.state, }, @@ -207,20 +223,23 @@ const buildContext = (options: { state: WorldStateRow; battleSim: BattleSimTrans }, profile.name ); - const auth: GameSessionTokenPayload = { - version: 1, - profile: profile.name, - issuedAt: new Date('2026-01-01T00:00:00Z').toISOString(), - expiresAt: new Date('2026-01-02T00:00:00Z').toISOString(), - sessionId: 'session-1', - user: { - id: 'user-1', - username: 'tester', - displayName: 'Tester', - roles: [], - }, - sanctions: {}, - }; + const auth: GameSessionTokenPayload | null = + options.userId === null + ? null + : { + version: 1, + profile: profile.name, + issuedAt: new Date('2026-01-01T00:00:00Z').toISOString(), + expiresAt: new Date('2026-01-02T00:00:00Z').toISOString(), + sessionId: 'session-1', + user: { + id: options.userId ?? 'user-1', + username: 'tester', + displayName: 'Tester', + roles: [], + }, + sanctions: {}, + }; return { db: db as unknown as DatabaseClient, turnDaemon: new InMemoryTurnDaemonTransport(), @@ -255,14 +274,204 @@ describe('battle router orchestration', () => { const response = await caller.battle.simulate(buildBattleRequest()); expect(response.status).toBe('queued'); expect(battleSim.simulateCalls).toBe(1); + expect(battleSim.lastRequesterUserId).toBe('user-1'); const queued = await caller.battle.getSimulation({ jobId: response.jobId }); expect(queued.status).toBe('queued'); - battleSim.pushResult(response.jobId, { result: true, reason: 'success', avgWar: 1 }); + battleSim.pushResult(response.jobId, 'user-1', { result: true, reason: 'success', avgWar: 1 }); const completed = await caller.battle.getSimulation({ jobId: response.jobId }); expect(completed.status).toBe('completed'); expect(completed.payload?.result).toBe(true); }); + + it('requires login, allows a user without a general, and does not open an input-event transaction', async () => { + const battleSim = new QueuedBattleSimTransport(); + const state: WorldStateRow = { + id: 1, + scenarioCode: 'default', + currentYear: 200, + currentMonth: 1, + tickSeconds: 600, + config: {}, + meta: {}, + updatedAt: new Date('2026-01-01T00:00:00Z'), + }; + let transactionCalls = 0; + const db = { + worldState: { findFirst: async () => state }, + $transaction: async () => { + transactionCalls += 1; + throw new Error('simulation must not create an input event transaction'); + }, + } as unknown as DatabaseClient; + + const anonymous = appRouter.createCaller(buildContext({ state, battleSim, userId: null, db })); + await expect(anonymous.battle.simulate(buildBattleRequest())).rejects.toMatchObject({ + code: 'UNAUTHORIZED', + }); + + const noGeneralUser = appRouter.createCaller( + buildContext({ state, battleSim, userId: 'user-without-general', db }) + ); + await expect(noGeneralUser.battle.simulate(buildBattleRequest())).resolves.toMatchObject({ + status: 'queued', + }); + expect(transactionCalls).toBe(0); + expect(battleSim.lastRequesterUserId).toBe('user-without-general'); + }); + + it('does not expose queued results across authenticated users', async () => { + const battleSim = new QueuedBattleSimTransport(); + const state: WorldStateRow = { + id: 1, + scenarioCode: 'default', + currentYear: 200, + currentMonth: 1, + tickSeconds: 600, + config: {}, + meta: {}, + updatedAt: new Date('2026-01-01T00:00:00Z'), + }; + const owner = appRouter.createCaller(buildContext({ state, battleSim, userId: 'owner-user' })); + const other = appRouter.createCaller(buildContext({ state, battleSim, userId: 'other-user' })); + const response = await owner.battle.simulate(buildBattleRequest()); + battleSim.pushResult(response.jobId, 'owner-user', { result: true, reason: 'success', avgWar: 7 }); + + await expect(owner.battle.getSimulation({ jobId: response.jobId })).resolves.toMatchObject({ + status: 'completed', + payload: { avgWar: 7 }, + }); + await expect(other.battle.getSimulation({ jobId: response.jobId })).resolves.toEqual({ + status: 'queued', + jobId: response.jobId, + }); + }); +}); + +describe('battle simulator general import permissions', () => { + const state: WorldStateRow = { + id: 1, + scenarioCode: 'default', + currentYear: 200, + currentMonth: 1, + tickSeconds: 600, + config: {}, + meta: {}, + updatedAt: new Date('2026-01-01T00:00:00Z'), + }; + + const buildGeneral = (overrides: Record) => ({ + id: 1, + userId: 'same-nation-user', + name: '관전자', + npcState: 0, + nationId: 1, + leadership: 70, + strength: 71, + intel: 72, + officerLevel: 1, + injury: 0, + rice: 9000, + crew: 5000, + crewTypeId: 100, + atmos: 100, + train: 100, + experience: 400, + horseCode: null, + weaponCode: null, + bookCode: null, + itemCode: null, + personalCode: null, + special2Code: null, + meta: {}, + ...overrides, + }); + + const actor = buildGeneral({ id: 1, userId: 'same-nation-user', nationId: 1 }); + const ally = buildGeneral({ + id: 2, + userId: 'ally-user', + name: '아군 장수', + nationId: 1, + officerLevel: 4, + rice: 4321, + crew: 3210, + train: 97, + atmos: 96, + horseCode: 'che_적토마', + weaponCode: 'che_의천검', + bookCode: 'che_손자병법', + itemCode: 'che_옥새', + meta: { + dex1: 10000, + rank_warnum: 33, + rank_killnum: 22, + rank_killcrew: 1111, + }, + }); + const foreignActor = buildGeneral({ id: 3, userId: 'foreign-user', nationId: 2 }); + const generals = [actor, ally, foreignActor]; + const db = { + worldState: { findFirst: async () => state }, + general: { + findFirst: async ({ where }: { where: { userId: string } }) => + generals.find((general) => general.userId === where.userId) ?? null, + findUnique: async ({ where }: { where: { id: number } }) => + generals.find((general) => general.id === where.id) ?? null, + }, + } as unknown as DatabaseClient; + + it('returns full ally details to the same nation but redacts them for another nation', async () => { + const battleSim = new QueuedBattleSimTransport(); + const sameNation = appRouter.createCaller(buildContext({ state, battleSim, userId: 'same-nation-user', db })); + const foreign = appRouter.createCaller(buildContext({ state, battleSim, userId: 'foreign-user', db })); + + const visible = await sameNation.battle.getGeneralDetail({ generalId: ally.id }); + expect(visible.general).toMatchObject({ + name: '아군 장수', + officer_level: 4, + horse: 'che_적토마', + crew: 3210, + rice: 4321, + train: 97, + atmos: 96, + warnum: 33, + killnum: 22, + killcrew: 1111, + }); + + const redacted = await foreign.battle.getGeneralDetail({ generalId: ally.id }); + expect(redacted.general).toMatchObject({ + name: '아군 장수', + officer_level: 1, + horse: null, + weapon: null, + book: null, + item: null, + crew: 0, + rice: 10000, + dex1: 0, + warnum: 0, + killnum: 0, + killcrew: 0, + }); + }); + + it('requires a game general only for server-side general import', async () => { + const caller = appRouter.createCaller( + buildContext({ + state, + battleSim: new QueuedBattleSimTransport(), + userId: 'user-without-general', + db, + }) + ); + + await expect(caller.battle.getGeneralDetail({ generalId: ally.id })).rejects.toMatchObject({ + code: 'NOT_FOUND', + message: 'General not found', + }); + }); }); diff --git a/app/game-api/test/battleSimTransport.test.ts b/app/game-api/test/battleSimTransport.test.ts new file mode 100644 index 0000000..1f0eb54 --- /dev/null +++ b/app/game-api/test/battleSimTransport.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, it } from 'vitest'; + +import { buildBattleSimQueueKeys } from '../src/battleSim/keys.js'; +import { RedisBattleSimTransport } from '../src/battleSim/redisTransport.js'; +import type { BattleSimJob, BattleSimJobPayload } from '../src/battleSim/types.js'; + +class FakeRedisClient { + readonly values = new Map(); + readonly lists = new Map(); + + async rPush(key: string, value: string): Promise { + const list = this.lists.get(key) ?? []; + list.push(value); + this.lists.set(key, list); + return list.length; + } + + async blPop(): Promise { + return null; + } + + async set(key: string, value: string): Promise<'OK'> { + this.values.set(key, value); + return 'OK'; + } + + async get(key: string): Promise { + return this.values.get(key) ?? null; + } + + async expire(): Promise { + return 1; + } +} + +describe('RedisBattleSimTransport requester isolation', () => { + it('records the requester on queued jobs and scopes completed results to that user', async () => { + const client = new FakeRedisClient(); + const keys = buildBattleSimQueueKeys('che:test'); + const transport = new RedisBattleSimTransport(client, { + keys, + requestTimeoutMs: 1, + resultTtlSeconds: 60, + }); + + const response = await transport.simulate({} as BattleSimJobPayload, 'user/one'); + expect(response.status).toBe('queued'); + + const queuedRaw = client.lists.get(keys.queueKey)?.[0]; + expect(queuedRaw).toBeTruthy(); + expect(JSON.parse(queuedRaw ?? '{}') as BattleSimJob).toMatchObject({ + jobId: response.jobId, + requesterUserId: 'user/one', + }); + + await transport.pushResult(response.jobId, 'user/one', { + result: true, + reason: 'success', + avgWar: 3, + }); + + await expect(transport.getSimulationResult(response.jobId, 'user/one')).resolves.toMatchObject({ + result: true, + avgWar: 3, + }); + await expect(transport.getSimulationResult(response.jobId, 'user/two')).resolves.toBeNull(); + expect(Array.from(client.values.keys()).some((key) => key.includes('user%2Fone'))).toBe(true); + }); +}); diff --git a/app/game-api/test/battleSimWorker.integration.test.ts b/app/game-api/test/battleSimWorker.integration.test.ts new file mode 100644 index 0000000..6a8ccf8 --- /dev/null +++ b/app/game-api/test/battleSimWorker.integration.test.ts @@ -0,0 +1,94 @@ +import fs from 'node:fs/promises'; +import path from 'node:path'; +import { randomUUID } from 'node:crypto'; + +import { createRedisConnector, resolveRedisConfigFromEnv } from '@sammo-ts/infra'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { buildBattleSimEnvironment } from '../src/battleSim/environment.js'; +import { buildBattleSimQueueKeys } from '../src/battleSim/keys.js'; +import { RedisBattleSimTransport } from '../src/battleSim/redisTransport.js'; +import type { BattleSimRequestPayload } from '../src/battleSim/types.js'; +import { runBattleSimWorker } from '../src/battleSim/worker.js'; +import type { WorldStateRow } from '../src/context.js'; + +const liveDescribe = process.env.REDIS_URL ? describe : describe.skip; + +afterEach(() => { + vi.unstubAllEnvs(); +}); + +liveDescribe('battle simulator worker with live Redis', () => { + it('consumes an isolated queue, produces a result, and stops cleanly', { timeout: 30_000 }, async () => { + const scenario = `battle-sim-e2e-${randomUUID()}`; + const profileName = `che:${scenario}`; + const requesterUserId = 'worker-e2e-user'; + vi.stubEnv('PROFILE', 'che'); + vi.stubEnv('SCENARIO', scenario); + vi.stubEnv('GAME_TOKEN_SECRET', 'battle-sim-test-only'); + + const fixturePath = path.resolve( + process.cwd(), + '../../tools/integration-tests/fixtures/battle/basic-infantry.json' + ); + const fixture = JSON.parse(await fs.readFile(fixturePath, 'utf8')) as BattleSimRequestPayload & { + startYear: number; + }; + const { startYear, ...request } = fixture; + const worldState: WorldStateRow = { + id: 1, + scenarioCode: 'default', + currentYear: request.year, + currentMonth: request.month, + tickSeconds: 600, + config: {}, + meta: { scenarioMeta: { startYear } }, + updatedAt: new Date(), + }; + const environment = await buildBattleSimEnvironment(worldState, 'che'); + const payload = { + ...request, + unitSet: environment.unitSet, + config: environment.config, + time: { year: request.year, month: request.month, startYear }, + }; + + const clientConnector = createRedisConnector(resolveRedisConfigFromEnv()); + await clientConnector.connect(); + const keys = buildBattleSimQueueKeys(profileName); + const transport = new RedisBattleSimTransport(clientConnector.client, { + keys, + requestTimeoutMs: 15_000, + resultTtlSeconds: 60, + }); + const abortController = new AbortController(); + const worker = runBattleSimWorker({ signal: abortController.signal }); + let jobId: string | null = null; + + try { + const result = await transport.simulate(payload, requesterUserId); + jobId = result.jobId; + expect(result.status).toBe('completed'); + if (result.status === 'completed') { + expect(result.payload).toMatchObject({ + result: true, + reason: 'success', + avgWar: 1, + }); + expect(result.payload.phase).toBeGreaterThan(0); + } + } finally { + abortController.abort(); + await worker; + if (jobId) { + const encodedRequester = encodeURIComponent(requesterUserId); + await clientConnector.client.del([ + keys.queueKey, + `${keys.resultKeyPrefix}${encodedRequester}:${jobId}`, + `${keys.notifyKeyPrefix}${encodedRequester}:${jobId}`, + ]); + } + await clientConnector.disconnect(); + } + }); +}); diff --git a/app/gateway-api/src/adminRouter.ts b/app/gateway-api/src/adminRouter.ts index e469052..4552131 100644 --- a/app/gateway-api/src/adminRouter.ts +++ b/app/gateway-api/src/adminRouter.ts @@ -817,6 +817,7 @@ export const adminRouter = router({ profileName: profile.profileName, apiRunning: false, daemonRunning: false, + battleSimRunning: false, tournamentRunning: false, }, })); diff --git a/app/gateway-api/src/lobby/profileStatusService.ts b/app/gateway-api/src/lobby/profileStatusService.ts index b65c2f5..9814831 100644 --- a/app/gateway-api/src/lobby/profileStatusService.ts +++ b/app/gateway-api/src/lobby/profileStatusService.ts @@ -26,6 +26,7 @@ export type LobbyProfileStatus = { runtime: { apiRunning: boolean; daemonRunning: boolean; + battleSimRunning: boolean; tournamentRunning: boolean; }; korName: string; @@ -69,7 +70,10 @@ export class RepositoryProfileStatusService implements GatewayProfileStatusServi private mapProfile( row: GatewayProfileRecord, - runtimeMap: Map + runtimeMap: Map< + string, + { apiRunning: boolean; daemonRunning: boolean; battleSimRunning: boolean; tournamentRunning: boolean } + > ): LobbyProfileStatus { const meta = row.meta; return { @@ -81,6 +85,7 @@ export class RepositoryProfileStatusService implements GatewayProfileStatusServi runtime: runtimeMap.get(row.profileName) ?? { apiRunning: false, daemonRunning: false, + battleSimRunning: false, tournamentRunning: false, }, korName: (meta.korName as string | undefined) ?? row.profile, diff --git a/app/gateway-api/src/orchestrator/gatewayOrchestrator.ts b/app/gateway-api/src/orchestrator/gatewayOrchestrator.ts index 273c083..804e411 100644 --- a/app/gateway-api/src/orchestrator/gatewayOrchestrator.ts +++ b/app/gateway-api/src/orchestrator/gatewayOrchestrator.ts @@ -39,6 +39,7 @@ export interface GatewayOrchestratorOptions { export interface ProfileRuntimeState { apiRunning: boolean; daemonRunning: boolean; + battleSimRunning: boolean; tournamentRunning: boolean; } @@ -66,13 +67,19 @@ export const planProfileReconcile = ( ): { shouldStart: boolean; shouldStop: boolean } => { if (status === 'RUNNING' || status === 'PREOPEN' || status === 'PAUSED' || status === 'COMPLETED') { return { - shouldStart: !(runtime.apiRunning && runtime.daemonRunning && runtime.tournamentRunning), + shouldStart: !( + runtime.apiRunning && + runtime.daemonRunning && + runtime.battleSimRunning && + runtime.tournamentRunning + ), shouldStop: false, }; } return { shouldStart: false, - shouldStop: runtime.apiRunning || runtime.daemonRunning || runtime.tournamentRunning, + shouldStop: + runtime.apiRunning || runtime.daemonRunning || runtime.battleSimRunning || runtime.tournamentRunning, }; }; @@ -273,8 +280,16 @@ const parseInstallOptions = ( }; }; -const buildProcessName = (profileName: string, role: 'api' | 'daemon' | 'tournament'): string => - `sammo:${profileName}:${role === 'api' ? 'game-api' : role === 'daemon' ? 'turn-daemon' : 'tournament-worker'}`; +const buildProcessName = (profileName: string, role: 'api' | 'daemon' | 'battle-sim' | 'tournament'): string => + `sammo:${profileName}:${ + role === 'api' + ? 'game-api' + : role === 'daemon' + ? 'turn-daemon' + : role === 'battle-sim' + ? 'battle-sim-worker' + : 'tournament-worker' + }`; const isMissingProcessError = (error: unknown): boolean => error instanceof Error && /process or namespace not found/i.test(error.message); @@ -285,11 +300,13 @@ export const buildProcessDefinitions = ( ): { api: { name: string; script: string; cwd: string; env: Record }; daemon: { name: string; script: string; cwd: string; env: Record }; + battleSim: { name: string; script: string; cwd: string; env: Record }; tournament: { name: string; script: string; cwd: string; env: Record }; } => { const baseEnv = { ...(config.baseEnv ?? {}) }; const apiName = buildProcessName(profile.profileName, 'api'); const daemonName = buildProcessName(profile.profileName, 'daemon'); + const battleSimName = buildProcessName(profile.profileName, 'battle-sim'); const tournamentName = buildProcessName(profile.profileName, 'tournament'); const runtimeWorkspace = profile.buildWorkspace ?? config.workspaceRoot; const apiCwd = path.join(runtimeWorkspace, 'app', 'game-api'); @@ -327,6 +344,15 @@ export const buildProcessDefinitions = ( cwd: daemonCwd, env: daemonEnv, }, + battleSim: { + name: battleSimName, + script: apiScript, + cwd: apiCwd, + env: { + ...apiEnv, + GAME_API_ROLE: 'battle-sim-worker', + }, + }, tournament: { name: tournamentName, script: apiScript, @@ -376,11 +402,13 @@ const mapRuntimeStates = (profileNames: string[], processNames: Map { const apiName = buildProcessName(profileName, 'api'); const daemonName = buildProcessName(profileName, 'daemon'); + const battleSimName = buildProcessName(profileName, 'battle-sim'); const tournamentName = buildProcessName(profileName, 'tournament'); return { profileName, apiRunning: processNames.get(apiName) ?? false, daemonRunning: processNames.get(daemonName) ?? false, + battleSimRunning: processNames.get(battleSimName) ?? false, tournamentRunning: processNames.get(tournamentName) ?? false, }; }); @@ -981,6 +1009,7 @@ export class GatewayOrchestrator implements GatewayOrchestratorHandle { try { await this.processManager.start(definitions.api); await this.processManager.start(definitions.daemon); + await this.processManager.start(definitions.battleSim); await this.processManager.start(definitions.tournament); await this.repository.updateLastError(profile.profileName, null); return true; @@ -996,10 +1025,11 @@ export class GatewayOrchestrator implements GatewayOrchestratorHandle { private async stopProfile(profile: GatewayProfileRecord): Promise { const apiName = buildProcessName(profile.profileName, 'api'); const daemonName = buildProcessName(profile.profileName, 'daemon'); + const battleSimName = buildProcessName(profile.profileName, 'battle-sim'); const tournamentName = buildProcessName(profile.profileName, 'tournament'); const existingNames = new Set((await this.processManager.list()).map((process) => process.name)); const failures: string[] = []; - for (const name of [apiName, daemonName, tournamentName]) { + for (const name of [apiName, daemonName, battleSimName, tournamentName]) { if (!existingNames.has(name)) { continue; } diff --git a/app/gateway-api/test/orchestratorOperations.test.ts b/app/gateway-api/test/orchestratorOperations.test.ts index 7a47e10..787d20a 100644 --- a/app/gateway-api/test/orchestratorOperations.test.ts +++ b/app/gateway-api/test/orchestratorOperations.test.ts @@ -88,6 +88,7 @@ const createHarness = ( ? [ { name: 'sammo:che:2:game-api', status: 'online' }, { name: 'sammo:che:2:turn-daemon', status: 'online' }, + { name: 'sammo:che:2:battle-sim-worker', status: 'online' }, { name: 'sammo:che:2:tournament-worker', status: 'online' }, ] : [], @@ -138,7 +139,7 @@ const createHarness = ( }; describe('GatewayOrchestrator first-class operations', () => { - it('starts both profile processes and records success', async () => { + it('starts every profile process and records success', async () => { const harness = createHarness(buildOperation('START')); await harness.orchestrator.runOperationsNow(); @@ -147,12 +148,13 @@ describe('GatewayOrchestrator first-class operations', () => { expect(harness.started.map((definition) => definition.name)).toEqual([ 'sammo:che:2:game-api', 'sammo:che:2:turn-daemon', + 'sammo:che:2:battle-sim-worker', 'sammo:che:2:tournament-worker', ]); expect(harness.completions).toEqual(['SUCCEEDED']); }); - it('stops both profile processes and records success', async () => { + it('stops every profile process and records success', async () => { const harness = createHarness(buildOperation('STOP')); await harness.orchestrator.runOperationsNow(); @@ -161,11 +163,13 @@ describe('GatewayOrchestrator first-class operations', () => { expect(harness.stopped).toEqual([ 'sammo:che:2:game-api', 'sammo:che:2:turn-daemon', + 'sammo:che:2:battle-sim-worker', 'sammo:che:2:tournament-worker', ]); expect(harness.deleted).toEqual([ 'sammo:che:2:game-api', 'sammo:che:2:turn-daemon', + 'sammo:che:2:battle-sim-worker', 'sammo:che:2:tournament-worker', ]); expect(harness.completions).toEqual(['SUCCEEDED']); @@ -190,6 +194,7 @@ describe('GatewayOrchestrator first-class operations', () => { expect(harness.deleted).toEqual([ 'sammo:che:2:game-api', 'sammo:che:2:turn-daemon', + 'sammo:che:2:battle-sim-worker', 'sammo:che:2:tournament-worker', ]); expect(harness.completions).toEqual(['SUCCEEDED']); @@ -203,7 +208,7 @@ describe('GatewayOrchestrator first-class operations', () => { expect(harness.completions).toEqual(['FAILED']); }); - it('attempts to stop both roles before reporting a partial PM2 failure', async () => { + it('attempts to stop every role before reporting a partial PM2 failure', async () => { const harness = createHarness(buildOperation('STOP'), false, true); await harness.orchestrator.runOperationsNow(); @@ -211,11 +216,13 @@ describe('GatewayOrchestrator first-class operations', () => { expect(harness.stopped).toEqual([ 'sammo:che:2:game-api', 'sammo:che:2:turn-daemon', + 'sammo:che:2:battle-sim-worker', 'sammo:che:2:tournament-worker', ]); expect(harness.deleted).toEqual([ 'sammo:che:2:game-api', 'sammo:che:2:turn-daemon', + 'sammo:che:2:battle-sim-worker', 'sammo:che:2:tournament-worker', ]); expect(harness.completions).toEqual(['FAILED']); diff --git a/app/gateway-api/test/orchestratorPlan.test.ts b/app/gateway-api/test/orchestratorPlan.test.ts index ae92d15..431a840 100644 --- a/app/gateway-api/test/orchestratorPlan.test.ts +++ b/app/gateway-api/test/orchestratorPlan.test.ts @@ -29,6 +29,7 @@ describe('planProfileReconcile', () => { planProfileReconcile('RUNNING', { apiRunning: true, daemonRunning: false, + battleSimRunning: true, tournamentRunning: true, }) ).toEqual({ shouldStart: true, shouldStop: false }); @@ -39,6 +40,7 @@ describe('planProfileReconcile', () => { planProfileReconcile('PREOPEN', { apiRunning: false, daemonRunning: false, + battleSimRunning: false, tournamentRunning: false, }) ).toEqual({ shouldStart: true, shouldStop: false }); @@ -49,6 +51,7 @@ describe('planProfileReconcile', () => { planProfileReconcile('RUNNING', { apiRunning: true, daemonRunning: true, + battleSimRunning: true, tournamentRunning: true, }) ).toEqual({ shouldStart: false, shouldStop: false }); @@ -59,6 +62,7 @@ describe('planProfileReconcile', () => { planProfileReconcile('STOPPED', { apiRunning: false, daemonRunning: true, + battleSimRunning: false, tournamentRunning: false, }) ).toEqual({ shouldStart: false, shouldStop: true }); @@ -69,6 +73,7 @@ describe('planProfileReconcile', () => { planProfileReconcile('RESERVED', { apiRunning: false, daemonRunning: false, + battleSimRunning: false, tournamentRunning: false, }) ).toEqual({ shouldStart: false, shouldStop: false }); @@ -95,6 +100,11 @@ describe('buildProcessDefinitions', () => { }); expect(definitions.daemon.cwd).toBe(path.join(buildWorkspace, 'app', 'game-engine')); expect(definitions.daemon.script).toBe(path.join(buildWorkspace, 'app', 'game-engine', 'dist', 'index.js')); + expect(definitions.battleSim).toMatchObject({ + cwd: path.join(buildWorkspace, 'app', 'game-api'), + script: path.join(buildWorkspace, 'app', 'game-api', 'dist', 'index.js'), + env: { GAME_API_ROLE: 'battle-sim-worker' }, + }); expect(definitions.tournament).toMatchObject({ cwd: path.join(buildWorkspace, 'app', 'game-api'), script: path.join(buildWorkspace, 'app', 'game-api', 'dist', 'index.js'), @@ -107,6 +117,7 @@ describe('buildProcessDefinitions', () => { expect(definitions.api.cwd).toBe(path.join(processConfig.workspaceRoot, 'app', 'game-api')); expect(definitions.daemon.cwd).toBe(path.join(processConfig.workspaceRoot, 'app', 'game-engine')); + expect(definitions.battleSim.cwd).toBe(path.join(processConfig.workspaceRoot, 'app', 'game-api')); expect(definitions.tournament.cwd).toBe(path.join(processConfig.workspaceRoot, 'app', 'game-api')); }); }); diff --git a/app/gateway-frontend/e2e/server-operations.spec.ts b/app/gateway-frontend/e2e/server-operations.spec.ts index ba61af7..65d02c9 100644 --- a/app/gateway-frontend/e2e/server-operations.spec.ts +++ b/app/gateway-frontend/e2e/server-operations.spec.ts @@ -38,6 +38,7 @@ const profile = (runtimeRunning: boolean) => ({ profileName: 'che:2', apiRunning: runtimeRunning, daemonRunning: runtimeRunning, + battleSimRunning: runtimeRunning, tournamentRunning: runtimeRunning, }, }); diff --git a/app/gateway-frontend/src/views/AdminView.vue b/app/gateway-frontend/src/views/AdminView.vue index 565317c..b2c9fa6 100644 --- a/app/gateway-frontend/src/views/AdminView.vue +++ b/app/gateway-frontend/src/views/AdminView.vue @@ -70,6 +70,7 @@ type AdminProfile = { runtime: { apiRunning: boolean; daemonRunning: boolean; + battleSimRunning: boolean; tournamentRunning: boolean; }; buildCommitSha?: string; @@ -1352,7 +1353,8 @@ onMounted(() => {
상태: {{ profile.status }} / API: {{ profile.runtime.apiRunning ? 'ON' : 'OFF' }} / - DAEMON: {{ profile.runtime.daemonRunning ? 'ON' : 'OFF' }} / TOURNAMENT: + DAEMON: {{ profile.runtime.daemonRunning ? 'ON' : 'OFF' }} / BATTLE SIM: + {{ profile.runtime.battleSimRunning ? 'ON' : 'OFF' }} / TOURNAMENT: {{ profile.runtime.tournamentRunning ? 'ON' : 'OFF' }}
diff --git a/app/gateway-frontend/src/views/ServerOperationsView.vue b/app/gateway-frontend/src/views/ServerOperationsView.vue index 9908d48..b39a048 100644 --- a/app/gateway-frontend/src/views/ServerOperationsView.vue +++ b/app/gateway-frontend/src/views/ServerOperationsView.vue @@ -16,7 +16,12 @@ type Profile = { buildWorkspace?: string; buildError?: string; lastError?: string; - runtime: { apiRunning: boolean; daemonRunning: boolean; tournamentRunning: boolean }; + runtime: { + apiRunning: boolean; + daemonRunning: boolean; + battleSimRunning: boolean; + tournamentRunning: boolean; + }; }; type Scenario = { @@ -377,6 +382,14 @@ onBeforeUnmount(() => { {{ selectedProfile.runtime.daemonRunning ? 'RUNNING' : 'STOPPED' }} +
+
Battle sim worker
+
+ {{ selectedProfile.runtime.battleSimRunning ? 'RUNNING' : 'STOPPED' }} +
+
Tournament worker
Date: Sun, 26 Jul 2026 05:31:25 +0000 Subject: [PATCH 10/16] feat: complete in-game message parity --- app/game-api/src/messages/targets.ts | 3 +- app/game-api/src/router/messages/index.ts | 194 ++++++- app/game-api/test/messagesRouter.test.ts | 339 +++++++++++- .../src/components/main/MessagePanel.vue | 510 ++++++++++++------ .../src/components/main/MessagePlate.vue | 431 +++++++++++++++ app/game-frontend/src/stores/mainDashboard.ts | 162 +++++- app/game-frontend/src/views/MainView.vue | 83 +-- docs/architecture/todo.md | 4 +- .../ingame-message-parity.spec.ts | 384 +++++++++++++ .../instant-diplomacy-message.spec.ts | 35 +- .../playwright.config.mjs | 1 + .../reference-ingame-message.mjs | 178 ++++++ 12 files changed, 2080 insertions(+), 244 deletions(-) create mode 100644 app/game-frontend/src/components/main/MessagePlate.vue create mode 100644 tools/frontend-legacy-parity/ingame-message-parity.spec.ts create mode 100644 tools/frontend-legacy-parity/reference-ingame-message.mjs diff --git a/app/game-api/src/messages/targets.ts b/app/game-api/src/messages/targets.ts index 9c9f167..fa5c815 100644 --- a/app/game-api/src/messages/targets.ts +++ b/app/game-api/src/messages/targets.ts @@ -23,13 +23,14 @@ export const resolveNationInfo = async ( export const buildTargetFromGeneral = async (db: DatabaseClient, general: GeneralRow): Promise => { const nation = await resolveNationInfo(db, general.nationId); + const picture = general.picture?.trim() || 'default.jpg'; return { generalId: general.id, generalName: general.name, nationId: general.nationId, nationName: nation.name, color: nation.color, - icon: '', + icon: general.imageServer ? `d_pic/${picture}` : `/image/icons/${picture}`, }; }; diff --git a/app/game-api/src/router/messages/index.ts b/app/game-api/src/router/messages/index.ts index 16a3dcf..b6a49aa 100644 --- a/app/game-api/src/router/messages/index.ts +++ b/app/game-api/src/router/messages/index.ts @@ -1,5 +1,7 @@ import { TRPCError } from '@trpc/server'; import { z } from 'zod'; +import { asRecord } from '@sammo-ts/common'; +import type { UserSanctions } from '@sammo-ts/common/auth/gameToken'; import { authedProcedure, router } from '../../trpc.js'; import { @@ -26,6 +28,75 @@ import { respondToDiplomaticMessage } from '../../messages/diplomaticResponse.js const zMessageType = z.enum(['private', 'public', 'national', 'diplomacy']); +const redactDiplomacyMessages = (messages: MessageView[], permission: number): MessageView[] => { + if (permission >= 3) { + return messages; + } + return messages.map((message) => { + if (!message.dest || message.dest.nationId === 0) { + return message; + } + return { + ...message, + text: '(외교 메시지입니다)', + option: { + ...(message.option ?? {}), + invalid: true, + }, + }; + }); +}; + +const isFutureDate = (value: string | undefined, now = Date.now()): boolean => { + if (!value) { + return false; + } + const parsed = Date.parse(value); + return Number.isFinite(parsed) && parsed > now; +}; + +const isMessageFeatureBlocked = (sanctions: UserSanctions, profileNames: string[]): boolean => { + if ( + isFutureDate(sanctions.mutedUntil) || + isFutureDate(sanctions.suspendedUntil) || + isFutureDate(sanctions.bannedUntil) + ) { + return true; + } + for (const profileName of profileNames) { + const restriction = sanctions.serverRestrictions?.[profileName]; + if (!restriction) { + continue; + } + if (restriction.until && !isFutureDate(restriction.until)) { + continue; + } + if (restriction.blockedFeatures?.includes('messages')) { + return true; + } + } + return false; +}; + +const readPenaltyNumber = (penalty: unknown, key: string, fallback: number): number => { + const value = asRecord(penalty)[key]; + if (typeof value === 'number' && Number.isFinite(value)) { + return value; + } + if (typeof value === 'string') { + const parsed = Number(value); + if (Number.isFinite(parsed)) { + return parsed; + } + } + return fallback; +}; + +const hasPenalty = (penalty: unknown, key: string): boolean => { + const value = asRecord(penalty)[key]; + return value === true || value === 1 || value === '1'; +}; + export const messagesRouter = router({ getRecent: authedProcedure .input( @@ -85,11 +156,12 @@ export const messagesRouter = router({ : null, ]); + const permission = nationId > 0 && nation ? resolveNationPermission(general, nation.meta, false) : -1; const messageBuckets: Record = { private: privateMessages, public: publicMessages, national: nationalMessages, - diplomacy: diplomacyMessages, + diplomacy: redactDiplomacyMessages(diplomacyMessages, permission), }; let nextSequence = sequence; @@ -128,10 +200,8 @@ export const messagesRouter = router({ sequence: nextSequence, nationId: nationId, generalName: general.name, - canRespondDiplomacy: - general.officerLevel > 4 && - nation !== null && - resolveNationPermission(general, nation.meta, false) >= 4, + permission, + canRespondDiplomacy: permission >= 4 && general.officerLevel > 4, latestRead: { diplomacy: readState?.latestDiplomacyMessage ?? 0, private: readState?.latestPrivateMessage ?? 0, @@ -178,6 +248,7 @@ export const messagesRouter = router({ ]; return { nation: nationList.map((nation) => ({ + nationId: nation.id, mailbox: MESSAGE_MAILBOX_NATIONAL_BASE + nation.id, name: nation.name, color: nation.color, @@ -234,14 +305,24 @@ export const messagesRouter = router({ if (message.payload.src.generalId !== general.id) { throw new TRPCError({ code: 'FORBIDDEN', message: '본인의 메시지만 삭제할 수 있습니다.' }); } - if (message.msgType === 'diplomacy' || message.payload.option?.deletable === false) { + if (message.msgType === 'diplomacy' && message.payload.option?.action) { + throw new TRPCError({ + code: 'BAD_REQUEST', + message: '시스템 외교 메시지는 삭제할 수 없습니다.', + }); + } + if (message.payload.option?.deletable === false) { throw new TRPCError({ code: 'BAD_REQUEST', message: '삭제할 수 없는 메시지입니다.' }); } if (Date.now() - message.time.getTime() > 5 * 60 * 1000) { throw new TRPCError({ code: 'BAD_REQUEST', message: '5분 이내의 메시지만 삭제할 수 있습니다.' }); } const receiverMessageId = message.payload.option?.receiverMessageID; - const ids = [message.id, ...(typeof receiverMessageId === 'number' ? [receiverMessageId] : [])]; + const shouldDeleteReceiverCopy = message.msgType === 'private' || message.msgType === 'national'; + const ids = [ + message.id, + ...(shouldDeleteReceiverCopy && typeof receiverMessageId === 'number' ? [receiverMessageId] : []), + ]; await invalidateMessages(ctx.db, ids); return { ok: true, deletedIds: ids }; }), @@ -291,6 +372,14 @@ export const messagesRouter = router({ const general = await getOwnedGeneral(ctx, input.generalId); const nationId = general.nationId; + const nation = + nationId > 0 + ? await ctx.db.nation.findUnique({ + where: { id: nationId }, + select: { meta: true }, + }) + : null; + const permission = nationId > 0 && nation ? resolveNationPermission(general, nation.meta, false) : -1; const mailboxes = { private: general.id, public: MESSAGE_MAILBOX_PUBLIC, @@ -312,7 +401,8 @@ export const messagesRouter = router({ toSeq: input.to, limit: 15, }); - messageBuckets[input.type] = messages; + messageBuckets[input.type] = + input.type === 'diplomacy' ? redactDiplomacyMessages(messages, permission) : messages; return { result: true, @@ -320,6 +410,7 @@ export const messagesRouter = router({ sequence: 0, nationId, generalName: general.name, + permission, ...messageBuckets, }; }), @@ -333,6 +424,12 @@ export const messagesRouter = router({ ) .mutation(async ({ ctx, input }) => { const general = await getOwnedGeneral(ctx, input.generalId); + if (!ctx.auth || isMessageFeatureBlocked(ctx.auth.sanctions, [ctx.profile.name, ctx.profile.id])) { + throw new TRPCError({ + code: 'FORBIDDEN', + message: '메시지 전송이 제한된 계정입니다.', + }); + } const src = await buildTargetFromGeneral(ctx.db, general); const now = new Date(); @@ -340,28 +437,93 @@ export const messagesRouter = router({ let msgType: MessageType; let dest = src; + let receiverMailbox = input.mailbox; if (input.mailbox === MESSAGE_MAILBOX_PUBLIC) { - msgType = 'public'; - } else if (input.mailbox >= MESSAGE_MAILBOX_NATIONAL_BASE) { - const destNationId = input.mailbox - MESSAGE_MAILBOX_NATIONAL_BASE; - if (destNationId <= 0) { + if (hasPenalty(general.penalty, 'noSendPublicMsg')) { throw new TRPCError({ - code: 'BAD_REQUEST', - message: 'Invalid nation mailbox.', + code: 'FORBIDDEN', + message: '공개 메세지를 보낼 수 없습니다.', }); } + msgType = 'public'; + } else if (input.mailbox >= MESSAGE_MAILBOX_NATIONAL_BASE) { + const sourceNation = + general.nationId > 0 + ? await ctx.db.nation.findUnique({ + where: { id: general.nationId }, + select: { meta: true }, + }) + : null; + const permission = + general.nationId > 0 && sourceNation ? resolveNationPermission(general, sourceNation.meta) : -1; + const destNationId = permission < 4 ? general.nationId : input.mailbox - MESSAGE_MAILBOX_NATIONAL_BASE; const nationInfo = await resolveNationInfo(ctx.db, destNationId); + if (destNationId > 0) { + const destNation = await ctx.db.nation.findUnique({ where: { id: destNationId } }); + if (!destNation) { + throw new TRPCError({ + code: 'NOT_FOUND', + message: '존재하지 않는 국가입니다.', + }); + } + } dest = buildNationTarget(destNationId, nationInfo.name, nationInfo.color); msgType = destNationId === general.nationId ? 'national' : 'diplomacy'; + receiverMailbox = MESSAGE_MAILBOX_NATIONAL_BASE + destNationId; } else if (input.mailbox > 0) { + if (hasPenalty(general.penalty, 'noSendPrivateMsg')) { + throw new TRPCError({ + code: 'FORBIDDEN', + message: '개인 메세지를 보낼 수 없습니다.', + }); + } + const intervalSeconds = Math.max( + 0, + Math.ceil(readPenaltyNumber(general.penalty, 'sendPrivateMsgDelay', 2)) + ); + if (intervalSeconds > 0) { + const rateLimitKey = `game:${ctx.profile.name}:message:private:${ctx.auth.sessionId}`; + const acquired = await ctx.redis.set(rateLimitKey, '1', { + NX: true, + PX: intervalSeconds * 1000, + }); + if (acquired === null) { + throw new TRPCError({ + code: 'TOO_MANY_REQUESTS', + message: `개인메세지는 ${intervalSeconds}초당 1건만 보낼 수 있습니다!`, + }); + } + } const destGeneral = await ctx.db.general.findUnique({ where: { id: input.mailbox }, }); if (!destGeneral) { throw new TRPCError({ code: 'NOT_FOUND', - message: 'Destination general not found.', + message: '존재하지 않는 유저입니다.', + }); + } + const [sourceNation, destNation] = await Promise.all([ + general.nationId > 0 + ? ctx.db.nation.findUnique({ where: { id: general.nationId }, select: { meta: true } }) + : null, + destGeneral.nationId > 0 + ? ctx.db.nation.findUnique({ where: { id: destGeneral.nationId }, select: { meta: true } }) + : null, + ]); + const sourcePermission = + sourceNation && general.nationId > 0 + ? resolveNationPermission(general, sourceNation.meta, false) + : -1; + const destPermission = + destNation && destGeneral.nationId > 0 + ? resolveNationPermission(destGeneral, destNation.meta, false) + : -1; + if (sourcePermission === 4 && destPermission === 4 && destGeneral.nationId !== general.nationId) { + throw new TRPCError({ + code: 'FORBIDDEN', + message: '외교권자끼리는 메시지를 보낼 수 없습니다.', }); } dest = await buildTargetFromGeneral(ctx.db, destGeneral); @@ -394,7 +556,7 @@ export const messagesRouter = router({ await publishRealtimeEvent(ctx.redis, ctx.profile.name, { type: 'messageCreated', at: now.toISOString(), - mailbox: input.mailbox, + mailbox: receiverMailbox, msgType, messageId: result.receiverId, senderId: general.id, diff --git a/app/game-api/test/messagesRouter.test.ts b/app/game-api/test/messagesRouter.test.ts index 9ba2940..b96645c 100644 --- a/app/game-api/test/messagesRouter.test.ts +++ b/app/game-api/test/messagesRouter.test.ts @@ -30,7 +30,7 @@ const auth: GameSessionTokenPayload = { sanctions: {}, }; -const buildContext = (overrides: Record = {}) => { +const buildContext = (overrides: Record = {}, contextOverrides: Record = {}) => { const executeRaw = vi.fn(async () => 1); const updateMany = vi.fn(async () => ({ count: 1 })); const db = { @@ -55,11 +55,15 @@ const buildContext = (overrides: Record = {}) => { $executeRaw: executeRaw, ...overrides, }; + const redis = { + set: vi.fn(async () => 'OK'), + publish: vi.fn(async () => 1), + }; const context = { db, auth, profile: { id: 'che', scenario: 'default', name: 'che:default' }, - redis: {}, + redis, turnDaemon: {}, battleSim: {}, uploadDir: 'uploads', @@ -68,8 +72,9 @@ const buildContext = (overrides: Record = {}) => { accessTokenStore: {}, flushStore: {}, gameTokenSecret: 'test-secret', + ...contextOverrides, } as unknown as GameApiContext; - return { caller: appRouter.createCaller(context), db, executeRaw, updateMany }; + return { caller: appRouter.createCaller(context), db, executeRaw, updateMany, redis }; }; describe('messages router missing-flow compatibility', () => { @@ -99,6 +104,291 @@ describe('messages router missing-flow compatibility', () => { expect(result.canRespondDiplomacy).toBe(true); }); + it('lists an appointed ambassador as permission 4 but keeps responses limited to officers', async () => { + const ambassador = { + ...general, + officerLevel: 1, + meta: { permission: 'ambassador' }, + } as GeneralRow; + const { caller } = buildContext({ + general: { + findUnique: vi.fn(async () => ambassador), + findMany: vi.fn(async () => []), + }, + nation: { + findMany: vi.fn(async () => []), + findUnique: vi.fn(async () => ({ meta: {} })), + }, + }); + + const result = await caller.messages.getRecent({ generalId: ambassador.id }); + + expect(result.permission).toBe(4); + expect(result.canRespondDiplomacy).toBe(false); + }); + + it('redacts recent and old diplomacy content below secret permission 3', async () => { + const diplomacyRow = { + id: 19, + mailbox: 9001, + type: 'diplomacy', + src: 9002, + dest: 9001, + time: new Date(), + valid_until: new Date('9999-12-31T00:00:00Z'), + message: { + src: { + generalId: 8, + generalName: '외교관', + nationId: 2, + nationName: '촉', + color: '#000000', + icon: '', + }, + dest: { + generalId: 0, + generalName: '', + nationId: 1, + nationName: '위', + color: '#ffffff', + icon: '', + }, + text: '보이면 안 되는 외교 본문', + option: { action: 'noAggression' }, + }, + }; + const queryRaw = vi.fn(async () => [diplomacyRow]); + const { caller } = buildContext({ + $queryRaw: queryRaw, + nation: { + findMany: vi.fn(async () => []), + findUnique: vi.fn(async () => ({ meta: {} })), + }, + }); + + const recent = await caller.messages.getRecent({ generalId: general.id }); + const old = await caller.messages.getOld({ + generalId: general.id, + type: 'diplomacy', + to: 20, + }); + + expect(recent.permission).toBe(2); + expect(recent.diplomacy[0]).toMatchObject({ + text: '(외교 메시지입니다)', + option: { action: 'noAggression', invalid: true }, + }); + expect(old.diplomacy[0]).toMatchObject({ + text: '(외교 메시지입니다)', + option: { action: 'noAggression', invalid: true }, + }); + }); + + it('forces a non-diplomat foreign nation target back to the owned nation mailbox', async () => { + const queryRaw = vi.fn(async () => [{ id: 51 }]); + const findNation = vi.fn(async ({ where }: { where: { id: number } }) => ({ + id: where.id, + name: where.id === 1 ? '위' : '촉', + color: '#112233', + meta: {}, + })); + const { caller } = buildContext({ + $queryRaw: queryRaw, + nation: { + findMany: vi.fn(async () => []), + findUnique: findNation, + }, + }); + + const result = await caller.messages.send({ + generalId: general.id, + mailbox: 9002, + text: '국가 메시지', + }); + + expect(result.msgType).toBe('national'); + expect(queryRaw.mock.calls[0]?.slice(1)).toEqual(expect.arrayContaining([9001, 'national'])); + }); + + it('allows an ambassador to target a foreign nation mailbox as diplomacy', async () => { + const ambassador = { + ...general, + officerLevel: 1, + meta: { permission: 'ambassador' }, + } as GeneralRow; + const queryRaw = vi.fn(async () => [{ id: 52 }]); + const { caller } = buildContext({ + $queryRaw: queryRaw, + general: { + findUnique: vi.fn(async () => ambassador), + findMany: vi.fn(async () => []), + }, + nation: { + findMany: vi.fn(async () => []), + findUnique: vi.fn(async ({ where }: { where: { id: number } }) => ({ + id: where.id, + name: where.id === 1 ? '위' : '촉', + color: '#112233', + meta: {}, + })), + }, + }); + + const result = await caller.messages.send({ + generalId: ambassador.id, + mailbox: 9002, + text: '외교 메시지', + }); + + expect(result.msgType).toBe('diplomacy'); + expect(queryRaw.mock.calls[0]?.slice(1)).toEqual(expect.arrayContaining([9002, 'diplomacy'])); + }); + + it('blocks private messages between foreign ambassadors', async () => { + const ambassador = { + ...general, + officerLevel: 1, + meta: { permission: 'ambassador' }, + } as GeneralRow; + const foreignAmbassador = { + ...ambassador, + id: 8, + userId: 'user-8', + name: '상대 외교관', + nationId: 2, + } as GeneralRow; + const { caller } = buildContext({ + general: { + findUnique: vi.fn(async ({ where }: { where: { id: number } }) => + where.id === ambassador.id ? ambassador : foreignAmbassador + ), + findMany: vi.fn(async () => []), + }, + nation: { + findMany: vi.fn(async () => []), + findUnique: vi.fn(async ({ where }: { where: { id: number } }) => ({ + id: where.id, + name: where.id === 1 ? '위' : '촉', + color: '#112233', + meta: {}, + })), + }, + }); + + await expect( + caller.messages.send({ + generalId: ambassador.id, + mailbox: foreignAmbassador.id, + text: '개인 메시지', + }) + ).rejects.toMatchObject({ + code: 'FORBIDDEN', + message: '외교권자끼리는 메시지를 보낼 수 없습니다.', + }); + }); + + it.each([ + ['public', { noSendPublicMsg: 1 }, 9999, '공개 메세지를 보낼 수 없습니다.'], + ['private', { noSendPrivateMsg: 1 }, 8, '개인 메세지를 보낼 수 없습니다.'], + ])('enforces the general %s-message penalty', async (_type, penalty, mailbox, message) => { + const penalized = { ...general, penalty } as GeneralRow; + const { caller } = buildContext({ + general: { + findUnique: vi.fn(async () => penalized), + findMany: vi.fn(async () => []), + }, + nation: { + findMany: vi.fn(async () => []), + findUnique: vi.fn(async () => ({ id: 1, name: '위', color: '#fff', meta: {} })), + }, + }); + + await expect( + caller.messages.send({ + generalId: penalized.id, + mailbox, + text: '차단 메시지', + }) + ).rejects.toMatchObject({ code: 'FORBIDDEN', message }); + }); + + it('enforces the legacy private-message interval through Redis without touching lifecycle', async () => { + const redis = { + set: vi.fn(async () => null), + publish: vi.fn(async () => 1), + }; + const { caller } = buildContext( + { + nation: { + findMany: vi.fn(async () => []), + findUnique: vi.fn(async () => ({ id: 1, name: '위', color: '#fff', meta: {} })), + }, + }, + { redis } + ); + + await expect( + caller.messages.send({ + generalId: general.id, + mailbox: 8, + text: '너무 빠른 메시지', + }) + ).rejects.toMatchObject({ + code: 'TOO_MANY_REQUESTS', + message: '개인메세지는 2초당 1건만 보낼 수 있습니다!', + }); + }); + + it('blocks sends for a muted authenticated user independently of general permission', async () => { + const mutedAuth = { + ...auth, + sanctions: { mutedUntil: '2099-01-01T00:00:00.000Z' }, + }; + const { caller } = buildContext({}, { auth: mutedAuth }); + + await expect( + caller.messages.send({ + generalId: general.id, + mailbox: 9999, + text: '사용자 mute', + }) + ).rejects.toMatchObject({ + code: 'FORBIDDEN', + message: '메시지 전송이 제한된 계정입니다.', + }); + }); + + it('rejects every remaining general-scoped message mutation for another user general', async () => { + const foreignGeneral = { ...general, userId: 'user-8' } as GeneralRow; + const { caller } = buildContext({ + general: { + findUnique: vi.fn(async () => foreignGeneral), + findMany: vi.fn(async () => []), + }, + }); + + await expect(caller.messages.getContacts({ generalId: foreignGeneral.id })).rejects.toMatchObject({ + code: 'FORBIDDEN', + }); + await expect( + caller.messages.readLatest({ + generalId: foreignGeneral.id, + type: 'private', + messageId: 1, + }) + ).rejects.toMatchObject({ code: 'FORBIDDEN' }); + await expect(caller.messages.delete({ generalId: foreignGeneral.id, messageId: 1 })).rejects.toMatchObject({ + code: 'FORBIDDEN', + }); + await expect( + caller.messages.respond({ + generalId: foreignGeneral.id, + messageId: 1, + response: true, + }) + ).rejects.toMatchObject({ code: 'FORBIDDEN' }); + }); + it('persists latest-read updates through the monotonic upsert', async () => { const { caller, executeRaw } = buildContext(); @@ -154,6 +444,49 @@ describe('messages router missing-flow compatibility', () => { }); }); + it('lets the sender delete a manual diplomacy copy without deleting the receiver copy', async () => { + const queryRaw = vi.fn(async () => [ + { + id: 25, + mailbox: 9001, + type: 'diplomacy', + src: 9001, + dest: 9002, + time: new Date(), + valid_until: new Date('9999-12-31T00:00:00Z'), + message: { + src: { + generalId: general.id, + generalName: general.name, + nationId: 1, + nationName: '위', + color: '#fff', + icon: '', + }, + dest: { + generalId: 0, + generalName: '', + nationId: 2, + nationName: '촉', + color: '#000', + icon: '', + }, + text: '일반 외교 메시지', + option: { receiverMessageID: 26 }, + }, + }, + ]); + const { caller, updateMany } = buildContext({ $queryRaw: queryRaw }); + + const result = await caller.messages.delete({ generalId: general.id, messageId: 25 }); + + expect(result.deletedIds).toEqual([25]); + expect(updateMany).toHaveBeenCalledWith({ + where: { id: { in: [25] } }, + data: { validUntil: expect.any(Date) }, + }); + }); + it('rejects deleting another general message', async () => { const queryRaw = vi.fn(async () => [ { diff --git a/app/game-frontend/src/components/main/MessagePanel.vue b/app/game-frontend/src/components/main/MessagePanel.vue index d97f9cd..2ab2bd1 100644 --- a/app/game-frontend/src/components/main/MessagePanel.vue +++ b/app/game-frontend/src/components/main/MessagePanel.vue @@ -1,13 +1,25 @@ diff --git a/app/game-frontend/src/components/main/MessagePlate.vue b/app/game-frontend/src/components/main/MessagePlate.vue new file mode 100644 index 0000000..fc665d0 --- /dev/null +++ b/app/game-frontend/src/components/main/MessagePlate.vue @@ -0,0 +1,431 @@ + + + + + diff --git a/app/game-frontend/src/stores/mainDashboard.ts b/app/game-frontend/src/stores/mainDashboard.ts index 042482c..9f5803d 100644 --- a/app/game-frontend/src/stores/mainDashboard.ts +++ b/app/game-frontend/src/stores/mainDashboard.ts @@ -23,6 +23,7 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => { type MapLayout = Awaited>; type CommandTable = Awaited>; type MessageBundle = Awaited>; + type MessageContacts = Awaited>; type BoardAccess = Awaited>; type ReservedTurnView = Awaited>[number]; @@ -37,12 +38,14 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => { const mapLayout = ref(null); const commandTable = ref(null); const messages = ref(null); + const messageContacts = ref(null); const boardAccess = ref(null); const reservedGeneralTurns = ref(null); const reservedNationTurns = ref(null); const messageDraftText = ref(''); const targetMailbox = ref(MESSAGE_MAILBOX_PUBLIC); + let initializedMailboxGeneralId: number | null = null; const general = computed(() => generalContext.value?.general ?? null); const city = computed(() => generalContext.value?.city ?? null); @@ -86,18 +89,85 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => { } as const; }); - const mailboxOptions = computed(() => { - const options: Array<{ label: string; value: number; disabled?: boolean }> = [ - { label: '공공', value: MESSAGE_MAILBOX_PUBLIC }, + const mailboxGroups = computed(() => { + type MailboxOption = { + label: string; + value: number; + disabled?: boolean; + color?: string; + }; + type MailboxGroup = { + label: string; + color?: string; + options: MailboxOption[]; + }; + + const ownNationId = general.value?.nationId ?? 0; + const ownMailbox = MESSAGE_MAILBOX_NATIONAL_BASE + ownNationId; + const permission = messages.value?.permission ?? -1; + const contacts = messageContacts.value?.nation ?? []; + const ownNation = contacts.find((nation) => nation.mailbox === ownMailbox); + const groups: MailboxGroup[] = [ + { + label: '즐겨찾기', + color: '#000000', + options: [ + { + label: '【 아국 메세지 】', + value: ownMailbox, + color: ownNation?.color ?? '#000000', + }, + { + label: '【 전체 메세지 】', + value: MESSAGE_MAILBOX_PUBLIC, + color: '#000000', + }, + ], + }, ]; - if (nationId.value) { - options.push({ label: '국가', value: MESSAGE_MAILBOX_NATIONAL_BASE + nationId.value }); - } else { - options.push({ label: '국가', value: -1, disabled: true }); + + if (permission >= 4) { + groups.push({ + label: '외교메시지', + color: '#000000', + options: contacts + .filter((nation) => nation.mailbox !== ownMailbox && nation.nationId > 0) + .map((nation) => ({ + label: nation.name, + value: nation.mailbox, + color: nation.color, + })), + }); } - options.push({ label: '외교', value: -2, disabled: true }); - options.push({ label: '개인', value: -3, disabled: true }); - return options; + + const sortedContacts = [...contacts].sort((left, right) => { + if (left.mailbox === ownMailbox) return -1; + if (right.mailbox === ownMailbox) return 1; + return left.mailbox - right.mailbox; + }); + for (const nation of sortedContacts) { + const options = [...nation.general] + .filter(([id]) => id !== generalId.value) + .sort((left, right) => left[1].localeCompare(right[1], 'ko')) + .map(([id, name, flags]) => { + const ruler = Boolean(flags & 1); + const ambassador = Boolean(flags & 4); + return { + label: ruler ? `*${name}*` : ambassador ? `#${name}#` : name, + value: id, + disabled: permission === 4 && ambassador && nation.mailbox !== ownMailbox, + color: nation.color, + }; + }); + if (options.length > 0) { + groups.push({ + label: nation.name, + color: nation.color, + options, + }); + } + } + return groups; }); const statusLine = computed(() => { @@ -147,25 +217,32 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => { context.general.nationId > 0 && context.general.officerLevel >= 5 ? trpc.turns.reserved.getNation.query({ generalId: id }) : Promise.resolve(null); - const [layout, lobby, map, commands, messageData, access, generalTurns, nationTurns] = await Promise.all([ - layoutPromise, - trpc.lobby.info.query(), - trpc.world.getMap.query({ generalId: id, showMe: true, useCache: true }), - trpc.turns.getCommandTable.query({ generalId: id }), - trpc.messages.getRecent.query({ generalId: id }), - trpc.board.getAccess.query(), - generalTurnsPromise, - nationTurnsPromise, - ]); + const [layout, lobby, map, commands, messageData, contacts, access, generalTurns, nationTurns] = + await Promise.all([ + layoutPromise, + trpc.lobby.info.query(), + trpc.world.getMap.query({ generalId: id, showMe: true, useCache: true }), + trpc.turns.getCommandTable.query({ generalId: id }), + trpc.messages.getRecent.query({ generalId: id }), + trpc.messages.getContacts.query({ generalId: id }), + trpc.board.getAccess.query(), + generalTurnsPromise, + nationTurnsPromise, + ]); mapLayout.value = layout; lobbyInfo.value = lobby; worldMap.value = map; commandTable.value = commands; messages.value = messageData; + messageContacts.value = contacts; boardAccess.value = access; reservedGeneralTurns.value = generalTurns; reservedNationTurns.value = nationTurns; + if (initializedMailboxGeneralId !== id) { + targetMailbox.value = MESSAGE_MAILBOX_NATIONAL_BASE + context.general.nationId; + initializedMailboxGeneralId = id; + } } catch (err) { error.value = resolveErrorMessage(err); } finally { @@ -200,12 +277,12 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => { } try { + messageDraftText.value = ''; await trpc.messages.send.mutate({ generalId: id, mailbox, text, }); - messageDraftText.value = ''; await refreshMessages(); } catch (err) { error.value = resolveErrorMessage(err); @@ -260,6 +337,44 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => { } }; + const readLatestMessage = async (type: 'private' | 'diplomacy', messageId: number) => { + const id = generalId.value; + if (!id || messageId <= 0) { + return; + } + try { + await trpc.messages.readLatest.mutate({ + generalId: id, + type, + messageId, + }); + if (messages.value) { + messages.value = { + ...messages.value, + latestRead: { + ...messages.value.latestRead, + [type]: Math.max(messages.value.latestRead[type], messageId), + }, + }; + } + } catch (err) { + error.value = resolveErrorMessage(err); + } + }; + + const deleteMessage = async (messageId: number) => { + const id = generalId.value; + if (!id) { + return; + } + try { + await trpc.messages.delete.mutate({ generalId: id, messageId }); + await refreshMessages(); + } catch (err) { + error.value = resolveErrorMessage(err); + } + }; + const setGeneralTurn = async (turnIndex: number, action: string) => { const id = generalId.value; if (!id) { @@ -484,12 +599,13 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => { selectedCity, commandTable, messages, + messageContacts, boardAccess, reservedGeneralTurns, reservedNationTurns, messageDraftText, targetMailbox, - mailboxOptions, + mailboxGroups, statusLine, realtimeLabel, setRealtimeEnabled, @@ -498,6 +614,8 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => { sendMessage, loadOlderMessages, respondToMessage, + readLatestMessage, + deleteMessage, setGeneralTurn, shiftGeneralTurns, setNationTurn, diff --git a/app/game-frontend/src/views/MainView.vue b/app/game-frontend/src/views/MainView.vue index c6e139c..5beb0e2 100644 --- a/app/game-frontend/src/views/MainView.vue +++ b/app/game-frontend/src/views/MainView.vue @@ -50,7 +50,7 @@ const { reservedNationTurns, messageDraftText, targetMailbox, - mailboxOptions, + mailboxGroups, statusLine, realtimeLabel, } = storeToRefs(dashboard); @@ -216,22 +216,26 @@ watch(
- - - +
@@ -251,22 +255,6 @@ watch(
세력 {{ lobbyInfo?.nationCnt ?? '-' }}
- - -
@@ -302,6 +290,26 @@ watch(
개인 기록 영역
+ @@ -396,6 +404,15 @@ button { gap: 16px; } +.desktop-message-panel { + grid-column: 1 / -1; +} + +.mobile-message-panel { + width: calc(100% + 48px); + margin-left: -24px; +} + .layout-mobile { display: flex; flex-direction: column; diff --git a/docs/architecture/todo.md b/docs/architecture/todo.md index 53fe248..db2881d 100644 --- a/docs/architecture/todo.md +++ b/docs/architecture/todo.md @@ -49,7 +49,7 @@ Move items into the main docs once they are finalized. - [AI suggestion] Define gateway login handoff + profile selection flow for the game frontend (token delivery, auto-login, cookie vs localStorage policy). - [AI suggestion] Implement Public 화면: 캐싱된 지도/중원정세/세력일람 + 제한된 장수일람 API/뷰. - [AI suggestion] Define main screen SSE contract + 실시간 동기화 토글 연동 (지도/명령/도시/국가/장수/메시지/동향/기록). -- [AI suggestion] Port legacy main UI components into `app/game-frontend` (MapViewer, CommandSelectForm, MessagePanel 등). +- [AI suggestion] Port remaining legacy main UI components into `app/game-frontend` (MessagePanel 이관 완료; 나머지 패널 추적). - [AI suggestion] Provide map city name/position data for MapViewer (API or scenario export) and replace placeholder layout. - [AI suggestion] Implement join/빙의 UI and post-creation refresh flow. - [AI suggestion] Build and maintain a legacy-to-SPA route mapping table with data requirements. @@ -57,7 +57,7 @@ Move items into the main docs once they are finalized. - [AI suggestion] Wire `realtimeEnabled` to an SSE or polling channel and update main dashboard data buckets (map/lobby/messages/commands). - [AI suggestion] Finalize static asset and web base URLs (`VITE_GAME_WEB_URL`, `VITE_GAME_ASSET_URL`) and document deployment mapping for legacy images. - [AI suggestion] Expand Join UI to cover inherit options (특기/도시/턴타임/보너스 스탯) using `join.getConfig` and `join.createGeneral` inputs. -- [AI suggestion] Extend MessagePanel to support private/diplomacy targets and surface sender/receiver metadata from message payloads. +- [x] Extend MessagePanel to support private/diplomacy targets and surface sender/receiver metadata from message payloads. - [AI suggestion] Port legacy TipTap-based editors (국가 방침/임관 권유) into game-frontend and reuse the new board image upload policy. ## Runtime and Operations (Lower Priority) diff --git a/tools/frontend-legacy-parity/ingame-message-parity.spec.ts b/tools/frontend-legacy-parity/ingame-message-parity.spec.ts new file mode 100644 index 0000000..726494a --- /dev/null +++ b/tools/frontend-legacy-parity/ingame-message-parity.spec.ts @@ -0,0 +1,384 @@ +import { expect, test, type Page, type Route } from '@playwright/test'; + +import { canonicalFrontendFixture as fixture } from './fixtures/canonical'; + +const gamePort = process.env.FRONTEND_PARITY_GAME_PORT ?? '15102'; +const response = (data: unknown) => ({ result: { data } }); +const errorResponse = (path: string, message: string) => ({ + error: { + message, + code: -32000, + data: { code: 'BAD_REQUEST', httpStatus: 400, path }, + }, +}); + +const operationNames = (route: Route): string[] => { + const pathname = new URL(route.request().url()).pathname; + return decodeURIComponent(pathname.slice(pathname.lastIndexOf('/trpc/') + 6)).split(','); +}; + +const general = { + id: 1, + name: '테스트장수', + npcState: 0, + nationId: 1, + cityId: 1, + troopId: 0, + picture: 'default.jpg', + imageServer: 0, + officerLevel: 1, + stats: { leadership: 80, strength: 70, intelligence: 90 }, + gold: 1000, + rice: 1000, + crew: 500, + train: 100, + atmos: 100, + injury: 0, + experience: 1200, + dedication: 900, + items: { horse: null, weapon: null, book: null, item: null }, +}; + +const generalContext = { + general, + city: { + id: 1, + name: '낙양', + level: 7, + nationId: 1, + population: 50000, + agriculture: 5000, + commerce: 5000, + security: 5000, + defence: 5000, + wall: 5000, + supplyState: 1, + frontState: 2, + }, + nation: { + id: 1, + name: '테스트국', + color: '#d32f2f', + level: 5, + gold: 10000, + rice: 10000, + tech: 1200, + typeCode: 'che_군벌', + capitalCityId: 1, + }, + settings: {}, + penalties: {}, +}; + +const target = (generalId: number, generalName: string, nationId: number, nationName: string, color: string) => ({ + generalId, + generalName, + nationId, + nationName, + color, + icon: '/image/icons/default.jpg', +}); + +const ownTarget = target(1, '테스트장수', 1, '테스트국', '#d32f2f'); +const foreignTarget = target(8, '상대장수', 2, '상대국', '#2457a6'); +const messageTime = new Date().toISOString().replace('T', ' ').slice(0, 19); + +const buildMessages = (permission: number) => ({ + result: true, + public: [ + { + id: 101, + msgType: 'public', + src: ownTarget, + dest: null, + text: '전체 메시지 본문', + option: {}, + time: messageTime, + }, + ], + national: [ + { + id: 102, + msgType: 'national', + src: ownTarget, + dest: target(0, '', 1, '테스트국', '#d32f2f'), + text: '국가 메시지 본문', + option: {}, + time: messageTime, + }, + ], + private: [ + { + id: 103, + msgType: 'private', + src: foreignTarget, + dest: ownTarget, + text: '개인 메시지 본문', + option: {}, + time: messageTime, + }, + ], + diplomacy: [ + { + id: 104, + msgType: 'diplomacy', + src: foreignTarget, + dest: target(0, '', 1, '테스트국', '#d32f2f'), + text: permission >= 3 ? '외교 메시지 본문' : '(외교 메시지입니다)', + option: + permission >= 3 + ? { action: 'noAggression', deletable: false } + : { action: 'noAggression', deletable: false, invalid: true }, + time: messageTime, + }, + ], + sequence: 104, + nationId: 1, + generalName: general.name, + permission, + canRespondDiplomacy: permission >= 4 && general.officerLevel > 4, + latestRead: { private: 0, diplomacy: 0 }, +}); + +const contacts = { + nation: [ + { + nationId: 0, + mailbox: 9000, + name: '재야', + color: '#000000', + general: [], + }, + { + nationId: 1, + mailbox: 9001, + name: '테스트국', + color: '#d32f2f', + general: [ + [1, '테스트장수', 4], + [2, '아군군주', 1], + ], + }, + { + nationId: 2, + mailbox: 9002, + name: '상대국', + color: '#2457a6', + general: [ + [8, '상대외교관', 4], + [9, '상대일반', 0], + ], + }, + ], +}; + +const installFixture = async ( + page: Page, + options: { permission: number; sendError?: string } +): Promise> => { + const mutations: Array<{ operation: string; body: unknown }> = []; + await page.addInitScript( + ({ gameToken, profile }) => { + window.localStorage.setItem('sammo-game-token', gameToken); + window.localStorage.setItem('sammo-game-profile', profile); + }, + { + gameToken: fixture.game.session.gameToken, + profile: fixture.game.session.profile, + } + ); + await page.route('**/image/**', (route) => route.fulfill({ status: 204, body: '' })); + await page.route('**/che/api/events**', (route) => route.abort()); + await page.route('**/che/api/trpc/**', async (route) => { + const body = route.request().postDataJSON(); + const results = operationNames(route).map((operation) => { + if (operation === 'lobby.info') { + return response({ ...fixture.game.lobby, myGeneral: general }); + } + if (operation === 'general.me') return response(generalContext); + if (operation === 'world.getMapLayout') return response(fixture.game.mapLayout); + if (operation === 'world.getMap') { + return response({ ...fixture.game.map, myCity: 1, myNation: 1 }); + } + if (operation === 'turns.getCommandTable') return response({ general: [], nation: [] }); + if (operation === 'turns.reserved.getGeneral' || operation === 'turns.reserved.getNation') { + return response([]); + } + if (operation === 'messages.getRecent') return response(buildMessages(options.permission)); + if (operation === 'messages.getContacts') return response(contacts); + if (operation === 'board.getAccess') return response({ canMeeting: true, canSecret: true }); + if (operation === 'tournament.getState') return response({ stage: 0 }); + if ( + operation === 'messages.send' || + operation === 'messages.readLatest' || + operation === 'messages.delete' || + operation === 'messages.respond' + ) { + mutations.push({ operation, body }); + if (operation === 'messages.send' && options.sendError) { + return errorResponse(operation, options.sendError); + } + return response(operation === 'messages.respond' ? { result: true, reason: 'success' } : { ok: true }); + } + return errorResponse(operation, `Unhandled message fixture operation: ${operation}`); + }); + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify(results), + }); + }); + return mutations; +}; + +const openMessages = async (page: Page, viewport: { width: number; height: number }) => { + await page.setViewportSize(viewport); + await page.goto(`http://127.0.0.1:${gamePort}/che/`); + await expect(page.getByRole('heading', { name: '전장 현황' })).toBeVisible(); + if (viewport.width <= 1024) { + await page.getByRole('button', { name: '메시지', exact: true }).click(); + } + await expect(page.locator('.MessagePanel')).toBeVisible(); +}; + +for (const viewport of [ + { width: 1000, height: 900 }, + { width: 500, height: 900 }, +]) { + test(`matches the reference message computed DOM at ${viewport.width}px Chromium viewport`, async ({ page }) => { + await installFixture(page, { permission: 4 }); + await openMessages(page, viewport); + const geometry = await page.locator('.MessagePanel').evaluate((panel) => { + const required = (selector: string) => panel.querySelector(selector)!; + const rect = (element: Element) => { + const box = element.getBoundingClientRect(); + return { x: box.x, y: box.y, width: box.width, height: box.height }; + }; + const panelStyle = getComputedStyle(panel); + const header = required('.BoardHeader'); + const plate = required('.msg-plate'); + const icon = required('.general-icon'); + return { + panel: rect(panel), + inputForm: rect(required('.MessageInputForm')), + select: rect(required('.message-select')), + input: rect(required('.message-text')), + submit: rect(required('.message-send')), + publicSection: rect(required('.PublicTalk')), + nationalSection: rect(required('.NationalTalk')), + firstHeader: rect(header), + firstPlate: rect(plate), + firstIcon: rect(icon), + computed: { + panelDisplay: panelStyle.display, + panelColumns: panelStyle.gridTemplateColumns, + panelFontSize: panelStyle.fontSize, + headerColor: getComputedStyle(header).color, + headerOutlineWidth: getComputedStyle(header).outlineWidth, + plateBackgroundColor: getComputedStyle(plate).backgroundColor, + plateFontSize: getComputedStyle(plate).fontSize, + plateMinHeight: getComputedStyle(plate).minHeight, + iconObjectFit: getComputedStyle(icon).objectFit, + }, + }; + }); + + expect(geometry.panel.x).toBeCloseTo(0, 0); + expect(geometry.panel.width).toBeCloseTo(viewport.width, 0); + expect(geometry.inputForm.width).toBeCloseTo(viewport.width, 0); + expect(geometry.select.height).toBeCloseTo(35.5, 0); + expect(geometry.submit.height).toBeCloseTo(35.5, 0); + expect(geometry.firstHeader.height).toBeCloseTo(25, 0); + expect(geometry.firstPlate.height).toBeGreaterThanOrEqual(64); + expect(geometry.firstIcon).toMatchObject({ width: 64, height: 64 }); + expect(geometry.computed).toMatchObject({ + panelFontSize: '14px', + headerColor: 'rgb(255, 255, 255)', + headerOutlineWidth: '1px', + plateBackgroundColor: 'rgb(20, 28, 101)', + plateFontSize: '12.5px', + plateMinHeight: '64px', + iconObjectFit: 'fill', + }); + + if (viewport.width === 1000) { + expect(geometry.computed.panelDisplay).toBe('grid'); + expect(geometry.computed.panelColumns).toBe('500px 500px'); + expect(geometry.select.width).toBeCloseTo(166.66, 0); + expect(geometry.input.width).toBeCloseTo(666.66, 0); + expect(geometry.submit.width).toBeCloseTo(166.66, 0); + expect(geometry.publicSection.width).toBeCloseTo(500, 0); + expect(geometry.nationalSection.x).toBeCloseTo(500, 0); + } else { + expect(geometry.computed.panelDisplay).toBe('block'); + expect(geometry.select.width).toBeCloseTo(250, 0); + expect(geometry.input.width).toBeCloseTo(500, 0); + expect(geometry.input.height).toBeCloseTo(33.5, 0); + expect(geometry.submit.width).toBeCloseTo(250, 0); + } + + const submit = page.locator('.message-send'); + await submit.hover(); + expect( + await submit.evaluate((element) => ({ + cursor: getComputedStyle(element).cursor, + backgroundColor: getComputedStyle(element).backgroundColor, + })) + ).toEqual({ cursor: 'pointer', backgroundColor: 'rgb(55, 90, 127)' }); + await submit.focus(); + expect( + await submit.evaluate((element) => ({ + outlineWidth: getComputedStyle(element).outlineWidth, + boxShadow: getComputedStyle(element).boxShadow, + })) + ).toEqual({ outlineWidth: '0px', boxShadow: 'none' }); + }); +} + +test('exposes ambassador targets, reply, read, delete, and successful send interactions', async ({ page }) => { + const mutations = await installFixture(page, { permission: 4 }); + await openMessages(page, { width: 500, height: 900 }); + + const select = page.getByLabel('메시지 수신 대상'); + await expect(select.locator('option[value="9002"]')).toHaveCount(1); + await expect(select.locator('option[value="8"]')).toBeDisabled(); + await expect(select.locator('option[value="9"]')).toBeEnabled(); + + await page.locator('.PrivateTalk .msg-target').filter({ hasText: '상대장수' }).click(); + await expect(select).toHaveValue('8'); + + await page.locator('.PrivateTalk').getByRole('button', { name: '모두 읽음' }).click(); + await expect.poll(() => mutations.filter((entry) => entry.operation === 'messages.readLatest').length).toBe(1); + + const deleteButton = page.locator('.PublicTalk .delete-message'); + page.once('dialog', (dialog) => dialog.accept()); + await deleteButton.click(); + await expect.poll(() => mutations.filter((entry) => entry.operation === 'messages.delete').length).toBe(1); + + await select.selectOption('9999'); + await page.getByLabel('메시지 입력').fill('전송 성공'); + await page.getByRole('button', { name: '서신전달&갱신' }).click(); + await expect(page.getByLabel('메시지 입력')).toHaveValue(''); + await expect.poll(() => mutations.filter((entry) => entry.operation === 'messages.send').length).toBe(1); +}); + +test('redacts diplomacy for a low-permission general and preserves the failed-send error flow', async ({ page }) => { + const mutations = await installFixture(page, { + permission: 2, + sendError: '공개 메세지를 보낼 수 없습니다.', + }); + await openMessages(page, { width: 500, height: 900 }); + + const select = page.getByLabel('메시지 수신 대상'); + await expect(select.locator('option[value="9002"]')).toHaveCount(0); + await expect(page.locator('.DiplomacyTalk')).toContainText('삭제된 메시지입니다'); + await expect(page.locator('.DiplomacyTalk')).not.toContainText('외교 메시지 본문'); + await expect(page.locator('.DiplomacyTalk .message-response button').first()).toBeDisabled(); + + await select.selectOption('9999'); + await page.getByLabel('메시지 입력').fill('차단될 메시지'); + await page.getByRole('button', { name: '서신전달&갱신' }).click(); + await expect(page.getByLabel('메시지 입력')).toHaveValue(''); + await expect(page.locator('.error')).toHaveText('공개 메세지를 보낼 수 없습니다.'); + await expect.poll(() => mutations.filter((entry) => entry.operation === 'messages.send').length).toBe(1); +}); diff --git a/tools/frontend-legacy-parity/instant-diplomacy-message.spec.ts b/tools/frontend-legacy-parity/instant-diplomacy-message.spec.ts index f15c6ef..dc526bf 100644 --- a/tools/frontend-legacy-parity/instant-diplomacy-message.spec.ts +++ b/tools/frontend-legacy-parity/instant-diplomacy-message.spec.ts @@ -5,6 +5,7 @@ import { resolve } from 'node:path'; import { canonicalFrontendFixture as fixture } from './fixtures/canonical'; const artifactRoot = process.env.FRONTEND_PARITY_ARTIFACT_DIR; +const gamePort = process.env.FRONTEND_PARITY_GAME_PORT ?? '15102'; const response = (data: unknown) => ({ result: { data } }); const operationNames = (route: Route): string[] => { @@ -90,6 +91,7 @@ const messageBundle = (visible: boolean, canRespondDiplomacy = true) => ({ sequence: visible ? diplomacyMessage.id : -1, nationId: 1, generalName: general.name, + permission: canRespondDiplomacy ? 4 : 2, canRespondDiplomacy, latestRead: { diplomacy: 0, private: 0 }, }); @@ -131,6 +133,9 @@ const installFixture = async ( if (operation === 'messages.getRecent') { return response(messageBundle(visible, options.canRespondDiplomacy)); } + if (operation === 'messages.getContacts') return response({ nation: [] }); + if (operation === 'board.getAccess') return response({ canMeeting: true, canSecret: true }); + if (operation === 'tournament.getState') return response({ stage: 0 }); if (operation === 'messages.respond') { mutations.push({ operation, body: requestBody }); if (options.acceptResponse) { @@ -151,9 +156,9 @@ const installFixture = async ( }; const openDiplomacyTab = async (page: Page) => { - await page.goto('http://127.0.0.1:15102/che/'); + await page.goto(`http://127.0.0.1:${gamePort}/che/`); await expect(page.getByRole('heading', { name: '전장 현황' })).toBeVisible(); - await page.getByRole('button', { name: '외교', exact: true }).last().click(); + await expect(page.locator('.DiplomacyTalk')).toBeVisible(); await expect(page.getByText(diplomacyMessage.text)).toBeVisible(); }; @@ -186,20 +191,20 @@ test.describe('instant diplomacy response UI', () => { }); expect(geometry.buttons).toHaveLength(2); - expect(geometry.buttons[1]!.x - (geometry.buttons[0]!.x + geometry.buttons[0]!.width)).toBeCloseTo(4, 0); + expect(geometry.buttons[1]!.x - (geometry.buttons[0]!.x + geometry.buttons[0]!.width)).toBeCloseTo(0, 0); expect(geometry.buttons[0]).toMatchObject({ - color: 'rgb(143, 209, 143)', - fontSize: '11.2px', + color: 'rgb(255, 255, 255)', + fontSize: '12.5px', borderWidth: '1px', cursor: 'pointer', }); expect(geometry.buttons[1]).toMatchObject({ - color: 'rgb(224, 154, 154)', - fontSize: '11.2px', + color: 'rgb(255, 255, 255)', + fontSize: '12.5px', borderWidth: '1px', cursor: 'pointer', }); - expect(geometry.buttons.every((button) => button.height >= 22 && button.height <= 26)).toBe(true); + expect(geometry.buttons.every((button) => button.height >= 20 && button.height <= 22)).toBe(true); await decline.hover(); expect(await decline.evaluate((element) => getComputedStyle(element).cursor)).toBe('pointer'); @@ -234,18 +239,17 @@ test.describe('instant diplomacy response UI', () => { test('keeps the message and exposes a rejected response on mobile Chromium', async ({ page }) => { const mutations = await installFixture(page, { acceptResponse: false }); await page.setViewportSize({ width: 390, height: 844 }); - await page.goto('http://127.0.0.1:15102/che/'); + await page.goto(`http://127.0.0.1:${gamePort}/che/`); await expect(page.getByRole('heading', { name: '전장 현황' })).toBeVisible(); await page.getByRole('button', { name: '메시지', exact: true }).click(); - await page.getByRole('button', { name: '외교', exact: true }).click(); const responseRow = page.locator('.message-response'); await expect(responseRow).toBeVisible(); const itemWidth = await page - .locator('.message-item') + .locator('.DiplomacyTalk .msg-plate') .evaluate((element) => element.getBoundingClientRect().width); - expect(itemWidth).toBeGreaterThan(320); - expect(itemWidth).toBeLessThanOrEqual(342); + expect(itemWidth).toBeGreaterThanOrEqual(389); + expect(itemWidth).toBeLessThanOrEqual(390); page.once('dialog', async (dialog) => { expect(dialog.message()).toBe('거절하시겠습니까?'); @@ -272,10 +276,9 @@ test.describe('instant diplomacy response UI', () => { canRespondDiplomacy: false, }); await page.setViewportSize({ width: 390, height: 844 }); - await page.goto('http://127.0.0.1:15102/che/'); + await page.goto(`http://127.0.0.1:${gamePort}/che/`); await expect(page.getByRole('heading', { name: '전장 현황' })).toBeVisible(); await page.getByRole('button', { name: '메시지', exact: true }).click(); - await page.getByRole('button', { name: '외교', exact: true }).click(); const accept = page.locator('.message-response').getByRole('button', { name: '수락' }); await expect(accept).toBeDisabled(); @@ -284,7 +287,7 @@ test.describe('instant diplomacy response UI', () => { const style = getComputedStyle(element); return { cursor: style.cursor, opacity: style.opacity }; }) - ).toEqual({ cursor: 'not-allowed', opacity: '0.5' }); + ).toEqual({ cursor: 'not-allowed', opacity: '0.65' }); await accept.click({ force: true }); expect(mutations).toHaveLength(0); }); diff --git a/tools/frontend-legacy-parity/playwright.config.mjs b/tools/frontend-legacy-parity/playwright.config.mjs index eece2a1..b42bc03 100644 --- a/tools/frontend-legacy-parity/playwright.config.mjs +++ b/tools/frontend-legacy-parity/playwright.config.mjs @@ -12,6 +12,7 @@ export default defineConfig({ 'visual-parity.spec.ts', 'public-gaps.spec.ts', 'instant-diplomacy-message.spec.ts', + 'ingame-message-parity.spec.ts', 'tournament-betting.spec.ts', ], fullyParallel: false, diff --git a/tools/frontend-legacy-parity/reference-ingame-message.mjs b/tools/frontend-legacy-parity/reference-ingame-message.mjs new file mode 100644 index 0000000..45c147e --- /dev/null +++ b/tools/frontend-legacy-parity/reference-ingame-message.mjs @@ -0,0 +1,178 @@ +import { createHash } from 'node:crypto'; +import { mkdir, readFile } from 'node:fs/promises'; +import { dirname, resolve } from 'node:path'; + +import { chromium } from '@playwright/test'; + +const baseUrl = process.env.REF_MESSAGE_URL ?? 'http://127.0.0.1:3400/sam/'; +const username = process.env.REF_MESSAGE_USER ?? 'refuser1'; +const passwordFile = process.env.REF_MESSAGE_PASSWORD_FILE; +const artifactRoot = process.env.REF_MESSAGE_ARTIFACT_DIR; + +if (!passwordFile) { + throw new Error('REF_MESSAGE_PASSWORD_FILE is required.'); +} + +const password = (await readFile(passwordFile, 'utf8')).trim(); + +const login = async (context, page) => { + await page.goto(baseUrl, { waitUntil: 'networkidle', timeout: 60_000 }); + const globalSalt = await page.locator('#global_salt').inputValue(); + const passwordHash = createHash('sha512') + .update(globalSalt + password + globalSalt) + .digest('hex'); + const response = await context.request.post(new URL('api.php?path=Login/LoginByID', baseUrl).toString(), { + data: { username, password: passwordHash }, + }); + const result = await response.json(); + if (!response.ok() || result.result !== true) { + throw new Error('Reference login failed.'); + } +}; + +const ensureGeneral = async (page) => { + await page.goto(new URL('hwe/index.php', baseUrl).toString(), { + waitUntil: 'networkidle', + timeout: 60_000, + }); + if (await page.locator('.MessagePanel').isVisible()) { + return; + } + + await page.goto(new URL('hwe/v_join.php', baseUrl).toString(), { + waitUntil: 'networkidle', + timeout: 60_000, + }); + const create = page.getByRole('button', { name: '장수 생성', exact: true }); + await create.waitFor({ state: 'visible', timeout: 30_000 }); + page.once('dialog', (dialog) => dialog.accept()); + await create.click(); + await page.locator('.MessagePanel').waitFor({ state: 'visible', timeout: 60_000 }); +}; + +const measure = async (browser, name, viewport) => { + const context = await browser.newContext({ + viewport, + deviceScaleFactor: 1, + colorScheme: 'dark', + locale: 'ko-KR', + timezoneId: 'UTC', + ignoreHTTPSErrors: true, + }); + try { + const page = await context.newPage(); + await login(context, page); + await ensureGeneral(page); + await page.locator('.MessagePanel').waitFor({ state: 'visible', timeout: 30_000 }); + await page.locator('.BoardHeader').first().waitFor({ state: 'visible' }); + const marker = `computed-dom-${name}-${Date.now()}`; + await page.locator('.MessageInputForm select').selectOption('9999'); + await page.locator('.MessageInputForm input').fill(marker); + await page.getByRole('button', { name: '서신전달&갱신' }).click(); + await page.getByText(marker, { exact: true }).waitFor({ state: 'visible', timeout: 30_000 }); + + if (artifactRoot) { + const path = resolve(artifactRoot, `message-ref-${name}.png`); + await mkdir(dirname(path), { recursive: true }); + await page.locator('.MessagePanel').screenshot({ + path, + animations: 'disabled', + }); + } + + const result = await page.evaluate(() => { + const rect = (element) => { + const box = element.getBoundingClientRect(); + return { + x: box.x, + y: box.y, + width: box.width, + height: box.height, + }; + }; + const required = (selector) => { + const element = document.querySelector(selector); + if (!element) throw new Error(`Missing reference selector: ${selector}`); + return element; + }; + const optionalRect = (selector) => { + const element = document.querySelector(selector); + return element ? rect(element) : null; + }; + const style = (selector) => getComputedStyle(required(selector)); + const input = required('.MessageInputForm input'); + const select = required('.MessageInputForm select'); + const submit = required('#msg_submit-col button'); + const firstPlate = document.querySelector('.msg_plate'); + const firstIcon = document.querySelector('.msg_plate .generalIcon'); + const panelStyle = style('.MessagePanel'); + const headerStyle = style('.BoardHeader'); + const plateStyle = firstPlate ? getComputedStyle(firstPlate) : null; + const iconStyle = firstIcon ? getComputedStyle(firstIcon) : null; + return { + panel: rect(required('.MessagePanel')), + inputForm: rect(required('.MessageInputForm')), + select: rect(select), + input: rect(input), + submit: rect(submit), + publicSection: rect(required('.PublicTalk')), + nationalSection: rect(required('.NationalTalk')), + privateSection: rect(required('.PrivateTalk')), + diplomacySection: rect(required('.DiplomacyTalk')), + firstHeader: rect(required('.BoardHeader')), + firstPlate: optionalRect('.msg_plate'), + firstIcon: optionalRect('.msg_plate .generalIcon'), + computed: { + panelDisplay: panelStyle.display, + panelColumns: panelStyle.gridTemplateColumns, + panelFontSize: panelStyle.fontSize, + headerColor: headerStyle.color, + headerOutlineWidth: headerStyle.outlineWidth, + headerBackgroundImage: headerStyle.backgroundImage, + plateBackgroundColor: plateStyle?.backgroundColor ?? null, + plateFontSize: plateStyle?.fontSize ?? null, + plateMinHeight: plateStyle?.minHeight ?? null, + iconObjectFit: iconStyle?.objectFit ?? null, + }, + }; + }); + + const submit = page.locator('#msg_submit-col button'); + await submit.hover(); + const hover = await submit.evaluate((element) => { + const style = getComputedStyle(element); + return { + cursor: style.cursor, + backgroundColor: style.backgroundColor, + }; + }); + await submit.focus(); + const focus = await submit.evaluate((element) => { + const style = getComputedStyle(element); + return { + outline: style.outline, + boxShadow: style.boxShadow, + }; + }); + const markerPlate = page.locator('.msg_plate').filter({ hasText: marker }); + const deleteButton = markerPlate.locator('.btn-delete-msg'); + if (await deleteButton.isVisible()) { + page.once('dialog', (dialog) => dialog.accept()); + await deleteButton.click(); + } + return { ...result, interaction: { hover, focus } }; + } finally { + await context.close(); + } +}; + +const browser = await chromium.launch({ headless: true }); +try { + const measurements = { + desktop: await measure(browser, 'desktop', { width: 1000, height: 900 }), + mobile: await measure(browser, 'mobile', { width: 500, height: 900 }), + }; + process.stdout.write(`${JSON.stringify(measurements, null, 2)}\n`); +} finally { + await browser.close(); +} From 47f03abeb47c5279cff56acc9267e9377d1abaf1 Mon Sep 17 00:00:00 2001 From: hided62 Date: Sun, 26 Jul 2026 05:30:35 +0000 Subject: [PATCH 11/16] feat(frontend): finish battle simulator workflows --- app/game-frontend/e2e/battleSimulator.spec.ts | 320 ++++++++++++++++++ .../e2e/battleSimulatorRef.spec.ts | 73 ++++ app/game-frontend/e2e/playwright.config.mjs | 2 + app/game-frontend/package.json | 1 + .../components/battle/BattleGeneralCard.vue | 55 ++- app/game-frontend/src/router/index.ts | 1 - .../src/views/BattleSimulatorView.vue | 239 ++++++++++--- app/game-frontend/src/views/JoinView.vue | 23 +- docs/frontend-legacy-parity.md | 18 +- 9 files changed, 636 insertions(+), 96 deletions(-) create mode 100644 app/game-frontend/e2e/battleSimulator.spec.ts create mode 100644 app/game-frontend/e2e/battleSimulatorRef.spec.ts diff --git a/app/game-frontend/e2e/battleSimulator.spec.ts b/app/game-frontend/e2e/battleSimulator.spec.ts new file mode 100644 index 0000000..bf0760f --- /dev/null +++ b/app/game-frontend/e2e/battleSimulator.spec.ts @@ -0,0 +1,320 @@ +import { expect, test, type Page, type Route } from '@playwright/test'; +import { readFile } from 'node:fs/promises'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../../..'); +const imageRoots = [resolve(repositoryRoot, '../image'), resolve(repositoryRoot, '../../image')]; +const artifactRoot = process.env.BATTLE_SIM_ARTIFACT_DIR; + +const response = (data: unknown) => ({ result: { data } }); +const errorResponse = (path: string, message: string) => ({ + error: { + message, + code: -32000, + data: { code: 'BAD_REQUEST', httpStatus: 400, path }, + }, +}); + +const operationNames = (route: Route): string[] => { + const url = new URL(route.request().url()); + return decodeURIComponent(url.pathname.slice(url.pathname.lastIndexOf('/trpc/') + 6)).split(','); +}; + +const readImage = async (relative: string): Promise => { + for (const root of imageRoots) { + try { + return await readFile(resolve(root, relative)); + } catch { + // Main checkout and feature worktrees have different image-root parents. + } + } + throw new Error(`Reference image not found: ${relative}`); +}; + +const simulatorOptions = { + world: { startYear: 190, currentYear: 205, currentMonth: 8 }, + config: { + maxTrainByWar: 120, + maxAtmosByWar: 120, + maxTrainByCommand: 100, + maxAtmosByCommand: 100, + }, + unitSet: { + defaultCrewTypeId: 100, + crewTypes: [ + { id: 100, name: '보병', armType: 1 }, + { id: 200, name: '궁병', armType: 2 }, + ], + }, + nationTypes: [{ key: 'che_중립', name: '중립', info: '특별한 효과 없음' }], + warTraits: [{ key: 'che_필살', name: '필살', info: '필살 확률 증가' }], + personalities: [{ key: 'che_대담', name: '대담', info: '공격적인 성격' }], + items: { horse: [], weapon: [], book: [], item: [] }, + nationLevels: [ + { level: 0, name: '방랑군' }, + { level: 1, name: '소국' }, + ], + cityLevels: [ + { level: 1, name: '소도시' }, + { level: 5, name: '대도시' }, + ], + dexLevels: [ + { level: 0, label: 'F', value: 0 }, + { level: 1, label: 'E', value: 1000 }, + ], +}; + +const generalMe = { + general: { + id: 7, + name: '유비', + npcState: 0, + nationId: 1, + cityId: 1, + troopId: 0, + picture: '22.jpg', + imageServer: 0, + officerLevel: 12, + stats: { leadership: 85, strength: 72, intelligence: 78 }, + gold: 1000, + rice: 8765, + crew: 4321, + train: 99, + atmos: 98, + injury: 0, + experience: 900, + dedication: 100, + items: { horse: null, weapon: null, book: null, item: null }, + }, + city: { id: 1, level: 1, defence: 2222, wall: 3333 }, + nation: { id: 1, level: 1, tech: 4500, typeCode: 'che_중립', capitalCityId: 1 }, + settings: {}, + penalties: {}, +}; + +const importedGeneral = { + general: { + no: 7, + name: '유비', + officer_level: 12, + explevel: 30, + leadership: 85, + strength: 72, + intel: 78, + horse: null, + weapon: null, + book: null, + item: null, + injury: 0, + rice: 8765, + personal: 'che_대담', + special2: 'che_필살', + crew: 4321, + crewtype: 100, + atmos: 98, + train: 99, + dex1: 1000, + dex2: 0, + dex3: 0, + dex4: 0, + dex5: 0, + defence_train: 90, + warnum: 12, + killnum: 7, + killcrew: 3456, + }, +}; + +const simulationResult = { + result: true, + reason: 'success', + datetime: '205-08', + avgWar: 5, + phase: 13, + killed: 1234, + maxKilled: 1400, + minKilled: 1100, + dead: 432, + maxDead: 500, + minDead: 400, + attackerRice: 321, + defenderRice: 654, + attackerSkills: { 필살: 2 }, + defendersSkills: [{ 회피: 1 }], + lastWarLog: { + generalHistoryLog: '', + generalActionLog: '', + generalBattleResultLog: '유비가 모의전에서 승리했습니다.', + generalBattleDetailLog: '필살 발동, 피해 1,234', + nationalHistoryLog: '', + globalHistoryLog: '', + globalActionLog: '', + }, +}; + +type Fixture = { + hasGeneral: boolean; + failNextSimulation?: boolean; + queueFirst?: boolean; + pollingCount: number; + requests: string[]; +}; + +const installImages = async (page: Page) => { + for (const filename of ['back_walnut.jpg', 'back_green.jpg', 'back_blue.jpg']) { + await page.route(`**/image/game/${filename}`, async (route) => { + await route.fulfill({ + status: 200, + contentType: 'image/jpeg', + body: await readImage(`game/${filename}`), + }); + }); + } +}; + +const installApi = async (page: Page, fixture: Fixture) => { + await installImages(page); + await page.addInitScript(() => { + window.localStorage.setItem('sammo-game-token', 'ga_battle_sim_playwright'); + window.localStorage.setItem('sammo-game-profile', 'che:default'); + }); + await page.route('**/che/api/trpc/**', async (route) => { + const operations = operationNames(route); + const results = operations.map((operation) => { + fixture.requests.push(operation); + if (operation === 'lobby.info') { + return response({ + year: 205, + month: 8, + myGeneral: fixture.hasGeneral ? { name: '유비', picture: '22.jpg' } : null, + }); + } + if (operation === 'battle.getSimulatorContext') return response(simulatorOptions); + if (operation === 'general.me') return response(fixture.hasGeneral ? generalMe : null); + if (operation === 'battle.getGeneralList') { + return response({ + myNationId: 1, + myGeneralId: 7, + nations: [{ id: 1, name: '촉', color: '#8fbc8f' }], + generalsByNation: { 1: [{ id: 7, name: '유비', npcState: 0 }] }, + }); + } + if (operation === 'battle.getGeneralDetail') return response(importedGeneral); + if (operation === 'battle.simulate') { + if (fixture.failNextSimulation) { + fixture.failNextSimulation = false; + return errorResponse(operation, '시뮬레이터 입력 오류'); + } + if (fixture.queueFirst) { + return response({ status: 'queued', jobId: 'job-playwright' }); + } + return response({ status: 'completed', jobId: 'job-playwright', payload: simulationResult }); + } + if (operation === 'battle.getSimulation') { + fixture.pollingCount += 1; + if (fixture.pollingCount === 1) { + return response({ status: 'queued', jobId: 'job-playwright' }); + } + return response({ + status: 'completed', + jobId: 'job-playwright', + payload: simulationResult, + }); + } + return errorResponse(operation, `Unhandled battle simulator fixture operation: ${operation}`); + }); + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify(results), + }); + }); +}; + +const gotoSimulator = async (page: Page) => { + await page.goto('battle-simulator'); + await expect(page.getByRole('heading', { name: '전투 시뮬레이터' })).toBeVisible(); + await expect(page.getByLabel('시뮬레이터 데이터 안내')).toBeVisible(); + await expect(page.getByText('출병자 설정')).toBeVisible(); +}; + +test('operates independent/game presets, imports my general, and renders battle logs', async ({ page }) => { + const fixture: Fixture = { hasGeneral: true, queueFirst: true, pollingCount: 0, requests: [] }; + await installApi(page, fixture); + await page.setViewportSize({ width: 1280, height: 900 }); + await gotoSimulator(page); + + const notice = page.getByLabel('시뮬레이터 데이터 안내'); + const noticeRect = await notice.boundingBox(); + expect(noticeRect?.width).toBeGreaterThan(900); + expect(await notice.evaluate((element) => getComputedStyle(element).display)).toBe('flex'); + + await page.getByRole('button', { name: '독립 기본값' }).click(); + await expect(page.getByLabel('연도', { exact: true })).toHaveValue('190'); + await expect(page.getByLabel('월')).toHaveValue('1'); + + await page.getByRole('button', { name: '현재 게임 환경 적용' }).click(); + await expect(page.getByLabel('연도', { exact: true })).toHaveValue('205'); + await expect(page.getByLabel('월')).toHaveValue('8'); + + await page.getByRole('button', { name: '내 장수를 출병자로' }).click(); + await expect(page.getByLabel('이름').first()).toHaveValue('유비'); + await expect(page.getByLabel('병사').first()).toHaveValue('4321'); + + const battleButton = page.getByRole('button', { name: '전투', exact: true }); + await battleButton.hover(); + expect(await battleButton.evaluate((element) => getComputedStyle(element).cursor)).toBe('pointer'); + await page.getByLabel('시드').fill('playwright-fixed-seed'); + await battleButton.click(); + + await expect(page.getByText('유비가 모의전에서 승리했습니다.')).toBeVisible(); + await expect(page.getByText('5', { exact: true })).toBeVisible(); + expect(fixture.pollingCount).toBe(2); + expect(fixture.requests).toContain('battle.getSimulation'); + + if (artifactRoot) { + await page.screenshot({ + path: resolve(artifactRoot, 'battle-simulator-core-desktop.png'), + fullPage: true, + animations: 'disabled', + }); + } +}); + +test('keeps simulation available without a game general and preserves input after an API error', async ({ page }) => { + const fixture: Fixture = { + hasGeneral: false, + failNextSimulation: true, + pollingCount: 0, + requests: [], + }; + await installApi(page, fixture); + await page.setViewportSize({ width: 500, height: 900 }); + await gotoSimulator(page); + + await expect(page).toHaveURL(/battle-simulator/); + await expect(page.getByRole('button', { name: '내 장수를 출병자로' })).toBeDisabled(); + await expect(page.getByRole('button', { name: '서버에서 가져오기' }).first()).toBeDisabled(); + + await page.getByLabel('시드').fill('keep-this-seed'); + await page.getByRole('button', { name: '전투', exact: true }).click(); + await expect(page.getByText('시뮬레이터 입력 오류')).toBeVisible(); + await expect(page.getByLabel('시드')).toHaveValue('keep-this-seed'); + + await page.getByRole('button', { name: '전투', exact: true }).click(); + await expect(page.getByText('유비가 모의전에서 승리했습니다.')).toBeVisible(); + await expect(page.getByText('시뮬레이터 입력 오류')).toHaveCount(0); + + const notice = page.getByLabel('시뮬레이터 데이터 안내'); + expect(await notice.evaluate((element) => getComputedStyle(element).flexDirection)).toBe('column'); + expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true); + + if (artifactRoot) { + await page.screenshot({ + path: resolve(artifactRoot, 'battle-simulator-core-mobile.png'), + fullPage: true, + animations: 'disabled', + }); + } +}); diff --git a/app/game-frontend/e2e/battleSimulatorRef.spec.ts b/app/game-frontend/e2e/battleSimulatorRef.spec.ts new file mode 100644 index 0000000..b11b48a --- /dev/null +++ b/app/game-frontend/e2e/battleSimulatorRef.spec.ts @@ -0,0 +1,73 @@ +import { createHash } from 'node:crypto'; +import { readFile } from 'node:fs/promises'; +import { resolve } from 'node:path'; + +import { expect, test } from '@playwright/test'; + +const refBaseUrl = process.env.REF_BATTLE_SIM_URL; +const refPasswordFile = process.env.REF_USER_PASSWORD_FILE; +const refUsername = process.env.REF_USER_ID ?? 'refuser1'; +const artifactRoot = process.env.BATTLE_SIM_ARTIFACT_DIR; +const refTest = refBaseUrl && refPasswordFile ? test : test.skip; + +refTest('runs the legacy simulator in the same Chromium and captures its rendered contract', async ({ page }) => { + test.setTimeout(120_000); + if (!refBaseUrl || !refPasswordFile) { + throw new Error('REF_BATTLE_SIM_URL and REF_USER_PASSWORD_FILE are required'); + } + const password = (await readFile(refPasswordFile, 'utf8')).trim(); + await page.setViewportSize({ width: 1280, height: 900 }); + await page.goto(refBaseUrl, { waitUntil: 'networkidle' }); + await page.locator('#username').fill(refUsername); + await page.locator('#password').fill(password); + const globalSalt = await page.locator('#global_salt').inputValue(); + const passwordHash = createHash('sha512') + .update(globalSalt + password + globalSalt) + .digest('hex'); + const loginResponse = await page + .context() + .request.post(new URL('api.php?path=Login/LoginByID', refBaseUrl).toString(), { + data: { username: refUsername, password: passwordHash }, + }); + expect(loginResponse.status()).toBe(200); + await expect(loginResponse.json()).resolves.toMatchObject({ result: true }); + + await page.goto(new URL('hwe/battle_simulator.php', refBaseUrl).toString(), { + waitUntil: 'networkidle', + }); + const battleButton = page.locator('.btn-begin_battle'); + await expect(battleButton).toBeVisible(); + const container = page.locator('#container'); + const rect = await container.boundingBox(); + expect(rect?.width).toBeGreaterThanOrEqual(995); + expect(rect?.width).toBeLessThanOrEqual(1005); + + // A login with no game general leaves the legacy nation selects without a + // selected option. Choose the first legal independent value before running. + await page.locator('.form_nation_type').evaluateAll((elements) => { + for (const element of elements) { + const select = element as HTMLSelectElement; + select.selectedIndex = 0; + select.dispatchEvent(new Event('change', { bubbles: true })); + } + }); + await expect(page.locator('.form_nation_type').first()).not.toHaveValue(''); + + await battleButton.hover(); + expect(await battleButton.evaluate((element) => getComputedStyle(element).cursor)).toBe('pointer'); + const simulationResponse = page.waitForResponse( + (response) => response.url().includes('/j_simulate_battle.php') && response.status() === 200, + { timeout: 90_000 } + ); + await battleButton.click(); + await simulationResponse; + await expect(page.locator('#generalBattleResultLog')).not.toBeEmpty(); + + if (artifactRoot) { + await page.screenshot({ + path: resolve(artifactRoot, 'battle-simulator-ref-desktop.png'), + fullPage: true, + animations: 'disabled', + }); + } +}); diff --git a/app/game-frontend/e2e/playwright.config.mjs b/app/game-frontend/e2e/playwright.config.mjs index 94135ac..5ef6863 100644 --- a/app/game-frontend/e2e/playwright.config.mjs +++ b/app/game-frontend/e2e/playwright.config.mjs @@ -16,6 +16,8 @@ export default defineConfig({ 'nationOffices.spec.ts', 'nationGeneralSecret.spec.ts', 'npcPolicy.spec.ts', + 'battleSimulator.spec.ts', + 'battleSimulatorRef.spec.ts', ], fullyParallel: false, workers: 1, diff --git a/app/game-frontend/package.json b/app/game-frontend/package.json index a60d1d3..5d3a6bd 100644 --- a/app/game-frontend/package.json +++ b/app/game-frontend/package.json @@ -11,6 +11,7 @@ "test:e2e:nation-offices": "playwright test nationOffices.spec.ts --config e2e/playwright.config.mjs", "test:e2e:npc-policy": "playwright test npcPolicy.spec.ts --config e2e/playwright.config.mjs", "test:e2e:board": "playwright test board.spec.ts --config e2e/playwright.config.mjs", + "test:e2e:battle-simulator": "playwright test battleSimulator.spec.ts --config e2e/playwright.config.mjs", "lint": "eslint .", "lint:fix": "eslint . --fix", "test": "node -e \"console.log('test not configured')\"", diff --git a/app/game-frontend/src/components/battle/BattleGeneralCard.vue b/app/game-frontend/src/components/battle/BattleGeneralCard.vue index 8f60d54..7a84f23 100644 --- a/app/game-frontend/src/components/battle/BattleGeneralCard.vue +++ b/app/game-frontend/src/components/battle/BattleGeneralCard.vue @@ -7,6 +7,7 @@ interface Props { options: BattleSimOptions; mode: 'attacker' | 'defender'; title: string; + canImportServer: boolean; } const props = defineProps(); @@ -59,7 +60,19 @@ const officerLevelOptions = [
No {{ general.no }}
- + @@ -187,21 +200,11 @@ const officerLevelOptions = [
@@ -391,6 +379,11 @@ const officerLevelOptions = [ color: #f0b6b6; } +.action:disabled { + cursor: not-allowed; + opacity: 0.45; +} + .form-block { display: flex; flex-direction: column; diff --git a/app/game-frontend/src/router/index.ts b/app/game-frontend/src/router/index.ts index 63d0a16..c4dd81d 100644 --- a/app/game-frontend/src/router/index.ts +++ b/app/game-frontend/src/router/index.ts @@ -197,7 +197,6 @@ const routes = [ component: BattleSimulatorView, meta: { requiresAuth: true, - requiresGeneral: true, }, }, { diff --git a/app/game-frontend/src/views/BattleSimulatorView.vue b/app/game-frontend/src/views/BattleSimulatorView.vue index 9b6dec7..e8ced0d 100644 --- a/app/game-frontend/src/views/BattleSimulatorView.vue +++ b/app/game-frontend/src/views/BattleSimulatorView.vue @@ -26,6 +26,7 @@ type BattleExport = { type ExportedInfo = { objType: 'general'; data: GeneralExport } | { objType: 'battle'; data: BattleExport }; type GeneralListResponse = Awaited>; +type GeneralMeResponse = Awaited>; const loading = ref(true); const error = ref(null); @@ -72,6 +73,7 @@ const importTarget = ref(null); const generalList = ref(null); const generalListLoading = ref(false); const selectedGeneralId = ref(null); +const gameDefaults = ref(null); let generalIdSeed = 0; @@ -250,6 +252,7 @@ const initializeDefaults = async () => { try { const [context, me] = await Promise.all([trpc.battle.getSimulatorContext.query(), trpc.general.me.query()]); options.value = context; + gameDefaults.value = me; year.value = context.world.currentYear; month.value = context.world.currentMonth; repeatCnt.value = 1; @@ -283,6 +286,47 @@ const initializeDefaults = async () => { } }; +const hasGameGeneral = computed(() => !!gameDefaults.value?.general?.id); + +const applyGameEnvironment = () => { + if (!options.value) { + return; + } + const me = gameDefaults.value; + const nationTypeDefault = options.value.nationTypes[0]?.key ?? 'che_중립'; + year.value = options.value.world.currentYear; + month.value = options.value.world.currentMonth; + attackerNation.type = me?.nation?.typeCode ?? nationTypeDefault; + defenderNation.type = attackerNation.type; + attackerNation.level = me?.nation?.level ?? 0; + defenderNation.level = attackerNation.level; + attackerNation.tech = me?.nation?.tech ? Math.floor(me.nation.tech / 1000) : 1; + defenderNation.tech = attackerNation.tech; + attackerCity.level = me?.city?.level ?? 5; + defenderCity.level = attackerCity.level; + defenderCity.def = me?.city?.defence ?? 1000; + defenderCity.wall = me?.city?.wall ?? 1000; + attackerNation.isCapital = !!me?.city && me.nation?.capitalCityId === me.city.id; + defenderNation.isCapital = attackerNation.isCapital; + error.value = null; +}; + +const applyIndependentEnvironment = () => { + if (!options.value) { + return; + } + const nationTypeDefault = options.value.nationTypes[0]?.key ?? 'che_중립'; + year.value = options.value.world.startYear; + month.value = 1; + seed.value = ''; + repeatCnt.value = 1; + Object.assign(attackerNation, { type: nationTypeDefault, tech: 1, level: 0, isCapital: false }); + Object.assign(defenderNation, { type: nationTypeDefault, tech: 1, level: 0, isCapital: false }); + attackerCity.level = 5; + Object.assign(defenderCity, { level: 5, def: 1000, wall: 1000 }); + error.value = null; +}; + onMounted(() => { void initializeDefaults(); }); @@ -536,13 +580,19 @@ const runSimulation = async (action: BattleSimRequestPayload['action']) => { } isSimulating.value = true; + error.value = null; + if (action === 'battle') { + battleResult.value = null; + } statusMessage.value = action === 'battle' ? '전투를 진행 중입니다.' : '수비자 순서를 계산 중입니다.'; try { const payload = buildBattlePayload(action); const response = await trpc.battle.simulate.mutate(payload); const result = - 'payload' in response && response.payload ? response.payload : await waitForSimulationResult(response.jobId); + 'payload' in response && response.payload + ? response.payload + : await waitForSimulationResult(response.jobId); if (!result.result) { error.value = result.reason || 'battle_failed'; @@ -786,6 +836,10 @@ const loadGeneralList = async () => { }; const openImportModal = async (target: GeneralDraft) => { + if (!hasGameGeneral.value) { + error.value = '게임 장수를 보유한 사용자만 서버 장수 정보를 가져올 수 있습니다.'; + return; + } importTarget.value = target; importOpen.value = true; if (!generalList.value) { @@ -801,47 +855,62 @@ const closeImportModal = () => { importTarget.value = null; }; +const applyServerGeneral = async (target: GeneralDraft, generalId: number) => { + const response = await trpc.battle.getGeneralDetail.query({ generalId }); + applyGeneralExport(target, { + no: response.general.no, + name: response.general.name, + officerLevel: response.general.officer_level, + expLevel: response.general.explevel, + leadership: response.general.leadership, + strength: response.general.strength, + intel: response.general.intel, + horse: response.general.horse, + weapon: response.general.weapon, + book: response.general.book, + item: response.general.item, + injury: response.general.injury, + rice: response.general.rice, + personal: response.general.personal, + special2: response.general.special2, + crew: response.general.crew, + crewtype: response.general.crewtype, + atmos: response.general.atmos, + train: response.general.train, + dex1: response.general.dex1, + dex2: response.general.dex2, + dex3: response.general.dex3, + dex4: response.general.dex4, + dex5: response.general.dex5, + defenceTrain: response.general.defence_train, + warnum: response.general.warnum, + killnum: response.general.killnum, + killcrew: response.general.killcrew, + inheritBuff: createInheritBuff(), + }); + target.no = target === attackerGeneral.value ? 1 : resolveGeneralNo(response.general.no, target.id); +}; + +const applyMyGeneralToAttacker = async () => { + const generalId = gameDefaults.value?.general?.id; + if (!attackerGeneral.value || !generalId) { + error.value = '불러올 내 장수가 없습니다.'; + return; + } + try { + error.value = null; + await applyServerGeneral(attackerGeneral.value, generalId); + } catch (err) { + error.value = resolveErrorMessage(err); + } +}; + const confirmImport = async () => { if (!importTarget.value || !selectedGeneralId.value) { return; } try { - const response = await trpc.battle.getGeneralDetail.query({ generalId: selectedGeneralId.value }); - applyGeneralExport(importTarget.value, { - no: response.general.no, - name: response.general.name, - officerLevel: response.general.officer_level, - expLevel: response.general.explevel, - leadership: response.general.leadership, - strength: response.general.strength, - intel: response.general.intel, - horse: response.general.horse, - weapon: response.general.weapon, - book: response.general.book, - item: response.general.item, - injury: response.general.injury, - rice: response.general.rice, - personal: response.general.personal, - special2: response.general.special2, - crew: response.general.crew, - crewtype: response.general.crewtype, - atmos: response.general.atmos, - train: response.general.train, - dex1: response.general.dex1, - dex2: response.general.dex2, - dex3: response.general.dex3, - dex4: response.general.dex4, - dex5: response.general.dex5, - defenceTrain: response.general.defence_train, - warnum: response.general.warnum, - killnum: response.general.killnum, - killcrew: response.general.killcrew, - inheritBuff: createInheritBuff(), - }); - importTarget.value.no = - importTarget.value === attackerGeneral.value - ? 1 - : resolveGeneralNo(response.general.no, importTarget.value.id); + await applyServerGeneral(importTarget.value, selectedGeneralId.value); } catch (err) { error.value = resolveErrorMessage(err); } finally { @@ -882,19 +951,21 @@ const summaryRows = computed(() => { { label: '전투 페이즈', value: formatNumber(battleResult.value.phase) }, { label: '준 피해', - value: battleResult.value.minKilled !== battleResult.value.maxKilled - ? `${formatNumber(battleResult.value.killed)} (${formatNumber(battleResult.value.minKilled)} ~ ${formatNumber( - battleResult.value.maxKilled - )})` - : formatNumber(battleResult.value.killed), + value: + battleResult.value.minKilled !== battleResult.value.maxKilled + ? `${formatNumber(battleResult.value.killed)} (${formatNumber(battleResult.value.minKilled)} ~ ${formatNumber( + battleResult.value.maxKilled + )})` + : formatNumber(battleResult.value.killed), }, { label: '받은 피해', - value: battleResult.value.minDead !== battleResult.value.maxDead - ? `${formatNumber(battleResult.value.dead)} (${formatNumber(battleResult.value.minDead)} ~ ${formatNumber( - battleResult.value.maxDead - )})` - : formatNumber(battleResult.value.dead), + value: + battleResult.value.minDead !== battleResult.value.maxDead + ? `${formatNumber(battleResult.value.dead)} (${formatNumber(battleResult.value.minDead)} ~ ${formatNumber( + battleResult.value.maxDead + )})` + : formatNumber(battleResult.value.dead), }, { label: '출병자 군량 소모', value: formatNumber(battleResult.value.attackerRice) }, { label: '수비자 군량 소모', value: formatNumber(battleResult.value.defenderRice) }, @@ -937,6 +1008,32 @@ const shouldShowUI = computed(() => !loading.value && !!options.value);
+
+
+ 게임 상태와 분리된 모의 계산 +

+ 현재 연도·국가·도시는 시작값으로만 읽으며, 아래 편집과 전투 결과는 턴·DB·장수 상태를 변경하지 + 않습니다. +

+
+
+ + + +
+
+
{{ error }}
{{ statusMessage }}
@@ -1032,6 +1129,7 @@ const shouldShowUI = computed(() => !loading.value && !!options.value); :options="options!" mode="attacker" title="출병자 설정" + :can-import-server="hasGameGeneral" @import="openImportModal(attackerGeneral!)" @save="saveGeneral(attackerGeneral!)" @load="(payload) => handleGeneralLoad({ target: attackerGeneral!, file: payload.file })" @@ -1099,6 +1197,7 @@ const shouldShowUI = computed(() => !loading.value && !!options.value); :options="options!" mode="defender" :title="`수비자 설정 ${index + 1}`" + :can-import-server="hasGameGeneral" @import="openImportModal(defender)" @save="saveGeneral(defender)" @load="(payload) => handleGeneralLoad({ target: defender, file: payload.file })" @@ -1146,11 +1245,7 @@ const shouldShowUI = computed(() => !loading.value && !!options.value);