merge: 최신 main을 국가 메시지 편집기 보완에 통합한다
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
import { TRPCError } from '@trpc/server';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { LogCategory, LogScope } from '@sammo-ts/logic';
|
||||
import { getBillByLevel, LogCategory, LogScope } from '@sammo-ts/logic';
|
||||
import { asRecord, type RankDataType } from '@sammo-ts/common';
|
||||
|
||||
import type { GameApiContext } from '../../context.js';
|
||||
@@ -45,6 +45,7 @@ import {
|
||||
import {
|
||||
resolveGeneralTypeCall,
|
||||
resolveLeadershipBonus,
|
||||
resolveNextTurnMonthOffset,
|
||||
resolveRefreshScoreText,
|
||||
resolveRemainingMinutes,
|
||||
} from '../../services/generalBasicCardProjection.js';
|
||||
@@ -265,6 +266,7 @@ export const getGeneralContext = async (ctx: GameApiContext) => {
|
||||
dedication: true,
|
||||
age: true,
|
||||
turnTime: true,
|
||||
turnTick: true,
|
||||
recentWarTime: true,
|
||||
crewTypeId: true,
|
||||
personalCode: true,
|
||||
@@ -333,7 +335,14 @@ export const getGeneralContext = async (ctx: GameApiContext) => {
|
||||
})
|
||||
: Promise.resolve(NEUTRAL_NATION_CONTEXT),
|
||||
ctx.db.worldState.findFirst({
|
||||
select: { currentYear: true, currentMonth: true, tickSeconds: true, config: true, meta: true },
|
||||
select: {
|
||||
currentYear: true,
|
||||
currentMonth: true,
|
||||
tickSeconds: true,
|
||||
lastTurnTick: true,
|
||||
config: true,
|
||||
meta: true,
|
||||
},
|
||||
}),
|
||||
officerCityId > 0
|
||||
? ctx.db.city.findUnique({ where: { id: officerCityId }, select: { name: true } })
|
||||
@@ -517,9 +526,17 @@ export const getGeneralContext = async (ctx: GameApiContext) => {
|
||||
injury: general.injury,
|
||||
experience: general.experience,
|
||||
dedication: general.dedication,
|
||||
bill: getBillByLevel(dedicationLevel),
|
||||
age: general.age,
|
||||
retirementYear,
|
||||
turnTime: general.turnTime.toISOString(),
|
||||
nextTurnMonthOffset: resolveNextTurnMonthOffset({
|
||||
turnTime: general.turnTime,
|
||||
turnTick: general.turnTick,
|
||||
lastExecuted: parsedLastExecuted,
|
||||
lastTurnTick: worldState?.lastTurnTick,
|
||||
turnSeconds: worldState?.tickSeconds ?? 0,
|
||||
}),
|
||||
recentWar: general.recentWarTime?.toISOString() ?? null,
|
||||
defenceTrain: settings.defence_train,
|
||||
killTurn: readNumber(metaRecord.killturn ?? metaRecord.killTurn, 0),
|
||||
|
||||
@@ -68,7 +68,10 @@ export const lobbyRouter = router({
|
||||
preopenAt: worldState.meta.preopenAt ?? '',
|
||||
turntime: worldState.meta.turntime ?? '',
|
||||
serverTime: gameTime.now.toISOString(),
|
||||
serverWallTime: gameTime.wallNow.toISOString(),
|
||||
clockMode: gameTime.mode ?? 'realtime',
|
||||
clockRunning: gameTime.running,
|
||||
clockStartsAt: gameTime.startsAt?.toISOString() ?? null,
|
||||
otherTextInfo: worldState.meta.otherTextInfo ?? '',
|
||||
npcMode: worldState.config.npcMode ?? 0,
|
||||
defaultStatTotal: asNumber(asRecord(rawConfig.stat).total, 165),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { TRPCError } from '@trpc/server';
|
||||
|
||||
import { asRecord, type RankDataType } from '@sammo-ts/common';
|
||||
import { LogCategory } from '@sammo-ts/logic';
|
||||
import { getBillByLevel, LogCategory } from '@sammo-ts/logic';
|
||||
|
||||
import { accessAuthedProcedure } from '../../../trpc.js';
|
||||
import {
|
||||
@@ -201,6 +201,7 @@ export const getBattleCenter = accessAuthedProcedure.query(async ({ ctx }) => {
|
||||
},
|
||||
experience: general.experience,
|
||||
dedication: general.dedication,
|
||||
bill: getBillByLevel(dedicationLevel),
|
||||
injury: general.injury,
|
||||
gold: general.gold,
|
||||
rice: general.rice,
|
||||
|
||||
@@ -79,7 +79,7 @@ export const troopRouter = router({
|
||||
troopLeaderIds.length === 0
|
||||
? []
|
||||
: await ctx.db.generalTurn.findMany({
|
||||
where: { generalId: { in: troopLeaderIds } },
|
||||
where: { generalId: { in: troopLeaderIds }, turnIdx: { lt: 5 } },
|
||||
select: { generalId: true, turnIdx: true, actionCode: true },
|
||||
orderBy: [{ generalId: 'asc' }, { turnIdx: 'asc' }],
|
||||
});
|
||||
@@ -94,7 +94,8 @@ export const troopRouter = router({
|
||||
: 30;
|
||||
for (const turn of turns) {
|
||||
const list = reservedByLeader.get(turn.generalId) ?? [];
|
||||
list.push(turn.actionCode);
|
||||
// Ref 부대 편성은 앞쪽 슬롯이 집합인지 여부만 공개하고 다른 명령은 가립니다.
|
||||
list.push(turn.actionCode === 'che_집합' ? '집합' : '-');
|
||||
reservedByLeader.set(turn.generalId, list);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,14 +4,25 @@ import type { DatabaseClient } from '../context.js';
|
||||
|
||||
export interface CurrentGameTime {
|
||||
now: Date;
|
||||
wallNow: Date;
|
||||
tick: number | null;
|
||||
mode: GameClockMode | null;
|
||||
running: boolean;
|
||||
startsAt: Date | null;
|
||||
dateToTick(date: Date): number | null;
|
||||
}
|
||||
|
||||
export const loadCurrentGameTime = async (db: DatabaseClient, wallNow = new Date()): Promise<CurrentGameTime> => {
|
||||
if (!db.worldState) {
|
||||
return { now: wallNow, tick: null, mode: null, dateToTick: () => null };
|
||||
return {
|
||||
now: wallNow,
|
||||
wallNow,
|
||||
tick: null,
|
||||
mode: null,
|
||||
running: true,
|
||||
startsAt: null,
|
||||
dateToTick: () => null,
|
||||
};
|
||||
}
|
||||
const state = await db.worldState.findFirst({
|
||||
orderBy: { id: 'asc' },
|
||||
@@ -24,7 +35,15 @@ export const loadCurrentGameTime = async (db: DatabaseClient, wallNow = new Date
|
||||
},
|
||||
});
|
||||
if (!state?.clockBaseTime || state.clockTick === null || !state.clockWallAnchor) {
|
||||
return { now: wallNow, tick: null, mode: null, dateToTick: () => null };
|
||||
return {
|
||||
now: wallNow,
|
||||
wallNow,
|
||||
tick: null,
|
||||
mode: null,
|
||||
running: true,
|
||||
startsAt: null,
|
||||
dateToTick: () => null,
|
||||
};
|
||||
}
|
||||
const mode: GameClockMode = state.clockMode === 'manual' ? 'manual' : 'realtime';
|
||||
const storedTick = Number(state.clockTick);
|
||||
@@ -39,10 +58,14 @@ export const loadCurrentGameTime = async (db: DatabaseClient, wallNow = new Date
|
||||
turnSeconds: state.tickSeconds,
|
||||
});
|
||||
const tick = clock.nowTick(wallNow);
|
||||
const running = mode === 'realtime' && wallNow.getTime() >= state.clockWallAnchor.getTime();
|
||||
return {
|
||||
now: clock.tickToDate(tick),
|
||||
wallNow,
|
||||
tick,
|
||||
mode,
|
||||
running,
|
||||
startsAt: mode === 'realtime' && !running ? state.clockWallAnchor : null,
|
||||
dateToTick: (date) => clock.dateToTick(date),
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { GAME_TICKS_PER_TURN } from '@sammo-ts/common';
|
||||
|
||||
export interface GeneralBasicStats {
|
||||
leadership: number;
|
||||
strength: number;
|
||||
@@ -53,3 +55,41 @@ export const resolveRemainingMinutes = (
|
||||
}
|
||||
return Math.floor(Math.min(999, Math.max(0, (nextTurnMillis - lastExecuted.getTime()) / 60_000)));
|
||||
};
|
||||
|
||||
export interface NextTurnMonthOffsetInput {
|
||||
turnTime: Date;
|
||||
turnTick?: bigint | number | null;
|
||||
lastExecuted: Date | null;
|
||||
lastTurnTick?: bigint | number | null;
|
||||
turnSeconds: number;
|
||||
}
|
||||
|
||||
const normalizeTick = (value: bigint | number | null | undefined): bigint | null => {
|
||||
if (typeof value === 'bigint') return value;
|
||||
if (typeof value === 'number' && Number.isSafeInteger(value)) return BigInt(value);
|
||||
return null;
|
||||
};
|
||||
|
||||
const turnBucket = (tick: bigint): bigint => {
|
||||
const ticksPerTurn = BigInt(GAME_TICKS_PER_TURN);
|
||||
const quotient = tick / ticksPerTurn;
|
||||
return tick % ticksPerTurn < 0 ? quotient - 1n : quotient;
|
||||
};
|
||||
|
||||
/**
|
||||
* Ref Command.GetReservedCommand cuts both clocks to a gameplay-turn bucket.
|
||||
* A general in the next bucket has already acted in the displayed world month,
|
||||
* so the first reserved command belongs to the following month.
|
||||
*/
|
||||
export const resolveNextTurnMonthOffset = (input: NextTurnMonthOffsetInput): 0 | 1 => {
|
||||
const turnTick = normalizeTick(input.turnTick);
|
||||
const lastTurnTick = normalizeTick(input.lastTurnTick);
|
||||
if (turnTick !== null && lastTurnTick !== null) {
|
||||
return turnBucket(turnTick) > turnBucket(lastTurnTick) ? 1 : 0;
|
||||
}
|
||||
|
||||
const turnTimeMs = input.turnTime.getTime();
|
||||
const lastExecutedMs = input.lastExecuted?.getTime() ?? Number.NaN;
|
||||
if (!Number.isFinite(turnTimeMs) || !Number.isFinite(lastExecutedMs) || input.turnSeconds <= 0) return 0;
|
||||
return turnTimeMs >= lastExecutedMs + input.turnSeconds * 1_000 ? 1 : 0;
|
||||
};
|
||||
|
||||
@@ -57,8 +57,11 @@ describe('auction worker clock-shift race', () => {
|
||||
const now = new Date('2026-07-30T12:00:00.000Z');
|
||||
const time = {
|
||||
now,
|
||||
wallNow: now,
|
||||
tick: 36_000_000,
|
||||
mode: 'manual' as const,
|
||||
running: false,
|
||||
startsAt: null,
|
||||
dateToTick: () => 72_000_000,
|
||||
};
|
||||
const closeAt = new Date('2099-01-01T00:00:00.000Z');
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import type { DatabaseClient } from '../src/context.js';
|
||||
import { loadCurrentGameTime } from '../src/services/gameClock.js';
|
||||
|
||||
const buildDatabase = (mode: 'realtime' | 'manual' = 'realtime'): DatabaseClient =>
|
||||
({
|
||||
worldState: {
|
||||
findFirst: vi.fn(async () => ({
|
||||
clockBaseTime: new Date('2026-08-21T09:50:00.000Z'),
|
||||
clockTick: 36_000_000n,
|
||||
clockMode: mode,
|
||||
clockWallAnchor: new Date('2026-08-21T11:00:00.000Z'),
|
||||
tickSeconds: 600,
|
||||
})),
|
||||
},
|
||||
}) as unknown as DatabaseClient;
|
||||
|
||||
describe('current game time projection', () => {
|
||||
it('holds a realtime clock at its persisted tick until the future wall anchor', async () => {
|
||||
const db = buildDatabase();
|
||||
|
||||
const preopen = await loadCurrentGameTime(db, new Date('2026-08-21T10:30:00.000Z'));
|
||||
expect(preopen).toMatchObject({
|
||||
now: new Date('2026-08-21T10:00:00.000Z'),
|
||||
wallNow: new Date('2026-08-21T10:30:00.000Z'),
|
||||
tick: 36_000_000,
|
||||
mode: 'realtime',
|
||||
running: false,
|
||||
startsAt: new Date('2026-08-21T11:00:00.000Z'),
|
||||
});
|
||||
|
||||
const opened = await loadCurrentGameTime(db, new Date('2026-08-21T11:00:05.000Z'));
|
||||
expect(opened).toMatchObject({
|
||||
now: new Date('2026-08-21T10:00:05.000Z'),
|
||||
tick: 36_300_000,
|
||||
running: true,
|
||||
startsAt: null,
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps a manual clock stopped without scheduling an automatic start', async () => {
|
||||
const result = await loadCurrentGameTime(buildDatabase('manual'), new Date('2026-08-21T12:00:00.000Z'));
|
||||
|
||||
expect(result).toMatchObject({
|
||||
now: new Date('2026-08-21T10:00:00.000Z'),
|
||||
tick: 36_000_000,
|
||||
running: false,
|
||||
startsAt: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
resolveGeneralTypeCall,
|
||||
resolveLeadershipBonus,
|
||||
resolveNextTurnMonthOffset,
|
||||
resolveRefreshScoreText,
|
||||
resolveRemainingMinutes,
|
||||
} from '../src/services/generalBasicCardProjection.js';
|
||||
@@ -41,4 +42,55 @@ describe('general basic card Ref projection', () => {
|
||||
expect(resolveRemainingMinutes(new Date('2026-08-12T23:59:00.000Z'), lastExecuted, 3_600)).toBe(59);
|
||||
expect(resolveRemainingMinutes(new Date('2026-08-13T00:07:06.000Z'), null, 3_600)).toBeNull();
|
||||
});
|
||||
|
||||
it('moves the first reserved month only after the general turn bucket has passed', () => {
|
||||
const lastExecuted = new Date('2026-08-13T00:00:00.000Z');
|
||||
const lastTurnTick = 36_000_000n * 11n;
|
||||
|
||||
expect(
|
||||
resolveNextTurnMonthOffset({
|
||||
turnTime: new Date('2026-08-13T00:07:00.000Z'),
|
||||
turnTick: lastTurnTick + 12_000_000n,
|
||||
lastExecuted,
|
||||
lastTurnTick,
|
||||
turnSeconds: 600,
|
||||
})
|
||||
).toBe(0);
|
||||
expect(
|
||||
resolveNextTurnMonthOffset({
|
||||
turnTime: new Date('2026-08-13T00:17:00.000Z'),
|
||||
turnTick: lastTurnTick + 48_000_000n,
|
||||
lastExecuted,
|
||||
lastTurnTick,
|
||||
turnSeconds: 600,
|
||||
})
|
||||
).toBe(1);
|
||||
expect(
|
||||
resolveNextTurnMonthOffset({
|
||||
turnTime: new Date('2026-08-13T00:10:00.000Z'),
|
||||
turnTick: 1n,
|
||||
lastExecuted,
|
||||
lastTurnTick: -1n,
|
||||
turnSeconds: 600,
|
||||
})
|
||||
).toBe(1);
|
||||
});
|
||||
|
||||
it('keeps the same boundary for legacy Date-only schedules', () => {
|
||||
const lastExecuted = new Date('2026-08-13T00:00:00.000Z');
|
||||
expect(
|
||||
resolveNextTurnMonthOffset({
|
||||
turnTime: new Date('2026-08-13T00:07:00.000Z'),
|
||||
lastExecuted,
|
||||
turnSeconds: 600,
|
||||
})
|
||||
).toBe(0);
|
||||
expect(
|
||||
resolveNextTurnMonthOffset({
|
||||
turnTime: new Date('2026-08-13T00:10:00.000Z'),
|
||||
lastExecuted,
|
||||
turnSeconds: 600,
|
||||
})
|
||||
).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -297,6 +297,7 @@ describe('in-game my information ownership', () => {
|
||||
statUpgradeLimit: 20,
|
||||
dex: [350, 1_375, 3_500, 7_125, 12_650],
|
||||
},
|
||||
bill: 1_000,
|
||||
},
|
||||
city: {
|
||||
population: 322_886,
|
||||
@@ -433,6 +434,7 @@ describe('in-game my information ownership', () => {
|
||||
stats: { attack: 100, defence: 150, speed: 7, avoid: 10, magicCoef: 0, cost: 9, rice: 9 },
|
||||
},
|
||||
progression: { experienceLevel: 4, dedicationLevel: 2, dedicationText: '29품관' },
|
||||
bill: 800,
|
||||
itemNames: { horse: '노새(+3)' },
|
||||
itemInfo: { horse: '통솔 +3' },
|
||||
},
|
||||
@@ -855,6 +857,7 @@ describe('battle-center general and user permissions', () => {
|
||||
statUpgradeLimit: 20,
|
||||
dex: [0, 0, 0, 0, 0],
|
||||
},
|
||||
bill: 600,
|
||||
serviceYears: 3,
|
||||
battleStats: {
|
||||
kills: 5,
|
||||
|
||||
@@ -68,6 +68,32 @@ describe('lobby season state', () => {
|
||||
|
||||
expect(result.serverTime).toBe('2026-08-15T02:00:00.000Z');
|
||||
expect(result.clockMode).toBe('manual');
|
||||
expect(result.clockRunning).toBe(false);
|
||||
expect(result.clockStartsAt).toBeNull();
|
||||
expect(new Date(result.serverWallTime).getTime()).not.toBeNaN();
|
||||
});
|
||||
|
||||
it('exposes the future realtime wall anchor without advancing the preopen clock', async () => {
|
||||
const wallAnchor = new Date('2099-08-21T11:00:00.000Z');
|
||||
const result = await appRouter
|
||||
.createCaller(
|
||||
buildContext(
|
||||
{},
|
||||
{
|
||||
baseTime: new Date('2026-08-21T09:00:00.000Z'),
|
||||
tick: 36_000_000n,
|
||||
mode: 'realtime',
|
||||
wallAnchor,
|
||||
}
|
||||
)
|
||||
)
|
||||
.lobby.info();
|
||||
|
||||
expect(result.serverTime).toBe('2026-08-21T10:00:00.000Z');
|
||||
expect(result.clockMode).toBe('realtime');
|
||||
expect(result.clockRunning).toBe(false);
|
||||
expect(result.clockStartsAt).toBe(wallAnchor.toISOString());
|
||||
expect(new Date(result.serverWallTime).getTime()).toBeLessThan(wallAnchor.getTime());
|
||||
});
|
||||
|
||||
it('preserves zero as the first official game index', async () => {
|
||||
|
||||
@@ -77,10 +77,12 @@ const buildContext = (options: {
|
||||
auth?: GameSessionTokenPayload | null;
|
||||
requestId?: string;
|
||||
transaction?: ReturnType<typeof vi.fn>;
|
||||
turns?: Array<{ generalId: number; turnIdx: number; actionCode: string }>;
|
||||
result: Awaited<ReturnType<TurnDaemonTransport['requestCommand']>>;
|
||||
}) => {
|
||||
const me = options.me ?? buildGeneral();
|
||||
const requestCommand = vi.fn(async () => options.result);
|
||||
const generalTurnFindMany = vi.fn(async () => options.turns ?? []);
|
||||
const db = {
|
||||
...(options.transaction ? { $transaction: options.transaction } : {}),
|
||||
general: {
|
||||
@@ -110,7 +112,7 @@ const buildContext = (options: {
|
||||
},
|
||||
city: { findMany: vi.fn(async () => [{ id: 1, name: '북평' }]) },
|
||||
worldState: { findFirst: vi.fn(async () => ({ config: { const: { upgradeLimit: 20 } } })) },
|
||||
generalTurn: { findMany: vi.fn(async () => []) },
|
||||
generalTurn: { findMany: generalTurnFindMany },
|
||||
};
|
||||
const accessTokenStore = new RedisAccessTokenStore(
|
||||
{
|
||||
@@ -134,7 +136,7 @@ const buildContext = (options: {
|
||||
flushStore: new InMemoryFlushStore(),
|
||||
gameTokenSecret: 'test-secret',
|
||||
};
|
||||
return { context, requestCommand };
|
||||
return { context, requestCommand, generalTurnFindMany };
|
||||
};
|
||||
|
||||
describe('troop router permissions and mutations', () => {
|
||||
@@ -175,6 +177,30 @@ describe('troop router permissions and mutations', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('returns only the first five Ref-redacted troop command labels without exposing action codes', async () => {
|
||||
const fixture = buildContext({
|
||||
me: buildGeneral({ troopId: 1 }),
|
||||
turns: [
|
||||
{ generalId: 1, turnIdx: 0, actionCode: 'che_집합' },
|
||||
{ generalId: 1, turnIdx: 1, actionCode: 'che_이동' },
|
||||
{ generalId: 1, turnIdx: 2, actionCode: 'che_징병' },
|
||||
{ generalId: 1, turnIdx: 3, actionCode: '휴식' },
|
||||
{ generalId: 1, turnIdx: 4, actionCode: 'che_화계' },
|
||||
],
|
||||
result: null,
|
||||
});
|
||||
|
||||
const result = await appRouter.createCaller(fixture.context).troop.getList();
|
||||
|
||||
expect(result.troops[0]?.reservedCommands).toEqual(['집합', '-', '-', '-', '-']);
|
||||
expect(JSON.stringify(result.troops)).not.toContain('che_');
|
||||
expect(fixture.generalTurnFindMany).toHaveBeenCalledWith({
|
||||
where: { generalId: { in: [1] }, turnIdx: { lt: 5 } },
|
||||
select: { generalId: true, turnIdx: true, actionCode: true },
|
||||
orderBy: [{ generalId: 'asc' }, { turnIdx: 'asc' }],
|
||||
});
|
||||
});
|
||||
|
||||
it('creates a troop only for the general owned by the authenticated user', async () => {
|
||||
const { context, requestCommand } = buildContext({
|
||||
result: { type: 'troopCreate', ok: true, generalId: 1, troopId: 1, troopName: '백마대' },
|
||||
|
||||
@@ -50,6 +50,7 @@ export interface ScenarioInstallOptions {
|
||||
joinMode?: 'full' | 'onlyRandom';
|
||||
autorunUser?: ScenarioAutorunOptions | null;
|
||||
preopenAt?: Date | null;
|
||||
openAt?: Date | null;
|
||||
season?: number;
|
||||
firstGameIdx?: number;
|
||||
serverId?: string;
|
||||
@@ -229,11 +230,14 @@ export const seedScenarioToDatabase = async (options: ScenarioSeedOptions): Prom
|
||||
const sync = install?.sync ?? false;
|
||||
const startState = resolveStartState(scenario.startYear ?? null, now, turnTermMinutes, sync);
|
||||
const gameClockMode = options.gameClockMode ?? 'realtime';
|
||||
// A realtime season prepared before its formal opening must not consume
|
||||
// wall time while users are only allowed to edit reserved commands.
|
||||
const initialClockWallAnchor = install?.openAt && install.openAt.getTime() > now.getTime() ? install.openAt : now;
|
||||
const initialClock = new GameClock({
|
||||
baseTime: startState.startTime,
|
||||
tick: 0,
|
||||
mode: gameClockMode,
|
||||
wallAnchor: now,
|
||||
wallAnchor: initialClockWallAnchor,
|
||||
turnSeconds: tickSeconds,
|
||||
});
|
||||
const initialClockTick = initialClock.dateToTick(now);
|
||||
@@ -410,7 +414,7 @@ export const seedScenarioToDatabase = async (options: ScenarioSeedOptions): Prom
|
||||
clockBaseTime: initialClock.baseTime,
|
||||
clockTick: BigInt(initialClockTick),
|
||||
clockMode: gameClockMode,
|
||||
clockWallAnchor: now,
|
||||
clockWallAnchor: initialClock.wallAnchor,
|
||||
lastTurnTick: BigInt(initialClockTick),
|
||||
config: asJson({ ...scenarioConfig, ...worldConfig }),
|
||||
meta: asJson(worldMeta),
|
||||
|
||||
@@ -50,6 +50,7 @@ type ScenarioSeederPrismaClient = {
|
||||
tickSeconds: number;
|
||||
currentYear: number;
|
||||
currentMonth: number;
|
||||
clockWallAnchor: Date | null;
|
||||
} | null>;
|
||||
};
|
||||
gameHistory: {
|
||||
@@ -364,6 +365,8 @@ describeDb('scenario database seed', () => {
|
||||
develop: true,
|
||||
},
|
||||
},
|
||||
preopenAt: new Date('2030-01-01T01:00:00Z'),
|
||||
openAt: new Date('2030-01-01T02:00:00Z'),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -385,6 +388,7 @@ describeDb('scenario database seed', () => {
|
||||
}
|
||||
expect(worldState.tickSeconds).toBe(180);
|
||||
expect(worldState.currentMonth).toBe(1);
|
||||
expect(worldState.clockWallAnchor).toEqual(new Date('2030-01-01T02:00:00.000Z'));
|
||||
|
||||
const config = (worldState.config ?? {}) as Record<string, unknown>;
|
||||
expect(config.extendedGeneral).toBe(false);
|
||||
|
||||
@@ -629,6 +629,10 @@ test('nation directory reuses only the public general-directory row on hover and
|
||||
await expect(preview.locator('[data-general-card-id="10"]')).toContainText('대담');
|
||||
await expect(preview.locator('[data-directory-tooltip="card-special-domestic-10"]')).toContainText('상재');
|
||||
await expect(preview.locator('[data-directory-tooltip="card-special-war-10"]')).toContainText('귀모');
|
||||
await expect(preview.locator('[data-directory-tooltip="card-special-domestic-10"]')).toHaveCSS(
|
||||
'text-decoration-line',
|
||||
'none'
|
||||
);
|
||||
await expect(preview).not.toContainText('user-');
|
||||
await expect(preview).not.toContainText('secret');
|
||||
|
||||
|
||||
@@ -112,6 +112,7 @@ const myGeneral = (state: FixtureState) => ({
|
||||
injury: 0,
|
||||
experience: 100,
|
||||
dedication: 200,
|
||||
bill: 800,
|
||||
age: 30,
|
||||
turnTime: '2026-01-01 00:10:00',
|
||||
recentWar: '2026-01-01 00:00:00',
|
||||
@@ -296,6 +297,7 @@ const battleCenter = (state: FixtureState) => ({
|
||||
stats: { leadership: 70, strength: 60, intelligence: 50 },
|
||||
experience: 100,
|
||||
dedication: 200,
|
||||
bill: 800,
|
||||
injury: 0,
|
||||
gold: 1_000,
|
||||
rice: 2_000,
|
||||
@@ -334,6 +336,7 @@ const battleCenter = (state: FixtureState) => ({
|
||||
stats: { leadership: 50, strength: 50, intelligence: 50 },
|
||||
experience: 0,
|
||||
dedication: 0,
|
||||
bill: 400,
|
||||
injury: 0,
|
||||
gold: 500,
|
||||
rice: 500,
|
||||
@@ -1245,6 +1248,7 @@ test('내 정보&설정 keeps desktop density and becomes a 390px horizontal-ide
|
||||
await expect(page.locator('.general-table')).toContainText('병종보병');
|
||||
await expect(page.locator('.general-table')).toContainText('삭턴6 턴');
|
||||
await expect(page.locator('.battle-general-extra')).toContainText('계급29품관');
|
||||
await expect(page.locator('.battle-general-extra')).toContainText('봉급800');
|
||||
await expect(page.locator('.battle-general-extra')).toContainText('전투8회');
|
||||
await expect(page.locator('.battle-general-extra')).toContainText('계략12');
|
||||
await expect(page.locator('.battle-general-extra')).toContainText('사관4년');
|
||||
@@ -1255,7 +1259,7 @@ test('내 정보&설정 keeps desktop density and becomes a 390px horizontal-ide
|
||||
await expect(page.locator('.battle-general-extra__recent-value')).toHaveText('01-01 00:00');
|
||||
await expect(page.locator('.legacy-general-details')).toHaveCount(0);
|
||||
expect(await readGeneralSummaryRows(page.locator('.battle-general-extra'))).toEqual([
|
||||
['명성', '계급', ''],
|
||||
['명성', '계급', '봉급'],
|
||||
['전투', '계략', '사관'],
|
||||
['승률', '승리', '패배'],
|
||||
['살상률', '사살', '피살'],
|
||||
@@ -1429,6 +1433,7 @@ test('내 정보 항목과 국가 성향은 HTML 리치 툴팁을 마우스와
|
||||
const showWithMouse = async (testId: string, expectedTexts: readonly string[]) => {
|
||||
const trigger = page.locator(`[data-rich-tooltip="${testId}"]`);
|
||||
await expect(trigger).toHaveAttribute('tabindex', '0');
|
||||
await expect(trigger).toHaveCSS('text-decoration-line', 'none');
|
||||
await trigger.hover();
|
||||
await expect(visibleTooltip).toHaveCount(1);
|
||||
await expect(visibleTooltip).toHaveAttribute('role', 'tooltip');
|
||||
@@ -2039,6 +2044,7 @@ test('감찰부 keeps the selector interaction and shows the permission error pa
|
||||
await expect(page.locator('.battle-general-name')).toContainText('간의대부');
|
||||
await expect(page.locator('.battle-general-name')).toContainText('건강');
|
||||
await expect(page.locator('.battle-general-extra')).toContainText('계급29품관');
|
||||
await expect(page.locator('.battle-general-extra')).toContainText('봉급800');
|
||||
await expect(page.locator('.battle-general-card')).toContainText('병종보병');
|
||||
await expect(page.locator('.battle-general-card')).not.toContainText('che_');
|
||||
await expect(page.locator('.battle-general-card')).toHaveAttribute('data-general-basic-card', '');
|
||||
@@ -2049,7 +2055,7 @@ test('감찰부 keeps the selector interaction and shows the permission error pa
|
||||
await expect(page.locator('.battle-general-extra')).toContainText('승률62.50%');
|
||||
await expect(page.locator('.battle-general-extra')).toContainText('살상률181.84%');
|
||||
expect(await readGeneralSummaryRows(page.locator('.battle-general-extra'))).toEqual([
|
||||
['명성', '계급', ''],
|
||||
['명성', '계급', '봉급'],
|
||||
['전투', '계략', '사관'],
|
||||
['승률', '승리', '패배'],
|
||||
['살상률', '사살', '피살'],
|
||||
|
||||
@@ -34,8 +34,12 @@ type NavigationFixture = {
|
||||
operations: string[];
|
||||
generalName?: string;
|
||||
generalTurnTime?: string;
|
||||
nextTurnMonthOffset?: 0 | 1;
|
||||
serverTime?: string;
|
||||
serverWallTime?: string;
|
||||
clockMode?: 'realtime' | 'manual';
|
||||
clockRunning?: boolean;
|
||||
clockStartsAt?: string | null;
|
||||
cityDefence?: number;
|
||||
cityState?: number;
|
||||
nationRate?: number;
|
||||
@@ -437,6 +441,7 @@ const generalContext = (state: NavigationFixture) => ({
|
||||
crewTypeName: '보병',
|
||||
traits: { personal: '대담', specialDomestic: '상재', specialWar: '무쌍' },
|
||||
turnTime: state.generalTurnTime ?? '0185-01-01T00:00:00.000Z',
|
||||
nextTurnMonthOffset: state.nextTurnMonthOffset ?? 0,
|
||||
},
|
||||
city: {
|
||||
id: 1,
|
||||
@@ -587,7 +592,10 @@ const installFixture = async (page: Page, state: NavigationFixture) => {
|
||||
month: state.currentMonth ?? 1,
|
||||
turnTerm: 10,
|
||||
serverTime: state.serverTime ?? '2026-08-13T00:00:00.000Z',
|
||||
serverWallTime: state.serverWallTime ?? '2026-08-13T00:00:00.000Z',
|
||||
clockMode: state.clockMode ?? 'realtime',
|
||||
clockRunning: state.clockRunning ?? true,
|
||||
clockStartsAt: state.clockStartsAt ?? null,
|
||||
scenarioTitle: state.scenarioTitle ?? '',
|
||||
});
|
||||
}
|
||||
@@ -1182,7 +1190,7 @@ test('desktop menus preserve ref columns, prefix-safe routes, and controlled dro
|
||||
await expect(page.locator('.legacy-game-info')).toContainText('현재: 185년 1월');
|
||||
await expect(page.locator('.legacy-game-info')).toContainText('턴: 10분');
|
||||
await expect(page.locator('.legacy-game-info')).not.toContainText('최근 턴:');
|
||||
await expect(page.locator('.execution-status')).toHaveText('동작 시각: 08-13 09:05');
|
||||
await expect(page.locator('.execution-status')).toHaveText('현재 시각: 08-13 09:00');
|
||||
await expect(page.locator('.tournament-status')).toHaveText('토너먼트: 참가 모집중');
|
||||
await expect(page.locator('.vote-status')).toHaveText('설문: 메뉴 설문');
|
||||
const headerStatusGeometry = await page.locator('.main-page').evaluate((element) => {
|
||||
@@ -1617,6 +1625,105 @@ test('the repeated bottom global menu opens upward on the mobile document', asyn
|
||||
await persistArtifact(page, `${basePath.slice(1)}-mobile-bottom-dropup`);
|
||||
});
|
||||
|
||||
test('first reserved month crosses December only after the general turn has passed', async ({ page }, testInfo) => {
|
||||
const state: NavigationFixture = {
|
||||
officerLevel: 0,
|
||||
permission: 0,
|
||||
nationLevel: 0,
|
||||
stage: 0,
|
||||
npcMode: 1,
|
||||
generalMeCalls: 0,
|
||||
operations: [],
|
||||
currentYear: 179,
|
||||
currentMonth: 12,
|
||||
nextTurnMonthOffset: 0,
|
||||
validMapImages: true,
|
||||
reservedTurns: [
|
||||
{ index: 0, action: '휴식', args: {} },
|
||||
{ index: 1, action: '휴식', args: {} },
|
||||
],
|
||||
};
|
||||
await installRealtimeHarness(page);
|
||||
await installFixture(page, state);
|
||||
await page.setViewportSize({ width: 1200, height: 900 });
|
||||
await waitForMain(page);
|
||||
await waitForMainRealtime(page);
|
||||
|
||||
const map = page.locator('[data-main-target="map"] .map-viewer').first();
|
||||
const commandPanel = page.locator('[data-main-target="commands"]').first();
|
||||
const firstDate = commandPanel.locator('.date-column [data-turn-index="0"]');
|
||||
const secondDate = commandPanel.locator('.date-column [data-turn-index="1"]');
|
||||
|
||||
await expect(map).toContainText('179年 12月');
|
||||
await expect(firstDate).toHaveText('179年 12月');
|
||||
await expect(secondDate).toHaveText('180年 1月');
|
||||
const before = await firstDate.evaluate((element) => {
|
||||
const rect = element.getBoundingClientRect();
|
||||
const style = getComputedStyle(element);
|
||||
return {
|
||||
rect: rect.toJSON(),
|
||||
fontSize: style.fontSize,
|
||||
lineHeight: style.lineHeight,
|
||||
color: style.color,
|
||||
documentScrollWidth: document.documentElement.scrollWidth,
|
||||
viewportWidth: window.innerWidth,
|
||||
};
|
||||
});
|
||||
await commandPanel.screenshot({ path: testInfo.outputPath('turn-month-before.png') });
|
||||
|
||||
state.nextTurnMonthOffset = 1;
|
||||
state.contextRevision = 'BBBBBBBBBBBBBBBBBBBBBB';
|
||||
state.contextOperations = [{ op: 'replace', path: '/general/nextTurnMonthOffset', value: 1 }];
|
||||
await emitReadModelInvalidation(page, readModelInvalidation({ context: true }));
|
||||
|
||||
await expect(map).toContainText('179年 12月');
|
||||
await expect(firstDate).toHaveText('180年 1月');
|
||||
await expect(secondDate).toHaveText('180年 2月');
|
||||
await firstDate.hover();
|
||||
const after = await firstDate.evaluate((element) => {
|
||||
const rect = element.getBoundingClientRect();
|
||||
const style = getComputedStyle(element);
|
||||
return {
|
||||
rect: rect.toJSON(),
|
||||
fontSize: style.fontSize,
|
||||
lineHeight: style.lineHeight,
|
||||
color: style.color,
|
||||
documentScrollWidth: document.documentElement.scrollWidth,
|
||||
viewportWidth: window.innerWidth,
|
||||
};
|
||||
});
|
||||
expect(after.rect.width).toBe(before.rect.width);
|
||||
expect(after.rect.height).toBe(before.rect.height);
|
||||
expect(after.rect.left).toBe(before.rect.left);
|
||||
expect(after.rect.right).toBe(before.rect.right);
|
||||
expect(after.fontSize).toBe(before.fontSize);
|
||||
expect(after.lineHeight).toBe(before.lineHeight);
|
||||
expect(after.color).toBe(before.color);
|
||||
expect(before.documentScrollWidth).toBe(before.viewportWidth);
|
||||
expect(after.documentScrollWidth).toBe(after.viewportWidth);
|
||||
await commandPanel.screenshot({ path: testInfo.outputPath('turn-month-after.png') });
|
||||
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await firstDate.scrollIntoViewIfNeeded();
|
||||
await expect(firstDate).toHaveText('180年 1月');
|
||||
const mobile = await firstDate.evaluate((element) => {
|
||||
const rect = element.getBoundingClientRect();
|
||||
const style = getComputedStyle(element);
|
||||
return {
|
||||
rect: rect.toJSON(),
|
||||
fontSize: style.fontSize,
|
||||
lineHeight: style.lineHeight,
|
||||
documentScrollWidth: document.documentElement.scrollWidth,
|
||||
};
|
||||
});
|
||||
expect(mobile.rect.left).toBeGreaterThanOrEqual(0);
|
||||
expect(mobile.rect.right).toBeLessThanOrEqual(500);
|
||||
expect(mobile.fontSize).toBe(before.fontSize);
|
||||
expect(mobile.lineHeight).toBe(before.lineHeight);
|
||||
expect(mobile.documentScrollWidth).toBe(500);
|
||||
await commandPanel.screenshot({ path: testInfo.outputPath('turn-month-mobile.png') });
|
||||
});
|
||||
|
||||
test('main general card uses local turn time and command clock tracks corrected server time', async ({ page }) => {
|
||||
const state: NavigationFixture = {
|
||||
officerLevel: 0,
|
||||
@@ -1743,12 +1850,131 @@ test('main general card uses local turn time and command clock tracks corrected
|
||||
}
|
||||
|
||||
state.clockMode = 'manual';
|
||||
state.clockRunning = false;
|
||||
state.serverTime = '2026-08-13T00:08:30.000Z';
|
||||
await page.reload();
|
||||
const frozenClock = page.locator('[data-main-target="commands"] [data-command-current-time]').first();
|
||||
await expect(frozenClock).toHaveText('09:08:30');
|
||||
await page.clock.runFor(2_000);
|
||||
await expect(frozenClock).toHaveText('09:08:30');
|
||||
|
||||
state.clockMode = 'realtime';
|
||||
state.clockRunning = false;
|
||||
state.serverTime = '2026-08-13T00:10:00.000Z';
|
||||
state.serverWallTime = '2026-08-21T10:00:00.000Z';
|
||||
state.clockStartsAt = '2026-08-21T10:00:02.000Z';
|
||||
await page.reload();
|
||||
const preopenClock = page.locator('[data-main-target="commands"] [data-command-current-time]').first();
|
||||
await expect(preopenClock).toHaveText('09:10:00');
|
||||
const operationsBeforePreopenBoundary = state.operations.length;
|
||||
await page.clock.runFor(1_500);
|
||||
await expect(preopenClock).toHaveText('09:10:00');
|
||||
if (artifactRoot) {
|
||||
const preopenGeometry = await preopenClock.evaluate((element) => ({
|
||||
rect: element.getBoundingClientRect().toJSON(),
|
||||
overflow: element.scrollWidth - element.clientWidth,
|
||||
fontSize: getComputedStyle(element).fontSize,
|
||||
lineHeight: getComputedStyle(element).lineHeight,
|
||||
value: element.textContent,
|
||||
}));
|
||||
expect(preopenGeometry.overflow).toBeLessThanOrEqual(0);
|
||||
await Promise.all([
|
||||
page.screenshot({
|
||||
path: resolve(artifactRoot, 'main-preopen-clock-frozen-mobile-500.png'),
|
||||
fullPage: true,
|
||||
}),
|
||||
writeFile(
|
||||
resolve(artifactRoot, 'main-preopen-clock-frozen-mobile-500.json'),
|
||||
`${JSON.stringify(preopenGeometry, null, 2)}\n`
|
||||
),
|
||||
]);
|
||||
}
|
||||
await page.clock.runFor(1_500);
|
||||
await expect(preopenClock).toHaveText('09:10:01');
|
||||
expect(state.operations).toHaveLength(operationsBeforePreopenBoundary);
|
||||
});
|
||||
|
||||
test('main header clock follows minute boundaries only while game-server contact is recent', async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
const state: NavigationFixture = {
|
||||
officerLevel: 0,
|
||||
permission: 0,
|
||||
nationLevel: 0,
|
||||
stage: 0,
|
||||
npcMode: 1,
|
||||
generalMeCalls: 0,
|
||||
operations: [],
|
||||
serverTime: '2026-08-13T00:00:35.000Z',
|
||||
serverWallTime: '2026-08-13T00:00:00.000Z',
|
||||
clockMode: 'realtime',
|
||||
clockRunning: true,
|
||||
};
|
||||
await installRealtimeHarness(page);
|
||||
await installFixture(page, state);
|
||||
await page.clock.install({ time: new Date('2026-08-13T00:00:00.000Z') });
|
||||
await page.setViewportSize({ width: 1200, height: 900 });
|
||||
await waitForMain(page);
|
||||
await waitForMainRealtime(page);
|
||||
|
||||
const clock = page.locator('.execution-status');
|
||||
const initialRequestCount = state.trpcRequests?.length ?? 0;
|
||||
await expect(clock).toHaveText('현재 시각: 08-13 09:00');
|
||||
await expect(clock).not.toHaveClass(/execution-status--stale/u);
|
||||
|
||||
await page.clock.runFor(25_000);
|
||||
await expect(clock).toHaveText('현재 시각: 08-13 09:01');
|
||||
|
||||
await page.clock.runFor(21_000);
|
||||
await expect(clock).toHaveClass(/execution-status--stale/u);
|
||||
await expect(clock).toHaveAttribute('title', '최근 45초 동안 서버 통신이 없어 시각 갱신을 멈췄습니다.');
|
||||
await expect.poll(() => clock.evaluate((element) => getComputedStyle(element).color)).toBe('rgb(255, 0, 255)');
|
||||
const staleDesktopGeometry = await clock.evaluate((element) => ({
|
||||
rect: element.getBoundingClientRect().toJSON(),
|
||||
overflow: element.scrollWidth - element.clientWidth,
|
||||
color: getComputedStyle(element).color,
|
||||
fontSize: getComputedStyle(element).fontSize,
|
||||
lineHeight: getComputedStyle(element).lineHeight,
|
||||
}));
|
||||
expect(staleDesktopGeometry.rect.width).toBeCloseTo(333.33, 0);
|
||||
expect(staleDesktopGeometry.rect.height).toBeGreaterThanOrEqual(36);
|
||||
expect(staleDesktopGeometry.overflow).toBeLessThanOrEqual(0);
|
||||
await clock.screenshot({ path: testInfo.outputPath('main-header-clock-stale-desktop-1200.png') });
|
||||
await page.clock.runFor(60_000);
|
||||
await expect(clock).toHaveText('현재 시각: 08-13 09:01');
|
||||
|
||||
await page.evaluate(() => {
|
||||
(window as unknown as { __emitMainRealtime: (type: string, value: unknown) => void }).__emitMainRealtime(
|
||||
'ping',
|
||||
{}
|
||||
);
|
||||
});
|
||||
await expect(clock).toHaveText('현재 시각: 08-13 09:02');
|
||||
await expect(clock).not.toHaveClass(/execution-status--stale/u);
|
||||
await page.clock.runFor(39_000);
|
||||
await expect(clock).toHaveText('현재 시각: 08-13 09:03');
|
||||
await expect.poll(() => clock.evaluate((element) => getComputedStyle(element).color)).toBe('rgb(0, 255, 255)');
|
||||
|
||||
await page.setViewportSize({ width: 500, height: 900 });
|
||||
const freshMobileGeometry = await clock.evaluate((element) => ({
|
||||
rect: element.getBoundingClientRect().toJSON(),
|
||||
overflow: element.scrollWidth - element.clientWidth,
|
||||
color: getComputedStyle(element).color,
|
||||
fontSize: getComputedStyle(element).fontSize,
|
||||
lineHeight: getComputedStyle(element).lineHeight,
|
||||
documentScrollWidth: document.documentElement.scrollWidth,
|
||||
}));
|
||||
expect(freshMobileGeometry.rect.width).toBeCloseTo(166.67, 0);
|
||||
expect(freshMobileGeometry.overflow).toBeLessThanOrEqual(0);
|
||||
expect(freshMobileGeometry.documentScrollWidth).toBe(500);
|
||||
await Promise.all([
|
||||
clock.screenshot({ path: testInfo.outputPath('main-header-clock-fresh-mobile-500.png') }),
|
||||
writeFile(
|
||||
testInfo.outputPath('main-header-clock-geometry.json'),
|
||||
`${JSON.stringify({ staleDesktopGeometry, freshMobileGeometry }, null, 2)}\n`
|
||||
),
|
||||
]);
|
||||
expect(state.trpcRequests?.length ?? 0).toBe(initialRequestCount);
|
||||
});
|
||||
|
||||
test('message targets keep reply behavior and use nation-color contrast in labels and select options', async ({
|
||||
@@ -2064,6 +2290,7 @@ test('main cards and command input stay inside their Ref-sized grid slots', asyn
|
||||
expect(Math.max(...nationRowHeights) - Math.min(...nationRowHeights)).toBeLessThanOrEqual(0.01);
|
||||
const strategicCell = nationCard.locator('.strategic');
|
||||
const strategicTooltip = strategicCell.getByRole('tooltip');
|
||||
await expect(strategicCell).toHaveCSS('text-decoration-line', 'none');
|
||||
await expect(strategicTooltip).toBeHidden();
|
||||
await strategicCell.hover();
|
||||
await expect(strategicTooltip).toBeVisible();
|
||||
|
||||
@@ -266,6 +266,7 @@ test('renders Ref-shaped token cards, preserves keep cooldown and retries posses
|
||||
});
|
||||
const tooltip = page.locator('.npc-tooltip').first();
|
||||
const tooltipPopup = tooltip.getByRole('tooltip');
|
||||
await expect(tooltip).toHaveCSS('text-decoration-line', 'none');
|
||||
await expect(tooltipPopup).toBeHidden();
|
||||
await tooltip.hover();
|
||||
await expect(tooltipPopup).toBeVisible();
|
||||
|
||||
@@ -80,7 +80,7 @@ const baseTroops = (): TroopFixture[] => [
|
||||
name: '백마대',
|
||||
nationId: 1,
|
||||
turnTime: '2026-07-25T08:20:30.000Z',
|
||||
reservedCommands: ['che_집합', 'che_이동'],
|
||||
reservedCommands: ['집합', '-'],
|
||||
leader: {
|
||||
id: 1,
|
||||
name: '공손찬',
|
||||
@@ -96,7 +96,7 @@ const baseTroops = (): TroopFixture[] => [
|
||||
name: '청룡대',
|
||||
nationId: 1,
|
||||
turnTime: '2026-07-25T08:30:30.000Z',
|
||||
reservedCommands: ['che_징병'],
|
||||
reservedCommands: ['-'],
|
||||
leader: {
|
||||
id: 2,
|
||||
name: '관우',
|
||||
@@ -224,6 +224,27 @@ const installApiFixture = async (page: Page, state: FixtureState) => {
|
||||
});
|
||||
};
|
||||
|
||||
test('shows only the Ref-safe first-five troop command labels on desktop and mobile', async ({ page }) => {
|
||||
await installApiFixture(page, {
|
||||
me: { id: 1, troopId: 1 },
|
||||
permission: 4,
|
||||
troops: baseTroops(),
|
||||
});
|
||||
|
||||
for (const viewport of [
|
||||
{ width: 1000, height: 800 },
|
||||
{ width: 500, height: 800 },
|
||||
]) {
|
||||
await page.setViewportSize(viewport);
|
||||
await gotoTroop(page);
|
||||
|
||||
const firstTroopCommands = page.locator('.troopReservedCommand').first();
|
||||
await expect(firstTroopCommands).toContainText('1: 집합');
|
||||
await expect(firstTroopCommands).toContainText('2: -');
|
||||
await expect(page.locator('#troopList')).not.toContainText('che_');
|
||||
}
|
||||
});
|
||||
|
||||
test('renders the legacy desktop grid with matching computed geometry and states', async ({ page }) => {
|
||||
await installApiFixture(page, {
|
||||
me: { id: 1, troopId: 1 },
|
||||
@@ -233,6 +254,9 @@ test('renders the legacy desktop grid with matching computed geometry and states
|
||||
await page.setViewportSize({ width: 1000, height: 800 });
|
||||
await gotoTroop(page);
|
||||
await expect(page.locator('.troopInfo').filter({ hasText: '백마대' })).toBeVisible();
|
||||
await expect(page.locator('.troopReservedCommand').first()).toContainText('1: 집합');
|
||||
await expect(page.locator('.troopReservedCommand').first()).toContainText('2: -');
|
||||
await expect(page.locator('#troopList')).not.toContainText('che_');
|
||||
|
||||
const geometry = await page
|
||||
.locator('.troopItem')
|
||||
@@ -319,6 +343,9 @@ test('matches the legacy 500px responsive placement', async ({ page }) => {
|
||||
await page.setViewportSize({ width: 500, height: 800 });
|
||||
await gotoTroop(page);
|
||||
await expect(page.locator('.troopInfo').filter({ hasText: '백마대' })).toBeVisible();
|
||||
await expect(page.locator('.troopReservedCommand').first()).toContainText('1: 집합');
|
||||
await expect(page.locator('.troopReservedCommand').first()).toContainText('2: -');
|
||||
await expect(page.locator('#troopList')).not.toContainText('che_');
|
||||
|
||||
const geometry = await page
|
||||
.locator('.troopItem')
|
||||
|
||||
@@ -29,8 +29,6 @@ defineProps<{
|
||||
}
|
||||
.directory-tooltip--enabled {
|
||||
cursor: help;
|
||||
text-decoration: underline dotted rgb(150 210 255 / 85%);
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
.directory-tooltip--enabled:focus-visible {
|
||||
border-radius: 2px;
|
||||
|
||||
@@ -3,6 +3,7 @@ import { computed, onUnmounted, ref, watch } from 'vue';
|
||||
import { addMinutes } from 'date-fns';
|
||||
import ReservedCommandEditor from '../command/ReservedCommandEditor.vue';
|
||||
import { formatLocalDateTime, formatLocalTimeSeconds } from '../../utils/legacyDateTime';
|
||||
import { projectServerClock, sampleServerClock, type SampledServerClock } from '../../utils/serverClockProjection';
|
||||
import type {
|
||||
CommandMapData,
|
||||
CommandMapLayout,
|
||||
@@ -15,12 +16,15 @@ const props = defineProps<{
|
||||
commandTable: CommandTable | null;
|
||||
loading: boolean;
|
||||
reservedGeneralTurns: Array<{ index: number; action: string; args?: unknown }> | null;
|
||||
general: { id: number; turnTime?: string } | null;
|
||||
general: { id: number; turnTime?: string; nextTurnMonthOffset?: 0 | 1 } | null;
|
||||
currentYear?: number;
|
||||
currentMonth?: number;
|
||||
turnTermMinutes?: number;
|
||||
serverTime?: string;
|
||||
serverWallTime?: string;
|
||||
clockMode?: 'realtime' | 'manual';
|
||||
clockRunning?: boolean;
|
||||
clockStartsAt?: string | null;
|
||||
autorunLimit?: number | null;
|
||||
storageKey?: string;
|
||||
mapData?: CommandMapData | null;
|
||||
@@ -41,13 +45,19 @@ const labelMap = computed(() => {
|
||||
return result;
|
||||
});
|
||||
|
||||
const firstReservedMonth = computed(
|
||||
() =>
|
||||
(props.currentYear ?? 0) * 12 +
|
||||
(props.currentMonth ?? 1) -
|
||||
1 +
|
||||
(props.general?.nextTurnMonthOffset ?? 0)
|
||||
);
|
||||
|
||||
const rows = computed<ReservedCommandRow[]>(() => {
|
||||
const base = props.general?.turnTime ? new Date(props.general.turnTime) : null;
|
||||
const term = props.turnTermMinutes ?? 0;
|
||||
const baseYear = props.currentYear ?? 0;
|
||||
const baseMonth = props.currentMonth ?? 1;
|
||||
return (props.reservedGeneralTurns ?? []).map((turn, offset) => {
|
||||
const absoluteMonth = baseYear * 12 + baseMonth - 1 + offset;
|
||||
const absoluteMonth = firstReservedMonth.value + offset;
|
||||
const date = base && Number.isFinite(base.getTime()) ? addMinutes(base, offset * term) : null;
|
||||
return {
|
||||
...turn,
|
||||
@@ -67,9 +77,7 @@ const rows = computed<ReservedCommandRow[]>(() => {
|
||||
|
||||
const autonomousUntil = computed(() => {
|
||||
if (props.autorunLimit == null) return null;
|
||||
const baseYear = props.currentYear ?? 0;
|
||||
const baseMonth = props.currentMonth ?? 1;
|
||||
const currentAbsoluteMonth = baseYear * 12 + baseMonth - 1;
|
||||
const currentAbsoluteMonth = firstReservedMonth.value;
|
||||
const lastAutonomousMonth = props.autorunLimit - 1;
|
||||
if (lastAutonomousMonth < currentAbsoluteMonth) return null;
|
||||
|
||||
@@ -86,32 +94,34 @@ const autonomousUntil = computed(() => {
|
||||
});
|
||||
|
||||
const currentServerTime = ref('--:--:--');
|
||||
let sampledServerTimeMs: number | null = null;
|
||||
let sampledClientTimeMs = 0;
|
||||
const MAX_SERVER_CLOCK_TIMER_DELAY_MS = 60_000;
|
||||
let serverClockSample: SampledServerClock | null = null;
|
||||
let serverClockTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
const updateServerClock = () => {
|
||||
if (serverClockTimer !== undefined) clearTimeout(serverClockTimer);
|
||||
serverClockTimer = undefined;
|
||||
if (sampledServerTimeMs === null) {
|
||||
if (serverClockSample === null) {
|
||||
currentServerTime.value = '--:--:--';
|
||||
return;
|
||||
}
|
||||
const projectedTime = new Date(
|
||||
props.clockMode === 'manual' ? sampledServerTimeMs : sampledServerTimeMs + Date.now() - sampledClientTimeMs
|
||||
);
|
||||
const { clientElapsedMs, time: projectedTime } = projectServerClock(serverClockSample);
|
||||
currentServerTime.value = formatLocalTimeSeconds(projectedTime);
|
||||
if (props.clockMode !== 'manual') {
|
||||
serverClockTimer = setTimeout(updateServerClock, 1_000 - projectedTime.getMilliseconds());
|
||||
if (serverClockSample.clockMode !== 'manual' && serverClockSample.startDelayMs !== null) {
|
||||
const untilStartMs = serverClockSample.startDelayMs - clientElapsedMs;
|
||||
serverClockTimer = setTimeout(
|
||||
updateServerClock,
|
||||
untilStartMs > 0
|
||||
? Math.min(untilStartMs, MAX_SERVER_CLOCK_TIMER_DELAY_MS)
|
||||
: 1_000 - projectedTime.getMilliseconds()
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
watch(
|
||||
() => [props.serverTime, props.clockMode] as const,
|
||||
([serverTime]) => {
|
||||
const parsed = serverTime ? new Date(serverTime).getTime() : Number.NaN;
|
||||
sampledServerTimeMs = Number.isFinite(parsed) ? parsed : null;
|
||||
sampledClientTimeMs = Date.now();
|
||||
() => [props.serverTime, props.serverWallTime, props.clockMode, props.clockRunning, props.clockStartsAt] as const,
|
||||
([serverTime, serverWallTime, clockMode, clockRunning, clockStartsAt]) => {
|
||||
serverClockSample = sampleServerClock({ serverTime, serverWallTime, clockMode, clockRunning, clockStartsAt });
|
||||
updateServerClock();
|
||||
},
|
||||
{ immediate: true }
|
||||
|
||||
@@ -7,6 +7,7 @@ export type GeneralBattleSummaryData = {
|
||||
available?: boolean;
|
||||
experience?: number | null;
|
||||
dedicationText?: string | null;
|
||||
bill?: number | null;
|
||||
warnum?: number | null;
|
||||
wins?: number | null;
|
||||
losses?: number | null;
|
||||
@@ -62,8 +63,13 @@ const killRate = computed(() => {
|
||||
<template v-else>
|
||||
<span>명성</span><strong>{{ numberText(summary.experience) }}</strong> <span>계급</span
|
||||
><strong>{{ summary.dedicationText || '-' }}</strong>
|
||||
<span class="battle-general-extra__empty" aria-hidden="true"></span>
|
||||
<strong class="battle-general-extra__empty" aria-hidden="true"></strong>
|
||||
<template v-if="summary.bill !== undefined">
|
||||
<span>봉급</span><strong>{{ numberText(summary.bill) }}</strong>
|
||||
</template>
|
||||
<template v-else>
|
||||
<span class="battle-general-extra__empty" aria-hidden="true"></span>
|
||||
<strong class="battle-general-extra__empty" aria-hidden="true"></strong>
|
||||
</template>
|
||||
<span>전투</span
|
||||
><strong>{{ numberText(summary.warnum) }}<template v-if="summary.warnum != null">회</template></strong>
|
||||
<span>계략</span><strong>{{ numberText(summary.strategies) }}</strong>
|
||||
|
||||
@@ -1,10 +1,26 @@
|
||||
<script setup lang="ts">
|
||||
import { formatServerDateTime } from '@sammo-ts/common/time/ServerDateTime';
|
||||
import { computed } from 'vue';
|
||||
import { computed, onUnmounted, ref, watch } from 'vue';
|
||||
import { resolveTournamentStageName } from '../../utils/tournamentStatus';
|
||||
import {
|
||||
GAME_SERVER_ACTIVITY_FRESHNESS_MS,
|
||||
gameServerActivity,
|
||||
isRecentGameServerActivity,
|
||||
} from '../../utils/gameServerActivity';
|
||||
import {
|
||||
millisecondsUntilNextMinute,
|
||||
projectServerClock,
|
||||
sampleServerClock,
|
||||
type SampledServerClock,
|
||||
} from '../../utils/serverClockProjection';
|
||||
|
||||
const props = defineProps<{
|
||||
tournamentStage: number;
|
||||
serverTime?: string;
|
||||
serverWallTime?: string;
|
||||
clockMode?: 'realtime' | 'manual';
|
||||
clockRunning?: boolean;
|
||||
clockStartsAt?: string | null;
|
||||
status: {
|
||||
onlineUserCount: number;
|
||||
onlineNations: string;
|
||||
@@ -20,16 +36,75 @@ const props = defineProps<{
|
||||
}>();
|
||||
|
||||
const tournamentStatus = computed(() => resolveTournamentStageName(props.tournamentStage));
|
||||
const lastExecutedStatus = computed(() =>
|
||||
formatServerDateTime(props.status?.lastExecuted, { format: 'monthDayTime', fallback: '기록 없음' })
|
||||
const currentServerTime = ref('기록 없음');
|
||||
const hasServerClock = ref(false);
|
||||
const serverClockFresh = ref(false);
|
||||
const serverClockTitle = computed(() => {
|
||||
if (!hasServerClock.value) return '서버 시각을 아직 받지 못했습니다.';
|
||||
if (!serverClockFresh.value) return '최근 45초 동안 서버 통신이 없어 시각 갱신을 멈췄습니다.';
|
||||
return undefined;
|
||||
});
|
||||
|
||||
let serverClockSample: SampledServerClock | null = null;
|
||||
let serverClockTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
const updateServerClock = () => {
|
||||
if (serverClockTimer !== undefined) clearTimeout(serverClockTimer);
|
||||
serverClockTimer = undefined;
|
||||
if (serverClockSample === null) {
|
||||
currentServerTime.value = '기록 없음';
|
||||
hasServerClock.value = false;
|
||||
serverClockFresh.value = false;
|
||||
return;
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const projection = projectServerClock(serverClockSample, now);
|
||||
currentServerTime.value = formatServerDateTime(projection.time, {
|
||||
format: 'monthDayTime',
|
||||
fallback: '기록 없음',
|
||||
});
|
||||
hasServerClock.value = true;
|
||||
|
||||
const lastContactAt = gameServerActivity.lastContactAt.value;
|
||||
serverClockFresh.value = isRecentGameServerActivity(lastContactAt, now);
|
||||
if (!serverClockFresh.value || lastContactAt === null) return;
|
||||
|
||||
const nextDelays = [lastContactAt + GAME_SERVER_ACTIVITY_FRESHNESS_MS - now + 1];
|
||||
if (serverClockSample.clockMode !== 'manual' && serverClockSample.startDelayMs !== null) {
|
||||
const untilStartMs = serverClockSample.startDelayMs - projection.clientElapsedMs;
|
||||
nextDelays.push(untilStartMs > 0 ? untilStartMs : millisecondsUntilNextMinute(projection.time));
|
||||
}
|
||||
serverClockTimer = setTimeout(updateServerClock, Math.max(1, Math.min(...nextDelays)));
|
||||
};
|
||||
|
||||
watch(
|
||||
() => [props.serverTime, props.serverWallTime, props.clockMode, props.clockRunning, props.clockStartsAt] as const,
|
||||
([serverTime, serverWallTime, clockMode, clockRunning, clockStartsAt]) => {
|
||||
serverClockSample = sampleServerClock({ serverTime, serverWallTime, clockMode, clockRunning, clockStartsAt });
|
||||
updateServerClock();
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
watch(() => gameServerActivity.lastContactAt.value, updateServerClock);
|
||||
|
||||
onUnmounted(() => {
|
||||
if (serverClockTimer !== undefined) clearTimeout(serverClockTimer);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="front-status" aria-label="접속 현황과 국가 방침">
|
||||
<div class="activity-status" aria-label="동작 시각, 토너먼트와 설문 진행 현황">
|
||||
<div class="status-row execution-status" :class="{ 'execution-status--empty': !status?.lastExecuted }">
|
||||
동작 시각: {{ lastExecutedStatus }}
|
||||
<div class="activity-status" aria-label="현재 시각, 토너먼트와 설문 진행 현황">
|
||||
<div
|
||||
class="status-row execution-status"
|
||||
:class="{
|
||||
'execution-status--empty': !hasServerClock,
|
||||
'execution-status--stale': hasServerClock && !serverClockFresh,
|
||||
}"
|
||||
:title="serverClockTitle"
|
||||
>
|
||||
현재 시각: {{ currentServerTime }}
|
||||
</div>
|
||||
<div class="status-row tournament-status">
|
||||
<RouterLink to="/tournament">
|
||||
@@ -120,6 +195,10 @@ const lastExecutedStatus = computed(() =>
|
||||
color: magenta;
|
||||
}
|
||||
|
||||
.execution-status--stale {
|
||||
color: magenta;
|
||||
}
|
||||
|
||||
.vote-label {
|
||||
color: cyan;
|
||||
}
|
||||
|
||||
@@ -284,7 +284,6 @@ const displayChiefName = (chief: NationChief | undefined): string => {
|
||||
|
||||
.strategic.has-tooltip {
|
||||
overflow: visible;
|
||||
text-decoration: underline dashed red;
|
||||
}
|
||||
|
||||
.cooldown-tooltip {
|
||||
|
||||
@@ -97,8 +97,6 @@ watch(
|
||||
|
||||
.rich-tooltip-trigger--enabled {
|
||||
cursor: help;
|
||||
text-decoration: underline dotted rgb(150 210 255 / 85%);
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
|
||||
.rich-tooltip-trigger--enabled:focus-visible {
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
import { createBroadcastTabCoordinator, type BroadcastTabCoordinator } from '../utils/broadcastTabCoordinator';
|
||||
import { resolveWithReadModelSnapshotFallback } from '../utils/readModelDeltaRecovery';
|
||||
import { createRealtimeRequestOptions } from '../utils/realtimeAccessGrant';
|
||||
import { markGameServerContact } from '../utils/gameServerActivity';
|
||||
|
||||
const REALTIME_FULL_REFRESH_MIN_INTERVAL_MS = 5_000;
|
||||
|
||||
@@ -1097,10 +1098,12 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => {
|
||||
onPayload: (message) => {
|
||||
if (!isRealtimeParticipant()) return;
|
||||
if (message.kind === 'patch') {
|
||||
markGameServerContact();
|
||||
applyDashboardPatch(message.patch);
|
||||
return;
|
||||
}
|
||||
realtimeStatus.value = message.status;
|
||||
if (message.status === 'connected') markGameServerContact();
|
||||
},
|
||||
});
|
||||
realtimeCoordinator.start();
|
||||
@@ -1153,6 +1156,7 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => {
|
||||
realtimeSource = source;
|
||||
|
||||
source.addEventListener('open', () => {
|
||||
markGameServerContact();
|
||||
realtimeStatus.value = 'connected';
|
||||
realtimeCoordinator?.postFromLeader({ kind: 'status', status: 'connected' });
|
||||
});
|
||||
@@ -1166,6 +1170,7 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => {
|
||||
if (!payload || payload.type !== 'readModelInvalidated') {
|
||||
return;
|
||||
}
|
||||
markGameServerContact();
|
||||
readModelRefreshQueue.request(payload.invalidation, payload.refreshGrant);
|
||||
});
|
||||
source.addEventListener('messagesInvalidated', (event) => {
|
||||
@@ -1174,6 +1179,7 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => {
|
||||
if (!payload || payload.type !== 'messagesInvalidated') {
|
||||
return;
|
||||
}
|
||||
markGameServerContact();
|
||||
void refreshMessages(payload.refreshGrant);
|
||||
});
|
||||
|
||||
@@ -1182,14 +1188,17 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => {
|
||||
for (const legacyEventType of ['turnCompleted', 'readModelChanged'] as const) {
|
||||
source.addEventListener(legacyEventType, () => {
|
||||
if (realtimeCoordinator !== null && !realtimeCoordinator.isLeader()) return;
|
||||
markGameServerContact();
|
||||
realtimeRefreshQueue.request();
|
||||
});
|
||||
}
|
||||
source.addEventListener('messageCreated', () => {
|
||||
if (realtimeCoordinator !== null && !realtimeCoordinator.isLeader()) return;
|
||||
markGameServerContact();
|
||||
void refreshMessages();
|
||||
});
|
||||
source.addEventListener('ping', () => {
|
||||
markGameServerContact();
|
||||
if (realtimeEnabled.value) {
|
||||
realtimeStatus.value = 'connected';
|
||||
realtimeCoordinator?.postFromLeader({ kind: 'status', status: 'connected' });
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { readonly, ref, type Ref } from 'vue';
|
||||
|
||||
export const GAME_SERVER_ACTIVITY_FRESHNESS_MS = 45_000;
|
||||
|
||||
export type GameServerActivityTracker = {
|
||||
lastContactAt: Readonly<Ref<number | null>>;
|
||||
markContact: (contactAt?: number) => void;
|
||||
};
|
||||
|
||||
export const createGameServerActivityTracker = (): GameServerActivityTracker => {
|
||||
const lastContactAt = ref<number | null>(null);
|
||||
|
||||
return {
|
||||
lastContactAt: readonly(lastContactAt),
|
||||
markContact(contactAt = Date.now()) {
|
||||
if (!Number.isFinite(contactAt)) return;
|
||||
lastContactAt.value = contactAt;
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export const isRecentGameServerActivity = (
|
||||
lastContactAt: number | null,
|
||||
now = Date.now(),
|
||||
freshnessMs = GAME_SERVER_ACTIVITY_FRESHNESS_MS
|
||||
): boolean =>
|
||||
lastContactAt !== null &&
|
||||
Number.isFinite(lastContactAt) &&
|
||||
Number.isFinite(now) &&
|
||||
Math.max(0, now - lastContactAt) <= freshnessMs;
|
||||
|
||||
export const gameServerActivity = createGameServerActivityTracker();
|
||||
|
||||
export const markGameServerContact = (contactAt = Date.now()) => gameServerActivity.markContact(contactAt);
|
||||
@@ -0,0 +1,67 @@
|
||||
export type ServerClockProjectionInput = {
|
||||
serverTime?: string;
|
||||
serverWallTime?: string;
|
||||
clockMode?: 'realtime' | 'manual';
|
||||
clockRunning?: boolean;
|
||||
clockStartsAt?: string | null;
|
||||
};
|
||||
|
||||
export type SampledServerClock = {
|
||||
serverTimeMs: number;
|
||||
sampledClientTimeMs: number;
|
||||
clockMode: 'realtime' | 'manual';
|
||||
startDelayMs: number | null;
|
||||
};
|
||||
|
||||
const parseInstant = (value?: string | null): number | null => {
|
||||
if (!value) return null;
|
||||
const parsed = new Date(value).getTime();
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
};
|
||||
|
||||
export const sampleServerClock = (
|
||||
input: ServerClockProjectionInput,
|
||||
sampledClientTimeMs = Date.now()
|
||||
): SampledServerClock | null => {
|
||||
const serverTimeMs = parseInstant(input.serverTime);
|
||||
if (serverTimeMs === null) return null;
|
||||
|
||||
let startDelayMs: number | null;
|
||||
if (input.clockMode === 'manual') {
|
||||
startDelayMs = null;
|
||||
} else if (input.clockRunning !== false) {
|
||||
startDelayMs = 0;
|
||||
} else {
|
||||
const serverWallTimeMs = parseInstant(input.serverWallTime);
|
||||
const clockStartsAtMs = parseInstant(input.clockStartsAt);
|
||||
startDelayMs =
|
||||
serverWallTimeMs !== null && clockStartsAtMs !== null
|
||||
? Math.max(0, clockStartsAtMs - serverWallTimeMs)
|
||||
: null;
|
||||
}
|
||||
|
||||
return {
|
||||
serverTimeMs,
|
||||
sampledClientTimeMs,
|
||||
clockMode: input.clockMode ?? 'realtime',
|
||||
startDelayMs,
|
||||
};
|
||||
};
|
||||
|
||||
export const projectServerClock = (sample: SampledServerClock, clientTimeMs = Date.now()) => {
|
||||
const clientElapsedMs = Math.max(0, clientTimeMs - sample.sampledClientTimeMs);
|
||||
const elapsedGameMs =
|
||||
sample.clockMode === 'manual' || sample.startDelayMs === null
|
||||
? 0
|
||||
: Math.max(0, clientElapsedMs - sample.startDelayMs);
|
||||
|
||||
return {
|
||||
clientElapsedMs,
|
||||
time: new Date(sample.serverTimeMs + elapsedGameMs),
|
||||
};
|
||||
};
|
||||
|
||||
export const millisecondsUntilNextMinute = (time: Date): number => {
|
||||
const remainder = ((time.getTime() % 60_000) + 60_000) % 60_000;
|
||||
return remainder === 0 ? 60_000 : 60_000 - remainder;
|
||||
};
|
||||
@@ -3,6 +3,7 @@ import { REALTIME_ACCESS_GRANT_HEADER } from '@sammo-ts/common/realtime/types';
|
||||
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
|
||||
import type { AppRouter } from '@sammo-ts/game-api';
|
||||
import { resolveBatchRealtimeAccessGrant } from './realtimeAccessGrant';
|
||||
import { markGameServerContact } from './gameServerActivity';
|
||||
|
||||
const getGameToken = (): string | null => {
|
||||
if (typeof window === 'undefined') {
|
||||
@@ -17,6 +18,11 @@ export const trpc = createTRPCProxyClient<AppRouter>({
|
||||
httpBatchLink({
|
||||
url: import.meta.env.VITE_GAME_API_URL ?? '/api/trpc',
|
||||
...trpcJsonBodyHttpClientOptions,
|
||||
async fetch(input, init) {
|
||||
const result = await globalThis.fetch(input, init);
|
||||
markGameServerContact();
|
||||
return result;
|
||||
},
|
||||
headers({ opList }) {
|
||||
const token = getGameToken();
|
||||
const refreshGrant = resolveBatchRealtimeAccessGrant(opList);
|
||||
|
||||
@@ -291,6 +291,7 @@ onMounted(() => {
|
||||
available: true,
|
||||
experience: selectedGeneral.experience,
|
||||
dedicationText: selectedGeneral.progression.dedicationText,
|
||||
bill: selectedGeneral.bill,
|
||||
warnum: selectedGeneral.warnum,
|
||||
wins: selectedGeneral.battleStats.kills,
|
||||
losses: selectedGeneral.battleStats.deaths,
|
||||
|
||||
@@ -1733,7 +1733,6 @@ onUnmounted(() => {
|
||||
.npc-tooltip {
|
||||
position: relative;
|
||||
cursor: help;
|
||||
text-decoration: underline dotted;
|
||||
}
|
||||
|
||||
.npc-tooltip [role='tooltip'] {
|
||||
|
||||
@@ -243,7 +243,15 @@ watch(
|
||||
</div>
|
||||
|
||||
<div data-main-target="policy">
|
||||
<MainFrontStatus :status="frontStatus" :tournament-stage="tournamentStage" />
|
||||
<MainFrontStatus
|
||||
:status="frontStatus"
|
||||
:tournament-stage="tournamentStage"
|
||||
:server-time="lobbyInfo?.serverTime"
|
||||
:server-wall-time="lobbyInfo?.serverWallTime"
|
||||
:clock-mode="lobbyInfo?.clockMode"
|
||||
:clock-running="lobbyInfo?.clockRunning"
|
||||
:clock-starts-at="lobbyInfo?.clockStartsAt"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<aside v-if="surveyNotice" class="survey-notice" role="status" aria-live="polite">
|
||||
@@ -267,7 +275,10 @@ watch(
|
||||
:current-month="lobbyInfo?.month"
|
||||
:turn-term-minutes="lobbyInfo?.turnTerm"
|
||||
:server-time="lobbyInfo?.serverTime"
|
||||
:server-wall-time="lobbyInfo?.serverWallTime"
|
||||
:clock-mode="lobbyInfo?.clockMode"
|
||||
:clock-running="lobbyInfo?.clockRunning"
|
||||
:clock-starts-at="lobbyInfo?.clockStartsAt"
|
||||
:autorun-limit="reservedGeneralAutorunLimit"
|
||||
:map-data="worldMap"
|
||||
:map-layout="mapLayout"
|
||||
@@ -437,7 +448,10 @@ watch(
|
||||
:current-month="lobbyInfo?.month"
|
||||
:turn-term-minutes="lobbyInfo?.turnTerm"
|
||||
:server-time="lobbyInfo?.serverTime"
|
||||
:server-wall-time="lobbyInfo?.serverWallTime"
|
||||
:clock-mode="lobbyInfo?.clockMode"
|
||||
:clock-running="lobbyInfo?.clockRunning"
|
||||
:clock-starts-at="lobbyInfo?.clockStartsAt"
|
||||
:autorun-limit="reservedGeneralAutorunLimit"
|
||||
:map-data="worldMap"
|
||||
:map-layout="mapLayout"
|
||||
|
||||
@@ -421,6 +421,7 @@ onMounted(() => {
|
||||
available: true,
|
||||
experience: data.general.experience,
|
||||
dedicationText: data.general.progression?.dedicationText,
|
||||
bill: data.general.bill,
|
||||
warnum: data.general.records.battles,
|
||||
wins: data.general.records.wins,
|
||||
losses: data.general.records.losses,
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import {
|
||||
GAME_SERVER_ACTIVITY_FRESHNESS_MS,
|
||||
createGameServerActivityTracker,
|
||||
isRecentGameServerActivity,
|
||||
} from '../src/utils/gameServerActivity.ts';
|
||||
|
||||
void test('keeps the most recently observed server contact timestamp', () => {
|
||||
const tracker = createGameServerActivityTracker();
|
||||
tracker.markContact(2_000);
|
||||
tracker.markContact(1_000);
|
||||
tracker.markContact(Number.NaN);
|
||||
assert.equal(tracker.lastContactAt.value, 1_000);
|
||||
});
|
||||
|
||||
void test('treats three heartbeat intervals as recent activity', () => {
|
||||
assert.equal(isRecentGameServerActivity(1_000, 1_000 + GAME_SERVER_ACTIVITY_FRESHNESS_MS), true);
|
||||
assert.equal(isRecentGameServerActivity(1_000, 1_001 + GAME_SERVER_ACTIVITY_FRESHNESS_MS), false);
|
||||
assert.equal(isRecentGameServerActivity(null, 1_000), false);
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import {
|
||||
millisecondsUntilNextMinute,
|
||||
projectServerClock,
|
||||
sampleServerClock,
|
||||
} from '../src/utils/serverClockProjection.ts';
|
||||
|
||||
void test('projects a running server clock from the browser sample instant', () => {
|
||||
const sample = sampleServerClock(
|
||||
{
|
||||
serverTime: '2026-08-13T00:00:35.250Z',
|
||||
clockMode: 'realtime',
|
||||
clockRunning: true,
|
||||
},
|
||||
10_000
|
||||
);
|
||||
assert.ok(sample);
|
||||
assert.equal(projectServerClock(sample, 34_750).time.toISOString(), '2026-08-13T00:01:00.000Z');
|
||||
assert.equal(millisecondsUntilNextMinute(projectServerClock(sample, 10_000).time), 24_750);
|
||||
});
|
||||
|
||||
void test('keeps manual clocks fixed even while client time advances', () => {
|
||||
const sample = sampleServerClock(
|
||||
{ serverTime: '2026-08-13T00:00:35.000Z', clockMode: 'manual', clockRunning: false },
|
||||
10_000
|
||||
);
|
||||
assert.ok(sample);
|
||||
assert.equal(projectServerClock(sample, 130_000).time.toISOString(), '2026-08-13T00:00:35.000Z');
|
||||
});
|
||||
|
||||
void test('holds a preopen clock until its wall-clock start delay passes', () => {
|
||||
const sample = sampleServerClock(
|
||||
{
|
||||
serverTime: '2026-08-13T00:00:00.000Z',
|
||||
serverWallTime: '2026-08-13T08:00:00.000Z',
|
||||
clockMode: 'realtime',
|
||||
clockRunning: false,
|
||||
clockStartsAt: '2026-08-13T08:01:00.000Z',
|
||||
},
|
||||
10_000
|
||||
);
|
||||
assert.ok(sample);
|
||||
assert.equal(projectServerClock(sample, 69_999).time.toISOString(), '2026-08-13T00:00:00.000Z');
|
||||
assert.equal(projectServerClock(sample, 70_001).time.toISOString(), '2026-08-13T00:00:00.001Z');
|
||||
});
|
||||
|
||||
void test('rejects an invalid server clock sample', () => {
|
||||
assert.equal(sampleServerClock({ serverTime: 'not-a-time' }, 10_000), null);
|
||||
});
|
||||
@@ -396,6 +396,7 @@ const parseInstallOptions = (
|
||||
joinMode: joinMode === 'full' || joinMode === 'onlyRandom' ? joinMode : undefined,
|
||||
autorunUser: autorunUser ?? null,
|
||||
preopenAt: preopenAt ?? null,
|
||||
openAt: openAt ?? null,
|
||||
installOperationId: action.installOperationId,
|
||||
};
|
||||
|
||||
@@ -2173,6 +2174,7 @@ export class GatewayOrchestrator implements GatewayOrchestratorHandle {
|
||||
? {
|
||||
...options.installOptions,
|
||||
preopenAt: options.installOptions.preopenAt?.toISOString() ?? null,
|
||||
openAt: options.installOptions.openAt?.toISOString() ?? null,
|
||||
}
|
||||
: undefined,
|
||||
adminUser: options.adminUser,
|
||||
|
||||
@@ -9,7 +9,10 @@ interface ProfileSeedRequest {
|
||||
scenarioId: number;
|
||||
tickSeconds?: number;
|
||||
now: string;
|
||||
installOptions?: Omit<ScenarioInstallOptions, 'preopenAt'> & { preopenAt?: string | null };
|
||||
installOptions?: Omit<ScenarioInstallOptions, 'preopenAt' | 'openAt'> & {
|
||||
preopenAt?: string | null;
|
||||
openAt?: string | null;
|
||||
};
|
||||
adminUser?: AdminSeedUser | null;
|
||||
}
|
||||
|
||||
@@ -49,6 +52,11 @@ export const runProfileSeedCli = async (env: NodeJS.ProcessEnv = process.env): P
|
||||
if (preopenAt && Number.isNaN(preopenAt.getTime())) {
|
||||
throw new Error('Profile seed preopenAt must be an ISO date-time.');
|
||||
}
|
||||
const rawOpenAt = request.installOptions?.openAt;
|
||||
const openAt = typeof rawOpenAt === 'string' ? new Date(rawOpenAt) : null;
|
||||
if (openAt && Number.isNaN(openAt.getTime())) {
|
||||
throw new Error('Profile seed openAt must be an ISO date-time.');
|
||||
}
|
||||
const resourceRoot = path.join(process.cwd(), 'resources');
|
||||
|
||||
await seedProfileDatabase({
|
||||
@@ -61,6 +69,7 @@ export const runProfileSeedCli = async (env: NodeJS.ProcessEnv = process.env): P
|
||||
? {
|
||||
...request.installOptions,
|
||||
preopenAt,
|
||||
openAt,
|
||||
}
|
||||
: undefined,
|
||||
scenarioOptions: { scenarioRoot: path.join(resourceRoot, 'scenario') },
|
||||
|
||||
@@ -54,6 +54,8 @@ describeDatabase('selected workspace profile seed CLI', () => {
|
||||
firstGameIdx: 0,
|
||||
installOperationId: 'selected-cli-operation',
|
||||
installCommitSha: 'selected-cli-commit',
|
||||
preopenAt: '2036-03-03T01:00:00.000Z',
|
||||
openAt: '2036-03-03T02:00:00.000Z',
|
||||
},
|
||||
adminUser: {
|
||||
id: 'selected-cli-admin',
|
||||
@@ -69,6 +71,7 @@ describeDatabase('selected workspace profile seed CLI', () => {
|
||||
const world = await connector.prisma.worldState.findFirstOrThrow();
|
||||
expect(world).toMatchObject({
|
||||
scenarioCode: '1010',
|
||||
clockWallAnchor: new Date('2036-03-03T02:00:00.000Z'),
|
||||
meta: {
|
||||
firstGameIdx: 0,
|
||||
gameIdx: completedGameCount,
|
||||
|
||||
@@ -13,13 +13,18 @@ describe('parseProfileSeedRequest', () => {
|
||||
installOperationId: 'operation-id',
|
||||
installCommitSha: 'abcdef',
|
||||
preopenAt: null,
|
||||
openAt: '2030-01-01T02:00:00.000Z',
|
||||
},
|
||||
adminUser: { id: 'admin', username: 'admin' },
|
||||
})
|
||||
).toMatchObject({
|
||||
scenarioId: 1010,
|
||||
tickSeconds: 60,
|
||||
installOptions: { installOperationId: 'operation-id', installCommitSha: 'abcdef' },
|
||||
installOptions: {
|
||||
installOperationId: 'operation-id',
|
||||
installCommitSha: 'abcdef',
|
||||
openAt: '2030-01-01T02:00:00.000Z',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -36,7 +36,10 @@ available sort keys and placement. NPC·암행부·세력도시는 Ref의 고정
|
||||
`내림차순 → 오름차순 → 해제`를 순환하고, 여러 열의 방향과 우선순위를 scoped
|
||||
SFC indicator로 표시합니다. 장수 일람의 성격·특기·부상 설명은 많은 행에서
|
||||
eager popup instance를 만들지 않는 `DirectoryTooltip.vue` scoped CSS가 소유하며,
|
||||
mobile에서는 viewport 가장자리 8px 안의 고정 설명판으로 전환합니다.
|
||||
mobile에서는 viewport 가장자리 8px 안의 고정 설명판으로 전환합니다. 게임 내
|
||||
tooltip trigger는 hover/focus 동작과 `cursor: help`를 유지하되, tooltip이 있는 모든
|
||||
텍스트에 점선 밑줄을 반복하지 않습니다. keyboard `focus-visible` outline은 별도의
|
||||
접근성 상태로 유지합니다.
|
||||
|
||||
## Button composition
|
||||
|
||||
|
||||
Reference in New Issue
Block a user