Add nation general and secret office parity
This commit is contained in:
@@ -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,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -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<string, unknown>, 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<number, string[]>();
|
||||
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,
|
||||
};
|
||||
});
|
||||
@@ -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,
|
||||
|
||||
@@ -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> = {}): 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' });
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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,
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -104,6 +104,10 @@ watch(
|
||||
<RouterLink class="ghost" to="/global-info">중원 정보</RouterLink>
|
||||
<RouterLink class="ghost" to="/current-city">현재 도시</RouterLink>
|
||||
<RouterLink class="ghost" to="/nation/generals">세력 장수</RouterLink>
|
||||
<RouterLink v-if="(boardAccess?.permission ?? -1) >= 1" class="ghost" to="/nation/secret"
|
||||
>암행부</RouterLink
|
||||
>
|
||||
<span v-else class="ghost disabled" aria-disabled="true">암행부</span>
|
||||
<RouterLink class="ghost" to="/nation/personnel">인사부</RouterLink>
|
||||
<RouterLink class="ghost" to="/troop">부대 편성</RouterLink>
|
||||
<RouterLink class="ghost" to="/nation/finance">내무부</RouterLink>
|
||||
|
||||
@@ -1,349 +1,226 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
import PanelCard from '../components/ui/PanelCard.vue';
|
||||
import SkeletonLines from '../components/ui/SkeletonLines.vue';
|
||||
import { trpc } from '../utils/trpc';
|
||||
import { formatOfficerLevelText } from '../utils/nationFormat';
|
||||
import { trpc } from '../utils/trpc';
|
||||
|
||||
type GeneralListResponse = Awaited<ReturnType<typeof trpc.nation.getGeneralList.query>>;
|
||||
|
||||
type GeneralEntry = GeneralListResponse['generals'][number];
|
||||
|
||||
type SortKey =
|
||||
| 1
|
||||
| 2
|
||||
| 3
|
||||
| 4
|
||||
| 5
|
||||
| 6
|
||||
| 7
|
||||
| 8
|
||||
| 9
|
||||
| 10
|
||||
| 11
|
||||
| 12
|
||||
| 13
|
||||
| 14
|
||||
| 15;
|
||||
|
||||
const sortOptions: Array<{ key: SortKey; label: string }> = [
|
||||
{ key: 1, label: '관직' },
|
||||
{ key: 2, label: '공헌' },
|
||||
{ key: 3, label: '경험' },
|
||||
{ key: 4, label: '통솔' },
|
||||
{ key: 5, label: '무력' },
|
||||
{ key: 6, label: '지력' },
|
||||
{ key: 7, label: '자금' },
|
||||
{ key: 8, label: '군량' },
|
||||
{ key: 9, label: '병사' },
|
||||
{ key: 10, label: '벌점' },
|
||||
{ key: 11, label: '성격' },
|
||||
{ key: 12, label: '내특' },
|
||||
{ key: 13, label: '전특' },
|
||||
{ key: 14, label: '사관' },
|
||||
{ key: 15, label: 'NPC' },
|
||||
];
|
||||
|
||||
type Result = Awaited<ReturnType<typeof trpc.nation.getGeneralList.query>>;
|
||||
type General = Result['generals'][number];
|
||||
type Sort = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15;
|
||||
const data = ref<Result | null>(null);
|
||||
const error = ref('');
|
||||
const loading = ref(false);
|
||||
const error = ref<string | null>(null);
|
||||
const data = ref<GeneralListResponse | null>(null);
|
||||
const sortKey = ref<SortKey>(1);
|
||||
const filterText = ref('');
|
||||
|
||||
const resolveErrorMessage = (value: unknown): string => {
|
||||
if (value instanceof Error) {
|
||||
return value.message;
|
||||
}
|
||||
if (typeof value === 'string') {
|
||||
return value;
|
||||
}
|
||||
return 'unknown_error';
|
||||
};
|
||||
|
||||
const loadGenerals = async () => {
|
||||
if (loading.value) {
|
||||
return;
|
||||
}
|
||||
const sort = ref<Sort>(1);
|
||||
const options = [
|
||||
'관직',
|
||||
'계급',
|
||||
'명성',
|
||||
'통솔',
|
||||
'무력',
|
||||
'지력',
|
||||
'자금',
|
||||
'군량',
|
||||
'병사',
|
||||
'벌점',
|
||||
'성격',
|
||||
'내특',
|
||||
'전특',
|
||||
'사관',
|
||||
'NPC',
|
||||
];
|
||||
const visibleCrew = (general: General): number | null => ('crew' in general ? general.crew : null);
|
||||
const load = async () => {
|
||||
loading.value = true;
|
||||
error.value = null;
|
||||
|
||||
error.value = '';
|
||||
try {
|
||||
data.value = await trpc.nation.getGeneralList.query();
|
||||
} catch (err) {
|
||||
error.value = resolveErrorMessage(err);
|
||||
} catch (cause) {
|
||||
error.value = cause instanceof Error ? cause.message : '세력 장수를 불러오지 못했습니다.';
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const sortGenerals = (list: GeneralEntry[]): GeneralEntry[] => {
|
||||
const key = sortKey.value;
|
||||
const sorted = [...list].sort((lhs, rhs) => {
|
||||
switch (key) {
|
||||
case 1:
|
||||
return rhs.officerLevel - lhs.officerLevel;
|
||||
case 2:
|
||||
return rhs.dedication - lhs.dedication;
|
||||
case 3:
|
||||
return rhs.experience - lhs.experience;
|
||||
case 4:
|
||||
return rhs.stats.leadership - lhs.stats.leadership;
|
||||
case 5:
|
||||
return rhs.stats.strength - lhs.stats.strength;
|
||||
case 6:
|
||||
return rhs.stats.intelligence - lhs.stats.intelligence;
|
||||
case 7:
|
||||
return rhs.gold - lhs.gold;
|
||||
case 8:
|
||||
return rhs.rice - lhs.rice;
|
||||
case 9:
|
||||
return rhs.crew - lhs.crew;
|
||||
case 10:
|
||||
return 0;
|
||||
case 11:
|
||||
return (lhs.personality?.name ?? '').localeCompare(rhs.personality?.name ?? '');
|
||||
case 12:
|
||||
return (lhs.specialDomestic?.name ?? '').localeCompare(rhs.specialDomestic?.name ?? '');
|
||||
case 13:
|
||||
return (lhs.specialWar?.name ?? '').localeCompare(rhs.specialWar?.name ?? '');
|
||||
case 14:
|
||||
return rhs.belong - lhs.belong;
|
||||
case 15:
|
||||
return rhs.npcState - lhs.npcState;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
});
|
||||
|
||||
if (key === 11 || key === 12 || key === 13) {
|
||||
return sorted;
|
||||
}
|
||||
|
||||
return sorted;
|
||||
};
|
||||
|
||||
const filteredGenerals = computed(() => {
|
||||
const list = data.value?.generals ?? [];
|
||||
const keyword = filterText.value.trim().toLowerCase();
|
||||
const filtered = keyword
|
||||
? list.filter((general) => {
|
||||
return (
|
||||
general.name.toLowerCase().includes(keyword) ||
|
||||
(general.cityName ?? '').toLowerCase().includes(keyword) ||
|
||||
(general.officerCityName ?? '').toLowerCase().includes(keyword)
|
||||
);
|
||||
})
|
||||
: list;
|
||||
|
||||
return sortGenerals(filtered);
|
||||
});
|
||||
|
||||
const nationLevel = computed(() => data.value?.nation.level ?? 0);
|
||||
|
||||
const formatSpecial = (general: GeneralEntry): string => {
|
||||
const domestic = general.specialDomestic?.name ?? '-';
|
||||
const war = general.specialWar?.name ?? '-';
|
||||
return `${domestic} / ${war}`;
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
void loadGenerals();
|
||||
});
|
||||
const generals = computed(() =>
|
||||
[...(data.value?.generals ?? [])].sort((a, b) => {
|
||||
if (sort.value === 1) return b.officerLevel - a.officerLevel || a.id - b.id;
|
||||
if (sort.value === 2) return b.dedicationLevel - a.dedicationLevel || a.id - b.id;
|
||||
if (sort.value === 3) return b.experienceLevel - a.experienceLevel || a.id - b.id;
|
||||
if (sort.value === 4) return b.stats.leadership - a.stats.leadership || a.id - b.id;
|
||||
if (sort.value === 5) return b.stats.strength - a.stats.strength || a.id - b.id;
|
||||
if (sort.value === 6) return b.stats.intelligence - a.stats.intelligence || a.id - b.id;
|
||||
if (sort.value === 7) return b.gold - a.gold || a.id - b.id;
|
||||
if (sort.value === 8) return b.rice - a.rice || a.id - b.id;
|
||||
if (sort.value === 9) return (visibleCrew(b) ?? -1) - (visibleCrew(a) ?? -1) || a.id - b.id;
|
||||
if (sort.value === 10) return b.refreshScoreTotal - a.refreshScoreTotal || a.id - b.id;
|
||||
if (sort.value === 11) return (a.personality?.name ?? '').localeCompare(b.personality?.name ?? '');
|
||||
if (sort.value === 12) return (a.specialDomestic?.name ?? '').localeCompare(b.specialDomestic?.name ?? '');
|
||||
if (sort.value === 13) return (a.specialWar?.name ?? '').localeCompare(b.specialWar?.name ?? '');
|
||||
if (sort.value === 14) return b.belong - a.belong || a.id - b.id;
|
||||
if (sort.value === 15) return b.npcState - a.npcState || a.id - b.id;
|
||||
return a.id - b.id;
|
||||
})
|
||||
);
|
||||
const special = (general: General) => `${general.specialDomestic?.name ?? '-'} / ${general.specialWar?.name ?? '-'}`;
|
||||
onMounted(load);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<main class="nation-page">
|
||||
<header class="page-header">
|
||||
<div>
|
||||
<h1 class="page-title">세력 장수</h1>
|
||||
<p class="page-subtitle">세력 내 장수 현황 및 정렬</p>
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<RouterLink class="ghost" to="/">메인</RouterLink>
|
||||
<RouterLink class="ghost" to="/nation/cities">세력 도시</RouterLink>
|
||||
<RouterLink class="ghost" to="/nation/personnel">인사부</RouterLink>
|
||||
<button class="ghost" @click="loadGenerals">새로고침</button>
|
||||
</div>
|
||||
<main class="general-page legacy-bg0">
|
||||
<header>
|
||||
<strong>세력 장수</strong>
|
||||
<span
|
||||
><RouterLink to="/">돌아가기</RouterLink>
|
||||
<button :disabled="loading" @click="load">새로고침</button></span
|
||||
>
|
||||
</header>
|
||||
|
||||
<div v-if="error" class="error">{{ error }}</div>
|
||||
|
||||
<PanelCard title="세력 장수 목록" subtitle="국가 소속 장수들을 확인합니다.">
|
||||
<template #actions>
|
||||
<div class="toolbar-actions">
|
||||
<select v-model.number="sortKey" class="select-input">
|
||||
<option v-for="option in sortOptions" :key="option.key" :value="option.key">
|
||||
{{ option.label }}
|
||||
</option>
|
||||
</select>
|
||||
<input v-model="filterText" class="filter-input" placeholder="이름/도시 검색" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div class="list-meta">총 {{ filteredGenerals.length }}명</div>
|
||||
|
||||
<SkeletonLines v-if="loading" :lines="6" />
|
||||
<div v-else class="table-scroll">
|
||||
<table class="nation-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>이름</th>
|
||||
<th>관직</th>
|
||||
<th>공헌</th>
|
||||
<th>경험</th>
|
||||
<th>통솔</th>
|
||||
<th>무력</th>
|
||||
<th>지력</th>
|
||||
<th>자금</th>
|
||||
<th>군량</th>
|
||||
<th>병사</th>
|
||||
<th>성격</th>
|
||||
<th>특기</th>
|
||||
<th>사관</th>
|
||||
<th>현재 도시</th>
|
||||
<th>관직 도시</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="general in filteredGenerals" :key="general.id">
|
||||
<td>
|
||||
<span v-if="general.npcState > 0" class="npc-tag">NPC</span>
|
||||
{{ general.name }}
|
||||
</td>
|
||||
<td>{{ formatOfficerLevelText(general.officerLevel, nationLevel) }}</td>
|
||||
<td>{{ general.dedication }}</td>
|
||||
<td>{{ general.experience }}</td>
|
||||
<td>{{ general.stats.leadership }}</td>
|
||||
<td>{{ general.stats.strength }}</td>
|
||||
<td>{{ general.stats.intelligence }}</td>
|
||||
<td>{{ general.gold }}</td>
|
||||
<td>{{ general.rice }}</td>
|
||||
<td>{{ general.crew }}</td>
|
||||
<td>{{ general.personality?.name ?? '-' }}</td>
|
||||
<td>{{ formatSpecial(general) }}</td>
|
||||
<td>{{ general.belong > 0 ? general.belong : '-' }}</td>
|
||||
<td>{{ general.cityName ?? '-' }}</td>
|
||||
<td>{{ general.officerCityName ?? '-' }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</PanelCard>
|
||||
<section class="sort">
|
||||
정렬순서 :
|
||||
<select v-model.number="sort" aria-label="세력 장수 정렬">
|
||||
<option v-for="(label, index) in options" :key="label" :value="index + 1">{{ label }}</option>
|
||||
</select>
|
||||
<button>정렬하기</button>
|
||||
<small v-if="data">열람 등급 {{ data.viewer.permission }}</small>
|
||||
</section>
|
||||
<p v-if="error" class="state error" role="alert">{{ error }}</p>
|
||||
<p v-else-if="loading" class="state">불러오는 중...</p>
|
||||
<div v-else class="scroll">
|
||||
<table id="nation-general-list">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>이 름</th>
|
||||
<th>관 직</th>
|
||||
<th>통무지</th>
|
||||
<th>명성/계급</th>
|
||||
<th>자금</th>
|
||||
<th>군량</th>
|
||||
<th>도시</th>
|
||||
<th>부대</th>
|
||||
<th>병사</th>
|
||||
<th>성격</th>
|
||||
<th>특기</th>
|
||||
<th>사관</th>
|
||||
<th>벌점</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="general in generals" :key="general.id">
|
||||
<td :class="`npc-${general.npcState}`">{{ general.name }}</td>
|
||||
<td>{{ formatOfficerLevelText(general.officerLevel, data?.nation.level) }}</td>
|
||||
<td>
|
||||
{{ general.stats.leadership }}∥{{ general.stats.strength }}∥{{ general.stats.intelligence }}
|
||||
</td>
|
||||
<td>
|
||||
Lv {{ general.experienceLevel }}<br />{{
|
||||
general.dedicationLevel ? `${11 - general.dedicationLevel}품관` : '무품관'
|
||||
}}
|
||||
</td>
|
||||
<td>{{ general.gold.toLocaleString() }}</td>
|
||||
<td>{{ general.rice.toLocaleString() }}</td>
|
||||
<td>{{ general.cityName ?? '?' }}</td>
|
||||
<td>{{ general.troopName ?? '?' }}</td>
|
||||
<td>{{ visibleCrew(general)?.toLocaleString() ?? '?' }}</td>
|
||||
<td :title="general.personality?.info ?? ''">{{ general.personality?.name ?? '-' }}</td>
|
||||
<td
|
||||
:title="
|
||||
[general.specialDomestic?.info, general.specialWar?.info].filter(Boolean).join('\n')
|
||||
"
|
||||
>
|
||||
{{ special(general) }}
|
||||
</td>
|
||||
<td>{{ general.belong }}</td>
|
||||
<td>{{ general.refreshScoreTotal }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<footer><RouterLink to="/">돌아가기</RouterLink></footer>
|
||||
</main>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.nation-page {
|
||||
.general-page {
|
||||
width: 1000px;
|
||||
min-height: 100vh;
|
||||
padding: 24px;
|
||||
margin: 8px auto 0;
|
||||
font:
|
||||
16px 'Times New Roman',
|
||||
serif;
|
||||
color: #fff;
|
||||
}
|
||||
header,
|
||||
.sort,
|
||||
footer,
|
||||
.state {
|
||||
position: relative;
|
||||
border: 1px solid #777;
|
||||
padding: 4px;
|
||||
text-align: center;
|
||||
}
|
||||
header {
|
||||
min-height: 39px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.page-header {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
border-bottom: 1px solid rgba(201, 164, 90, 0.4);
|
||||
padding-bottom: 12px;
|
||||
}
|
||||
|
||||
.page-title {
|
||||
font-size: 1.6rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.page-subtitle {
|
||||
font-size: 0.85rem;
|
||||
color: rgba(232, 221, 196, 0.7);
|
||||
}
|
||||
|
||||
.header-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.ghost {
|
||||
border: 1px solid rgba(201, 164, 90, 0.4);
|
||||
padding: 6px 12px;
|
||||
font-size: 0.8rem;
|
||||
cursor: pointer;
|
||||
text-decoration: none;
|
||||
color: inherit;
|
||||
background: rgba(16, 16, 16, 0.6);
|
||||
}
|
||||
|
||||
.error {
|
||||
color: #f5b7b1;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.toolbar-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.select-input {
|
||||
border: 1px solid rgba(201, 164, 90, 0.4);
|
||||
background: rgba(16, 16, 16, 0.8);
|
||||
color: rgba(232, 221, 196, 0.9);
|
||||
padding: 6px 8px;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.filter-input {
|
||||
border: 1px solid rgba(201, 164, 90, 0.4);
|
||||
background: rgba(16, 16, 16, 0.8);
|
||||
color: rgba(232, 221, 196, 0.9);
|
||||
padding: 6px 8px;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.list-meta {
|
||||
margin-bottom: 8px;
|
||||
font-size: 0.75rem;
|
||||
color: rgba(232, 221, 196, 0.6);
|
||||
}
|
||||
|
||||
.table-scroll {
|
||||
overflow-x: auto;
|
||||
max-height: 70vh;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.nation-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.nation-table th,
|
||||
.nation-table td {
|
||||
padding: 6px 8px;
|
||||
border-bottom: 1px solid rgba(201, 164, 90, 0.2);
|
||||
text-align: left;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.nation-table thead th {
|
||||
font-size: 0.7rem;
|
||||
color: rgba(232, 221, 196, 0.6);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
}
|
||||
|
||||
.npc-tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 0.6rem;
|
||||
padding: 2px 4px;
|
||||
}
|
||||
header span {
|
||||
position: absolute;
|
||||
right: 6px;
|
||||
}
|
||||
button,
|
||||
select {
|
||||
border: 1px solid #888;
|
||||
border-radius: 2px;
|
||||
background: #222;
|
||||
color: #fff;
|
||||
padding: 1px 6px;
|
||||
}
|
||||
.sort small {
|
||||
float: right;
|
||||
margin-right: 6px;
|
||||
border: 1px solid rgba(201, 164, 90, 0.4);
|
||||
color: rgba(232, 221, 196, 0.8);
|
||||
color: #ccc;
|
||||
}
|
||||
.scroll {
|
||||
width: 1030px;
|
||||
margin-left: -15px;
|
||||
min-height: calc(100vh - 112px);
|
||||
overflow: auto;
|
||||
}
|
||||
table {
|
||||
width: 1030px;
|
||||
min-width: 1030px;
|
||||
border-collapse: separate;
|
||||
table-layout: fixed;
|
||||
}
|
||||
th,
|
||||
td {
|
||||
border: 1px solid #777;
|
||||
padding: 3px;
|
||||
text-align: center;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
th {
|
||||
height: 30px;
|
||||
background: #14241b url('/image/game/back_green.jpg');
|
||||
font-weight: 400;
|
||||
}
|
||||
tbody tr {
|
||||
height: 66px;
|
||||
background: rgb(0 0 0 / 18%);
|
||||
}
|
||||
.npc-1 {
|
||||
color: cyan;
|
||||
}
|
||||
.npc-2,
|
||||
.npc-3,
|
||||
.npc-4,
|
||||
.npc-5 {
|
||||
color: #aaa;
|
||||
}
|
||||
.error {
|
||||
color: #ff7373;
|
||||
}
|
||||
@media (max-width: 1000px) {
|
||||
.general-page {
|
||||
margin: 8px 0 0;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
import { trpc } from '../utils/trpc';
|
||||
type Result = Awaited<ReturnType<typeof trpc.nation.getSecretGeneralList.query>>;
|
||||
type Sort = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
|
||||
const data = ref<Result | null>(null);
|
||||
const error = ref('');
|
||||
const loading = ref(false);
|
||||
const sort = ref<Sort>(7);
|
||||
const options = ['자금', '군량', '도시', '병종', '병사', '삭제턴', '턴', '부대'];
|
||||
const load = async () => {
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
data.value = await trpc.nation.getSecretGeneralList.query();
|
||||
} catch (cause) {
|
||||
error.value = cause instanceof Error ? cause.message : '암행부를 불러오지 못했습니다.';
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
const generals = computed(() =>
|
||||
[...(data.value?.generals ?? [])].sort((a, b) => {
|
||||
if (sort.value === 1) return b.gold - a.gold || a.id - b.id;
|
||||
if (sort.value === 2) return b.rice - a.rice || a.id - b.id;
|
||||
if (sort.value === 3) return a.cityId - b.cityId || a.id - b.id;
|
||||
if (sort.value === 4) return b.crewTypeId - a.crewTypeId || a.id - b.id;
|
||||
if (sort.value === 5) return b.crew - a.crew || a.id - b.id;
|
||||
if (sort.value === 6) return a.killTurn - b.killTurn || a.id - b.id;
|
||||
if (sort.value === 7) return a.turnTime.localeCompare(b.turnTime) || a.id - b.id;
|
||||
return b.troopId - a.troopId || a.id - b.id;
|
||||
})
|
||||
);
|
||||
onMounted(load);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<main class="secret-page">
|
||||
<table class="layout legacy-bg0 title">
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>암 행 부<br /><RouterLink to="/">창 닫기</RouterLink></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
정렬순서 :
|
||||
<select v-model.number="sort" aria-label="암행부 정렬">
|
||||
<option v-for="(label, index) in options" :key="label" :value="index + 1">
|
||||
{{ label }}
|
||||
</option>
|
||||
</select>
|
||||
<button>정렬하기</button> <button :disabled="loading" @click="load">새로고침</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p v-if="error" class="state error legacy-bg0" role="alert">{{ error }}</p>
|
||||
<p v-else-if="loading" class="state legacy-bg0">불러오는 중...</p>
|
||||
<template v-else-if="data">
|
||||
<table class="layout summary legacy-bg0">
|
||||
<tbody>
|
||||
<tr>
|
||||
<th>전체 금</th>
|
||||
<td>{{ data.summary.gold.toLocaleString() }}</td>
|
||||
<th>전체 쌀</th>
|
||||
<td>{{ data.summary.rice.toLocaleString() }}</td>
|
||||
<th>평균 금</th>
|
||||
<td>{{ data.summary.averageGold.toFixed(2) }}</td>
|
||||
<th>평균 쌀</th>
|
||||
<td>{{ data.summary.averageRice.toFixed(2) }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>전체 병력/장수</th>
|
||||
<td>{{ data.summary.crew.toLocaleString() }}/{{ data.summary.generalCount }}</td>
|
||||
<template v-for="level in [90, 80, 60] as const" :key="level"
|
||||
><th>훈사 {{ level }} 병력/장수</th>
|
||||
<td>
|
||||
{{ data.summary.readiness[level].crew.toLocaleString() }}/{{
|
||||
data.summary.readiness[level].generals
|
||||
}}
|
||||
</td></template
|
||||
>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<table id="secret-general-list" class="layout list legacy-bg0">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>이 름</th>
|
||||
<th>통무지</th>
|
||||
<th>부 대</th>
|
||||
<th>자 금</th>
|
||||
<th>군 량</th>
|
||||
<th>도시</th>
|
||||
<th>守</th>
|
||||
<th>병 종</th>
|
||||
<th>병 사</th>
|
||||
<th>훈련</th>
|
||||
<th>사기</th>
|
||||
<th class="commands">명 령</th>
|
||||
<th>삭턴</th>
|
||||
<th>턴</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="general in generals" :key="general.id">
|
||||
<td>{{ general.name }}<br />Lv {{ general.experienceLevel }}</td>
|
||||
<td>
|
||||
{{ general.stats.leadership }}∥{{ general.stats.strength }}∥{{ general.stats.intelligence }}
|
||||
</td>
|
||||
<td>{{ general.troopName ?? '-' }}</td>
|
||||
<td>{{ general.gold }}</td>
|
||||
<td>{{ general.rice }}</td>
|
||||
<td>{{ general.cityName ?? '-' }}</td>
|
||||
<td>{{ general.defenceTrainText }}</td>
|
||||
<td>{{ general.crewTypeId }}</td>
|
||||
<td>{{ general.crew }}</td>
|
||||
<td>{{ general.train }}</td>
|
||||
<td>{{ general.atmos }}</td>
|
||||
<td class="turns">
|
||||
<template v-if="general.npcState >= 2">NPC 장수</template
|
||||
><template v-else
|
||||
><div v-for="(command, index) in general.reservedCommands" :key="index">
|
||||
{{ index + 1 }} : {{ command }}
|
||||
</div></template
|
||||
>
|
||||
</td>
|
||||
<td>{{ general.killTurn }}</td>
|
||||
<td>{{ general.turnTime.slice(11, 16) }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</template>
|
||||
<table class="layout legacy-bg0 footer">
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><RouterLink to="/">창 닫기</RouterLink></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</main>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.secret-page {
|
||||
width: 1000px;
|
||||
margin: 8px auto 0;
|
||||
font:
|
||||
16px 'Times New Roman',
|
||||
serif;
|
||||
color: #fff;
|
||||
}
|
||||
.layout {
|
||||
width: 1000px;
|
||||
border-collapse: collapse;
|
||||
table-layout: fixed;
|
||||
}
|
||||
td,
|
||||
th,
|
||||
.state {
|
||||
border: 1px solid #777;
|
||||
padding: 3px;
|
||||
text-align: center;
|
||||
font-weight: 400;
|
||||
}
|
||||
button,
|
||||
select {
|
||||
border: 1px solid #888;
|
||||
border-radius: 2px;
|
||||
background: #222;
|
||||
color: #fff;
|
||||
padding: 1px 6px;
|
||||
}
|
||||
.summary {
|
||||
margin: 5px auto;
|
||||
}
|
||||
.summary th,
|
||||
.list th {
|
||||
background: #14241b url('/image/game/back_green.jpg');
|
||||
}
|
||||
.summary th {
|
||||
width: 120px;
|
||||
}
|
||||
.list {
|
||||
width: 1030px;
|
||||
margin-left: -15px;
|
||||
border-collapse: separate;
|
||||
}
|
||||
.list tbody tr {
|
||||
height: 39px;
|
||||
}
|
||||
.commands {
|
||||
width: 213px;
|
||||
}
|
||||
.turns {
|
||||
text-align: left;
|
||||
font-size: 11px;
|
||||
}
|
||||
.error {
|
||||
color: #ff7373;
|
||||
}
|
||||
.footer {
|
||||
margin-top: 5px;
|
||||
}
|
||||
@media (max-width: 1000px) {
|
||||
.secret-page {
|
||||
margin: 8px 0 0;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -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();
|
||||
}
|
||||
Reference in New Issue
Block a user