merge: 최신 main을 첩보 명령 복원에 반영

This commit is contained in:
2026-08-20 16:08:06 +00:00
25 changed files with 2041 additions and 251 deletions
+13 -4
View File
@@ -4,11 +4,13 @@ import { z } from 'zod';
import { asRecord } from '@sammo-ts/common'; import { asRecord } from '@sammo-ts/common';
import { procedure, router } from '../../trpc.js'; import { procedure, router } from '../../trpc.js';
import type { LegacyEmperorRow } from '../../services/legacyArchiveStore.js';
import { import {
findLegacyEmperor, findLegacyEmperor,
findLegacyEmperors, findLegacyEmperorsByProfile,
findLegacyGeneralsForServer, findLegacyGeneralsForServer,
findLegacyNations, findLegacyNations,
isLegacyArchiveProfile,
} from '../../services/legacyArchiveStore.js'; } from '../../services/legacyArchiveStore.js';
const zDynastyDetailInput = z.object({ const zDynastyDetailInput = z.object({
@@ -65,7 +67,7 @@ const firstText = (...values: unknown[]): string => {
return ''; return '';
}; };
const legacyEmperorListEntry = (row: Awaited<ReturnType<typeof findLegacyEmperors>>[number]) => { const legacyEmperorListEntry = (row: LegacyEmperorRow) => {
const data = asRecord(row.data); const data = asRecord(row.data);
return { return {
id: Number(row.id), id: Number(row.id),
@@ -132,7 +134,9 @@ const formatNationLevel = (level: number | null): string => {
export const dynastyRouter = router({ export const dynastyRouter = router({
getList: procedure.input(zDynastyListInput).query(async ({ ctx, input }) => { getList: procedure.input(zDynastyListInput).query(async ({ ctx, input }) => {
if ((input?.source ?? 'current') === 'legacy') { if ((input?.source ?? 'current') === 'legacy') {
const rows = await findLegacyEmperors(ctx.db); const rows = isLegacyArchiveProfile(ctx.profile.id)
? await findLegacyEmperorsByProfile(ctx.db, ctx.profile.id)
: [];
return { return {
source: 'legacy' as const, source: 'legacy' as const,
current: null, current: null,
@@ -186,7 +190,12 @@ export const dynastyRouter = router({
}), }),
getDetail: procedure.input(zDynastyDetailInput).query(async ({ ctx, input }) => { getDetail: procedure.input(zDynastyDetailInput).query(async ({ ctx, input }) => {
if (input.source === 'legacy') { if (input.source === 'legacy') {
const archived = await findLegacyEmperor(ctx.db, input.emperorId); const archived = isLegacyArchiveProfile(ctx.profile.id)
? await findLegacyEmperor(ctx.db, {
id: input.emperorId,
sourceProfile: ctx.profile.id,
})
: null;
if (!archived) { if (!archived) {
throw new TRPCError({ code: 'NOT_FOUND', message: '이전 서버 왕조 정보를 찾을 수 없습니다.' }); throw new TRPCError({ code: 'NOT_FOUND', message: '이전 서버 왕조 정보를 찾을 수 없습니다.' });
} }
+5 -4
View File
@@ -13,6 +13,7 @@ import {
} from '@sammo-ts/logic'; } from '@sammo-ts/logic';
import type { InheritBuffType } from '@sammo-ts/logic'; import type { InheritBuffType } from '@sammo-ts/logic';
import { simpleSerialize } from '@sammo-ts/logic/war/utils.js'; import { simpleSerialize } from '@sammo-ts/logic/war/utils.js';
import { resolveLegacyCompatibleUniqueConfig } from '@sammo-ts/logic/rewards/legacyUniqueItemPool.js';
import { import {
appendInheritanceLog, appendInheritanceLog,
buildResetCost, buildResetCost,
@@ -74,17 +75,17 @@ const readBuffLevel = (buff: Record<string, number>, key: InheritBuffType): numb
}; };
const loadAvailableUniqueItems = async (worldState: WorldStateRow) => { const loadAvailableUniqueItems = async (worldState: WorldStateRow) => {
const configuredItems = asRecord(asRecord(worldState.config).const).allItems; const configConst = asRecord(asRecord(worldState.config).const);
const loader = new ItemLoader();
const { allItems } = await resolveLegacyCompatibleUniqueConfig(configConst, loader);
const enabledKeys: Array<Parameters<ItemLoader['load']>[0]> = []; const enabledKeys: Array<Parameters<ItemLoader['load']>[0]> = [];
for (const entries of Object.values(asRecord(configuredItems))) { for (const entries of Object.values(allItems)) {
for (const [key, amount] of Object.entries(asRecord(entries))) { for (const [key, amount] of Object.entries(asRecord(entries))) {
if (asNumber(amount, 0) !== 0 && isItemKey(key)) { if (asNumber(amount, 0) !== 0 && isItemKey(key)) {
enabledKeys.push(key); enabledKeys.push(key);
} }
} }
} }
const loader = new ItemLoader();
const items = await Promise.all( const items = await Promise.all(
[...new Set(enabledKeys)].map(async (key) => { [...new Set(enabledKeys)].map(async (key) => {
const item = await loader.load(key); const item = await loader.load(key);
@@ -270,7 +270,26 @@ export const findLegacyEmperors = async (
`); `);
}; };
export const findLegacyEmperor = async (db: LegacyArchiveDatabase, id: number): Promise<LegacyEmperorRow | null> => { export const findLegacyEmperorsByProfile = async (
db: LegacyArchiveDatabase,
sourceProfile: LegacyArchiveProfile
): Promise<LegacyEmperorRow[]> =>
db.$queryRaw<LegacyEmperorRow[]>(GamePrisma.sql`
SELECT
"id",
"source_profile" AS "sourceProfile",
"legacy_id" AS "legacyId",
"server_id" AS "serverId",
"data"
FROM "legacy_archive"."emperor"
WHERE "source_profile" = ${sourceProfile}
ORDER BY "id" DESC
`);
export const findLegacyEmperor = async (
db: LegacyArchiveDatabase,
input: { id: number; sourceProfile: LegacyArchiveProfile }
): Promise<LegacyEmperorRow | null> => {
const rows = await db.$queryRaw<LegacyEmperorRow[]>(GamePrisma.sql` const rows = await db.$queryRaw<LegacyEmperorRow[]>(GamePrisma.sql`
SELECT SELECT
"id", "id",
@@ -279,7 +298,8 @@ export const findLegacyEmperor = async (db: LegacyArchiveDatabase, id: number):
"server_id" AS "serverId", "server_id" AS "serverId",
"data" "data"
FROM "legacy_archive"."emperor" FROM "legacy_archive"."emperor"
WHERE "id" = ${id} WHERE "id" = ${input.id}
AND "source_profile" = ${input.sourceProfile}
LIMIT 1 LIMIT 1
`); `);
return rows[0] ?? null; return rows[0] ?? null;
+43 -17
View File
@@ -120,20 +120,24 @@ const authFor = (userId: string, roles: string[] = []): GameSessionTokenPayload
const buildContext = ( const buildContext = (
auth: GameSessionTokenPayload | null, auth: GameSessionTokenPayload | null,
oldNations: Array<Record<string, unknown>> = [oldNation, deletedOldNation] oldNations: Array<Record<string, unknown>> = [oldNation, deletedOldNation],
profileId = profile.id
): GameApiContext => { ): GameApiContext => {
const selectedProfile = { ...profile, id: profileId, name: `${profileId}:default` };
const db = { const db = {
$queryRaw: async (query: { strings?: readonly string[] }) => { $queryRaw: async (query: { strings?: readonly string[]; values?: unknown[] }) => {
const sql = query.strings?.join(' ') ?? ''; const sql = query.strings?.join(' ') ?? '';
if (sql.includes('legacy_archive"."emperor')) { if (sql.includes('legacy_archive"."emperor')) {
if (!query.values?.includes(selectedProfile.id)) return [];
if (sql.includes('WHERE "id"') && !query.values.includes(101)) return [];
return [ return [
{ {
id: 101n, id: 101n,
sourceProfile: 'hwe', sourceProfile: selectedProfile.id,
legacyId: 7, legacyId: 7,
serverId: emperor.serverId, serverId: emperor.serverId,
data: { data: {
phase: '이전 훼2기', phase: `이전 ${selectedProfile.id.toUpperCase()} 2기`,
nation_count: emperor.nationCount, nation_count: emperor.nationCount,
nation_name: emperor.nationName, nation_name: emperor.nationName,
nation_hist: emperor.nationHist, nation_hist: emperor.nationHist,
@@ -170,9 +174,10 @@ const buildContext = (
]; ];
} }
if (sql.includes('legacy_archive"."nation')) { if (sql.includes('legacy_archive"."nation')) {
if (!query.values?.includes(selectedProfile.id)) return [];
return [ return [
{ {
sourceProfile: 'hwe', sourceProfile: selectedProfile.id,
legacyId: oldNation.id, legacyId: oldNation.id,
serverId: oldNation.serverId, serverId: oldNation.serverId,
nation: oldNation.nation, nation: oldNation.nation,
@@ -182,6 +187,7 @@ const buildContext = (
]; ];
} }
if (sql.includes('legacy_archive"."general')) { if (sql.includes('legacy_archive"."general')) {
if (!query.values?.includes(selectedProfile.id)) return [];
return [ return [
{ generalNo: 11, name: '유비', lastYearMonth: 21504 }, { generalNo: 11, name: '유비', lastYearMonth: 21504 },
{ generalNo: 12, name: '제갈량', lastYearMonth: 21504 }, { generalNo: 12, name: '제갈량', lastYearMonth: 21504 },
@@ -217,13 +223,13 @@ const buildContext = (
db: db as unknown as DatabaseClient, db: db as unknown as DatabaseClient,
turnDaemon: new InMemoryTurnDaemonTransport(), turnDaemon: new InMemoryTurnDaemonTransport(),
battleSim: new InMemoryBattleSimTransport(), battleSim: new InMemoryBattleSimTransport(),
profile, profile: selectedProfile,
auth, auth,
uploadDir: 'uploads', uploadDir: 'uploads',
uploadPath: '/uploads', uploadPath: '/uploads',
uploadPublicUrl: null, uploadPublicUrl: null,
redis, redis,
accessTokenStore: new RedisAccessTokenStore(redis, profile.name), accessTokenStore: new RedisAccessTokenStore(redis, selectedProfile.name),
flushStore: new InMemoryFlushStore(), flushStore: new InMemoryFlushStore(),
gameTokenSecret: 'test-secret', gameTokenSecret: 'test-secret',
}; };
@@ -252,27 +258,31 @@ describe('dynasty public read model', () => {
]); ]);
}); });
it('reads previous-server dynasties only when the archive source is selected', async () => { it('scopes previous-server dynasties and detail to the request profile', async () => {
const caller = appRouter.createCaller(buildContext(null)); const cheCaller = appRouter.createCaller(buildContext(null));
const list = await caller.dynasty.getList({ source: 'legacy' }); const cheList = await cheCaller.dynasty.getList({ source: 'legacy' });
expect(list).toMatchObject({ expect(cheList).toMatchObject({
source: 'legacy', source: 'legacy',
current: null, current: null,
entries: [ entries: [
expect.objectContaining({ expect.objectContaining({
id: 101, id: 101,
source: 'legacy', source: 'legacy',
sourceProfile: 'hwe', sourceProfile: 'che',
phase: '이전 2기', phase: '이전 CHE 2기',
}), }),
], ],
}); });
const detail = await caller.dynasty.getDetail({ emperorId: 101, source: 'legacy' }); const staleListInput = { source: 'legacy' as const, sourceProfile: 'hwe' as const };
expect(detail).toMatchObject({ const staleList = await cheCaller.dynasty.getList(staleListInput);
expect(staleList.entries.map((entry) => entry.sourceProfile)).toEqual(['che']);
const cheDetail = await cheCaller.dynasty.getDetail({ emperorId: 101, source: 'legacy' });
expect(cheDetail).toMatchObject({
source: 'legacy', source: 'legacy',
sourceProfile: 'hwe', sourceProfile: 'che',
emperor: expect.objectContaining({ id: 101, phase: '이전 2기', name: '촉' }), emperor: expect.objectContaining({ id: 101, phase: '이전 CHE 2기', name: '촉' }),
nations: [ nations: [
expect.objectContaining({ expect.objectContaining({
name: '촉', name: '촉',
@@ -283,6 +293,22 @@ describe('dynasty public read model', () => {
}), }),
], ],
}); });
const staleDetailInput = { emperorId: 101, source: 'legacy' as const, sourceProfile: 'hwe' as const };
const staleDetail = await cheCaller.dynasty.getDetail(staleDetailInput);
expect(staleDetail.sourceProfile).toBe('che');
const hweCaller = appRouter.createCaller(buildContext(null, undefined, 'hwe'));
const hweList = await hweCaller.dynasty.getList({ source: 'legacy' });
expect(hweList.entries).toEqual([expect.objectContaining({ sourceProfile: 'hwe', phase: '이전 HWE 2기' })]);
const hweDetail = await hweCaller.dynasty.getDetail({ emperorId: 101, source: 'legacy' });
expect(hweDetail.sourceProfile).toBe('hwe');
const developmentCaller = appRouter.createCaller(buildContext(null, undefined, 'development'));
await expect(developmentCaller.dynasty.getList({ source: 'legacy' })).resolves.toMatchObject({ entries: [] });
await expect(developmentCaller.dynasty.getDetail({ emperorId: 101, source: 'legacy' })).rejects.toMatchObject({
code: 'NOT_FOUND',
});
}); });
it('exposes the same public DTO to anonymous, general owners and admins', async () => { it('exposes the same public DTO to anonymous, general owners and admins', async () => {
+27 -1
View File
@@ -97,6 +97,7 @@ const buildContext = (options: {
target?: GeneralRow | null; target?: GeneralRow | null;
inheritancePoint?: number; inheritancePoint?: number;
inheritanceLogs?: Array<{ id: number; year: number; month: number; text: string; createdAt: Date }>; inheritanceLogs?: Array<{ id: number; year: number; month: number; text: string; createdAt: Date }>;
configConst?: Record<string, unknown>;
}) => { }) => {
const auth = options.auth === undefined ? buildAuth() : options.auth; const auth = options.auth === undefined ? buildAuth() : options.auth;
const general = options.general === undefined ? buildGeneral() : options.general; const general = options.general === undefined ? buildGeneral() : options.general;
@@ -113,10 +114,19 @@ const buildContext = (options: {
const logCreate = vi.fn(async () => ({})); const logCreate = vi.fn(async () => ({}));
const findMany = vi.fn(async () => (target ? [{ id: target.id, name: target.name }] : [])); const findMany = vi.fn(async () => (target ? [{ id: target.id, name: target.name }] : []));
const inheritanceLogFindMany = vi.fn(async () => options.inheritanceLogs ?? []); const inheritanceLogFindMany = vi.fn(async () => options.inheritanceLogs ?? []);
const activeWorldState =
options.configConst === undefined
? worldState
: {
...worldState,
config: {
const: options.configConst,
},
};
const db = { const db = {
$queryRaw: vi.fn(async () => [{ value: options.inheritancePoint ?? 10_000 }]), $queryRaw: vi.fn(async () => [{ value: options.inheritancePoint ?? 10_000 }]),
worldState: { worldState: {
findFirst: vi.fn(async () => worldState), findFirst: vi.fn(async () => activeWorldState),
}, },
general: { general: {
findFirst: vi.fn(async ({ where }: { where: { userId: string } }) => findFirst: vi.fn(async ({ where }: { where: { userId: string } }) =>
@@ -192,6 +202,22 @@ describe('inherit router actor and permission boundaries', () => {
}); });
}); });
it.each([{}, { allItems: '{}' }])(
'restores selectable Ref default uniques for a legacy scenario config: %j',
async (configConst) => {
const fixture = buildContext({ configConst });
const status = await appRouter.createCaller(fixture.context).inherit.getStatus();
expect(status.availableUnique.length).toBeGreaterThan(80);
expect(status.availableUnique).toEqual(
expect.arrayContaining([
expect.objectContaining({ key: 'che_무기_12_칠성검', rawName: '칠성검' }),
expect.objectContaining({ key: 'che_서적_07_논어', rawName: '논어' }),
])
);
}
);
it('loads the first inheritance-log page without an out-of-range integer cursor', async () => { it('loads the first inheritance-log page without an out-of-range integer cursor', async () => {
const createdAt = new Date('2026-07-26T00:00:00Z'); const createdAt = new Date('2026-07-26T00:00:00Z');
const fixture = buildContext({ const fixture = buildContext({
+72
View File
@@ -1,6 +1,7 @@
import { randomUUID } from 'node:crypto'; import { randomUUID } from 'node:crypto';
import { createGamePostgresConnector, GamePrisma, type GamePrismaClient } from '@sammo-ts/infra'; import { createGamePostgresConnector, GamePrisma, type GamePrismaClient } from '@sammo-ts/infra';
import { isItemKey, ItemLoader } from '@sammo-ts/logic';
import type { TurnDaemonCommand, TurnDaemonCommandResult } from '../lifecycle/types.js'; import type { TurnDaemonCommand, TurnDaemonCommandResult } from '../lifecycle/types.js';
import type { InMemoryTurnWorld } from '../turn/inMemoryWorld.js'; import type { InMemoryTurnWorld } from '../turn/inMemoryWorld.js';
@@ -23,6 +24,7 @@ const MIN_EXTENSION_MINUTES_PER_BID = 1;
interface AuctionRow { interface AuctionRow {
id: number; id: number;
type: AuctionType; type: AuctionType;
targetCode: string | null;
hostGeneralId: number; hostGeneralId: number;
detail: unknown; detail: unknown;
status: AuctionStatus; status: AuctionStatus;
@@ -99,6 +101,7 @@ const loadAuction = async (prisma: QueryClient, auctionId: number): Promise<Auct
GamePrisma.sql` GamePrisma.sql`
SELECT id, SELECT id,
type, type,
target_code as "targetCode",
host_general_id as "hostGeneralId", host_general_id as "hostGeneralId",
detail, detail,
status, status,
@@ -178,6 +181,7 @@ export const createAuctionBidder = async (options: {
await connector.connect(); await connector.connect();
const prisma = connector.prisma; const prisma = connector.prisma;
const world = options.world; const world = options.world;
const itemLoader = new ItemLoader();
return { return {
bid: async (command, commandDb): Promise<TurnDaemonCommandResult> => { bid: async (command, commandDb): Promise<TurnDaemonCommandResult> => {
@@ -290,6 +294,74 @@ export const createAuctionBidder = async (options: {
reason: '장수 정보를 찾을 수 없습니다.', reason: '장수 정보를 찾을 수 없습니다.',
}; };
} }
if (auction.type === 'UNIQUE_ITEM') {
const itemKey = auction.targetCode;
if (!itemKey || !isItemKey(itemKey)) {
return {
type: 'auctionBid',
ok: false,
auctionId: command.auctionId,
reason: '아이템이 올바르지 않습니다.',
};
}
const item = await itemLoader.load(itemKey).catch(() => null);
if (!item || item.buyable) {
return {
type: 'auctionBid',
ok: false,
auctionId: command.auctionId,
reason: item ? '구매할 수 있는 아이템입니다.' : '아이템 정보를 불러올 수 없습니다.',
};
}
const currentSlotItem = general.role.items[item.slot];
if (currentSlotItem && currentSlotItem !== 'None' && isItemKey(currentSlotItem)) {
const currentItem = await itemLoader.load(currentSlotItem).catch(() => null);
if (currentItem && !currentItem.buyable) {
return {
type: 'auctionBid',
ok: false,
auctionId: command.auctionId,
reason:
currentSlotItem === itemKey
? '이미 그 유니크를 가지고 있습니다.'
: '이미 다른 유니크를 가지고 있습니다.',
};
}
}
const otherHighestBids = await db.$queryRaw<Array<{ auctionId: number; targetCode: string | null }>>(
GamePrisma.sql`
SELECT candidate.id as "auctionId", candidate.target_code as "targetCode"
FROM auction candidate
INNER JOIN LATERAL (
SELECT bid.general_id
FROM auction_bid bid
WHERE bid.auction_id = candidate.id
ORDER BY bid.amount DESC, bid.id ASC
LIMIT 1
) highest ON true
WHERE candidate.type = 'UNIQUE_ITEM'
AND candidate.status IN ('OPEN', 'FINALIZING')
AND candidate.id <> ${auction.id}
AND highest.general_id = ${command.generalId}
`
);
for (const other of otherHighestBids) {
if (!other.targetCode || !isItemKey(other.targetCode)) {
continue;
}
const otherItem = await itemLoader.load(other.targetCode).catch(() => null);
if (otherItem?.slot === item.slot) {
return {
type: 'auctionBid',
ok: false,
auctionId: command.auctionId,
reason: '1순위 입찰자인 경매중에 같은 부위가 있습니다.',
};
}
}
}
if (auction.type !== 'UNIQUE_ITEM' && auction.hostGeneralId === general.id) { if (auction.type !== 'UNIQUE_ITEM' && auction.hostGeneralId === general.id) {
return { return {
type: 'auctionBid', type: 'auctionBid',
+13 -3
View File
@@ -1,5 +1,6 @@
import { createGamePostgresConnector, GamePrisma } from '@sammo-ts/infra'; import { createGamePostgresConnector, GamePrisma } from '@sammo-ts/infra';
import { ActionLogger, ItemLoader, LogFormat, UserLogger, isItemKey, resolveUniqueConfig } from '@sammo-ts/logic'; import { ActionLogger, ItemLoader, LogFormat, UserLogger, isItemKey } from '@sammo-ts/logic';
import { resolveLegacyCompatibleUniqueConfig } from '@sammo-ts/logic/rewards/legacyUniqueItemPool.js';
import { cloneItemInventory, ensureItemInventory, equipNewItem } from '@sammo-ts/logic/items/index.js'; import { cloneItemInventory, ensureItemInventory, equipNewItem } from '@sammo-ts/logic/items/index.js';
import { asRecord, JosaUtil } from '@sammo-ts/common'; import { asRecord, JosaUtil } from '@sammo-ts/common';
@@ -18,6 +19,8 @@ type AuctionStatus = 'OPEN' | 'FINALIZING' | 'FINISHED' | 'CANCELED';
const COEFF_EXTENSION_MINUTES_PER_BID = 1 / 6; const COEFF_EXTENSION_MINUTES_PER_BID = 1 / 6;
const MIN_EXTENSION_MINUTES_PER_BID = 1; const MIN_EXTENSION_MINUTES_PER_BID = 1;
const MIN_EXTENSION_MINUTES_LIMIT_BY_BID = 5; const MIN_EXTENSION_MINUTES_LIMIT_BY_BID = 5;
const COEFF_EXTENSION_MINUTES_LIMIT_UNIQUE_COUNT = 24;
const MIN_EXTENSION_MINUTES_BY_EXTENSION_QUERY = 5;
interface AuctionRow { interface AuctionRow {
id: number; id: number;
@@ -363,7 +366,10 @@ export const createAuctionFinalizer = async (options: {
} }
const state = world.getState(); const state = world.getState();
const config = resolveUniqueConfig(asRecord(world.getScenarioConfig().const)); const config = await resolveLegacyCompatibleUniqueConfig(
asRecord(world.getScenarioConfig().const),
itemLoader
);
const scenarioMeta = asRecord(state.meta.scenarioMeta); const scenarioMeta = asRecord(state.meta.scenarioMeta);
const startYear = const startYear =
typeof scenarioMeta.startYear === 'number' && Number.isFinite(scenarioMeta.startYear) typeof scenarioMeta.startYear === 'number' && Number.isFinite(scenarioMeta.startYear)
@@ -392,7 +398,11 @@ export const createAuctionFinalizer = async (options: {
const turnMinutes = await resolveTurnMinutes(db); const turnMinutes = await resolveTurnMinutes(db);
const nextCloseAt = new Date( const nextCloseAt = new Date(
auction.closeAt.getTime() + auction.closeAt.getTime() +
Math.max(MIN_EXTENSION_MINUTES_LIMIT_BY_BID, turnMinutes * 0.5) * 60_000 Math.max(
MIN_EXTENSION_MINUTES_BY_EXTENSION_QUERY,
turnMinutes * COEFF_EXTENSION_MINUTES_LIMIT_UNIQUE_COUNT
) *
60_000
); );
const nextLatestBidCloseAt = new Date( const nextLatestBidCloseAt = new Date(
nextCloseAt.getTime() + nextCloseAt.getTime() +
+6 -11
View File
@@ -2,14 +2,8 @@ import { randomUUID } from 'node:crypto';
import { asRecord, JosaUtil } from '@sammo-ts/common'; import { asRecord, JosaUtil } from '@sammo-ts/common';
import { acquireGameSchemaAdvisoryXactLock, GamePrisma } from '@sammo-ts/infra'; import { acquireGameSchemaAdvisoryXactLock, GamePrisma } from '@sammo-ts/infra';
import { import { ActionLogger, ItemLoader, LogFormat, buildAuctionAlias, isItemKey } from '@sammo-ts/logic';
ActionLogger, import { resolveLegacyCompatibleUniqueConfig } from '@sammo-ts/logic/rewards/legacyUniqueItemPool.js';
ItemLoader,
LogFormat,
buildAuctionAlias,
isItemKey,
resolveUniqueConfig,
} from '@sammo-ts/logic';
import type { TurnDaemonCommand, TurnDaemonCommandResult } from '../lifecycle/types.js'; import type { TurnDaemonCommand, TurnDaemonCommandResult } from '../lifecycle/types.js';
import type { InMemoryTurnWorld } from '../turn/inMemoryWorld.js'; import type { InMemoryTurnWorld } from '../turn/inMemoryWorld.js';
@@ -147,7 +141,8 @@ const openUniqueAuction = async (
return fail(`최소 경매 금액은 ${minimumPoint}입니다.`); return fail(`최소 경매 금액은 ${minimumPoint}입니다.`);
} }
const item = await new ItemLoader().load(itemKey).catch(() => null); const itemLoader = new ItemLoader();
const item = await itemLoader.load(itemKey).catch(() => null);
if (!item) { if (!item) {
return fail('아이템 정보를 불러올 수 없습니다.'); return fail('아이템 정보를 불러올 수 없습니다.');
} }
@@ -156,7 +151,7 @@ const openUniqueAuction = async (
} }
const currentSlotItem = general.role.items[item.slot]; const currentSlotItem = general.role.items[item.slot];
if (currentSlotItem && currentSlotItem !== 'None' && isItemKey(currentSlotItem)) { if (currentSlotItem && currentSlotItem !== 'None' && isItemKey(currentSlotItem)) {
const currentItem = await new ItemLoader().load(currentSlotItem).catch(() => null); const currentItem = await itemLoader.load(currentSlotItem).catch(() => null);
if (currentItem && !currentItem.buyable) { if (currentItem && !currentItem.buyable) {
return fail('이미 가진 아이템이 있습니다.'); return fail('이미 가진 아이템이 있습니다.');
} }
@@ -189,7 +184,7 @@ const openUniqueAuction = async (
return fail('아직 경매가 끝나지 않았습니다.'); return fail('아직 경매가 끝나지 않았습니다.');
} }
const uniqueConfig = resolveUniqueConfig(configConst); const uniqueConfig = await resolveLegacyCompatibleUniqueConfig(configConst, itemLoader);
const configuredAmount = uniqueConfig.allItems[item.slot]?.[itemKey] ?? 0; const configuredAmount = uniqueConfig.allItems[item.slot]?.[itemKey] ?? 0;
const occupiedAmount = world const occupiedAmount = world
.listGenerals() .listGenerals()
+74 -1
View File
@@ -1231,7 +1231,9 @@ test('내 정보&설정의 지난 플레이는 기본 탐색과 분리되어 오
const actions = element.querySelector<HTMLElement>('.title-actions')!.getBoundingClientRect(); const actions = element.querySelector<HTMLElement>('.title-actions')!.getBoundingClientRect();
const navigation = element.querySelector<HTMLElement>('.navigation-actions')!.getBoundingClientRect(); const navigation = element.querySelector<HTMLElement>('.navigation-actions')!.getBoundingClientRect();
const back = element.querySelector<HTMLAnchorElement>('.navigation-actions a')!.getBoundingClientRect(); const back = element.querySelector<HTMLAnchorElement>('.navigation-actions a')!.getBoundingClientRect();
const refresh = element.querySelector<HTMLButtonElement>('.navigation-actions button')!.getBoundingClientRect(); const refresh = element
.querySelector<HTMLButtonElement>('.navigation-actions button')!
.getBoundingClientRect();
const past = element.querySelector<HTMLAnchorElement>('.past-plays-link')!.getBoundingClientRect(); const past = element.querySelector<HTMLAnchorElement>('.past-plays-link')!.getBoundingClientRect();
const pastStyle = getComputedStyle(element.querySelector<HTMLAnchorElement>('.past-plays-link')!); const pastStyle = getComputedStyle(element.querySelector<HTMLAnchorElement>('.past-plays-link')!);
return { return {
@@ -1269,6 +1271,77 @@ test('내 정보&설정의 지난 플레이는 기본 탐색과 분리되어 오
} }
}); });
test('내 정보&설정에서 모바일 메인 패널을 드래그하거나 버튼으로 재정렬하고 Ref 순서로 복원한다', async ({ page }) => {
const state: FixtureState = { permission: 'head', myset: 3, settingMutations: [], accessPages: [] };
await install(page, state);
await page.setViewportSize({ width: 390, height: 844 });
await page.goto('my-page');
await page.getByRole('button', { name: '순서 바꾸기', exact: true }).click();
const dialog = page.getByRole('dialog', { name: '모바일 레이아웃 순서 바꾸기' });
await expect(dialog).toBeVisible();
const readOrder = () =>
dialog
.locator('[data-mobile-layout-id]')
.evaluateAll((elements) => elements.map((element) => element.getAttribute('data-mobile-layout-id')));
const defaultOrder = [
'commands',
'nation-menu',
'nation',
'general',
'city',
'map',
'records',
'global-menu',
'messages',
];
await expect.poll(readOrder).toEqual(defaultOrder);
await dialog
.locator('[data-mobile-layout-id="messages"]')
.dragTo(dialog.locator('[data-mobile-layout-id="commands"]'));
await expect
.poll(readOrder)
.toEqual(['messages', 'commands', 'nation-menu', 'nation', 'general', 'city', 'map', 'records', 'global-menu']);
await dialog.getByRole('button', { name: '지도 위로' }).click();
await expect
.poll(readOrder)
.toEqual(['messages', 'commands', 'nation-menu', 'nation', 'general', 'map', 'city', 'records', 'global-menu']);
const dialogGeometry = await dialog.evaluate((element) => {
const rect = element.getBoundingClientRect();
const firstItem = element.querySelector<HTMLElement>('[data-mobile-layout-id]')?.getBoundingClientRect();
const moveButton = element.querySelector<HTMLButtonElement>('[aria-label$="아래로"]')?.getBoundingClientRect();
return {
rect: rect.toJSON(),
firstItem: firstItem?.toJSON() ?? null,
moveButton: moveButton?.toJSON() ?? null,
overflowX: getComputedStyle(element).overflowX,
documentWidth: document.documentElement.scrollWidth,
};
});
expect(dialogGeometry.rect.left).toBeGreaterThanOrEqual(0);
expect(dialogGeometry.rect.right).toBeLessThanOrEqual(390);
expect(dialogGeometry.firstItem?.height).toBeGreaterThanOrEqual(44);
expect(dialogGeometry.moveButton?.width).toBeGreaterThanOrEqual(36);
expect(dialogGeometry.documentWidth).toBe(390);
await persistParityArtifact(page, 'core-my-page-mobile-layout-order-dialog', dialogGeometry);
await dialog.getByRole('button', { name: '적용', exact: true }).click();
await expect(dialog).toBeHidden();
await expect
.poll(() => page.evaluate(() => JSON.parse(localStorage.getItem('sam.mobileMainPanelOrder.v1') ?? '[]')))
.toEqual(['messages', 'commands', 'nation-menu', 'nation', 'general', 'map', 'city', 'records', 'global-menu']);
await page.getByRole('button', { name: '순서 바꾸기', exact: true }).click();
await dialog.getByRole('button', { name: 'Ref 초깃값' }).click();
await expect.poll(readOrder).toEqual(defaultOrder);
await dialog.getByRole('button', { name: '적용', exact: true }).click();
await expect
.poll(() => page.evaluate(() => JSON.parse(localStorage.getItem('sam.mobileMainPanelOrder.v1') ?? '[]')))
.toEqual(defaultOrder);
});
for (const [label, failure] of [ for (const [label, failure] of [
['daemon timeout', 'TIMEOUT'], ['daemon timeout', 'TIMEOUT'],
['engine transaction 오류', 'INTERNAL_SERVER_ERROR'], ['engine transaction 오류', 'INTERNAL_SERVER_ERROR'],
@@ -11,6 +11,7 @@ const isLegacyRequest = (route: Route): boolean =>
const installArchiveViews = async (page: Page) => { const installArchiveViews = async (page: Page) => {
const hallRequests: string[] = []; const hallRequests: string[] = [];
const dynastyRequests: string[] = [];
await page.addInitScript((profile) => { await page.addInitScript((profile) => {
localStorage.setItem('sammo-game-token', 'ga_archive_views'); localStorage.setItem('sammo-game-token', 'ga_archive_views');
localStorage.setItem('sammo-game-profile', profile); localStorage.setItem('sammo-game-profile', profile);
@@ -21,6 +22,9 @@ const installArchiveViews = async (page: Page) => {
if (operations.some((operation) => operation.startsWith('ranking.getHallOfFame'))) { if (operations.some((operation) => operation.startsWith('ranking.getHallOfFame'))) {
hallRequests.push(decodeURIComponent(`${route.request().url()} ${route.request().postData() ?? ''}`)); hallRequests.push(decodeURIComponent(`${route.request().url()} ${route.request().postData() ?? ''}`));
} }
if (operations.some((operation) => operation.startsWith('dynasty.'))) {
dynastyRequests.push(decodeURIComponent(`${route.request().url()} ${route.request().postData() ?? ''}`));
}
const results = operations.map((operation) => { const results = operations.map((operation) => {
if (operation === 'auth.status') return response({ ok: true }); if (operation === 'auth.status') return response({ ok: true });
if (operation === 'lobby.info') return response({ myGeneral: { id: 1, name: '기록장수' } }); if (operation === 'lobby.info') return response({ myGeneral: { id: 1, name: '기록장수' } });
@@ -67,8 +71,8 @@ const installArchiveViews = async (page: Page) => {
{ {
id: legacy ? 101 : 1, id: legacy ? 101 : 1,
source: legacy ? 'legacy' : 'current', source: legacy ? 'legacy' : 'current',
sourceProfile: legacy ? 'hwe' : 'che', sourceProfile: 'che',
serverId: legacy ? 'hwe-old-1' : 'che-current-1', serverId: legacy ? 'che-old-1' : 'che-current-1',
phase: legacy ? '이전 1기' : '현재 1기', phase: legacy ? '이전 1기' : '현재 1기',
name: '촉', name: '촉',
year: 215, year: 215,
@@ -93,10 +97,10 @@ const installArchiveViews = async (page: Page) => {
if (operation === 'dynasty.getDetail') { if (operation === 'dynasty.getDetail') {
return response({ return response({
source: 'legacy', source: 'legacy',
sourceProfile: 'hwe', sourceProfile: 'che',
emperor: { emperor: {
id: 101, id: 101,
serverId: 'hwe-old-1', serverId: 'che-old-1',
winnerNationId: 1, winnerNationId: 1,
phase: '이전 1기', phase: '이전 1기',
nationCount: '1 / 2', nationCount: '1 / 2',
@@ -189,7 +193,7 @@ const installArchiveViews = async (page: Page) => {
}); });
await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(results) }); await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(results) });
}); });
return { hallRequests }; return { dynastyRequests, hallRequests };
}; };
test('명예의 전당은 현재 profile의 현재·이전 서버 기록만 조회한다', async ({ page }, testInfo) => { test('명예의 전당은 현재 profile의 현재·이전 서버 기록만 조회한다', async ({ page }, testInfo) => {
@@ -217,19 +221,36 @@ test('명예의 전당은 현재 profile의 현재·이전 서버 기록만 조
await page.screenshot({ path: testInfo.outputPath('hall-profile-scope-mobile.png'), fullPage: true }); await page.screenshot({ path: testInfo.outputPath('hall-profile-scope-mobile.png'), fullPage: true });
}); });
test('왕조 일람과 상세는 이전 서버 source와 profile을 유지한다', async ({ page }) => { test('왕조 일람과 상세는 현재 profile의 이전 서버 기록만 조회한다', async ({ page }, testInfo) => {
await installArchiveViews(page); const state = await installArchiveViews(page);
await page.setViewportSize({ width: 1200, height: 800 }); await page.setViewportSize({ width: 1200, height: 800 });
await page.goto('dynasty'); await page.goto('dynasty');
await expect(page.getByText('현재 1기')).toBeVisible(); await expect(page.getByText('현재 1기')).toBeVisible();
await page.getByLabel('기록 구분').focus();
await expect(page.getByLabel('기록 구분')).toBeFocused();
await page.getByLabel('기록 구분').selectOption('legacy'); await page.getByLabel('기록 구분').selectOption('legacy');
await expect(page.getByText(/이전 1기.*HWE 이전 서버/)).toBeVisible(); await expect(page.getByText(/이전 1기.*이전 서버/)).toBeVisible();
await expect(page.getByText(/CHE 이전 서버|HWE 이전 서버/)).toHaveCount(0);
await expect(page.locator('.dynasty-page')).toHaveCSS('width', '1000px');
await expect(page.locator('.dynasty-table')).toHaveCSS('height', '139px');
await expect(page.locator('.dynasty-table .phase-heading')).toHaveCSS('background-color', 'rgb(135, 206, 235)');
await page.screenshot({ path: testInfo.outputPath('dynasty-list-profile-scope-desktop.png'), fullPage: true });
await page.setViewportSize({ width: 390, height: 844 });
await expect(page.locator('.dynasty-page')).toHaveCSS('width', '1000px');
await page.screenshot({ path: testInfo.outputPath('dynasty-list-profile-scope-mobile.png'), fullPage: true });
await page.setViewportSize({ width: 1200, height: 800 });
const detailLink = page.getByRole('link', { name: '자세히' }); const detailLink = page.getByRole('link', { name: '자세히' });
await expect(detailLink).toHaveAttribute('href', /dynasty\/101\?source=legacy$/); await expect(detailLink).toHaveAttribute('href', /dynasty\/101\?source=legacy$/);
await detailLink.click(); await detailLink.click();
await expect(page.getByText(/이전 1기.*HWE 이전 서버/)).toBeVisible(); await expect(page.getByText(/이전 1기.*이전 서버/)).toBeVisible();
await expect(page.getByText(/CHE 이전 서버|HWE 이전 서버/)).toHaveCount(0);
await expect(page.locator('.dynasty-page')).toHaveCSS('width', '1000px'); await expect(page.locator('.dynasty-page')).toHaveCSS('width', '1000px');
expect(state.dynastyRequests.some((request) => request.includes('legacy'))).toBe(true);
expect(state.dynastyRequests.every((request) => !request.includes('sourceProfile'))).toBe(true);
await page.screenshot({ path: testInfo.outputPath('dynasty-detail-profile-scope-desktop.png'), fullPage: true });
}); });
test('연감 국가 라벨은 밝은 배경에 검정, 어두운 배경에 흰 글자를 사용한다', async ({ page }, testInfo) => { test('연감 국가 라벨은 밝은 배경에 검정, 어두운 배경에 흰 글자를 사용한다', async ({ page }, testInfo) => {
+51 -12
View File
@@ -95,11 +95,10 @@ type DashboardBundleInput = {
const operationInput = (route: Route, index: number): DashboardBundleInput => { const operationInput = (route: Route, index: number): DashboardBundleInput => {
const request = route.request(); const request = route.request();
const queryInput = new URL(request.url()).searchParams.get('input'); const queryInput = new URL(request.url()).searchParams.get('input');
const parsed = (request.postData() const parsed = (request.postData() ? request.postDataJSON() : queryInput ? JSON.parse(queryInput) : {}) as Record<
? request.postDataJSON() string,
: queryInput unknown
? JSON.parse(queryInput) >;
: {}) as Record<string, unknown>;
const entry = (parsed[String(index)] ?? parsed) as { json?: DashboardBundleInput }; const entry = (parsed[String(index)] ?? parsed) as { json?: DashboardBundleInput };
return entry.json ?? (entry as DashboardBundleInput); return entry.json ?? (entry as DashboardBundleInput);
}; };
@@ -1558,10 +1557,7 @@ test('message targets keep reply behavior and use nation-color contrast in label
await page.setViewportSize({ width: 500, height: 900 }); await page.setViewportSize({ width: 500, height: 900 });
const mobilePanel = page.locator('.mobile-message-panel'); const mobilePanel = page.locator('.mobile-message-panel');
await expect(mobilePanel.locator('.msg-plate[data-id="101"] .msg-target')).toHaveCSS( await expect(mobilePanel.locator('.msg-plate[data-id="101"] .msg-target')).toHaveCSS('color', 'rgb(255, 255, 255)');
'color',
'rgb(255, 255, 255)'
);
await expect(mobilePanel.locator('.msg-plate[data-id="103"] .msg-target')).toHaveCSS('color', 'rgb(0, 0, 0)'); await expect(mobilePanel.locator('.msg-plate[data-id="103"] .msg-target')).toHaveCSS('color', 'rgb(0, 0, 0)');
await expect(mobilePanel.locator('#mailbox_list optgroup[label="밝은국"]')).toHaveCSS('color', 'rgb(0, 0, 0)'); await expect(mobilePanel.locator('#mailbox_list optgroup[label="밝은국"]')).toHaveCSS('color', 'rgb(0, 0, 0)');
await persistArtifact(page, `${basePath.slice(1)}-message-nation-contrast-mobile-500`); await persistArtifact(page, `${basePath.slice(1)}-message-nation-contrast-mobile-500`);
@@ -2217,6 +2213,49 @@ test('the 939/940 boundary switches to the Ref-style 500px single document', asy
]) { ]) {
await expect(page.locator(selector)).toBeVisible(); await expect(page.locator(selector)).toBeVisible();
} }
const readMobilePanelOrder = () =>
page
.locator('.layout-mobile > [data-mobile-panel-id]')
.evaluateAll((elements) => elements.map((element) => element.getAttribute('data-mobile-panel-id')));
await expect
.poll(readMobilePanelOrder)
.toEqual(['commands', 'nation-menu', 'nation', 'general', 'city', 'map', 'records', 'global-menu', 'messages']);
await page.evaluate(() => {
localStorage.setItem(
'sam.mobileMainPanelOrder.v1',
JSON.stringify([
'messages',
'map',
'commands',
'nation-menu',
'nation',
'general',
'city',
'records',
'global-menu',
])
);
document.dispatchEvent(new CustomEvent('sam-mobile-main-panel-order-changed'));
});
await expect
.poll(readMobilePanelOrder)
.toEqual(['messages', 'map', 'commands', 'nation-menu', 'nation', 'general', 'city', 'records', 'global-menu']);
const customPanelGeometry = await page.locator('.layout-mobile > [data-mobile-panel-id]').evaluateAll((elements) =>
elements.map((element) => {
const rect = element.getBoundingClientRect();
return {
id: element.getAttribute('data-mobile-panel-id'),
top: rect.top,
bottom: rect.bottom,
left: rect.left,
right: rect.right,
};
})
);
expect(customPanelGeometry.every(({ left, right }) => left >= 0 && right <= 500)).toBe(true);
expect(
customPanelGeometry.every((panel, index) => index === 0 || panel.top >= customPanelGeometry[index - 1]!.bottom)
).toBe(true);
await persistArtifact(page, `${basePath.slice(1)}-mobile-500`); await persistArtifact(page, `${basePath.slice(1)}-mobile-500`);
}); });
@@ -3040,9 +3079,9 @@ for (const viewport of [
await refreshActivityAndCommands(); await refreshActivityAndCommands();
await expect(picker.getByLabel('장비 종류', { exact: true })).toHaveValue('weapon'); await expect(picker.getByLabel('장비 종류', { exact: true })).toHaveValue('weapon');
await expect(picker.getByLabel('장비', { exact: true })).toHaveValue('청룡언월도'); await expect(picker.getByLabel('장비', { exact: true })).toHaveValue('청룡언월도');
await expect.poll(() => page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual( await expect
viewport.width .poll(() => page.evaluate(() => document.documentElement.scrollWidth))
); .toBeLessThanOrEqual(viewport.width);
}); });
} }
@@ -0,0 +1,420 @@
import { expect, test, type Page, type Route } from '@playwright/test';
import { gameProfile, gameTrpcRoute } from './gameTestPaths.js';
type Role = 'head' | 'member';
type AppointmentInput = { destGeneralId: number; destCityId: number; officerLevel: number };
type FixtureState = {
role: Role;
appointed: boolean;
secretForbidden?: boolean;
appointmentInputs: AppointmentInput[];
};
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 operations = (route: Route): string[] =>
decodeURIComponent(new URL(route.request().url()).pathname.split('/trpc/')[1] ?? '').split(',');
const requestInput = (route: Route, index: number): Record<string, unknown> => {
const body: unknown = route.request().postData() ? route.request().postDataJSON() : {};
const record = body && typeof body === 'object' ? (body as Record<string, unknown>) : {};
const raw = record[String(index)] ?? record;
const payload = raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {};
const input = payload.input && typeof payload.input === 'object' ? (payload.input as Record<string, unknown>) : {};
const json = payload.json ?? input.json ?? payload;
return json && typeof json === 'object' ? (json as Record<string, unknown>) : {};
};
const cities = [
{
id: 1,
name: '허창',
level: 7,
region: 2,
population: 99_000,
populationMax: 100_000,
agriculture: 9_500,
agricultureMax: 10_000,
commerce: 8_000,
commerceMax: 10_000,
security: 8_000,
securityMax: 10_000,
trust: 80,
trade: 100,
defence: 4_500,
defenceMax: 5_000,
wall: 4_500,
wallMax: 5_000,
supplyState: 1,
frontState: 0,
incomes: { gold: 1000, rice: 900, wall: 800 },
},
{
id: 2,
name: '낙양',
level: 6,
region: 2,
population: 60_000,
populationMax: 100_000,
agriculture: 5_000,
agricultureMax: 10_000,
commerce: 5_000,
commerceMax: 10_000,
security: 5_000,
securityMax: 10_000,
trust: 70,
trade: 90,
defence: 2_500,
defenceMax: 5_000,
wall: 2_500,
wallMax: 5_000,
supplyState: 1,
frontState: 0,
incomes: { gold: 800, rice: 700, wall: 600 },
},
] as const;
const overviewFixture = (state: FixtureState) => ({
me: { id: state.role === 'head' ? 20 : 21, officerLevel: state.role === 'head' ? 5 : 1 },
nation: {
id: 1,
name: '위',
color: '#008000',
level: 3,
typeCode: 'che_법가',
capitalCityId: 1,
rate: 20,
},
chiefStatMin: 65,
cities: cities.map((city) => ({
...city,
officers: {
4: state.appointed
? { id: 21, name: '장료', npcState: 0, officerLevel: 4, cityId: 1, cityName: '허창' }
: null,
3: null,
2: null,
},
})),
generals: [
{
id: 1,
name: '조조',
npcState: 0,
officerLevel: 12,
cityId: 1,
officerCity: 0,
stats: { leadership: 90, strength: 80, intelligence: 90 },
},
{
id: 20,
name: '순욱',
npcState: 0,
officerLevel: 5,
cityId: 1,
officerCity: 0,
stats: { leadership: 75, strength: 70, intelligence: 90 },
},
{
id: 21,
name: '장료',
npcState: 0,
officerLevel: state.appointed ? 4 : 1,
cityId: 1,
officerCity: state.appointed ? 1 : 0,
stats: { leadership: 80, strength: 70, intelligence: 50 },
},
{
id: 22,
name: '조홍',
npcState: 2,
officerLevel: 1,
cityId: 2,
officerCity: 0,
stats: { leadership: 60, strength: 65, intelligence: 40 },
},
],
});
const secretGeneral = (id: number, name: string, cityId: number, overrides: Record<string, unknown> = {}) => ({
id,
name,
npcState: 0,
injury: 0,
stats: { leadership: 70, strength: 70, intelligence: 70 },
leadershipBonus: 0,
experienceLevel: 9,
troopId: 0,
troopName: null,
gold: 1000,
rice: 2000,
cityId,
cityName: cityId === 1 ? '허창' : '낙양',
defenceTrain: 90,
defenceTrainText: '☆',
crewTypeId: 1,
crewTypeName: '보병',
crew: 300,
train: 90,
atmos: 90,
killTurn: 7,
turnTime: '2026-01-01T01:02:00.000Z',
reservedCommands: ['농지 개간', '훈련'],
...overrides,
});
const secretFixture = () => ({
nation: { id: 1, name: '위', color: '#008000', level: 3 },
viewer: { generalId: 20, permission: 1 },
summary: {
gold: 4000,
rice: 8000,
crew: 1200,
generalCount: 4,
averageGold: 1000,
averageRice: 2000,
readiness: {
90: { crew: 1200, generals: 4 },
80: { crew: 1200, generals: 4 },
60: { crew: 1200, generals: 4 },
},
},
generals: [
secretGeneral(1, '조조', 1, { leadershipBonus: 6 }),
secretGeneral(20, '순욱', 1, { leadershipBonus: 3 }),
secretGeneral(21, '장료', 1, {
stats: { leadership: 80, strength: 70, intelligence: 50 },
}),
secretGeneral(22, '조홍', 2, { npcState: 2, reservedCommands: [] }),
],
});
const personnelGeneral = (id: number, name: string, officerLevel: number, overrides: Record<string, unknown> = {}) => ({
id,
name,
npcState: 0,
officerLevel,
cityId: 1,
cityName: '허창',
troopId: 0,
troopName: null,
picture: null,
imageServer: 0,
officerCity: officerLevel >= 2 && officerLevel <= 4 ? 1 : 0,
officerCityName: officerLevel >= 2 && officerLevel <= 4 ? '허창' : null,
stats: { leadership: 70, strength: 70, intelligence: 70 },
experience: 100,
dedication: 200,
injury: 0,
gold: 1000,
rice: 1000,
crew: 100,
personality: null,
specialDomestic: null,
specialWar: null,
belong: 10,
permission: 'normal',
...overrides,
});
const personnelFixture = (state: FixtureState) => {
const allGenerals = [
personnelGeneral(1, '조조', 12),
personnelGeneral(20, '순욱', 5, { stats: { leadership: 75, strength: 70, intelligence: 90 } }),
personnelGeneral(21, '장료', state.appointed ? 4 : 1, {
stats: { leadership: 80, strength: 70, intelligence: 50 },
}),
personnelGeneral(22, '조홍', 1, {
npcState: 2,
cityId: 2,
cityName: '낙양',
stats: { leadership: 60, strength: 65, intelligence: 40 },
}),
];
const canManage = state.role === 'head';
return {
me: {
id: canManage ? 20 : 21,
officerLevel: canManage ? 5 : 1,
canManage,
canChangePermissions: false,
canKick: canManage,
},
nation: {
id: 1,
name: '위',
color: '#008000',
level: 3,
typeCode: 'che_법가',
capitalCityId: 1,
chiefSet: 0,
},
chiefStatMin: 65,
generals: canManage ? allGenerals : [],
chiefAssignments: { 12: allGenerals[0], 5: allGenerals[1] },
cityAssignments: cities.map((city) => ({
id: city.id,
name: city.name,
level: city.level,
region: city.region,
officerSet: city.id === 1 && state.appointed ? 1 << 4 : 0,
officers: {
4: city.id === 1 && state.appointed ? allGenerals[2] : null,
3: null,
2: null,
},
})),
awards: { tigers: [], eagles: [] },
permissionCandidates: { ambassadors: [], auditors: [] },
};
};
const install = async (page: Page, state: FixtureState): Promise<void> => {
await page.addInitScript((profile) => {
localStorage.setItem('sammo-game-token', 'ga_city_office');
localStorage.setItem('sammo-game-profile', profile);
}, gameProfile);
await page.route(gameTrpcRoute, async (route) => {
const result = operations(route).map((operation, index) => {
if (operation === 'auth.status') return response({ ok: true });
if (operation === 'lobby.info') return response({ myGeneral: { id: 20, name: '순욱' } });
if (operation === 'join.getConfig') return response({});
if (operation === 'nation.getCityOverview') return response(overviewFixture(state));
if (operation === 'nation.getSecretGeneralList') {
return state.secretForbidden
? errorResponse(
operation,
'권한이 부족합니다. 수뇌부가 아니거나 사관년도가 부족합니다.',
'FORBIDDEN'
)
: response(secretFixture());
}
if (operation === 'nation.getPersonnelInfo') return response(personnelFixture(state));
if (operation === 'nation.appoint') {
const input = requestInput(route, index);
state.appointmentInputs.push({
destGeneralId: Number(input.destGeneralId),
destCityId: Number(input.destCityId),
officerLevel: Number(input.officerLevel),
});
state.appointed = true;
return response({ ok: true });
}
return errorResponse(operation, `Unhandled fixture operation: ${operation}`);
});
await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(result) });
});
};
test('암행부 행을 도시별로 나누고 수뇌의 인사부 즉시 임명을 반영한다', async ({ page }, testInfo) => {
const state: FixtureState = { role: 'head', appointed: false, appointmentInputs: [] };
await install(page, state);
await page.setViewportSize({ width: 1200, height: 900 });
await page.goto('nation/cities');
await expect(page.locator('.nation-cities-page')).toBeVisible();
await expect(page.locator('.city-user-table')).toHaveCount(0);
await expect(page.getByRole('button', { name: '인사부 연동' })).toHaveCount(0);
await page.getByRole('button', { name: '암행부 연동' }).click();
await expect(page.locator('.city-user-table')).toHaveCount(2);
await expect(page.locator('.city[data-city-id="1"] .city-user-table tr[data-general-id="21"]')).toContainText(
'장료'
);
await expect(page.locator('.city[data-city-id="2"] .city-user-table tr[data-general-id="22"]')).toContainText(
'조홍'
);
await expect(page.locator('.city[data-city-id="2"] .city-user-table tr[data-general-id="21"]')).toHaveCount(0);
await expect(page.locator('.city[data-city-id="1"] tr[data-general-id="21"] .command-attention')).toHaveText(
'농지 개간'
);
const integratedBox = await page.locator('.city[data-city-id="1"] .city-user-table').evaluate((element) => {
const rect = element.getBoundingClientRect();
const style = getComputedStyle(element);
return { width: rect.width, borderCollapse: style.borderCollapse, fontSize: style.fontSize };
});
expect(integratedBox).toEqual({ width: 941, borderCollapse: 'collapse', fontSize: '14px' });
await page.getByRole('button', { name: '인사부 연동' }).click();
const ordinaryRow = page.locator('.city[data-city-id="1"] tr[data-general-id="21"]');
await expect(ordinaryRow.locator('.appointment-button')).toHaveCount(3);
await expect(ordinaryRow.locator('.mode-4')).toBeEnabled();
await expect(ordinaryRow.locator('.mode-3')).toBeDisabled();
await expect(ordinaryRow.locator('.mode-2')).toBeEnabled();
await expect(page.locator('tr[data-general-id="1"] .appointment-button')).toHaveCount(0);
const disabledStyle = await ordinaryRow.locator('.mode-3').evaluate((button) => {
const style = getComputedStyle(button);
return { borderTopWidth: style.borderTopWidth, backgroundColor: style.backgroundColor };
});
expect(disabledStyle).toEqual({ borderTopWidth: '0px', backgroundColor: 'rgba(0, 0, 0, 0)' });
const appointButton = page.getByRole('button', { name: '장료을(를) 허창 태수로 임명' });
await appointButton.hover();
expect(await appointButton.evaluate((button) => getComputedStyle(button).cursor)).toBe('pointer');
await appointButton.focus();
await expect(appointButton).toBeFocused();
await page.screenshot({ path: testInfo.outputPath('nation-city-integrated-desktop.png'), fullPage: true });
await appointButton.click();
await expect.poll(() => state.appointmentInputs).toEqual([{ destGeneralId: 21, destCityId: 1, officerLevel: 4 }]);
await expect(page.locator('.city[data-city-id="1"] .officer-4-value')).toHaveText('장료');
await expect(page.locator('.city[data-city-id="1"] .officer-4-value')).toHaveClass(/effective-officer/u);
await expect(page.locator('.city[data-city-id="1"] tr[data-general-id="21"] .mode-4')).toBeDisabled();
await page.setViewportSize({ width: 500, height: 900 });
expect(await page.locator('.nation-cities-page').evaluate((element) => element.getBoundingClientRect().width)).toBe(
1000
);
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeGreaterThanOrEqual(1000);
await page.screenshot({ path: testInfo.outputPath('nation-city-integrated-mobile.png'), fullPage: true });
});
test('수뇌 대상은 재확인하고 일반 장수에게는 임명 버튼을 열지 않는다', async ({ page }) => {
const headState: FixtureState = { role: 'head', appointed: false, appointmentInputs: [] };
await install(page, headState);
await page.goto('nation/cities');
await page.getByRole('button', { name: '암행부 연동' }).click();
await page.getByRole('button', { name: '인사부 연동' }).click();
const chiefButton = page.getByRole('button', { name: '순욱을(를) 허창 태수로 임명' });
expect(await chiefButton.evaluate((button) => getComputedStyle(button).color)).toBe('rgb(255, 0, 0)');
page.once('dialog', async (dialog) => {
expect(dialog.message()).toBe('수뇌입니다. 임명할까요?');
await dialog.dismiss();
});
await chiefButton.click();
await expect.poll(() => headState.appointmentInputs.length).toBe(0);
await page.unroute(gameTrpcRoute);
const memberState: FixtureState = { role: 'member', appointed: false, appointmentInputs: [] };
await install(page, memberState);
await page.reload();
await page.getByRole('button', { name: '암행부 연동' }).click();
page.once('dialog', async (dialog) => {
expect(dialog.message()).toBe('수뇌가 아닙니다!');
await dialog.accept();
});
await page.getByRole('button', { name: '인사부 연동' }).click();
await expect(page.locator('.appointment-button')).toHaveCount(0);
expect(memberState.appointmentInputs).toEqual([]);
});
test('암행부 권한 거부는 도시 기밀 행과 인사부 연동을 열지 않는다', async ({ page }) => {
const state: FixtureState = {
role: 'member',
appointed: false,
secretForbidden: true,
appointmentInputs: [],
};
await install(page, state);
await page.goto('nation/cities');
await page.getByRole('button', { name: '암행부 연동' }).click();
await expect(page.locator('.integration-error')).toContainText('권한이 부족합니다.');
await expect(page.locator('.city-user-table')).toHaveCount(0);
await expect(page.getByRole('button', { name: '인사부 연동' })).toHaveCount(0);
expect(state.appointmentInputs).toEqual([]);
});
@@ -21,6 +21,7 @@ export default defineConfig({
'troop.spec.ts', 'troop.spec.ts',
'board.spec.ts', 'board.spec.ts',
'inGameInfo.spec.ts', 'inGameInfo.spec.ts',
'nationCityOfficeIntegration.spec.ts',
'inGameMenus.spec.ts', 'inGameMenus.spec.ts',
'nationOffices.spec.ts', 'nationOffices.spec.ts',
'diplomacy.spec.ts', 'diplomacy.spec.ts',
@@ -0,0 +1,85 @@
export const MOBILE_MAIN_PANEL_ORDER_STORAGE_KEY = 'sam.mobileMainPanelOrder.v1';
export const MOBILE_MAIN_PANEL_ORDER_CHANGED_EVENT = 'sam-mobile-main-panel-order-changed';
export const MOBILE_MAIN_PANEL_DEFINITIONS = [
{ id: 'commands', label: '명령 목록' },
{ id: 'nation-menu', label: '국가 메뉴' },
{ id: 'nation', label: '국가 정보' },
{ id: 'general', label: '장수 정보' },
{ id: 'city', label: '도시 정보' },
{ id: 'map', label: '지도' },
{ id: 'records', label: '기록 영역' },
{ id: 'global-menu', label: '공통 메뉴' },
{ id: 'messages', label: '서신' },
] as const;
export type MobileMainPanelId = (typeof MOBILE_MAIN_PANEL_DEFINITIONS)[number]['id'];
export const DEFAULT_MOBILE_MAIN_PANEL_ORDER: readonly MobileMainPanelId[] = MOBILE_MAIN_PANEL_DEFINITIONS.map(
({ id }) => id
);
const mobilePanelIds = new Set<string>(DEFAULT_MOBILE_MAIN_PANEL_ORDER);
export const normalizeMobileMainPanelOrder = (value: unknown): MobileMainPanelId[] => {
const source = Array.isArray(value) ? value : [];
const seen = new Set<string>();
const normalized: MobileMainPanelId[] = [];
for (const item of source) {
if (typeof item !== 'string' || !mobilePanelIds.has(item) || seen.has(item)) continue;
seen.add(item);
normalized.push(item as MobileMainPanelId);
}
for (const item of DEFAULT_MOBILE_MAIN_PANEL_ORDER) {
if (!seen.has(item)) normalized.push(item);
}
return normalized;
};
export const parseMobileMainPanelOrder = (raw: string | null): MobileMainPanelId[] => {
if (!raw) return [...DEFAULT_MOBILE_MAIN_PANEL_ORDER];
try {
return normalizeMobileMainPanelOrder(JSON.parse(raw));
} catch {
return [...DEFAULT_MOBILE_MAIN_PANEL_ORDER];
}
};
export const loadMobileMainPanelOrder = (storage: Pick<Storage, 'getItem'> = window.localStorage) =>
parseMobileMainPanelOrder(storage.getItem(MOBILE_MAIN_PANEL_ORDER_STORAGE_KEY));
export const saveMobileMainPanelOrder = (
value: readonly MobileMainPanelId[],
storage: Pick<Storage, 'setItem'> = window.localStorage
): MobileMainPanelId[] => {
const normalized = normalizeMobileMainPanelOrder(value);
storage.setItem(MOBILE_MAIN_PANEL_ORDER_STORAGE_KEY, JSON.stringify(normalized));
if (typeof document !== 'undefined') {
document.dispatchEvent(new CustomEvent(MOBILE_MAIN_PANEL_ORDER_CHANGED_EVENT));
}
return normalized;
};
export const moveMobileMainPanel = (
value: readonly MobileMainPanelId[],
fromIndex: number,
toIndex: number
): MobileMainPanelId[] => {
const normalized = normalizeMobileMainPanelOrder(value);
if (
fromIndex < 0 ||
fromIndex >= normalized.length ||
toIndex < 0 ||
toIndex >= normalized.length ||
fromIndex === toIndex
) {
return normalized;
}
const [moved] = normalized.splice(fromIndex, 1);
if (!moved) return normalized;
normalized.splice(toIndex, 0, moved);
return normalized;
};
@@ -92,9 +92,7 @@ onMounted(loadDetail);
<td class="phase-heading centered" colspan="6"> <td class="phase-heading centered" colspan="6">
<span class="large-text"> <span class="large-text">
{{ data.emperor.phase }} {{ data.emperor.phase }}
<template v-if="data.source === 'legacy'"> <template v-if="data.source === 'legacy'"> [이전 서버] </template>
[{{ data.sourceProfile.toUpperCase() }} 이전 서버]
</template>
</span> </span>
</td> </td>
</tr> </tr>
@@ -98,9 +98,7 @@ watch(selectedSource, loadDynasty);
<td class="phase-heading" colspan="8"> <td class="phase-heading" colspan="8">
<span class="large-text" <span class="large-text"
>{{ entry.phase >{{ entry.phase
}}<template v-if="entry.source === 'legacy'"> }}<template v-if="entry.source === 'legacy'"> [이전 서버]</template></span
[{{ entry.sourceProfile.toUpperCase() }} 이전 서버]</template
></span
> >
<RouterLink <RouterLink
:to="{ :to="{
+11 -5
View File
@@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import { formatServerDateTime } from '@sammo-ts/common'; import { formatServerDateTime, JosaUtil } from '@sammo-ts/common';
import { computed, onMounted, reactive, ref } from 'vue'; import { computed, onMounted, reactive, ref } from 'vue';
import { trpc } from '../utils/trpc'; import { trpc } from '../utils/trpc';
@@ -379,7 +379,8 @@ const buyRandomUnique = async () => {
}; };
const openUniqueAuction = async () => { const openUniqueAuction = async () => {
if (!uniqueForm.itemId.trim()) { const selectedItem = status.value?.availableUnique.find((item) => item.key === uniqueForm.itemId.trim());
if (!selectedItem) {
actionError.value = '유니크를 선택해주세요.'; actionError.value = '유니크를 선택해주세요.';
return; return;
} }
@@ -388,15 +389,20 @@ const openUniqueAuction = async () => {
actionError.value = '입찰 포인트를 입력해주세요.'; actionError.value = '입찰 포인트를 입력해주세요.';
return; return;
} }
if (!window.confirm(`유니크 경매를 ${amount} 포인트로 신청하시겠습니까?`)) { if (previousPoint.value < amount) {
actionError.value = '유산 포인트가 부족합니다.';
return;
}
const itemJosa = JosaUtil.pick(selectedItem.rawName, '을');
if (!window.confirm(`${amount} 포인트로 ${selectedItem.name}${itemJosa} 입찰하겠습니까?`)) {
return; return;
} }
await runAction(async () => { await runAction(async () => {
await trpc.inherit.openUniqueAuction.mutate({ await trpc.inherit.openUniqueAuction.mutate({
itemId: uniqueForm.itemId.trim(), itemId: selectedItem.key,
amount, amount,
}); });
}); }, '성공했습니다. 경매장을 확인해주세요.');
}; };
const checkOwner = async () => { const checkOwner = async () => {
+55 -12
View File
@@ -29,6 +29,12 @@ import { useMainDashboardStore } from '../stores/mainDashboard';
import { useGameFeedback } from '../composables/useGameFeedback'; import { useGameFeedback } from '../composables/useGameFeedback';
import { trpc } from '../utils/trpc'; import { trpc } from '../utils/trpc';
import type { CommandPatternEntry } from '../components/command/types'; import type { CommandPatternEntry } from '../components/command/types';
import {
loadMobileMainPanelOrder,
MOBILE_MAIN_PANEL_ORDER_CHANGED_EVENT,
MOBILE_MAIN_PANEL_ORDER_STORAGE_KEY,
type MobileMainPanelId,
} from '../utils/mobileMainPanelOrder';
const session = useSessionStore(); const session = useSessionStore();
const dashboard = useMainDashboardStore(); const dashboard = useMainDashboardStore();
@@ -38,8 +44,20 @@ const isMobile = useMediaQuery('(max-width: 939.98px)');
const npcMode = ref(0); const npcMode = ref(0);
const globalNavigation = ref<MainNavigationEntry[]>(defaultGlobalNavigation); const globalNavigation = ref<MainNavigationEntry[]>(defaultGlobalNavigation);
const versionDialog = ref<HTMLDialogElement | null>(null); const versionDialog = ref<HTMLDialogElement | null>(null);
const mobilePanelOrder = ref(loadMobileMainPanelOrder());
const navigationUrl = (import.meta.env.VITE_GATEWAY_API_URL ?? '/api/trpc').replace(/\/trpc\/?$/u, '/navigation'); const navigationUrl = (import.meta.env.VITE_GATEWAY_API_URL ?? '/api/trpc').replace(/\/trpc\/?$/u, '/navigation');
const reloadMobilePanelOrder = () => {
mobilePanelOrder.value = loadMobileMainPanelOrder();
};
const handleMobilePanelStorage = (event: StorageEvent) => {
if (event.key === MOBILE_MAIN_PANEL_ORDER_STORAGE_KEY) reloadMobilePanelOrder();
};
const isFlushMobilePanel = (panelId: MobileMainPanelId, index: number): boolean => {
const previous = mobilePanelOrder.value[index - 1];
return (panelId === 'general' && previous === 'nation') || (panelId === 'city' && previous === 'general');
};
const { const {
loading, loading,
refreshing, refreshing,
@@ -100,10 +118,14 @@ onUnmounted(() => {
clearTimeout(surveyNoticeTimer); clearTimeout(surveyNoticeTimer);
} }
dashboard.stopRealtime(); dashboard.stopRealtime();
window.removeEventListener('storage', handleMobilePanelStorage);
document.removeEventListener(MOBILE_MAIN_PANEL_ORDER_CHANGED_EVENT, reloadMobilePanelOrder);
}); });
onMounted(() => { onMounted(() => {
dashboard.startRealtime(); dashboard.startRealtime();
window.addEventListener('storage', handleMobilePanelStorage);
document.addEventListener(MOBILE_MAIN_PANEL_ORDER_CHANGED_EVENT, reloadMobilePanelOrder);
void fetch(navigationUrl, { headers: { Accept: 'application/json' } }) void fetch(navigationUrl, { headers: { Accept: 'application/json' } })
.then(async (response) => { .then(async (response) => {
if (!response.ok) throw new Error(`메뉴 설정 조회 실패: HTTP ${response.status}`); if (!response.ok) throw new Error(`메뉴 설정 조회 실패: HTTP ${response.status}`);
@@ -130,10 +152,7 @@ const repeatGeneralTurns = (amount: number) => {
}; };
const loadMainData = async () => { const loadMainData = async () => {
const [, worldState] = await Promise.all([ const [, worldState] = await Promise.all([dashboard.loadMainData(), trpc.world.getState.query().catch(() => null)]);
dashboard.loadMainData(),
trpc.world.getState.query().catch(() => null),
]);
npcMode.value = worldState?.config.npcMode ?? 0; npcMode.value = worldState?.config.npcMode ?? 0;
}; };
@@ -239,7 +258,8 @@ watch(
</aside> </aside>
<section v-if="isMobile" class="layout-mobile"> <section v-if="isMobile" class="layout-mobile">
<div class="mobile-panel"> <template v-for="(panelId, panelIndex) in mobilePanelOrder" :key="panelId">
<div v-if="panelId === 'commands'" class="mobile-panel" data-mobile-panel-id="commands">
<PanelCard title="명령 목록" subtitle="예턴/명령 배치 영역" data-main-target="commands"> <PanelCard title="명령 목록" subtitle="예턴/명령 배치 영역" data-main-target="commands">
<CommandListPanel <CommandListPanel
:command-table="commandTable" :command-table="commandTable"
@@ -261,7 +281,7 @@ watch(
</PanelCard> </PanelCard>
</div> </div>
<div class="mobile-panel"> <div v-else-if="panelId === 'nation-menu'" class="mobile-panel" data-mobile-panel-id="nation-menu">
<MainNationMenu <MainNationMenu
class="nation-menu-middle" class="nation-menu-middle"
:access="nationAccess" :access="nationAccess"
@@ -270,25 +290,45 @@ watch(
/> />
</div> </div>
<div class="mobile-panel"> <div v-else-if="panelId === 'nation'" class="mobile-panel" data-mobile-panel-id="nation">
<PanelCard title="국가 정보" data-main-target="nation"> <PanelCard title="국가 정보" data-main-target="nation">
<NationBasicCard :nation="nation" :loading="loading" /> <NationBasicCard :nation="nation" :loading="loading" />
</PanelCard> </PanelCard>
</div>
<div
v-else-if="panelId === 'general'"
class="mobile-panel"
:class="{ 'mobile-panel--flush': isFlushMobilePanel(panelId, panelIndex) }"
data-mobile-panel-id="general"
>
<PanelCard title="장수 스탯" data-main-target="general"> <PanelCard title="장수 스탯" data-main-target="general">
<GeneralBasicCard :general="general" :loading="loading" :nation-color="nation?.color" /> <GeneralBasicCard :general="general" :loading="loading" :nation-color="nation?.color" />
</PanelCard> </PanelCard>
</div>
<div
v-else-if="panelId === 'city'"
class="mobile-panel"
:class="{ 'mobile-panel--flush': isFlushMobilePanel(panelId, panelIndex) }"
data-mobile-panel-id="city"
>
<PanelCard title="도시 정보" data-main-target="city"> <PanelCard title="도시 정보" data-main-target="city">
<CityBasicCard :city="city" :loading="loading" /> <CityBasicCard :city="city" :loading="loading" />
</PanelCard> </PanelCard>
</div> </div>
<div class="mobile-panel"> <div v-else-if="panelId === 'map'" class="mobile-panel" data-mobile-panel-id="map">
<PanelCard title="지도" data-main-target="map"> <PanelCard title="지도" data-main-target="map">
<MapViewer :map-data="worldMap" :map-layout="mapLayout" :loading="loading" /> <MapViewer :map-data="worldMap" :map-layout="mapLayout" :loading="loading" />
</PanelCard> </PanelCard>
</div> </div>
<div class="mobile-panel record-zone-mobile"> <div
v-else-if="panelId === 'records'"
class="mobile-panel record-zone-mobile"
data-mobile-panel-id="records"
>
<RecordPanel title="장수 동향" data-main-target="global-records"> <RecordPanel title="장수 동향" data-main-target="global-records">
<SkeletonLines v-if="loading" :lines="4" /> <SkeletonLines v-if="loading" :lines="4" />
<div v-else-if="recordsError" class="record-error" role="alert">{{ recordsError }}</div> <div v-else-if="recordsError" class="record-error" role="alert">{{ recordsError }}</div>
@@ -334,15 +374,17 @@ watch(
</div> </div>
<MainGlobalMenu <MainGlobalMenu
v-else-if="panelId === 'global-menu'"
class="common-menu-middle" class="common-menu-middle"
data-menu-position="middle" data-menu-position="middle"
data-mobile-panel-id="global-menu"
:npc-mode="npcMode" :npc-mode="npcMode"
:vote-active="voteActive" :vote-active="voteActive"
:entries="globalNavigation" :entries="globalNavigation"
@action="handleNavigationAction" @action="handleNavigationAction"
/> />
<div class="mobile-panel"> <div v-else class="mobile-panel" data-mobile-panel-id="messages">
<MessagePanel <MessagePanel
class="mobile-message-panel" class="mobile-message-panel"
:messages="messages" :messages="messages"
@@ -364,6 +406,7 @@ watch(
@delete="dashboard.deleteMessage" @delete="dashboard.deleteMessage"
/> />
</div> </div>
</template>
</section> </section>
<section v-else class="layout-desktop"> <section v-else class="layout-desktop">
@@ -798,8 +841,8 @@ button {
gap: 0; gap: 0;
} }
.layout-mobile > .mobile-panel:nth-of-type(3) { .layout-mobile > .mobile-panel--flush {
gap: 0; margin-top: -4px;
} }
.layout-mobile [data-main-target='commands'] { .layout-mobile [data-main-target='commands'] {
+239 -1
View File
@@ -9,11 +9,19 @@ import { resolveGeneralIconUrl, useDefaultGeneralIcon } from '../utils/generalIc
import LegacyGeneralProgress from '../components/ui/LegacyGeneralProgress.vue'; import LegacyGeneralProgress from '../components/ui/LegacyGeneralProgress.vue';
import GeneralBasicCard from '../components/main/GeneralBasicCard.vue'; import GeneralBasicCard from '../components/main/GeneralBasicCard.vue';
import { useGameFeedback } from '../composables/useGameFeedback'; import { useGameFeedback } from '../composables/useGameFeedback';
import {
DEFAULT_MOBILE_MAIN_PANEL_ORDER,
loadMobileMainPanelOrder,
MOBILE_MAIN_PANEL_DEFINITIONS,
moveMobileMainPanel,
saveMobileMainPanelOrder,
type MobileMainPanelId,
} from '../utils/mobileMainPanelOrder';
const SCREEN_MODE_KEY = 'sam.screenMode'; const SCREEN_MODE_KEY = 'sam.screenMode';
const CUSTOM_CSS_KEY = 'sam_customCSS'; const CUSTOM_CSS_KEY = 'sam_customCSS';
const PENDING_DIE_ON_PRESTART_KEY = 'sam.pending.dieOnPrestart'; const PENDING_DIE_ON_PRESTART_KEY = 'sam.pending.dieOnPrestart';
const { error: showErrorToast, showDialog } = useGameFeedback(); const { success: showSuccessToast, error: showErrorToast, showDialog } = useGameFeedback();
type ScreenMode = 'auto' | '500px' | '1000px'; type ScreenMode = 'auto' | '500px' | '1000px';
type LogType = 'generalHistory' | 'battleDetail' | 'battleResult' | 'generalAction'; type LogType = 'generalHistory' | 'battleDetail' | 'battleResult' | 'generalAction';
type ItemSlotKey = 'horse' | 'weapon' | 'book' | 'item'; type ItemSlotKey = 'horse' | 'weapon' | 'book' | 'item';
@@ -48,6 +56,9 @@ const screenMode = ref<ScreenMode>('auto');
const customCss = ref(''); const customCss = ref('');
const selectedIconId = ref(''); const selectedIconId = ref('');
const cssSaving = ref(false); const cssSaving = ref(false);
const mobileLayoutDialog = ref<HTMLDialogElement | null>(null);
const mobileLayoutOrder = ref<MobileMainPanelId[]>(loadMobileMainPanelOrder());
const mobileLayoutDragIndex = ref<number | null>(null);
const session = useSessionStore(); const session = useSessionStore();
let cssTimer: number | null = null; let cssTimer: number | null = null;
const readPendingDieOnPrestartId = (): string => { const readPendingDieOnPrestartId = (): string => {
@@ -169,6 +180,43 @@ const items = computed<Array<{ key: ItemSlotKey; slotName: string; displayName:
); );
const iconChoices = computed(() => data.value?.iconChoices ?? []); const iconChoices = computed(() => data.value?.iconChoices ?? []);
const selectedIcon = computed(() => iconChoices.value.find((icon) => icon.id === selectedIconId.value) ?? null); const selectedIcon = computed(() => iconChoices.value.find((icon) => icon.id === selectedIconId.value) ?? null);
const mobileLayoutLabels = Object.fromEntries(
MOBILE_MAIN_PANEL_DEFINITIONS.map(({ id, label }) => [id, label])
) as Record<MobileMainPanelId, string>;
const openMobileLayoutDialog = () => {
mobileLayoutOrder.value = loadMobileMainPanelOrder();
mobileLayoutDialog.value?.showModal();
window.requestAnimationFrame(() => mobileLayoutDialog.value?.querySelector<HTMLButtonElement>('button')?.focus());
};
const moveMobileLayoutItem = (fromIndex: number, toIndex: number) => {
mobileLayoutOrder.value = moveMobileMainPanel(mobileLayoutOrder.value, fromIndex, toIndex);
};
const startMobileLayoutDrag = (event: DragEvent, index: number) => {
mobileLayoutDragIndex.value = index;
event.dataTransfer?.setData('text/plain', mobileLayoutOrder.value[index] ?? '');
if (event.dataTransfer) event.dataTransfer.effectAllowed = 'move';
};
const dropMobileLayoutItem = (event: DragEvent, targetIndex: number) => {
event.preventDefault();
const sourceIndex = mobileLayoutDragIndex.value;
mobileLayoutDragIndex.value = null;
if (sourceIndex === null) return;
moveMobileLayoutItem(sourceIndex, targetIndex);
};
const resetMobileLayoutOrder = () => {
mobileLayoutOrder.value = [...DEFAULT_MOBILE_MAIN_PANEL_ORDER];
};
const applyMobileLayoutOrder = () => {
mobileLayoutOrder.value = saveMobileMainPanelOrder(mobileLayoutOrder.value);
mobileLayoutDialog.value?.close();
showSuccessToast('모바일 메인 레이아웃 순서를 저장했습니다.');
};
const autorunUser = computed(() => asRecord(world.value?.meta.autorun_user)); const autorunUser = computed(() => asRecord(world.value?.meta.autorun_user));
const showAutoNationTurn = computed(() => asRecord(autorunUser.value.options).chief !== false); const showAutoNationTurn = computed(() => asRecord(autorunUser.value.options).chief !== false);
@@ -581,6 +629,16 @@ onMounted(() => {
</div> </div>
</div> </div>
<div class="mobile-layout-setting-row">
<span>
모바일 레이아웃 순서 바꾸기<br />
<small>500px 메인 화면의 패널 순서를 기기에 저장합니다.</small>
</span>
<button class="mobile-layout-open" type="button" @click="openMobileLayoutDialog">
순서 바꾸기
</button>
</div>
<div class="item-title">아이템 파기</div> <div class="item-title">아이템 파기</div>
<div class="item-group"> <div class="item-group">
<button <button
@@ -635,6 +693,61 @@ onMounted(() => {
삼국지 모의전투 HiDCHe / KOEI의 이미지를 사용, 응용하였습니다 / 제작: HideD / Credit 삼국지 모의전투 HiDCHe / KOEI의 이미지를 사용, 응용하였습니다 / 제작: HideD / Credit
</footer> </footer>
</main> </main>
<dialog
ref="mobileLayoutDialog"
class="mobile-layout-dialog"
aria-labelledby="mobile-layout-dialog-title"
@close="mobileLayoutDragIndex = null"
>
<div class="mobile-layout-dialog__header">
<h2 id="mobile-layout-dialog-title">모바일 레이아웃 순서 바꾸기</h2>
<form method="dialog">
<button type="submit" aria-label="모바일 레이아웃 순서 닫기">×</button>
</form>
</div>
<p>항목을 끌어 놓거나 ·아래 버튼으로 상대 순서를 바꿉니다.</p>
<ol class="mobile-layout-list">
<li
v-for="(panelId, index) in mobileLayoutOrder"
:key="panelId"
:data-mobile-layout-id="panelId"
draggable="true"
@dragstart="startMobileLayoutDrag($event, index)"
@dragend="mobileLayoutDragIndex = null"
@dragover.prevent
@drop.stop="dropMobileLayoutItem($event, index)"
>
<span class="mobile-layout-handle" aria-hidden="true"></span>
<span class="mobile-layout-label">
<span class="mobile-layout-position">{{ index + 1 }}</span>
{{ mobileLayoutLabels[panelId] }}
</span>
<span class="mobile-layout-move-buttons">
<button
type="button"
:aria-label="`${mobileLayoutLabels[panelId]} 위로`"
:disabled="index === 0"
@click="moveMobileLayoutItem(index, index - 1)"
>
</button>
<button
type="button"
:aria-label="`${mobileLayoutLabels[panelId]} 아래로`"
:disabled="index === mobileLayoutOrder.length - 1"
@click="moveMobileLayoutItem(index, index + 1)"
>
</button>
</span>
</li>
</ol>
<div class="mobile-layout-dialog__actions">
<button type="button" @click="resetMobileLayoutOrder">Ref 초깃값</button>
<form method="dialog"><button type="submit">취소</button></form>
<button class="mobile-layout-apply" type="button" @click="applyMobileLayoutOrder">적용</button>
</div>
</dialog>
<div class="my-page-mobile-scroll-spacer" aria-hidden="true"></div> <div class="my-page-mobile-scroll-spacer" aria-hidden="true"></div>
</template> </template>
@@ -822,6 +935,125 @@ button:disabled {
align-items: center; align-items: center;
margin: 14px 0; margin: 14px 0;
} }
.mobile-layout-setting-row {
display: grid;
grid-template-columns: minmax(0, 1fr) 128px;
align-items: center;
gap: 8px;
margin: 14px 0;
}
.mobile-layout-setting-row small {
color: orange;
}
.mobile-layout-open {
min-height: 34px;
background: #315f86;
font-weight: 700;
}
.mobile-layout-dialog {
box-sizing: border-box;
width: min(460px, calc(100vw - 24px));
max-height: calc(100dvh - 24px);
margin: auto;
overflow: auto;
border: 1px solid #777;
border-radius: 4px;
padding: 12px;
background: #171717 var(--sammo-texture-walnut);
color: #fff;
font: 14px/1.3 var(--sammo-font-sans);
}
.mobile-layout-dialog::backdrop {
background: rgb(0 0 0 / 72%);
}
.mobile-layout-dialog__header,
.mobile-layout-dialog__actions,
.mobile-layout-move-buttons {
display: flex;
align-items: center;
}
.mobile-layout-dialog__header {
justify-content: space-between;
gap: 12px;
}
.mobile-layout-dialog__header h2,
.mobile-layout-dialog p {
margin: 0 0 10px;
}
.mobile-layout-dialog__header h2 {
color: skyblue;
font-size: 18px;
}
.mobile-layout-dialog__header form,
.mobile-layout-dialog__actions form {
margin: 0;
}
.mobile-layout-dialog__header button {
min-width: 32px;
min-height: 32px;
font-size: 20px;
}
.mobile-layout-list {
display: grid;
gap: 6px;
margin: 0;
padding: 0;
list-style: none;
}
.mobile-layout-list > li {
display: grid;
grid-template-columns: 28px minmax(0, 1fr) auto;
min-height: 44px;
align-items: center;
border: 1px solid #777;
background: #172a52 var(--sammo-texture-blue);
cursor: grab;
}
.mobile-layout-list > li:active {
cursor: grabbing;
}
.mobile-layout-handle {
color: #aaa;
text-align: center;
font-size: 20px;
}
.mobile-layout-label {
min-width: 0;
font-weight: 700;
}
.mobile-layout-position {
display: inline-grid;
width: 22px;
height: 22px;
place-items: center;
margin-right: 4px;
border: 1px solid #7186a7;
border-radius: 50%;
font-size: 12px;
}
.mobile-layout-move-buttons {
gap: 4px;
padding-right: 5px;
}
.mobile-layout-move-buttons button {
width: 36px;
min-height: 34px;
background: #315f86;
font-weight: 700;
}
.mobile-layout-dialog__actions {
justify-content: flex-end;
gap: 6px;
margin-top: 12px;
}
.mobile-layout-dialog__actions button {
min-height: 34px;
padding: 4px 10px;
}
.mobile-layout-dialog__actions .mobile-layout-apply {
background: #225500;
font-weight: 700;
}
.button-group { .button-group {
display: flex; display: flex;
} }
@@ -933,6 +1165,12 @@ button:disabled {
grid-template-columns: 1fr; grid-template-columns: 1fr;
gap: 6px; gap: 6px;
} }
.mobile-layout-setting-row {
grid-template-columns: 1fr;
}
.mobile-layout-open {
width: 100%;
}
.button-group { .button-group {
overflow-x: auto; overflow-x: auto;
} }
@@ -1,16 +1,28 @@
<script setup lang="ts"> <script setup lang="ts">
import { formatServerDateTime } from '@sammo-ts/common';
import { computed, onMounted, ref } from 'vue'; import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router'; import { useRouter } from 'vue-router';
import { useGameFeedback } from '../composables/useGameFeedback';
import { getNpcColor } from '../utils/npcColor'; import { getNpcColor } from '../utils/npcColor';
import { legacyNationTextColor } from '../utils/legacyNationColor'; import { legacyNationTextColor } from '../utils/legacyNationColor';
import { cityLevelMap, regionMap } from '../utils/nationFormat'; import { cityLevelMap, regionMap } from '../utils/nationFormat';
import { trpc } from '../utils/trpc'; import { trpc } from '../utils/trpc';
type Result = Awaited<ReturnType<typeof trpc.nation.getCityOverview.query>>; type Result = Awaited<ReturnType<typeof trpc.nation.getCityOverview.query>>;
type SecretResult = Awaited<ReturnType<typeof trpc.nation.getSecretGeneralList.query>>;
type PersonnelResult = Awaited<ReturnType<typeof trpc.nation.getPersonnelInfo.query>>;
type City = Result['cities'][number]; type City = Result['cities'][number];
type SecretGeneral = SecretResult['generals'][number];
type OfficerLevel = 2 | 3 | 4;
type Sort = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12; type Sort = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12;
const data = ref<Result | null>(null); const data = ref<Result | null>(null);
const secretData = ref<SecretResult | null>(null);
const personnelData = ref<PersonnelResult | null>(null);
const error = ref(''); const error = ref('');
const integrationError = ref('');
const secretLoading = ref(false);
const personnelLoading = ref(false);
const pendingAppointment = ref('');
const sort = ref<Sort>(10); const sort = ref<Sort>(10);
const extraSort = ref< const extraSort = ref<
| 'name' | 'name'
@@ -25,10 +37,16 @@ const extraSort = ref<
| null | null
>(null); >(null);
const router = useRouter(); const router = useRouter();
const { error: showErrorToast, info: showInfoToast, success: showSuccessToast } = useGameFeedback();
const options = ['기본', '인구', '인구율', '민심', '농업', '상업', '치안', '수비', '성벽', '시세', '지역', '규모']; const options = ['기본', '인구', '인구율', '민심', '농업', '상업', '치안', '수비', '성벽', '시세', '지역', '규모'];
const officerLabels: Record<OfficerLevel, string> = { 4: '태수', 3: '군사', 2: '종사' };
const generalsForCity = (cityId: number) => data.value?.generals.filter((general) => general.cityId === cityId) ?? []; const generalsForCity = (cityId: number) => data.value?.generals.filter((general) => general.cityId === cityId) ?? [];
const secretGeneralsForCity = (cityId: number) =>
secretData.value?.generals.filter((general) => general.cityId === cityId) ?? [];
const displayGeneralName = (general: Result['generals'][number]) => const displayGeneralName = (general: Result['generals'][number]) =>
general.npcState > 0 && !/^[ⓜⓝ]/u.test(general.name) ? `${general.name}` : general.name; general.npcState > 0 && !/^[ⓜⓝ]/u.test(general.name) ? `${general.name}` : general.name;
const displaySecretGeneralName = (general: SecretGeneral) =>
general.npcState > 0 && !/^[ⓜⓝ㉥]/u.test(general.name) ? `${general.name}` : general.name;
const generalCount = (cityId: number) => const generalCount = (cityId: number) =>
data.value?.generals.filter((general) => general.cityId === cityId).length ?? 0; data.value?.generals.filter((general) => general.cityId === cityId).length ?? 0;
const cities = computed(() => { const cities = computed(() => {
@@ -91,6 +109,138 @@ const developmentClass = (
const isRegionBreak = (city: City, index: number) => const isRegionBreak = (city: City, index: number) =>
sort.value === 10 && extraSort.value === null && (index === 0 || cities.value[index - 1]?.region !== city.region); sort.value === 10 && extraSort.value === null && (index === 0 || cities.value[index - 1]?.region !== city.region);
const officer = (city: City, level: 2 | 3 | 4) => city.officers[level]?.name ?? '-'; const officer = (city: City, level: 2 | 3 | 4) => city.officers[level]?.name ?? '-';
const officerIsStationed = (city: City, level: OfficerLevel): boolean =>
secretData.value !== null && city.officers[level]?.cityId === city.id;
const personnelGeneralMap = computed(
() => new Map((personnelData.value?.generals ?? []).map((general) => [general.id, general]))
);
const personnelCityMap = computed(
() => new Map((personnelData.value?.cityAssignments ?? []).map((city) => [city.id, city]))
);
const officerLocked = (cityId: number, level: OfficerLevel): boolean => {
const officerSet = personnelCityMap.value.get(cityId)?.officerSet ?? 0;
return (officerSet & (1 << level)) !== 0;
};
const canAppoint = (cityId: number, generalId: number, level: OfficerLevel): boolean => {
if (!personnelData.value?.me.canManage || officerLocked(cityId, level)) return false;
const general = personnelGeneralMap.value.get(generalId);
if (!general || general.officerLevel === 12) return false;
if (level === 4) return general.stats.strength >= personnelData.value.chiefStatMin;
if (level === 3) return general.stats.intelligence >= personnelData.value.chiefStatMin;
return true;
};
const canShowAppointmentButtons = (generalId: number): boolean => {
const general = personnelGeneralMap.value.get(generalId);
return personnelData.value?.me.canManage === true && general !== undefined && general.officerLevel !== 12;
};
const isChief = (generalId: number): boolean => (personnelGeneralMap.value.get(generalId)?.officerLevel ?? 0) >= 5;
const appointmentKey = (cityId: number, generalId: number, level: OfficerLevel): string =>
`${cityId}:${generalId}:${level}`;
const commandNeedsAttention = (city: City, command: string): boolean => {
const normalized = command.replaceAll(/\s/gu, '');
if (normalized.includes('정착장려')) {
return city.population - city.populationMax > -20_000 || city.population > city.populationMax * 0.92;
}
if (normalized.includes('농지개간')) return city.agriculture - city.agricultureMax > -1_000;
if (normalized.includes('상업투자')) return city.commerce - city.commerceMax > -1_000;
if (normalized.includes('치안강화')) return city.security - city.securityMax > -1_000;
if (normalized.includes('수비강화')) return city.defence - city.defenceMax > -700;
if (normalized.includes('성벽보수')) return city.wall - city.wallMax > -700;
return false;
};
const loadSecretIntegration = async (): Promise<void> => {
if (secretLoading.value) {
showInfoToast('암행부 정보를 불러오는 중입니다.');
return;
}
if (secretData.value) {
showInfoToast('암행부 정보가 이미 연동되어 있습니다.');
return;
}
secretLoading.value = true;
integrationError.value = '';
try {
secretData.value = await trpc.nation.getSecretGeneralList.query();
} catch (cause) {
integrationError.value = cause instanceof Error ? cause.message : '암행부 연동에 실패했습니다.';
showErrorToast(integrationError.value);
} finally {
secretLoading.value = false;
}
};
const loadPersonnelIntegration = async (): Promise<void> => {
if (personnelLoading.value) {
showInfoToast('인사부 정보를 불러오는 중입니다.');
return;
}
if (personnelData.value?.me.canManage) {
showInfoToast('인사부 정보가 이미 연동되어 있습니다.');
return;
}
personnelLoading.value = true;
integrationError.value = '';
try {
const personnel = await trpc.nation.getPersonnelInfo.query();
if (!personnel.me.canManage) {
window.alert('수뇌가 아닙니다!');
return;
}
personnelData.value = personnel;
} catch (cause) {
integrationError.value = cause instanceof Error ? cause.message : '인사부 연동에 실패했습니다.';
showErrorToast(integrationError.value);
} finally {
personnelLoading.value = false;
}
};
const refreshIntegratedData = async (): Promise<void> => {
const [overview, secret, personnel] = await Promise.all([
trpc.nation.getCityOverview.query(),
trpc.nation.getSecretGeneralList.query(),
trpc.nation.getPersonnelInfo.query(),
]);
data.value = overview;
secretData.value = secret;
personnelData.value = personnel;
};
const appointCityOfficer = async (city: City, general: SecretGeneral, level: OfficerLevel): Promise<void> => {
if (!canAppoint(city.id, general.id, level)) return;
const key = appointmentKey(city.id, general.id, level);
if (pendingAppointment.value) {
showInfoToast('다른 임명을 처리하는 중입니다.');
return;
}
if (isChief(general.id) && !window.confirm('수뇌입니다. 임명할까요?')) return;
pendingAppointment.value = key;
integrationError.value = '';
try {
await trpc.nation.appoint.mutate({
destGeneralId: general.id,
destCityId: city.id,
officerLevel: level,
});
showSuccessToast(`${general.name}을(를) ${city.name} ${officerLabels[level]}로 임명했습니다.`);
try {
await refreshIntegratedData();
} catch (cause) {
integrationError.value =
cause instanceof Error
? `임명은 완료됐지만 화면을 갱신하지 못했습니다: ${cause.message}`
: '임명은 완료됐지만 화면을 갱신하지 못했습니다.';
showErrorToast(integrationError.value);
}
} catch (cause) {
integrationError.value = cause instanceof Error ? cause.message : '임명에 실패했습니다.';
showErrorToast(integrationError.value);
} finally {
pendingAppointment.value = '';
}
};
onMounted(async () => { onMounted(async () => {
try { try {
data.value = await trpc.nation.getCityOverview.query(); data.value = await trpc.nation.getCityOverview.query();
@@ -121,7 +271,18 @@ onMounted(async () => {
</option> </option>
</select> </select>
<input type="submit" value="정렬하기" /> <input type="submit" value="정렬하기" />
<button type="button">암행부 연동</button> <button type="button" :aria-busy="secretLoading" @click="loadSecretIntegration">
암행부 연동
</button>
<button
v-if="secretData"
id="load-duty-button"
type="button"
:aria-busy="personnelLoading"
@click="loadPersonnelIntegration"
>
인사부 연동
</button>
</form> </form>
</td> </td>
</tr> </tr>
@@ -141,12 +302,14 @@ onMounted(async () => {
</tr> </tr>
</tbody> </tbody>
</table> </table>
<p v-if="error" class="error">{{ error }}</p> <p v-if="error" class="error" role="alert">{{ error }}</p>
<p v-if="integrationError" class="error integration-error" role="alert">{{ integrationError }}</p>
<table <table
v-for="(city, index) in cities" v-for="(city, index) in cities"
:key="city.id" :key="city.id"
class="legacy-table city legacy-bg2" class="legacy-table city legacy-bg2"
:class="{ 'region-break': isRegionBreak(city, index) }" :class="{ 'region-break': isRegionBreak(city, index) }"
:data-city-id="city.id"
> >
<tbody> <tbody>
<tr> <tr>
@@ -223,18 +386,24 @@ onMounted(async () => {
<th>시세</th> <th>시세</th>
<td>{{ city.trade ?? '-' }}%</td> <td>{{ city.trade ?? '-' }}%</td>
<th>태수</th> <th>태수</th>
<td>{{ officer(city, 4) }}</td> <td class="officer-4-value" :class="{ 'effective-officer': officerIsStationed(city, 4) }">
{{ officer(city, 4) }}
</td>
<th>군사</th> <th>군사</th>
<td>{{ officer(city, 3) }}</td> <td class="officer-3-value" :class="{ 'effective-officer': officerIsStationed(city, 3) }">
{{ officer(city, 3) }}
</td>
<th>종사</th> <th>종사</th>
<td>{{ officer(city, 2) }}</td> <td class="officer-2-value" :class="{ 'effective-officer': officerIsStationed(city, 2) }">
{{ officer(city, 2) }}
</td>
</tr> </tr>
<tr> <tr>
<th>장수</th> <th>장수</th>
<td colspan="9" class="general-list"> <td colspan="9" class="general-list">
<template v-if="generalsForCity(city.id).length"> <template v-if="generalsForCity(city.id).length">
<template v-for="(general, index) in generalsForCity(city.id)" :key="general.id"> <template v-for="(general, cityGeneralIndex) in generalsForCity(city.id)" :key="general.id">
<span v-if="index">, </span <span v-if="cityGeneralIndex">, </span
><span :style="{ color: getNpcColor(general.npcState) }">{{ ><span :style="{ color: getNpcColor(general.npcState) }">{{
displayGeneralName(general) displayGeneralName(general)
}}</span> }}</span>
@@ -243,6 +412,108 @@ onMounted(async () => {
<template v-else>-</template> <template v-else>-</template>
</td> </td>
</tr> </tr>
<tr v-if="secretData" class="secret-integration-row">
<td colspan="10">
<table class="city-user-table legacy-bg0">
<colgroup>
<col class="secret-name-column" />
<col class="secret-stat-column" />
<col class="secret-troop-column" />
<col class="secret-gold-column" />
<col class="secret-rice-column" />
<col class="secret-defence-column" />
<col class="secret-crew-type-column" />
<col class="secret-crew-column" />
<col class="secret-train-column" />
<col class="secret-atmos-column" />
<col class="secret-command-column" />
<col class="secret-kill-column" />
<col class="secret-turn-column" />
</colgroup>
<thead>
<tr>
<th> </th>
<th>통무지</th>
<th> </th>
<th> </th>
<th> </th>
<th></th>
<th> </th>
<th> </th>
<th>훈련</th>
<th>사기</th>
<th> </th>
<th>삭턴</th>
<th></th>
</tr>
</thead>
<tbody>
<tr
v-for="general in secretGeneralsForCity(city.id)"
:key="general.id"
:data-general-id="general.id"
>
<td class="secret-name-cell">
<span :style="{ color: getNpcColor(general.npcState) }">{{
displaySecretGeneralName(general)
}}</span
><br />Lv {{ general.experienceLevel }}
<template v-if="canShowAppointmentButtons(general.id)">
<br class="for-duty" />
<button
v-for="level in [4, 3, 2] as const"
:key="level"
type="button"
class="appointment-button for-duty"
:class="[`mode-${level}`, { 'chief-target': isChief(general.id) }]"
:disabled="
!canAppoint(city.id, general.id, level) || pendingAppointment !== ''
"
:aria-label="`${general.name}() ${city.name} ${officerLabels[level]} 임명`"
@click="appointCityOfficer(city, general, level)"
>
{{ officerLabels[level].slice(0, 1) }}
</button>
</template>
</td>
<td :class="{ injured: general.injury > 0 }">
{{ general.stats.leadership
}}<span v-if="general.leadershipBonus" class="bonus"
>+{{ general.leadershipBonus }}</span
>{{ general.stats.strength }}{{ general.stats.intelligence }}
</td>
<td>{{ general.troopName ?? '-' }}</td>
<td>{{ general.gold }}</td>
<td>{{ general.rice }}</td>
<td>{{ general.defenceTrainText }}</td>
<td>{{ general.crewTypeName }}</td>
<td>{{ general.crew }}</td>
<td>{{ general.train }}</td>
<td>{{ general.atmos }}</td>
<td class="secret-commands">
<template v-if="general.npcState >= 2">NPC 장수</template>
<template v-else>
<div
v-for="(command, commandIndex) in general.reservedCommands"
:key="commandIndex"
>
{{ commandIndex + 1 }} :
<span
:class="{
'command-attention': commandNeedsAttention(city, command),
}"
>{{ command }}</span
>
</div>
</template>
</td>
<td>{{ general.killTurn }}</td>
<td>{{ formatServerDateTime(general.turnTime, { format: 'minuteSecond' }) }}</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody> </tbody>
</table> </table>
<table class="legacy-table legacy-bg0 title footer"> <table class="legacy-table legacy-bg0 title footer">
@@ -304,6 +575,81 @@ onMounted(async () => {
.general-list { .general-list {
text-align: left !important; text-align: left !important;
} }
.effective-officer {
color: lightgreen;
}
.secret-integration-row > td {
padding: 0;
}
.city-user-table {
width: 940px;
margin: 0 auto;
border-collapse: collapse;
table-layout: fixed;
}
.city-user-table td,
.city-user-table th {
width: auto;
border: 1px solid #808080;
padding: 0;
text-align: center;
word-break: break-all;
}
.city-user-table th {
background-image: var(--sammo-texture-green);
}
.secret-name-column,
.secret-stat-column,
.secret-troop-column {
width: 100px;
}
.secret-gold-column,
.secret-rice-column,
.secret-crew-type-column,
.secret-crew-column,
.secret-kill-column,
.secret-turn-column {
width: 60px;
}
.secret-defence-column {
width: 30px;
}
.secret-train-column,
.secret-atmos-column {
width: 50px;
}
.secret-command-column {
width: 150px;
}
.secret-name-cell {
line-height: normal;
}
.secret-commands {
text-align: left !important;
font-size: 12px;
}
.bonus {
color: cyan;
}
.injured {
color: red;
}
.command-attention {
color: yellow;
}
.nation-cities-page .appointment-button {
margin: 0;
padding: 1px 4px;
}
.nation-cities-page .appointment-button.chief-target:not(:disabled) {
color: red;
}
.nation-cities-page .appointment-button:disabled {
border: 0;
background: transparent;
color: inherit;
cursor: default;
}
.capital { .capital {
color: #0ff; color: #0ff;
} }
@@ -0,0 +1,55 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
DEFAULT_MOBILE_MAIN_PANEL_ORDER,
MOBILE_MAIN_PANEL_ORDER_STORAGE_KEY,
loadMobileMainPanelOrder,
moveMobileMainPanel,
normalizeMobileMainPanelOrder,
parseMobileMainPanelOrder,
saveMobileMainPanelOrder,
} from '../src/utils/mobileMainPanelOrder.ts';
void test('uses the Ref mobile panel order as the default', () => {
assert.deepEqual(DEFAULT_MOBILE_MAIN_PANEL_ORDER, [
'commands',
'nation-menu',
'nation',
'general',
'city',
'map',
'records',
'global-menu',
'messages',
]);
assert.deepEqual(parseMobileMainPanelOrder(null), DEFAULT_MOBILE_MAIN_PANEL_ORDER);
});
void test('keeps known unique entries and appends newly introduced panels', () => {
assert.deepEqual(normalizeMobileMainPanelOrder(['messages', 'commands', 'messages', 'unknown']), [
'messages',
'commands',
'nation-menu',
'nation',
'general',
'city',
'map',
'records',
'global-menu',
]);
assert.deepEqual(parseMobileMainPanelOrder('{broken'), DEFAULT_MOBILE_MAIN_PANEL_ORDER);
});
void test('moves and persists the normalized order', () => {
const values = new Map<string, string>();
const storage = {
getItem: (key: string) => values.get(key) ?? null,
setItem: (key: string, value: string) => values.set(key, value),
};
const moved = moveMobileMainPanel(DEFAULT_MOBILE_MAIN_PANEL_ORDER, 8, 0);
assert.equal(moved[0], 'messages');
assert.deepEqual(saveMobileMainPanelOrder(moved, storage), moved);
assert.equal(values.has(MOBILE_MAIN_PANEL_ORDER_STORAGE_KEY), true);
assert.deepEqual(loadMobileMainPanelOrder(storage), moved);
});
@@ -1,5 +1,6 @@
import { createItemModuleRegistry, ItemLoader, ITEM_KEYS, loadItemModules } from '@sammo-ts/logic/items/index.js';
import type { ItemModule } from '@sammo-ts/logic/items/types.js'; import type { ItemModule } from '@sammo-ts/logic/items/types.js';
import type { UniqueItemPool } from './uniqueLottery.js'; import { resolveUniqueConfig, type UniqueItemPool, type UniqueLotteryConfig } from './uniqueLottery.js';
const LEGACY_UNIQUE_ITEM_KEYS: Readonly<Record<ItemModule['slot'], readonly string[]>> = { const LEGACY_UNIQUE_ITEM_KEYS: Readonly<Record<ItemModule['slot'], readonly string[]>> = {
horse: [ horse: [
@@ -125,3 +126,38 @@ export const buildLegacyDefaultUniqueItemPool = (itemRegistry: Map<string, ItemM
} }
return pool; return pool;
}; };
let legacyDefaultUniqueItemPoolPromise: Promise<UniqueItemPool> | null = null;
const cloneUniqueItemPool = (pool: UniqueItemPool): UniqueItemPool =>
Object.fromEntries(Object.entries(pool).map(([slot, entries]) => [slot, { ...entries }]));
export const loadLegacyDefaultUniqueItemPool = async (loader?: ItemLoader): Promise<UniqueItemPool> => {
if (loader) {
const modules = await loadItemModules([...ITEM_KEYS], loader);
return buildLegacyDefaultUniqueItemPool(createItemModuleRegistry(modules));
}
legacyDefaultUniqueItemPoolPromise ??= loadItemModules([...ITEM_KEYS], new ItemLoader()).then((modules) =>
buildLegacyDefaultUniqueItemPool(createItemModuleRegistry(modules))
);
return cloneUniqueItemPool(await legacyDefaultUniqueItemPoolPromise);
};
/**
* Ref의 GameConst 기본값은 시나리오가 allItems를 덮어쓰지 않아도 항상 존재합니다.
* 오래된 Core snapshot의 생략값/문자열 빈 객체도 같은 기본 풀로 해석합니다.
*/
export const resolveLegacyCompatibleUniqueConfig = async (
configConst: Record<string, unknown>,
loader?: ItemLoader
): Promise<UniqueLotteryConfig> => {
const config = resolveUniqueConfig(configConst);
if (Object.keys(config.allItems).length > 0) {
return config;
}
return {
...config,
allItems: await loadLegacyDefaultUniqueItemPool(loader),
};
};
@@ -0,0 +1,30 @@
import { describe, expect, it } from 'vitest';
import { resolveLegacyCompatibleUniqueConfig } from '../src/rewards/legacyUniqueItemPool.js';
describe('legacy-compatible unique item pool', () => {
it.each([undefined, {}, '{}'] as const)('restores the Ref default pool when allItems is %j', async (allItems) => {
const config = await resolveLegacyCompatibleUniqueConfig(allItems === undefined ? {} : { allItems });
expect(Object.keys(config.allItems)).toEqual(['horse', 'weapon', 'book', 'item']);
expect(config.allItems.weapon?.che_무기_12_칠성검).toBe(2);
expect(config.allItems.item?.che_의술_청낭서).toBe(1);
expect(config.allItems.weapon?.che_무기_01_단도).toBeUndefined();
});
it('preserves an explicit scenario pool, including its counts', async () => {
const config = await resolveLegacyCompatibleUniqueConfig({
allItems: {
weapon: {
che_무기_12_칠성검: 7,
},
},
});
expect(config.allItems).toEqual({
weapon: {
che_무기_12_칠성검: 7,
},
});
});
});
@@ -87,6 +87,12 @@ const statusFixture = {
rawName: '칠성검', rawName: '칠성검',
info: '무력을 올려주는 유니크 무기입니다.', info: '무력을 올려주는 유니크 무기입니다.',
}, },
{
key: 'che_서적_07_논어',
name: '논어(+7)',
rawName: '논어',
info: '지력을 올려주는 유니크 서적입니다.',
},
], ],
availableTargetGenerals: [{ id: 8, name: '조조' }], availableTargetGenerals: [{ id: 8, name: '조조' }],
turnTimeZones: ['00:00'], turnTimeZones: ['00:00'],
@@ -98,6 +104,7 @@ const statusFixture = {
const installFixture = async (page: Page, options: { failBuff?: boolean } = {}) => { const installFixture = async (page: Page, options: { failBuff?: boolean } = {}) => {
let buffMutationCount = 0; let buffMutationCount = 0;
let resetTurnMutationCount = 0; let resetTurnMutationCount = 0;
const uniqueAuctionRequests: unknown[] = [];
await installImages(page); await installImages(page);
await page.addInitScript(() => { await page.addInitScript(() => {
window.localStorage.setItem('sammo-game-token', 'ga_inherit-visual-token'); window.localStorage.setItem('sammo-game-token', 'ga_inherit-visual-token');
@@ -105,6 +112,7 @@ const installFixture = async (page: Page, options: { failBuff?: boolean } = {})
}); });
await page.route('**/che/api/trpc/**', async (route) => { await page.route('**/che/api/trpc/**', async (route) => {
const names = operations(route); const names = operations(route);
const requestBody: unknown = route.request().postData() ? route.request().postDataJSON() : null;
if (options.failBuff && names.includes('inherit.buyHiddenBuff')) { if (options.failBuff && names.includes('inherit.buyHiddenBuff')) {
await route.fulfill({ await route.fulfill({
status: 500, status: 500,
@@ -145,6 +153,10 @@ const installFixture = async (page: Page, options: { failBuff?: boolean } = {})
resetTurnMutationCount += 1; resetTurnMutationCount += 1;
return response({ ok: true, nextTurnTimeBase: 302.5143852464758, nextTurnTimeLabel: '00:05' }); return response({ ok: true, nextTurnTimeBase: 302.5143852464758, nextTurnTimeLabel: '00:05' });
} }
if (name === 'inherit.openUniqueAuction') {
uniqueAuctionRequests.push(requestBody);
return response({ ok: true, auctionId: 31, closeAt: '2026-07-27T00:00:00.000Z' });
}
throw new Error(`Unhandled inheritance fixture operation: ${name}`); throw new Error(`Unhandled inheritance fixture operation: ${name}`);
}); });
await route.fulfill({ await route.fulfill({
@@ -156,6 +168,7 @@ const installFixture = async (page: Page, options: { failBuff?: boolean } = {})
return { return {
buffMutationCount: () => buffMutationCount, buffMutationCount: () => buffMutationCount,
resetTurnMutationCount: () => resetTurnMutationCount, resetTurnMutationCount: () => resetTurnMutationCount,
uniqueAuctionRequests,
}; };
}; };
@@ -290,6 +303,28 @@ test.describe('inheritance management legacy parity', () => {
await expect(page.locator('#inherit_previous_value')).toHaveValue('12,000'); await expect(page.locator('#inherit_previous_value')).toHaveValue('12,000');
}); });
test('selects a Ref default unique and starts its auction from the inheritance page', async ({ page }) => {
const fixture = await installFixture(page);
await page.goto(gameUrl);
await page.locator('#specific-unique').selectOption('che_서적_07_논어');
await page.locator('#specific-unique-amount').fill('6000');
page.once('dialog', async (dialog) => {
expect(dialog.message()).toBe('6000 포인트로 논어(+7)를 입찰하겠습니까?');
await dialog.accept();
});
await page
.locator('.shop-item')
.filter({ has: page.locator('#specific-unique') })
.getByRole('button', { name: '경매 시작' })
.click();
await expect.poll(() => fixture.uniqueAuctionRequests.length).toBe(1);
expect(JSON.stringify(fixture.uniqueAuctionRequests[0])).toContain('che_서적_07_논어');
expect(JSON.stringify(fixture.uniqueAuctionRequests[0])).toContain('6000');
await expect(page.locator('.notice.success')).toHaveText('성공했습니다. 경매장을 확인해주세요.');
});
test('keeps controls usable and renders an API mutation error', async ({ page }) => { test('keeps controls usable and renders an API mutation error', async ({ page }) => {
await installFixture(page, { failBuff: true }); await installFixture(page, { failBuff: true });
page.on('dialog', (dialog) => dialog.accept()); page.on('dialog', (dialog) => dialog.accept());
+220 -13
View File
@@ -26,15 +26,8 @@ import {
resolveRedisConfigFromEnv, resolveRedisConfigFromEnv,
GamePrisma, GamePrisma,
} from '@sammo-ts/infra'; } from '@sammo-ts/infra';
import { import { buildNeutralResourceAuctionPlan, ItemLoader, ITEM_KEYS } from '@sammo-ts/logic';
buildNeutralResourceAuctionPlan, import { createItemInventoryFromSlots, serializeItemInventory } from '@sammo-ts/logic/items/inventory.js';
ItemLoader,
ITEM_KEYS,
} from '@sammo-ts/logic';
import {
createItemInventoryFromSlots,
serializeItemInventory,
} from '@sammo-ts/logic/items/inventory.js';
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const workspaceRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../..'); const workspaceRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../..');
@@ -301,6 +294,7 @@ describe('auction integration flow', () => {
databaseUrl: resolvePostgresConfigFromEnv({ schema: 'che' }).url, databaseUrl: resolvePostgresConfigFromEnv({ schema: 'che' }).url,
adminUser: bootstrap.user, adminUser: bootstrap.user,
installOptions: { installOptions: {
serverId: 'auction-integration-908',
turnTermMinutes: 1, turnTermMinutes: 1,
sync: false, sync: false,
fiction: 0, fiction: 0,
@@ -676,6 +670,69 @@ describe('auction integration flow', () => {
turnDaemonLoop = turnDaemon.lifecycle.start(); turnDaemonLoop = turnDaemon.lifecycle.start();
await sleep(500); await sleep(500);
const directTransport = new DatabaseTurnDaemonTransport(prisma, 30_000);
await expect(
directTransport.requestCommand(
{
type: 'auctionBid',
auctionId: auction.id,
generalId: validBidder.generalId,
amount: 400,
},
30_000
)
).resolves.toMatchObject({
type: 'auctionBid',
ok: false,
reason: '이미 다른 유니크를 가지고 있습니다.',
});
const siblingCloseAt = new Date(turnDaemon.world.getGameNow(new Date()).getTime() + 10 * 60_000);
const siblingAuction = await prisma.auction.create({
data: {
type: 'UNIQUE_ITEM',
targetCode: uniquePair.keyB,
hostGeneralId: 0,
hostName: '시스템',
detail: {
startBidAmount: 200,
isReverse: false,
availableLatestBidCloseDate: siblingCloseAt.toISOString(),
},
status: 'OPEN',
closeAt: siblingCloseAt,
closeTick: BigInt(turnDaemon.world.dateToGameTick(siblingCloseAt)),
},
});
await prisma.auctionBid.create({
data: {
auctionId: siblingAuction.id,
generalId: spareBidder.generalId,
amount: 350,
eventId: `same-slot-race-${siblingAuction.id}`,
eventAt: turnDaemon.world.getGameNow(new Date()),
},
});
await expect(
directTransport.requestCommand(
{
type: 'auctionBid',
auctionId: auction.id,
generalId: spareBidder.generalId,
amount: 400,
},
30_000
)
).resolves.toMatchObject({
type: 'auctionBid',
ok: false,
reason: '1순위 입찰자인 경매중에 같은 부위가 있습니다.',
});
await prisma.auction.update({
where: { id: siblingAuction.id },
data: { status: 'CANCELED', finishedAt: new Date() },
});
const finalizeAt = new Date(turnDaemon!.world.getGameNow(new Date()).getTime() - 1000); const finalizeAt = new Date(turnDaemon!.world.getGameNow(new Date()).getTime() - 1000);
const finalizeTick = turnDaemon!.world.dateToGameTick(finalizeAt); const finalizeTick = turnDaemon!.world.dateToGameTick(finalizeAt);
await prisma.auction.update({ await prisma.auction.update({
@@ -684,7 +741,6 @@ describe('auction integration flow', () => {
}); });
await redis.zAdd(keys.timerKey, [{ score: finalizeTick, value: String(auction.id) }]); await redis.zAdd(keys.timerKey, [{ score: finalizeTick, value: String(auction.id) }]);
const transport = new DatabaseTurnDaemonTransport(prisma, 30_000);
await prisma.$executeRaw( await prisma.$executeRaw(
GamePrisma.sql` GamePrisma.sql`
UPDATE auction UPDATE auction
@@ -694,15 +750,16 @@ describe('auction integration flow', () => {
WHERE id = ${auction.id} WHERE id = ${auction.id}
` `
); );
const result = await transport.requestCommand({ type: 'auctionFinalize', auctionId: auction.id }, 30_000); const result = await directTransport.requestCommand({ type: 'auctionFinalize', auctionId: auction.id }, 30_000);
expect(result).toMatchObject({ type: 'auctionFinalize', ok: false }); expect(result).toMatchObject({ type: 'auctionFinalize', ok: false });
const reopened = await prisma.auction.findUnique({ const reopened = await prisma.auction.findUnique({
where: { id: auction.id }, where: { id: auction.id },
select: { status: true, closeAt: true }, select: { status: true, closeAt: true },
}); });
expect(reopened?.status).toBe('OPEN'); expect(reopened).not.toBeNull();
expect(reopened?.closeAt.getTime()).toBeGreaterThan(finalizeAt.getTime()); expect(reopened!.status).toBe('OPEN');
expect(reopened!.closeAt.getTime() - finalizeAt.getTime()).toBe(24 * 60_000);
}, 60_000); }, 60_000);
it('unique auction: two bidders extend until limit, then winner gets item', async () => { it('unique auction: two bidders extend until limit, then winner gets item', async () => {
@@ -1013,4 +1070,154 @@ describe('auction integration flow', () => {
meta: expect.objectContaining({ neutralAuctionRegistrationKey: '180-02' }), meta: expect.objectContaining({ neutralAuctionRegistrationKey: '180-02' }),
}); });
}, 60_000); }, 60_000);
it('starts from inheritance, accepts another user bid, and awards a default-pool unique', async () => {
if (!gameConnector || !redisConnector || !gameServer) {
throw new Error('runtime not ready');
}
const prisma = gameConnector.prisma;
const redis = redisConnector.client;
const [host, bidder] = userSessions;
if (!host || !bidder) {
throw new Error('not enough bidders');
}
if (turnDaemon) {
await turnDaemon.lifecycle.stop('integration-test');
await turnDaemon.close();
await turnDaemonLoop;
}
const uniquePair = await findUniqueItemPair();
const slotField = resolveSlotField(uniquePair.slot);
if (!slotField) {
throw new Error('unsupported item slot');
}
const state = await prisma.worldState.findFirstOrThrow();
const config =
state.config && typeof state.config === 'object' && !Array.isArray(state.config) ? state.config : {};
const configConst =
config.const && typeof config.const === 'object' && !Array.isArray(config.const) ? config.const : {};
await prisma.worldState.update({
where: { id: state.id },
data: {
currentYear: 180,
currentMonth: 4,
config: {
...config,
const: {
...configConst,
// 표준 Ref 시나리오는 GameConst 기본값을 상속한다. 오래된
// Core snapshot의 문자열 빈 객체도 같은 입력으로 검증한다.
allItems: '{}',
},
},
},
});
await prisma.auction.updateMany({
where: { type: 'UNIQUE_ITEM', status: { in: ['OPEN', 'FINALIZING'] } },
data: { status: 'CANCELED', finishedAt: new Date() },
});
for (const session of [host, bidder]) {
const row = await prisma.general.findUniqueOrThrow({
where: { id: session.generalId },
select: { meta: true },
});
const meta = row.meta && typeof row.meta === 'object' && !Array.isArray(row.meta) ? row.meta : {};
await prisma.general.update({
where: { id: session.generalId },
data: {
weaponCode: 'None',
bookCode: 'None',
horseCode: 'None',
itemCode: 'None',
meta: {
...meta,
itemInventory: serializeItemInventory(
createItemInventoryFromSlots({ horse: null, weapon: null, book: null, item: null })
),
},
},
});
await prisma.inheritancePoint.upsert({
where: { userId_key: { userId: session.userId, key: 'previous' } },
update: { value: 100_000 },
create: { userId: session.userId, key: 'previous', value: 100_000 },
});
}
await prisma.general.updateMany({
where: { [slotField]: uniquePair.keyA } as GamePrisma.GeneralWhereInput,
data: { [slotField]: 'None' } as GamePrisma.GeneralUpdateManyMutationInput,
});
const gameDatabaseUrl = resolvePostgresConfigFromEnv({ schema: 'che' }).url;
const gatewayDatabaseUrl = resolvePostgresConfigFromEnv({ schema: 'public' }).url;
turnDaemon = await createTurnDaemonRuntime({
profile: 'che',
profileName: 'che:908',
databaseUrl: gameDatabaseUrl,
gatewayDatabaseUrl,
});
turnDaemonLoop = turnDaemon.lifecycle.start();
await sleep(500);
const hostClient = createGameClient(gameUrl, gameServer.config.trpcPath, { value: host.accessToken });
const bidderClient = createGameClient(gameUrl, gameServer.config.trpcPath, { value: bidder.accessToken });
const inheritStatus = await hostClient.inherit.getStatus.query();
expect(inheritStatus.availableUnique.length).toBeGreaterThan(80);
expect(inheritStatus.availableUnique).toEqual(
expect.arrayContaining([expect.objectContaining({ key: uniquePair.keyA })])
);
const opened = await hostClient.inherit.openUniqueAuction.mutate({
itemId: uniquePair.keyA,
amount: 5_000,
});
const auction = await prisma.auction.findUniqueOrThrow({ where: { id: opened.auctionId } });
expect(auction).toMatchObject({
type: 'UNIQUE_ITEM',
targetCode: uniquePair.keyA,
hostGeneralId: host.generalId,
status: 'OPEN',
});
const timerKeys = buildAuctionTimerKeys(gameServer.config.profileName);
await expect(redis.zScore(timerKeys.timerKey, String(auction.id))).resolves.not.toBeNull();
await bidderClient.auction.bidUnique.mutate({ auctionId: auction.id, amount: 5_100 });
await expect(
prisma.inheritancePoint.findUniqueOrThrow({
where: { userId_key: { userId: host.userId, key: 'previous' } },
})
).resolves.toMatchObject({ value: 100_000 });
const finalizeAt = new Date(turnDaemon.world.getGameNow(new Date()).getTime() - 1_000);
const finalizeTick = turnDaemon.world.dateToGameTick(finalizeAt);
await prisma.auction.update({
where: { id: auction.id },
data: {
closeAt: finalizeAt,
closeTick: BigInt(finalizeTick),
status: 'FINALIZING',
finalizingAt: new Date(),
},
});
const transport = new DatabaseTurnDaemonTransport(prisma, 30_000);
const result = await transport.requestCommand({ type: 'auctionFinalize', auctionId: auction.id }, 30_000);
expect(result).toMatchObject({ type: 'auctionFinalize', ok: true });
await expect(prisma.auction.findUniqueOrThrow({ where: { id: auction.id } })).resolves.toMatchObject({
status: 'FINISHED',
});
const winner = await prisma.general.findUniqueOrThrow({
where: { id: bidder.generalId },
select: { weaponCode: true, bookCode: true, horseCode: true, itemCode: true },
});
expect(Object.values(winner)).toContain(uniquePair.keyA);
await expect(
prisma.inheritancePoint.findUniqueOrThrow({
where: { userId_key: { userId: bidder.userId, key: 'previous' } },
})
).resolves.toMatchObject({ value: 94_900 });
}, 60_000);
}); });