Restore legacy NPC policy frontend

This commit is contained in:
2026-07-26 05:18:04 +00:00
parent 1cba5bdfbf
commit b82924b55f
6 changed files with 1168 additions and 693 deletions
+338
View File
@@ -0,0 +1,338 @@
import { expect, test, type Page, type Route } from '@playwright/test';
import { mkdir, readFile } from 'node:fs/promises';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
type FixtureState = {
permissionLevel: number;
failNextMutation?: boolean;
failLoad?: boolean;
mutations: string[];
};
const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../../..');
const artifactRoot = process.env.NPC_POLICY_PARITY_ARTIFACT_DIR
? resolve(process.env.NPC_POLICY_PARITY_ARTIFACT_DIR)
: null;
const imageRoots = [resolve(repositoryRoot, '../image'), resolve(repositoryRoot, '../../image')];
const referenceAsset = async (relativePath: string): Promise<Buffer> => {
for (const root of imageRoots) {
try {
return await readFile(resolve(root, relativePath));
} catch {
// Nested worktrees and the primary checkout have different image parents.
}
}
throw new Error(`Reference image not found: ${relativePath}`);
};
const response = (data: unknown) => ({ result: { data } });
const errorResponse = (path: string, message: string, code = 'BAD_REQUEST') => ({
error: { message, code: -32000, data: { code, httpStatus: code === 'FORBIDDEN' ? 403 : 400, path } },
});
const operationName = (route: Route): string => {
const url = new URL(route.request().url());
return decodeURIComponent(url.pathname.slice(url.pathname.lastIndexOf('/trpc/') + 6));
};
const fulfillJson = (route: Route, body: unknown) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(body) });
const nationPriority = [
'불가침제의',
'선전포고',
'천도',
'유저장긴급포상',
'부대전방발령',
'유저장구출발령',
'유저장후방발령',
'부대유저장후방발령',
'유저장전방발령',
'유저장포상',
'부대구출발령',
'부대후방발령',
'NPC긴급포상',
'NPC구출발령',
'NPC후방발령',
'NPC포상',
'NPC전방발령',
'유저장내정발령',
'NPC내정발령',
'NPC몰수',
];
const generalPriority = [
'NPC사망대비',
'귀환',
'금쌀구매',
'출병',
'긴급내정',
'전투준비',
'전방워프',
'NPC헌납',
'징병',
'후방워프',
'전쟁내정',
'소집해제',
'일반내정',
'내정워프',
];
const policy = {
reqNationGold: 10_000,
reqNationRice: 12_000,
CombatForce: {},
SupportForce: [],
DevelopForce: [],
reqHumanWarUrgentGold: 0,
reqHumanWarUrgentRice: 0,
reqHumanWarRecommandGold: 0,
reqHumanWarRecommandRice: 0,
reqHumanDevelGold: 10_000,
reqHumanDevelRice: 10_000,
reqNPCWarGold: 0,
reqNPCWarRice: 0,
reqNPCDevelGold: 0,
reqNPCDevelRice: 500,
minimumResourceActionAmount: 1_000,
maximumResourceActionAmount: 10_000,
minNPCWarLeadership: 40,
minWarCrew: 1_500,
minNPCRecruitCityPopulation: 50_000,
safeRecruitCityPopulationRatio: 0.5,
properWarTrainAtmos: 90,
cureThreshold: 10,
};
const policyFixture = (state: FixtureState) => ({
nationId: 1,
nationName: '위',
nationLevel: 3,
defaultNationPolicy: policy,
currentNationPolicy: policy,
zeroPolicy: {
...policy,
reqHumanWarUrgentGold: 7_600,
reqHumanWarUrgentRice: 7_600,
reqHumanWarRecommandGold: 15_200,
reqHumanWarRecommandRice: 15_200,
reqNPCWarGold: 2_700,
reqNPCWarRice: 2_700,
reqNPCDevelGold: 540,
},
defaultNationPriority: nationPriority,
currentNationPriority: nationPriority,
availableNationPriorityItems: nationPriority,
defaultGeneralActionPriority: generalPriority,
currentGeneralActionPriority: generalPriority,
availableGeneralActionPriorityItems: generalPriority,
lastSetters: {
policy: { setter: null, date: null },
nation: { setter: null, date: null },
general: { setter: null, date: null },
},
defaultStatMax: 70,
defaultStatNpcMax: 75,
permissionLevel: state.permissionLevel,
});
const installFixture = async (page: Page, state: FixtureState) => {
await page.addInitScript(() => {
localStorage.setItem('sammo-game-token', 'ga_npc_policy_playwright');
localStorage.setItem('sammo-game-profile', 'che:default');
});
for (const filename of ['back_walnut.jpg', 'back_green.jpg', 'back_blue.jpg']) {
await page.route(`**/image/game/${filename}`, async (route) =>
route.fulfill({
status: 200,
contentType: 'image/jpeg',
body: await referenceAsset(`game/${filename}`),
})
);
}
await page.route('**/che/api/trpc/**', async (route) => {
const operations = operationName(route).split(',');
const results = operations.map((operation) => {
if (operation === 'lobby.info') return response({ myGeneral: { id: 22, name: '정책담당' } });
if (operation === 'join.getConfig') return response({});
if (operation === 'npc.getPolicy') {
return state.failLoad
? errorResponse(operation, '권한이 부족합니다.', 'FORBIDDEN')
: response(policyFixture(state));
}
if (
operation === 'npc.setNationPolicy' ||
operation === 'npc.setNationPriority' ||
operation === 'npc.setGeneralPriority'
) {
state.mutations.push(operation);
if (state.failNextMutation) {
state.failNextMutation = false;
return errorResponse(operation, '권한이 부족합니다.', 'FORBIDDEN');
}
return response({ ok: true });
}
return errorResponse(operation, `Unhandled fixture operation: ${operation}`);
});
await fulfillJson(route, results);
});
};
const gotoPolicy = async (page: Page) => {
await page.goto('npc-control');
};
const screenshot = async (page: Page, name: string) => {
if (!artifactRoot) return;
await mkdir(artifactRoot, { recursive: true });
await page.screenshot({ path: resolve(artifactRoot, name), fullPage: true });
};
test('desktop geometry, typography, textures, drag, focus, tooltip, and successful save match the reference', async ({
page,
}) => {
const state: FixtureState = { permissionLevel: 4, mutations: [] };
await installFixture(page, state);
await page.setViewportSize({ width: 1000, height: 900 });
await gotoPolicy(page);
await expect(page.locator('#container')).toBeVisible();
const computed = await page.evaluate(() => {
const measure = (selector: string) => {
const element = document.querySelector<HTMLElement>(selector)!;
const rect = element.getBoundingClientRect();
const style = getComputedStyle(element);
return {
x: rect.x,
y: rect.y,
width: rect.width,
height: rect.height,
display: style.display,
gridTemplateColumns: style.gridTemplateColumns,
fontFamily: style.fontFamily,
fontSize: style.fontSize,
lineHeight: style.lineHeight,
color: style.color,
backgroundImage: style.backgroundImage,
backgroundColor: style.backgroundColor,
};
};
return {
body: measure('body'),
container: measure('#container'),
topBar: measure('.top-back-bar'),
section: measure('.section_bar'),
form: measure('.form_list'),
field: measure('.policy-field'),
input: measure('.field-row input'),
control: measure('.control_bar'),
reset: measure('.reset_btn'),
submit: measure('.submit_btn'),
priorityPanel: measure('.priority-panel'),
priorityList: measure('.priority-list'),
inactiveHeader: measure('.inactive-header'),
activeItem: measure('.priority-column:nth-child(2) .priority-item'),
help: measure('.help-button'),
documentWidth: document.documentElement.scrollWidth,
};
});
expect(computed.body).toMatchObject({ width: 1000, fontSize: '14px', lineHeight: '21px' });
expect(computed.body.fontFamily).toContain('Pretendard');
expect(computed.container).toMatchObject({ x: 0, y: 32, width: 1000 });
expect(computed.container.backgroundImage).toContain('back_walnut.jpg');
expect(computed.topBar).toMatchObject({ width: 1000, height: 32 });
expect(computed.section).toMatchObject({ x: 1, y: 33, width: 998, height: 23 });
expect(computed.section.backgroundImage).toContain('back_green.jpg');
expect(computed.form).toMatchObject({ x: 9, width: 982 });
expect(computed.form.gridTemplateColumns).toBe('491px 491px');
expect(computed.field.width).toBeCloseTo(491, 0);
expect(computed.input).toMatchObject({ width: 224, height: 34 });
expect(computed.reset).toMatchObject({ width: 150, height: 35.5, backgroundColor: 'rgb(48, 48, 48)' });
expect(computed.submit).toMatchObject({ width: 150, height: 35.5, backgroundColor: 'rgb(55, 90, 127)' });
expect(computed.priorityPanel.width).toBeCloseTo(499, 0);
expect(computed.priorityList.width).toBeCloseTo(229, 0);
expect(computed.inactiveHeader).toMatchObject({ height: 37, backgroundColor: 'rgb(214, 214, 214)' });
expect(computed.activeItem.height).toBe(37);
expect(computed.help).toMatchObject({ width: 24, height: 22.375 });
expect(computed.documentWidth).toBe(1000);
await screenshot(page, 'core-npc-policy-desktop-baseline.png');
const goldInput = page.getByLabel('국가 권장 금');
await goldInput.focus();
await expect(goldInput).toBeFocused();
expect(await goldInput.evaluate((element) => getComputedStyle(element).outlineStyle)).not.toBe('none');
const help = page.getByRole('button', { name: '불가침제의 설명' });
await help.hover();
await expect.poll(() => help.evaluate((element) => getComputedStyle(element, '::after').opacity)).toBe('1');
const active = page.locator('.priority-panel').first().locator('.priority-column').nth(1).getByText('불가침제의');
await active.dragTo(
page.locator('.priority-panel').first().locator('.priority-column').first().locator('.priority-list')
);
await expect(
page.locator('.priority-panel').first().locator('.priority-column').first().getByText('불가침제의')
).toBeVisible();
await goldInput.fill('12345');
page.once('dialog', (dialog) => dialog.accept());
await page.locator('#container > .control_bar').getByRole('button', { name: '설정' }).click();
await expect(page.getByRole('status')).toContainText('NPC 정책이 반영되었습니다.');
expect(state.mutations).toContain('npc.setNationPolicy');
await screenshot(page, 'core-npc-policy-desktop.png');
});
test('500px layout stacks policy fields and priority panels like the reference', async ({ page }) => {
await installFixture(page, { permissionLevel: 4, mutations: [] });
await page.setViewportSize({ width: 500, height: 900 });
await gotoPolicy(page);
await expect(page.locator('#container')).toBeVisible();
const geometry = await page.evaluate(() => {
const rect = (selector: string) => {
const value = document.querySelector<HTMLElement>(selector)!.getBoundingClientRect();
return { x: value.x, y: value.y, width: value.width, height: value.height };
};
return {
container: rect('#container'),
form: rect('.form_list'),
firstField: rect('.policy-field'),
panels: [...document.querySelectorAll<HTMLElement>('.priority-panel')].map((element) => {
const value = element.getBoundingClientRect();
return { x: value.x, y: value.y, width: value.width };
}),
documentWidth: document.documentElement.scrollWidth,
};
});
expect(geometry.container).toMatchObject({ x: 0, y: 32, width: 500 });
expect(geometry.form).toMatchObject({ x: 9, width: 482 });
expect(geometry.firstField.width).toBeCloseTo(482, 0);
expect(geometry.panels).toHaveLength(2);
expect(geometry.panels[0]).toMatchObject({ x: 1, width: 498 });
expect(geometry.panels[1]?.x).toBe(1);
expect(geometry.panels[1]?.y).toBeGreaterThan(geometry.panels[0]?.y ?? 0);
expect(geometry.documentWidth).toBe(500);
await screenshot(page, 'core-npc-policy-mobile.png');
});
test('a read-level user sees enabled legacy controls but a forbidden save retains the draft', async ({ page }) => {
const state: FixtureState = { permissionLevel: 1, failNextMutation: true, mutations: [] };
await installFixture(page, state);
await gotoPolicy(page);
const input = page.getByLabel('국가 권장 금');
await expect(input).toBeEnabled();
await input.fill('23456');
page.once('dialog', (dialog) => dialog.accept());
await page.locator('#container > .control_bar').getByRole('button', { name: '설정' }).click();
await expect(page.getByRole('alert')).toContainText('권한이 부족합니다.');
await expect(input).toHaveValue('23456');
expect(state.mutations).toEqual(['npc.setNationPolicy']);
});
test('a user below secret read permission receives a recoverable page error', async ({ page }) => {
await installFixture(page, { permissionLevel: 0, failLoad: true, mutations: [] });
await gotoPolicy(page);
await expect(page.getByRole('alert')).toContainText('권한이 부족합니다.');
await expect(page.locator('#container')).toHaveCount(0);
await expect(page.getByRole('button', { name: '다시 시도' })).toBeVisible();
});
+1 -1
View File
@@ -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', 'nationOffices.spec.ts', 'npcPolicy.spec.ts'],
fullyParallel: false,
workers: 1,
timeout: 30_000,
+1
View File
@@ -9,6 +9,7 @@
"preview": "vite preview",
"test:e2e:troop": "playwright test troop.spec.ts --config e2e/playwright.config.mjs",
"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",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
+693 -691
View File
@@ -1,78 +1,61 @@
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';
import PanelCard from '../components/ui/PanelCard.vue';
import SkeletonLines from '../components/ui/SkeletonLines.vue';
import { trpc } from '../utils/trpc';
import { npcPriorityHelp } from '../utils/npcPriorityHelp';
import { trpc } from '../utils/trpc';
type NpcPolicyResponse = Awaited<ReturnType<typeof trpc.npc.getPolicy.query>>;
type NationPolicy = NpcPolicyResponse['currentNationPolicy'];
type PolicyKey = keyof NationPolicy;
type PolicyField = {
key: PolicyKey;
type NumericPolicyKey = Exclude<keyof NationPolicy, 'CombatForce' | 'SupportForce' | 'DevelopForce'>;
type PrioritySectionKey = 'nation' | 'general';
type PriorityBucket = 'active' | 'inactive';
interface PolicyField {
key: NumericPolicyKey;
label: string;
step: number;
description: string;
hint?: string;
percent?: boolean;
};
min?: number;
max?: number;
}
type PolicySection = {
title: string;
fields: PolicyField[];
};
const NUMERIC_POLICY_KEYS = [
'reqNationGold',
'reqNationRice',
'reqHumanWarUrgentGold',
'reqHumanWarUrgentRice',
'reqHumanWarRecommandGold',
'reqHumanWarRecommandRice',
'reqHumanDevelGold',
'reqHumanDevelRice',
'reqNPCWarGold',
'reqNPCWarRice',
'reqNPCDevelGold',
'reqNPCDevelRice',
'minimumResourceActionAmount',
'maximumResourceActionAmount',
'minNPCWarLeadership',
'minWarCrew',
'minNPCRecruitCityPopulation',
'safeRecruitCityPopulationRatio',
'properWarTrainAtmos',
'cureThreshold',
] as const;
type NumericPolicyKey = (typeof NUMERIC_POLICY_KEYS)[number];
type PrioritySectionKey = 'nation' | 'general';
type PriorityListState = {
interface PriorityListState {
active: string[];
inactive: string[];
available: string[];
};
}
interface PriorityPanel {
key: PrioritySectionKey;
title: string;
description: string[];
setter: NpcPolicyResponse['lastSetters']['nation'];
state: PriorityListState;
}
interface DragState {
section: PrioritySectionKey;
bucket: PriorityBucket;
index: number;
}
const loading = ref(false);
const error = ref<string | null>(null);
const notice = ref<string | null>(null);
const data = ref<NpcPolicyResponse | null>(null);
const policyDraft = ref<NationPolicy | null>(null);
const lastSavedPolicy = ref<NationPolicy | null>(null);
const nationPriority = ref<PriorityListState | null>(null);
const generalPriority = ref<PriorityListState | null>(null);
const lastSavedNationPriority = ref<string[]>([]);
const lastSavedGeneralPriority = ref<string[]>([]);
const dragState = ref<DragState | null>(null);
const resolveErrorMessage = (value: unknown): string => {
if (value instanceof Error) {
return value.message;
}
if (typeof value === 'string') {
return value;
}
if (value instanceof Error) return value.message;
if (typeof value === 'string') return value;
return 'unknown_error';
};
@@ -85,851 +68,870 @@ const clonePolicy = (source: NationPolicy): NationPolicy => ({
const assignPriorityState = (active: string[], available: string[]): PriorityListState => {
const activeSet = new Set(active);
const inactive = available.filter((item) => !activeSet.has(item));
return {
active: [...active],
inactive,
inactive: available.filter((item) => !activeSet.has(item)),
available: [...available],
};
};
const loadPolicy = async () => {
if (loading.value) {
return;
}
if (loading.value) return;
loading.value = true;
error.value = null;
try {
data.value = await trpc.npc.getPolicy.query();
} catch (err) {
error.value = resolveErrorMessage(err);
} catch (caught) {
error.value = resolveErrorMessage(caught);
} finally {
loading.value = false;
}
};
onMounted(() => {
void loadPolicy();
watch(data, (value) => {
if (!value) return;
policyDraft.value = clonePolicy(value.currentNationPolicy);
lastSavedPolicy.value = clonePolicy(value.currentNationPolicy);
nationPriority.value = assignPriorityState(value.currentNationPriority, value.availableNationPriorityItems);
generalPriority.value = assignPriorityState(
value.currentGeneralActionPriority,
value.availableGeneralActionPriorityItems
);
lastSavedNationPriority.value = [...value.currentNationPriority];
lastSavedGeneralPriority.value = [...value.currentGeneralActionPriority];
});
watch(
() => data.value,
(value) => {
if (!value) {
return;
}
policyDraft.value = clonePolicy(value.currentNationPolicy);
lastSavedPolicy.value = clonePolicy(value.currentNationPolicy);
nationPriority.value = assignPriorityState(value.currentNationPriority, value.availableNationPriorityItems);
generalPriority.value = assignPriorityState(
value.currentGeneralActionPriority,
value.availableGeneralActionPriorityItems
);
lastSavedNationPriority.value = [...value.currentNationPriority];
lastSavedGeneralPriority.value = [...value.currentGeneralActionPriority];
}
);
onMounted(() => void loadPolicy());
const formatNumber = (value: number): string => new Intl.NumberFormat('ko-KR').format(Math.round(value));
const calcPolicyValue = (key: NumericPolicyKey): number => {
if (!data.value || !policyDraft.value) {
return 0;
}
if (!data.value || !policyDraft.value) return 0;
const value = policyDraft.value[key];
if (value === 0) {
return data.value.zeroPolicy[key];
}
return value;
return value === 0 ? data.value.zeroPolicy[key] : value;
};
const safeRecruitPercent = computed({
get: () => (policyDraft.value?.safeRecruitCityPopulationRatio ?? 0) * 100,
set: (value: number) => {
if (!policyDraft.value) {
return;
}
policyDraft.value.safeRecruitCityPopulationRatio = value / 100;
if (policyDraft.value) policyDraft.value.safeRecruitCityPopulationRatio = value / 100;
},
});
const policySections = computed<PolicySection[]>(() => {
if (!data.value) {
return [];
}
const policyFields = computed<PolicyField[]>(() => {
if (!data.value) return [];
const statMax = data.value.defaultStatMax;
const statNpcMax = data.value.defaultStatNpcMax;
return [
{
title: '국가 재정',
fields: [
{
key: 'reqNationGold',
label: '국가 권장 금',
step: 100,
description: '이보다 많으면 포상, 적으면 몰수/헌납합니다.(긴급포상 제외)',
},
{
key: 'reqNationRice',
label: '국가 권장 쌀',
step: 100,
description: '이보다 많으면 포상, 적으면 몰수/헌납합니다.(긴급포상 제외)',
},
],
key: 'reqNationGold',
label: '국가 권장 금',
step: 100,
description: '이보다 많으면 포상, 적으면 몰수/헌납합니다.(긴급포상 제외)',
},
{
title: '유저 전투장',
fields: [
{
key: 'reqHumanWarUrgentGold',
label: '긴급포상 금',
step: 100,
description:
'유저장긴급포상시 이보다 금이 적은 장수에게 포상합니다.',
hint: `0이면 보병 6회 징병(${formatNumber(statMax * 100 * 6)}) 가능한 금을 기준으로 하며, 현재 ${formatNumber(
data.value.zeroPolicy.reqHumanWarUrgentGold
)}입니다.`,
},
{
key: 'reqHumanWarUrgentRice',
label: '긴급포상 쌀',
step: 100,
description:
'유저장긴급포상시 이보다 쌀이 적은 장수에게 포상합니다.',
hint: `0이면 기본 병종으로 ${formatNumber(statMax * 100 * 6)}명 사살 가능한 쌀을 기준으로 하며, 현재 ${formatNumber(
data.value.zeroPolicy.reqHumanWarUrgentRice
)}입니다.`,
},
{
key: 'reqHumanWarRecommandGold',
label: '권장 금',
step: 100,
description: '유저전투장에게 주는 금입니다. 이보다 적으면 포상합니다.',
hint: `0이면 긴급포상 금의 2배를 기준으로 하며, 현재 ${formatNumber(
calcPolicyValue('reqHumanWarUrgentGold') * 2
)}입니다.`,
},
{
key: 'reqHumanWarRecommandRice',
label: '권장 쌀',
step: 100,
description: '유저전투장에게 주는 쌀입니다. 이보다 적으면 포상합니다.',
hint: `0이면 긴급포상 쌀의 2배를 기준으로 하며, 현재 ${formatNumber(
calcPolicyValue('reqHumanWarUrgentRice') * 2
)}입니다.`,
},
],
key: 'reqNationRice',
label: '국가 권장 쌀',
step: 100,
description: '이보다 많으면 포상, 적으면 몰수/헌납합니다.(긴급포상 제외)',
},
{
title: '유저 내정장',
fields: [
{
key: 'reqHumanDevelGold',
label: '권장 금',
step: 100,
description: '유저내정장에게 주는 금입니다. 이보다 적으면 포상합니다.',
},
{
key: 'reqHumanDevelRice',
label: '권장 쌀',
step: 100,
description: '유저내정장에게 주는 쌀입니다. 이보다 적으면 포상합니다.',
},
],
key: 'reqHumanWarUrgentGold',
label: '유저전투장 긴급포상 금',
step: 100,
description: '유저장긴급포상시 이보다 금이 적은 장수에게 포상합니다.',
hint: `0이면 보병 6회 징병(${formatNumber(statMax * 100)} * 6) 가능한 금을 기준으로 하며, 그 수치는 현재 ${formatNumber(data.value.zeroPolicy.reqHumanWarUrgentGold)}입니다.`,
},
{
title: 'NPC 전투장',
fields: [
{
key: 'reqNPCWarGold',
label: '권장 금',
step: 100,
description: 'NPC전투장에게 주는 금입니다. 이보다 적으면 포상합니다.',
hint: `0이면 기본 병종 4회(${formatNumber(statNpcMax * 100 * 4)}) 징병비를 기준으로 하며, 현재 ${formatNumber(
data.value.zeroPolicy.reqNPCWarGold
)}입니다.`,
},
{
key: 'reqNPCWarRice',
label: '권장 쌀',
step: 100,
description: 'NPC전투장에게 주는 쌀입니다. 이보다 적으면 포상합니다.',
hint: `0이면 기본 병종으로 ${formatNumber(statNpcMax * 100 * 4)}명 사살 가능한 쌀을 기준으로 하며, 현재 ${formatNumber(
data.value.zeroPolicy.reqNPCWarRice
)}입니다.`,
},
],
key: 'reqHumanWarUrgentRice',
label: '유저전투장 긴급포상 쌀',
step: 100,
description: '유저장긴급포상시 이보다 쌀이 적은 장수에게 포상합니다.',
hint: `0이면 기본 병종으로 ${formatNumber(statMax * 100)} * 6명 사살 가능한 쌀을 기준으로 하며, 그 수치는 현재 ${formatNumber(data.value.zeroPolicy.reqHumanWarUrgentRice)}입니다.`,
},
{
title: 'NPC 내정장',
fields: [
{
key: 'reqNPCDevelGold',
label: '권장 금',
step: 100,
description: 'NPC내정장에게 주는 금입니다. 이보다 5배 더 많다면 헌납합니다.',
hint: `0이면 30턴 내정 가능한 금을 기준으로 하며, 현재 ${formatNumber(
data.value.zeroPolicy.reqNPCDevelGold
)}입니다.`,
},
{
key: 'reqNPCDevelRice',
label: '권장 쌀',
step: 100,
description: 'NPC내정장에게 주는 쌀입니다. 이보다 5배 더 많다면 헌납합니다.',
},
],
key: 'reqHumanWarRecommandGold',
label: '유저전투장 권장 금',
step: 100,
description: '유저전투장에게 주는 금입니다. 이보다 적으면 포상합니다.',
hint: `0이면 유저전투장 긴급포상 금의 2배를 기준으로 하며, 그 수치는 현재 ${formatNumber(calcPolicyValue('reqHumanWarUrgentGold') * 2)}입니다.`,
},
{
title: '자원 정책',
fields: [
{
key: 'minimumResourceActionAmount',
label: '포상/몰수/헌납 최소 단위',
step: 100,
description: '연산결과가 이 단위보다 적다면 수행하지 않습니다.',
},
{
key: 'maximumResourceActionAmount',
label: '포상/몰수/헌납 최대 단위',
step: 100,
description: '연산결과가 이 단위보다 크다면 이 값에 맞춥니다.',
},
],
key: 'reqHumanWarRecommandRice',
label: '유저전투장 권장 쌀',
step: 100,
description: '유저전투장에게 주는 쌀입니다. 이보다 적으면 포상합니다.',
hint: `0이면 유저전투장 긴급포상 쌀의 2배를 기준으로 하며, 그 수치는 현재 ${formatNumber(calcPolicyValue('reqHumanWarUrgentRice') * 2)}입니다.`,
},
{
title: '전투/징병 기준',
fields: [
{
key: 'minWarCrew',
label: '최소 전투 가능 병력 수',
step: 50,
description: '이보다 적을 때에는 징병을 시도합니다.',
},
{
key: 'minNPCRecruitCityPopulation',
label: 'NPC 최소 징병 가능 인구 수',
step: 100,
description:
'도시의 인구가 이보다 낮으면 NPC는 도시에서 징병하지 않고 후방 워프합니다.',
},
{
key: 'safeRecruitCityPopulationRatio',
label: '제자리 징병 허용 인구율(%)',
step: 0.5,
description:
'전쟁 시 후방 발령, 후방 워프의 기준 인구입니다. 이보다 많다면 충분하다고 판단합니다.',
percent: true,
},
{
key: 'minNPCWarLeadership',
label: 'NPC 전투 참여 통솔 기준',
step: 5,
description: '이 수치보다 같거나 높으면 NPC전투장으로 분류됩니다.',
},
],
key: 'reqHumanDevelGold',
label: '유저내정장 권장 금',
step: 100,
description: '유저내정장에게 주는 금입니다. 이보다 적으면 포상합니다.',
},
{
title: '상태 기준',
fields: [
{
key: 'properWarTrainAtmos',
label: '훈련/사기진작 목표치',
step: 5,
description: '훈련/사기진작 기준치입니다. 이보다 같거나 높으면 출병합니다.',
},
{
key: 'cureThreshold',
label: '요양 기준(%)',
step: 5,
description: '요양 기준입니다. 이보다 많이 부상을 입으면 요양합니다.',
},
],
key: 'reqHumanDevelRice',
label: '유저내정장 권장 쌀',
step: 100,
description: '유저내정장에게 주는 쌀입니다. 이보다 적으면 포상합니다.',
},
{
key: 'reqNPCWarGold',
label: 'NPC전투장 권장 금',
step: 100,
description: 'NPC전투장에게 주는 금입니다. 이보다 적으면 포상합니다.',
hint: `0이면 기본 병종 4회(${formatNumber(statNpcMax * 100)} * 4) 징병비를 기준으로 하며, 그 수치는 현재 ${formatNumber(data.value.zeroPolicy.reqNPCWarGold)}입니다.`,
},
{
key: 'reqNPCWarRice',
label: 'NPC전투장 권장 쌀',
step: 100,
description: 'NPC전투장에게 주는 쌀입니다. 이보다 적으면 포상합니다.',
hint: `0이면 기본 병종으로 ${formatNumber(statNpcMax * 100)} * 4명 사살 가능한 쌀을 기준으로 하며, 그 수치는 현재 ${formatNumber(data.value.zeroPolicy.reqNPCWarRice)}입니다.`,
},
{
key: 'reqNPCDevelGold',
label: 'NPC내정장 권장 금',
step: 100,
description: 'NPC내정장에게 주는 금입니다. 이보다 5배 더 많다면 헌납합니다.',
hint: `0이면 30턴 내정 가능한 금을 기준으로 하며, 그 수치는 현재 ${formatNumber(data.value.zeroPolicy.reqNPCDevelGold)}입니다.`,
},
{
key: 'reqNPCDevelRice',
label: 'NPC내정장 권장 쌀',
step: 100,
description: 'NPC내정장에게 주는 쌀입니다. 이보다 5배 더 많다면 헌납합니다.',
},
{
key: 'minimumResourceActionAmount',
label: '포상/몰수/헌납/삼/팜 최소 단위',
step: 100,
min: 100,
description: '연산결과가 이 단위보다 적다면 수행하지 않습니다.',
},
{
key: 'maximumResourceActionAmount',
label: '포상/몰수/헌납/삼/팜 최대 단위',
step: 100,
min: 100,
description: '연산결과가 이 단위보다 크다면, 이 값에 맞춥니다.',
},
{
key: 'minWarCrew',
label: '최소 전투 가능 병력 수',
step: 50,
description: '이보다 적을 때에는 징병을 시도합니다.',
},
{
key: 'minNPCRecruitCityPopulation',
label: 'NPC 최소 징병 가능 인구 수',
step: 100,
description: '도시의 인구가 이보다 낮으면 NPC는 도시에서 징병하지 않고 후방 워프합니다.',
hint: 'NPC의 최대 병력수보다 낮게 설정하면 제자리에서 정착장려를 합니다.',
},
{
key: 'safeRecruitCityPopulationRatio',
label: '제자리 징병 허용 인구율(%)',
step: 0.5,
min: 0,
max: 100,
percent: true,
description: '전쟁 시 후방 발령, 후방 워프의 기준 인구입니다. 이보다 많다면 충분하다고 판단합니다.',
hint: 'NPC의 최대 병력수보다 낮게 설정하면 제자리에서 정착장려를 합니다.',
},
{
key: 'minNPCWarLeadership',
label: 'NPC 전투 참여 통솔 기준',
step: 5,
description: '이 수치보다 같거나 높으면 NPC전투장으로 분류됩니다.',
},
{
key: 'properWarTrainAtmos',
label: '훈련/사기진작 목표치',
step: 5,
min: 20,
max: 100,
description: '훈련/사기진작 기준치입니다. 이보다 같거나 높으면 출병합니다.',
},
{
key: 'cureThreshold',
label: '요양 기준',
step: 5,
min: 10,
max: 100,
description: '요양 기준 %입니다. 이보다 많이 부상을 입으면 요양합니다.',
},
];
});
const canEdit = computed(() => (data.value?.permissionLevel ?? 0) >= 3);
const priorityPanels = computed<PriorityPanel[]>(() => {
if (!data.value || !nationPriority.value || !generalPriority.value) return [];
return [
{
key: 'nation',
title: 'NPC 사령턴 우선순위',
description: ['예턴이 없거나, 지정되어 있더라도 실패하면', '아래 순위에 따라 사령턴을 시도합니다.'],
setter: data.value.lastSetters.nation,
state: nationPriority.value,
},
{
key: 'general',
title: 'NPC 일반턴 우선순위',
description: [
'순위가 높은 것부터 시도합니다.',
'아무것도 실행할 수 없으면 물자조달이나 인재탐색을 합니다.',
],
setter: data.value.lastSetters.general,
state: generalPriority.value,
},
];
});
const resetPolicy = () => {
if (!data.value) {
return;
}
if (!window.confirm('초기 설정으로 되돌릴까요?')) {
return;
}
if (!data.value || !window.confirm('초기 설정으로 되돌릴까요?')) return;
policyDraft.value = clonePolicy(data.value.defaultNationPolicy);
notice.value = '서버 초깃값을 적용했습니다. 설정 버튼을 누르면 반영됩니다.';
};
const rollbackPolicy = () => {
if (!lastSavedPolicy.value) {
return;
}
if (!window.confirm('이전 설정으로 되돌릴까요?')) {
return;
}
if (!lastSavedPolicy.value || !window.confirm('이전 설정으로 되돌릴까요?')) return;
policyDraft.value = clonePolicy(lastSavedPolicy.value);
notice.value = '이전 설정으로 되돌렸습니다.';
};
const submitPolicy = async () => {
if (!policyDraft.value) {
return;
}
if (!window.confirm('저장할까요?')) {
return;
}
if (!policyDraft.value || !window.confirm('저장할까요?')) return;
error.value = null;
notice.value = null;
try {
await trpc.npc.setNationPolicy.mutate(policyDraft.value);
await loadPolicy();
} catch (err) {
error.value = resolveErrorMessage(err);
lastSavedPolicy.value = clonePolicy(policyDraft.value);
notice.value = 'NPC 정책이 반영되었습니다.';
} catch (caught) {
error.value = `설정하지 못했습니다: ${resolveErrorMessage(caught)}`;
}
};
const moveItem = (list: string[], from: number, to: number) => {
if (to < 0 || to >= list.length) {
return;
}
const [item] = list.splice(from, 1);
list.splice(to, 0, item);
};
const insertByOrder = (list: string[], item: string, orderMap: Map<string, number>) => {
const targetOrder = orderMap.get(item) ?? Number.MAX_SAFE_INTEGER;
const index = list.findIndex((entry) => (orderMap.get(entry) ?? Number.MAX_SAFE_INTEGER) > targetOrder);
if (index === -1) {
list.push(item);
} else {
list.splice(index, 0, item);
}
};
const togglePriority = (section: PrioritySectionKey, item: string, enable: boolean) => {
const target = section === 'nation' ? nationPriority.value : generalPriority.value;
if (!target) {
return;
}
if (enable) {
const index = target.inactive.indexOf(item);
if (index >= 0) {
target.inactive.splice(index, 1);
const orderMap = new Map(target.available.map((entry, idx) => [entry, idx]));
insertByOrder(target.active, item, orderMap);
}
return;
}
const index = target.active.indexOf(item);
if (index >= 0) {
target.active.splice(index, 1);
const orderMap = new Map(target.available.map((entry, idx) => [entry, idx]));
insertByOrder(target.inactive, item, orderMap);
}
};
const reorderPriority = (section: PrioritySectionKey, index: number, direction: number) => {
const target = section === 'nation' ? nationPriority.value : generalPriority.value;
if (!target) {
return;
}
moveItem(target.active, index, index + direction);
};
const resetPriority = (section: PrioritySectionKey) => {
if (!data.value) {
return;
}
if (!window.confirm('초기 설정으로 되돌릴까요?')) {
return;
}
if (!data.value || !window.confirm('초기 설정으로 되돌릴까요?')) return;
if (section === 'nation') {
nationPriority.value = assignPriorityState(data.value.defaultNationPriority, data.value.availableNationPriorityItems);
nationPriority.value = assignPriorityState(
data.value.defaultNationPriority,
data.value.availableNationPriorityItems
);
} else {
generalPriority.value = assignPriorityState(
data.value.defaultGeneralActionPriority,
data.value.availableGeneralActionPriorityItems
);
}
notice.value = '서버 초깃값을 적용했습니다. 설정 버튼을 누르면 반영됩니다.';
};
const rollbackPriority = (section: PrioritySectionKey) => {
if (!window.confirm('이전 설정으로 되돌릴까요?')) {
return;
}
if (section === 'nation' && data.value) {
nationPriority.value = assignPriorityState(lastSavedNationPriority.value, data.value.availableNationPriorityItems);
}
if (section === 'general' && data.value) {
if (!data.value || !window.confirm('이전 설정으로 되돌릴까요?')) return;
if (section === 'nation') {
nationPriority.value = assignPriorityState(
lastSavedNationPriority.value,
data.value.availableNationPriorityItems
);
} else {
generalPriority.value = assignPriorityState(
lastSavedGeneralPriority.value,
data.value.availableGeneralActionPriorityItems
);
}
notice.value = '이전 설정으로 되돌렸습니다.';
};
const submitPriority = async (section: PrioritySectionKey) => {
if (!data.value) {
return;
}
if (!window.confirm('저장할까요?')) {
return;
}
const state = section === 'nation' ? nationPriority.value : generalPriority.value;
if (!state || !window.confirm('저장할까요?')) return;
error.value = null;
notice.value = null;
try {
if (section === 'nation' && nationPriority.value) {
await trpc.npc.setNationPriority.mutate(nationPriority.value.active);
if (section === 'nation') {
await trpc.npc.setNationPriority.mutate(state.active);
lastSavedNationPriority.value = [...state.active];
} else {
await trpc.npc.setGeneralPriority.mutate(state.active);
lastSavedGeneralPriority.value = [...state.active];
}
if (section === 'general' && generalPriority.value) {
await trpc.npc.setGeneralPriority.mutate(generalPriority.value.active);
}
await loadPolicy();
} catch (err) {
error.value = resolveErrorMessage(err);
notice.value = 'NPC 정책이 반영되었습니다.';
} catch (caught) {
error.value = `설정하지 못했습니다: ${resolveErrorMessage(caught)}`;
}
};
const startDrag = (event: DragEvent, section: PrioritySectionKey, bucket: PriorityBucket, index: number) => {
dragState.value = { section, bucket, index };
event.dataTransfer?.setData('text/plain', `${section}:${bucket}:${index}`);
if (event.dataTransfer) event.dataTransfer.effectAllowed = 'move';
};
const dropPriority = (event: DragEvent, section: PrioritySectionKey, bucket: PriorityBucket, targetIndex?: number) => {
event.preventDefault();
const source = dragState.value;
const state = section === 'nation' ? nationPriority.value : generalPriority.value;
if (!source || source.section !== section || !state) return;
const sourceList = state[source.bucket];
const targetList = state[bucket];
const [item] = sourceList.splice(source.index, 1);
if (!item) return;
let index = targetIndex ?? targetList.length;
if (sourceList === targetList && source.index < index) index -= 1;
targetList.splice(Math.max(0, Math.min(index, targetList.length)), 0, item);
dragState.value = null;
};
</script>
<template>
<main class="npc-page">
<header class="page-header">
<div>
<h1 class="page-title">NPC 정책</h1>
<p class="page-subtitle">사령/일반 AI 우선순위 자원 기준</p>
<main id="npc-policy-page" class="npc-page">
<nav class="top-back-bar legacy-bg0">
<RouterLink class="back-button" to="/">돌아가기</RouterLink>
<strong>NPC 정책</strong>
</nav>
<div v-if="loading && !data" class="page-state legacy-bg0">불러오는 중...</div>
<div v-else-if="!data" class="page-state error-state legacy-bg0" role="alert">
{{ error ?? 'NPC 정책을 불러오지 못했습니다.' }}
<button type="button" @click="loadPolicy">다시 시도</button>
</div>
<section v-else-if="policyDraft" id="container" class="policy-container legacy-bg0">
<div class="section_bar legacy-bg1">국가 정책</div>
<div class="setter">
최근 설정: {{ data.lastSetters.policy.setter ?? '-없음-' }} ({{
data.lastSetters.policy.date ?? '설정 기록 없음'
}})
</div>
<div class="header-actions">
<RouterLink class="ghost" to="/">메인</RouterLink>
<button class="ghost" @click="loadPolicy">새로고침</button>
<div v-if="error" class="feedback error-feedback" role="alert">{{ error }}</div>
<div v-if="notice" class="feedback notice-feedback" role="status">{{ notice }}</div>
<div class="form_list">
<div v-for="field in policyFields" :key="field.key" class="policy-field">
<div class="field-row">
<label :for="`npc-policy-${field.key}`">{{ field.label }}</label>
<input
v-if="field.percent"
:id="`npc-policy-${field.key}`"
v-model.number="safeRecruitPercent"
type="number"
:step="field.step"
:min="field.min"
:max="field.max"
/>
<input
v-else
:id="`npc-policy-${field.key}`"
v-model.number="policyDraft[field.key]"
type="number"
:step="field.step"
:min="field.min"
:max="field.max"
/>
</div>
<p>{{ field.description }}</p>
<p v-if="field.hint">{{ field.hint }}</p>
</div>
</div>
</header>
<div v-if="error" class="error">{{ error }}</div>
<div class="work-in-progress">
전투 부대는 작업중입니다(json양식: {부대번호:[시작도시번호(아국),도착도시번호(적국)],...})
<br />후방 징병 부대는 작업중입니다(json양식: [부대번호,...]) <br />내정 부대는 작업중입니다(json양식:
[부대번호,...])
<input type="hidden" :value="JSON.stringify(policyDraft.CombatForce)" />
<input type="hidden" :value="JSON.stringify(policyDraft.SupportForce)" />
<input type="hidden" :value="JSON.stringify(policyDraft.DevelopForce)" />
</div>
<section v-if="loading && !data">
<PanelCard title="NPC 정책 로딩">
<SkeletonLines :lines="6" />
</PanelCard>
</section>
<section v-else-if="data && policyDraft" class="npc-layout">
<PanelCard title="국가 정책" subtitle="NPC 자원 기준과 전투 판단 기준">
<div class="setter">
최근 설정: {{ data.lastSetters.policy.setter ?? '-없음-' }} ({{
data.lastSetters.policy.date ?? '설정 기록 없음'
}})
<div class="control_bar">
<div class="button-group">
<button class="reset_btn" type="button" @click="resetPolicy">초깃값으로</button>
<button class="revert_btn" type="button" @click="rollbackPolicy">이전값으로</button>
</div>
<div v-if="!canEdit" class="readonly-note">권한이 부족하여 읽기 전용으로 표시됩니다.</div>
<div v-for="section in policySections" :key="section.title" class="policy-section">
<h3 class="section-title">{{ section.title }}</h3>
<div class="policy-grid">
<div
v-for="field in section.fields"
:key="field.key"
class="policy-field"
>
<label class="field-label">{{ field.label }}</label>
<input
v-if="field.percent"
v-model.number="safeRecruitPercent"
type="number"
class="field-input"
:step="field.step"
min="0"
max="100"
:disabled="!canEdit"
/>
<input
v-else
v-model.number="policyDraft[field.key as PolicyKey]"
type="number"
class="field-input"
:step="field.step"
min="0"
:disabled="!canEdit"
/>
<p class="field-desc">{{ field.description }}</p>
<p v-if="field.hint" class="field-hint">{{ field.hint }}</p>
</div>
</div>
</div>
<div class="control-bar">
<div class="btn-group">
<button class="ghost" :disabled="!canEdit" @click="resetPolicy">초깃값으로</button>
<button class="ghost" :disabled="!canEdit" @click="rollbackPolicy">이전값으로</button>
</div>
<button class="primary" :disabled="!canEdit" @click="submitPolicy">설정</button>
</div>
</PanelCard>
<button class="submit_btn" type="button" @click="submitPolicy">설정</button>
</div>
<div class="priority-grid">
<PanelCard title="NPC 사령턴 우선순위" subtitle="예턴 실패 시 우선순위대로 실행">
<div class="setter">
최근 설정: {{ data.lastSetters.nation.setter ?? '-없음-' }} ({{
data.lastSetters.nation.date ?? '설정 기록 없음'
}})
<div class="priority-sections">
<section
v-for="panel in priorityPanels"
:key="panel.key"
:class="['priority-panel', panel.key === 'nation' ? 'half_section_left' : 'half_section_right']"
>
<div class="section_bar legacy-bg1">{{ panel.title }}</div>
<div class="priority-meta">
<small>
최근 설정: {{ panel.setter.setter ?? '-없음-' }} ({{
panel.setter.date ?? '설정 기록 없음'
}})
</small>
</div>
<div class="priority-description">
<small>{{ panel.description[0] }}<br />{{ panel.description[1] }}</small>
</div>
<div v-if="!canEdit" class="readonly-note">권한이 부족하여 읽기 전용으로 표시됩니다.</div>
<div class="priority-columns">
<div class="priority-column">
<div class="column-title">비활성</div>
<div class="priority-list">
<div class="sub_bar legacy-bg2">비활성</div>
<div
class="priority-list"
@dragover.prevent
@drop="dropPriority($event, panel.key, 'inactive')"
>
<div class="inactive-header">&lt;비활성화 항목들&gt;</div>
<div
v-for="item in nationPriority?.inactive ?? []"
v-for="(item, index) in panel.state.inactive"
:key="item"
class="priority-item"
draggable="true"
@dragstart="startDrag($event, panel.key, 'inactive', index)"
@dragover.prevent
@drop.stop="dropPriority($event, panel.key, 'inactive', index)"
>
<span class="priority-name">{{ item }}</span>
<span
class="priority-help"
:data-text="npcPriorityHelp[item] ?? '설명 없음'"
>
?
</span>
<button class="ghost" :disabled="!canEdit" @click="togglePriority('nation', item, true)">
활성
</button>
<div class="priority_info">
<span class="drag-handle"></span>
<span>{{ item }}</span>
<button
class="help-button"
type="button"
:aria-label="`${item} 설명`"
:data-text="npcPriorityHelp[item] ?? '설명 없음'"
>
?
</button>
</div>
</div>
</div>
</div>
<div class="priority-column">
<div class="column-title">활성</div>
<div class="priority-list">
<div class="sub_bar legacy-bg2">활성</div>
<div
class="priority-list"
@dragover.prevent
@drop="dropPriority($event, panel.key, 'active')"
>
<div
v-for="(item, idx) in nationPriority?.active ?? []"
:key="item"
v-for="(item, index) in panel.state.active"
:key="`${item}-${index}`"
class="priority-item"
draggable="true"
@dragstart="startDrag($event, panel.key, 'active', index)"
@dragover.prevent
@drop.stop="dropPriority($event, panel.key, 'active', index)"
>
<div class="priority-main">
<span class="priority-name">{{ item }}</span>
<span
class="priority-help"
<div class="priority_info">
<span class="drag-handle"></span>
<span>{{ item }}</span>
<button
class="help-button"
type="button"
:aria-label="`${item} 설명`"
:data-text="npcPriorityHelp[item] ?? '설명 없음'"
>
?
</span>
</div>
<div class="priority-actions">
<button class="ghost" :disabled="!canEdit" @click="reorderPriority('nation', idx, -1)"></button>
<button class="ghost" :disabled="!canEdit" @click="reorderPriority('nation', idx, 1)">아래</button>
<button class="ghost" :disabled="!canEdit" @click="togglePriority('nation', item, false)">
비활성
</button>
</div>
</div>
</div>
</div>
</div>
<div class="control-bar">
<div class="btn-group">
<button class="ghost" :disabled="!canEdit" @click="resetPriority('nation')">초깃값으로</button>
<button class="ghost" :disabled="!canEdit" @click="rollbackPriority('nation')">이전값으로</button>
<div class="control_bar priority-control">
<div class="button-group">
<button class="reset_btn" type="button" @click="resetPriority(panel.key)">
초깃값으로
</button>
<button class="revert_btn" type="button" @click="rollbackPriority(panel.key)">
이전값으로
</button>
</div>
<button class="primary" :disabled="!canEdit" @click="submitPriority('nation')">설정</button>
<button class="submit_btn" type="button" @click="submitPriority(panel.key)">설정</button>
</div>
</PanelCard>
<PanelCard title="NPC 일반턴 우선순위" subtitle="순위가 높은 것부터 시도">
<div class="setter">
최근 설정: {{ data.lastSetters.general.setter ?? '-없음-' }} ({{
data.lastSetters.general.date ?? '설정 기록 없음'
}})
</div>
<div v-if="!canEdit" class="readonly-note">권한이 부족하여 읽기 전용으로 표시됩니다.</div>
<div class="priority-columns">
<div class="priority-column">
<div class="column-title">비활성</div>
<div class="priority-list">
<div
v-for="item in generalPriority?.inactive ?? []"
:key="item"
class="priority-item"
>
<span class="priority-name">{{ item }}</span>
<span
class="priority-help"
:data-text="npcPriorityHelp[item] ?? '설명 없음'"
>
?
</span>
<button class="ghost" :disabled="!canEdit" @click="togglePriority('general', item, true)">
활성
</button>
</div>
</div>
</div>
<div class="priority-column">
<div class="column-title">활성</div>
<div class="priority-list">
<div
v-for="(item, idx) in generalPriority?.active ?? []"
:key="item"
class="priority-item"
>
<div class="priority-main">
<span class="priority-name">{{ item }}</span>
<span
class="priority-help"
:data-text="npcPriorityHelp[item] ?? '설명 없음'"
>
?
</span>
</div>
<div class="priority-actions">
<button class="ghost" :disabled="!canEdit" @click="reorderPriority('general', idx, -1)"></button>
<button class="ghost" :disabled="!canEdit" @click="reorderPriority('general', idx, 1)">아래</button>
<button class="ghost" :disabled="!canEdit" @click="togglePriority('general', item, false)">
비활성
</button>
</div>
</div>
</div>
</div>
</div>
<div class="control-bar">
<div class="btn-group">
<button class="ghost" :disabled="!canEdit" @click="resetPriority('general')">초깃값으로</button>
<button class="ghost" :disabled="!canEdit" @click="rollbackPriority('general')">이전값으로</button>
</div>
<button class="primary" :disabled="!canEdit" @click="submitPriority('general')">설정</button>
</div>
</PanelCard>
</section>
</div>
</section>
</main>
</template>
<style scoped>
:global(html),
:global(body),
:global(#app) {
min-width: 500px;
margin: 0;
background: #000;
font-family: Pretendard, 'Apple SD Gothic Neo', 'Noto Sans KR', 'Malgun Gothic', sans-serif;
font-size: 14px;
line-height: 21px;
}
:global(body:has(#npc-policy-page)) {
min-width: 500px;
line-height: 21px;
}
.npc-page {
min-height: 100vh;
padding: 24px;
display: flex;
flex-direction: column;
gap: 16px;
color: #fff;
font-family: Pretendard, 'Apple SD Gothic Neo', 'Noto Sans KR', 'Malgun Gothic', sans-serif;
font-size: 14px;
line-height: 21px;
}
.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;
.legacy-bg0 {
background-image: url('/image/game/back_walnut.jpg');
}
.page-title {
font-size: 1.6rem;
font-weight: 600;
.legacy-bg1 {
background-image: url('/image/game/back_green.jpg');
}
.page-subtitle {
font-size: 0.85rem;
color: rgba(232, 221, 196, 0.7);
.legacy-bg2 {
background-image: url('/image/game/back_blue.jpg');
}
.header-actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
.top-back-bar {
position: relative;
height: 32px;
max-width: 1000px;
margin: 0 auto;
text-align: center;
box-sizing: border-box;
}
.ghost {
border: 1px solid rgba(201, 164, 90, 0.4);
padding: 6px 12px;
font-size: 0.8rem;
cursor: pointer;
background: rgba(16, 16, 16, 0.6);
color: inherit;
.top-back-bar strong {
font-size: 24px;
line-height: 32px;
font-weight: 400;
}
.primary {
border: 1px solid rgba(201, 164, 90, 0.6);
padding: 6px 12px;
font-size: 0.8rem;
cursor: pointer;
background: rgba(201, 164, 90, 0.2);
color: inherit;
.back-button {
position: absolute;
inset: 0 auto 0 0;
width: 88px;
color: #fff;
background: #087f45;
border: 1px solid #0a9960;
border-radius: 0 0 4px;
font-weight: 700;
line-height: 30px;
text-decoration: none;
}
.error {
color: #f5b7b1;
font-size: 0.85rem;
.back-button:hover,
.back-button:focus-visible {
background: #0a9960;
outline: 2px solid #fff;
outline-offset: -2px;
}
.npc-layout {
display: flex;
flex-direction: column;
gap: 16px;
.policy-container,
.page-state {
width: 100%;
max-width: 1000px;
margin: 0 auto;
border: 1px solid #888;
box-sizing: border-box;
}
.setter {
font-size: 0.75rem;
color: rgba(232, 221, 196, 0.6);
margin-bottom: 8px;
.page-state {
padding: 16px;
min-height: 100px;
}
.readonly-note {
font-size: 0.75rem;
color: rgba(245, 208, 138, 0.8);
margin-bottom: 8px;
.page-state button {
margin-left: 12px;
}
.policy-section {
margin-top: 12px;
.section_bar {
min-height: 23px;
border: 0.5px solid #aaa;
box-sizing: border-box;
text-align: center;
}
.section-title {
font-size: 0.95rem;
margin-bottom: 8px;
color: rgba(232, 221, 196, 0.9);
.setter,
.priority-meta {
min-height: 21px;
padding: 0 12px;
color: #8e8e8e;
font-size: 12.25px;
line-height: 18.375px;
text-align: right;
box-sizing: border-box;
}
.policy-grid {
.feedback {
margin: 4px 12px;
padding: 5px 10px;
border: 1px solid;
border-radius: 4px;
}
.error-feedback,
.error-state {
color: #ffd4d4;
border-color: #a94442;
background-color: rgba(120, 20, 20, 0.75);
}
.notice-feedback {
color: #d9ffd9;
border-color: #3c763d;
background-color: rgba(20, 90, 20, 0.7);
}
.form_list {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
gap: 12px;
grid-template-columns: repeat(2, minmax(0, 1fr));
margin: 8px;
}
.policy-field {
border: 1px solid rgba(201, 164, 90, 0.2);
background: rgba(16, 16, 16, 0.5);
padding: 10px;
display: flex;
flex-direction: column;
gap: 6px;
min-width: 0;
padding: 0 10.5px;
box-sizing: border-box;
}
.field-label {
font-size: 0.8rem;
font-weight: 600;
}
.field-input {
background: rgba(12, 12, 12, 0.8);
border: 1px solid rgba(201, 164, 90, 0.3);
color: inherit;
padding: 6px 8px;
font-size: 0.8rem;
font-family: inherit;
}
.field-desc {
font-size: 0.7rem;
color: rgba(232, 221, 196, 0.6);
}
.field-hint {
font-size: 0.7rem;
color: rgba(232, 221, 196, 0.45);
white-space: pre-line;
}
.control-bar {
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: 8px;
margin-top: 12px;
}
.btn-group {
display: flex;
gap: 8px;
}
.priority-grid {
.field-row {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
gap: 16px;
grid-template-columns: minmax(0, 1fr) 224px;
align-items: center;
min-height: 34px;
}
.field-row label {
min-width: 0;
}
.field-row input {
width: 224px;
height: 34px;
padding: 5.25px 10.5px;
color: #303030;
background: #ddd;
border: 1px solid #000;
border-radius: 4px;
box-sizing: border-box;
font: inherit;
}
.field-row input:focus {
border-color: #66afe9;
outline: 2px solid rgba(102, 175, 233, 0.7);
}
.policy-field p {
min-height: 18.375px;
margin: 0;
color: #888;
font-size: 12.25px;
line-height: 18.375px;
text-align: right;
}
.work-in-progress {
margin: 0 11px 15px;
padding: 14px;
color: #fff;
background: #444;
border: 1px solid #444;
border-radius: 4px;
}
.control_bar {
display: flex;
justify-content: flex-end;
padding: 0 10.6667px 10.6667px;
min-height: 56.8125px;
box-sizing: border-box;
}
.button-group {
display: flex;
}
.control_bar button {
width: 150px;
height: 35.5px;
margin-top: 10.6667px;
padding: 5.25px 10.5px;
color: #fff;
border: 1px solid;
font: inherit;
cursor: pointer;
}
.reset_btn {
background: #303030;
border-color: #2b2b2b !important;
border-radius: 4px 0 0 4px;
}
.revert_btn {
background: #444;
border-color: #3d3d3d !important;
border-radius: 0 4px 4px 0;
}
.submit_btn {
margin-left: 14px;
background: #375a7f;
border-color: #325172 !important;
border-radius: 4px;
}
.control_bar button:hover {
filter: brightness(1.15);
}
.control_bar button:focus-visible,
.help-button:focus-visible {
outline: 2px solid #fff;
outline-offset: -2px;
}
.priority-sections {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.priority-panel {
min-width: 0;
}
.half_section_left {
border-right: 0.5px solid #aaa;
}
.priority-meta {
float: right;
}
.priority-description {
clear: both;
min-height: 42px;
padding: 0 8px;
color: #888;
box-sizing: border-box;
}
.priority-description small {
font-size: 12.25px;
line-height: 18.375px;
}
.priority-columns {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
gap: 12px;
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.priority-column {
border: 1px solid rgba(201, 164, 90, 0.2);
padding: 8px;
background: rgba(12, 12, 12, 0.5);
min-width: 0;
}
.column-title {
font-size: 0.8rem;
margin-bottom: 6px;
color: rgba(232, 221, 196, 0.7);
.sub_bar {
height: 22px;
margin: 0 5px;
border: 0.5px solid #aaa;
text-align: center;
box-sizing: border-box;
}
.priority-list {
display: flex;
min-height: 37px;
margin: 0 10px;
flex-direction: column;
gap: 6px;
}
.inactive-header,
.priority-item {
height: 37px;
padding: 7px 14px;
border: 1px solid #444;
box-sizing: border-box;
}
.inactive-header {
color: #1d1d1d;
background: #d6d6d6;
}
.priority-item {
border: 1px solid rgba(201, 164, 90, 0.2);
padding: 6px;
display: flex;
flex-direction: column;
gap: 6px;
background: rgba(16, 16, 16, 0.6);
color: #fff;
background: #303030;
cursor: grab;
}
.priority-main {
display: flex;
.priority-item:active {
cursor: grabbing;
opacity: 0.8;
}
.priority_info {
display: grid;
height: 21px;
grid-template-columns: 24px minmax(0, 1fr) 24px;
align-items: center;
gap: 6px;
}
.priority-name {
font-size: 0.78rem;
.drag-handle {
font-size: 18px;
}
.priority-actions {
display: flex;
gap: 6px;
flex-wrap: wrap;
}
.priority-help {
.help-button {
position: relative;
display: inline-flex;
align-items: center;
justify-content: center;
width: 18px;
height: 18px;
font-size: 0.7rem;
border-radius: 999px;
border: 1px solid rgba(201, 164, 90, 0.4);
cursor: default;
width: 24px;
height: 22.375px;
padding: 0 3.5px;
color: #fff;
background: #444;
border: 1px solid #3d3d3d;
border-radius: 3px;
font-size: 12.25px;
line-height: 18.375px;
cursor: pointer;
}
.priority-help::after {
content: attr(data-text);
.help-button::after {
position: absolute;
bottom: 125%;
left: 50%;
transform: translateX(-50%);
background: rgba(16, 16, 16, 0.9);
border: 1px solid rgba(201, 164, 90, 0.4);
padding: 8px;
font-size: 0.7rem;
width: 220px;
right: 0;
bottom: calc(100% + 5px);
z-index: 10;
width: 300px;
padding: 7px;
color: #fff;
background: #111;
border: 1px solid #777;
border-radius: 4px;
content: attr(data-text);
font-size: 12px;
line-height: 18px;
text-align: left;
white-space: pre-line;
opacity: 0;
pointer-events: none;
transition: opacity 0.2s ease;
z-index: 10;
transition: opacity 0.15s ease;
}
.priority-help:hover::after {
.help-button:hover::after,
.help-button:focus-visible::after {
opacity: 1;
}
@media (max-width: 1024px) {
.npc-page {
padding: 16px;
.priority-control {
margin-top: 0;
}
@media (max-width: 991px) {
.form_list,
.priority-sections {
grid-template-columns: 1fr;
}
.half_section_left {
border-right: 0;
}
}
</style>
+18 -1
View File
@@ -57,8 +57,9 @@ storage, route guards, and image loading.
| survey | `hwe/v_vote.php`, `hwe/ts/PageVote.vue` | 1000/500px fixed container, blue title/green table textures, list/detail/results/comments, selection/focus/hover, submit and retained-selection API error |
| nation personnel | `hwe/b_myBossInfo.php` | fixed 1000px document at both viewports, chief icon columns, officer/permission/city/kick controls, role redaction |
| nation finance | `hwe/v_nationStratFinan.php` | 1000/500px at the legacy 940px breakpoint, exact diplomacy grid, policy controls, role gating and failed-mutation rollback |
| NPC policy | `hwe/v_NPCControl.php` | 1000/500px form and priority-list geometry, walnut/green textures, dynamic zero hints, drag/focus/tooltip, successful save and permission failures |
| tournament | `hwe/b_tournament.php` | fixed 2000px canvas, 16×125px bracket, eight 250px group tables, walnut texture, 1024px overflow, hover/focus |
| tournament betting | `hwe/b_betting.php` | fixed 1120px canvas, 16×70px candidates, four 280px rank tables, exact title/button geometry, retained selection on error |
| tournament betting | `hwe/b_betting.php` | fixed 1120px canvas, 16×70px candidates, four 280px rank tables, exact title/button geometry, retained selection on error |
The global game baseline is black, white, Pretendard 14px. Legacy texture
helpers intentionally follow `common.orig.css`: `bg0` is walnut, `bg1` is
@@ -96,6 +97,22 @@ reference collection, `tools/frontend-legacy-parity/reference-nation-offices.mjs
records desktop/500px computed DOM and screenshots from the PHP service without
changing its product code.
The NPC policy suite and its reference collector can be run independently:
```sh
PLAYWRIGHT_FRONTEND_PORT=15126 \
pnpm --filter @sammo-ts/game-frontend test:e2e:npc-policy
REF_PARITY_USER=refuser1 \
REF_PARITY_PASSWORD_FILE=/path/to/password-file \
REF_PARITY_BASE_URL=http://127.0.0.1:3400/sam/ \
node tools/frontend-legacy-parity/reference-npc-policy.mjs
```
The collector writes desktop and 500px screenshots plus computed DOM JSON only
when `REF_PARITY_ARTIFACT_DIR` is set. It requires an existing reference general
owned by the supplied account and never accepts a password on the command line.
For a review run that also writes full-page screenshots, create an ignored
artifact directory and set `FRONTEND_PARITY_ARTIFACT_DIR` before invoking the
suite. The ordinary CI run does not write screenshots after successful tests.
@@ -0,0 +1,117 @@
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_PARITY_URL ?? 'http://127.0.0.1:3400/sam/';
const username = process.env.REF_PARITY_USER ?? 'refadmin';
const passwordFile = process.env.REF_PARITY_PASSWORD_FILE;
const artifactRoot = resolve(process.env.REF_PARITY_ARTIFACT_DIR ?? 'test-results/reference-npc-policy');
if (!passwordFile) {
throw new Error('REF_PARITY_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 browser = await chromium.launch({ headless: true });
try {
const result = {};
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();
await login(context, page);
await page.goto(new URL('hwe/', baseUrl).toString(), { waitUntil: 'networkidle' });
await page.goto(new URL('hwe/v_NPCControl.php', baseUrl).toString(), { waitUntil: 'networkidle' });
try {
await page.locator('#container').waitFor({ timeout: 10_000 });
} catch {
throw new Error(
`Reference NPC policy failed to mount: ${JSON.stringify({
url: page.url(),
text: (await page.locator('body').innerText()).slice(0, 500),
})}`
);
}
result[viewport.name] = await page.evaluate(() => {
const measure = (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: {
display: style.display,
gridTemplateColumns: style.gridTemplateColumns,
fontFamily: style.fontFamily,
fontSize: style.fontSize,
lineHeight: style.lineHeight,
color: style.color,
backgroundColor: style.backgroundColor,
backgroundImage: style.backgroundImage,
borderColor: style.borderColor,
padding: style.padding,
margin: style.margin,
cursor: style.cursor,
},
};
};
return {
body: measure('body'),
container: measure('#container'),
topBackBar: measure('body > :first-child'),
sectionBar: measure('.section_bar'),
formList: measure('.form_list'),
firstField: measure('.form_list > .col'),
firstInput: measure('input[type="number"]'),
firstInfoButton: measure('.form_list button'),
controlBar: measure('.control_bar'),
resetButton: measure('.reset_btn'),
submitButton: measure('.submit_btn'),
priorityGrid: measure('.half_section_left'),
priorityColumn: measure('.priority-list'),
priorityItem: measure('.priority-list .list-group-item'),
helpButton: measure('.priority_info button'),
document: {
width: document.documentElement.scrollWidth,
height: document.documentElement.scrollHeight,
},
};
});
await page.screenshot({
path: resolve(artifactRoot, `ref-npc-policy-${viewport.name}.png`),
fullPage: true,
});
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();
}