merge: 최신 main을 메인 도시 정보 호환에 통합
This commit is contained in:
@@ -44,6 +44,7 @@ export type WorldStateConfig = z.infer<typeof zWorldStateConfig>;
|
|||||||
|
|
||||||
export const zWorldStateMeta = z.object({
|
export const zWorldStateMeta = z.object({
|
||||||
serverId: z.string().optional(),
|
serverId: z.string().optional(),
|
||||||
|
gameIdx: z.number().int().positive().optional(),
|
||||||
starttime: z.string().optional(),
|
starttime: z.string().optional(),
|
||||||
opentime: z.string().optional(),
|
opentime: z.string().optional(),
|
||||||
preopenAt: z.string().optional(),
|
preopenAt: z.string().optional(),
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import {
|
|||||||
isWarTraitKey,
|
isWarTraitKey,
|
||||||
} from '@sammo-ts/logic';
|
} from '@sammo-ts/logic';
|
||||||
import type { InheritBuffType } from '@sammo-ts/logic';
|
import type { InheritBuffType } from '@sammo-ts/logic';
|
||||||
|
import type { ItemSlot } 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 { resolveLegacyCompatibleUniqueConfig } from '@sammo-ts/logic/rewards/legacyUniqueItemPool.js';
|
||||||
import {
|
import {
|
||||||
@@ -39,6 +40,8 @@ const BUFF_KEYS: InheritBuffType[] = [
|
|||||||
'warMagicTrialProbOppose',
|
'warMagicTrialProbOppose',
|
||||||
];
|
];
|
||||||
|
|
||||||
|
const UNIQUE_ITEM_SLOT_ORDER: readonly ItemSlot[] = ['horse', 'weapon', 'book', 'item'];
|
||||||
|
|
||||||
const BUFF_LABELS: Record<InheritBuffType, string> = {
|
const BUFF_LABELS: Record<InheritBuffType, string> = {
|
||||||
warAvoidRatio: '회피 확률 증가',
|
warAvoidRatio: '회피 확률 증가',
|
||||||
warCriticalRatio: '필살 확률 증가',
|
warCriticalRatio: '필살 확률 증가',
|
||||||
@@ -79,7 +82,8 @@ const loadAvailableUniqueItems = async (worldState: WorldStateRow) => {
|
|||||||
const loader = new ItemLoader();
|
const loader = new ItemLoader();
|
||||||
const { allItems } = await resolveLegacyCompatibleUniqueConfig(configConst, loader);
|
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(allItems)) {
|
for (const slot of UNIQUE_ITEM_SLOT_ORDER) {
|
||||||
|
const entries = allItems[slot] ?? {};
|
||||||
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);
|
||||||
@@ -94,10 +98,11 @@ const loadAvailableUniqueItems = async (worldState: WorldStateRow) => {
|
|||||||
name: item.name,
|
name: item.name,
|
||||||
rawName: item.rawName,
|
rawName: item.rawName,
|
||||||
info: item.info ?? '',
|
info: item.info ?? '',
|
||||||
|
slot: item.slot,
|
||||||
};
|
};
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
return items.sort((left, right) => left.name.localeCompare(right.name, 'ko'));
|
return items;
|
||||||
};
|
};
|
||||||
|
|
||||||
const resolveWorld = async (ctx: { db: { worldState: { findFirst: () => Promise<unknown> } } }) => {
|
const resolveWorld = async (ctx: { db: { worldState: { findFirst: () => Promise<unknown> } } }) => {
|
||||||
|
|||||||
@@ -53,6 +53,8 @@ export const lobbyRouter = router({
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
serverId: worldState.meta.serverId?.trim() || ctx.profile?.name || 'game',
|
serverId: worldState.meta.serverId?.trim() || ctx.profile?.name || 'game',
|
||||||
|
profile: ctx.profile.id,
|
||||||
|
gameIdx: worldState.meta.gameIdx ?? 1,
|
||||||
year: worldState.currentYear,
|
year: worldState.currentYear,
|
||||||
month: worldState.currentMonth,
|
month: worldState.currentMonth,
|
||||||
userCnt,
|
userCnt,
|
||||||
|
|||||||
@@ -218,6 +218,32 @@ describe('inherit router actor and permission boundaries', () => {
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
|
it('orders unique auction candidates by Ref slot order and preserves order within each slot', async () => {
|
||||||
|
const fixture = buildContext({
|
||||||
|
configConst: {
|
||||||
|
allItems: {
|
||||||
|
item: { che_보물_도기: 1 },
|
||||||
|
book: { che_서적_07_논어: 1 },
|
||||||
|
weapon: { che_무기_12_칠성검: 1 },
|
||||||
|
horse: {
|
||||||
|
che_명마_07_백마: 1,
|
||||||
|
che_명마_07_기주마: 1,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const status = await appRouter.createCaller(fixture.context).inherit.getStatus();
|
||||||
|
|
||||||
|
expect(status.availableUnique.map(({ key, slot }) => ({ key, slot }))).toEqual([
|
||||||
|
{ key: 'che_명마_07_백마', slot: 'horse' },
|
||||||
|
{ key: 'che_명마_07_기주마', slot: 'horse' },
|
||||||
|
{ key: 'che_무기_12_칠성검', slot: 'weapon' },
|
||||||
|
{ key: 'che_서적_07_논어', slot: 'book' },
|
||||||
|
{ key: 'che_보물_도기', slot: 'item' },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
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({
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ const buildContext = (
|
|||||||
): GameApiContext =>
|
): GameApiContext =>
|
||||||
({
|
({
|
||||||
auth: null,
|
auth: null,
|
||||||
|
profile: { id: 'che', scenario: 'default', name: 'che:default' },
|
||||||
db: {
|
db: {
|
||||||
worldState: {
|
worldState: {
|
||||||
findFirst: vi.fn(async () => ({
|
findFirst: vi.fn(async () => ({
|
||||||
@@ -75,6 +76,7 @@ describe('lobby season state', () => {
|
|||||||
buildContext(
|
buildContext(
|
||||||
{
|
{
|
||||||
serverId: 'che_260819_season',
|
serverId: 'che_260819_season',
|
||||||
|
gameIdx: 101,
|
||||||
preopenAt: '2026-08-19 22:00:00',
|
preopenAt: '2026-08-19 22:00:00',
|
||||||
opentime: '2026-08-19 23:00:00',
|
opentime: '2026-08-19 23:00:00',
|
||||||
scenarioMeta: { title: '【가상모드27-b】 아시아 명장전(비급)' },
|
scenarioMeta: { title: '【가상모드27-b】 아시아 명장전(비급)' },
|
||||||
@@ -103,6 +105,8 @@ describe('lobby season state', () => {
|
|||||||
|
|
||||||
expect(result).toMatchObject({
|
expect(result).toMatchObject({
|
||||||
serverId: 'che_260819_season',
|
serverId: 'che_260819_season',
|
||||||
|
profile: 'che',
|
||||||
|
gameIdx: 101,
|
||||||
preopenAt: '2026-08-19 22:00:00',
|
preopenAt: '2026-08-19 22:00:00',
|
||||||
opentime: '2026-08-19 23:00:00',
|
opentime: '2026-08-19 23:00:00',
|
||||||
scenarioTitle: '【가상모드27-b】 아시아 명장전(비급)',
|
scenarioTitle: '【가상모드27-b】 아시아 명장전(비급)',
|
||||||
|
|||||||
@@ -323,9 +323,6 @@ export const seedScenarioToDatabase = async (options: ScenarioSeedOptions): Prom
|
|||||||
options: install.autorunUser.options,
|
options: install.autorunUser.options,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
const archivedWorldMeta = { ...worldMeta };
|
|
||||||
delete archivedWorldMeta.hiddenSeed;
|
|
||||||
|
|
||||||
await connector.connect();
|
await connector.connect();
|
||||||
try {
|
try {
|
||||||
const result: ScenarioSeedResult = { seed, warnings, applied: true };
|
const result: ScenarioSeedResult = { seed, warnings, applied: true };
|
||||||
@@ -383,6 +380,20 @@ export const seedScenarioToDatabase = async (options: ScenarioSeedOptions): Prom
|
|||||||
await prisma.worldState.deleteMany();
|
await prisma.worldState.deleteMany();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const serverId = typeof worldMeta.serverId === 'string' ? worldMeta.serverId : undefined;
|
||||||
|
const completedGameCount = await prisma.gameHistory.count({
|
||||||
|
where: {
|
||||||
|
status: 'COMPLETED',
|
||||||
|
...(serverId ? { serverId: { not: serverId } } : {}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
// Ref fixes server_cnt once during ResetHelper initialization. Keep the
|
||||||
|
// frequently rendered game index in the same persisted read model and
|
||||||
|
// exclude abandoned or unfinished rows from the official sequence.
|
||||||
|
worldMeta.gameIdx = completedGameCount + 1;
|
||||||
|
const archivedWorldMeta = { ...worldMeta };
|
||||||
|
delete archivedWorldMeta.hiddenSeed;
|
||||||
|
|
||||||
await prisma.worldState.create({
|
await prisma.worldState.create({
|
||||||
data: {
|
data: {
|
||||||
scenarioCode: String(options.scenarioId),
|
scenarioCode: String(options.scenarioId),
|
||||||
|
|||||||
@@ -156,15 +156,15 @@ export const applyLegacyGeneralProgression = (
|
|||||||
meta.explevel = expLevel;
|
meta.explevel = expLevel;
|
||||||
if (expLevel !== previousExpLevel && actionResolvedExpLevel !== expLevel) {
|
if (expLevel !== previousExpLevel && actionResolvedExpLevel !== expLevel) {
|
||||||
const josaRo = JosaUtil.pick(String(expLevel), '로');
|
const josaRo = JosaUtil.pick(String(expLevel), '로');
|
||||||
logs.push({
|
logs.push(
|
||||||
scope: LogScope.GENERAL,
|
createGeneralActionLog(
|
||||||
category: LogCategory.ACTION,
|
general.id,
|
||||||
format: LogFormat.PLAIN,
|
|
||||||
text:
|
|
||||||
expLevel > previousExpLevel
|
expLevel > previousExpLevel
|
||||||
? `<C>Lv ${expLevel}</>${josaRo} <C>레벨업</>!`
|
? `<C>Lv ${expLevel}</>${josaRo} <C>레벨업</>!`
|
||||||
: `<C>Lv ${expLevel}</>${josaRo} <R>레벨다운</>!`,
|
: `<C>Lv ${expLevel}</>${josaRo} <R>레벨다운</>!`,
|
||||||
});
|
{ format: LogFormat.PLAIN }
|
||||||
|
)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!preserveLevel && (forceRefreshLevel || general.dedication !== previousGeneral.dedication)) {
|
if (!preserveLevel && (forceRefreshLevel || general.dedication !== previousGeneral.dedication)) {
|
||||||
@@ -176,15 +176,15 @@ export const applyLegacyGeneralProgression = (
|
|||||||
const billText = getBillByLevel(dedicationLevel).toLocaleString('en-US');
|
const billText = getBillByLevel(dedicationLevel).toLocaleString('en-US');
|
||||||
const josaRoDedication = JosaUtil.pick(dedicationLevelText, '로');
|
const josaRoDedication = JosaUtil.pick(dedicationLevelText, '로');
|
||||||
const josaRoBill = JosaUtil.pick(billText, '로');
|
const josaRoBill = JosaUtil.pick(billText, '로');
|
||||||
logs.push({
|
logs.push(
|
||||||
scope: LogScope.GENERAL,
|
createGeneralActionLog(
|
||||||
category: LogCategory.ACTION,
|
general.id,
|
||||||
format: LogFormat.PLAIN,
|
|
||||||
text:
|
|
||||||
dedicationLevel > previousDedicationLevel
|
dedicationLevel > previousDedicationLevel
|
||||||
? `<Y>${dedicationLevelText}</>${josaRoDedication} <C>승급</>하여 봉록이 <C>${billText}</>${josaRoBill} <C>상승</>했습니다!`
|
? `<Y>${dedicationLevelText}</>${josaRoDedication} <C>승급</>하여 봉록이 <C>${billText}</>${josaRoBill} <C>상승</>했습니다!`
|
||||||
: `<Y>${dedicationLevelText}</>${josaRoDedication} <R>강등</>되어 봉록이 <C>${billText}</>${josaRoBill} <R>하락</>했습니다!`,
|
: `<Y>${dedicationLevelText}</>${josaRoDedication} <R>강등</>되어 봉록이 <C>${billText}</>${josaRoBill} <R>하락</>했습니다!`,
|
||||||
});
|
{ format: LogFormat.PLAIN }
|
||||||
|
)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -715,12 +715,27 @@ const buildConstraintContext = (
|
|||||||
mode: 'full',
|
mode: 'full',
|
||||||
});
|
});
|
||||||
|
|
||||||
const createActionLog = (message: string, meta?: Record<string, unknown>): LogEntryDraft => ({
|
/**
|
||||||
|
* Ref ActionLogger is constructed with a general ID, so every personal action
|
||||||
|
* log carries its owner before it reaches persistence. Keep that ownership
|
||||||
|
* explicit here: finalizeLogEntry intentionally rejects ownerless GENERAL logs.
|
||||||
|
*/
|
||||||
|
interface GeneralActionLogOptions {
|
||||||
|
format?: LogFormat;
|
||||||
|
meta?: Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const createGeneralActionLog = (
|
||||||
|
generalId: number,
|
||||||
|
message: string,
|
||||||
|
options: GeneralActionLogOptions = {}
|
||||||
|
): LogEntryDraft => ({
|
||||||
scope: LogScope.GENERAL,
|
scope: LogScope.GENERAL,
|
||||||
category: LogCategory.ACTION,
|
category: LogCategory.ACTION,
|
||||||
format: LogFormat.MONTH,
|
generalId,
|
||||||
|
format: options.format ?? LogFormat.MONTH,
|
||||||
text: message,
|
text: message,
|
||||||
meta,
|
...(options.meta ? { meta: options.meta } : {}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const resolveDefinition = (
|
const resolveDefinition = (
|
||||||
@@ -936,7 +951,7 @@ export const createReservedTurnHandler = async (options: {
|
|||||||
actionKey = definition.key;
|
actionKey = definition.key;
|
||||||
usedFallback = true;
|
usedFallback = true;
|
||||||
blockedReason = failureText;
|
blockedReason = failureText;
|
||||||
logs.push(createActionLog(failureText));
|
logs.push(createGeneralActionLog(currentGeneral.id, failureText));
|
||||||
}
|
}
|
||||||
|
|
||||||
const actionConstraintEnv = {
|
const actionConstraintEnv = {
|
||||||
@@ -972,7 +987,7 @@ export const createReservedTurnHandler = async (options: {
|
|||||||
const failureText =
|
const failureText =
|
||||||
failedDefinition.formatConstraintFailure?.(reason, constraintCtx, failedActionArgs, view) ??
|
failedDefinition.formatConstraintFailure?.(reason, constraintCtx, failedActionArgs, view) ??
|
||||||
`${reason} ${failedDefinition.name} 실패.`;
|
`${reason} ${failedDefinition.name} 실패.`;
|
||||||
logs.push(createActionLog(failureText, meta));
|
logs.push(createGeneralActionLog(currentGeneral.id, failureText, meta ? { meta } : {}));
|
||||||
}
|
}
|
||||||
if (!usedFallback && (kind === 'general' || currentNation)) {
|
if (!usedFallback && (kind === 'general' || currentNation)) {
|
||||||
const currentYearMonth = joinYearMonth(context.world.currentYear, context.world.currentMonth);
|
const currentYearMonth = joinYearMonth(context.world.currentYear, context.world.currentMonth);
|
||||||
@@ -987,7 +1002,7 @@ export const createReservedTurnHandler = async (options: {
|
|||||||
actionKey = definition.key;
|
actionKey = definition.key;
|
||||||
usedFallback = true;
|
usedFallback = true;
|
||||||
blockedReason = `${remainTurn}턴 더 기다려야 합니다`;
|
blockedReason = `${remainTurn}턴 더 기다려야 합니다`;
|
||||||
logs.push(createActionLog(blockedReason));
|
logs.push(createGeneralActionLog(currentGeneral.id, blockedReason));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1068,7 +1083,7 @@ export const createReservedTurnHandler = async (options: {
|
|||||||
actionKey = definition.key;
|
actionKey = definition.key;
|
||||||
usedFallback = true;
|
usedFallback = true;
|
||||||
blockedReason = '예약된 명령을 실행하지 못했습니다.';
|
blockedReason = '예약된 명령을 실행하지 못했습니다.';
|
||||||
logs.push(createActionLog('예약된 명령을 실행하지 못했습니다.'));
|
logs.push(createGeneralActionLog(currentGeneral.id, '예약된 명령을 실행하지 못했습니다.'));
|
||||||
actionRng = sharedActionRng ?? buildRng(actionKey);
|
actionRng = sharedActionRng ?? buildRng(actionKey);
|
||||||
baseContext = {
|
baseContext = {
|
||||||
general: currentGeneral,
|
general: currentGeneral,
|
||||||
@@ -1151,7 +1166,7 @@ export const createReservedTurnHandler = async (options: {
|
|||||||
const progressText =
|
const progressText =
|
||||||
executionDefinition.getProgressText?.(actionContext, actionArgs, nextTerm, termMax) ??
|
executionDefinition.getProgressText?.(actionContext, actionArgs, nextTerm, termMax) ??
|
||||||
`${definition.name} 수행중... (${nextTerm}/${termMax})`;
|
`${definition.name} 수행중... (${nextTerm}/${termMax})`;
|
||||||
logs.push(createActionLog(progressText));
|
logs.push(createGeneralActionLog(currentGeneral.id, progressText));
|
||||||
return { actionKey, usedFallback, completed: false, blockedReason };
|
return { actionKey, usedFallback, completed: false, blockedReason };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1576,7 +1591,7 @@ export const createReservedTurnHandler = async (options: {
|
|||||||
},
|
},
|
||||||
rng: preprocessRng,
|
rng: preprocessRng,
|
||||||
log: {
|
log: {
|
||||||
push: (message) => logs.push(createActionLog(message)),
|
push: (message) => logs.push(createGeneralActionLog(currentGeneral.id, message)),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
preTurnPipeline.getPreTurnExecuteTriggerList(preTurnContext).fire(preTurnContext, baseConstraintEnv);
|
preTurnPipeline.getPreTurnExecuteTriggerList(preTurnContext).fire(preTurnContext, baseConstraintEnv);
|
||||||
@@ -1602,7 +1617,12 @@ export const createReservedTurnHandler = async (options: {
|
|||||||
}
|
}
|
||||||
currentGeneral.crew = 0;
|
currentGeneral.crew = 0;
|
||||||
currentGeneral.rice = 0;
|
currentGeneral.rice = 0;
|
||||||
logs.push(createActionLog('군량이 모자라 병사들이 <R>소집해제</>되었습니다!'));
|
logs.push(
|
||||||
|
createGeneralActionLog(
|
||||||
|
currentGeneral.id,
|
||||||
|
'군량이 모자라 병사들이 <R>소집해제</>되었습니다!'
|
||||||
|
)
|
||||||
|
);
|
||||||
preTurnContext.skill.activate('pre.소집해제');
|
preTurnContext.skill.activate('pre.소집해제');
|
||||||
}
|
}
|
||||||
preTurnContext.skill.activate('pre.병력군량소모');
|
preTurnContext.skill.activate('pre.병력군량소모');
|
||||||
@@ -1625,7 +1645,8 @@ export const createReservedTurnHandler = async (options: {
|
|||||||
if (isBlocked) {
|
if (isBlocked) {
|
||||||
currentGeneral.meta.killturn = Math.max(0, currentGeneral.meta.killturn - 1);
|
currentGeneral.meta.killturn = Math.max(0, currentGeneral.meta.killturn - 1);
|
||||||
logs.push(
|
logs.push(
|
||||||
createActionLog(
|
createGeneralActionLog(
|
||||||
|
currentGeneral.id,
|
||||||
blockCode === 2
|
blockCode === 2
|
||||||
? '현재 멀티, 또는 비매너로 인한<R>블럭</> 대상자입니다.'
|
? '현재 멀티, 또는 비매너로 인한<R>블럭</> 대상자입니다.'
|
||||||
: '현재 악성유저로 분류되어 <R>블럭</> 대상자입니다.'
|
: '현재 악성유저로 분류되어 <R>블럭</> 대상자입니다.'
|
||||||
@@ -1981,7 +2002,8 @@ export const createReservedTurnHandler = async (options: {
|
|||||||
? currentGeneral.meta.owner_name
|
? currentGeneral.meta.owner_name
|
||||||
: currentGeneral.userId;
|
: currentGeneral.userId;
|
||||||
logs.push(
|
logs.push(
|
||||||
createActionLog(
|
createGeneralActionLog(
|
||||||
|
currentGeneral.id,
|
||||||
`${ownerName ?? '사용자'}이 <Y>${currentGeneral.name}</>의 육체에서 <S>유체이탈</>합니다!`
|
`${ownerName ?? '사용자'}이 <Y>${currentGeneral.name}</>의 육체에서 <S>유체이탈</>합니다!`
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
@@ -2060,7 +2082,8 @@ export const createReservedTurnHandler = async (options: {
|
|||||||
chiefGeneralId: successor.id,
|
chiefGeneralId: successor.id,
|
||||||
};
|
};
|
||||||
logs.push(
|
logs.push(
|
||||||
createActionLog(
|
createGeneralActionLog(
|
||||||
|
currentGeneral.id,
|
||||||
`<Y>${successor.name}</>이 <D><b>${currentNation.name}</b></>의 유지를 이어 받았습니다`
|
`<Y>${successor.name}</>이 <D><b>${currentNation.name}</b></>의 유지를 이어 받았습니다`
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
@@ -2093,7 +2116,12 @@ export const createReservedTurnHandler = async (options: {
|
|||||||
if (!deleteGeneral && currentGeneral.age >= retirementYear && currentGeneral.npcState === 0) {
|
if (!deleteGeneral && currentGeneral.age >= retirementYear && currentGeneral.npcState === 0) {
|
||||||
currentGeneral = resetRetiredGeneral(currentGeneral);
|
currentGeneral = resetRetiredGeneral(currentGeneral);
|
||||||
lifecycleOutcome = 'retired';
|
lifecycleOutcome = 'retired';
|
||||||
logs.push(createActionLog('나이가 들어 <R>은퇴</>하고 자손에게 자리를 물려줍니다.'));
|
logs.push(
|
||||||
|
createGeneralActionLog(
|
||||||
|
currentGeneral.id,
|
||||||
|
'나이가 들어 <R>은퇴</>하고 자손에게 자리를 물려줍니다.'
|
||||||
|
)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
currentGeneral = {
|
currentGeneral = {
|
||||||
@@ -2245,13 +2273,7 @@ export const createImmediateGeneralActionExecutor = async (options: {
|
|||||||
definition.formatConstraintFailure?.(reason, constraintCtx, args, view) ??
|
definition.formatConstraintFailure?.(reason, constraintCtx, args, view) ??
|
||||||
`${reason} ${definition.name} 실패.`;
|
`${reason} ${definition.name} 실패.`;
|
||||||
if (input.actionKey === 'che_접경귀환' || input.actionKey === 'che_등용수락') {
|
if (input.actionKey === 'che_접경귀환' || input.actionKey === 'che_등용수락') {
|
||||||
options.world.pushLog(
|
options.world.pushLog(createGeneralActionLog(general.id, failureText), general.turnTime);
|
||||||
{
|
|
||||||
...createActionLog(failureText),
|
|
||||||
generalId: general.id,
|
|
||||||
},
|
|
||||||
general.turnTime
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
return { ok: false, reason: failureText };
|
return { ok: false, reason: failureText };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { describe, expect, it, vi } from 'vitest';
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
import type { TurnSchedule } from '@sammo-ts/logic';
|
import { finalizeLogEntry, type TurnSchedule } from '@sammo-ts/logic';
|
||||||
import type { TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js';
|
import type { TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js';
|
||||||
import { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js';
|
import { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js';
|
||||||
import { InMemoryReservedTurnStore } from '../src/turn/reservedTurnStore.js';
|
import { InMemoryReservedTurnStore } from '../src/turn/reservedTurnStore.js';
|
||||||
@@ -41,8 +41,9 @@ const mockDate = new Date('0189-01-01T00:00:00Z');
|
|||||||
|
|
||||||
// We need a mock Prisma client that satisfies the shape required by InMemoryReservedTurnStore
|
// We need a mock Prisma client that satisfies the shape required by InMemoryReservedTurnStore
|
||||||
// It expects { generalTurn: { findMany, deleteMany, createMany }, nationTurn: { ... } }
|
// It expects { generalTurn: { findMany, deleteMany, createMany }, nationTurn: { ... } }
|
||||||
const createMockPrisma = (initialGeneralRows: any[] = []) => {
|
const createMockPrisma = (initialGeneralRows: any[] = [], initialNationRows: any[] = []) => {
|
||||||
let generalRows = [...initialGeneralRows];
|
let generalRows = [...initialGeneralRows];
|
||||||
|
let nationRows = [...initialNationRows];
|
||||||
return {
|
return {
|
||||||
generalTurn: {
|
generalTurn: {
|
||||||
findMany: vi.fn(async ({ where } = {}) => {
|
findMany: vi.fn(async ({ where } = {}) => {
|
||||||
@@ -67,9 +68,28 @@ const createMockPrisma = (initialGeneralRows: any[] = []) => {
|
|||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
nationTurn: {
|
nationTurn: {
|
||||||
findMany: vi.fn(async () => []),
|
findMany: vi.fn(async ({ where } = {}) => {
|
||||||
deleteMany: vi.fn(async () => ({ count: 0 })),
|
if (where?.nationId && where?.officerLevel) {
|
||||||
createMany: vi.fn(async () => ({ count: 0 })),
|
return nationRows
|
||||||
|
.filter((row) => row.nationId === where.nationId && row.officerLevel === where.officerLevel)
|
||||||
|
.sort((left, right) => left.turnIdx - right.turnIdx);
|
||||||
|
}
|
||||||
|
return nationRows;
|
||||||
|
}),
|
||||||
|
deleteMany: vi.fn(async ({ where } = {}) => {
|
||||||
|
if (where?.nationId && where?.officerLevel) {
|
||||||
|
nationRows = nationRows.filter(
|
||||||
|
(row) => row.nationId !== where.nationId || row.officerLevel !== where.officerLevel
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return { count: 0 };
|
||||||
|
}),
|
||||||
|
createMany: vi.fn(async ({ data }) => {
|
||||||
|
if (Array.isArray(data)) {
|
||||||
|
nationRows.push(...data);
|
||||||
|
}
|
||||||
|
return { count: data.length };
|
||||||
|
}),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
@@ -423,8 +443,17 @@ describe('Reserved Turn Execution Integration', () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const invalidRows = [{ generalId: 1, turnIdx: 0, actionCode: 'che_이동', arg: { destCityId: 'bad' } }];
|
const invalidRows = [{ generalId: 1, turnIdx: 0, actionCode: 'che_이동', arg: { destCityId: 'bad' } }];
|
||||||
|
const invalidNationRows = [
|
||||||
|
{
|
||||||
|
nationId: 1,
|
||||||
|
officerLevel: 5,
|
||||||
|
turnIdx: 0,
|
||||||
|
actionCode: 'che_천도',
|
||||||
|
arg: { destCityId: 'bad' },
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
const mockPrisma = createMockPrisma(invalidRows);
|
const mockPrisma = createMockPrisma(invalidRows, invalidNationRows);
|
||||||
const reservedTurnStore = new InMemoryReservedTurnStore(mockPrisma as any, {
|
const reservedTurnStore = new InMemoryReservedTurnStore(mockPrisma as any, {
|
||||||
maxGeneralTurns: 10,
|
maxGeneralTurns: 10,
|
||||||
maxNationTurns: 10,
|
maxNationTurns: 10,
|
||||||
@@ -456,7 +485,26 @@ describe('Reserved Turn Execution Integration', () => {
|
|||||||
|
|
||||||
const dirty = world.consumeDirtyState();
|
const dirty = world.consumeDirtyState();
|
||||||
expect(world.getGeneralById(1)!.cityId).toBe(1);
|
expect(world.getGeneralById(1)!.cityId).toBe(1);
|
||||||
expect(dirty.logs.some((log) => log.text.includes('인자가 올바르지 않습니다. 이동 실패.'))).toBe(true);
|
expect(dirty.logs.find((log) => log.text.includes('인자가 올바르지 않습니다. 천도 실패.'))).toMatchObject({
|
||||||
|
scope: 'GENERAL',
|
||||||
|
category: 'ACTION',
|
||||||
|
generalId: 1,
|
||||||
|
});
|
||||||
|
expect(dirty.logs.find((log) => log.text.includes('인자가 올바르지 않습니다. 이동 실패.'))).toMatchObject({
|
||||||
|
scope: 'GENERAL',
|
||||||
|
category: 'ACTION',
|
||||||
|
generalId: 1,
|
||||||
|
});
|
||||||
|
const personalActionLogs = dirty.logs.filter(
|
||||||
|
(log) => log.scope === 'GENERAL' && log.category === 'ACTION'
|
||||||
|
);
|
||||||
|
expect(personalActionLogs.length).toBeGreaterThan(0);
|
||||||
|
expect(personalActionLogs.every((log) => log.generalId === 1)).toBe(true);
|
||||||
|
expect(
|
||||||
|
personalActionLogs.map((log) =>
|
||||||
|
finalizeLogEntry(log, { year: invalidState.currentYear, month: invalidState.currentMonth })
|
||||||
|
)
|
||||||
|
).not.toContain(null);
|
||||||
expect(dirty.logs.some((log) => log.text.includes('아무것도 실행하지 않았습니다.'))).toBe(true);
|
expect(dirty.logs.some((log) => log.text.includes('아무것도 실행하지 않았습니다.'))).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -620,6 +668,7 @@ describe('Reserved Turn Execution Integration', () => {
|
|||||||
const denyLog = dirty.logs.find((log) => log.text.includes('같은 도시입니다.'));
|
const denyLog = dirty.logs.find((log) => log.text.includes('같은 도시입니다.'));
|
||||||
expect(denyLog?.text).toContain('이동 실패.');
|
expect(denyLog?.text).toContain('이동 실패.');
|
||||||
expect(denyLog?.meta?.constraintName).toBe('notSameDestCity');
|
expect(denyLog?.meta?.constraintName).toBe('notSameDestCity');
|
||||||
|
expect(denyLog?.generalId).toBe(1);
|
||||||
expect(dirty.logs.some((log) => log.text.includes('아무것도 실행하지 않았습니다.'))).toBe(true);
|
expect(dirty.logs.some((log) => log.text.includes('아무것도 실행하지 않았습니다.'))).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -128,6 +128,58 @@ describeDb('scenario database seed', () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('persists the next official game index without counting cancelled or unfinished games', async () => {
|
||||||
|
const marker = `scenario-seeder-game-index-${Date.now()}`;
|
||||||
|
const connector = createGamePostgresConnector({ url: databaseUrl });
|
||||||
|
await connector.connect();
|
||||||
|
try {
|
||||||
|
const completedBefore = await connector.prisma.gameHistory.count({ where: { status: 'COMPLETED' } });
|
||||||
|
await connector.prisma.gameHistory.createMany({
|
||||||
|
data: [
|
||||||
|
{
|
||||||
|
serverId: `${marker}-completed`,
|
||||||
|
date: new Date('2026-08-01T00:00:00.000Z'),
|
||||||
|
season: 1,
|
||||||
|
scenario: 1010,
|
||||||
|
scenarioName: '정상 종료 fixture',
|
||||||
|
status: 'COMPLETED',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
serverId: `${marker}-abandoned`,
|
||||||
|
date: new Date('2026-08-02T00:00:00.000Z'),
|
||||||
|
season: 1,
|
||||||
|
scenario: 1010,
|
||||||
|
scenarioName: '취소 fixture',
|
||||||
|
status: 'ABANDONED',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
serverId: `${marker}-open`,
|
||||||
|
date: new Date('2026-08-03T00:00:00.000Z'),
|
||||||
|
season: 1,
|
||||||
|
scenario: 1010,
|
||||||
|
scenarioName: '미완료 fixture',
|
||||||
|
status: 'OPEN',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
await seedScenarioToDatabase({
|
||||||
|
scenarioId: 1010,
|
||||||
|
databaseUrl,
|
||||||
|
installOptions: { serverId: marker },
|
||||||
|
});
|
||||||
|
|
||||||
|
const worldState = await connector.prisma.worldState.findFirstOrThrow();
|
||||||
|
expect(worldState.meta).toMatchObject({ gameIdx: completedBefore + 2 });
|
||||||
|
await expect(
|
||||||
|
connector.prisma.gameHistory.findUniqueOrThrow({ where: { serverId: marker } })
|
||||||
|
).resolves.toMatchObject({ status: 'OPEN' });
|
||||||
|
} finally {
|
||||||
|
await connector.prisma.gameHistory.deleteMany({ where: { serverId: { startsWith: marker } } });
|
||||||
|
await connector.disconnect();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
test('writes scenario data into tables', async () => {
|
test('writes scenario data into tables', async () => {
|
||||||
const { seed } = await seedScenarioToDatabase({
|
const { seed } = await seedScenarioToDatabase({
|
||||||
scenarioId,
|
scenarioId,
|
||||||
|
|||||||
@@ -0,0 +1,137 @@
|
|||||||
|
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||||
|
import { createGamePostgresConnector, type GamePrismaClient, type InputJsonValue } from '@sammo-ts/infra';
|
||||||
|
import { LogCategory, LogFormat, LogScope, type TurnSchedule } from '@sammo-ts/logic';
|
||||||
|
|
||||||
|
import { createDatabaseTurnHooks, type DatabaseTurnHooks } from '../src/turn/databaseHooks.js';
|
||||||
|
import { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js';
|
||||||
|
import type { TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js';
|
||||||
|
|
||||||
|
const databaseUrl = process.env.INPUT_EVENT_DATABASE_URL;
|
||||||
|
const integration = describe.skipIf(!databaseUrl);
|
||||||
|
const worldId = 2_146_200_820;
|
||||||
|
const generalId = 2_146_200_821;
|
||||||
|
const turnTime = new Date('0190-01-01T00:00:00.000Z');
|
||||||
|
const turnRunResult = {
|
||||||
|
lastTurnTime: turnTime.toISOString(),
|
||||||
|
processedGenerals: 1,
|
||||||
|
processedTurns: 1,
|
||||||
|
durationMs: 0,
|
||||||
|
partial: false,
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const schedule: TurnSchedule = {
|
||||||
|
entries: [{ startMinute: 0, tickMinutes: 10 }],
|
||||||
|
};
|
||||||
|
|
||||||
|
const state: TurnWorldState = {
|
||||||
|
id: worldId,
|
||||||
|
currentYear: 190,
|
||||||
|
currentMonth: 1,
|
||||||
|
tickSeconds: 600,
|
||||||
|
lastTurnTime: turnTime,
|
||||||
|
meta: {},
|
||||||
|
};
|
||||||
|
|
||||||
|
const snapshot: TurnWorldSnapshot = {
|
||||||
|
generals: [],
|
||||||
|
cities: [],
|
||||||
|
nations: [],
|
||||||
|
troops: [],
|
||||||
|
diplomacy: [],
|
||||||
|
events: [],
|
||||||
|
initialEvents: [],
|
||||||
|
map: {
|
||||||
|
id: 'turn-failure-log-persistence',
|
||||||
|
name: '턴 실패 로그 영속화',
|
||||||
|
cities: [],
|
||||||
|
defaults: { trust: 50, trade: 100, supplyState: 1, frontState: 0 },
|
||||||
|
},
|
||||||
|
scenarioConfig: {
|
||||||
|
stat: { total: 300, min: 10, max: 100, npcTotal: 150, npcMax: 50, npcMin: 10, chiefMin: 70 },
|
||||||
|
iconPath: '',
|
||||||
|
map: {},
|
||||||
|
const: {},
|
||||||
|
environment: { mapName: 'che', unitSet: 'che' },
|
||||||
|
},
|
||||||
|
scenarioMeta: {
|
||||||
|
title: '턴 실패 로그 영속화',
|
||||||
|
startYear: 190,
|
||||||
|
life: null,
|
||||||
|
fiction: null,
|
||||||
|
history: [],
|
||||||
|
ignoreDefaultEvents: false,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
integration('turn failure personal-record persistence', () => {
|
||||||
|
let db: GamePrismaClient;
|
||||||
|
let disconnect: (() => Promise<void>) | undefined;
|
||||||
|
let databaseHooks: DatabaseTurnHooks | undefined;
|
||||||
|
|
||||||
|
const cleanup = async () => {
|
||||||
|
await db.logEntry.deleteMany({ where: { generalId } });
|
||||||
|
await db.worldState.deleteMany({ where: { id: worldId } });
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
const connector = createGamePostgresConnector({ url: databaseUrl! });
|
||||||
|
await connector.connect();
|
||||||
|
db = connector.prisma;
|
||||||
|
disconnect = () => connector.disconnect();
|
||||||
|
await cleanup();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await databaseHooks?.close();
|
||||||
|
await cleanup();
|
||||||
|
await disconnect?.();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stores personal and nation-turn failure reasons under the acting general', async () => {
|
||||||
|
await db.worldState.create({
|
||||||
|
data: {
|
||||||
|
id: worldId,
|
||||||
|
scenarioCode: 'turn-failure-log-persistence',
|
||||||
|
currentYear: state.currentYear,
|
||||||
|
currentMonth: state.currentMonth,
|
||||||
|
tickSeconds: state.tickSeconds,
|
||||||
|
config: snapshot.scenarioConfig as unknown as InputJsonValue,
|
||||||
|
meta: {},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const world = new InMemoryTurnWorld(state, snapshot, { schedule });
|
||||||
|
world.pushLog({
|
||||||
|
scope: LogScope.GENERAL,
|
||||||
|
category: LogCategory.ACTION,
|
||||||
|
generalId,
|
||||||
|
format: LogFormat.MONTH,
|
||||||
|
text: '대상 도시가 아국이 아닙니다. 발령 실패.',
|
||||||
|
});
|
||||||
|
world.pushLog({
|
||||||
|
scope: LogScope.GENERAL,
|
||||||
|
category: LogCategory.ACTION,
|
||||||
|
generalId,
|
||||||
|
format: LogFormat.MONTH,
|
||||||
|
text: '같은 도시입니다. 이동 실패.',
|
||||||
|
});
|
||||||
|
|
||||||
|
databaseHooks = await createDatabaseTurnHooks(databaseUrl!, world);
|
||||||
|
await databaseHooks.hooks.flushChanges?.(turnRunResult);
|
||||||
|
|
||||||
|
const records = await db.logEntry.findMany({
|
||||||
|
where: {
|
||||||
|
scope: LogScope.GENERAL,
|
||||||
|
category: LogCategory.ACTION,
|
||||||
|
generalId,
|
||||||
|
},
|
||||||
|
orderBy: { id: 'asc' },
|
||||||
|
select: { generalId: true, text: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(records).toEqual([
|
||||||
|
{ generalId, text: '<C>●</>1월:대상 도시가 아국이 아닙니다. 발령 실패.' },
|
||||||
|
{ generalId, text: '<C>●</>1월:같은 도시입니다. 이동 실패.' },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -898,6 +898,62 @@ test('메인 장수 동향과 개인 전투 기록은 Ref 행 간격·색상·
|
|||||||
await persistParityArtifact(page, 'core-main-personal-battle-log-inline-mobile', mobileGeometry);
|
await persistParityArtifact(page, 'core-main-personal-battle-log-inline-mobile', mobileGeometry);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('개인턴·수뇌턴 실패 사유를 메인 개인 기록에 표시한다', async ({ page }) => {
|
||||||
|
const state: FixtureState = {
|
||||||
|
permission: 'head',
|
||||||
|
myset: 3,
|
||||||
|
settingMutations: [],
|
||||||
|
accessPages: [],
|
||||||
|
recentRecords: {
|
||||||
|
global: [],
|
||||||
|
general: [
|
||||||
|
{
|
||||||
|
id: 19002,
|
||||||
|
text: '<C>●</>1월:대상 도시가 아국이 아닙니다. <Y>여포</> 발령 실패.',
|
||||||
|
createdAt: '2026-01-01T03:55:00.000Z',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 19001,
|
||||||
|
text: '<C>●</>1월:같은 도시입니다. <G><b>업</b></>으로 이동 실패.',
|
||||||
|
createdAt: '2026-01-01T03:54:00.000Z',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
history: [],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
await install(page, state);
|
||||||
|
await page.setViewportSize({ width: 1200, height: 900 });
|
||||||
|
await page.goto('');
|
||||||
|
|
||||||
|
const inspectFailureLogs = async (selector: string) => {
|
||||||
|
const lines = page.locator(selector);
|
||||||
|
await expect(lines).toHaveCount(2);
|
||||||
|
await expect(lines.nth(0)).toContainText('대상 도시가 아국이 아닙니다. 여포 발령 실패. 12:55');
|
||||||
|
await expect(lines.nth(1)).toContainText('같은 도시입니다. 업으로 이동 실패. 12:54');
|
||||||
|
return lines.evaluateAll((elements) =>
|
||||||
|
elements.map((element) => {
|
||||||
|
const rect = element.getBoundingClientRect();
|
||||||
|
const style = getComputedStyle(element);
|
||||||
|
return {
|
||||||
|
text: element.textContent?.trim(),
|
||||||
|
width: rect.width,
|
||||||
|
height: rect.height,
|
||||||
|
lineHeight: style.lineHeight,
|
||||||
|
};
|
||||||
|
})
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const desktop = await inspectFailureLogs('.record-zone [data-record-bucket="general"] .record-line');
|
||||||
|
expect(desktop.every((line) => line.width > 0 && line.height === 21 && line.lineHeight === '21px')).toBe(true);
|
||||||
|
await persistParityArtifact(page, 'core-main-turn-failure-personal-records-desktop', desktop);
|
||||||
|
|
||||||
|
await page.setViewportSize({ width: 500, height: 900 });
|
||||||
|
const mobile = await inspectFailureLogs('.record-zone-mobile [data-record-bucket="general"] .record-line');
|
||||||
|
expect(mobile.every((line) => line.width > 0 && line.height === 21 && line.lineHeight === '21px')).toBe(true);
|
||||||
|
await persistParityArtifact(page, 'core-main-turn-failure-personal-records-mobile', mobile);
|
||||||
|
});
|
||||||
|
|
||||||
test('전투시드는 메인·내 정보·감찰부에서 숨긴 채 선택할 수 있다', async ({ page }) => {
|
test('전투시드는 메인·내 정보·감찰부에서 숨긴 채 선택할 수 있다', async ({ page }) => {
|
||||||
const seedText = '(전투시드: 0123456789abcdef)';
|
const seedText = '(전투시드: 0123456789abcdef)';
|
||||||
const logText =
|
const logText =
|
||||||
|
|||||||
@@ -52,6 +52,8 @@ type NavigationFixture = {
|
|||||||
currentYear?: number;
|
currentYear?: number;
|
||||||
currentMonth?: number;
|
currentMonth?: number;
|
||||||
serverId?: string;
|
serverId?: string;
|
||||||
|
profile?: string;
|
||||||
|
gameIdx?: number;
|
||||||
scenarioTitle?: string;
|
scenarioTitle?: string;
|
||||||
nationColor?: string;
|
nationColor?: string;
|
||||||
lastExecuted?: string | null;
|
lastExecuted?: string | null;
|
||||||
@@ -538,6 +540,8 @@ const installFixture = async (page: Page, state: NavigationFixture) => {
|
|||||||
return response({
|
return response({
|
||||||
myGeneral: { id: 7, name: '메뉴검증장수' },
|
myGeneral: { id: 7, name: '메뉴검증장수' },
|
||||||
serverId: state.serverId ?? 'che_fixture_season',
|
serverId: state.serverId ?? 'che_fixture_season',
|
||||||
|
profile: state.profile ?? 'che',
|
||||||
|
gameIdx: state.gameIdx ?? 101,
|
||||||
year: state.currentYear ?? 185,
|
year: state.currentYear ?? 185,
|
||||||
month: state.currentMonth ?? 1,
|
month: state.currentMonth ?? 1,
|
||||||
turnTerm: 10,
|
turnTerm: 10,
|
||||||
@@ -1121,7 +1125,9 @@ test('desktop menus preserve ref columns, prefix-safe routes, and controlled dro
|
|||||||
await expect(page.locator('.main-mobile-bottom')).toBeHidden();
|
await expect(page.locator('.main-mobile-bottom')).toBeHidden();
|
||||||
await expect(page.locator('.layout-desktop')).toBeVisible();
|
await expect(page.locator('.layout-desktop')).toBeVisible();
|
||||||
await expect(page.locator('.layout-mobile')).toHaveCount(0);
|
await expect(page.locator('.layout-mobile')).toHaveCount(0);
|
||||||
await expect(page.getByRole('heading', { name: '메인 화면 검증 시나리오', exact: true })).toHaveCount(1);
|
await expect(page.getByRole('heading', { name: '메인 화면 검증 시나리오 체섭 101기', exact: true })).toHaveCount(
|
||||||
|
1
|
||||||
|
);
|
||||||
await expect(page.locator('.game-shell__subtitle')).toHaveCount(0);
|
await expect(page.locator('.game-shell__subtitle')).toHaveCount(0);
|
||||||
await expect(page.locator('.legacy-game-info')).toContainText('현재: 185년 1월');
|
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')).toContainText('턴: 10분');
|
||||||
@@ -1273,6 +1279,56 @@ test('desktop menus preserve ref columns, prefix-safe routes, and controlled dro
|
|||||||
await persistArtifact(page, `${basePath.slice(1)}-desktop-1200`);
|
await persistArtifact(page, `${basePath.slice(1)}-desktop-1200`);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('shows the persisted official game index beside the scenario title without viewport overflow', async ({ page }) => {
|
||||||
|
const state: NavigationFixture = {
|
||||||
|
officerLevel: 5,
|
||||||
|
permission: 2,
|
||||||
|
nationLevel: 3,
|
||||||
|
stage: 0,
|
||||||
|
npcMode: 1,
|
||||||
|
profile: 'hwe',
|
||||||
|
gameIdx: 7,
|
||||||
|
scenarioTitle: '메인 화면 검증 시나리오',
|
||||||
|
generalMeCalls: 0,
|
||||||
|
operations: [],
|
||||||
|
};
|
||||||
|
await installFixture(page, state);
|
||||||
|
if (artifactRoot) await mkdir(resolve(artifactRoot), { recursive: true });
|
||||||
|
|
||||||
|
for (const viewport of [
|
||||||
|
{ width: 1200, height: 900 },
|
||||||
|
{ width: 500, height: 900 },
|
||||||
|
]) {
|
||||||
|
await page.setViewportSize(viewport);
|
||||||
|
if (page.url() === 'about:blank') await waitForMain(page);
|
||||||
|
|
||||||
|
const title = page.getByRole('heading', { name: '메인 화면 검증 시나리오 훼섭 7기', exact: true });
|
||||||
|
await expect(title).toBeVisible();
|
||||||
|
const geometry = await title.evaluate((element) => {
|
||||||
|
const rect = element.getBoundingClientRect();
|
||||||
|
const mainRect = element.closest<HTMLElement>('.main-page')?.getBoundingClientRect();
|
||||||
|
const style = getComputedStyle(element);
|
||||||
|
return {
|
||||||
|
left: rect.left,
|
||||||
|
right: rect.right,
|
||||||
|
mainLeft: mainRect?.left,
|
||||||
|
mainRight: mainRect?.right,
|
||||||
|
fontFamily: style.fontFamily,
|
||||||
|
fontSize: style.fontSize,
|
||||||
|
lineHeight: style.lineHeight,
|
||||||
|
documentOverflow: document.documentElement.scrollWidth - document.documentElement.clientWidth,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
expect(geometry.left).toBeGreaterThanOrEqual(geometry.mainLeft ?? 0);
|
||||||
|
expect(geometry.right).toBeLessThanOrEqual(geometry.mainRight ?? viewport.width);
|
||||||
|
expect(geometry.documentOverflow).toBeLessThanOrEqual(0);
|
||||||
|
expect(geometry.fontSize).toBe('25.6px');
|
||||||
|
expect(geometry.lineHeight).toBe('38.4px');
|
||||||
|
expect(geometry.fontFamily).toContain('Pretendard');
|
||||||
|
await persistArtifact(page, `official-game-index-${viewport.width}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
test('nation split buttons keep square inner corners and a single divider in every interaction state', async ({
|
test('nation split buttons keep square inner corners and a single divider in every interaction state', async ({
|
||||||
page,
|
page,
|
||||||
}, testInfo) => {
|
}, testInfo) => {
|
||||||
@@ -2248,7 +2304,7 @@ test('the 939/940 boundary switches to the Ref-style 500px single document', asy
|
|||||||
await expect(page.locator('.main-mobile-bottom')).toBeVisible();
|
await expect(page.locator('.main-mobile-bottom')).toBeVisible();
|
||||||
|
|
||||||
await page.setViewportSize({ width: 500, height: 900 });
|
await page.setViewportSize({ width: 500, height: 900 });
|
||||||
await expect(page.getByRole('heading', { name: '모바일 검증 시나리오', exact: true })).toHaveCount(1);
|
await expect(page.getByRole('heading', { name: '모바일 검증 시나리오 체섭 101기', exact: true })).toHaveCount(1);
|
||||||
await expect(page.locator('.game-shell__subtitle')).toHaveCount(0);
|
await expect(page.locator('.game-shell__subtitle')).toHaveCount(0);
|
||||||
await expect(page.locator('.legacy-game-info')).toContainText('현재: 185년 1월');
|
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')).toContainText('턴: 10분');
|
||||||
|
|||||||
@@ -285,9 +285,7 @@ const screenshot = async (page: Page, name: string) => {
|
|||||||
await page.screenshot({ path: resolve(artifactRoot, name), fullPage: true });
|
await page.screenshot({ path: resolve(artifactRoot, name), fullPage: true });
|
||||||
};
|
};
|
||||||
|
|
||||||
test('personnel keeps the legacy frame while presenting modern appointment cards and interaction states', async ({
|
test('personnel keeps the desktop frame while exposing row-level appointment controls', async ({ page }) => {
|
||||||
page,
|
|
||||||
}) => {
|
|
||||||
await installFixture(page, { role: 'leader', rate: 20 });
|
await installFixture(page, { role: 'leader', rate: 20 });
|
||||||
await page.setViewportSize({ width: 1000, height: 900 });
|
await page.setViewportSize({ width: 1000, height: 900 });
|
||||||
await gotoOffice(page, 'nation/personnel');
|
await gotoOffice(page, 'nation/personnel');
|
||||||
@@ -313,8 +311,9 @@ test('personnel keeps the legacy frame while presenting modern appointment cards
|
|||||||
heading: box('.heading-table'),
|
heading: box('.heading-table'),
|
||||||
status: box('.chief-status'),
|
status: box('.chief-status'),
|
||||||
icon: box('.general-icon'),
|
icon: box('.general-icon'),
|
||||||
appointmentCard: box('.appointment-card'),
|
chiefEntry: box('.chief-entry-cell'),
|
||||||
selectionTrigger: box('.selection-trigger'),
|
changeButton: box('.personnel-change-button'),
|
||||||
|
cityOfficer: box('.city-officer-cell'),
|
||||||
documentWidth: document.documentElement.scrollWidth,
|
documentWidth: document.documentElement.scrollWidth,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
@@ -322,23 +321,27 @@ test('personnel keeps the legacy frame while presenting modern appointment cards
|
|||||||
expect(computed.heading.width).toBe(1000);
|
expect(computed.heading.width).toBe(1000);
|
||||||
expect(computed.heading.height).toBeCloseTo(56, 0);
|
expect(computed.heading.height).toBeCloseTo(56, 0);
|
||||||
expect(computed.status.width).toBe(1000);
|
expect(computed.status.width).toBe(1000);
|
||||||
expect(computed.icon.width).toBeCloseTo(64.7, 0);
|
expect(computed.icon.width).toBe(64);
|
||||||
expect(computed.icon.height).toBeCloseTo(64, 0);
|
expect(computed.icon.height).toBeCloseTo(64, 0);
|
||||||
expect(computed.appointmentCard.width).toBeGreaterThan(450);
|
expect(computed.chiefEntry.width).toBeGreaterThan(499);
|
||||||
expect(computed.appointmentCard.height).toBeGreaterThan(140);
|
expect(computed.chiefEntry.width).toBeLessThan(501);
|
||||||
expect(computed.selectionTrigger.height).toBeGreaterThanOrEqual(70);
|
expect(computed.chiefEntry.height).toBeGreaterThanOrEqual(76);
|
||||||
|
expect(computed.changeButton.height).toBeGreaterThanOrEqual(34);
|
||||||
|
expect(computed.cityOfficer.width).toBeCloseTo(280, 0);
|
||||||
expect(computed.container.fontFamily).toContain('Pretendard');
|
expect(computed.container.fontFamily).toContain('Pretendard');
|
||||||
expect(computed.container.fontSize).toBe('14px');
|
expect(computed.container.fontSize).toBe('14px');
|
||||||
expect(computed.container.lineHeight).toBe('18.2px');
|
expect(computed.container.lineHeight).toBe('18.2px');
|
||||||
expect(computed.status.backgroundImage).toContain('back_walnut.jpg');
|
expect(computed.status.backgroundImage).toContain('back_walnut.jpg');
|
||||||
expect(computed.documentWidth).toBe(1000);
|
expect(computed.documentWidth).toBe(1000);
|
||||||
|
|
||||||
const appointButton = page.getByRole('button', { name: '주부 임명', exact: true });
|
const changeButton = page.getByRole('button', { name: '주부 변경하기', exact: true });
|
||||||
expect(await appointButton.evaluate((button) => getComputedStyle(button).backgroundColor)).toBe('rgb(55, 104, 70)');
|
expect(await changeButton.evaluate((button) => getComputedStyle(button).backgroundColor)).toBe('rgb(49, 91, 61)');
|
||||||
await appointButton.hover();
|
await changeButton.hover();
|
||||||
expect(await appointButton.evaluate((button) => getComputedStyle(button).cursor)).toBe('pointer');
|
expect(await changeButton.evaluate((button) => getComputedStyle(button).cursor)).toBe('pointer');
|
||||||
await appointButton.focus();
|
await changeButton.focus();
|
||||||
expect(await appointButton.evaluate((button) => getComputedStyle(button).outlineStyle)).not.toBe('none');
|
expect(await changeButton.evaluate((button) => getComputedStyle(button).outlineStyle)).not.toBe('none');
|
||||||
|
await expect(page.getByRole('button', { name: '허창 태수 변경하기', exact: true })).toBeVisible();
|
||||||
|
await expect(page.getByRole('button', { name: '허창 군사 변경하기', exact: true })).toHaveCount(0);
|
||||||
await screenshot(page, 'core-personnel-desktop-leader.png');
|
await screenshot(page, 'core-personnel-desktop-leader.png');
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -348,7 +351,7 @@ test('personnel selects an informed general and reports the JosaUtil-composed re
|
|||||||
await page.setViewportSize({ width: 1000, height: 900 });
|
await page.setViewportSize({ width: 1000, height: 900 });
|
||||||
await gotoOffice(page, 'nation/personnel');
|
await gotoOffice(page, 'nation/personnel');
|
||||||
|
|
||||||
await page.getByRole('button', { name: '주부 장수 선택', exact: true }).click();
|
await page.getByRole('button', { name: '주부 변경하기', exact: true }).click();
|
||||||
const picker = page.getByTestId('personnel-selection-dialog');
|
const picker = page.getByTestId('personnel-selection-dialog');
|
||||||
await expect(picker).toBeVisible();
|
await expect(picker).toBeVisible();
|
||||||
await expect(picker.getByRole('heading', { name: '주부 임명 대상 선택' })).toBeVisible();
|
await expect(picker.getByRole('heading', { name: '주부 임명 대상 선택' })).toBeVisible();
|
||||||
@@ -363,14 +366,11 @@ test('personnel selects an informed general and reports the JosaUtil-composed re
|
|||||||
await candidate.focus();
|
await candidate.focus();
|
||||||
expect(await candidate.evaluate((button) => getComputedStyle(button).outlineStyle)).not.toBe('none');
|
expect(await candidate.evaluate((button) => getComputedStyle(button).outlineStyle)).not.toBe('none');
|
||||||
await screenshot(page, 'core-personnel-desktop-general-picker.png');
|
await screenshot(page, 'core-personnel-desktop-general-picker.png');
|
||||||
await candidate.click();
|
|
||||||
|
|
||||||
await expect(page.getByRole('button', { name: '주부 장수 선택', exact: true })).toContainText('장료');
|
|
||||||
page.once('dialog', async (dialog) => {
|
page.once('dialog', async (dialog) => {
|
||||||
expect(dialog.message()).toBe('장료를 주부직에 임명하시겠습니까?');
|
expect(dialog.message()).toBe('장료를 주부직에 임명하시겠습니까?');
|
||||||
await dialog.accept();
|
await dialog.accept();
|
||||||
});
|
});
|
||||||
await page.getByRole('button', { name: '주부 임명', exact: true }).click();
|
await candidate.click();
|
||||||
|
|
||||||
await expect(page.getByTestId('game-toast')).toContainText('장료를 임명했습니다.');
|
await expect(page.getByTestId('game-toast')).toContainText('장료를 임명했습니다.');
|
||||||
expect(state.appointedGeneralId).toBe(6);
|
expect(state.appointedGeneralId).toBe(6);
|
||||||
@@ -380,21 +380,41 @@ test('personnel selects an informed general and reports the JosaUtil-composed re
|
|||||||
await screenshot(page, 'core-personnel-appointment-toast.png');
|
await screenshot(page, 'core-personnel-appointment-toast.png');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('personnel preserves the legacy fixed 1000px document on a 500px viewport', async ({ page }) => {
|
test('personnel reflows row-level appointments at 500px and 390px without gradients or overflow', async ({ page }) => {
|
||||||
await installFixture(page, { role: 'head', rate: 20 });
|
const state: FixtureState = { role: 'head', rate: 20 };
|
||||||
|
await installFixture(page, state);
|
||||||
await page.setViewportSize({ width: 500, height: 900 });
|
await page.setViewportSize({ width: 500, height: 900 });
|
||||||
await gotoOffice(page, 'nation/personnel');
|
await gotoOffice(page, 'nation/personnel');
|
||||||
await expect(page.getByText('작위검증국')).toBeVisible();
|
await expect(page.getByText('작위검증국')).toBeVisible();
|
||||||
expect(
|
expect(
|
||||||
await page.locator('#personnel-container').evaluate((element) => element.getBoundingClientRect().width)
|
await page.locator('#personnel-container').evaluate((element) => element.getBoundingClientRect().width)
|
||||||
).toBe(1000);
|
).toBe(500);
|
||||||
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBe(1000);
|
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBe(500);
|
||||||
|
const rowGeometry = await page.locator('#personnel-container').evaluate((container) => {
|
||||||
|
const rect = (selector: string) => container.querySelector<HTMLElement>(selector)!.getBoundingClientRect();
|
||||||
|
return {
|
||||||
|
chiefWidth: rect('.chief-entry-cell').width,
|
||||||
|
cityWidth: rect('.city-identity').width,
|
||||||
|
officerWidth: rect('.city-officer-cell').width,
|
||||||
|
gradientCount: [...container.querySelectorAll<HTMLElement>('*')].filter((element) =>
|
||||||
|
getComputedStyle(element).backgroundImage.includes('gradient')
|
||||||
|
).length,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
expect(rowGeometry.chiefWidth).toBeGreaterThan(249);
|
||||||
|
expect(rowGeometry.chiefWidth).toBeLessThan(251);
|
||||||
|
expect(rowGeometry.cityWidth).toBeGreaterThan(79);
|
||||||
|
expect(rowGeometry.cityWidth).toBeLessThan(81);
|
||||||
|
expect(rowGeometry.officerWidth).toBeGreaterThan(139);
|
||||||
|
expect(rowGeometry.officerWidth).toBeLessThan(141);
|
||||||
|
expect(rowGeometry.gradientCount).toBe(0);
|
||||||
await expect(page.getByRole('combobox', { name: '외교권자' })).toHaveCount(0);
|
await expect(page.getByRole('combobox', { name: '외교권자' })).toHaveCount(0);
|
||||||
await expect(page.getByRole('combobox', { name: '추방 대상 장수' })).toBeVisible();
|
await expect(page.getByRole('combobox', { name: '추방 대상 장수' })).toBeVisible();
|
||||||
|
|
||||||
await page.getByRole('button', { name: '태수 도시 선택', exact: true }).click();
|
await page.getByRole('button', { name: '허창 태수 변경하기', exact: true }).click();
|
||||||
const picker = page.getByTestId('personnel-selection-dialog');
|
const picker = page.getByTestId('personnel-selection-dialog');
|
||||||
await expect(picker).toBeVisible();
|
await expect(picker).toBeVisible();
|
||||||
|
await expect(picker.getByRole('heading', { name: '허창 태수 변경' })).toBeVisible();
|
||||||
expect(await picker.evaluate((element) => getComputedStyle(element).transitionDuration)).toContain('0.15s');
|
expect(await picker.evaluate((element) => getComputedStyle(element).transitionDuration)).toContain('0.15s');
|
||||||
await expect(picker).toHaveCSS('transform', 'none');
|
await expect(picker).toHaveCSS('transform', 'none');
|
||||||
const pickerGeometry = await picker.evaluate((element) => {
|
const pickerGeometry = await picker.evaluate((element) => {
|
||||||
@@ -414,26 +434,71 @@ test('personnel preserves the legacy fixed 1000px document on a 500px viewport',
|
|||||||
expect(pickerGeometry.bottom).toBe(900);
|
expect(pickerGeometry.bottom).toBe(900);
|
||||||
expect(pickerGeometry.width).toBeGreaterThan(480);
|
expect(pickerGeometry.width).toBeGreaterThan(480);
|
||||||
expect(pickerGeometry.borderTopLeftRadius).toBe('16px');
|
expect(pickerGeometry.borderTopLeftRadius).toBe('16px');
|
||||||
await expect(picker.getByRole('button', { name: /낙양/ })).toContainText('중원 · 중도시');
|
|
||||||
await expect(picker.getByRole('button', { name: /허창/ })).toContainText('현재 태수하후돈');
|
|
||||||
await picker.getByRole('button', { name: /낙양/ }).focus();
|
|
||||||
expect(
|
expect(
|
||||||
await picker.getByRole('button', { name: /낙양/ }).evaluate((button) => getComputedStyle(button).outlineStyle)
|
await picker.evaluate(
|
||||||
|
(element) =>
|
||||||
|
[...element.querySelectorAll<HTMLElement>('*')].filter((child) =>
|
||||||
|
getComputedStyle(child).backgroundImage.includes('gradient')
|
||||||
|
).length
|
||||||
|
)
|
||||||
|
).toBe(0);
|
||||||
|
await expect(picker.getByRole('button', { name: /장료/ })).toContainText('허창 · 일반 장수');
|
||||||
|
await expect(picker.getByRole('button', { name: /하후돈/ })).toContainText('현재 임명 중');
|
||||||
|
await picker.getByRole('button', { name: /장료/ }).focus();
|
||||||
|
expect(
|
||||||
|
await picker.getByRole('button', { name: /장료/ }).evaluate((button) => getComputedStyle(button).outlineStyle)
|
||||||
).not.toBe('none');
|
).not.toBe('none');
|
||||||
await screenshot(page, 'core-personnel-mobile-city-picker.png');
|
await screenshot(page, 'core-personnel-mobile-city-picker.png');
|
||||||
await picker.getByRole('button', { name: /낙양/ }).click();
|
page.once('dialog', async (dialog) => {
|
||||||
await expect(page.getByRole('button', { name: '태수 도시 선택', exact: true })).toContainText('낙양');
|
expect(dialog.message()).toBe('장료를 허창 태수직에 임명하시겠습니까?');
|
||||||
await screenshot(page, 'core-personnel-mobile-head.png');
|
await dialog.accept();
|
||||||
|
});
|
||||||
|
await picker.getByRole('button', { name: /장료/ }).click();
|
||||||
|
await expect(page.getByTestId('game-toast')).toContainText('장료를 임명했습니다.');
|
||||||
|
expect(state.appointedGeneralId).toBe(6);
|
||||||
|
expect(state.appointedCityId).toBe(1);
|
||||||
|
expect(state.appointedOfficerLevel).toBe(4);
|
||||||
|
|
||||||
|
await page.setViewportSize({ width: 390, height: 844 });
|
||||||
|
await page.waitForTimeout(250);
|
||||||
|
expect(
|
||||||
|
await page.locator('#personnel-container').evaluate((element) => element.getBoundingClientRect().width)
|
||||||
|
).toBe(390);
|
||||||
|
const overflowContributors = await page.evaluate(() =>
|
||||||
|
[...document.querySelectorAll<HTMLElement>('body *')]
|
||||||
|
.map((element) => {
|
||||||
|
const rect = element.getBoundingClientRect();
|
||||||
|
return {
|
||||||
|
element: `${element.tagName.toLowerCase()}#${element.id}.${element.className}`,
|
||||||
|
parent: `${element.parentElement?.tagName.toLowerCase() ?? ''}#${element.parentElement?.id ?? ''}.${element.parentElement?.className ?? ''}`,
|
||||||
|
left: rect.left,
|
||||||
|
right: rect.right,
|
||||||
|
width: rect.width,
|
||||||
|
};
|
||||||
|
})
|
||||||
|
.filter((entry) => entry.right > window.innerWidth + 0.5 || entry.left < -0.5)
|
||||||
|
.slice(0, 12)
|
||||||
|
);
|
||||||
|
expect(overflowContributors).toEqual([]);
|
||||||
|
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBe(390);
|
||||||
|
const narrowChiefWidth = await page
|
||||||
|
.locator('.chief-entry-cell')
|
||||||
|
.first()
|
||||||
|
.evaluate((element) => element.getBoundingClientRect().width);
|
||||||
|
expect(narrowChiefWidth).toBeGreaterThan(194);
|
||||||
|
expect(narrowChiefWidth).toBeLessThan(196);
|
||||||
|
await screenshot(page, 'core-personnel-mobile-rows.png');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('personnel hides every mutation control for an ordinary member and exposes load errors', async ({ page }) => {
|
test('personnel hides every mutation control for an ordinary member and exposes load errors', async ({ page }) => {
|
||||||
await installFixture(page, { role: 'member', rate: 20 });
|
await installFixture(page, { role: 'member', rate: 20 });
|
||||||
await gotoOffice(page, 'nation/personnel');
|
await gotoOffice(page, 'nation/personnel');
|
||||||
await expect(page.getByText('도 시 관 직 임 명')).toHaveCount(0);
|
await expect(page.getByRole('button', { name: /변경하기/ })).toHaveCount(0);
|
||||||
await expect(page.getByText('외 교 권 자 임 명')).toHaveCount(0);
|
await expect(page.getByText('외 교 권 자 임 명')).toHaveCount(0);
|
||||||
await expect(page.getByRole('combobox', { name: '추방 대상 장수' })).toHaveCount(0);
|
await expect(page.getByRole('combobox', { name: '추방 대상 장수' })).toHaveCount(0);
|
||||||
await expect(page.getByRole('button', { name: '추방', exact: true })).toHaveCount(0);
|
await expect(page.getByRole('button', { name: '추방', exact: true })).toHaveCount(0);
|
||||||
await expect(page.getByText(/곽가\(10년\).*허창/)).toBeVisible();
|
const auditorCell = page.locator('.city-officer-cell').filter({ hasText: '곽가' });
|
||||||
|
await expect(auditorCell).toContainText('10년 · 허창');
|
||||||
|
|
||||||
const failed = await page.context().newPage();
|
const failed = await page.context().newPage();
|
||||||
await installFixture(failed, { role: 'member', rate: 20, failPersonnelLoad: true });
|
await installFixture(failed, { role: 'member', rate: 20, failPersonnelLoad: true });
|
||||||
@@ -556,9 +621,7 @@ test('finance editor preserves Ref formatting controls and uploads images throug
|
|||||||
const editor = page.getByRole('textbox', { name: '국가 방침' });
|
const editor = page.getByRole('textbox', { name: '국가 방침' });
|
||||||
const editorFrame = page.locator('#notice-form .legacy-html-editor');
|
const editorFrame = page.locator('#notice-form .legacy-html-editor');
|
||||||
await expect(editor).toBeVisible();
|
await expect(editor).toBeVisible();
|
||||||
expect(await editorFrame.evaluate((element) => getComputedStyle(element).backgroundColor)).toBe(
|
expect(await editorFrame.evaluate((element) => getComputedStyle(element).backgroundColor)).toBe('rgba(0, 0, 0, 0)');
|
||||||
'rgba(0, 0, 0, 0)'
|
|
||||||
);
|
|
||||||
expect(await editor.evaluate((element) => getComputedStyle(element).backgroundColor)).toBe('rgba(0, 0, 0, 0)');
|
expect(await editor.evaluate((element) => getComputedStyle(element).backgroundColor)).toBe('rgba(0, 0, 0, 0)');
|
||||||
|
|
||||||
await editor.fill('서식 검증');
|
await editor.fill('서식 검증');
|
||||||
|
|||||||
@@ -40,10 +40,11 @@ body {
|
|||||||
min-width: 500px;
|
min-width: 500px;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* These redesigned identity/tournament screens own a true handheld layout. */
|
/* These redesigned screens own a true handheld layout. */
|
||||||
#app:has(.responsive-settings-page),
|
#app:has(.responsive-settings-page),
|
||||||
#app:has(#tournament-container),
|
#app:has(#tournament-container),
|
||||||
#app:has(#tournament-betting-container) {
|
#app:has(#tournament-betting-container),
|
||||||
|
#app:has(#personnel-container) {
|
||||||
min-width: 320px;
|
min-width: 320px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -245,7 +245,7 @@ onBeforeUnmount(() => {
|
|||||||
align-items: flex-start;
|
align-items: flex-start;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
padding: 20px 22px 16px;
|
padding: 20px 22px 16px;
|
||||||
background: linear-gradient(135deg, rgb(69 57 34 / 72%), rgb(25 28 22 / 96%));
|
background: #29281f;
|
||||||
border-bottom: 1px solid #53482f;
|
border-bottom: 1px solid #53482f;
|
||||||
}
|
}
|
||||||
.personnel-picker-eyebrow {
|
.personnel-picker-eyebrow {
|
||||||
@@ -370,7 +370,7 @@ onBeforeUnmount(() => {
|
|||||||
display: grid;
|
display: grid;
|
||||||
place-items: center;
|
place-items: center;
|
||||||
color: #d8be79;
|
color: #d8be79;
|
||||||
background: radial-gradient(circle at 50% 30%, #353626, #11130f 72%);
|
background: #25271f;
|
||||||
font: 700 24px/1 var(--sammo-font-sans);
|
font: 700 24px/1 var(--sammo-font-sans);
|
||||||
}
|
}
|
||||||
.personnel-picker-card-body,
|
.personnel-picker-card-body,
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { trpc } from '../utils/trpc';
|
|||||||
type InheritStatus = Awaited<ReturnType<typeof trpc.inherit.getStatus.query>>;
|
type InheritStatus = Awaited<ReturnType<typeof trpc.inherit.getStatus.query>>;
|
||||||
type InheritLog = Awaited<ReturnType<typeof trpc.inherit.getLogs.query>>[number];
|
type InheritLog = Awaited<ReturnType<typeof trpc.inherit.getLogs.query>>[number];
|
||||||
type JoinConfig = Awaited<ReturnType<typeof trpc.join.getConfig.query>>;
|
type JoinConfig = Awaited<ReturnType<typeof trpc.join.getConfig.query>>;
|
||||||
|
type UniqueItemSlot = InheritStatus['availableUnique'][number]['slot'];
|
||||||
|
|
||||||
type BuffKey =
|
type BuffKey =
|
||||||
| 'warAvoidRatio'
|
| 'warAvoidRatio'
|
||||||
@@ -67,6 +68,14 @@ const pointOrder = [
|
|||||||
'betting',
|
'betting',
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
|
const uniqueItemSlotOrder: readonly UniqueItemSlot[] = ['horse', 'weapon', 'book', 'item'];
|
||||||
|
const uniqueItemSlotLabels: Record<UniqueItemSlot, string> = {
|
||||||
|
horse: '명마',
|
||||||
|
weapon: '무기',
|
||||||
|
book: '서적',
|
||||||
|
item: '도구',
|
||||||
|
};
|
||||||
|
|
||||||
const pointHelp: Record<string, string> = {
|
const pointHelp: Record<string, string> = {
|
||||||
previous: '이전에 물려받은 포인트입니다.',
|
previous: '이전에 물려받은 포인트입니다.',
|
||||||
lived_month: '살아남은 기간입니다. (1개월 단위)',
|
lived_month: '살아남은 기간입니다. (1개월 단위)',
|
||||||
@@ -196,6 +205,15 @@ const specialNameMap = computed(() => {
|
|||||||
const selectedSpecialWarInfo = computed(
|
const selectedSpecialWarInfo = computed(
|
||||||
() => status.value?.availableSpecialWar.find((entry) => entry.key === nextSpecialKey.value)?.info ?? ''
|
() => status.value?.availableSpecialWar.find((entry) => entry.key === nextSpecialKey.value)?.info ?? ''
|
||||||
);
|
);
|
||||||
|
const availableUniqueGroups = computed(() =>
|
||||||
|
uniqueItemSlotOrder
|
||||||
|
.map((slot) => ({
|
||||||
|
slot,
|
||||||
|
label: uniqueItemSlotLabels[slot],
|
||||||
|
items: status.value?.availableUnique.filter((item) => item.slot === slot) ?? [],
|
||||||
|
}))
|
||||||
|
.filter((group) => group.items.length > 0)
|
||||||
|
);
|
||||||
|
|
||||||
const buffCost = (key: BuffKey, target: number): number => {
|
const buffCost = (key: BuffKey, target: number): number => {
|
||||||
const points = status.value?.inheritConst.inheritBuffPoints ?? [0, 0, 0, 0, 0, 0];
|
const points = status.value?.inheritConst.inheritBuffPoints ?? [0, 0, 0, 0, 0, 0];
|
||||||
@@ -518,9 +536,11 @@ onMounted(() => {
|
|||||||
<label for="specific-unique">유니크 경매</label>
|
<label for="specific-unique">유니크 경매</label>
|
||||||
<select id="specific-unique" v-model="uniqueForm.itemId">
|
<select id="specific-unique" v-model="uniqueForm.itemId">
|
||||||
<option disabled value="">유니크 선택</option>
|
<option disabled value="">유니크 선택</option>
|
||||||
<option v-for="item in status.availableUnique" :key="item.key" :value="item.key">
|
<optgroup v-for="group in availableUniqueGroups" :key="group.slot" :label="group.label">
|
||||||
{{ item.name }}
|
<option v-for="item in group.items" :key="item.key" :value="item.key">
|
||||||
</option>
|
{{ item.name }}
|
||||||
|
</option>
|
||||||
|
</optgroup>
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
<div class="control-row">
|
<div class="control-row">
|
||||||
|
|||||||
@@ -95,6 +95,27 @@ const nationAccess = computed(() => ({
|
|||||||
}));
|
}));
|
||||||
const nationColor = computed(() => nation.value?.color ?? '#000000');
|
const nationColor = computed(() => nation.value?.color ?? '#000000');
|
||||||
const voteActive = computed(() => Boolean(frontStatus.value?.latestVote));
|
const voteActive = computed(() => Boolean(frontStatus.value?.latestVote));
|
||||||
|
const profileLabels: Record<string, string> = {
|
||||||
|
che: '체',
|
||||||
|
kwe: '퀘',
|
||||||
|
pwe: '풰',
|
||||||
|
twe: '퉤',
|
||||||
|
nya: '냐',
|
||||||
|
pya: '퍄',
|
||||||
|
hwe: '훼',
|
||||||
|
};
|
||||||
|
const gameProfileLabel = computed(() => {
|
||||||
|
const profile = lobbyInfo.value?.profile?.trim();
|
||||||
|
return profile ? (profileLabels[profile] ?? profile) : '';
|
||||||
|
});
|
||||||
|
const gameTitle = computed(() => {
|
||||||
|
const scenarioTitle = lobbyInfo.value?.scenarioTitle || '전장 현황';
|
||||||
|
const profileLabel = gameProfileLabel.value;
|
||||||
|
const gameIdx = lobbyInfo.value?.gameIdx;
|
||||||
|
return profileLabel && typeof gameIdx === 'number' && Number.isInteger(gameIdx) && gameIdx > 0
|
||||||
|
? `${scenarioTitle} ${profileLabel}섭 ${gameIdx}기`
|
||||||
|
: scenarioTitle;
|
||||||
|
});
|
||||||
const recordTimeSuffixPattern = /\d{2}:\d{2}(?:<\/>)?\s*$/u;
|
const recordTimeSuffixPattern = /\d{2}:\d{2}(?:<\/>)?\s*$/u;
|
||||||
const formatRecord = (entry: { text: string; createdAt?: string | Date }, appendTime = false): string => {
|
const formatRecord = (entry: { text: string; createdAt?: string | Date }, appendTime = false): string => {
|
||||||
if (!appendTime || recordTimeSuffixPattern.test(entry.text)) return formatLog(entry.text);
|
if (!appendTime || recordTimeSuffixPattern.test(entry.text)) return formatLog(entry.text);
|
||||||
@@ -199,7 +220,7 @@ watch(
|
|||||||
|
|
||||||
<header class="game-shell__header">
|
<header class="game-shell__header">
|
||||||
<h1 class="game-shell__title">
|
<h1 class="game-shell__title">
|
||||||
{{ lobbyInfo?.scenarioTitle || '전장 현황' }}
|
{{ gameTitle }}
|
||||||
</h1>
|
</h1>
|
||||||
<div class="game-shell__actions desktop-action-controls">
|
<div class="game-shell__actions desktop-action-controls">
|
||||||
<button
|
<button
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, onMounted, reactive, ref, watch } from 'vue';
|
import { computed, onMounted, ref, watch } from 'vue';
|
||||||
import { useRouter } from 'vue-router';
|
import { useRouter } from 'vue-router';
|
||||||
|
|
||||||
import { JosaUtil } from '@sammo-ts/common';
|
import { JosaUtil } from '@sammo-ts/common';
|
||||||
@@ -26,9 +26,7 @@ type SelectionDialogItem = {
|
|||||||
details: Array<{ label: string; value: string }>;
|
details: Array<{ label: string; value: string }>;
|
||||||
};
|
};
|
||||||
type SelectionContext =
|
type SelectionContext =
|
||||||
| { kind: 'chief-general'; level: number }
|
{ kind: 'chief-general'; level: number } | { kind: 'city-general'; level: OfficerLevel; cityId: number };
|
||||||
| { kind: 'city'; level: OfficerLevel }
|
|
||||||
| { kind: 'city-general'; level: OfficerLevel };
|
|
||||||
|
|
||||||
const officerLabels: Record<OfficerLevel, string> = { 4: '태수', 3: '군사', 2: '종사' };
|
const officerLabels: Record<OfficerLevel, string> = { 4: '태수', 3: '군사', 2: '종사' };
|
||||||
const cityOfficerLevels: OfficerLevel[] = [4, 3, 2];
|
const cityOfficerLevels: OfficerLevel[] = [4, 3, 2];
|
||||||
@@ -36,12 +34,6 @@ const loading = ref(false);
|
|||||||
const error = ref<string | null>(null);
|
const error = ref<string | null>(null);
|
||||||
const data = ref<PersonnelResponse | null>(null);
|
const data = ref<PersonnelResponse | null>(null);
|
||||||
const selectionContext = ref<SelectionContext | null>(null);
|
const selectionContext = ref<SelectionContext | null>(null);
|
||||||
const chiefAppointmentDraft = reactive<Record<number, number>>({});
|
|
||||||
const cityDraft = reactive<Record<OfficerLevel, { cityId: number; generalId: number }>>({
|
|
||||||
4: { cityId: 0, generalId: 0 },
|
|
||||||
3: { cityId: 0, generalId: 0 },
|
|
||||||
2: { cityId: 0, generalId: 0 },
|
|
||||||
});
|
|
||||||
const kickTargetId = ref(0);
|
const kickTargetId = ref(0);
|
||||||
const ambassadorSelection = ref<number[]>([]);
|
const ambassadorSelection = ref<number[]>([]);
|
||||||
const auditorSelection = ref<number[]>([]);
|
const auditorSelection = ref<number[]>([]);
|
||||||
@@ -68,11 +60,6 @@ const nationLevel = computed(() => data.value?.nation.level ?? 0);
|
|||||||
const canManage = computed(() => data.value?.me.canManage ?? false);
|
const canManage = computed(() => data.value?.me.canManage ?? false);
|
||||||
const canChangePermissions = computed(() => data.value?.me.canChangePermissions ?? false);
|
const canChangePermissions = computed(() => data.value?.me.canChangePermissions ?? false);
|
||||||
const canKick = computed(() => data.value?.me.canKick ?? false);
|
const canKick = computed(() => data.value?.me.canKick ?? false);
|
||||||
const chiefLevels = computed(() => {
|
|
||||||
const levels: number[] = [];
|
|
||||||
for (let level = 12; level >= getNationChiefLevel(nationLevel.value); level -= 1) levels.push(level);
|
|
||||||
return levels;
|
|
||||||
});
|
|
||||||
const chiefPairs = computed(() => {
|
const chiefPairs = computed(() => {
|
||||||
const pairs: Array<[number, number]> = [];
|
const pairs: Array<[number, number]> = [];
|
||||||
for (let level = 12; level >= getNationChiefLevel(nationLevel.value); level -= 2) {
|
for (let level = 12; level >= getNationChiefLevel(nationLevel.value); level -= 2) {
|
||||||
@@ -111,27 +98,14 @@ const cityCandidates = (level: OfficerLevel): GeneralEntry[] => {
|
|||||||
if (level === 3) return candidates.filter((general) => general.stats.intelligence >= minimum);
|
if (level === 3) return candidates.filter((general) => general.stats.intelligence >= minimum);
|
||||||
return candidates;
|
return candidates;
|
||||||
};
|
};
|
||||||
const openCities = (level: OfficerLevel) =>
|
|
||||||
(data.value?.cityAssignments ?? []).filter((city) => !cityOfficerLocked(city, level));
|
|
||||||
const selectedChief = (level: number): GeneralEntry | undefined =>
|
|
||||||
generalMap.value.get(chiefAppointmentDraft[level] ?? 0);
|
|
||||||
const selectedCity = (level: OfficerLevel): PersonnelResponse['cityAssignments'][number] | undefined =>
|
|
||||||
data.value?.cityAssignments.find((city) => city.id === cityDraft[level].cityId);
|
|
||||||
const selectedCityGeneral = (level: OfficerLevel): GeneralEntry | undefined =>
|
|
||||||
generalMap.value.get(cityDraft[level].generalId);
|
|
||||||
const kickCandidates = computed(() =>
|
const kickCandidates = computed(() =>
|
||||||
(data.value?.generals ?? []).filter((general) => general.id !== data.value?.me.id)
|
(data.value?.generals ?? []).filter((general) => general.id !== data.value?.me.id)
|
||||||
);
|
);
|
||||||
const awardText = (entries: PersonnelResponse['awards']['tigers']): string =>
|
const awardText = (entries: PersonnelResponse['awards']['tigers']): string =>
|
||||||
entries.map((entry) => `${entry.name}【${entry.value.toLocaleString('ko-KR')}】`).join(', ');
|
entries.map((entry) => `${entry.name}【${entry.value.toLocaleString('ko-KR')}】`).join(', ');
|
||||||
|
|
||||||
const initializeDrafts = () => {
|
const initializePermissions = () => {
|
||||||
if (!data.value) return;
|
if (!data.value) return;
|
||||||
for (const level of chiefLevels.value) chiefAppointmentDraft[level] = chiefAssignments.value[level]?.id ?? 0;
|
|
||||||
for (const level of [4, 3, 2] as const) {
|
|
||||||
cityDraft[level].cityId = openCities(level)[0]?.id ?? 0;
|
|
||||||
cityDraft[level].generalId = 0;
|
|
||||||
}
|
|
||||||
ambassadorSelection.value = data.value.permissionCandidates.ambassadors
|
ambassadorSelection.value = data.value.permissionCandidates.ambassadors
|
||||||
.filter((candidate) => candidate.permission === 'ambassador')
|
.filter((candidate) => candidate.permission === 'ambassador')
|
||||||
.map((candidate) => candidate.id);
|
.map((candidate) => candidate.id);
|
||||||
@@ -139,7 +113,7 @@ const initializeDrafts = () => {
|
|||||||
.filter((candidate) => candidate.permission === 'auditor')
|
.filter((candidate) => candidate.permission === 'auditor')
|
||||||
.map((candidate) => candidate.id);
|
.map((candidate) => candidate.id);
|
||||||
};
|
};
|
||||||
watch(data, initializeDrafts);
|
watch(data, initializePermissions);
|
||||||
|
|
||||||
const runMutation = async (action: () => Promise<unknown>, successMessage: string) => {
|
const runMutation = async (action: () => Promise<unknown>, successMessage: string) => {
|
||||||
error.value = null;
|
error.value = null;
|
||||||
@@ -152,8 +126,7 @@ const runMutation = async (action: () => Promise<unknown>, successMessage: strin
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const appointChief = async (level: number) => {
|
const appointChief = async (level: number, targetId: number) => {
|
||||||
const targetId = chiefAppointmentDraft[level] ?? 0;
|
|
||||||
const target = generalMap.value.get(targetId);
|
const target = generalMap.value.get(targetId);
|
||||||
const office = formatOfficerLevelText(level, nationLevel.value);
|
const office = formatOfficerLevelText(level, nationLevel.value);
|
||||||
const prompt = target
|
const prompt = target
|
||||||
@@ -166,10 +139,9 @@ const appointChief = async (level: number) => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const appointCityOfficer = async (level: OfficerLevel) => {
|
const appointCityOfficer = async (level: OfficerLevel, cityId: number, targetId: number) => {
|
||||||
const draft = cityDraft[level];
|
const city = data.value?.cityAssignments.find((entry) => entry.id === cityId);
|
||||||
const city = data.value?.cityAssignments.find((entry) => entry.id === draft.cityId);
|
const target = generalMap.value.get(targetId);
|
||||||
const target = generalMap.value.get(draft.generalId);
|
|
||||||
const prompt = target
|
const prompt = target
|
||||||
? `${JosaUtil.put(target.name, '을')} ${city?.name ?? ''} ${officerLabels[level]}직에 임명하시겠습니까?`
|
? `${JosaUtil.put(target.name, '을')} ${city?.name ?? ''} ${officerLabels[level]}직에 임명하시겠습니까?`
|
||||||
: `${city?.name ?? ''} ${officerLabels[level]}직을 비우시겠습니까?`;
|
: `${city?.name ?? ''} ${officerLabels[level]}직을 비우시겠습니까?`;
|
||||||
@@ -177,16 +149,16 @@ const appointCityOfficer = async (level: OfficerLevel) => {
|
|||||||
await runMutation(
|
await runMutation(
|
||||||
() =>
|
() =>
|
||||||
trpc.nation.appoint.mutate({
|
trpc.nation.appoint.mutate({
|
||||||
destGeneralId: draft.generalId,
|
destGeneralId: targetId,
|
||||||
destCityId: draft.cityId,
|
destCityId: cityId,
|
||||||
officerLevel: level,
|
officerLevel: level,
|
||||||
}),
|
}),
|
||||||
target ? `${JosaUtil.put(target.name, '을')} 임명했습니다.` : '관직을 비웠습니다.'
|
target ? `${JosaUtil.put(target.name, '을')} 임명했습니다.` : '관직을 비웠습니다.'
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const generalSelectionItem = (general: GeneralEntry, targetLevel: number): SelectionDialogItem => {
|
const generalSelectionItem = (general: GeneralEntry, currentGeneralId: number): SelectionDialogItem => {
|
||||||
const isCurrent = general.officerLevel === targetLevel;
|
const isCurrent = general.id === currentGeneralId;
|
||||||
const isAssigned = general.officerLevel > 1 && !isCurrent;
|
const isAssigned = general.officerLevel > 1 && !isCurrent;
|
||||||
const office = currentOfficeText(general);
|
const office = currentOfficeText(general);
|
||||||
const city = general.cityName ?? cityNameMap.value.get(general.cityId) ?? '-';
|
const city = general.cityName ?? cityNameMap.value.get(general.cityId) ?? '-';
|
||||||
@@ -227,44 +199,18 @@ const generalSelectionItem = (general: GeneralEntry, targetLevel: number): Selec
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
const citySelectionItem = (
|
|
||||||
city: PersonnelResponse['cityAssignments'][number],
|
|
||||||
level: OfficerLevel
|
|
||||||
): SelectionDialogItem => {
|
|
||||||
const current = city.officers[level];
|
|
||||||
const region = regionMap[city.region] ?? '-';
|
|
||||||
const scale = cityLevelMap[city.level] ?? '-';
|
|
||||||
return {
|
|
||||||
id: city.id,
|
|
||||||
name: city.name,
|
|
||||||
subtitle: `${region} · ${scale}도시`,
|
|
||||||
searchText: `${city.name} ${region} ${scale} ${current?.name ?? '공석'}`,
|
|
||||||
accent: current ? 'assigned' : 'available',
|
|
||||||
badges: [current ? `${officerLabels[level]} 재직 중` : `${officerLabels[level]} 공석`],
|
|
||||||
details: [
|
|
||||||
{ label: '지역', value: region },
|
|
||||||
{ label: '규모', value: `${scale}도시` },
|
|
||||||
{ label: `현재 ${officerLabels[level]}`, value: current?.name ?? '공석' },
|
|
||||||
{ label: '소재지', value: current?.cityName ?? '-' },
|
|
||||||
],
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
const selectionTitle = computed(() => {
|
const selectionTitle = computed(() => {
|
||||||
const context = selectionContext.value;
|
const context = selectionContext.value;
|
||||||
if (!context) return '';
|
if (!context) return '';
|
||||||
if (context.kind === 'chief-general') {
|
if (context.kind === 'chief-general') {
|
||||||
return `${formatOfficerLevelText(context.level, nationLevel.value)} 임명 대상 선택`;
|
return `${formatOfficerLevelText(context.level, nationLevel.value)} 임명 대상 선택`;
|
||||||
}
|
}
|
||||||
if (context.kind === 'city') return `${officerLabels[context.level]} 임명 도시 선택`;
|
const city = data.value?.cityAssignments.find((entry) => entry.id === context.cityId);
|
||||||
return `${officerLabels[context.level]} 임명 대상 선택`;
|
return `${city?.name ?? ''} ${officerLabels[context.level]} 변경`;
|
||||||
});
|
});
|
||||||
const selectionDescription = computed(() => {
|
const selectionDescription = computed(() => {
|
||||||
const context = selectionContext.value;
|
const context = selectionContext.value;
|
||||||
if (!context) return '';
|
if (!context) return '';
|
||||||
if (context.kind === 'city') {
|
|
||||||
return '지역과 도시 규모, 현재 재직자를 확인한 뒤 임명할 도시를 선택하세요.';
|
|
||||||
}
|
|
||||||
if (context.kind === 'chief-general') {
|
if (context.kind === 'chief-general') {
|
||||||
if (context.level === 11) return '군주를 제외한 장수 중에서 임명할 수 있습니다.';
|
if (context.level === 11) return '군주를 제외한 장수 중에서 임명할 수 있습니다.';
|
||||||
const stat = context.level % 2 === 0 ? '무력' : '지력';
|
const stat = context.level % 2 === 0 ? '무력' : '지력';
|
||||||
@@ -282,27 +228,25 @@ const selectionItems = computed<SelectionDialogItem[]>(() => {
|
|||||||
const context = selectionContext.value;
|
const context = selectionContext.value;
|
||||||
if (!context) return [];
|
if (!context) return [];
|
||||||
if (context.kind === 'chief-general') {
|
if (context.kind === 'chief-general') {
|
||||||
return chiefCandidates(context.level).map((general) => generalSelectionItem(general, context.level));
|
const currentGeneralId = chiefAssignments.value[context.level]?.id ?? 0;
|
||||||
|
return chiefCandidates(context.level).map((general) => generalSelectionItem(general, currentGeneralId));
|
||||||
}
|
}
|
||||||
if (context.kind === 'city') {
|
const city = data.value?.cityAssignments.find((entry) => entry.id === context.cityId);
|
||||||
return openCities(context.level).map((city) => citySelectionItem(city, context.level));
|
const currentGeneralId = city?.officers[context.level]?.id ?? 0;
|
||||||
}
|
return cityCandidates(context.level).map((general) => generalSelectionItem(general, currentGeneralId));
|
||||||
return cityCandidates(context.level).map((general) => generalSelectionItem(general, context.level));
|
|
||||||
});
|
});
|
||||||
const selectionId = computed(() => {
|
const selectionId = computed(() => {
|
||||||
const context = selectionContext.value;
|
const context = selectionContext.value;
|
||||||
if (!context) return 0;
|
if (!context) return 0;
|
||||||
if (context.kind === 'chief-general') return chiefAppointmentDraft[context.level] ?? 0;
|
if (context.kind === 'chief-general') return chiefAssignments.value[context.level]?.id ?? 0;
|
||||||
if (context.kind === 'city') return cityDraft[context.level].cityId;
|
return data.value?.cityAssignments.find((entry) => entry.id === context.cityId)?.officers[context.level]?.id ?? 0;
|
||||||
return cityDraft[context.level].generalId;
|
|
||||||
});
|
});
|
||||||
const applySelection = (id: number): void => {
|
const applySelection = async (id: number): Promise<void> => {
|
||||||
const context = selectionContext.value;
|
const context = selectionContext.value;
|
||||||
if (!context) return;
|
if (!context) return;
|
||||||
if (context.kind === 'chief-general') chiefAppointmentDraft[context.level] = id;
|
|
||||||
else if (context.kind === 'city') cityDraft[context.level].cityId = id;
|
|
||||||
else cityDraft[context.level].generalId = id;
|
|
||||||
selectionContext.value = null;
|
selectionContext.value = null;
|
||||||
|
if (context.kind === 'chief-general') await appointChief(context.level, id);
|
||||||
|
else await appointCityOfficer(context.level, context.cityId, id);
|
||||||
};
|
};
|
||||||
|
|
||||||
const enforcePermissionLimit = (selection: number[]) => {
|
const enforcePermissionLimit = (selection: number[]) => {
|
||||||
@@ -374,121 +318,51 @@ onMounted(() => void loadPersonnel());
|
|||||||
</tr>
|
</tr>
|
||||||
<tr v-for="[leftLevel, rightLevel] in chiefPairs" :key="leftLevel">
|
<tr v-for="[leftLevel, rightLevel] in chiefPairs" :key="leftLevel">
|
||||||
<template v-for="level in [leftLevel, rightLevel]" :key="level">
|
<template v-for="level in [leftLevel, rightLevel]" :key="level">
|
||||||
<td class="green-cell role-cell">{{ formatOfficerLevelText(level, nationLevel) }}</td>
|
<td colspan="3" class="chief-entry-cell">
|
||||||
<td
|
<div class="chief-entry" :class="{ locked: chiefLocked(level) }">
|
||||||
class="general-icon"
|
<span class="chief-entry-role">{{
|
||||||
:style="{ backgroundImage: imageBackground(chiefAssignments[level]) }"
|
formatOfficerLevelText(level, nationLevel)
|
||||||
/>
|
}}</span>
|
||||||
<td class="chief-name">
|
<span
|
||||||
{{ chiefAssignments[level]?.name ?? '-' }}({{
|
class="general-icon"
|
||||||
chiefAssignments[level]?.belong ?? '-'
|
:style="{ backgroundImage: imageBackground(chiefAssignments[level]) }"
|
||||||
}}년)
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
<span class="chief-entry-copy">
|
||||||
|
<strong>{{ chiefAssignments[level]?.name ?? '공석' }}</strong>
|
||||||
|
<small>
|
||||||
|
{{ chiefAssignments[level]?.belong ?? '-' }}년 ·
|
||||||
|
{{ chiefAssignments[level]?.cityName ?? '소재지 없음' }}
|
||||||
|
</small>
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
v-if="canManage && level !== 12 && !chiefLocked(level)"
|
||||||
|
type="button"
|
||||||
|
class="personnel-change-button"
|
||||||
|
:aria-label="`${formatOfficerLevelText(level, nationLevel)} 변경하기`"
|
||||||
|
aria-haspopup="dialog"
|
||||||
|
@click="selectionContext = { kind: 'chief-general', level }"
|
||||||
|
>
|
||||||
|
변경하기
|
||||||
|
</button>
|
||||||
|
<small v-else-if="chiefLocked(level)" class="personnel-lock-label">변경 잠금</small>
|
||||||
|
</div>
|
||||||
</td>
|
</td>
|
||||||
</template>
|
</template>
|
||||||
</tr>
|
</tr>
|
||||||
<tr>
|
<tr>
|
||||||
<td class="green-cell">오호장군【승전】</td>
|
<td class="green-cell award-label" colspan="2">
|
||||||
<td colspan="5">{{ awardText(data.awards.tigers) }}</td>
|
<span class="award-label-full">오호장군【승전】</span>
|
||||||
</tr>
|
<span class="award-label-compact">오호장군</span>
|
||||||
<tr>
|
|
||||||
<td class="green-cell">건안칠자【계략】</td>
|
|
||||||
<td colspan="5">{{ awardText(data.awards.eagles) }}</td>
|
|
||||||
</tr>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
<table class="legacy-table appointment-table">
|
|
||||||
<colgroup>
|
|
||||||
<col class="office-label-column" />
|
|
||||||
<col class="office-control-column" />
|
|
||||||
<col class="office-label-column" />
|
|
||||||
<col class="office-control-column" />
|
|
||||||
</colgroup>
|
|
||||||
<tbody>
|
|
||||||
<tr>
|
|
||||||
<td colspan="4" class="spacer" />
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td colspan="4" class="section-title blue">수 뇌 부 임 명</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td colspan="4" class="appointment-workspace-cell">
|
|
||||||
<div class="appointment-card-grid">
|
|
||||||
<article v-for="level in chiefLevels" :key="level" class="appointment-card">
|
|
||||||
<header class="appointment-card-header">
|
|
||||||
<span>{{ formatOfficerLevelText(level, nationLevel) }}</span>
|
|
||||||
<small v-if="chiefLocked(level)" class="appointment-lock">변경 잠금</small>
|
|
||||||
<small v-else> 현재 {{ chiefAssignments[level]?.name ?? '공석' }} </small>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
<template v-if="canManage && level !== 12 && !chiefLocked(level)">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="selection-trigger"
|
|
||||||
:aria-label="`${formatOfficerLevelText(level, nationLevel)} 장수 선택`"
|
|
||||||
aria-haspopup="dialog"
|
|
||||||
@click="selectionContext = { kind: 'chief-general', level }"
|
|
||||||
>
|
|
||||||
<span
|
|
||||||
v-if="selectedChief(level)"
|
|
||||||
class="selection-trigger-portrait"
|
|
||||||
:style="{ backgroundImage: imageBackground(selectedChief(level)) }"
|
|
||||||
aria-hidden="true"
|
|
||||||
/>
|
|
||||||
<span v-else class="selection-trigger-empty" aria-hidden="true">+</span>
|
|
||||||
<span class="selection-trigger-copy">
|
|
||||||
<small>임명 대상</small>
|
|
||||||
<strong>{{ selectedChief(level)?.name ?? '공석으로 두기' }}</strong>
|
|
||||||
<span v-if="selectedChief(level)">
|
|
||||||
{{ selectedChief(level)?.cityName ?? '-' }} ·
|
|
||||||
{{ currentOfficeText(selectedChief(level)!) }}
|
|
||||||
</span>
|
|
||||||
<span v-else>눌러서 장수를 선택하세요</span>
|
|
||||||
</span>
|
|
||||||
<span class="selection-trigger-chevron" aria-hidden="true">›</span>
|
|
||||||
</button>
|
|
||||||
<div v-if="selectedChief(level)" class="selected-general-stats">
|
|
||||||
<span
|
|
||||||
>통솔
|
|
||||||
<strong>{{ selectedChief(level)?.stats.leadership }}</strong></span
|
|
||||||
>
|
|
||||||
<span
|
|
||||||
>무력 <strong>{{ selectedChief(level)?.stats.strength }}</strong></span
|
|
||||||
>
|
|
||||||
<span
|
|
||||||
>지력
|
|
||||||
<strong>{{ selectedChief(level)?.stats.intelligence }}</strong></span
|
|
||||||
>
|
|
||||||
<span
|
|
||||||
>소속 <strong>{{ selectedChief(level)?.belong }}년</strong></span
|
|
||||||
>
|
|
||||||
</div>
|
|
||||||
<button type="button" class="appointment-submit" @click="appointChief(level)">
|
|
||||||
{{ formatOfficerLevelText(level, nationLevel) }} 임명
|
|
||||||
</button>
|
|
||||||
</template>
|
|
||||||
<div v-else class="appointment-readonly">
|
|
||||||
<span
|
|
||||||
v-if="chiefAssignments[level]"
|
|
||||||
class="selection-trigger-portrait"
|
|
||||||
:style="{ backgroundImage: imageBackground(chiefAssignments[level]) }"
|
|
||||||
aria-hidden="true"
|
|
||||||
/>
|
|
||||||
<span v-else class="selection-trigger-empty" aria-hidden="true">-</span>
|
|
||||||
<span>
|
|
||||||
<strong>{{ chiefAssignments[level]?.name ?? '공석' }}</strong>
|
|
||||||
<small>{{ chiefAssignments[level]?.cityName ?? '임명된 장수 없음' }}</small>
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</article>
|
|
||||||
</div>
|
|
||||||
</td>
|
</td>
|
||||||
|
<td colspan="4">{{ awardText(data.awards.tigers) }}</td>
|
||||||
</tr>
|
</tr>
|
||||||
<tr>
|
<tr>
|
||||||
<td colspan="4" class="legend">
|
<td class="green-cell award-label" colspan="2">
|
||||||
※ 장수 선택 창에서 현재 임명 중인 장수, 다른 관직 재직자와 일반 장수를 구분하고 주요
|
<span class="award-label-full">건안칠자【계략】</span>
|
||||||
능력치·소재지·부대 정보를 함께 확인할 수 있습니다.
|
<span class="award-label-compact">건안칠자</span>
|
||||||
</td>
|
</td>
|
||||||
|
<td colspan="4">{{ awardText(data.awards.eagles) }}</td>
|
||||||
</tr>
|
</tr>
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
@@ -560,109 +434,12 @@ onMounted(() => void loadPersonnel());
|
|||||||
<tr>
|
<tr>
|
||||||
<td colspan="5" class="spacer" />
|
<td colspan="5" class="spacer" />
|
||||||
</tr>
|
</tr>
|
||||||
<template v-if="canManage">
|
|
||||||
<tr>
|
|
||||||
<td colspan="5" class="section-title orange-bg">도 시 관 직 임 명</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td colspan="5" class="appointment-workspace-cell">
|
|
||||||
<div class="city-appointment-grid">
|
|
||||||
<article
|
|
||||||
v-for="level in cityOfficerLevels"
|
|
||||||
:key="level"
|
|
||||||
class="appointment-card city-appointment-card"
|
|
||||||
>
|
|
||||||
<header class="appointment-card-header">
|
|
||||||
<span>{{ officerLabels[level] }}</span>
|
|
||||||
<small>도시 관직</small>
|
|
||||||
</header>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="selection-trigger compact"
|
|
||||||
:aria-label="`${officerLabels[level]} 도시 선택`"
|
|
||||||
aria-haspopup="dialog"
|
|
||||||
@click="selectionContext = { kind: 'city', level }"
|
|
||||||
>
|
|
||||||
<span class="selection-trigger-city" aria-hidden="true">城</span>
|
|
||||||
<span class="selection-trigger-copy">
|
|
||||||
<small>임명 도시</small>
|
|
||||||
<strong>{{ selectedCity(level)?.name ?? '도시 선택' }}</strong>
|
|
||||||
<span v-if="selectedCity(level)">
|
|
||||||
{{ regionMap[selectedCity(level)?.region ?? 0] ?? '-' }} ·
|
|
||||||
{{ cityLevelMap[selectedCity(level)?.level ?? 0] ?? '-' }}도시
|
|
||||||
</span>
|
|
||||||
</span>
|
|
||||||
<span class="selection-trigger-chevron" aria-hidden="true">›</span>
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="selection-trigger compact"
|
|
||||||
:aria-label="`${officerLabels[level]} 장수 선택`"
|
|
||||||
aria-haspopup="dialog"
|
|
||||||
@click="selectionContext = { kind: 'city-general', level }"
|
|
||||||
>
|
|
||||||
<span
|
|
||||||
v-if="selectedCityGeneral(level)"
|
|
||||||
class="selection-trigger-portrait"
|
|
||||||
:style="{
|
|
||||||
backgroundImage: imageBackground(selectedCityGeneral(level)),
|
|
||||||
}"
|
|
||||||
aria-hidden="true"
|
|
||||||
/>
|
|
||||||
<span v-else class="selection-trigger-empty" aria-hidden="true">+</span>
|
|
||||||
<span class="selection-trigger-copy">
|
|
||||||
<small>임명 대상</small>
|
|
||||||
<strong>{{
|
|
||||||
selectedCityGeneral(level)?.name ?? '공석으로 두기'
|
|
||||||
}}</strong>
|
|
||||||
<span v-if="selectedCityGeneral(level)">
|
|
||||||
{{ selectedCityGeneral(level)?.cityName ?? '-' }} ·
|
|
||||||
{{ currentOfficeText(selectedCityGeneral(level)!) }}
|
|
||||||
</span>
|
|
||||||
</span>
|
|
||||||
<span class="selection-trigger-chevron" aria-hidden="true">›</span>
|
|
||||||
</button>
|
|
||||||
<div v-if="selectedCityGeneral(level)" class="selected-general-stats compact">
|
|
||||||
<span
|
|
||||||
>통
|
|
||||||
<strong>{{
|
|
||||||
selectedCityGeneral(level)?.stats.leadership
|
|
||||||
}}</strong></span
|
|
||||||
>
|
|
||||||
<span
|
|
||||||
>무
|
|
||||||
<strong>{{ selectedCityGeneral(level)?.stats.strength }}</strong></span
|
|
||||||
>
|
|
||||||
<span
|
|
||||||
>지
|
|
||||||
<strong>{{
|
|
||||||
selectedCityGeneral(level)?.stats.intelligence
|
|
||||||
}}</strong></span
|
|
||||||
>
|
|
||||||
</div>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="appointment-submit"
|
|
||||||
:disabled="!selectedCity(level)"
|
|
||||||
@click="appointCityOfficer(level)"
|
|
||||||
>
|
|
||||||
{{ officerLabels[level] }} 임명
|
|
||||||
</button>
|
|
||||||
</article>
|
|
||||||
</div>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td colspan="5" class="legend">
|
|
||||||
※ 도시의 지역·규모·현재 재직자와 장수의 능력치·현재 관직을 확인한 뒤 임명할 수 있습니다.
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
</template>
|
|
||||||
<tr class="city-header">
|
<tr class="city-header">
|
||||||
<td colspan="2">도 시</td>
|
<td colspan="2">도 시</td>
|
||||||
<td>태 수 (사관) 【현재도시】</td>
|
<td v-for="level in cityOfficerLevels" :key="level">
|
||||||
<td>군 사 (사관) 【현재도시】</td>
|
<span class="city-header-full">{{ officerLabels[level] }} (사관) 【현재도시】</span>
|
||||||
<td>종 사 (사관) 【현재도시】</td>
|
<span class="city-header-compact">{{ officerLabels[level] }}</span>
|
||||||
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
<template v-for="(city, index) in data.cityAssignments" :key="city.id">
|
<template v-for="(city, index) in data.cityAssignments" :key="city.id">
|
||||||
<tr v-if="index === 0 || data.cityAssignments[index - 1]?.region !== city.region">
|
<tr v-if="index === 0 || data.cityAssignments[index - 1]?.region !== city.region">
|
||||||
@@ -673,40 +450,51 @@ onMounted(() => void loadPersonnel());
|
|||||||
</tr>
|
</tr>
|
||||||
<tr>
|
<tr>
|
||||||
<td
|
<td
|
||||||
class="nation-city"
|
colspan="2"
|
||||||
|
class="nation-city city-identity"
|
||||||
:style="{
|
:style="{
|
||||||
backgroundColor: data.nation.color,
|
backgroundColor: data.nation.color,
|
||||||
color: legacyNationTextColor(data.nation.color),
|
color: legacyNationTextColor(data.nation.color),
|
||||||
}"
|
}"
|
||||||
>
|
>
|
||||||
【{{ cityLevelMap[city.level] ?? '-' }}】
|
<small>【{{ cityLevelMap[city.level] ?? '-' }}】</small>
|
||||||
</td>
|
<strong>{{ city.name }}</strong>
|
||||||
<td
|
|
||||||
class="nation-city city-name"
|
|
||||||
:style="{
|
|
||||||
backgroundColor: data.nation.color,
|
|
||||||
color: legacyNationTextColor(data.nation.color),
|
|
||||||
}"
|
|
||||||
>
|
|
||||||
{{ city.name }}
|
|
||||||
</td>
|
</td>
|
||||||
<td
|
<td
|
||||||
v-for="level in cityOfficerLevels"
|
v-for="level in cityOfficerLevels"
|
||||||
:key="level"
|
:key="level"
|
||||||
|
class="city-officer-cell"
|
||||||
:class="{ locked: cityOfficerLocked(city, level) }"
|
:class="{ locked: cityOfficerLocked(city, level) }"
|
||||||
>
|
>
|
||||||
<template v-if="city.officers[level]">
|
<div class="city-officer-entry">
|
||||||
{{ city.officers[level]?.name }}({{ city.officers[level]?.belong }}년) 【{{
|
<span class="city-officer-copy">
|
||||||
city.officers[level]?.cityName ?? '-'
|
<strong>{{ city.officers[level]?.name ?? '공석' }}</strong>
|
||||||
}}】
|
<small v-if="city.officers[level]">
|
||||||
</template>
|
{{ city.officers[level]?.belong }}년 ·
|
||||||
<template v-else>-</template>
|
{{ city.officers[level]?.cityName ?? '-' }}
|
||||||
|
</small>
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
v-if="canManage && !cityOfficerLocked(city, level)"
|
||||||
|
type="button"
|
||||||
|
class="personnel-change-button city-change-button"
|
||||||
|
:aria-label="`${city.name} ${officerLabels[level]} 변경하기`"
|
||||||
|
aria-haspopup="dialog"
|
||||||
|
@click="selectionContext = { kind: 'city-general', level, cityId: city.id }"
|
||||||
|
>
|
||||||
|
변경하기
|
||||||
|
</button>
|
||||||
|
<small v-else-if="cityOfficerLocked(city, level)" class="personnel-lock-label">
|
||||||
|
변경 잠금
|
||||||
|
</small>
|
||||||
|
</div>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
</template>
|
</template>
|
||||||
<tr>
|
<tr>
|
||||||
<td colspan="5" class="legend">
|
<td colspan="5" class="legend">
|
||||||
※ <span class="orange">노란색</span>은 변경 불가능, 하얀색은 변경 가능 관직입니다.
|
※ 각 수뇌·도시 관직의 변경 버튼에서 후보 정보 확인과 임명을 한 번에 진행합니다.
|
||||||
|
<span class="orange">노란색</span>은 변경 불가능 관직입니다.
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
</tbody>
|
</tbody>
|
||||||
@@ -772,10 +560,8 @@ onMounted(() => void loadPersonnel());
|
|||||||
:description="selectionDescription"
|
:description="selectionDescription"
|
||||||
:items="selectionItems"
|
:items="selectionItems"
|
||||||
:selected-id="selectionId"
|
:selected-id="selectionId"
|
||||||
:search-placeholder="
|
search-placeholder="장수명·도시·관직·특성 검색"
|
||||||
selectionContext?.kind === 'city' ? '도시명·지역·재직자 검색' : '장수명·도시·관직·특성 검색'
|
vacancy-label="공석으로 두기"
|
||||||
"
|
|
||||||
:vacancy-label="selectionContext?.kind === 'city' ? null : '공석으로 두기'"
|
|
||||||
@cancel="selectionContext = null"
|
@cancel="selectionContext = null"
|
||||||
@select="applySelection"
|
@select="applySelection"
|
||||||
/>
|
/>
|
||||||
@@ -902,19 +688,77 @@ select[multiple] {
|
|||||||
.kick-control-column {
|
.kick-control-column {
|
||||||
width: 90%;
|
width: 90%;
|
||||||
}
|
}
|
||||||
.chief-status .role-cell {
|
.chief-entry-cell {
|
||||||
|
padding: 6px !important;
|
||||||
|
}
|
||||||
|
.chief-entry {
|
||||||
|
display: grid;
|
||||||
|
grid-template-areas: 'role icon copy action';
|
||||||
|
grid-template-columns: 82px 64px minmax(0, 1fr) 78px;
|
||||||
|
gap: 8px;
|
||||||
|
align-items: center;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.chief-entry-role {
|
||||||
|
grid-area: role;
|
||||||
|
border: 1px solid #507d5b;
|
||||||
|
padding: 7px 4px;
|
||||||
|
color: #fff;
|
||||||
|
background: #24472e;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
font-size: 18px;
|
font-size: 17px;
|
||||||
|
font-weight: 700;
|
||||||
}
|
}
|
||||||
.general-icon {
|
.general-icon {
|
||||||
|
grid-area: icon;
|
||||||
|
width: 64px;
|
||||||
height: 64px;
|
height: 64px;
|
||||||
background-repeat: no-repeat;
|
background-repeat: no-repeat;
|
||||||
background-position: center;
|
background-position: center;
|
||||||
background-size: 64px 64px;
|
background-size: 64px 64px;
|
||||||
}
|
}
|
||||||
.chief-name {
|
.chief-entry-copy {
|
||||||
width: 332px;
|
display: grid;
|
||||||
|
grid-area: copy;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.chief-entry-copy strong {
|
||||||
|
overflow: hidden;
|
||||||
font-size: 18px;
|
font-size: 18px;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.chief-entry-copy small {
|
||||||
|
overflow: hidden;
|
||||||
|
color: #c8c5bc;
|
||||||
|
font-size: 11px;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.personnel-change-button {
|
||||||
|
grid-area: action;
|
||||||
|
min-height: 34px;
|
||||||
|
border-color: #557d5e;
|
||||||
|
padding: 4px 8px;
|
||||||
|
background: #315b3d;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
.personnel-change-button:hover {
|
||||||
|
filter: none;
|
||||||
|
background: #3c704a;
|
||||||
|
border-color: #7ba286;
|
||||||
|
}
|
||||||
|
.personnel-lock-label {
|
||||||
|
grid-area: action;
|
||||||
|
color: #e7b64c;
|
||||||
|
text-align: center;
|
||||||
|
font-size: 11px;
|
||||||
|
}
|
||||||
|
.award-label {
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
.award-label-compact {
|
||||||
|
display: none;
|
||||||
}
|
}
|
||||||
.green-cell,
|
.green-cell,
|
||||||
.city-header,
|
.city-header,
|
||||||
@@ -943,187 +787,10 @@ select[multiple] {
|
|||||||
.red-bg {
|
.red-bg {
|
||||||
background: red;
|
background: red;
|
||||||
}
|
}
|
||||||
.appointment-table .appoint-label,
|
|
||||||
.permission-label {
|
.permission-label {
|
||||||
width: 98px;
|
width: 98px;
|
||||||
text-align: right;
|
text-align: right;
|
||||||
}
|
}
|
||||||
.appointment-table .appoint-control {
|
|
||||||
width: 398px;
|
|
||||||
}
|
|
||||||
.appointment-workspace-cell {
|
|
||||||
padding: 12px !important;
|
|
||||||
background: linear-gradient(rgb(7 9 7 / 72%), rgb(7 9 7 / 72%)), var(--sammo-texture-walnut);
|
|
||||||
}
|
|
||||||
.appointment-card-grid,
|
|
||||||
.city-appointment-grid {
|
|
||||||
display: grid;
|
|
||||||
gap: 12px;
|
|
||||||
}
|
|
||||||
.appointment-card-grid {
|
|
||||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
|
||||||
}
|
|
||||||
.city-appointment-grid {
|
|
||||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
|
||||||
}
|
|
||||||
.appointment-card {
|
|
||||||
min-width: 0;
|
|
||||||
padding: 12px;
|
|
||||||
background: linear-gradient(145deg, rgb(36 40 31 / 96%), rgb(16 18 15 / 98%));
|
|
||||||
border: 1px solid #555845;
|
|
||||||
border-radius: 10px;
|
|
||||||
box-shadow: 0 7px 18px rgb(0 0 0 / 28%);
|
|
||||||
}
|
|
||||||
.appointment-card-header {
|
|
||||||
display: flex;
|
|
||||||
gap: 8px;
|
|
||||||
align-items: baseline;
|
|
||||||
justify-content: space-between;
|
|
||||||
margin-bottom: 9px;
|
|
||||||
color: #e4cc8a;
|
|
||||||
}
|
|
||||||
.appointment-card-header > span {
|
|
||||||
font-size: 17px;
|
|
||||||
font-weight: 800;
|
|
||||||
}
|
|
||||||
.appointment-card-header small {
|
|
||||||
color: #aaa99f;
|
|
||||||
}
|
|
||||||
.appointment-card-header .appointment-lock {
|
|
||||||
color: #e6aa45;
|
|
||||||
}
|
|
||||||
.selection-trigger,
|
|
||||||
.appointment-readonly {
|
|
||||||
display: grid;
|
|
||||||
grid-template-columns: 48px minmax(0, 1fr) 18px;
|
|
||||||
gap: 9px;
|
|
||||||
align-items: center;
|
|
||||||
width: 100%;
|
|
||||||
min-width: 0;
|
|
||||||
min-height: 70px;
|
|
||||||
border: 1px solid #5a5e4d;
|
|
||||||
border-radius: 8px;
|
|
||||||
padding: 8px;
|
|
||||||
color: #f7f4eb;
|
|
||||||
background: #10120f;
|
|
||||||
text-align: left;
|
|
||||||
}
|
|
||||||
.selection-trigger {
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
.selection-trigger:hover {
|
|
||||||
filter: none;
|
|
||||||
background: #1d211a;
|
|
||||||
border-color: #9f9063;
|
|
||||||
}
|
|
||||||
.selection-trigger:focus-visible {
|
|
||||||
outline: 2px solid #f0cf75;
|
|
||||||
outline-offset: 2px;
|
|
||||||
}
|
|
||||||
.selection-trigger.compact {
|
|
||||||
grid-template-columns: 42px minmax(0, 1fr) 16px;
|
|
||||||
min-height: 62px;
|
|
||||||
margin-top: 7px;
|
|
||||||
}
|
|
||||||
.selection-trigger-portrait,
|
|
||||||
.selection-trigger-empty,
|
|
||||||
.selection-trigger-city {
|
|
||||||
width: 48px;
|
|
||||||
height: 48px;
|
|
||||||
border: 1px solid #5e6251;
|
|
||||||
border-radius: 8px;
|
|
||||||
background-color: #060706;
|
|
||||||
}
|
|
||||||
.selection-trigger-portrait {
|
|
||||||
background-position: center;
|
|
||||||
background-repeat: no-repeat;
|
|
||||||
background-size: cover;
|
|
||||||
}
|
|
||||||
.selection-trigger-empty,
|
|
||||||
.selection-trigger-city {
|
|
||||||
display: grid;
|
|
||||||
place-items: center;
|
|
||||||
color: #d9bf78;
|
|
||||||
background: radial-gradient(circle at 50% 30%, #363828, #0d0f0c 75%);
|
|
||||||
font: 700 22px/1 var(--sammo-font-sans);
|
|
||||||
}
|
|
||||||
.compact .selection-trigger-portrait,
|
|
||||||
.compact .selection-trigger-empty,
|
|
||||||
.compact .selection-trigger-city {
|
|
||||||
width: 42px;
|
|
||||||
height: 42px;
|
|
||||||
}
|
|
||||||
.selection-trigger-copy,
|
|
||||||
.appointment-readonly > span:last-child {
|
|
||||||
display: grid;
|
|
||||||
min-width: 0;
|
|
||||||
}
|
|
||||||
.selection-trigger-copy small,
|
|
||||||
.appointment-readonly small {
|
|
||||||
color: #aaa99f;
|
|
||||||
font-size: 10px;
|
|
||||||
}
|
|
||||||
.selection-trigger-copy strong,
|
|
||||||
.appointment-readonly strong {
|
|
||||||
overflow: hidden;
|
|
||||||
color: #fff;
|
|
||||||
font-size: 15px;
|
|
||||||
text-overflow: ellipsis;
|
|
||||||
white-space: nowrap;
|
|
||||||
}
|
|
||||||
.selection-trigger-copy > span:last-child {
|
|
||||||
overflow: hidden;
|
|
||||||
color: #c0c0b8;
|
|
||||||
font-size: 11px;
|
|
||||||
text-overflow: ellipsis;
|
|
||||||
white-space: nowrap;
|
|
||||||
}
|
|
||||||
.selection-trigger-chevron {
|
|
||||||
color: #cdb56e;
|
|
||||||
font-size: 26px;
|
|
||||||
text-align: center;
|
|
||||||
}
|
|
||||||
.appointment-readonly {
|
|
||||||
grid-template-columns: 48px minmax(0, 1fr);
|
|
||||||
color: #bbb;
|
|
||||||
background: #0d0e0c;
|
|
||||||
}
|
|
||||||
.selected-general-stats {
|
|
||||||
display: grid;
|
|
||||||
grid-template-columns: repeat(4, 1fr);
|
|
||||||
gap: 5px;
|
|
||||||
margin-top: 7px;
|
|
||||||
}
|
|
||||||
.selected-general-stats.compact {
|
|
||||||
grid-template-columns: repeat(3, 1fr);
|
|
||||||
}
|
|
||||||
.selected-general-stats > span {
|
|
||||||
display: flex;
|
|
||||||
gap: 4px;
|
|
||||||
justify-content: center;
|
|
||||||
padding: 4px 3px;
|
|
||||||
color: #aaa99f;
|
|
||||||
background: rgb(0 0 0 / 32%);
|
|
||||||
border-radius: 5px;
|
|
||||||
font-size: 10px;
|
|
||||||
}
|
|
||||||
.selected-general-stats strong {
|
|
||||||
color: #ead27f;
|
|
||||||
}
|
|
||||||
.appointment-submit {
|
|
||||||
width: 100%;
|
|
||||||
margin-top: 8px;
|
|
||||||
border-color: #4f7959;
|
|
||||||
color: #fff;
|
|
||||||
background: #376846;
|
|
||||||
font-weight: 800;
|
|
||||||
}
|
|
||||||
.appointment-submit:hover {
|
|
||||||
filter: brightness(1.15);
|
|
||||||
}
|
|
||||||
.city-appointment-card {
|
|
||||||
padding: 10px;
|
|
||||||
}
|
|
||||||
.legend {
|
.legend {
|
||||||
line-height: 18px;
|
line-height: 18px;
|
||||||
}
|
}
|
||||||
@@ -1131,7 +798,7 @@ select[multiple] {
|
|||||||
color: red;
|
color: red;
|
||||||
}
|
}
|
||||||
.orange,
|
.orange,
|
||||||
.locked {
|
.city-officer-cell.locked {
|
||||||
color: orange;
|
color: orange;
|
||||||
}
|
}
|
||||||
.permission-table select {
|
.permission-table select {
|
||||||
@@ -1145,6 +812,9 @@ select[multiple] {
|
|||||||
text-align: center;
|
text-align: center;
|
||||||
font-size: 18px;
|
font-size: 18px;
|
||||||
}
|
}
|
||||||
|
.city-header-compact {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
.city-header td:first-child {
|
.city-header td:first-child {
|
||||||
width: 158px;
|
width: 158px;
|
||||||
}
|
}
|
||||||
@@ -1153,13 +823,45 @@ select[multiple] {
|
|||||||
color: skyblue;
|
color: skyblue;
|
||||||
font-size: 18px;
|
font-size: 18px;
|
||||||
}
|
}
|
||||||
.nation-city {
|
.city-identity {
|
||||||
width: 78px;
|
display: table-cell;
|
||||||
|
width: 158px;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
font-size: 16.8px;
|
font-size: 16.8px;
|
||||||
}
|
}
|
||||||
.city-name {
|
.city-identity small,
|
||||||
text-align: right;
|
.city-identity strong {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
.city-identity small {
|
||||||
|
font-size: 10px;
|
||||||
|
}
|
||||||
|
.city-officer-cell {
|
||||||
|
padding: 5px !important;
|
||||||
|
vertical-align: middle;
|
||||||
|
}
|
||||||
|
.city-officer-entry,
|
||||||
|
.city-officer-copy {
|
||||||
|
display: grid;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.city-officer-entry {
|
||||||
|
grid-template-columns: minmax(0, 1fr) auto;
|
||||||
|
gap: 7px;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
.city-officer-copy strong,
|
||||||
|
.city-officer-copy small {
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.city-officer-copy small {
|
||||||
|
color: #c9c6bd;
|
||||||
|
font-size: 10px;
|
||||||
|
}
|
||||||
|
.city-change-button {
|
||||||
|
min-width: 70px;
|
||||||
}
|
}
|
||||||
.kick-label {
|
.kick-label {
|
||||||
width: 498px;
|
width: 498px;
|
||||||
@@ -1184,4 +886,113 @@ select[multiple] {
|
|||||||
margin: 0;
|
margin: 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@media (max-width: 620px) {
|
||||||
|
.legacy-office,
|
||||||
|
.legacy-table,
|
||||||
|
.feedback,
|
||||||
|
.loading {
|
||||||
|
width: min(500px, 100vw);
|
||||||
|
}
|
||||||
|
.heading-table {
|
||||||
|
margin-bottom: 10px;
|
||||||
|
}
|
||||||
|
.nation-heading {
|
||||||
|
font-size: 18px;
|
||||||
|
}
|
||||||
|
.chief-entry-cell {
|
||||||
|
padding: 4px !important;
|
||||||
|
}
|
||||||
|
.chief-entry {
|
||||||
|
grid-template-areas:
|
||||||
|
'icon copy'
|
||||||
|
'role action';
|
||||||
|
grid-template-columns: 48px minmax(0, 1fr);
|
||||||
|
gap: 5px 7px;
|
||||||
|
}
|
||||||
|
.chief-entry-role {
|
||||||
|
padding: 5px 2px;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
.general-icon {
|
||||||
|
width: 48px;
|
||||||
|
height: 48px;
|
||||||
|
background-size: 48px 48px;
|
||||||
|
}
|
||||||
|
.chief-entry-copy strong {
|
||||||
|
font-size: 15px;
|
||||||
|
}
|
||||||
|
.chief-entry-copy small {
|
||||||
|
font-size: 9px;
|
||||||
|
}
|
||||||
|
.personnel-change-button {
|
||||||
|
min-height: 30px;
|
||||||
|
padding: 3px 5px;
|
||||||
|
font-size: 11px;
|
||||||
|
line-height: 18px;
|
||||||
|
}
|
||||||
|
.personnel-lock-label {
|
||||||
|
font-size: 10px;
|
||||||
|
}
|
||||||
|
.award-label {
|
||||||
|
font-size: 11px;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.award-label-full {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
.award-label-compact {
|
||||||
|
display: inline;
|
||||||
|
}
|
||||||
|
select[multiple] {
|
||||||
|
width: calc(100% - 58px);
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.city-header td {
|
||||||
|
height: 26px;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
.city-header-full {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
.city-header-compact {
|
||||||
|
display: inline;
|
||||||
|
}
|
||||||
|
.region-heading {
|
||||||
|
height: 25px;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
.city-identity {
|
||||||
|
width: 16%;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
.city-identity small {
|
||||||
|
font-size: 8px;
|
||||||
|
}
|
||||||
|
.city-officer-cell {
|
||||||
|
padding: 4px !important;
|
||||||
|
}
|
||||||
|
.city-officer-entry {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
gap: 4px;
|
||||||
|
}
|
||||||
|
.city-officer-copy strong {
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
.city-officer-copy small {
|
||||||
|
font-size: 9px;
|
||||||
|
}
|
||||||
|
.city-change-button {
|
||||||
|
width: 100%;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.legend {
|
||||||
|
font-size: 10px;
|
||||||
|
}
|
||||||
|
.kick-label {
|
||||||
|
width: auto;
|
||||||
|
}
|
||||||
|
.footer-table {
|
||||||
|
margin-top: 10px;
|
||||||
|
}
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -44,7 +44,11 @@ import {
|
|||||||
writeProfileReleaseSource,
|
writeProfileReleaseSource,
|
||||||
type ProfileReleaseSource,
|
type ProfileReleaseSource,
|
||||||
} from './profileReleaseSource.js';
|
} from './profileReleaseSource.js';
|
||||||
import type { GitWorkspaceManager } from './workspaceManager.js';
|
import {
|
||||||
|
DEFAULT_MANAGED_WORKSPACE_KEEP_NEWEST,
|
||||||
|
DEFAULT_MANAGED_WORKSPACE_RETENTION_MS,
|
||||||
|
type GitWorkspaceManager,
|
||||||
|
} from './workspaceManager.js';
|
||||||
import type { AdminSeedUser } from './seedProfileDatabase.js';
|
import type { AdminSeedUser } from './seedProfileDatabase.js';
|
||||||
import { assertReleaseComponents, readReleaseManifest } from './releaseManifest.js';
|
import { assertReleaseComponents, readReleaseManifest } from './releaseManifest.js';
|
||||||
|
|
||||||
@@ -73,6 +77,8 @@ export interface GatewayOrchestratorOptions {
|
|||||||
cancelGame?: typeof defaultCancelGame;
|
cancelGame?: typeof defaultCancelGame;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const WORKSPACE_CLEANUP_INTERVAL_MS = 24 * 60 * 60 * 1_000;
|
||||||
|
|
||||||
export interface ProfileRuntimeState {
|
export interface ProfileRuntimeState {
|
||||||
frontendRunning: boolean;
|
frontendRunning: boolean;
|
||||||
apiRunning: boolean;
|
apiRunning: boolean;
|
||||||
@@ -629,11 +635,13 @@ export class GatewayOrchestrator implements GatewayOrchestratorHandle {
|
|||||||
private scheduleTimer?: NodeJS.Timeout;
|
private scheduleTimer?: NodeJS.Timeout;
|
||||||
private buildTimer?: NodeJS.Timeout;
|
private buildTimer?: NodeJS.Timeout;
|
||||||
private adminActionTimer?: NodeJS.Timeout;
|
private adminActionTimer?: NodeJS.Timeout;
|
||||||
|
private workspaceCleanupTimer?: NodeJS.Timeout;
|
||||||
private reconcileInFlight = false;
|
private reconcileInFlight = false;
|
||||||
private scheduleInFlight = false;
|
private scheduleInFlight = false;
|
||||||
private buildInFlight = false;
|
private buildInFlight = false;
|
||||||
private adminActionInFlight = false;
|
private adminActionInFlight = false;
|
||||||
private operationInFlight = false;
|
private operationInFlight = false;
|
||||||
|
private workspaceCleanupInFlight = false;
|
||||||
private activeOperationAbortSignal?: AbortSignal;
|
private activeOperationAbortSignal?: AbortSignal;
|
||||||
private readonly resetInFlight = new Set<string>();
|
private readonly resetInFlight = new Set<string>();
|
||||||
private readonly operationLeaseOwner = randomUUID();
|
private readonly operationLeaseOwner = randomUUID();
|
||||||
@@ -714,7 +722,7 @@ export class GatewayOrchestrator implements GatewayOrchestratorHandle {
|
|||||||
start(): void {
|
start(): void {
|
||||||
this.stopping = false;
|
this.stopping = false;
|
||||||
this.trackTask(this.reconcileNow());
|
this.trackTask(this.reconcileNow());
|
||||||
this.trackTask(this.runOperationsNow());
|
this.trackTask(this.runOperationsNow().then(() => this.cleanupWorkspacesScheduled()));
|
||||||
this.trackTask(this.runAdminActionsNow());
|
this.trackTask(this.runAdminActionsNow());
|
||||||
this.reconcileTimer = setInterval(() => this.trackTask(this.reconcileNow()), this.reconcileIntervalMs);
|
this.reconcileTimer = setInterval(() => this.trackTask(this.reconcileNow()), this.reconcileIntervalMs);
|
||||||
this.scheduleTimer = setInterval(() => this.trackTask(this.runScheduleNow()), this.scheduleIntervalMs);
|
this.scheduleTimer = setInterval(() => this.trackTask(this.runScheduleNow()), this.scheduleIntervalMs);
|
||||||
@@ -723,6 +731,10 @@ export class GatewayOrchestrator implements GatewayOrchestratorHandle {
|
|||||||
this.trackTask(this.runOperationsNow());
|
this.trackTask(this.runOperationsNow());
|
||||||
this.trackTask(this.runAdminActionsNow());
|
this.trackTask(this.runAdminActionsNow());
|
||||||
}, this.adminActionIntervalMs);
|
}, this.adminActionIntervalMs);
|
||||||
|
this.workspaceCleanupTimer = setInterval(
|
||||||
|
() => this.trackTask(this.cleanupWorkspacesScheduled()),
|
||||||
|
WORKSPACE_CLEANUP_INTERVAL_MS
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async stop(): Promise<void> {
|
async stop(): Promise<void> {
|
||||||
@@ -747,6 +759,9 @@ export class GatewayOrchestrator implements GatewayOrchestratorHandle {
|
|||||||
if (this.adminActionTimer) {
|
if (this.adminActionTimer) {
|
||||||
clearInterval(this.adminActionTimer);
|
clearInterval(this.adminActionTimer);
|
||||||
}
|
}
|
||||||
|
if (this.workspaceCleanupTimer) {
|
||||||
|
clearInterval(this.workspaceCleanupTimer);
|
||||||
|
}
|
||||||
await Promise.allSettled([...this.inFlightTasks]);
|
await Promise.allSettled([...this.inFlightTasks]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -903,7 +918,7 @@ export class GatewayOrchestrator implements GatewayOrchestratorHandle {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async runBuildQueueNow(): Promise<void> {
|
async runBuildQueueNow(): Promise<void> {
|
||||||
if (this.stopping || this.buildInFlight) {
|
if (this.stopping || this.buildInFlight || this.workspaceCleanupInFlight) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
this.buildInFlight = true;
|
this.buildInFlight = true;
|
||||||
@@ -965,7 +980,7 @@ export class GatewayOrchestrator implements GatewayOrchestratorHandle {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async runOperationsNow(): Promise<void> {
|
async runOperationsNow(): Promise<void> {
|
||||||
if (this.stopping || this.operationInFlight || this.buildInFlight) {
|
if (this.stopping || this.operationInFlight || this.buildInFlight || this.workspaceCleanupInFlight) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
this.operationInFlight = true;
|
this.operationInFlight = true;
|
||||||
@@ -2160,83 +2175,56 @@ export class GatewayOrchestrator implements GatewayOrchestratorHandle {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async cleanupStaleWorkspaces(): Promise<{ removed: string[]; skipped: string[] }> {
|
async cleanupStaleWorkspaces(): Promise<{ removed: string[]; skipped: string[] }> {
|
||||||
const profiles = await this.repository.listProfiles();
|
if (this.buildInFlight || this.operationInFlight || this.workspaceCleanupInFlight) {
|
||||||
const cutoff = this.computeCutoffDate(6);
|
const managedWorkspaces = await this.workspaceManager.listManagedWorkspaces();
|
||||||
const workspaceMap = new Map<string, { profileNames: string[]; lastUsedAt?: Date; hasActiveBuild: boolean }>();
|
return { removed: [], skipped: managedWorkspaces.map((workspace) => workspace.root) };
|
||||||
for (const profile of profiles) {
|
}
|
||||||
const workspace = profile.buildWorkspace;
|
this.workspaceCleanupInFlight = true;
|
||||||
if (!workspace) {
|
try {
|
||||||
continue;
|
const managedWorkspaces = await this.workspaceManager.listManagedWorkspaces();
|
||||||
}
|
const profiles = await this.repository.listProfiles();
|
||||||
const entry = workspaceMap.get(workspace) ?? {
|
const protectedWorkspaces = new Set<string>();
|
||||||
profileNames: [],
|
for (const profile of profiles) {
|
||||||
lastUsedAt: undefined,
|
if (profile.buildWorkspace) {
|
||||||
hasActiveBuild: false,
|
protectedWorkspaces.add(path.resolve(profile.buildWorkspace));
|
||||||
};
|
}
|
||||||
entry.profileNames.push(profile.profileName);
|
if (profile.buildCommitSha && (profile.buildStatus === 'RUNNING' || profile.buildStatus === 'QUEUED')) {
|
||||||
if (profile.buildLastUsedAt) {
|
protectedWorkspaces.add(
|
||||||
const usedAt = new Date(profile.buildLastUsedAt);
|
path.resolve(this.workspaceManager.workspacePathForCommit(profile.buildCommitSha))
|
||||||
if (!entry.lastUsedAt || usedAt > entry.lastUsedAt) {
|
);
|
||||||
entry.lastUsedAt = usedAt;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (profile.buildStatus === 'RUNNING' || profile.buildStatus === 'QUEUED') {
|
|
||||||
entry.hasActiveBuild = true;
|
|
||||||
}
|
|
||||||
workspaceMap.set(workspace, entry);
|
|
||||||
}
|
|
||||||
|
|
||||||
const activeProcesses = (await this.processManager.list()).filter((process) =>
|
const activeProcesses = (await this.processManager.list()).filter((process) =>
|
||||||
isRuntimeProcessActive(process.status)
|
isRuntimeProcessActive(process.status)
|
||||||
);
|
|
||||||
const referencedWorkspaces = new Set<string>();
|
|
||||||
for (const [workspace, entry] of workspaceMap.entries()) {
|
|
||||||
const profileProcessNames = new Set(
|
|
||||||
entry.profileNames.flatMap((profileName) => [
|
|
||||||
buildProcessName(profileName, 'frontend'),
|
|
||||||
buildProcessName(profileName, 'api'),
|
|
||||||
buildProcessName(profileName, 'daemon'),
|
|
||||||
buildProcessName(profileName, 'auction'),
|
|
||||||
buildProcessName(profileName, 'battle-sim'),
|
|
||||||
buildProcessName(profileName, 'tournament'),
|
|
||||||
])
|
|
||||||
);
|
);
|
||||||
if (
|
for (const workspace of managedWorkspaces) {
|
||||||
activeProcesses.some(
|
if (
|
||||||
(process) =>
|
activeProcesses.some(
|
||||||
profileProcessNames.has(process.name) ||
|
(process) =>
|
||||||
isPathInside(process.cwd, workspace) ||
|
isPathInside(process.cwd, workspace.root) || isPathInside(process.script, workspace.root)
|
||||||
isPathInside(process.script, workspace)
|
)
|
||||||
)
|
) {
|
||||||
) {
|
protectedWorkspaces.add(workspace.root);
|
||||||
referencedWorkspaces.add(workspace);
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
const removed: string[] = [];
|
return await this.workspaceManager.cleanup({
|
||||||
const skipped: string[] = [];
|
protectedPaths: [...protectedWorkspaces],
|
||||||
for (const [workspace, entry] of workspaceMap.entries()) {
|
retentionMs: DEFAULT_MANAGED_WORKSPACE_RETENTION_MS,
|
||||||
if (!entry.lastUsedAt || entry.hasActiveBuild || referencedWorkspaces.has(workspace)) {
|
keepNewest: DEFAULT_MANAGED_WORKSPACE_KEEP_NEWEST,
|
||||||
skipped.push(workspace);
|
});
|
||||||
continue;
|
} finally {
|
||||||
}
|
this.workspaceCleanupInFlight = false;
|
||||||
if (entry.lastUsedAt > cutoff) {
|
|
||||||
skipped.push(workspace);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
await this.workspaceManager.remove(workspace);
|
|
||||||
await this.repository.clearWorkspaceUsage(entry.profileNames);
|
|
||||||
removed.push(workspace);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return { removed, skipped };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private computeCutoffDate(months: number): Date {
|
private async cleanupWorkspacesScheduled(): Promise<void> {
|
||||||
const date = this.now();
|
if (this.stopping || this.buildInFlight || this.operationInFlight || this.workspaceCleanupInFlight) return;
|
||||||
const cutoff = new Date(date);
|
const result = await this.cleanupStaleWorkspaces();
|
||||||
cutoff.setMonth(cutoff.getMonth() - months);
|
if (result.removed.length > 0) {
|
||||||
return cutoff;
|
console.info(`[gateway-orchestrator] removed ${result.removed.length} stale profile worktrees`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async startProfile(profile: GatewayProfileRecord, assertLease?: () => Promise<void>): Promise<boolean> {
|
private async startProfile(profile: GatewayProfileRecord, assertLease?: () => Promise<void>): Promise<boolean> {
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ export interface WorkspaceManagerOptions {
|
|||||||
repoRoot: string;
|
repoRoot: string;
|
||||||
worktreeRoot: string;
|
worktreeRoot: string;
|
||||||
baseEnv?: Record<string, string>;
|
baseEnv?: Record<string, string>;
|
||||||
|
now?: () => Date;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface WorkspaceInfo {
|
export interface WorkspaceInfo {
|
||||||
@@ -14,6 +15,26 @@ export interface WorkspaceInfo {
|
|||||||
needsInstall: boolean;
|
needsInstall: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ManagedWorkspaceInfo {
|
||||||
|
root: string;
|
||||||
|
commitSha: string;
|
||||||
|
lastUsedAt: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ManagedWorkspaceCleanupOptions {
|
||||||
|
protectedPaths?: readonly string[];
|
||||||
|
retentionMs: number;
|
||||||
|
keepNewest: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ManagedWorkspaceCleanupResult {
|
||||||
|
removed: string[];
|
||||||
|
skipped: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DEFAULT_MANAGED_WORKSPACE_RETENTION_MS = 24 * 60 * 60 * 1_000;
|
||||||
|
export const DEFAULT_MANAGED_WORKSPACE_KEEP_NEWEST = 2;
|
||||||
|
|
||||||
const runGit = (args: string[], cwd: string, env?: Record<string, string>): Promise<{ ok: boolean; output: string }> =>
|
const runGit = (args: string[], cwd: string, env?: Record<string, string>): Promise<{ ok: boolean; output: string }> =>
|
||||||
new Promise((resolve) => {
|
new Promise((resolve) => {
|
||||||
const child = spawn('git', args, {
|
const child = spawn('git', args, {
|
||||||
@@ -58,11 +79,13 @@ export class GitWorkspaceManager {
|
|||||||
private readonly repoRoot: string;
|
private readonly repoRoot: string;
|
||||||
private readonly worktreeRoot: string;
|
private readonly worktreeRoot: string;
|
||||||
private readonly baseEnv?: Record<string, string>;
|
private readonly baseEnv?: Record<string, string>;
|
||||||
|
private readonly now: () => Date;
|
||||||
|
|
||||||
constructor(options: WorkspaceManagerOptions) {
|
constructor(options: WorkspaceManagerOptions) {
|
||||||
this.repoRoot = options.repoRoot;
|
this.repoRoot = options.repoRoot;
|
||||||
this.worktreeRoot = options.worktreeRoot;
|
this.worktreeRoot = options.worktreeRoot;
|
||||||
this.baseEnv = options.baseEnv;
|
this.baseEnv = options.baseEnv;
|
||||||
|
this.now = options.now ?? (() => new Date());
|
||||||
}
|
}
|
||||||
|
|
||||||
async resolveCommit(sourceMode: 'BRANCH' | 'COMMIT', sourceRef: string): Promise<string> {
|
async resolveCommit(sourceMode: 'BRANCH' | 'COMMIT', sourceRef: string): Promise<string> {
|
||||||
@@ -124,6 +147,8 @@ export class GitWorkspaceManager {
|
|||||||
} else {
|
} else {
|
||||||
await this.assertReusableWorkspace(workspacePath, commitSha);
|
await this.assertReusableWorkspace(workspacePath, commitSha);
|
||||||
}
|
}
|
||||||
|
const usedAt = this.now();
|
||||||
|
fs.utimesSync(workspacePath, usedAt, usedAt);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
root: workspacePath,
|
root: workspacePath,
|
||||||
@@ -138,13 +163,100 @@ export class GitWorkspaceManager {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
await this.assertRegisteredWorkspace(resolved);
|
await this.assertRegisteredWorkspace(resolved);
|
||||||
|
const status = await runGit(['status', '--porcelain'], resolved, this.baseEnv);
|
||||||
|
if (!status.ok) {
|
||||||
|
throw new Error(status.output || 'Failed to inspect managed workspace.');
|
||||||
|
}
|
||||||
|
if (status.output.trim()) {
|
||||||
|
throw new Error('Managed workspace has uncommitted changes.');
|
||||||
|
}
|
||||||
const result = await runGit(['worktree', 'remove', '--force', resolved], this.repoRoot, this.baseEnv);
|
const result = await runGit(['worktree', 'remove', '--force', resolved], this.repoRoot, this.baseEnv);
|
||||||
if (!result.ok) {
|
if (!result.ok) {
|
||||||
fs.rmSync(resolved, { recursive: true, force: true });
|
throw new Error(result.output || 'Failed to remove git worktree.');
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
workspacePathForCommit(commitSha: string): string {
|
||||||
|
if (!COMMIT_SHA_PATTERN.test(commitSha)) {
|
||||||
|
throw new Error('Invalid commit SHA.');
|
||||||
|
}
|
||||||
|
return path.join(this.worktreeRoot, commitSha);
|
||||||
|
}
|
||||||
|
|
||||||
|
async listManagedWorkspaces(): Promise<ManagedWorkspaceInfo[]> {
|
||||||
|
const listed = await runGit(['worktree', 'list', '--porcelain'], this.repoRoot, this.baseEnv);
|
||||||
|
if (!listed.ok) {
|
||||||
|
throw new Error(listed.output || 'Failed to inspect git worktrees.');
|
||||||
|
}
|
||||||
|
const workspaces: ManagedWorkspaceInfo[] = [];
|
||||||
|
for (const block of listed.output.split(/\n\n+/)) {
|
||||||
|
const lines = block.split('\n');
|
||||||
|
const worktreeLine = lines.find((line) => line.startsWith('worktree '));
|
||||||
|
const headLine = lines.find((line) => line.startsWith('HEAD '));
|
||||||
|
if (!worktreeLine || !headLine) continue;
|
||||||
|
const workspacePath = path.resolve(worktreeLine.slice('worktree '.length));
|
||||||
|
const commitSha = headLine.slice('HEAD '.length);
|
||||||
|
try {
|
||||||
|
this.assertManagedWorkspacePath(workspacePath);
|
||||||
|
} catch {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!COMMIT_SHA_PATTERN.test(commitSha) || !fs.existsSync(workspacePath)) continue;
|
||||||
|
workspaces.push({
|
||||||
|
root: workspacePath,
|
||||||
|
commitSha,
|
||||||
|
lastUsedAt: fs.statSync(workspacePath).mtime,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return workspaces;
|
||||||
|
}
|
||||||
|
|
||||||
|
async cleanup(options: ManagedWorkspaceCleanupOptions): Promise<ManagedWorkspaceCleanupResult> {
|
||||||
|
if (!Number.isFinite(options.retentionMs) || options.retentionMs < 0) {
|
||||||
|
throw new Error('Workspace retention must be a non-negative duration.');
|
||||||
|
}
|
||||||
|
if (!Number.isInteger(options.keepNewest) || options.keepNewest < 0) {
|
||||||
|
throw new Error('Workspace keepNewest must be a non-negative integer.');
|
||||||
|
}
|
||||||
|
const protectedPaths = new Set((options.protectedPaths ?? []).map((item) => path.resolve(item)));
|
||||||
|
const workspaces = await this.listManagedWorkspaces();
|
||||||
|
const unprotectedNewest = [...workspaces]
|
||||||
|
.filter((workspace) => !protectedPaths.has(workspace.root))
|
||||||
|
.sort((left, right) => right.lastUsedAt.getTime() - left.lastUsedAt.getTime())
|
||||||
|
.slice(0, options.keepNewest);
|
||||||
|
const retainedNewestPaths = new Set(unprotectedNewest.map((workspace) => workspace.root));
|
||||||
|
const cutoff = this.now().getTime() - options.retentionMs;
|
||||||
|
const removed: string[] = [];
|
||||||
|
const skipped: string[] = [];
|
||||||
|
|
||||||
|
for (const workspace of workspaces) {
|
||||||
|
if (
|
||||||
|
protectedPaths.has(workspace.root) ||
|
||||||
|
retainedNewestPaths.has(workspace.root) ||
|
||||||
|
workspace.lastUsedAt.getTime() > cutoff
|
||||||
|
) {
|
||||||
|
skipped.push(workspace.root);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if (await this.remove(workspace.root)) {
|
||||||
|
removed.push(workspace.root);
|
||||||
|
} else {
|
||||||
|
skipped.push(workspace.root);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
skipped.push(workspace.root);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const pruned = await runGit(['worktree', 'prune', '--expire', 'now'], this.repoRoot, this.baseEnv);
|
||||||
|
if (!pruned.ok) {
|
||||||
|
throw new Error(pruned.output || 'Failed to prune git worktree metadata.');
|
||||||
|
}
|
||||||
|
return { removed, skipped };
|
||||||
|
}
|
||||||
|
|
||||||
private assertManagedWorkspacePath(workspacePath: string): string {
|
private assertManagedWorkspacePath(workspacePath: string): string {
|
||||||
const resolved = path.resolve(workspacePath);
|
const resolved = path.resolve(workspacePath);
|
||||||
const root = path.resolve(this.worktreeRoot);
|
const root = path.resolve(this.worktreeRoot);
|
||||||
|
|||||||
@@ -1,15 +1,23 @@
|
|||||||
|
import path from 'node:path';
|
||||||
|
|
||||||
import { describe, expect, it } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
|
|
||||||
import { GatewayOrchestrator } from '../src/orchestrator/gatewayOrchestrator.js';
|
import { GatewayOrchestrator } from '../src/orchestrator/gatewayOrchestrator.js';
|
||||||
import type { ProcessManager } from '../src/orchestrator/processManager.js';
|
import type { ProcessManager } from '../src/orchestrator/processManager.js';
|
||||||
import type { GatewayProfileRecord, GatewayProfileRepository } from '../src/orchestrator/profileRepository.js';
|
import type { GatewayProfileRecord, GatewayProfileRepository } from '../src/orchestrator/profileRepository.js';
|
||||||
import type { GitWorkspaceManager } from '../src/orchestrator/workspaceManager.js';
|
import {
|
||||||
|
DEFAULT_MANAGED_WORKSPACE_KEEP_NEWEST,
|
||||||
|
DEFAULT_MANAGED_WORKSPACE_RETENTION_MS,
|
||||||
|
type GitWorkspaceManager,
|
||||||
|
type ManagedWorkspaceCleanupOptions,
|
||||||
|
} from '../src/orchestrator/workspaceManager.js';
|
||||||
|
|
||||||
|
const COMMIT_SHA = '0123456789abcdef0123456789abcdef01234567';
|
||||||
const oldUsage = '2025-01-01T00:00:00.000Z';
|
const oldUsage = '2025-01-01T00:00:00.000Z';
|
||||||
|
|
||||||
const makeProfile = (
|
const makeProfile = (
|
||||||
profileName: string,
|
profileName: string,
|
||||||
workspace: string,
|
workspace: string | undefined,
|
||||||
overrides: Partial<GatewayProfileRecord> = {}
|
overrides: Partial<GatewayProfileRecord> = {}
|
||||||
): GatewayProfileRecord => ({
|
): GatewayProfileRecord => ({
|
||||||
profileName,
|
profileName,
|
||||||
@@ -20,7 +28,7 @@ const makeProfile = (
|
|||||||
apiPort: 15_003,
|
apiPort: 15_003,
|
||||||
status: 'RUNNING',
|
status: 'RUNNING',
|
||||||
buildStatus: 'SUCCEEDED',
|
buildStatus: 'SUCCEEDED',
|
||||||
buildCommitSha: '0123456789abcdef0123456789abcdef01234567',
|
buildCommitSha: COMMIT_SHA,
|
||||||
buildWorkspace: workspace,
|
buildWorkspace: workspace,
|
||||||
buildLastUsedAt: oldUsage,
|
buildLastUsedAt: oldUsage,
|
||||||
meta: {},
|
meta: {},
|
||||||
@@ -32,17 +40,10 @@ const makeProfile = (
|
|||||||
const createHarness = (
|
const createHarness = (
|
||||||
profiles: GatewayProfileRecord[],
|
profiles: GatewayProfileRecord[],
|
||||||
processes: Awaited<ReturnType<ProcessManager['list']>>,
|
processes: Awaited<ReturnType<ProcessManager['list']>>,
|
||||||
workspaceExists = true
|
managedPaths: string[]
|
||||||
) => {
|
) => {
|
||||||
const removeCalls: string[] = [];
|
const cleanupCalls: ManagedWorkspaceCleanupOptions[] = [];
|
||||||
const clearedProfiles: string[][] = [];
|
const repository = { listProfiles: async () => profiles } as unknown as GatewayProfileRepository;
|
||||||
|
|
||||||
const repository = {
|
|
||||||
listProfiles: async () => profiles,
|
|
||||||
clearWorkspaceUsage: async (profileNames: string[]) => {
|
|
||||||
clearedProfiles.push(profileNames);
|
|
||||||
},
|
|
||||||
} as unknown as GatewayProfileRepository;
|
|
||||||
const processManager: ProcessManager = {
|
const processManager: ProcessManager = {
|
||||||
list: async () => processes,
|
list: async () => processes,
|
||||||
start: async () => {},
|
start: async () => {},
|
||||||
@@ -50,9 +51,16 @@ const createHarness = (
|
|||||||
delete: async () => {},
|
delete: async () => {},
|
||||||
};
|
};
|
||||||
const workspaceManager = {
|
const workspaceManager = {
|
||||||
remove: async (workspace: string) => {
|
listManagedWorkspaces: async () =>
|
||||||
removeCalls.push(workspace);
|
managedPaths.map((root) => ({ root, commitSha: path.basename(root), lastUsedAt: new Date(oldUsage) })),
|
||||||
return workspaceExists;
|
workspacePathForCommit: (commitSha: string) => `/srv/sammo/worktrees/${commitSha}`,
|
||||||
|
cleanup: async (options: ManagedWorkspaceCleanupOptions) => {
|
||||||
|
cleanupCalls.push(options);
|
||||||
|
const protectedPaths = new Set(options.protectedPaths);
|
||||||
|
return {
|
||||||
|
removed: managedPaths.filter((workspace) => !protectedPaths.has(workspace)),
|
||||||
|
skipped: managedPaths.filter((workspace) => protectedPaths.has(workspace)),
|
||||||
|
};
|
||||||
},
|
},
|
||||||
} as unknown as GitWorkspaceManager;
|
} as unknown as GitWorkspaceManager;
|
||||||
const orchestrator = new GatewayOrchestrator({
|
const orchestrator = new GatewayOrchestrator({
|
||||||
@@ -70,126 +78,67 @@ const createHarness = (
|
|||||||
scheduleIntervalMs: 60_000,
|
scheduleIntervalMs: 60_000,
|
||||||
buildIntervalMs: 60_000,
|
buildIntervalMs: 60_000,
|
||||||
adminActionIntervalMs: 60_000,
|
adminActionIntervalMs: 60_000,
|
||||||
now: () => new Date('2026-07-30T00:00:00.000Z'),
|
|
||||||
});
|
});
|
||||||
|
return { orchestrator, cleanupCalls };
|
||||||
return { orchestrator, removeCalls, clearedProfiles };
|
|
||||||
};
|
};
|
||||||
|
|
||||||
describe('GatewayOrchestrator workspace cleanup', () => {
|
describe('GatewayOrchestrator workspace cleanup', () => {
|
||||||
it('skips a workspace referenced by any active process cwd', async () => {
|
it('always protects every workspace currently selected by a profile', async () => {
|
||||||
const workspace = '/srv/sammo/worktrees/active';
|
const current = '/srv/sammo/worktrees/current';
|
||||||
|
const stale = '/srv/sammo/worktrees/stale';
|
||||||
|
const harness = createHarness([makeProfile('che:default', current)], [], [current, stale]);
|
||||||
|
|
||||||
|
await expect(harness.orchestrator.cleanupStaleWorkspaces()).resolves.toEqual({
|
||||||
|
removed: [stale],
|
||||||
|
skipped: [current],
|
||||||
|
});
|
||||||
|
expect(harness.cleanupCalls[0]).toMatchObject({
|
||||||
|
retentionMs: DEFAULT_MANAGED_WORKSPACE_RETENTION_MS,
|
||||||
|
keepNewest: DEFAULT_MANAGED_WORKSPACE_KEEP_NEWEST,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('protects the commit target of queued and running builds before the profile reference changes', async () => {
|
||||||
|
const target = `/srv/sammo/worktrees/${COMMIT_SHA}`;
|
||||||
|
const harness = createHarness([makeProfile('che:default', undefined, { buildStatus: 'QUEUED' })], [], [target]);
|
||||||
|
|
||||||
|
await expect(harness.orchestrator.cleanupStaleWorkspaces()).resolves.toEqual({
|
||||||
|
removed: [],
|
||||||
|
skipped: [target],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('protects an otherwise orphaned workspace referenced by any active process cwd or script', async () => {
|
||||||
|
const cwdWorkspace = '/srv/sammo/worktrees/cwd-orphan';
|
||||||
|
const scriptWorkspace = '/srv/sammo/worktrees/script-orphan';
|
||||||
|
const stale = '/srv/sammo/worktrees/stale';
|
||||||
const harness = createHarness(
|
const harness = createHarness(
|
||||||
[makeProfile('che:default', workspace)],
|
[],
|
||||||
[
|
[
|
||||||
{
|
{ name: 'custom-build', status: 'online', cwd: `${cwdWorkspace}/app/game-api` },
|
||||||
name: 'sammo:che:default:frontend',
|
{ name: 'custom-worker', status: 'launching', script: `${scriptWorkspace}/dist/index.js` },
|
||||||
status: 'online',
|
{ name: 'stopped-worker', status: 'stopped', cwd: `${stale}/app/game-api` },
|
||||||
cwd: `${workspace}/app/game-frontend`,
|
],
|
||||||
},
|
[cwdWorkspace, scriptWorkspace, stale]
|
||||||
]
|
|
||||||
);
|
);
|
||||||
|
|
||||||
await expect(harness.orchestrator.cleanupStaleWorkspaces()).resolves.toEqual({
|
await expect(harness.orchestrator.cleanupStaleWorkspaces()).resolves.toEqual({
|
||||||
removed: [],
|
removed: [stale],
|
||||||
skipped: [workspace],
|
skipped: [cwdWorkspace, scriptWorkspace],
|
||||||
});
|
});
|
||||||
expect(harness.removeCalls).toEqual([]);
|
|
||||||
expect(harness.clearedProfiles).toEqual([]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('skips a workspace when only one profile process is active and cwd metadata is absent', async () => {
|
it('does not confuse sibling path prefixes with an active workspace reference', async () => {
|
||||||
const workspace = '/srv/sammo/worktrees/partial';
|
|
||||||
const harness = createHarness(
|
|
||||||
[makeProfile('che:default', workspace)],
|
|
||||||
[{ name: 'sammo:che:default:tournament-worker', status: 'launching' }]
|
|
||||||
);
|
|
||||||
|
|
||||||
await expect(harness.orchestrator.cleanupStaleWorkspaces()).resolves.toEqual({
|
|
||||||
removed: [],
|
|
||||||
skipped: [workspace],
|
|
||||||
});
|
|
||||||
expect(harness.removeCalls).toEqual([]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('skips a workspace referenced only by an active process script', async () => {
|
|
||||||
const workspace = '/srv/sammo/worktrees/script-reference';
|
|
||||||
const harness = createHarness(
|
|
||||||
[makeProfile('che:default', workspace)],
|
|
||||||
[
|
|
||||||
{
|
|
||||||
name: 'unregistered-worker-name',
|
|
||||||
status: 'online',
|
|
||||||
script: `${workspace}/app/game-api/dist/index.js`,
|
|
||||||
},
|
|
||||||
]
|
|
||||||
);
|
|
||||||
|
|
||||||
await expect(harness.orchestrator.cleanupStaleWorkspaces()).resolves.toEqual({
|
|
||||||
removed: [],
|
|
||||||
skipped: [workspace],
|
|
||||||
});
|
|
||||||
expect(harness.removeCalls).toEqual([]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('protects a shared workspace when a process for either profile is active', async () => {
|
|
||||||
const workspace = '/srv/sammo/worktrees/shared';
|
|
||||||
const harness = createHarness(
|
|
||||||
[makeProfile('che:default', workspace), makeProfile('hwe:default', workspace)],
|
|
||||||
[{ name: 'sammo:hwe:default:game-api', status: 'stopping' }]
|
|
||||||
);
|
|
||||||
|
|
||||||
await expect(harness.orchestrator.cleanupStaleWorkspaces()).resolves.toEqual({
|
|
||||||
removed: [],
|
|
||||||
skipped: [workspace],
|
|
||||||
});
|
|
||||||
expect(harness.removeCalls).toEqual([]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('removes an old unreferenced workspace and clears every profile reference', async () => {
|
|
||||||
const workspace = '/srv/sammo/worktrees/stale';
|
|
||||||
const harness = createHarness(
|
|
||||||
[makeProfile('che:default', workspace), makeProfile('hwe:default', workspace)],
|
|
||||||
[{ name: 'sammo:che:default:game-api', status: 'stopped', cwd: `${workspace}/app/game-api` }]
|
|
||||||
);
|
|
||||||
|
|
||||||
await expect(harness.orchestrator.cleanupStaleWorkspaces()).resolves.toEqual({
|
|
||||||
removed: [workspace],
|
|
||||||
skipped: [],
|
|
||||||
});
|
|
||||||
expect(harness.removeCalls).toEqual([workspace]);
|
|
||||||
expect(harness.clearedProfiles).toEqual([['che:default', 'hwe:default']]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('does not treat a sibling path with the same prefix as a workspace reference', async () => {
|
|
||||||
const workspace = '/srv/sammo/worktrees/commit-a';
|
const workspace = '/srv/sammo/worktrees/commit-a';
|
||||||
const harness = createHarness(
|
const harness = createHarness(
|
||||||
[makeProfile('che:default', workspace)],
|
[],
|
||||||
[
|
[{ name: 'custom-worker', status: 'online', cwd: `${workspace}-old/app/game-api` }],
|
||||||
{
|
[workspace]
|
||||||
name: 'unregistered-worker-name',
|
|
||||||
status: 'online',
|
|
||||||
cwd: '/srv/sammo/worktrees/commit-a-old/app/game-api',
|
|
||||||
},
|
|
||||||
]
|
|
||||||
);
|
);
|
||||||
|
|
||||||
await expect(harness.orchestrator.cleanupStaleWorkspaces()).resolves.toEqual({
|
await expect(harness.orchestrator.cleanupStaleWorkspaces()).resolves.toEqual({
|
||||||
removed: [workspace],
|
removed: [workspace],
|
||||||
skipped: [],
|
skipped: [],
|
||||||
});
|
});
|
||||||
expect(harness.removeCalls).toEqual([workspace]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('clears a stale database reference when the workspace is already missing', async () => {
|
|
||||||
const workspace = '/srv/sammo/worktrees/missing';
|
|
||||||
const harness = createHarness([makeProfile('che:default', workspace)], [], false);
|
|
||||||
|
|
||||||
await expect(harness.orchestrator.cleanupStaleWorkspaces()).resolves.toEqual({
|
|
||||||
removed: [workspace],
|
|
||||||
skipped: [],
|
|
||||||
});
|
|
||||||
expect(harness.removeCalls).toEqual([workspace]);
|
|
||||||
expect(harness.clearedProfiles).toEqual([['che:default']]);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ describe('readReleaseManifest', () => {
|
|||||||
await expect(readReleaseManifest(workspaceRoot)).resolves.toMatchObject({
|
await expect(readReleaseManifest(workspaceRoot)).resolves.toMatchObject({
|
||||||
controllerProtocol: RELEASE_CONTROLLER_PROTOCOL,
|
controllerProtocol: RELEASE_CONTROLLER_PROTOCOL,
|
||||||
gatewaySchemaHead: '20260819000000_backfill_profile_release_source',
|
gatewaySchemaHead: '20260819000000_backfill_profile_release_source',
|
||||||
gameSchemaHead: '20260820001000_restore_united_turn_halt',
|
gameSchemaHead: '20260820002000_persist_official_game_index',
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -163,4 +163,46 @@ describe('GitWorkspaceManager source resolution', () => {
|
|||||||
);
|
);
|
||||||
expect(fs.existsSync(unregistered)).toBe(true);
|
expect(fs.existsSync(unregistered)).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('cleans only expired unprotected worktrees beyond the newest cache and preserves dirty work', async () => {
|
||||||
|
const fixture = createRepositoryFixture();
|
||||||
|
const now = new Date('2026-08-20T12:00:00.000Z');
|
||||||
|
const manager = new GitWorkspaceManager({
|
||||||
|
repoRoot: fixture.checkout,
|
||||||
|
worktreeRoot: fixture.worktrees,
|
||||||
|
now: () => now,
|
||||||
|
});
|
||||||
|
const workspaces = [await manager.prepare(fixture.firstCommit)];
|
||||||
|
for (let index = 2; index <= 5; index += 1) {
|
||||||
|
fs.writeFileSync(path.join(fixture.source, 'version.txt'), `version ${index}\n`);
|
||||||
|
git(fixture.source, 'add', 'version.txt');
|
||||||
|
git(fixture.source, 'commit', '-m', `version ${index}`);
|
||||||
|
git(fixture.source, 'push', 'origin', 'main');
|
||||||
|
const commit = await manager.resolveCommit('BRANCH', 'main');
|
||||||
|
workspaces.push(await manager.prepare(commit));
|
||||||
|
}
|
||||||
|
const expired = new Date('2026-08-01T00:00:00.000Z');
|
||||||
|
for (const workspace of workspaces) fs.utimesSync(workspace.root, expired, expired);
|
||||||
|
fs.writeFileSync(path.join(workspaces[1]!.root, 'preserve-me.txt'), 'uncommitted\n');
|
||||||
|
fs.utimesSync(workspaces[1]!.root, expired, expired);
|
||||||
|
const recent = new Date('2026-08-20T11:00:00.000Z');
|
||||||
|
fs.utimesSync(workspaces[4]!.root, recent, recent);
|
||||||
|
|
||||||
|
const result = await manager.cleanup({
|
||||||
|
protectedPaths: [workspaces[0]!.root],
|
||||||
|
retentionMs: 24 * 60 * 60 * 1_000,
|
||||||
|
keepNewest: 1,
|
||||||
|
});
|
||||||
|
expect(result.removed).toHaveLength(2);
|
||||||
|
expect(result.removed).toEqual(expect.arrayContaining([workspaces[2]!.root, workspaces[3]!.root]));
|
||||||
|
expect(result.skipped).toHaveLength(3);
|
||||||
|
expect(result.skipped).toEqual(
|
||||||
|
expect.arrayContaining([workspaces[0]!.root, workspaces[1]!.root, workspaces[4]!.root])
|
||||||
|
);
|
||||||
|
expect(fs.existsSync(workspaces[0]!.root)).toBe(true);
|
||||||
|
expect(fs.existsSync(workspaces[1]!.root)).toBe(true);
|
||||||
|
expect(fs.existsSync(workspaces[2]!.root)).toBe(false);
|
||||||
|
expect(fs.existsSync(workspaces[3]!.root)).toBe(false);
|
||||||
|
expect(fs.existsSync(workspaces[4]!.root)).toBe(true);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -70,6 +70,13 @@ pnpm --filter @sammo-ts/release-controller status
|
|||||||
pnpm --filter @sammo-ts/release-controller run-once
|
pnpm --filter @sammo-ts/release-controller run-once
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Daemon은 시작 시와 이후 24시간마다 commit worktree를 자동 정리합니다. 현재·이전
|
||||||
|
Gateway release와 활성 PM2 process가 사용하는 경로는 항상 보호하고, 나머지는
|
||||||
|
마지막 사용 후 24시간과 최신 2개 cache를 보장한 뒤 제거합니다. 변경이 있거나 Git
|
||||||
|
제거가 실패한 worktree는 raw directory 삭제로 우회하지 않고 다음 주기까지
|
||||||
|
보존합니다. Profile worktree는 Gateway orchestrator가 같은 정책으로 별도
|
||||||
|
관리합니다.
|
||||||
|
|
||||||
## Controller self-upgrade
|
## Controller self-upgrade
|
||||||
|
|
||||||
이 명령은 현재 daemon과 별개의 CLI process에서 실행됩니다. 대상 worktree를
|
이 명령은 현재 daemon과 별개의 CLI process에서 실행됩니다. 대상 worktree를
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import {
|
|||||||
} from '@sammo-ts/gateway-api';
|
} from '@sammo-ts/gateway-api';
|
||||||
|
|
||||||
import { resolveReleaseControllerConfig } from './config.js';
|
import { resolveReleaseControllerConfig } from './config.js';
|
||||||
import { GatewayReleaseController } from './releaseController.js';
|
import { GatewayReleaseController, RELEASE_WORKSPACE_CLEANUP_INTERVAL_MS } from './releaseController.js';
|
||||||
import { upgradeReleaseController } from './selfUpgrade.js';
|
import { upgradeReleaseController } from './selfUpgrade.js';
|
||||||
|
|
||||||
export * from './config.js';
|
export * from './config.js';
|
||||||
@@ -67,6 +67,7 @@ const main = async (): Promise<void> => {
|
|||||||
}
|
}
|
||||||
if (command !== 'daemon') throw new Error(`Unknown release-controller command: ${command}`);
|
if (command !== 'daemon') throw new Error(`Unknown release-controller command: ${command}`);
|
||||||
let stopping = false;
|
let stopping = false;
|
||||||
|
let nextWorkspaceCleanupAt = 0;
|
||||||
const stop = async (): Promise<void> => {
|
const stop = async (): Promise<void> => {
|
||||||
if (stopping) return;
|
if (stopping) return;
|
||||||
stopping = true;
|
stopping = true;
|
||||||
@@ -75,6 +76,18 @@ const main = async (): Promise<void> => {
|
|||||||
process.once('SIGINT', () => void stop());
|
process.once('SIGINT', () => void stop());
|
||||||
process.once('SIGTERM', () => void stop());
|
process.once('SIGTERM', () => void stop());
|
||||||
while (!stopping) {
|
while (!stopping) {
|
||||||
|
const now = Date.now();
|
||||||
|
if (now >= nextWorkspaceCleanupAt) {
|
||||||
|
nextWorkspaceCleanupAt = now + RELEASE_WORKSPACE_CLEANUP_INTERVAL_MS;
|
||||||
|
try {
|
||||||
|
const result = await controller.cleanupStaleWorkspaces();
|
||||||
|
if (result.removed.length > 0) {
|
||||||
|
console.info(`[release-controller] removed ${result.removed.length} stale Gateway worktrees`);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[release-controller] workspace cleanup failed', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
await controller.runOnce();
|
await controller.runOnce();
|
||||||
await new Promise<void>((resolve) => setTimeout(resolve, config.pollIntervalMs));
|
await new Promise<void>((resolve) => setTimeout(resolve, config.pollIntervalMs));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ import {
|
|||||||
assertReleaseComponents,
|
assertReleaseComponents,
|
||||||
buildTurboReleaseCommand,
|
buildTurboReleaseCommand,
|
||||||
buildTurboReleaseTaskCommand,
|
buildTurboReleaseTaskCommand,
|
||||||
|
DEFAULT_MANAGED_WORKSPACE_KEEP_NEWEST,
|
||||||
|
DEFAULT_MANAGED_WORKSPACE_RETENTION_MS,
|
||||||
type BuildCommand,
|
type BuildCommand,
|
||||||
type BuildProgressEvent,
|
type BuildProgressEvent,
|
||||||
type BuildRunner,
|
type BuildRunner,
|
||||||
@@ -27,6 +29,16 @@ const HEARTBEAT_INTERVAL_MS = 60_000;
|
|||||||
const CANCELLATION_POLL_INTERVAL_MS = 500;
|
const CANCELLATION_POLL_INTERVAL_MS = 500;
|
||||||
const PROCESS_NAMES = ['sammo:gateway-api', 'sammo:gateway-frontend', 'sammo:gateway-orchestrator'] as const;
|
const PROCESS_NAMES = ['sammo:gateway-api', 'sammo:gateway-frontend', 'sammo:gateway-orchestrator'] as const;
|
||||||
const SENSITIVE_ENV_NAME = /(SECRET|TOKEN|PASSWORD|PASSWD|PRIVATE_KEY|CLIENT_SECRET|DATABASE_URL|REDIS_URL)/iu;
|
const SENSITIVE_ENV_NAME = /(SECRET|TOKEN|PASSWORD|PASSWD|PRIVATE_KEY|CLIENT_SECRET|DATABASE_URL|REDIS_URL)/iu;
|
||||||
|
export const RELEASE_WORKSPACE_CLEANUP_INTERVAL_MS = 24 * 60 * 60 * 1_000;
|
||||||
|
|
||||||
|
const isRuntimeProcessActive = (status: string): boolean =>
|
||||||
|
['online', 'launching', 'stopping'].includes(status.toLowerCase());
|
||||||
|
|
||||||
|
const isPathInside = (candidate: string | undefined, root: string): boolean => {
|
||||||
|
if (!candidate) return false;
|
||||||
|
const relative = path.relative(path.resolve(root), path.resolve(candidate));
|
||||||
|
return relative === '' || (!relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
|
||||||
|
};
|
||||||
|
|
||||||
const managedPostgresPoolMax = (env: Record<string, string>, roleVariable: string, fallback: number): string =>
|
const managedPostgresPoolMax = (env: Record<string, string>, roleVariable: string, fallback: number): string =>
|
||||||
String(resolvePostgresPoolMax(env[roleVariable] ?? env.POSTGRES_POOL_MAX, fallback));
|
String(resolvePostgresPoolMax(env[roleVariable] ?? env.POSTGRES_POOL_MAX, fallback));
|
||||||
@@ -132,6 +144,33 @@ export class GatewayReleaseController {
|
|||||||
private readonly fetchImpl: typeof fetch = fetch
|
private readonly fetchImpl: typeof fetch = fetch
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
|
async cleanupStaleWorkspaces(): Promise<{ removed: string[]; skipped: string[] }> {
|
||||||
|
const [state, processes, workspaces] = await Promise.all([
|
||||||
|
this.repository.getState(),
|
||||||
|
this.processManager.list(),
|
||||||
|
this.workspaceManager.listManagedWorkspaces(),
|
||||||
|
]);
|
||||||
|
const protectedWorkspaces = new Set<string>();
|
||||||
|
if (state.activeWorkspace) protectedWorkspaces.add(path.resolve(state.activeWorkspace));
|
||||||
|
if (state.previousWorkspace) protectedWorkspaces.add(path.resolve(state.previousWorkspace));
|
||||||
|
const activeProcesses = processes.filter((process) => isRuntimeProcessActive(process.status));
|
||||||
|
for (const workspace of workspaces) {
|
||||||
|
if (
|
||||||
|
activeProcesses.some(
|
||||||
|
(process) =>
|
||||||
|
isPathInside(process.cwd, workspace.root) || isPathInside(process.script, workspace.root)
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
protectedWorkspaces.add(workspace.root);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return this.workspaceManager.cleanup({
|
||||||
|
protectedPaths: [...protectedWorkspaces],
|
||||||
|
retentionMs: DEFAULT_MANAGED_WORKSPACE_RETENTION_MS,
|
||||||
|
keepNewest: DEFAULT_MANAGED_WORKSPACE_KEEP_NEWEST,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
private sanitizeLogMessage(message: string): string {
|
private sanitizeLogMessage(message: string): string {
|
||||||
let sanitized = stripVTControlCharacters(message);
|
let sanitized = stripVTControlCharacters(message);
|
||||||
const sensitiveValues = new Set([
|
const sensitiveValues = new Set([
|
||||||
|
|||||||
@@ -2,14 +2,17 @@ import fs from 'node:fs/promises';
|
|||||||
import os from 'node:os';
|
import os from 'node:os';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
|
|
||||||
import type {
|
import {
|
||||||
BuildRunner,
|
DEFAULT_MANAGED_WORKSPACE_KEEP_NEWEST,
|
||||||
GatewayReleaseOperationRecord,
|
DEFAULT_MANAGED_WORKSPACE_RETENTION_MS,
|
||||||
GatewayReleaseRepository,
|
type BuildRunner,
|
||||||
GatewayReleaseStateRecord,
|
type GatewayReleaseOperationRecord,
|
||||||
GitWorkspaceManager,
|
type GatewayReleaseRepository,
|
||||||
ProcessDefinition,
|
type GatewayReleaseStateRecord,
|
||||||
ProcessManager,
|
type GitWorkspaceManager,
|
||||||
|
type ManagedWorkspaceCleanupOptions,
|
||||||
|
type ProcessDefinition,
|
||||||
|
type ProcessManager,
|
||||||
} from '@sammo-ts/gateway-api';
|
} from '@sammo-ts/gateway-api';
|
||||||
import { afterEach, describe, expect, it } from 'vitest';
|
import { afterEach, describe, expect, it } from 'vitest';
|
||||||
|
|
||||||
@@ -178,6 +181,68 @@ it('rejects Gateway definitions before switching processes when Redis connection
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('GatewayReleaseController', () => {
|
describe('GatewayReleaseController', () => {
|
||||||
|
it('protects active, rollback, and running-process worktrees while delegating bounded cleanup', async () => {
|
||||||
|
const active = '/srv/sammo/releases/active';
|
||||||
|
const previous = '/srv/sammo/releases/previous';
|
||||||
|
const controllerWorkspace = '/srv/sammo/releases/controller';
|
||||||
|
const stale = '/srv/sammo/releases/stale';
|
||||||
|
const managedPaths = [active, previous, controllerWorkspace, stale];
|
||||||
|
const cleanupCalls: ManagedWorkspaceCleanupOptions[] = [];
|
||||||
|
const harness = createRepository();
|
||||||
|
const workspaceManager = {
|
||||||
|
listManagedWorkspaces: async () =>
|
||||||
|
managedPaths.map((root) => ({
|
||||||
|
root,
|
||||||
|
commitSha: SHA,
|
||||||
|
lastUsedAt: new Date('2025-01-01T00:00:00.000Z'),
|
||||||
|
})),
|
||||||
|
cleanup: async (options: ManagedWorkspaceCleanupOptions) => {
|
||||||
|
cleanupCalls.push(options);
|
||||||
|
const protectedPaths = new Set(options.protectedPaths);
|
||||||
|
return {
|
||||||
|
removed: managedPaths.filter((workspace) => !protectedPaths.has(workspace)),
|
||||||
|
skipped: managedPaths.filter((workspace) => protectedPaths.has(workspace)),
|
||||||
|
};
|
||||||
|
},
|
||||||
|
} as unknown as GitWorkspaceManager;
|
||||||
|
const controller = new GatewayReleaseController(
|
||||||
|
{
|
||||||
|
...harness.repository,
|
||||||
|
getState: async () => ({
|
||||||
|
...state,
|
||||||
|
activeWorkspace: active,
|
||||||
|
previousCommitSha: SHA,
|
||||||
|
previousWorkspace: previous,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
workspaceManager,
|
||||||
|
{ run: async () => ({ ok: true, exitCode: 0, output: '' }) },
|
||||||
|
{
|
||||||
|
list: async () => [
|
||||||
|
{
|
||||||
|
name: 'sammo:release-controller',
|
||||||
|
status: 'online',
|
||||||
|
cwd: `${controllerWorkspace}/app/release-controller`,
|
||||||
|
},
|
||||||
|
{ name: 'old-build', status: 'stopped', cwd: `${stale}/app/gateway-api` },
|
||||||
|
],
|
||||||
|
start: async () => {},
|
||||||
|
stop: async () => {},
|
||||||
|
delete: async () => {},
|
||||||
|
},
|
||||||
|
config
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(controller.cleanupStaleWorkspaces()).resolves.toEqual({
|
||||||
|
removed: [stale],
|
||||||
|
skipped: [active, previous, controllerWorkspace],
|
||||||
|
});
|
||||||
|
expect(cleanupCalls[0]).toMatchObject({
|
||||||
|
retentionMs: DEFAULT_MANAGED_WORKSPACE_RETENTION_MS,
|
||||||
|
keepNewest: DEFAULT_MANAGED_WORKSPACE_KEEP_NEWEST,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
it('builds, migrates, switches all gateway roles, verifies readiness, and publishes atomically', async () => {
|
it('builds, migrates, switches all gateway roles, verifies readiness, and publishes atomically', async () => {
|
||||||
const workspace = await createReleaseWorkspace();
|
const workspace = await createReleaseWorkspace();
|
||||||
const harness = createRepository();
|
const harness = createRepository();
|
||||||
|
|||||||
@@ -69,6 +69,29 @@ profile 범위 권한과 별개인 전역 `admin.releases.manage` 권한이 필
|
|||||||
- migration 이후 이전 애플리케이션으로 돌아갈 때 schema 하위 호환성이
|
- migration 이후 이전 애플리케이션으로 돌아갈 때 schema 하위 호환성이
|
||||||
유지됩니다.
|
유지됩니다.
|
||||||
|
|
||||||
|
## Commit worktree 자동 정리
|
||||||
|
|
||||||
|
Profile orchestrator와 Gateway release-controller는 서로 다른 worktree root를
|
||||||
|
사용하지만 같은 보존 정책을 적용합니다. 각 daemon은 시작 시 한 번, 이후 24시간마다
|
||||||
|
자신이 소유한 commit worktree를 점검합니다.
|
||||||
|
|
||||||
|
- `GatewayProfile.buildWorkspace`, `RUNNING`/`QUEUED` profile 빌드 대상,
|
||||||
|
`GatewayReleaseState`의 active/previous workspace는 기간과 무관하게 보호합니다.
|
||||||
|
- 활성 PM2 process의 cwd 또는 script 아래에 있는 worktree도 보호합니다. 여기에는
|
||||||
|
self-upgrade된 release-controller worktree도 포함됩니다.
|
||||||
|
- 보호 대상이 아닌 worktree는 마지막 prepare 이후 최소 24시간을 유예하고, 그중
|
||||||
|
최신 2개는 재시도 cache로 더 남깁니다. 나머지는 Git worktree로 제거하고
|
||||||
|
`git worktree prune --expire now`로 사라진 metadata를 정리합니다.
|
||||||
|
- tracked 또는 untracked 변경이 있으면 자동 삭제하지 않습니다. Git 제거 실패를
|
||||||
|
raw directory 삭제로 우회하지 않으며 다음 주기까지 보존합니다.
|
||||||
|
- 정리는 commit checkout과 재생성 가능한 build artifact만 대상으로 합니다.
|
||||||
|
Gateway/profile PostgreSQL, Redis, image, runtime data volume에는 접근하지 않습니다.
|
||||||
|
|
||||||
|
따라서 하루 안에 매우 많은 commit을 연속 배포하면 유예 구간만큼 일시적으로 늘 수
|
||||||
|
있지만, active/rollback/current profile 경로 외의 장기 누적은 다음 정리 주기에
|
||||||
|
제거됩니다. Profile 관리자 API의 `admin.profiles.cleanupWorkspaces`는 같은 보호
|
||||||
|
규칙을 사용하므로 진행 중인 build/operation이 있으면 전체 정리를 보류합니다.
|
||||||
|
|
||||||
## Profile 배포
|
## Profile 배포
|
||||||
|
|
||||||
버전 업데이트 화면에서 profile의 branch 또는 commit을 선택합니다. Branch는 worker가
|
버전 업데이트 화면에서 profile의 branch 또는 commit을 선택합니다. Branch는 worker가
|
||||||
|
|||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
-- Ref stores server_cnt once at reset time because it is rendered on every main-page load.
|
||||||
|
-- Backfill the active world's equivalent read-model value while excluding cancelled and
|
||||||
|
-- unfinished history rows from the official sequence.
|
||||||
|
UPDATE "world_state" AS ws
|
||||||
|
SET "meta" = jsonb_set(
|
||||||
|
COALESCE(ws."meta", '{}'::jsonb),
|
||||||
|
'{gameIdx}',
|
||||||
|
to_jsonb((
|
||||||
|
SELECT COUNT(*)::integer + 1
|
||||||
|
FROM "ng_games" AS history
|
||||||
|
WHERE history."status" = 'COMPLETED'
|
||||||
|
AND (
|
||||||
|
ws."meta"->>'serverId' IS NULL
|
||||||
|
OR history."server_id" <> ws."meta"->>'serverId'
|
||||||
|
)
|
||||||
|
)),
|
||||||
|
true
|
||||||
|
);
|
||||||
@@ -2,6 +2,6 @@
|
|||||||
"formatVersion": 1,
|
"formatVersion": 1,
|
||||||
"controllerProtocol": 2,
|
"controllerProtocol": 2,
|
||||||
"gatewaySchemaHead": "20260819000000_backfill_profile_release_source",
|
"gatewaySchemaHead": "20260819000000_backfill_profile_release_source",
|
||||||
"gameSchemaHead": "20260820001000_restore_united_turn_halt",
|
"gameSchemaHead": "20260820002000_persist_official_game_index",
|
||||||
"components": ["gateway-api", "gateway-frontend", "release-controller", "game-api", "game-engine", "game-frontend"]
|
"components": ["gateway-api", "gateway-frontend", "release-controller", "game-api", "game-engine", "game-frontend"]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -81,17 +81,33 @@ const statusFixture = {
|
|||||||
resetLevels: { resetSpecialWar: 0, resetTurnTime: 0 },
|
resetLevels: { resetSpecialWar: 0, resetTurnTime: 0 },
|
||||||
availableSpecialWar: [{ key: 'che_선봉', name: '선봉', info: '공격에 유리합니다.' }],
|
availableSpecialWar: [{ key: 'che_선봉', name: '선봉', info: '공격에 유리합니다.' }],
|
||||||
availableUnique: [
|
availableUnique: [
|
||||||
|
{
|
||||||
|
key: 'che_명마_07_백마',
|
||||||
|
name: '백마(+7)',
|
||||||
|
rawName: '백마',
|
||||||
|
info: '기동력을 올려주는 유니크 명마입니다.',
|
||||||
|
slot: 'horse',
|
||||||
|
},
|
||||||
{
|
{
|
||||||
key: 'che_무기_12_칠성검',
|
key: 'che_무기_12_칠성검',
|
||||||
name: '칠성검(+12)',
|
name: '칠성검(+12)',
|
||||||
rawName: '칠성검',
|
rawName: '칠성검',
|
||||||
info: '무력을 올려주는 유니크 무기입니다.',
|
info: '무력을 올려주는 유니크 무기입니다.',
|
||||||
|
slot: 'weapon',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'che_서적_07_논어',
|
key: 'che_서적_07_논어',
|
||||||
name: '논어(+7)',
|
name: '논어(+7)',
|
||||||
rawName: '논어',
|
rawName: '논어',
|
||||||
info: '지력을 올려주는 유니크 서적입니다.',
|
info: '지력을 올려주는 유니크 서적입니다.',
|
||||||
|
slot: 'book',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'che_보물_도기',
|
||||||
|
name: '도기',
|
||||||
|
rawName: '도기',
|
||||||
|
info: '전투를 돕는 유니크 도구입니다.',
|
||||||
|
slot: 'item',
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
availableTargetGenerals: [{ id: 8, name: '조조' }],
|
availableTargetGenerals: [{ id: 8, name: '조조' }],
|
||||||
@@ -197,7 +213,21 @@ test.describe('inheritance management legacy parity', () => {
|
|||||||
await page.setViewportSize({ width: 1280, height: 900 });
|
await page.setViewportSize({ width: 1280, height: 900 });
|
||||||
await page.goto(gameUrl);
|
await page.goto(gameUrl);
|
||||||
await expect(page.locator('#container')).toBeVisible();
|
await expect(page.locator('#container')).toBeVisible();
|
||||||
await expect(page.locator('#specific-unique')).toHaveValue('che_무기_12_칠성검');
|
await expect(page.locator('#specific-unique')).toHaveValue('che_명마_07_백마');
|
||||||
|
await expect(page.locator('#specific-unique optgroup')).toHaveCount(4);
|
||||||
|
expect(
|
||||||
|
await page.locator('#specific-unique optgroup').evaluateAll((groups) =>
|
||||||
|
groups.map((group) => ({
|
||||||
|
label: group.getAttribute('label'),
|
||||||
|
values: [...group.querySelectorAll('option')].map((option) => option.value),
|
||||||
|
}))
|
||||||
|
)
|
||||||
|
).toEqual([
|
||||||
|
{ label: '명마', values: ['che_명마_07_백마'] },
|
||||||
|
{ label: '무기', values: ['che_무기_12_칠성검'] },
|
||||||
|
{ label: '서적', values: ['che_서적_07_논어'] },
|
||||||
|
{ label: '도구', values: ['che_보물_도기'] },
|
||||||
|
]);
|
||||||
|
|
||||||
const desktop = await page.evaluate(() => {
|
const desktop = await page.evaluate(() => {
|
||||||
const rect = (selector: string) => {
|
const rect = (selector: string) => {
|
||||||
|
|||||||
@@ -888,8 +888,10 @@ export const runCoreTurnCommandTrace = async (
|
|||||||
id: index + 1,
|
id: index + 1,
|
||||||
scope: log.scope,
|
scope: log.scope,
|
||||||
category: log.category,
|
category: log.category,
|
||||||
generalId: log.generalId ?? (log.scope === 'GENERAL' ? actor.id : undefined),
|
// Keep the product draft unchanged. Inferring an owner here hid
|
||||||
nationId: log.nationId ?? (log.scope === 'NATION' ? actor.nationId : undefined),
|
// GENERAL logs that finalizeLogEntry would reject in production.
|
||||||
|
generalId: log.generalId,
|
||||||
|
nationId: log.nationId,
|
||||||
year: state.currentYear,
|
year: state.currentYear,
|
||||||
month: state.currentMonth,
|
month: state.currentMonth,
|
||||||
text: log.text,
|
text: log.text,
|
||||||
|
|||||||
Reference in New Issue
Block a user