merge: refresh degrade relations parity branch
This commit is contained in:
@@ -1,12 +1,11 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import { parseUnitSetDefinition, type UnitSetDefinition } from '@sammo-ts/logic';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
const REPO_ROOT = path.resolve(__dirname, '..', '..', '..', '..');
|
||||
import { resolveWorkspaceRoot } from '../paths.js';
|
||||
|
||||
const REPO_ROOT = resolveWorkspaceRoot();
|
||||
const DEFAULT_UNIT_SET_ROOT = path.resolve(REPO_ROOT, 'resources', 'unitset');
|
||||
|
||||
export interface UnitSetLoaderOptions {
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const hasWorkspaceMarker = (dir: string): boolean => fs.existsSync(path.join(dir, 'pnpm-workspace.yaml'));
|
||||
|
||||
export const resolveWorkspaceRoot = (
|
||||
startDir: string = process.env.GAME_WORKSPACE_ROOT ?? process.env.GATEWAY_WORKSPACE_ROOT ?? process.cwd(),
|
||||
maxDepth = 6
|
||||
): string => {
|
||||
let current = path.resolve(startDir);
|
||||
for (let depth = 0; depth <= maxDepth; depth += 1) {
|
||||
if (hasWorkspaceMarker(current)) return current;
|
||||
const parent = path.dirname(current);
|
||||
if (parent === current) break;
|
||||
current = parent;
|
||||
}
|
||||
return path.resolve(startDir);
|
||||
};
|
||||
@@ -1,8 +1,16 @@
|
||||
import { TRPCError } from '@trpc/server';
|
||||
import { z } from 'zod';
|
||||
import { ITEM_KEYS, loadItemModules } from '@sammo-ts/logic';
|
||||
|
||||
import { authedProcedure, router } from '../../trpc.js';
|
||||
import { buildBattleSimEnvironment } from '../../battleSim/environment.js';
|
||||
import { loadBattleSimTraitOptions } from '../../battleSim/simulatorOptions.js';
|
||||
import { buildTurnCommandTable } from '../../turns/commandTable.js';
|
||||
import {
|
||||
parseReservedTurnArgs,
|
||||
TURN_COMMAND_NATION_COLORS,
|
||||
type TurnCommandInputOptions,
|
||||
} from '../../turns/commandInput.js';
|
||||
import {
|
||||
MAX_GENERAL_TURNS,
|
||||
MAX_NATION_TURNS,
|
||||
@@ -25,6 +33,18 @@ const buildShiftAmountSchema = (maxTurns: number) =>
|
||||
message: 'Amount must be non-zero.',
|
||||
});
|
||||
|
||||
const parseCommandArgs = async (scope: 'general' | 'nation', action: string, args: unknown) => {
|
||||
try {
|
||||
return await parseReservedTurnArgs(scope, action, args);
|
||||
} catch (error) {
|
||||
throw new TRPCError({
|
||||
code: 'BAD_REQUEST',
|
||||
message: error instanceof Error ? error.message : 'Invalid turn command arguments.',
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const turnsRouter = router({
|
||||
getCommandTable: authedProcedure
|
||||
.input(
|
||||
@@ -45,7 +65,8 @@ export const turnsRouter = router({
|
||||
});
|
||||
}
|
||||
|
||||
const [city, nation, nationGenerals] = await Promise.all([
|
||||
const [city, nation, nationGenerals, cities, nations, generals, environment, traits, itemModules] =
|
||||
await Promise.all([
|
||||
general.cityId > 0
|
||||
? ctx.db.city.findUnique({
|
||||
where: { id: general.cityId },
|
||||
@@ -61,14 +82,76 @@ export const turnsRouter = router({
|
||||
where: { nationId: general.nationId },
|
||||
})
|
||||
: Promise.resolve(null),
|
||||
ctx.db.city.findMany({
|
||||
select: { id: true, name: true, nationId: true },
|
||||
orderBy: { id: 'asc' },
|
||||
}),
|
||||
ctx.db.nation.findMany({
|
||||
select: { id: true, name: true, color: true },
|
||||
orderBy: { id: 'asc' },
|
||||
}),
|
||||
ctx.db.general.findMany({
|
||||
where: { npcState: { lt: 2 } },
|
||||
select: { id: true, name: true, nationId: true, cityId: true },
|
||||
orderBy: { id: 'asc' },
|
||||
}),
|
||||
buildBattleSimEnvironment(worldState, ctx.profile.id),
|
||||
loadBattleSimTraitOptions(),
|
||||
loadItemModules([...ITEM_KEYS]),
|
||||
]);
|
||||
|
||||
const nationById = new Map(nations.map((entry) => [entry.id, entry]));
|
||||
const cityById = new Map(cities.map((entry) => [entry.id, entry]));
|
||||
const items: TurnCommandInputOptions['items'] = {
|
||||
horse: [{ value: 'None', label: '판매/해제' }],
|
||||
weapon: [{ value: 'None', label: '판매/해제' }],
|
||||
book: [{ value: 'None', label: '판매/해제' }],
|
||||
item: [{ value: 'None', label: '판매/해제' }],
|
||||
};
|
||||
for (const item of itemModules) {
|
||||
if (item.buyable) {
|
||||
items[item.slot].push({ value: item.key, label: item.name });
|
||||
}
|
||||
}
|
||||
const inputOptions: TurnCommandInputOptions = {
|
||||
cities: cities.map((entry) => ({
|
||||
value: entry.id,
|
||||
label: `${entry.name} (${nationById.get(entry.nationId)?.name ?? '무주'})`,
|
||||
})),
|
||||
nations: nations.map((entry) => ({
|
||||
value: entry.id,
|
||||
label: entry.name,
|
||||
color: entry.color,
|
||||
})),
|
||||
generals: generals.map((entry) => ({
|
||||
value: entry.id,
|
||||
label: `${entry.name} (${nationById.get(entry.nationId)?.name ?? '무소속'} · ${
|
||||
cityById.get(entry.cityId)?.name ?? '재야'
|
||||
})`,
|
||||
})),
|
||||
crewTypes: (environment.unitSet.crewTypes ?? [])
|
||||
.filter((entry) => !entry.requirements.some((requirement) => requirement.type === 'Impossible'))
|
||||
.map((entry) => ({ value: entry.id, label: entry.name })),
|
||||
armTypes: Object.entries(environment.unitSet.armTypes ?? {}).map(([value, label]) => ({
|
||||
value: Number(value),
|
||||
label,
|
||||
})),
|
||||
nationTypes: traits.nationTypes.map((entry) => ({ value: entry.key, label: entry.name })),
|
||||
colors: TURN_COMMAND_NATION_COLORS.map((color, index) => ({
|
||||
value: index,
|
||||
label: `색상 ${index + 1}`,
|
||||
color,
|
||||
})),
|
||||
items,
|
||||
};
|
||||
|
||||
return buildTurnCommandTable({
|
||||
worldState,
|
||||
general,
|
||||
city,
|
||||
nation,
|
||||
nationGenerals,
|
||||
inputOptions,
|
||||
});
|
||||
}),
|
||||
reserved: router({
|
||||
@@ -121,13 +204,14 @@ export const turnsRouter = router({
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await getOwnedGeneral(ctx, input.generalId);
|
||||
const args = await parseCommandArgs('general', input.action, input.args);
|
||||
|
||||
const turns = await setGeneralTurn(
|
||||
ctx.db,
|
||||
input.generalId,
|
||||
input.turnIndex,
|
||||
input.action,
|
||||
input.args
|
||||
args
|
||||
);
|
||||
return { ok: true, turns };
|
||||
}),
|
||||
@@ -171,6 +255,7 @@ export const turnsRouter = router({
|
||||
message: 'General is not an officer.',
|
||||
});
|
||||
}
|
||||
const args = await parseCommandArgs('nation', input.action, input.args);
|
||||
|
||||
const turns = await setNationTurn(
|
||||
ctx.db,
|
||||
@@ -178,7 +263,7 @@ export const turnsRouter = router({
|
||||
general.officerLevel,
|
||||
input.turnIndex,
|
||||
input.action,
|
||||
input.args
|
||||
args
|
||||
);
|
||||
return { ok: true, turns };
|
||||
}),
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
import {
|
||||
loadGeneralTurnCommandSpecs,
|
||||
loadNationTurnCommandSpecs,
|
||||
type GeneralTurnCommandSpec,
|
||||
type NationTurnCommandSpec,
|
||||
} from '@sammo-ts/logic';
|
||||
import { asRecord, isRecord } from '@sammo-ts/common';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { loadTurnCommandProfile } from './turnCommandProfile.js';
|
||||
|
||||
export type TurnCommandOptionValue = string | number;
|
||||
|
||||
export interface TurnCommandOption {
|
||||
value: TurnCommandOptionValue;
|
||||
label: string;
|
||||
color?: string;
|
||||
}
|
||||
|
||||
export type TurnCommandOptionSource =
|
||||
| 'cities'
|
||||
| 'nations'
|
||||
| 'generals'
|
||||
| 'crewTypes'
|
||||
| 'armTypes'
|
||||
| 'nationTypes'
|
||||
| 'colors'
|
||||
| 'items';
|
||||
|
||||
export interface TurnCommandInputField {
|
||||
key: string;
|
||||
label: string;
|
||||
kind: 'text' | 'number' | 'boolean' | 'select' | 'numberTuple' | 'hidden';
|
||||
required: boolean;
|
||||
min?: number;
|
||||
max?: number;
|
||||
step?: number;
|
||||
constValue?: TurnCommandOptionValue;
|
||||
options?: TurnCommandOption[];
|
||||
optionSource?: TurnCommandOptionSource;
|
||||
tupleLabels?: string[];
|
||||
}
|
||||
|
||||
export interface TurnCommandInputOptions {
|
||||
cities: TurnCommandOption[];
|
||||
nations: TurnCommandOption[];
|
||||
generals: TurnCommandOption[];
|
||||
crewTypes: TurnCommandOption[];
|
||||
armTypes: TurnCommandOption[];
|
||||
nationTypes: TurnCommandOption[];
|
||||
colors: TurnCommandOption[];
|
||||
items: Record<string, TurnCommandOption[]>;
|
||||
}
|
||||
|
||||
// 레거시 및 명령 실행 모듈의 인덱스 순서와 동일해야 한다.
|
||||
export const TURN_COMMAND_NATION_COLORS = [
|
||||
'#FF0000', '#800000', '#A0522D', '#FF6347', '#FFA500', '#FFDAB9', '#FFD700', '#FFFF00',
|
||||
'#7CFC00', '#00FF00', '#808000', '#008000', '#2E8B57', '#008080', '#20B2AA', '#6495ED',
|
||||
'#7FFFD4', '#AFEEEE', '#87CEEB', '#00FFFF', '#00BFFF', '#0000FF', '#000080', '#483D8B',
|
||||
'#7B68EE', '#BA55D3', '#800080', '#FF00FF', '#FFC0CB', '#F5F5DC', '#E0FFFF', '#FFFFFF',
|
||||
'#A9A9A9',
|
||||
] as const;
|
||||
|
||||
const FIELD_LABELS: Record<string, string> = {
|
||||
destCityId: '대상 도시',
|
||||
destCityID: '대상 도시',
|
||||
destGeneralId: '대상 장수',
|
||||
destGeneralID: '대상 장수',
|
||||
destNationId: '대상 국가',
|
||||
nationName: '국가명',
|
||||
nationType: '국가 성향',
|
||||
colorType: '국기 색상',
|
||||
srcArmType: '기존 병과',
|
||||
destArmType: '변경 병과',
|
||||
itemType: '장비 종류',
|
||||
itemCode: '장비',
|
||||
crewType: '병종',
|
||||
amount: '수량',
|
||||
buyRice: '거래',
|
||||
isGold: '물자',
|
||||
optionText: '행동',
|
||||
year: '기간(년)',
|
||||
month: '기간(월)',
|
||||
commandType: '대응 명령',
|
||||
amountList: '지원 물자',
|
||||
};
|
||||
|
||||
const OPTION_SOURCES: Record<string, TurnCommandOptionSource> = {
|
||||
destCityId: 'cities',
|
||||
destCityID: 'cities',
|
||||
destGeneralId: 'generals',
|
||||
destGeneralID: 'generals',
|
||||
destNationId: 'nations',
|
||||
nationType: 'nationTypes',
|
||||
colorType: 'colors',
|
||||
srcArmType: 'armTypes',
|
||||
destArmType: 'armTypes',
|
||||
itemCode: 'items',
|
||||
crewType: 'crewTypes',
|
||||
};
|
||||
|
||||
const STATIC_LABELS: Record<string, Record<string, string>> = {
|
||||
itemType: {
|
||||
horse: '명마',
|
||||
weapon: '무기',
|
||||
book: '서적',
|
||||
item: '도구',
|
||||
},
|
||||
commandType: {
|
||||
che_선전포고: '선전포고',
|
||||
che_불가침제의: '불가침 제의',
|
||||
che_불가침파기제의: '불가침 파기 제의',
|
||||
che_종전제의: '종전 제의',
|
||||
},
|
||||
};
|
||||
|
||||
type JsonSchema = Record<string, unknown>;
|
||||
|
||||
const collectObjectSchema = (schema: JsonSchema): JsonSchema => {
|
||||
const branches = schema.oneOf ?? schema.anyOf;
|
||||
if (Array.isArray(branches)) {
|
||||
const objectBranches = branches.filter(isRecord).map((branch) => collectObjectSchema(branch));
|
||||
const properties = Object.assign({}, ...objectBranches.map((branch) => asRecord(branch.properties)));
|
||||
const required = Array.from(
|
||||
new Set(
|
||||
objectBranches.flatMap((branch) =>
|
||||
Array.isArray(branch.required)
|
||||
? branch.required.filter((entry): entry is string => typeof entry === 'string')
|
||||
: []
|
||||
)
|
||||
)
|
||||
);
|
||||
return { ...schema, properties, required };
|
||||
}
|
||||
return schema;
|
||||
};
|
||||
|
||||
const enumOptions = (fieldKey: string, values: unknown[]): TurnCommandOption[] =>
|
||||
values
|
||||
.filter((value): value is TurnCommandOptionValue => typeof value === 'string' || typeof value === 'number')
|
||||
.filter((value) => fieldKey !== 'commandType' || value !== 'che_피장파장')
|
||||
.map((value) => ({
|
||||
value,
|
||||
label: STATIC_LABELS[fieldKey]?.[String(value)] ?? String(value),
|
||||
}));
|
||||
|
||||
const buildField = (key: string, rawSchema: unknown, required: boolean): TurnCommandInputField => {
|
||||
const schema = asRecord(rawSchema);
|
||||
const label = FIELD_LABELS[key] ?? key;
|
||||
const constValue = schema.const;
|
||||
if (typeof constValue === 'string' || typeof constValue === 'number') {
|
||||
return { key, label, kind: 'hidden', required, constValue };
|
||||
}
|
||||
|
||||
if (key === 'amountList') {
|
||||
return {
|
||||
key,
|
||||
label,
|
||||
kind: 'numberTuple',
|
||||
required,
|
||||
tupleLabels: ['금', '쌀'],
|
||||
min: 0,
|
||||
step: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const optionSource = OPTION_SOURCES[key];
|
||||
const enumValues = Array.isArray(schema.enum) ? enumOptions(key, schema.enum) : undefined;
|
||||
if (optionSource || enumValues) {
|
||||
return {
|
||||
key,
|
||||
label,
|
||||
kind: 'select',
|
||||
required,
|
||||
optionSource,
|
||||
options: enumValues,
|
||||
};
|
||||
}
|
||||
|
||||
if (schema.type === 'boolean') {
|
||||
return { key, label, kind: 'boolean', required };
|
||||
}
|
||||
if (schema.type === 'number' || schema.type === 'integer') {
|
||||
return {
|
||||
key,
|
||||
label,
|
||||
kind: 'number',
|
||||
required,
|
||||
min: typeof schema.minimum === 'number' ? schema.minimum : undefined,
|
||||
max: typeof schema.maximum === 'number' ? schema.maximum : undefined,
|
||||
step: schema.type === 'integer' ? 1 : undefined,
|
||||
};
|
||||
}
|
||||
if (schema.type === 'string') {
|
||||
return {
|
||||
key,
|
||||
label,
|
||||
kind: 'text',
|
||||
required,
|
||||
min: typeof schema.minLength === 'number' ? schema.minLength : undefined,
|
||||
max: typeof schema.maxLength === 'number' ? schema.maxLength : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
throw new Error(`Unsupported turn command argument schema: ${key}`);
|
||||
};
|
||||
|
||||
export const buildTurnCommandInputFields = (
|
||||
spec: GeneralTurnCommandSpec | NationTurnCommandSpec
|
||||
): TurnCommandInputField[] => {
|
||||
if (!spec.reqArg) {
|
||||
return [];
|
||||
}
|
||||
const jsonSchema = collectObjectSchema(asRecord(z.toJSONSchema(spec.argsSchema)));
|
||||
const properties = asRecord(jsonSchema.properties);
|
||||
const required = new Set(
|
||||
Array.isArray(jsonSchema.required)
|
||||
? jsonSchema.required.filter((entry): entry is string => typeof entry === 'string')
|
||||
: []
|
||||
);
|
||||
return Object.entries(properties).map(([key, schema]) => buildField(key, schema, required.has(key)));
|
||||
};
|
||||
|
||||
export const loadTurnCommandSpecs = async () => {
|
||||
const profile = await loadTurnCommandProfile();
|
||||
const [general, nation] = await Promise.all([
|
||||
loadGeneralTurnCommandSpecs(profile.general),
|
||||
loadNationTurnCommandSpecs(profile.nation),
|
||||
]);
|
||||
return { general, nation };
|
||||
};
|
||||
|
||||
export const parseReservedTurnArgs = async (
|
||||
scope: 'general' | 'nation',
|
||||
action: string,
|
||||
rawArgs: unknown
|
||||
): Promise<Record<string, unknown>> => {
|
||||
const specs = await loadTurnCommandSpecs();
|
||||
const spec = specs[scope].find((entry) => entry.key === action);
|
||||
if (!spec) {
|
||||
throw new Error(`Unknown ${scope} turn command: ${action}`);
|
||||
}
|
||||
if (!spec.reqArg) {
|
||||
return {};
|
||||
}
|
||||
return spec.argsSchema.parse(rawArgs);
|
||||
};
|
||||
@@ -13,12 +13,17 @@ import type {
|
||||
TurnCommandEnv,
|
||||
TriggerValue,
|
||||
} from '@sammo-ts/logic';
|
||||
import { evaluateConstraints, loadGeneralTurnCommandSpecs, loadNationTurnCommandSpecs } from '@sammo-ts/logic';
|
||||
import { evaluateConstraints } from '@sammo-ts/logic';
|
||||
import { projectItemSlots, readItemInventoryFromMeta } from '@sammo-ts/logic/items/index.js';
|
||||
import { asRecord, isRecord } from '@sammo-ts/common';
|
||||
|
||||
import type { CityRow, GeneralRow, NationRow, WorldStateRow } from '../context.js';
|
||||
import { loadTurnCommandProfile } from './turnCommandProfile.js';
|
||||
import {
|
||||
buildTurnCommandInputFields,
|
||||
loadTurnCommandSpecs,
|
||||
type TurnCommandInputField,
|
||||
type TurnCommandInputOptions,
|
||||
} from './commandInput.js';
|
||||
|
||||
type AvailabilityStatus = 'available' | 'blocked' | 'needsInput' | 'unknown';
|
||||
|
||||
@@ -29,6 +34,7 @@ export interface TurnCommandAvailability {
|
||||
possible: boolean;
|
||||
status: AvailabilityStatus;
|
||||
reason?: string;
|
||||
inputFields: TurnCommandInputField[];
|
||||
}
|
||||
|
||||
export interface TurnCommandGroup {
|
||||
@@ -39,6 +45,7 @@ export interface TurnCommandGroup {
|
||||
export interface TurnCommandTable {
|
||||
general: TurnCommandGroup[];
|
||||
nation: TurnCommandGroup[];
|
||||
inputOptions: TurnCommandInputOptions;
|
||||
}
|
||||
|
||||
type CommandEnv = TurnCommandEnv;
|
||||
@@ -54,6 +61,7 @@ interface CommandEntry {
|
||||
definition: GeneralActionDefinition;
|
||||
reqArg: boolean;
|
||||
availabilityArgs: Readonly<Record<string, unknown>>;
|
||||
inputFields: TurnCommandInputField[];
|
||||
evaluate?: (ctx: ConstraintContext, view: StateView) => AvailabilityCore;
|
||||
}
|
||||
|
||||
@@ -410,6 +418,7 @@ const buildEntries = (env: CommandEnv, specs: TurnCommandSpec[]): CommandEntry[]
|
||||
definition,
|
||||
reqArg: spec.reqArg,
|
||||
availabilityArgs: spec.reqArg ? spec.availabilityArgs : {},
|
||||
inputFields: buildTurnCommandInputFields(spec),
|
||||
};
|
||||
|
||||
if (spec.key === 'che_포상') {
|
||||
@@ -445,6 +454,7 @@ const buildGroups = (entries: CommandEntry[], ctx: ConstraintContext, view: Stat
|
||||
key: entry.definition.key,
|
||||
name: entry.definition.name,
|
||||
reqArg: entry.reqArg,
|
||||
inputFields: entry.inputFields,
|
||||
...availability,
|
||||
};
|
||||
|
||||
@@ -468,6 +478,7 @@ export const buildTurnCommandTable = async (options: {
|
||||
city: CityRow | null;
|
||||
nation: NationRow | null;
|
||||
nationGenerals: GeneralRow[] | null;
|
||||
inputOptions?: TurnCommandInputOptions;
|
||||
}): Promise<TurnCommandTable> => {
|
||||
// 턴 입력 화면에서 쓰는 사전 판단이므로 최소 정보로 가능/불가만 계산한다.
|
||||
const general = mapGeneralRow(options.general);
|
||||
@@ -486,16 +497,22 @@ export const buildTurnCommandTable = async (options: {
|
||||
};
|
||||
|
||||
const env = buildCommandEnv(options.worldState);
|
||||
const commandProfile = await loadTurnCommandProfile();
|
||||
const [generalSpecs, nationSpecs] = await Promise.all([
|
||||
loadGeneralTurnCommandSpecs(commandProfile.general),
|
||||
loadNationTurnCommandSpecs(commandProfile.nation),
|
||||
]);
|
||||
const { general: generalSpecs, nation: nationSpecs } = await loadTurnCommandSpecs();
|
||||
const generalEntries = buildEntries(env, generalSpecs);
|
||||
const nationEntries = buildEntries(env, nationSpecs);
|
||||
|
||||
return {
|
||||
general: buildGroups(generalEntries, ctx, view),
|
||||
nation: buildGroups(nationEntries, ctx, view),
|
||||
inputOptions: options.inputOptions ?? {
|
||||
cities: [],
|
||||
nations: [],
|
||||
generals: [],
|
||||
crewTypes: [],
|
||||
armTypes: [],
|
||||
nationTypes: [],
|
||||
colors: [],
|
||||
items: {},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import { DEFAULT_TURN_COMMAND_PROFILE, parseTurnCommandProfile, type TurnCommandProfile } from '@sammo-ts/logic';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
const REPO_ROOT = path.resolve(__dirname, '..', '..', '..', '..');
|
||||
import { resolveWorkspaceRoot } from '../paths.js';
|
||||
|
||||
const REPO_ROOT = resolveWorkspaceRoot();
|
||||
const DEFAULT_PROFILE_PATH = path.resolve(REPO_ROOT, 'resources', 'turn-commands', 'default.json');
|
||||
|
||||
export interface TurnCommandProfileOptions {
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import {
|
||||
GENERAL_TURN_COMMAND_KEYS,
|
||||
NATION_TURN_COMMAND_KEYS,
|
||||
loadGeneralTurnCommandSpecs,
|
||||
loadNationTurnCommandSpecs,
|
||||
} from '@sammo-ts/logic';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import {
|
||||
buildTurnCommandInputFields,
|
||||
parseReservedTurnArgs,
|
||||
} from '../src/turns/commandInput.js';
|
||||
|
||||
describe('turn command argument input', () => {
|
||||
it('builds supported fields for every argument-bearing command module', async () => {
|
||||
const [general, nation] = await Promise.all([
|
||||
loadGeneralTurnCommandSpecs([...GENERAL_TURN_COMMAND_KEYS]),
|
||||
loadNationTurnCommandSpecs([...NATION_TURN_COMMAND_KEYS]),
|
||||
]);
|
||||
const argumentSpecs = [...general, ...nation].filter((spec) => spec.reqArg);
|
||||
const fields = argumentSpecs.map((spec) => ({
|
||||
key: spec.key,
|
||||
fields: buildTurnCommandInputFields(spec),
|
||||
}));
|
||||
|
||||
expect(argumentSpecs).toHaveLength(44);
|
||||
expect(fields.every((entry) => entry.fields.length > 0)).toBe(true);
|
||||
expect(fields.find((entry) => entry.key === 'che_화계')?.fields).toMatchObject([
|
||||
{ key: 'destCityId', kind: 'select', optionSource: 'cities' },
|
||||
]);
|
||||
expect(fields.find((entry) => entry.key === 'che_물자원조')?.fields).toMatchObject([
|
||||
{ key: 'destNationId', kind: 'select', optionSource: 'nations' },
|
||||
{ key: 'amountList', kind: 'numberTuple' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('normalizes valid arguments and rejects malformed or wrong-scope commands', async () => {
|
||||
await expect(parseReservedTurnArgs('general', 'che_화계', { destCityId: 7 })).resolves.toEqual({
|
||||
destCityId: 7,
|
||||
});
|
||||
await expect(parseReservedTurnArgs('general', 'che_화계', { destCityId: '7' })).rejects.toBeDefined();
|
||||
await expect(
|
||||
parseReservedTurnArgs('nation', 'che_포상', {
|
||||
isGold: true,
|
||||
amount: 200,
|
||||
destGeneralId: 7,
|
||||
})
|
||||
).resolves.toEqual({
|
||||
isGold: true,
|
||||
amount: 200,
|
||||
destGeneralId: 7,
|
||||
});
|
||||
await expect(parseReservedTurnArgs('general', 'che_포상', {})).rejects.toThrow(
|
||||
'Unknown general turn command'
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -77,6 +77,8 @@ const buildContext = (options?: {
|
||||
general?: GeneralRow | null;
|
||||
generalTurns?: GeneralTurnRow[];
|
||||
nationTurns?: NationTurnRow[];
|
||||
generalTurnWrites?: unknown[];
|
||||
nationTurnWrites?: unknown[];
|
||||
auth?: GameSessionTokenPayload | null;
|
||||
}): GameApiContext => {
|
||||
const transport = options?.transport ?? new InMemoryTurnDaemonTransport();
|
||||
@@ -105,7 +107,10 @@ const buildContext = (options?: {
|
||||
findMany: async ({ where }: { where: { generalId: number } }) =>
|
||||
generalTurns.filter((row) => row.generalId === where.generalId),
|
||||
deleteMany: async () => ({}),
|
||||
createMany: async () => ({}),
|
||||
createMany: async (args: unknown) => {
|
||||
options?.generalTurnWrites?.push(args);
|
||||
return {};
|
||||
},
|
||||
},
|
||||
nationTurn: {
|
||||
findMany: async ({ where }: { where: { nationId: number; officerLevel: number } }) =>
|
||||
@@ -113,7 +118,10 @@ const buildContext = (options?: {
|
||||
(row) => row.nationId === where.nationId && row.officerLevel === where.officerLevel
|
||||
),
|
||||
deleteMany: async () => ({}),
|
||||
createMany: async () => ({}),
|
||||
createMany: async (args: unknown) => {
|
||||
options?.nationTurnWrites?.push(args);
|
||||
return {};
|
||||
},
|
||||
},
|
||||
};
|
||||
const accessTokenStore = new RedisAccessTokenStore(
|
||||
@@ -281,6 +289,59 @@ describe('appRouter', () => {
|
||||
expect(response[0]?.index).toBe(0);
|
||||
});
|
||||
|
||||
it('validates and persists general command arguments from the authenticated owner', async () => {
|
||||
const general = buildGeneralRow({ id: 13 });
|
||||
const writes: unknown[] = [];
|
||||
const caller = appRouter.createCaller(buildContext({ general, generalTurnWrites: writes }));
|
||||
|
||||
const response = await caller.turns.reserved.setGeneral({
|
||||
generalId: 13,
|
||||
turnIndex: 0,
|
||||
action: 'che_화계',
|
||||
args: { destCityId: 7 },
|
||||
});
|
||||
|
||||
expect(response.turns[0]).toMatchObject({ action: 'che_화계', args: { destCityId: 7 } });
|
||||
expect(writes).toHaveLength(1);
|
||||
const written = writes[0] as { data: unknown[] };
|
||||
expect(written.data).toHaveLength(30);
|
||||
expect(written.data[0]).toMatchObject({
|
||||
generalId: 13,
|
||||
turnIdx: 0,
|
||||
actionCode: 'che_화계',
|
||||
arg: { destCityId: 7 },
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects malformed and cross-scope arguments without writing turns', async () => {
|
||||
const general = buildGeneralRow({ id: 14, nationId: 3, officerLevel: 5 });
|
||||
const generalWrites: unknown[] = [];
|
||||
const nationWrites: unknown[] = [];
|
||||
const caller = appRouter.createCaller(
|
||||
buildContext({ general, generalTurnWrites: generalWrites, nationTurnWrites: nationWrites })
|
||||
);
|
||||
|
||||
await expect(
|
||||
caller.turns.reserved.setGeneral({
|
||||
generalId: 14,
|
||||
turnIndex: 0,
|
||||
action: 'che_화계',
|
||||
args: { destCityId: '7' },
|
||||
})
|
||||
).rejects.toMatchObject({ code: 'BAD_REQUEST' });
|
||||
await expect(
|
||||
caller.turns.reserved.setGeneral({
|
||||
generalId: 14,
|
||||
turnIndex: 0,
|
||||
action: 'che_포상',
|
||||
args: { isGold: true, amount: 1, destGeneralId: 7 },
|
||||
})
|
||||
).rejects.toMatchObject({ code: 'BAD_REQUEST' });
|
||||
|
||||
expect(generalWrites).toHaveLength(0);
|
||||
expect(nationWrites).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('rejects another user general across actor-owned routers', async () => {
|
||||
const general = buildGeneralRow({ id: 15, userId: 'user-2' });
|
||||
const caller = appRouter.createCaller(buildContext({ general }));
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
import { expect, test, type Page, type Route } from '@playwright/test';
|
||||
|
||||
const response = (data: unknown) => ({ result: { data } });
|
||||
const errorResponse = (path: string, message: string) => ({
|
||||
error: {
|
||||
message,
|
||||
code: -32000,
|
||||
data: { code: 'BAD_REQUEST', httpStatus: 400, path },
|
||||
},
|
||||
});
|
||||
const operations = (route: Route) =>
|
||||
decodeURIComponent(new URL(route.request().url()).pathname.split('/trpc/')[1] ?? '').split(',');
|
||||
|
||||
const inputOptions = {
|
||||
cities: [
|
||||
{ value: 1, label: '업 (아국)' },
|
||||
{ value: 2, label: '허창 (적국)' },
|
||||
],
|
||||
nations: [
|
||||
{ value: 1, label: '아국', color: '#008000' },
|
||||
{ value: 2, label: '적국', color: '#800000' },
|
||||
],
|
||||
generals: [
|
||||
{ value: 1, label: '장수 (아국 · 업)' },
|
||||
{ value: 2, label: '관우 (아국 · 업)' },
|
||||
],
|
||||
crewTypes: [{ value: 1100, label: '보병' }],
|
||||
armTypes: [{ value: 1, label: '보병' }],
|
||||
nationTypes: [{ value: 'che_중립', label: '중립' }],
|
||||
colors: [{ value: 0, label: '색상 1', color: '#ff0000' }],
|
||||
items: { horse: [{ value: 'None', label: '판매/해제' }] },
|
||||
};
|
||||
const commandTable = {
|
||||
general: [{
|
||||
category: '군사',
|
||||
values: [{
|
||||
key: 'che_화계',
|
||||
name: '화계',
|
||||
reqArg: true,
|
||||
possible: true,
|
||||
status: 'needsInput',
|
||||
inputFields: [{
|
||||
key: 'destCityId',
|
||||
label: '대상 도시',
|
||||
kind: 'select',
|
||||
required: true,
|
||||
optionSource: 'cities',
|
||||
}],
|
||||
}],
|
||||
}],
|
||||
nation: [{
|
||||
category: '인사',
|
||||
values: [{
|
||||
key: 'che_포상',
|
||||
name: '포상',
|
||||
reqArg: true,
|
||||
possible: true,
|
||||
status: 'needsInput',
|
||||
inputFields: [
|
||||
{ key: 'isGold', label: '물자', kind: 'boolean', required: true },
|
||||
{ key: 'amount', label: '수량', kind: 'number', required: true, min: 0, step: 1 },
|
||||
{
|
||||
key: 'destGeneralId',
|
||||
label: '대상 장수',
|
||||
kind: 'select',
|
||||
required: true,
|
||||
optionSource: 'generals',
|
||||
},
|
||||
],
|
||||
}],
|
||||
}],
|
||||
inputOptions,
|
||||
};
|
||||
const generalContext = {
|
||||
general: {
|
||||
id: 1, name: '장수', nationId: 1, cityId: 1, officerLevel: 5, npcState: 0, troopId: 0,
|
||||
picture: null, imageServer: 0, stats: { leadership: 70, strength: 60, intelligence: 50 },
|
||||
gold: 1000, rice: 1000, crew: 500, train: 90, atmos: 90, injury: 0, experience: 0,
|
||||
dedication: 0, items: { horse: 'None', weapon: 'None', book: 'None', item: 'None' },
|
||||
},
|
||||
city: { id: 1, name: '업', level: 8, region: 1, population: 1000, populationMax: 2000 },
|
||||
nation: { id: 1, name: '아국', color: '#008000', level: 1 },
|
||||
settings: {},
|
||||
penalties: {},
|
||||
};
|
||||
const turns = (count: number) =>
|
||||
Array.from({ length: count }, (_, index) => ({ index, action: '휴식', args: {} }));
|
||||
|
||||
const install = async (page: Page, rejectGeneral = false) => {
|
||||
const requests: unknown[] = [];
|
||||
await page.addInitScript(() => {
|
||||
localStorage.setItem('sammo-game-token', 'ga_commands');
|
||||
localStorage.setItem('sammo-game-profile', 'che:default');
|
||||
});
|
||||
await page.route('**/image/**', (route) => route.fulfill({ status: 404, body: '' }));
|
||||
await page.route('**/che/api/trpc/**', async (route) => {
|
||||
const names = operations(route);
|
||||
const body = route.request().postDataJSON();
|
||||
const results = names.map((name) => {
|
||||
if (name === 'general.me') return response(generalContext);
|
||||
if (name === 'world.getMapLayout') return response({
|
||||
mapName: 'che',
|
||||
cityList: [{ id: 1, name: '업', level: 8, region: 1, x: 100, y: 100, path: [] }],
|
||||
regionMap: { 1: '하북' },
|
||||
levelMap: { 8: '특' },
|
||||
});
|
||||
if (name === 'lobby.info') return response({
|
||||
myGeneral: { id: 1, name: '장수' },
|
||||
year: 200, month: 1, turnTerm: 10, userCnt: 1, maxUserCnt: 100, npcCnt: 0, nationCnt: 2,
|
||||
});
|
||||
if (name === 'join.getConfig') return response({});
|
||||
if (name === 'world.getMap') return response({
|
||||
result: true, version: 0, startYear: 180, year: 200, month: 1,
|
||||
cityList: [[1, 8, 0, 1, 1, 1]], nationList: [[1, '아국', '#008000', 1]],
|
||||
spyList: {}, shownByGeneralList: [], myCity: 1, myNation: 1,
|
||||
});
|
||||
if (name === 'turns.getCommandTable') return response(commandTable);
|
||||
if (name === 'turns.reserved.getGeneral') return response(turns(30));
|
||||
if (name === 'turns.reserved.getNation') return response(turns(12));
|
||||
if (name === 'messages.getRecent') return response({
|
||||
private: [], national: [], public: [], diplomacy: [], sequence: -1,
|
||||
hasMore: { private: false, national: false, public: false, diplomacy: false },
|
||||
latestRead: { private: 0, diplomacy: 0 },
|
||||
canRespondDiplomacy: false,
|
||||
});
|
||||
if (name === 'messages.getContacts') return response({ nation: [] });
|
||||
if (name === 'board.getAccess') return response({ canMeeting: false, canSecret: false });
|
||||
if (name === 'tournament.getState') return response({ stage: 0 });
|
||||
if (name === 'turns.reserved.setGeneral') {
|
||||
requests.push(body);
|
||||
return rejectGeneral
|
||||
? errorResponse(name, '대상 도시를 선택할 수 없습니다.')
|
||||
: response({ ok: true, turns: [{ index: 0, action: 'che_화계', args: { destCityId: 2 } }] });
|
||||
}
|
||||
if (name === 'turns.reserved.setNation') {
|
||||
requests.push(body);
|
||||
return response({
|
||||
ok: true,
|
||||
turns: [{ index: 0, action: 'che_포상', args: { isGold: false, amount: 300, destGeneralId: 2 } }],
|
||||
});
|
||||
}
|
||||
return errorResponse(name, `unhandled ${name}`);
|
||||
});
|
||||
await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(results) });
|
||||
});
|
||||
return requests;
|
||||
};
|
||||
|
||||
test('enters general and nation command arguments and sends exact values', async ({ page }) => {
|
||||
const requests = await install(page);
|
||||
await page.goto('/');
|
||||
|
||||
await page.getByRole('button', { name: /화계/ }).click();
|
||||
const form = page.getByTestId('command-argument-form');
|
||||
await expect(form).toBeVisible();
|
||||
await form.locator('select').selectOption('2');
|
||||
const generalSection = page.locator('.reserved-section').filter({ hasText: '일반 예턴' });
|
||||
await generalSection.getByRole('button', { name: '배치' }).first().click();
|
||||
await expect(generalSection.locator('.turn-action').first()).toHaveText('che_화계');
|
||||
|
||||
await page.getByRole('button', { name: '국가:인사' }).click();
|
||||
await page.getByRole('button', { name: /포상/ }).click();
|
||||
await form.getByRole('button', { name: '쌀' }).click();
|
||||
await form.locator('input[type=number]').fill('300');
|
||||
await form.locator('select').selectOption('2');
|
||||
const nationSection = page.locator('.reserved-section').filter({ hasText: '국가 예턴' });
|
||||
await nationSection.getByRole('button', { name: '배치' }).first().click();
|
||||
await expect(nationSection.locator('.turn-action').first()).toHaveText('che_포상');
|
||||
|
||||
expect(JSON.stringify(requests)).toContain('"destCityId":2');
|
||||
expect(JSON.stringify(requests)).toContain('"isGold":false');
|
||||
expect(JSON.stringify(requests)).toContain('"amount":300');
|
||||
expect(JSON.stringify(requests)).toContain('"destGeneralId":2');
|
||||
|
||||
const geometry = await form.evaluate((element) => {
|
||||
const row = element.querySelector('.argument-row');
|
||||
const rect = element.getBoundingClientRect();
|
||||
const style = getComputedStyle(element);
|
||||
return {
|
||||
width: rect.width,
|
||||
rowHeight: row?.getBoundingClientRect().height ?? 0,
|
||||
borderStyle: style.borderStyle,
|
||||
fontSize: style.fontSize,
|
||||
};
|
||||
});
|
||||
expect(geometry.width).toBeGreaterThan(250);
|
||||
expect(geometry.rowHeight).toBeGreaterThanOrEqual(34);
|
||||
expect(geometry.borderStyle).toBe('solid');
|
||||
expect(geometry.fontSize).toBe('10.5px');
|
||||
});
|
||||
|
||||
test('keeps the entered command visible and reports a server validation error', async ({ page }) => {
|
||||
await install(page, true);
|
||||
await page.goto('/');
|
||||
await page.getByRole('button', { name: /화계/ }).click();
|
||||
await page.getByTestId('command-argument-form').locator('select').selectOption('2');
|
||||
await page.locator('.reserved-section').filter({ hasText: '일반 예턴' })
|
||||
.getByRole('button', { name: '배치' }).first().click();
|
||||
|
||||
await expect(page.locator('.error')).toContainText('대상 도시를 선택할 수 없습니다.');
|
||||
await expect(page.getByTestId('command-argument-form').locator('select')).toHaveValue('2');
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
|
||||
import type { AppRouter as GatewayAppRouter } from '@sammo-ts/gateway-api';
|
||||
import type { AppRouter as GameAppRouter } from '@sammo-ts/game-api';
|
||||
import { expect, test } from '@playwright/test';
|
||||
|
||||
const gatewayUrl = process.env.COMMAND_LIVE_GATEWAY_URL ?? 'http://127.0.0.1:13160/trpc';
|
||||
const gameUrl = process.env.COMMAND_LIVE_GAME_URL ?? 'http://127.0.0.1:14160/trpc';
|
||||
type PlainTurn = { index: number; action: string; args: Record<string, unknown> };
|
||||
|
||||
test('reserves an argument command in the real game API and reads it back from PostgreSQL', async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
test.skip(process.env.COMMAND_LIVE !== '1', 'requires the isolated live gateway/game API fixture');
|
||||
test.setTimeout(60_000);
|
||||
const gateway = createTRPCProxyClient<GatewayAppRouter>({
|
||||
links: [httpBatchLink({ url: gatewayUrl })],
|
||||
});
|
||||
const login = await gateway.auth.login.mutate({
|
||||
username: 'demo1',
|
||||
password: 'demo-pass-1',
|
||||
});
|
||||
const issued = await gateway.auth.issueGameSession.mutate({
|
||||
sessionToken: login.sessionToken,
|
||||
profile: 'che:2',
|
||||
});
|
||||
let accessToken = '';
|
||||
const game = createTRPCProxyClient<GameAppRouter>({
|
||||
links: [
|
||||
httpBatchLink({
|
||||
url: gameUrl,
|
||||
headers: () => ({ authorization: `Bearer ${accessToken}` }),
|
||||
}),
|
||||
],
|
||||
});
|
||||
accessToken = (await game.auth.exchangeGatewayToken.mutate({ gatewayToken: issued.gameToken })).accessToken;
|
||||
const context = await game.general.me.query();
|
||||
if (!context) throw new Error('demo1 general is missing');
|
||||
const generalId = context.general.id;
|
||||
const original = (
|
||||
(await game.turns.reserved.getGeneral.query({ generalId })) as unknown as PlainTurn[]
|
||||
)[29];
|
||||
const originalNation = (
|
||||
(await game.turns.reserved.getNation.query({ generalId })) as unknown as PlainTurn[]
|
||||
)[11];
|
||||
|
||||
await page.addInitScript(
|
||||
({ token }) => {
|
||||
localStorage.setItem('sammo-game-token', token);
|
||||
localStorage.setItem('sammo-game-profile', 'che:2');
|
||||
},
|
||||
{ token: accessToken }
|
||||
);
|
||||
|
||||
try {
|
||||
await page.goto('/');
|
||||
await expect(page.getByRole('heading', { name: '전장 현황' })).toBeVisible();
|
||||
await page.getByRole('button', { name: '계략', exact: true }).click();
|
||||
await page.getByRole('button', { name: /화계/ }).click();
|
||||
const form = page.getByTestId('command-argument-form');
|
||||
await expect(form).toBeVisible();
|
||||
const citySelect = form.locator('select');
|
||||
const optionValues = await citySelect.locator('option').evaluateAll((options) =>
|
||||
options.map((option) => (option as HTMLOptionElement).value)
|
||||
);
|
||||
const targetCityId = Number(optionValues.find((value) => Number(value) !== context.general.cityId));
|
||||
expect(targetCityId).toBeGreaterThan(0);
|
||||
await citySelect.selectOption(String(targetCityId));
|
||||
|
||||
const generalSection = page.locator('.reserved-section').filter({ hasText: '일반 예턴' });
|
||||
const lastTurn = generalSection.locator('.reserved-item').nth(29);
|
||||
await lastTurn.getByRole('button', { name: '배치' }).click();
|
||||
await expect(lastTurn.locator('.turn-action')).toHaveText('che_화계');
|
||||
|
||||
const persisted = (await game.turns.reserved.getGeneral.query({ generalId }))[29];
|
||||
expect(persisted).toEqual({
|
||||
index: 29,
|
||||
action: 'che_화계',
|
||||
args: { destCityId: targetCityId },
|
||||
});
|
||||
|
||||
await page.getByRole('button', { name: '국가:인사', exact: true }).click();
|
||||
await page.getByRole('button', { name: /포상/ }).click();
|
||||
await form.getByRole('button', { name: '쌀', exact: true }).click();
|
||||
await form.locator('input[type=number]').fill('1');
|
||||
const generalSelect = form.locator('select');
|
||||
const generalValues = await generalSelect.locator('option').evaluateAll((options) =>
|
||||
options.map((option) => (option as HTMLOptionElement).value)
|
||||
);
|
||||
const targetGeneralId = Number(generalValues.find((value) => Number(value) !== generalId));
|
||||
expect(targetGeneralId).toBeGreaterThan(0);
|
||||
await generalSelect.selectOption(String(targetGeneralId));
|
||||
const nationSection = page.locator('.reserved-section').filter({ hasText: '국가 예턴' });
|
||||
const lastNationTurn = nationSection.locator('.reserved-item').nth(11);
|
||||
await lastNationTurn.getByRole('button', { name: '배치' }).click();
|
||||
await expect(lastNationTurn.locator('.turn-action')).toHaveText('che_포상');
|
||||
const persistedNation = (await game.turns.reserved.getNation.query({ generalId }))[11];
|
||||
expect(persistedNation).toEqual({
|
||||
index: 11,
|
||||
action: 'che_포상',
|
||||
args: { isGold: false, amount: 1, destGeneralId: targetGeneralId },
|
||||
});
|
||||
await page.screenshot({
|
||||
path: testInfo.outputPath('real-hwe-command-reserved.png'),
|
||||
fullPage: true,
|
||||
});
|
||||
} finally {
|
||||
await game.turns.reserved.setGeneral.mutate({
|
||||
generalId,
|
||||
turnIndex: 29,
|
||||
action: original?.action ?? '휴식',
|
||||
args: original?.args ?? {},
|
||||
});
|
||||
await game.turns.reserved.setNation.mutate({
|
||||
generalId,
|
||||
turnIndex: 11,
|
||||
action: originalNation?.action ?? '휴식',
|
||||
args: originalNation?.args ?? {},
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -5,6 +5,7 @@ import { defineConfig, devices } from '@playwright/test';
|
||||
const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../../..');
|
||||
const port = Number(process.env.PLAYWRIGHT_FRONTEND_PORT ?? 15120);
|
||||
const baseURL = `http://127.0.0.1:${port}/che/`;
|
||||
const gameApiUrl = process.env.PLAYWRIGHT_GAME_API_URL ?? '/che/api/trpc';
|
||||
|
||||
export default defineConfig({
|
||||
testDir: '.',
|
||||
@@ -20,6 +21,8 @@ export default defineConfig({
|
||||
'auction.spec.ts',
|
||||
'battleSimulator.spec.ts',
|
||||
'battleSimulatorRef.spec.ts',
|
||||
'commandArguments.spec.ts',
|
||||
'commandArgumentsLive.spec.ts',
|
||||
],
|
||||
fullyParallel: false,
|
||||
workers: 1,
|
||||
@@ -41,7 +44,7 @@ export default defineConfig({
|
||||
screenshot: 'only-on-failure',
|
||||
},
|
||||
webServer: {
|
||||
command: `VITE_APP_BASE_PATH=/che VITE_GAME_API_URL=/che/api/trpc pnpm --filter @sammo-ts/game-frontend dev --host 127.0.0.1 --port ${port}`,
|
||||
command: `VITE_APP_BASE_PATH=/che VITE_GAME_API_URL=${gameApiUrl} pnpm --filter @sammo-ts/game-frontend dev --host 127.0.0.1 --port ${port}`,
|
||||
cwd: repositoryRoot,
|
||||
url: baseURL,
|
||||
reuseExistingServer: false,
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, watch } from 'vue';
|
||||
|
||||
type OptionValue = string | number;
|
||||
interface CommandOption {
|
||||
value: OptionValue;
|
||||
label: string;
|
||||
color?: string;
|
||||
}
|
||||
interface CommandInputField {
|
||||
key: string;
|
||||
label: string;
|
||||
kind: 'text' | 'number' | 'boolean' | 'select' | 'numberTuple' | 'hidden';
|
||||
required: boolean;
|
||||
min?: number;
|
||||
max?: number;
|
||||
step?: number;
|
||||
constValue?: OptionValue;
|
||||
options?: CommandOption[];
|
||||
optionSource?: 'cities' | 'nations' | 'generals' | 'crewTypes' | 'armTypes' | 'nationTypes' | 'colors' | 'items';
|
||||
tupleLabels?: string[];
|
||||
}
|
||||
interface CommandInputOptions {
|
||||
cities: CommandOption[];
|
||||
nations: CommandOption[];
|
||||
generals: CommandOption[];
|
||||
crewTypes: CommandOption[];
|
||||
armTypes: CommandOption[];
|
||||
nationTypes: CommandOption[];
|
||||
colors: CommandOption[];
|
||||
items: Record<string, CommandOption[]>;
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
commandKey: string;
|
||||
fields: CommandInputField[];
|
||||
options: CommandInputOptions;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
(event: 'update:args', args: Record<string, unknown>): void;
|
||||
(event: 'update:valid', valid: boolean): void;
|
||||
}>();
|
||||
|
||||
const values = reactive<Record<string, unknown>>({});
|
||||
|
||||
const optionsFor = (field: CommandInputField): CommandOption[] => {
|
||||
if (field.options) return field.options;
|
||||
if (!field.optionSource) return [];
|
||||
if (field.optionSource === 'items') {
|
||||
return props.options.items[String(values.itemType ?? '')] ?? [];
|
||||
}
|
||||
return props.options[field.optionSource];
|
||||
};
|
||||
|
||||
const defaultValue = (field: CommandInputField): unknown => {
|
||||
if (field.kind === 'hidden') return field.constValue;
|
||||
if (field.kind === 'boolean') return true;
|
||||
if (field.kind === 'numberTuple') return [field.min ?? 0, field.min ?? 0];
|
||||
if (field.kind === 'number') return field.min ?? 0;
|
||||
if (field.kind === 'select') return optionsFor(field)[0]?.value ?? '';
|
||||
return '';
|
||||
};
|
||||
|
||||
const initialize = () => {
|
||||
for (const key of Object.keys(values)) delete values[key];
|
||||
for (const field of props.fields) values[field.key] = defaultValue(field);
|
||||
const itemCodeField = props.fields.find((field) => field.key === 'itemCode');
|
||||
if (itemCodeField) values.itemCode = defaultValue(itemCodeField);
|
||||
};
|
||||
|
||||
const setSelectValue = (field: CommandInputField, rawValue: string) => {
|
||||
const option = optionsFor(field).find((entry) => String(entry.value) === rawValue);
|
||||
values[field.key] = option?.value ?? rawValue;
|
||||
if (field.key === 'itemType') {
|
||||
const itemField = props.fields.find((entry) => entry.key === 'itemCode');
|
||||
if (itemField) values.itemCode = defaultValue(itemField);
|
||||
}
|
||||
};
|
||||
|
||||
const setTupleValue = (field: CommandInputField, index: number, rawValue: string) => {
|
||||
const tuple = Array.isArray(values[field.key]) ? [...(values[field.key] as unknown[])] : [0, 0];
|
||||
tuple[index] = Number(rawValue);
|
||||
values[field.key] = tuple;
|
||||
};
|
||||
|
||||
const isValid = computed(() =>
|
||||
props.fields.every((field) => {
|
||||
const value = values[field.key];
|
||||
if (field.kind === 'text') {
|
||||
const length = typeof value === 'string' ? value.trim().length : 0;
|
||||
return (!field.required || length > 0) && (field.min === undefined || length >= field.min) &&
|
||||
(field.max === undefined || length <= field.max);
|
||||
}
|
||||
if (field.kind === 'number') {
|
||||
return typeof value === 'number' && Number.isFinite(value) &&
|
||||
(field.min === undefined || value >= field.min) && (field.max === undefined || value <= field.max);
|
||||
}
|
||||
if (field.kind === 'numberTuple') {
|
||||
return Array.isArray(value) && value.length === 2 &&
|
||||
value.every((entry) => typeof entry === 'number' && Number.isFinite(entry) &&
|
||||
(field.min === undefined || entry >= field.min) && (field.max === undefined || entry <= field.max));
|
||||
}
|
||||
if (field.kind === 'select') return optionsFor(field).some((option) => option.value === value);
|
||||
return value !== undefined;
|
||||
})
|
||||
);
|
||||
|
||||
watch(() => [props.commandKey, props.fields, props.options] as const, initialize, { immediate: true, deep: true });
|
||||
watch(
|
||||
() => ({ ...values }),
|
||||
() => {
|
||||
emit('update:args', { ...values });
|
||||
emit('update:valid', isValid.value);
|
||||
},
|
||||
{ immediate: true, deep: true }
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="props.fields.length" class="command-argument-form" data-testid="command-argument-form">
|
||||
<div
|
||||
v-for="field in props.fields.filter((entry) => entry.kind !== 'hidden')"
|
||||
:key="field.key"
|
||||
class="argument-row"
|
||||
>
|
||||
<label :for="`command-arg-${field.key}`">{{ field.label }}</label>
|
||||
<input
|
||||
v-if="field.kind === 'text'"
|
||||
:id="`command-arg-${field.key}`"
|
||||
:value="String(values[field.key] ?? '')"
|
||||
:minlength="field.min"
|
||||
:maxlength="field.max"
|
||||
@input="values[field.key] = ($event.target as HTMLInputElement).value"
|
||||
/>
|
||||
<input
|
||||
v-else-if="field.kind === 'number'"
|
||||
:id="`command-arg-${field.key}`"
|
||||
type="number"
|
||||
:value="Number(values[field.key] ?? 0)"
|
||||
:min="field.min"
|
||||
:max="field.max"
|
||||
:step="field.step"
|
||||
@input="values[field.key] = Number(($event.target as HTMLInputElement).value)"
|
||||
/>
|
||||
<select
|
||||
v-else-if="field.kind === 'select'"
|
||||
:id="`command-arg-${field.key}`"
|
||||
:value="String(values[field.key] ?? '')"
|
||||
@change="setSelectValue(field, ($event.target as HTMLSelectElement).value)"
|
||||
>
|
||||
<option v-for="option in optionsFor(field)" :key="String(option.value)" :value="String(option.value)">
|
||||
{{ option.label }}
|
||||
</option>
|
||||
</select>
|
||||
<div v-else-if="field.kind === 'boolean'" class="boolean-options">
|
||||
<button
|
||||
type="button"
|
||||
:class="{ selected: values[field.key] === true }"
|
||||
@click="values[field.key] = true"
|
||||
>
|
||||
{{ field.key === 'buyRice' ? '쌀 구매' : field.key === 'isGold' ? '금' : '예' }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
:class="{ selected: values[field.key] === false }"
|
||||
@click="values[field.key] = false"
|
||||
>
|
||||
{{ field.key === 'buyRice' ? '쌀 판매' : field.key === 'isGold' ? '쌀' : '아니오' }}
|
||||
</button>
|
||||
</div>
|
||||
<div v-else-if="field.kind === 'numberTuple'" class="tuple-options">
|
||||
<label v-for="(tupleLabel, index) in field.tupleLabels ?? ['1', '2']" :key="tupleLabel">
|
||||
<span>{{ tupleLabel }}</span>
|
||||
<input
|
||||
type="number"
|
||||
:value="(values[field.key] as number[] | undefined)?.[index] ?? 0"
|
||||
:min="field.min"
|
||||
:max="field.max"
|
||||
:step="field.step"
|
||||
@input="setTupleValue(field, index, ($event.target as HTMLInputElement).value)"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="!isValid" class="argument-error" role="alert">필수 입력을 확인하세요.</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.command-argument-form {
|
||||
border: 1px solid rgba(201, 164, 90, 0.35);
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.argument-row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(76px, 0.36fr) 1fr;
|
||||
min-height: 34px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.argument-row:nth-child(odd) {
|
||||
background: rgba(255, 255, 255, 0.035);
|
||||
}
|
||||
|
||||
.argument-row > label {
|
||||
padding: 6px 8px;
|
||||
color: rgba(232, 221, 196, 0.72);
|
||||
}
|
||||
|
||||
input,
|
||||
select {
|
||||
min-width: 0;
|
||||
margin: 4px 6px 4px 0;
|
||||
border: 1px solid rgba(201, 164, 90, 0.45);
|
||||
background: rgba(7, 9, 12, 0.82);
|
||||
color: #e8ddc4;
|
||||
padding: 5px 6px;
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.boolean-options,
|
||||
.tuple-options {
|
||||
display: flex;
|
||||
gap: 5px;
|
||||
padding: 4px 6px 4px 0;
|
||||
}
|
||||
|
||||
.boolean-options button {
|
||||
flex: 1;
|
||||
border: 1px solid rgba(201, 164, 90, 0.35);
|
||||
padding: 5px;
|
||||
}
|
||||
|
||||
.boolean-options button.selected {
|
||||
border-color: #c9a45a;
|
||||
background: rgba(201, 164, 90, 0.18);
|
||||
color: #f5e4bd;
|
||||
}
|
||||
|
||||
.tuple-options label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.tuple-options input {
|
||||
width: 80px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.argument-error {
|
||||
padding: 5px 8px;
|
||||
color: #ff9a8f;
|
||||
border-top: 1px solid rgba(201, 164, 90, 0.2);
|
||||
}
|
||||
</style>
|
||||
@@ -1,7 +1,26 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue';
|
||||
import CommandArgumentForm from './CommandArgumentForm.vue';
|
||||
import CommandSelectForm from './CommandSelectForm.vue';
|
||||
|
||||
interface TurnCommandOption {
|
||||
value: string | number;
|
||||
label: string;
|
||||
color?: string;
|
||||
}
|
||||
interface TurnCommandInputField {
|
||||
key: string;
|
||||
label: string;
|
||||
kind: 'text' | 'number' | 'boolean' | 'select' | 'numberTuple' | 'hidden';
|
||||
required: boolean;
|
||||
min?: number;
|
||||
max?: number;
|
||||
step?: number;
|
||||
constValue?: string | number;
|
||||
options?: TurnCommandOption[];
|
||||
optionSource?: 'cities' | 'nations' | 'generals' | 'crewTypes' | 'armTypes' | 'nationTypes' | 'colors' | 'items';
|
||||
tupleLabels?: string[];
|
||||
}
|
||||
interface TurnCommandAvailability {
|
||||
key: string;
|
||||
name: string;
|
||||
@@ -9,6 +28,7 @@ interface TurnCommandAvailability {
|
||||
status: 'available' | 'blocked' | 'needsInput' | 'unknown';
|
||||
possible: boolean;
|
||||
reason?: string;
|
||||
inputFields: TurnCommandInputField[];
|
||||
}
|
||||
|
||||
interface TurnCommandGroup {
|
||||
@@ -19,6 +39,16 @@ interface TurnCommandGroup {
|
||||
interface TurnCommandTable {
|
||||
general: TurnCommandGroup[];
|
||||
nation: TurnCommandGroup[];
|
||||
inputOptions: {
|
||||
cities: TurnCommandOption[];
|
||||
nations: TurnCommandOption[];
|
||||
generals: TurnCommandOption[];
|
||||
crewTypes: TurnCommandOption[];
|
||||
armTypes: TurnCommandOption[];
|
||||
nationTypes: TurnCommandOption[];
|
||||
colors: TurnCommandOption[];
|
||||
items: Record<string, TurnCommandOption[]>;
|
||||
};
|
||||
}
|
||||
|
||||
interface SelectedCityInfo {
|
||||
@@ -50,67 +80,74 @@ const props = defineProps<{
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
(event: 'set-general-turn', payload: { index: number; action: string }): void;
|
||||
(event: 'set-general-turn', payload: { index: number; action: string; args: Record<string, unknown> }): void;
|
||||
(event: 'shift-general-turns', amount: number): void;
|
||||
(event: 'set-nation-turn', payload: { index: number; action: string }): void;
|
||||
(event: 'set-nation-turn', payload: { index: number; action: string; args: Record<string, unknown> }): void;
|
||||
(event: 'shift-nation-turns', amount: number): void;
|
||||
}>();
|
||||
|
||||
const activeCategory = ref('');
|
||||
const selectedCommand = ref<TurnCommandAvailability | null>(null);
|
||||
const selectedScope = ref<'general' | 'nation' | null>(null);
|
||||
const commandArgs = ref<Record<string, unknown>>({});
|
||||
const commandArgsValid = ref(false);
|
||||
|
||||
const handleSelect = (commandKey: string) => {
|
||||
if (!props.commandTable) {
|
||||
selectedCommand.value = null;
|
||||
selectedScope.value = null;
|
||||
return;
|
||||
}
|
||||
const allGroups = [...props.commandTable.general, ...props.commandTable.nation];
|
||||
for (const group of allGroups) {
|
||||
const match = group.values.find((entry) => entry.key === commandKey);
|
||||
if (match) {
|
||||
selectedCommand.value = match;
|
||||
return;
|
||||
for (const scope of ['general', 'nation'] as const) {
|
||||
for (const group of props.commandTable[scope]) {
|
||||
const match = group.values.find((entry) => entry.key === commandKey);
|
||||
if (match) {
|
||||
selectedCommand.value = match;
|
||||
selectedScope.value = scope;
|
||||
commandArgs.value = {};
|
||||
commandArgsValid.value = !match.reqArg;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
selectedCommand.value = null;
|
||||
selectedScope.value = null;
|
||||
};
|
||||
|
||||
const canReserveSelected = () => {
|
||||
const canReserveSelected = (scope: 'general' | 'nation') => {
|
||||
if (!selectedCommand.value) {
|
||||
return false;
|
||||
}
|
||||
if (selectedScope.value !== scope) return false;
|
||||
if (!selectedCommand.value.possible) {
|
||||
return false;
|
||||
}
|
||||
if (selectedCommand.value.status !== 'available') {
|
||||
if (!['available', 'needsInput'].includes(selectedCommand.value.status)) {
|
||||
return false;
|
||||
}
|
||||
if (selectedCommand.value.reqArg) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
return commandArgsValid.value;
|
||||
};
|
||||
|
||||
const reserveGeneralTurn = (index: number) => {
|
||||
if (!selectedCommand.value) {
|
||||
return;
|
||||
}
|
||||
emit('set-general-turn', { index, action: selectedCommand.value.key });
|
||||
emit('set-general-turn', { index, action: selectedCommand.value.key, args: commandArgs.value });
|
||||
};
|
||||
|
||||
const reserveNationTurn = (index: number) => {
|
||||
if (!selectedCommand.value) {
|
||||
return;
|
||||
}
|
||||
emit('set-nation-turn', { index, action: selectedCommand.value.key });
|
||||
emit('set-nation-turn', { index, action: selectedCommand.value.key, args: commandArgs.value });
|
||||
};
|
||||
|
||||
const clearGeneralTurn = (index: number) => {
|
||||
emit('set-general-turn', { index, action: '휴식' });
|
||||
emit('set-general-turn', { index, action: '휴식', args: {} });
|
||||
};
|
||||
|
||||
const clearNationTurn = (index: number) => {
|
||||
emit('set-nation-turn', { index, action: '휴식' });
|
||||
emit('set-nation-turn', { index, action: '휴식', args: {} });
|
||||
};
|
||||
|
||||
const canNationReserve = () =>
|
||||
@@ -146,6 +183,14 @@ const canNationReserve = () =>
|
||||
</div>
|
||||
<div v-else class="value muted">명령을 선택하세요.</div>
|
||||
</div>
|
||||
<CommandArgumentForm
|
||||
v-if="selectedCommand?.reqArg && props.commandTable"
|
||||
:command-key="selectedCommand.key"
|
||||
:fields="selectedCommand.inputFields"
|
||||
:options="props.commandTable.inputOptions"
|
||||
@update:args="commandArgs = $event"
|
||||
@update:valid="commandArgsValid = $event"
|
||||
/>
|
||||
<div class="reserved-section">
|
||||
<div class="reserved-header">
|
||||
<span>일반 예턴</span>
|
||||
@@ -160,7 +205,7 @@ const canNationReserve = () =>
|
||||
<div class="turn-label">#{{ turn.index + 1 }}</div>
|
||||
<div class="turn-action">{{ turn.action }}</div>
|
||||
<div class="turn-buttons">
|
||||
<button :disabled="!canReserveSelected()" @click="reserveGeneralTurn(turn.index)">
|
||||
<button :disabled="!canReserveSelected('general')" @click="reserveGeneralTurn(turn.index)">
|
||||
배치
|
||||
</button>
|
||||
<button class="ghost" @click="clearGeneralTurn(turn.index)">휴식</button>
|
||||
@@ -183,7 +228,7 @@ const canNationReserve = () =>
|
||||
<div class="turn-label">#{{ turn.index + 1 }}</div>
|
||||
<div class="turn-action">{{ turn.action }}</div>
|
||||
<div class="turn-buttons">
|
||||
<button :disabled="!canReserveSelected()" @click="reserveNationTurn(turn.index)">
|
||||
<button :disabled="!canReserveSelected('nation')" @click="reserveNationTurn(turn.index)">
|
||||
배치
|
||||
</button>
|
||||
<button class="ghost" @click="clearNationTurn(turn.index)">휴식</button>
|
||||
|
||||
@@ -34,14 +34,16 @@ const emit = defineEmits<{
|
||||
|
||||
const categories = computed(() => {
|
||||
if (!props.commandTable) {
|
||||
return [] as Array<{ label: string; category: string; groupType: 'general' | 'nation' }>;
|
||||
return [] as Array<{ id: string; label: string; category: string; groupType: 'general' | 'nation' }>;
|
||||
}
|
||||
const general = props.commandTable.general.map((group) => ({
|
||||
id: `general:${group.category}`,
|
||||
label: group.category,
|
||||
category: group.category,
|
||||
groupType: 'general' as const,
|
||||
}));
|
||||
const nation = props.commandTable.nation.map((group) => ({
|
||||
id: `nation:${group.category}`,
|
||||
label: `국가:${group.category}`,
|
||||
category: group.category,
|
||||
groupType: 'nation' as const,
|
||||
@@ -54,11 +56,9 @@ const selectedGroup = computed(() => {
|
||||
if (!props.commandTable) {
|
||||
return null;
|
||||
}
|
||||
const base = props.commandTable.general.find((group) => group.category === selectedCategory.value);
|
||||
if (base) {
|
||||
return base;
|
||||
}
|
||||
return props.commandTable.nation.find((group) => group.category === selectedCategory.value) ?? null;
|
||||
const [scope, ...categoryParts] = selectedCategory.value.split(':');
|
||||
const category = categoryParts.join(':');
|
||||
return props.commandTable[scope === 'nation' ? 'nation' : 'general'].find((group) => group.category === category) ?? null;
|
||||
});
|
||||
|
||||
watch(
|
||||
@@ -77,8 +77,8 @@ watch(
|
||||
selectedCategory.value = '';
|
||||
return;
|
||||
}
|
||||
if (!list.some((item) => item.category === selectedCategory.value)) {
|
||||
selectedCategory.value = list[0].category;
|
||||
if (!list.some((item) => item.id === selectedCategory.value)) {
|
||||
selectedCategory.value = list[0].id;
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
@@ -116,9 +116,9 @@ const statusLabel = (command: CommandAvailability) => {
|
||||
<div class="category-list">
|
||||
<button
|
||||
v-for="category in categories"
|
||||
:key="category.label"
|
||||
:class="['category-btn', { active: selectedCategory === category.category }]"
|
||||
@click="selectedCategory = category.category"
|
||||
:key="category.id"
|
||||
:class="['category-btn', { active: selectedCategory === category.id }]"
|
||||
@click="selectedCategory = category.id"
|
||||
>
|
||||
{{ category.label }}
|
||||
</button>
|
||||
|
||||
@@ -426,7 +426,7 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => {
|
||||
}
|
||||
};
|
||||
|
||||
const setGeneralTurn = async (turnIndex: number, action: string) => {
|
||||
const setGeneralTurn = async (turnIndex: number, action: string, args: Record<string, unknown> = {}) => {
|
||||
const id = generalId.value;
|
||||
if (!id) {
|
||||
return;
|
||||
@@ -436,7 +436,7 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => {
|
||||
generalId: id,
|
||||
turnIndex,
|
||||
action,
|
||||
args: {},
|
||||
args,
|
||||
});
|
||||
reservedGeneralTurns.value = result.turns;
|
||||
} catch (err) {
|
||||
@@ -460,7 +460,7 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => {
|
||||
}
|
||||
};
|
||||
|
||||
const setNationTurn = async (turnIndex: number, action: string) => {
|
||||
const setNationTurn = async (turnIndex: number, action: string, args: Record<string, unknown> = {}) => {
|
||||
const id = generalId.value;
|
||||
const currentGeneral = general.value;
|
||||
if (!id || !currentGeneral) {
|
||||
@@ -474,7 +474,7 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => {
|
||||
generalId: id,
|
||||
turnIndex,
|
||||
action,
|
||||
args: {},
|
||||
args,
|
||||
});
|
||||
reservedNationTurns.value = result.turns;
|
||||
} catch (err) {
|
||||
|
||||
@@ -5,6 +5,7 @@ import { addMinutes, format } from 'date-fns';
|
||||
import PanelCard from '../components/ui/PanelCard.vue';
|
||||
import SkeletonLines from '../components/ui/SkeletonLines.vue';
|
||||
import ChiefTurnCard from '../components/chief/ChiefTurnCard.vue';
|
||||
import CommandArgumentForm from '../components/main/CommandArgumentForm.vue';
|
||||
import CommandSelectForm from '../components/main/CommandSelectForm.vue';
|
||||
import { trpc } from '../utils/trpc';
|
||||
import { formatOfficerLevelText } from '../utils/nationFormat';
|
||||
@@ -48,6 +49,19 @@ type CommandAvailability = {
|
||||
status: 'available' | 'blocked' | 'needsInput' | 'unknown';
|
||||
possible: boolean;
|
||||
reason?: string;
|
||||
inputFields: Array<{
|
||||
key: string;
|
||||
label: string;
|
||||
kind: 'text' | 'number' | 'boolean' | 'select' | 'numberTuple' | 'hidden';
|
||||
required: boolean;
|
||||
min?: number;
|
||||
max?: number;
|
||||
step?: number;
|
||||
constValue?: string | number;
|
||||
options?: Array<{ value: string | number; label: string; color?: string }>;
|
||||
optionSource?: 'cities' | 'nations' | 'generals' | 'crewTypes' | 'armTypes' | 'nationTypes' | 'colors' | 'items';
|
||||
tupleLabels?: string[];
|
||||
}>;
|
||||
};
|
||||
|
||||
type CommandGroup = {
|
||||
@@ -58,6 +72,16 @@ type CommandGroup = {
|
||||
type CommandTable = {
|
||||
general: CommandGroup[];
|
||||
nation: CommandGroup[];
|
||||
inputOptions: {
|
||||
cities: Array<{ value: string | number; label: string; color?: string }>;
|
||||
nations: Array<{ value: string | number; label: string; color?: string }>;
|
||||
generals: Array<{ value: string | number; label: string; color?: string }>;
|
||||
crewTypes: Array<{ value: string | number; label: string; color?: string }>;
|
||||
armTypes: Array<{ value: string | number; label: string; color?: string }>;
|
||||
nationTypes: Array<{ value: string | number; label: string; color?: string }>;
|
||||
colors: Array<{ value: string | number; label: string; color?: string }>;
|
||||
items: Record<string, Array<{ value: string | number; label: string; color?: string }>>;
|
||||
};
|
||||
};
|
||||
|
||||
const chiefApi = trpc as unknown as {
|
||||
@@ -89,6 +113,8 @@ const commandTable = ref<CommandTable | null>(null);
|
||||
const selectedChiefLevel = ref<number | null>(null);
|
||||
const activeCategory = ref('');
|
||||
const selectedCommandKey = ref<string | null>(null);
|
||||
const commandArgs = ref<Record<string, unknown>>({});
|
||||
const commandArgsValid = ref(false);
|
||||
|
||||
const isMobile = useMediaQuery('(max-width: 1024px)');
|
||||
|
||||
@@ -210,6 +236,11 @@ const selectedCommand = computed<CommandAvailability | null>(() => {
|
||||
return null;
|
||||
});
|
||||
|
||||
watch(selectedCommand, (command) => {
|
||||
commandArgs.value = {};
|
||||
commandArgsValid.value = Boolean(command && !command.reqArg);
|
||||
});
|
||||
|
||||
const canReserveSelected = computed(() => {
|
||||
if (!selectedCommand.value) {
|
||||
return false;
|
||||
@@ -217,10 +248,10 @@ const canReserveSelected = computed(() => {
|
||||
if (!selectedCommand.value.possible) {
|
||||
return false;
|
||||
}
|
||||
if (selectedCommand.value.status !== 'available') {
|
||||
if (!['available', 'needsInput'].includes(selectedCommand.value.status)) {
|
||||
return false;
|
||||
}
|
||||
return !selectedCommand.value.reqArg;
|
||||
return commandArgsValid.value;
|
||||
});
|
||||
|
||||
const selectedChief = computed<ChiefEntry | null>(() => {
|
||||
@@ -308,7 +339,7 @@ const reserveTurn = async (turnIndex: number) => {
|
||||
generalId: data.value.me.id,
|
||||
turnIndex,
|
||||
action: selectedCommand.value.key,
|
||||
args: {},
|
||||
args: commandArgs.value,
|
||||
});
|
||||
updateMyTurns(result.turns);
|
||||
} catch (err) {
|
||||
@@ -402,6 +433,14 @@ const shiftTurns = async (amount: number) => {
|
||||
</div>
|
||||
<div v-else class="value muted">명령을 선택하세요.</div>
|
||||
</div>
|
||||
<CommandArgumentForm
|
||||
v-if="selectedCommand?.reqArg && commandTable"
|
||||
:command-key="selectedCommand.key"
|
||||
:fields="selectedCommand.inputFields"
|
||||
:options="commandTable.inputOptions"
|
||||
@update:args="commandArgs = $event"
|
||||
@update:valid="commandArgsValid = $event"
|
||||
/>
|
||||
<div class="turn-actions">
|
||||
<button @click="shiftTurns(-1)">앞당김</button>
|
||||
<button @click="shiftTurns(1)">미루기</button>
|
||||
@@ -479,6 +518,14 @@ const shiftTurns = async (amount: number) => {
|
||||
</div>
|
||||
<div v-else class="value muted">명령을 선택하세요.</div>
|
||||
</div>
|
||||
<CommandArgumentForm
|
||||
v-if="selectedCommand?.reqArg && commandTable"
|
||||
:command-key="selectedCommand.key"
|
||||
:fields="selectedCommand.inputFields"
|
||||
:options="commandTable.inputOptions"
|
||||
@update:args="commandArgs = $event"
|
||||
@update:valid="commandArgsValid = $event"
|
||||
/>
|
||||
<div class="turn-actions">
|
||||
<button @click="shiftTurns(-1)">앞당김</button>
|
||||
<button @click="shiftTurns(1)">미루기</button>
|
||||
|
||||
@@ -60,16 +60,16 @@ const {
|
||||
realtimeLabel,
|
||||
} = storeToRefs(dashboard);
|
||||
|
||||
const reserveGeneralTurn = (payload: { index: number; action: string }) => {
|
||||
void dashboard.setGeneralTurn(payload.index, payload.action);
|
||||
const reserveGeneralTurn = (payload: { index: number; action: string; args: Record<string, unknown> }) => {
|
||||
void dashboard.setGeneralTurn(payload.index, payload.action, payload.args);
|
||||
};
|
||||
|
||||
const shiftGeneralTurns = (amount: number) => {
|
||||
void dashboard.shiftGeneralTurns(amount);
|
||||
};
|
||||
|
||||
const reserveNationTurn = (payload: { index: number; action: string }) => {
|
||||
void dashboard.setNationTurn(payload.index, payload.action);
|
||||
const reserveNationTurn = (payload: { index: number; action: string; args: Record<string, unknown> }) => {
|
||||
void dashboard.setNationTurn(payload.index, payload.action, payload.args);
|
||||
};
|
||||
|
||||
const shiftNationTurns = (amount: number) => {
|
||||
|
||||
Reference in New Issue
Block a user