diff --git a/app/game-api/src/router/nation/endpoints/getGeneralList.ts b/app/game-api/src/router/nation/endpoints/getGeneralList.ts index 8223e9b..21ed1f6 100644 --- a/app/game-api/src/router/nation/endpoints/getGeneralList.ts +++ b/app/game-api/src/router/nation/endpoints/getGeneralList.ts @@ -2,7 +2,21 @@ import { TRPCError } from '@trpc/server'; import { authedProcedure } from '../../../trpc.js'; import { getMyGeneral } from '../../shared/general.js'; -import { assertNationAccess, loadTraitNames, mapGeneralList, resolveChiefStatMin } from '../shared.js'; +import { + assertNationAccess, + loadTraitNames, + mapGeneralList, + resolveChiefStatMin, + resolveNationPermission, +} from '../shared.js'; + +const experienceLevel = (experience: number): number => + Math.max( + 0, + Math.min(100, experience < 1000 ? Math.floor(experience / 100) : Math.floor(Math.sqrt(experience / 10))) + ); +const dedicationLevel = (dedication: number): number => + Math.max(0, Math.min(10, Math.ceil(Math.sqrt(dedication) / 10))); export const getGeneralList = authedProcedure.query(async ({ ctx }) => { const general = await getMyGeneral(ctx); @@ -62,7 +76,38 @@ export const getGeneralList = authedProcedure.query(async ({ ctx }) => { 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 accessRows = generalRows.length + ? await ctx.db.generalAccessLog.findMany({ + where: { generalId: { in: generalRows.map((entry) => entry.id) } }, + select: { generalId: true, refreshScoreTotal: true }, + }) + : []; + const accessByGeneral = new Map(accessRows.map((entry) => [entry.generalId, entry.refreshScoreTotal])); const nationTrait = (await loadTraitNames([nation.typeCode], 'nation')).get(nation.typeCode); + const permission = resolveNationPermission(general, nation.meta, true); + const visibleList = list.map((entry) => { + const { permission: _targetPermission, ...safeEntry } = entry; + if (permission >= 1) { + return { + ...safeEntry, + refreshScoreTotal: accessByGeneral.get(entry.id) ?? 0, + experienceLevel: experienceLevel(entry.experience), + dedicationLevel: dedicationLevel(entry.dedication), + }; + } + const { crew: _crew, experience: _experience, dedication: _dedication, ...visible } = safeEntry; + return { + ...visible, + refreshScoreTotal: accessByGeneral.get(entry.id) ?? 0, + officerLevel: entry.officerLevel >= 5 ? entry.officerLevel : Math.min(1, entry.officerLevel), + cityName: null, + troopName: null, + officerCity: 0, + officerCityName: null, + experienceLevel: experienceLevel(entry.experience), + dedicationLevel: dedicationLevel(entry.dedication), + }; + }); return { nation: { @@ -79,6 +124,7 @@ export const getGeneralList = authedProcedure.query(async ({ ctx }) => { capitalCityId: nation.capitalCityId ?? 0, }, chiefStatMin: resolveChiefStatMin(worldState), - generals: list, + viewer: { generalId: general.id, permission }, + generals: visibleList, }; }); diff --git a/app/game-api/src/router/nation/endpoints/getSecretGeneralList.ts b/app/game-api/src/router/nation/endpoints/getSecretGeneralList.ts new file mode 100644 index 0000000..b72977f --- /dev/null +++ b/app/game-api/src/router/nation/endpoints/getSecretGeneralList.ts @@ -0,0 +1,141 @@ +import { TRPCError } from '@trpc/server'; + +import { asRecord } from '@sammo-ts/common'; + +import { authedProcedure } from '../../../trpc.js'; +import { getMyGeneral } from '../../shared/general.js'; +import { assertNationAccess, resolveNationPermission } from '../shared.js'; + +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 woundedStat = (value: number, injury: number): number => + injury > 0 ? Math.floor((value * (100 - injury)) / 100) : value; +const experienceLevel = (experience: number): number => + Math.max( + 0, + Math.min(100, experience < 1000 ? Math.floor(experience / 100) : Math.floor(Math.sqrt(experience / 10))) + ); +const leadershipBonus = (officerLevel: number, nationLevel: number): number => + officerLevel === 12 ? nationLevel * 2 : officerLevel >= 5 ? nationLevel : 0; +const defenceTrainText = (value: number): string => + value === 999 ? '×' : value >= 90 ? '☆' : value >= 80 ? '◎' : value >= 60 ? '○' : '△'; + +export const getSecretGeneralList = authedProcedure.query(async ({ ctx }) => { + 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, meta: true }, + }); + if (!nation) throw new TRPCError({ code: 'NOT_FOUND', message: 'Nation not found' }); + const permission = resolveNationPermission(me, nation.meta, true); + if (permission < 1) { + throw new TRPCError({ + code: 'FORBIDDEN', + message: '권한이 부족합니다. 수뇌부가 아니거나 사관년도가 부족합니다.', + }); + } + + const [cities, troops, 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 turns = generalIds.length + ? await ctx.db.generalTurn.findMany({ + where: { generalId: { in: generalIds }, turnIdx: { lt: 5 } }, + select: { generalId: true, turnIdx: true, actionCode: true }, + orderBy: [{ generalId: 'asc' }, { turnIdx: 'asc' }], + }) + : []; + const cityNames = new Map(cities.map((city) => [city.id, city.name])); + const troopNames = new Map(troops.map((troop) => [troop.troopLeaderId, troop.name])); + const turnMap = new Map(); + for (const turn of turns) { + const list = turnMap.get(turn.generalId) ?? []; + list[turn.turnIdx] = turn.actionCode; + turnMap.set(turn.generalId, list); + } + const generals = generalRows.map((general) => { + const meta = asRecord(general.meta); + const defenceTrain = readNumber(meta, ['defenceTrain', 'defence_train'], 80); + return { + id: general.id, + name: general.name, + npcState: general.npcState, + injury: general.injury, + stats: { + leadership: woundedStat(general.leadership, general.injury), + strength: woundedStat(general.strength, general.injury), + intelligence: woundedStat(general.intel, general.injury), + }, + leadershipBonus: leadershipBonus(general.officerLevel, nation.level), + experienceLevel: experienceLevel(general.experience), + troopId: general.troopId, + troopName: troopNames.get(general.troopId) ?? null, + gold: general.gold, + rice: general.rice, + cityId: general.cityId, + cityName: cityNames.get(general.cityId) ?? null, + defenceTrain, + defenceTrainText: defenceTrainText(defenceTrain), + crewTypeId: general.crewTypeId, + crew: general.crew, + train: general.train, + atmos: general.atmos, + killTurn: readNumber(meta, ['killturn', 'killTurn']), + turnTime: general.turnTime.toISOString(), + reservedCommands: general.npcState < 2 ? (turnMap.get(general.id) ?? []) : [], + }; + }); + const counted = generals.filter((general) => general.npcState !== 5); + const summary = counted.reduce( + (result, general) => { + result.gold += general.gold; + result.rice += general.rice; + result.crew += general.crew; + if (general.crew > 0) { + for (const threshold of [90, 80, 60] as const) { + if (general.train >= threshold && general.atmos >= threshold) { + result.readiness[threshold].crew += general.crew; + result.readiness[threshold].generals += 1; + } + } + } + return result; + }, + { + gold: 0, + rice: 0, + crew: 0, + readiness: { + 90: { crew: 0, generals: 0 }, + 80: { crew: 0, generals: 0 }, + 60: { crew: 0, generals: 0 }, + }, + } + ); + return { + nation: { id: nation.id, name: nation.name, color: nation.color, level: nation.level }, + viewer: { generalId: me.id, permission }, + summary: { + ...summary, + generalCount: counted.length, + averageGold: counted.length ? summary.gold / counted.length : 0, + averageRice: counted.length ? summary.rice / counted.length : 0, + }, + generals, + }; +}); diff --git a/app/game-api/src/router/nation/index.ts b/app/game-api/src/router/nation/index.ts index e810b96..04ff481 100644 --- a/app/game-api/src/router/nation/index.ts +++ b/app/game-api/src/router/nation/index.ts @@ -5,6 +5,7 @@ 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 { getSecretGeneralList } from './endpoints/getSecretGeneralList.js'; import { getGeneralLog } from './endpoints/getGeneralLog.js'; import { getNationInfo } from './endpoints/getNationInfo.js'; import { getPersonnelInfo } from './endpoints/getPersonnelInfo.js'; @@ -21,6 +22,7 @@ import { setSecretLimit } from './endpoints/setSecretLimit.js'; export const nationRouter = router({ getNationInfo, getGeneralList, + getSecretGeneralList, getCityOverview, getPersonnelInfo, getStratFinan, diff --git a/app/game-api/test/nationGeneralSecretRouter.test.ts b/app/game-api/test/nationGeneralSecretRouter.test.ts new file mode 100644 index 0000000..c1fce96 --- /dev/null +++ b/app/game-api/test/nationGeneralSecretRouter.test.ts @@ -0,0 +1,142 @@ +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:00Z'); +const general = (overrides: Partial = {}): GeneralRow => ({ + id: 1, + userId: 'u1', + name: '장수', + nationId: 1, + cityId: 1, + troopId: 0, + npcState: 0, + affinity: null, + bornYear: 180, + deadYear: 300, + picture: null, + imageServer: 0, + leadership: 70, + strength: 60, + intel: 50, + injury: 0, + experience: 900, + dedication: 100, + officerLevel: 1, + gold: 1000, + rice: 2000, + 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 token = (userId: string): GameSessionTokenPayload => ({ + version: 1, + profile: 'che:default', + issuedAt: now.toISOString(), + expiresAt: new Date(now.getTime() + 86400000).toISOString(), + sessionId: userId, + user: { id: userId, username: userId, displayName: userId, roles: [] }, + sanctions: {}, +}); +const fixture = (generals: GeneralRow[], userId = 'u1') => { + const db = { + general: { + findFirst: vi.fn(async ({ where }: { where: { userId: string } }) => + generals.find((g) => g.userId === where.userId) + ), + findMany: vi.fn(async ({ where }: { where: { nationId: number } }) => + generals.filter((g) => g.nationId === where.nationId) + ), + }, + nation: { + findUnique: vi.fn(async () => ({ + id: 1, + name: '위', + color: '#080', + level: 3, + typeCode: 'che_중립', + capitalCityId: 1, + meta: { secretlimit: 3 }, + })), + }, + city: { findMany: vi.fn(async () => [{ id: 1, name: '업' }]) }, + troop: { findMany: vi.fn(async () => [{ troopLeaderId: 2, name: '선봉대' }]) }, + worldState: { findFirst: vi.fn(async () => null) }, + generalTurn: { findMany: vi.fn(async () => [{ generalId: 1, turnIdx: 0, actionCode: '징병' }]) }, + generalAccessLog: { + findMany: vi.fn(async () => generals.map((g) => ({ generalId: g.id, refreshScoreTotal: g.id * 10 }))), + }, + }; + const redis = { get: vi.fn(async () => null), set: vi.fn(async () => null) } as unknown as RedisConnector['client']; + const context: GameApiContext = { + db: db as unknown as DatabaseClient, + redis, + turnDaemon: {} as GameApiContext['turnDaemon'], + battleSim: {} as GameApiContext['battleSim'], + profile: { id: 'che', scenario: 'default', name: 'che:default' }, + auth: token(userId), + uploadDir: 'uploads', + uploadPath: '/uploads', + uploadPublicUrl: null, + accessTokenStore: new RedisAccessTokenStore(redis, 'che:default'), + flushStore: new InMemoryFlushStore(), + gameTokenSecret: 'secret', + }; + return { caller: appRouter.createCaller(context), db }; +}; + +describe('nation general and secret office permissions', () => { + it('redacts ordinary-member details and denies the secret office', async () => { + const { caller } = fixture([general()]); + const result = await caller.nation.getGeneralList(); + expect(result.viewer).toEqual({ generalId: 1, permission: 0 }); + expect(result.generals[0]).toMatchObject({ + officerLevel: 1, + cityName: null, + troopName: null, + refreshScoreTotal: 10, + }); + expect(result.generals[0]).not.toHaveProperty('crew'); + await expect(caller.nation.getSecretGeneralList()).rejects.toMatchObject({ code: 'FORBIDDEN' }); + }); + it('uses the session-owned general and scopes secret rows to that nation', async () => { + const first = general(); + const actor = general({ id: 2, userId: 'u2', officerLevel: 5, meta: { belong: 1 } }); + const ally = general({ id: 3, userId: 'u3', gold: 3000, crew: 200, train: 80, atmos: 80 }); + const foreign = general({ id: 4, userId: 'u4', nationId: 2, gold: 99999 }); + const { caller, db } = fixture([first, actor, ally, foreign], 'u2'); + const result = await caller.nation.getSecretGeneralList(); + expect(result.viewer).toEqual({ generalId: 2, permission: 2 }); + expect(result.generals.map((g) => g.id)).toEqual([1, 2, 3]); + expect(result.summary).toMatchObject({ gold: 5000, crew: 800, generalCount: 3 }); + expect(db.general.findFirst).toHaveBeenCalledWith({ where: { userId: 'u2' } }); + expect(db.general.findMany).toHaveBeenCalledWith(expect.objectContaining({ where: { nationId: 1 } })); + }); + it('honors general penalties after a user switch', async () => { + const penalized = general({ officerLevel: 5, penalty: { noChief: true } }); + const { caller } = fixture([penalized]); + await expect(caller.nation.getSecretGeneralList()).rejects.toMatchObject({ code: 'FORBIDDEN' }); + }); +}); diff --git a/app/game-frontend/e2e/nationGeneralSecret.spec.ts b/app/game-frontend/e2e/nationGeneralSecret.spec.ts new file mode 100644 index 0000000..39a8f5a --- /dev/null +++ b/app/game-frontend/e2e/nationGeneralSecret.spec.ts @@ -0,0 +1,150 @@ +import { expect, test, type Page, type Route } from '@playwright/test'; + +const response = (data: unknown) => ({ result: { data } }); +const operations = (route: Route) => + decodeURIComponent(new URL(route.request().url()).pathname.split('/trpc/')[1] ?? '').split(','); +const general = { + id: 1, + name: '테스트장수', + npcState: 0, + officerLevel: 1, + cityId: 1, + cityName: null, + troopId: 0, + troopName: null, + officerCity: 0, + officerCityName: null, + stats: { leadership: 70, strength: 60, intelligence: 50 }, + experienceLevel: 9, + dedicationLevel: 1, + injury: 0, + gold: 1000, + rice: 2000, + personality: null, + specialDomestic: null, + specialWar: null, + belong: 1, + refreshScoreTotal: 10, + permission: 'normal', +}; +const install = async (page: Page, secretAllowed = true) => { + await page.addInitScript(() => { + localStorage.setItem('sammo-game-token', 'ga_general'); + localStorage.setItem('sammo-game-profile', 'che:default'); + }); + await page.route('**/che/api/trpc/**', async (route) => { + const results = operations(route).map((operation) => { + if (operation === 'lobby.info') return response({ myGeneral: { id: 1, name: '테스트장수' } }); + if (operation === 'join.getConfig') return response({}); + if (operation === 'nation.getGeneralList') + return response({ + nation: { id: 1, name: '위', color: '#008000', level: 3 }, + viewer: { generalId: 1, permission: 0 }, + generals: [general], + }); + if (operation === 'nation.getSecretGeneralList') { + if (!secretAllowed) + return { + error: { + message: '권한이 부족합니다.', + code: -32000, + data: { code: 'FORBIDDEN', httpStatus: 403, path: operation }, + }, + }; + return response({ + nation: { id: 1, name: '위', color: '#008000', level: 3 }, + viewer: { generalId: 1, permission: 1 }, + summary: { + gold: 1000, + rice: 2000, + crew: 300, + generalCount: 1, + averageGold: 1000, + averageRice: 2000, + readiness: { + 90: { crew: 300, generals: 1 }, + 80: { crew: 300, generals: 1 }, + 60: { crew: 300, generals: 1 }, + }, + }, + generals: [ + { + id: 1, + name: '테스트장수', + npcState: 0, + injury: 0, + stats: { leadership: 70, strength: 60, intelligence: 50 }, + leadershipBonus: 0, + experienceLevel: 9, + troopId: 0, + troopName: null, + gold: 1000, + rice: 2000, + cityId: 1, + cityName: '업', + defenceTrain: 90, + defenceTrainText: '☆', + crewTypeId: 1, + crew: 300, + train: 90, + atmos: 90, + killTurn: 7, + turnTime: '2026-01-01T01:02:00.000Z', + reservedCommands: ['징병', '훈련'], + }, + ], + }); + } + return { error: { message: `unhandled ${operation}`, data: { code: 'BAD_REQUEST' } } }; + }); + await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(results) }); + }); +}; + +test('nation generals keeps the 1000px legacy grid and redacted member columns', async ({ page }) => { + await install(page); + await page.setViewportSize({ width: 1200, height: 900 }); + await page.goto('nation/generals'); + await expect(page.locator('#nation-general-list')).toContainText('테스트장수'); + await expect(page.locator('#nation-general-list')).toContainText('?'); + const computed = await page.locator('.general-page').evaluate((element) => { + const rect = element.getBoundingClientRect(); + const style = getComputedStyle(element); + return { x: rect.x, width: rect.width, fontSize: style.fontSize, fontFamily: style.fontFamily }; + }); + expect(computed).toMatchObject({ x: 100, width: 1000, fontSize: '16px' }); + expect(computed.fontFamily).toContain('Times New Roman'); + expect(await page.locator('#nation-general-list').evaluate((el) => getComputedStyle(el).borderCollapse)).toBe( + 'separate' + ); + expect((await page.locator('#nation-general-list').boundingBox())?.width).toBe(1030); + expect((await page.locator('#nation-general-list tbody tr').boundingBox())?.height).toBe(66); +}); + +test('both pages preserve the legacy 1000px overflow contract at 500px', async ({ page }) => { + await install(page); + await page.setViewportSize({ width: 500, height: 900 }); + for (const path of ['nation/generals', 'nation/secret']) { + await page.goto(path); + await expect( + page.locator(path.endsWith('secret') ? '#secret-general-list' : '#nation-general-list') + ).toBeVisible(); + expect(await page.locator('main').evaluate((el) => el.getBoundingClientRect().width)).toBe(1000); + expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeGreaterThanOrEqual(1000); + } +}); + +test('secret office renders summary, turns, and the forbidden error flow', async ({ page }) => { + await install(page); + await page.setViewportSize({ width: 1200, height: 900 }); + await page.goto('nation/secret'); + await expect(page.locator('.summary')).toContainText('전체 금'); + await expect(page.locator('#secret-general-list')).toContainText('1 : 징병'); + expect(await page.locator('.secret-page').evaluate((el) => el.getBoundingClientRect().width)).toBe(1000); + + await page.unroute('**/che/api/trpc/**'); + await install(page, false); + await page.goto('nation/secret'); + await expect(page.getByRole('alert')).toContainText('권한이 부족합니다.'); + await expect(page.locator('#secret-general-list')).toHaveCount(0); +}); diff --git a/app/game-frontend/e2e/playwright.config.mjs b/app/game-frontend/e2e/playwright.config.mjs index ddee57a..273abd6 100644 --- a/app/game-frontend/e2e/playwright.config.mjs +++ b/app/game-frontend/e2e/playwright.config.mjs @@ -8,7 +8,13 @@ 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', + 'nationOffices.spec.ts', + 'nationGeneralSecret.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..651dd13 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'; @@ -148,6 +149,12 @@ const routes = [ requiresGeneral: true, }, }, + { + path: '/nation/secret', + name: 'nation-secret', + component: NationSecretView, + meta: { requiresAuth: true, requiresGeneral: true }, + }, { path: '/nation/personnel', name: 'nation-personnel', diff --git a/app/game-frontend/src/views/MainView.vue b/app/game-frontend/src/views/MainView.vue index c6e139c..258d795 100644 --- a/app/game-frontend/src/views/MainView.vue +++ b/app/game-frontend/src/views/MainView.vue @@ -104,6 +104,10 @@ watch( 중원 정보 현재 도시 세력 장수 + 암행부 + 암행부 인사부 부대 편성 내무부 diff --git a/app/game-frontend/src/views/NationGeneralsView.vue b/app/game-frontend/src/views/NationGeneralsView.vue index 763b854..347d0b7 100644 --- a/app/game-frontend/src/views/NationGeneralsView.vue +++ b/app/game-frontend/src/views/NationGeneralsView.vue @@ -1,349 +1,226 @@ diff --git a/app/game-frontend/src/views/NationSecretView.vue b/app/game-frontend/src/views/NationSecretView.vue new file mode 100644 index 0000000..aeb8c03 --- /dev/null +++ b/app/game-frontend/src/views/NationSecretView.vue @@ -0,0 +1,210 @@ + + + + + diff --git a/tools/frontend-legacy-parity/reference-general-lists.mjs b/tools/frontend-legacy-parity/reference-general-lists.mjs new file mode 100644 index 0000000..d0fcc2c --- /dev/null +++ b/tools/frontend-legacy-parity/reference-general-lists.mjs @@ -0,0 +1,91 @@ +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_GENERAL_URL ?? 'http://127.0.0.1:3400/sam/'; +const username = process.env.REF_GENERAL_USER ?? 'refuser1'; +const passwordFile = process.env.REF_GENERAL_PASSWORD_FILE; +const artifactRoot = resolve(process.env.REF_GENERAL_ARTIFACT_DIR ?? 'test-results/reference-general-lists'); +if (!passwordFile) throw new Error('REF_GENERAL_PASSWORD_FILE is required.'); +const password = (await readFile(passwordFile, 'utf8')).trim(); +await mkdir(artifactRoot, { recursive: true }); + +const measure = async (page, selectors) => + page.evaluate((items) => { + const result = {}; + for (const [name, selector] of Object.entries(items)) { + const element = document.querySelector(selector); + if (!element) { + result[name] = null; + continue; + } + const rect = element.getBoundingClientRect(); + const style = getComputedStyle(element); + result[name] = { + rect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height }, + style: { + fontFamily: style.fontFamily, + fontSize: style.fontSize, + borderCollapse: style.borderCollapse, + backgroundImage: style.backgroundImage, + color: style.color, + }, + }; + } + return { elements: result, documentWidth: document.documentElement.scrollWidth }; + }, selectors); + +const browser = await chromium.launch({ headless: true }); +try { + const context = await browser.newContext({ + viewport: { width: 1200, height: 900 }, + deviceScaleFactor: 1, + locale: 'ko-KR', + colorScheme: 'dark', + }); + const page = await context.newPage(); + await page.goto(baseUrl, { waitUntil: 'networkidle' }); + const salt = await page.locator('#global_salt').inputValue(); + const passwordHash = createHash('sha512') + .update(salt + password + salt) + .digest('hex'); + const login = await context.request.post(new URL('api.php?path=Login/LoginByID', baseUrl).toString(), { + data: { username, password: passwordHash }, + }); + const loginResult = await login.json(); + if (!login.ok() || loginResult.result !== true) throw new Error('Reference login failed.'); + + const output = {}; + for (const [name, path, selectors] of [ + [ + 'generals', + 'hwe/b_myGenInfo.php', + { + body: 'body', + title: 'body > table:first-of-type', + list: 'body > table:nth-of-type(2)', + firstRow: 'body > table:nth-of-type(2) tr:nth-child(2)', + }, + ], + [ + 'secret', + 'hwe/b_genList.php', + { + body: 'body', + title: 'body > table:first-of-type', + summary: 'body > table:nth-of-type(2)', + list: '#general_list', + firstRow: '#general_list tbody tr:first-child', + }, + ], + ]) { + await page.goto(new URL(path, baseUrl).toString(), { waitUntil: 'networkidle' }); + output[name] = await measure(page, selectors); + await page.screenshot({ path: resolve(artifactRoot, `ref-${name}.png`), fullPage: true }); + } + await writeFile(resolve(artifactRoot, 'computed-dom.json'), `${JSON.stringify(output, null, 2)}\n`); + process.stdout.write(`${JSON.stringify({ ok: true, artifactRoot, output })}\n`); +} finally { + await browser.close(); +}