Complete legacy-compatible in-game information menus

This commit is contained in:
2026-07-26 05:20:32 +00:00
parent 8fac491c9d
commit 0127fd501a
20 changed files with 3269 additions and 940 deletions
+10 -29
View File
@@ -37,15 +37,19 @@ const normalizeItemCode = (value: string | null): string | null => {
};
const resolveUserSettings = (meta: Record<string, unknown>) => {
const settings = asRecord(meta.userSettings);
const mysetRaw = settings.myset;
// The legacy general columns are persisted at the top level of General.meta.
// Keep reading the short-lived nested shape for installations that ran the
// initial rewrite implementation before this compatibility fix.
const nestedSettings = asRecord(meta.userSettings);
const readSetting = (key: string): unknown => meta[key] ?? nestedSettings[key];
const mysetRaw = readSetting('myset');
const myset = typeof mysetRaw === 'number' && Number.isFinite(mysetRaw) ? mysetRaw : null;
return {
tnmt: readNumber(settings.tnmt, 1),
defence_train: readNumber(settings.defence_train, 80),
use_treatment: readNumber(settings.use_treatment, 10),
use_auto_nation_turn: readNumber(settings.use_auto_nation_turn, 1),
tnmt: readNumber(readSetting('tnmt'), 1),
defence_train: readNumber(readSetting('defence_train'), 80),
use_treatment: readNumber(readSetting('use_treatment'), 10),
use_auto_nation_turn: readNumber(readSetting('use_auto_nation_turn'), 1),
myset,
};
};
@@ -262,29 +266,6 @@ export const generalRouter = router({
throw new TRPCError({ code: 'BAD_REQUEST', message: result.reason });
}
const metaRecord = asRecord(general.meta);
const prevSettings = asRecord(metaRecord.userSettings);
const prevMyset = typeof prevSettings.myset === 'number' && Number.isFinite(prevSettings.myset)
? prevSettings.myset
: null;
const nextSettings = {
...prevSettings,
...input,
} as Record<string, unknown>;
if (typeof prevMyset === 'number') {
nextSettings.myset = Math.max(0, prevMyset - 1);
}
await ctx.db.general.update({
where: { id: general.id },
data: {
meta: {
...metaRecord,
userSettings: nextSettings,
},
} as any,
});
return { ok: true };
}),
dropItem: authedProcedure.input(z.object({ itemType: z.string() })).mutation(async ({ ctx, input }) => {
@@ -1,84 +1,279 @@
import { TRPCError } from '@trpc/server';
import { asRecord } from '@sammo-ts/common';
import type { GameApiContext } from '../../../context.js';
import { authedProcedure } from '../../../trpc.js';
import { getMyGeneral } from '../../shared/general.js';
import { assertNationAccess, loadTraitNames, mapGeneralList, resolveChiefStatMin } from '../shared.js';
import {
assertNationAccess,
loadTraitNames,
resolveNationPermission,
resolveOfficerCity,
} from '../shared.js';
export const getGeneralList = authedProcedure.query(async ({ ctx }) => {
const general = await getMyGeneral(ctx);
assertNationAccess(general);
const MAX_DEDICATION_LEVEL = 10;
const [nation, cityRows, troopRows, generalRows, worldState] = await Promise.all([
ctx.db.nation.findUnique({
where: { id: general.nationId },
select: {
id: true,
name: true,
color: true,
level: true,
typeCode: true,
capitalCityId: true,
meta: true,
},
}),
ctx.db.city.findMany({ select: { id: true, name: true } }),
ctx.db.troop.findMany({ select: { troopLeaderId: true, name: true } }),
ctx.db.general.findMany({
where: { nationId: general.nationId },
select: {
id: true,
name: true,
npcState: true,
nationId: true,
cityId: true,
troopId: true,
picture: true,
imageServer: true,
officerLevel: true,
leadership: true,
strength: true,
intel: true,
experience: true,
dedication: true,
injury: true,
gold: true,
rice: true,
crew: true,
personalCode: true,
specialCode: true,
special2Code: true,
meta: true,
penalty: true,
},
orderBy: { id: 'asc' },
}),
ctx.db.worldState.findFirst(),
]);
const readNumber = (record: Record<string, unknown>, keys: string[], fallback = 0): number => {
for (const key of keys) {
const value = record[key];
if (typeof value === 'number' && Number.isFinite(value)) {
return value;
}
}
return fallback;
};
const experienceLevel = (experience: number): number =>
Math.max(0, Math.min(100, experience < 1_000 ? Math.floor(experience / 100) : Math.floor(Math.sqrt(experience / 10))));
const dedicationLevel = (dedication: number): number =>
Math.max(0, Math.min(MAX_DEDICATION_LEVEL, Math.ceil(Math.sqrt(Math.max(0, dedication)) / 10)));
const dedicationLevelText = (level: number): string =>
level === 0 ? '무품관' : `${MAX_DEDICATION_LEVEL - level + 1}품관`;
const honorText = (experience: number): string => {
const levels: Array<[number, string]> = [
[640, '전무'],
[2_560, '무명'],
[5_760, '신동'],
[10_240, '약간'],
[16_000, '평범'],
[23_040, '지역적'],
[31_360, '전국적'],
[40_960, '세계적'],
[45_000, '유명'],
[51_840, '명사'],
[55_000, '호걸'],
[64_000, '효웅'],
[77_440, '영웅'],
];
return levels.find(([limit]) => experience < limit)?.[1] ?? '구세주';
};
const leadershipBonus = (officerLevel: number, nationLevel: number): number => {
if (officerLevel === 12) return nationLevel * 2;
if (officerLevel >= 5) return nationLevel;
return 0;
};
const woundedStat = (value: number, injury: number): number =>
injury > 0 ? Math.floor((value * (100 - injury)) / 100) : value;
const defenceTrainText = (value: number): string => {
if (value === 999) return '×';
if (value >= 90) return '☆';
if (value >= 80) return '◎';
if (value >= 60) return '○';
return '△';
};
const loadNationGeneralData = async (ctx: GameApiContext) => {
const me = await getMyGeneral(ctx);
assertNationAccess(me);
const nation = await ctx.db.nation.findUnique({
where: { id: me.nationId },
select: {
id: true,
name: true,
color: true,
level: true,
typeCode: true,
capitalCityId: true,
meta: true,
},
});
if (!nation) {
throw new TRPCError({ code: 'NOT_FOUND', message: 'Nation not found' });
}
const viewerPermission = resolveNationPermission(me, nation.meta, true);
const cityNameMap = new Map(cityRows.map((city) => [city.id, city.name]));
const troopNameMap = new Map(troopRows.map((troop) => [troop.troopLeaderId, troop.name]));
const list = await mapGeneralList(generalRows, cityNameMap, troopNameMap);
const nationTrait = (await loadTraitNames([nation.typeCode], 'nation')).get(nation.typeCode);
const [cityRows, troopRows, generalRows] = await Promise.all([
ctx.db.city.findMany({ select: { id: true, name: true } }),
ctx.db.troop.findMany({
where: { nationId: me.nationId },
select: { troopLeaderId: true, name: true },
}),
ctx.db.general.findMany({
where: { nationId: me.nationId },
orderBy: [{ turnTime: 'asc' }, { id: 'asc' }],
}),
]);
const generalIds = generalRows.map((general) => general.id);
const [accessRows, turnRows] = await Promise.all([
ctx.db.generalAccessLog.findMany({
where: { generalId: { in: generalIds } },
select: { generalId: true, refreshScore: true, refreshScoreTotal: true },
}),
viewerPermission >= 1
? ctx.db.generalTurn.findMany({
where: { generalId: { in: generalIds }, turnIdx: { lt: 5 } },
select: { generalId: true, turnIdx: true, actionCode: true },
orderBy: [{ generalId: 'asc' }, { turnIdx: 'asc' }],
})
: Promise.resolve([]),
]);
const cityNames = new Map(cityRows.map((city) => [city.id, city.name]));
const troopNames = new Map(troopRows.map((troop) => [troop.troopLeaderId, troop.name]));
const accessByGeneral = new Map(accessRows.map((row) => [row.generalId, row]));
const turnsByGeneral = new Map<number, string[]>();
for (const turn of turnRows) {
const turns = turnsByGeneral.get(turn.generalId) ?? [];
turns[turn.turnIdx] = turn.actionCode;
turnsByGeneral.set(turn.generalId, turns);
}
const [personalityMap, domesticMap, warMap] = await Promise.all([
loadTraitNames(generalRows.map((general) => general.personalCode), 'personality'),
loadTraitNames(generalRows.map((general) => general.specialCode), 'domestic'),
loadTraitNames(generalRows.map((general) => general.special2Code), 'war'),
]);
const generals = generalRows.map((general) => {
const meta = asRecord(general.meta);
const officerCity = resolveOfficerCity(meta);
const access = accessByGeneral.get(general.id);
const dedLevel = dedicationLevel(general.dedication);
const actualOfficerLevel = general.officerLevel;
const visibleOfficerLevel =
viewerPermission >= 1 || actualOfficerLevel >= 5 ? actualOfficerLevel : Math.min(1, actualOfficerLevel);
const bonus = leadershipBonus(actualOfficerLevel, nation.level);
const detail =
viewerPermission >= 1
? {
officerLevel: actualOfficerLevel,
officerCity,
officerCityName: officerCity > 0 ? (cityNames.get(officerCity) ?? null) : null,
cityId: general.cityId,
cityName: cityNames.get(general.cityId) ?? null,
troopId: general.troopId,
troopName: troopNames.get(general.troopId) ?? null,
defenceTrain: readNumber(meta, ['defenceTrain', 'defence_train'], 80),
crewTypeId: general.crewTypeId,
crew: general.crew,
train: general.train,
atmos: general.atmos,
experience: general.experience,
dedication: general.dedication,
turnTime: general.turnTime.toISOString(),
recentWarTime: general.recentWarTime?.toISOString() ?? null,
killTurn: readNumber(meta, ['killturn', 'killTurn']),
refreshScore: access?.refreshScore ?? 0,
reservedCommands: general.npcState < 2 ? (turnsByGeneral.get(general.id) ?? []) : [],
}
: null;
return {
id: general.id,
name: general.name,
npcState: general.npcState,
picture: general.picture,
imageServer: general.imageServer,
injury: general.injury,
stats: {
leadership: woundedStat(general.leadership, general.injury),
strength: woundedStat(general.strength, general.injury),
intelligence: woundedStat(general.intel, general.injury),
},
leadershipBonus: bonus,
officerLevel: visibleOfficerLevel,
experienceLevel: experienceLevel(general.experience),
honorText: honorText(general.experience),
dedicationLevel: dedLevel,
dedicationLevelText: dedicationLevelText(dedLevel),
bill: dedLevel * 200 + 400,
gold: general.gold,
rice: general.rice,
age: general.age,
belong: readNumber(meta, ['belong']),
refreshScoreTotal: access?.refreshScoreTotal ?? 0,
personality: general.personalCode === 'None' ? null : (personalityMap.get(general.personalCode) ?? null),
specialDomestic:
general.specialCode === 'None' ? null : (domesticMap.get(general.specialCode) ?? null),
specialWar: general.special2Code === 'None' ? null : (warMap.get(general.special2Code) ?? null),
detail,
};
});
return {
me,
nation: {
id: nation.id,
name: nation.name,
color: nation.color,
level: nation.level,
typeCode: nation.typeCode,
type: {
key: nation.typeCode,
name: nationTrait?.name ?? nation.typeCode,
info: nationTrait?.info ?? '',
},
capitalCityId: nation.capitalCityId ?? 0,
},
chiefStatMin: resolveChiefStatMin(worldState),
generals: list,
viewerPermission,
generals,
};
};
export const getGeneralList = authedProcedure.query(async ({ ctx }) => {
const data = await loadNationGeneralData(ctx);
return {
nation: data.nation,
viewer: { generalId: data.me.id, permission: data.viewerPermission },
generals: data.generals,
};
});
export const getSecretGeneralList = authedProcedure.query(async ({ ctx }) => {
const data = await loadNationGeneralData(ctx);
if (data.viewerPermission < 1) {
throw new TRPCError({
code: 'FORBIDDEN',
message: '권한이 부족합니다. 수뇌부가 아니거나 사관년도가 부족합니다.',
});
}
const visibleGenerals = data.generals.filter((general) => general.npcState !== 5);
const summaryBase = visibleGenerals.reduce(
(summary, general) => {
const detail = general.detail;
if (!detail) return summary;
summary.gold += general.gold;
summary.rice += general.rice;
summary.crew += detail.crew;
if (detail.crew > 0) {
for (const threshold of [90, 80, 60] as const) {
if (detail.train >= threshold && detail.atmos >= threshold) {
summary.readiness[threshold].crew += detail.crew;
summary.readiness[threshold].generals += 1;
}
}
}
return summary;
},
{
gold: 0,
rice: 0,
crew: 0,
readiness: {
90: { crew: 0, generals: 0 },
80: { crew: 0, generals: 0 },
60: { crew: 0, generals: 0 },
},
}
);
const generalCount = visibleGenerals.length;
return {
nation: data.nation,
viewer: { generalId: data.me.id, permission: data.viewerPermission },
summary: {
...summaryBase,
generalCount,
averageGold: generalCount ? summaryBase.gold / generalCount : 0,
averageRice: generalCount ? summaryBase.rice / generalCount : 0,
},
generals: data.generals.map((general) => ({
...general,
defenceTrainText: defenceTrainText(general.detail?.defenceTrain ?? 0),
})),
};
});
+2 -1
View File
@@ -4,7 +4,7 @@ import { changePermission } from './endpoints/changePermission.js';
import { getBattleCenter } from './endpoints/getBattleCenter.js';
import { getChiefCenter } from './endpoints/getChiefCenter.js';
import { getCityOverview } from './endpoints/getCityOverview.js';
import { getGeneralList } from './endpoints/getGeneralList.js';
import { getGeneralList, getSecretGeneralList } from './endpoints/getGeneralList.js';
import { getGeneralLog } from './endpoints/getGeneralLog.js';
import { getNationInfo } from './endpoints/getNationInfo.js';
import { getPersonnelInfo } from './endpoints/getPersonnelInfo.js';
@@ -21,6 +21,7 @@ import { setSecretLimit } from './endpoints/setSecretLimit.js';
export const nationRouter = router({
getNationInfo,
getGeneralList,
getSecretGeneralList,
getCityOverview,
getPersonnelInfo,
getStratFinan,
+117
View File
@@ -42,6 +42,14 @@ type NationCountRow = {
type NpcListSort = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
type TrafficHistoryItem = {
year: number;
month: number;
refresh: number;
online: number;
date: string;
};
const PUBLIC_CACHE_TTL_SECONDS = 600;
const buildPublicCacheKey = (ctx: GameApiContext, key: string): string =>
@@ -163,6 +171,26 @@ const readFiniteMetaNumber = (meta: Record<string, unknown>, key: string): numbe
return typeof value === 'number' && Number.isFinite(value) ? value : 0;
};
const parseTrafficHistory = (value: unknown): TrafficHistoryItem[] => {
if (!Array.isArray(value)) {
return [];
}
const result: TrafficHistoryItem[] = [];
for (const item of value) {
const row = asRecord(item);
const year = readFiniteMetaNumber(row, 'year');
const month = readFiniteMetaNumber(row, 'month');
const refresh = readFiniteMetaNumber(row, 'refresh');
const online = readFiniteMetaNumber(row, 'online');
const date = typeof row.date === 'string' ? row.date : '';
if (year > 0 && month > 0 && date) {
result.push({ year, month, refresh, online, date });
}
}
return result;
};
const compareString = (left: string, right: string): number => {
if (left === right) {
return 0;
@@ -222,6 +250,95 @@ export const publicRouter = router({
getNationList: procedure.query(async ({ ctx }) => {
return loadCachedNationList(ctx);
}),
getTraffic: procedure.query(async ({ ctx }) => {
const worldState = await ctx.db.worldState.findFirst();
if (!worldState) {
throw new TRPCError({
code: 'PRECONDITION_FAILED',
message: 'World state is not initialized.',
});
}
const meta = asRecord(worldState.meta);
const rawOnlineSince = meta.lastTurnTime ?? meta.turntime;
const parsedOnlineSince =
typeof rawOnlineSince === 'string' || rawOnlineSince instanceof Date
? new Date(rawOnlineSince)
: null;
const onlineSince =
parsedOnlineSince && Number.isFinite(parsedOnlineSince.getTime())
? parsedOnlineSince
: new Date(Date.now() - worldState.tickSeconds * 1_000);
const [accessTotal, currentOnline, topAccess] = await Promise.all([
ctx.db.generalAccessLog.aggregate({
_sum: {
refresh: true,
refreshScoreTotal: true,
},
}),
ctx.db.generalAccessLog.count({
where: {
lastRefresh: {
gte: onlineSince,
},
},
}),
ctx.db.generalAccessLog.findMany({
orderBy: [{ refresh: 'desc' }, { generalId: 'asc' }],
take: 5,
select: {
generalId: true,
refresh: true,
refreshScoreTotal: true,
},
}),
]);
const generalIds = topAccess.map((entry) => entry.generalId);
const generalRows =
generalIds.length > 0
? await ctx.db.general.findMany({
where: { id: { in: generalIds } },
select: { id: true, name: true },
})
: [];
const generalName = new Map(generalRows.map((general) => [general.id, general.name]));
const totalRefresh = accessTotal._sum.refresh ?? 0;
const totalRefreshScore = accessTotal._sum.refreshScoreTotal ?? 0;
const currentRefresh = Math.max(readFiniteMetaNumber(meta, 'refresh'), totalRefresh);
const history = parseTrafficHistory(meta.recentTraffic);
history.push({
year: worldState.currentYear,
month: worldState.currentMonth,
refresh: currentRefresh,
online: currentOnline,
date: new Date().toISOString(),
});
return {
history,
maxRefresh: Math.max(
1,
readFiniteMetaNumber(meta, 'maxrefresh'),
...history.map((entry) => entry.refresh)
),
maxOnline: Math.max(1, readFiniteMetaNumber(meta, 'maxonline'), ...history.map((entry) => entry.online)),
suspects: [
{
generalId: null,
name: '접속자 총합',
refresh: totalRefresh,
refreshScoreTotal: totalRefreshScore,
},
...topAccess.map((entry) => ({
generalId: entry.generalId,
name: generalName.get(entry.generalId) ?? `장수 ${entry.generalId}`,
refresh: entry.refresh,
refreshScoreTotal: entry.refreshScoreTotal,
})),
],
};
}),
getGeneralList: procedure.query(async ({ ctx }) => {
const [generals, nations] = await Promise.all([
ctx.db.general.findMany({