Merge branch 'main' into feature/survey-unique-parity

This commit is contained in:
2026-07-26 04:18:00 +00:00
20 changed files with 1973 additions and 608 deletions
+20 -12
View File
@@ -1,5 +1,6 @@
import fs from 'node:fs/promises';
import path from 'node:path';
import { loadMapDefinitionByName } from './mapDefinition.js';
export interface MapLayoutCity {
id: number;
@@ -30,8 +31,7 @@ const LEGACY_CITY_CONST = path.resolve(process.cwd(), 'legacy/hwe/sammo/CityCons
const layoutCache = new Map<string, MapLayout>();
const stripComments = (value: string): string =>
value.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, '');
const stripComments = (value: string): string => value.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, '');
const extractPhpArray = (source: string, marker: string): string | null => {
const idx = source.indexOf(marker);
@@ -196,11 +196,7 @@ const parseCityConstFile = async (filePath: string): Promise<ParsedCityConst> =>
const resolveScenarioFile = async (scenario: string): Promise<string> => {
const normalized = scenario.replace(/\.json$/i, '');
const candidates = [
`${normalized}.json`,
`scenario_${normalized}.json`,
'default.json',
];
const candidates = [`${normalized}.json`, `scenario_${normalized}.json`, 'default.json'];
for (const candidate of candidates) {
const fullPath = path.join(LEGACY_SCENARIO_ROOT, candidate);
@@ -272,15 +268,15 @@ const normalizeInitCity = (
typeof levelLabel === 'number'
? levelLabel
: typeof levelLabel === 'string'
? levelMap.nameToId[levelLabel] ?? Number(levelLabel)
: 0;
? (levelMap.nameToId[levelLabel] ?? Number(levelLabel))
: 0;
const regionValue =
typeof regionLabel === 'number'
? regionLabel
: typeof regionLabel === 'string'
? regionMap.nameToId[regionLabel] ?? Number(regionLabel)
: 0;
? (regionMap.nameToId[regionLabel] ?? Number(regionLabel))
: 0;
const pathNames = Array.isArray(path) ? (path as string[]) : [];
const pathIds = pathNames
@@ -324,7 +320,19 @@ export const loadMapLayout = async (scenario: string): Promise<MapLayout> => {
const levelMap = buildLookupMap(levelMapRaw);
const initCity = map.initCity ?? base.initCity ?? [];
const cityList = normalizeInitCity(initCity, levelMap, regionMap);
let cityList = normalizeInitCity(initCity, levelMap, regionMap);
if (cityList.length === 0) {
const resourceMap = await loadMapDefinitionByName(mapName);
cityList = resourceMap.cities.map((city) => ({
id: city.id,
name: city.name,
level: city.level,
region: city.region,
x: city.position.x,
y: city.position.y,
path: [...city.connections],
}));
}
const layout: MapLayout = {
mapName,
@@ -0,0 +1,127 @@
import { TRPCError } from '@trpc/server';
import { asRecord } from '@sammo-ts/common';
import { LogCategory, LogScope } from '@sammo-ts/infra';
import { getGoldIncome, getOutcome, getRiceIncome, getWallIncome, getWarGoldIncome } from '@sammo-ts/logic';
import { authedProcedure } from '../../../trpc.js';
import { getMyGeneral } from '../../shared/general.js';
import {
assertNationAccess,
buildNationIncomeContext,
resolveNationBill,
resolveNationRate,
resolveOfficerCity,
toIncomeCity,
} from '../shared.js';
export const getNationInfo = authedProcedure.query(async ({ ctx }) => {
const me = await getMyGeneral(ctx);
assertNationAccess(me);
const [nation, cities, generals, history] = await Promise.all([
ctx.db.nation.findUnique({ where: { id: me.nationId } }),
ctx.db.city.findMany({ where: { nationId: me.nationId }, orderBy: { id: 'asc' } }),
ctx.db.general.findMany({ where: { nationId: me.nationId } }),
ctx.db.logEntry.findMany({
where: {
scope: LogScope.NATION,
category: LogCategory.HISTORY,
nationId: me.nationId,
},
select: { id: true, year: true, month: true, text: true },
orderBy: { id: 'asc' },
}),
]);
if (!nation) {
throw new TRPCError({ code: 'NOT_FOUND', message: 'Nation not found' });
}
const officerCntByCity = new Map<number, number>();
for (const general of generals) {
const officerCity = resolveOfficerCity(asRecord(general.meta));
if (
general.officerLevel >= 2 &&
general.officerLevel <= 4 &&
officerCity > 0 &&
general.cityId === officerCity
) {
officerCntByCity.set(officerCity, (officerCntByCity.get(officerCity) ?? 0) + 1);
}
}
const incomeContext = await buildNationIncomeContext(nation);
const incomeCities = cities.map(toIncomeCity);
const rate = resolveNationRate(nation);
const bill = resolveNationBill(asRecord(nation.meta));
const goldCity = getGoldIncome(
incomeContext,
incomeCities,
officerCntByCity,
nation.capitalCityId ?? 0,
nation.level
);
const goldWar = getWarGoldIncome(incomeContext, incomeCities);
const riceCity = getRiceIncome(
incomeContext,
incomeCities,
officerCntByCity,
nation.capitalCityId ?? 0,
nation.level
);
const riceWall = getWallIncome(
incomeContext,
incomeCities,
officerCntByCity,
nation.capitalCityId ?? 0,
nation.level
);
const outcome = getOutcome(
bill,
generals.filter((general) => general.npcState !== 5)
);
const population = cities.reduce((sum, city) => sum + city.population, 0);
const populationMax = cities.reduce((sum, city) => sum + city.populationMax, 0);
const crewGenerals = generals.filter((general) => general.npcState !== 5);
const crew = crewGenerals.reduce((sum, general) => sum + general.crew, 0);
const crewMax = crewGenerals.reduce((sum, general) => sum + general.leadership * 100, 0);
const meta = asRecord(nation.meta);
return {
nation: {
id: nation.id,
name: nation.name,
color: nation.color,
level: nation.level,
power: typeof meta.power === 'number' ? meta.power : 0,
gold: nation.gold,
rice: nation.rice,
tech: Math.floor(nation.tech),
rate,
bill,
capitalCityId: nation.capitalCityId ?? 0,
generalCount: generals.length,
},
population: { current: population, max: populationMax },
crew: { current: crew, max: crewMax },
income: {
goldCity,
goldWar,
goldTotal: goldCity + goldWar,
riceCity,
riceWall,
riceTotal: riceCity + riceWall,
outcome,
},
budget: {
gold: nation.gold + goldCity + goldWar - outcome,
rice: nation.rice + riceCity + riceWall - outcome,
},
cities: cities.map((city) => ({
id: city.id,
name: city.name,
capital: city.id === nation.capitalCityId,
})),
history,
};
});
+2 -1
View File
@@ -6,6 +6,7 @@ import { getChiefCenter } from './endpoints/getChiefCenter.js';
import { getCityOverview } from './endpoints/getCityOverview.js';
import { getGeneralList } from './endpoints/getGeneralList.js';
import { getGeneralLog } from './endpoints/getGeneralLog.js';
import { getNationInfo } from './endpoints/getNationInfo.js';
import { getPersonnelInfo } from './endpoints/getPersonnelInfo.js';
import { getStratFinan } from './endpoints/getStratFinan.js';
import { kick } from './endpoints/kick.js';
@@ -18,6 +19,7 @@ import { setScoutMsg } from './endpoints/setScoutMsg.js';
import { setSecretLimit } from './endpoints/setSecretLimit.js';
export const nationRouter = router({
getNationInfo,
getGeneralList,
getCityOverview,
getPersonnelInfo,
@@ -36,4 +38,3 @@ export const nationRouter = router({
kick,
appoint,
});
+205 -6
View File
@@ -1,15 +1,37 @@
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import {
type WorldStateRow,
zWorldStateConfig,
zWorldStateMeta,
} from '../../context.js';
import { type WorldStateRow, zWorldStateConfig, zWorldStateMeta } from '../../context.js';
import { procedure, router } from '../../trpc.js';
import { authedProcedure } from '../../trpc.js';
import { asRecord, isRecord } from '@sammo-ts/common';
import { loadWorldMap } from '../../maps/worldMap.js';
import { loadMapLayout } from '../../maps/mapLayout.js';
import { getOwnedGeneral } from '../shared/general.js';
import { getMyGeneral, getOwnedGeneral } from '../shared/general.js';
const isWorldAdmin = (roles: readonly string[]): boolean =>
roles.some((role) => role === 'superuser' || role === 'admin' || role === 'admin.superuser');
const numberRecord = (value: unknown): Record<number, number> => {
if (!isRecord(value)) return {};
return Object.fromEntries(
Object.entries(value)
.map(([key, item]) => [Number(key), typeof item === 'number' ? item : Number.NaN] as const)
.filter(([key, item]) => Number.isFinite(key) && Number.isFinite(item))
);
};
const officerCity = (meta: unknown): number => {
const value = asRecord(meta);
const raw = value.officerCity ?? value.officer_city;
return typeof raw === 'number' && Number.isFinite(raw) ? raw : 0;
};
const defenceTrain = (meta: unknown): number => {
const value = asRecord(meta);
const raw = value.defenceTrain ?? value.defence_train;
return typeof raw === 'number' && Number.isFinite(raw) ? raw : 0;
};
const toWorldStateSnapshot = (row: WorldStateRow) => ({
scenarioCode: row.scenarioCode,
@@ -22,6 +44,183 @@ const toWorldStateSnapshot = (row: WorldStateRow) => ({
});
export const worldRouter = router({
getGlobalInfo: authedProcedure.query(async ({ ctx }) => {
const me = await getMyGeneral(ctx);
const [nations, cities, diplomacy, map] = await Promise.all([
ctx.db.nation.findMany({ where: { level: { gt: 0 } } }),
ctx.db.city.findMany({ orderBy: { id: 'asc' } }),
ctx.db.diplomacy.findMany({ where: { isDead: false, isShowing: true } }),
loadWorldMap(ctx, { generalId: me.id, neutralView: false, showMe: true }),
]);
if (!map) {
throw new TRPCError({ code: 'PRECONDITION_FAILED', message: 'World state is not initialized.' });
}
const nationRows = nations
.map((nation) => ({
id: nation.id,
name: nation.name,
color: nation.color,
capitalCityId: nation.capitalCityId ?? 0,
level: nation.level,
power: typeof asRecord(nation.meta).power === 'number' ? Number(asRecord(nation.meta).power) : 0,
cities: cities.filter((city) => city.nationId === nation.id).map((city) => city.name),
}))
.sort((left, right) => right.power - left.power || left.id - right.id);
const matrix: Record<number, Record<number, number>> = {};
for (const nation of nationRows) {
matrix[nation.id] = {};
for (const other of nationRows) matrix[nation.id]![other.id] = 2;
}
for (const relation of diplomacy) {
if (!matrix[relation.srcNationId]) continue;
const related = relation.srcNationId === me.nationId || relation.destNationId === me.nationId;
matrix[relation.srcNationId]![relation.destNationId] = related
? relation.stateCode
: [3, 4, 5, 6, 7].includes(relation.stateCode)
? 2
: relation.stateCode;
}
const conflict = cities.flatMap((city) => {
const raw = numberRecord(city.conflict);
const entries = Object.entries(raw);
if (entries.length < 2) return [];
const sum = entries.reduce((total, [, value]) => total + value, 0);
if (sum <= 0) return [];
return [
{
cityId: city.id,
cityName: city.name,
nations: Object.fromEntries(
entries.map(([id, value]) => [id, Math.round((value * 1000) / sum) / 10])
),
},
];
});
return { myNationId: me.nationId, nations: nationRows, diplomacy: matrix, conflict, map };
}),
getCurrentCity: authedProcedure
.input(z.object({ cityId: z.number().int().positive().optional() }).optional())
.query(async ({ ctx, input }) => {
const me = await getMyGeneral(ctx);
const admin = isWorldAdmin(ctx.auth?.user.roles ?? []);
const [cities, nation, nationGenerals, nations, world, layout] = await Promise.all([
ctx.db.city.findMany({ orderBy: { id: 'asc' } }),
me.nationId > 0 ? ctx.db.nation.findUnique({ where: { id: me.nationId } }) : null,
me.nationId > 0
? ctx.db.general.findMany({ where: { nationId: me.nationId }, select: { cityId: true } })
: [],
ctx.db.nation.findMany(),
ctx.db.worldState.findFirst(),
loadMapLayout(ctx.profile.scenario),
]);
const cityById = new Map(cities.map((city) => [city.id, city]));
const requested = input?.cityId && cityById.has(input.cityId) ? input.cityId : me.cityId;
const selected = cityById.get(requested);
if (!selected) throw new TRPCError({ code: 'NOT_FOUND', message: 'City not found' });
const spy = numberRecord(asRecord(nation?.meta).spyList ?? asRecord(nation?.meta).spy);
const selectable = new Set<number>([me.cityId]);
if (me.officerLevel > 0 && me.nationId > 0) {
cities.filter((city) => city.nationId === me.nationId).forEach((city) => selectable.add(city.id));
nationGenerals.forEach((general) => selectable.add(general.cityId));
Object.keys(spy).forEach((id) => selectable.add(Number(id)));
}
if (admin) cities.forEach((city) => selectable.add(city.id));
const full = admin || selectable.has(selected.id);
const ownCities = new Set(
cities.filter((city) => city.nationId === me.nationId && me.nationId > 0).map((city) => city.id)
);
const layoutCity = layout.cityList.find((city) => city.id === selected.id);
const detailed = full || Boolean(layoutCity?.path.some((id) => ownCities.has(id)));
const generals = detailed
? await ctx.db.general.findMany({ where: { cityId: selected.id }, orderBy: { turnTime: 'asc' } })
: [];
const generalIds = generals
.filter((general) => general.nationId === me.nationId && general.npcState <= 1)
.map((general) => general.id);
const turns = generalIds.length
? await ctx.db.generalTurn.findMany({
where: { generalId: { in: generalIds }, turnIdx: { lt: 5 } },
orderBy: [{ generalId: 'asc' }, { turnIdx: 'asc' }],
})
: [];
const turnMap = new Map<number, string[]>();
for (const turn of turns) {
const list = turnMap.get(turn.generalId) ?? [];
list[turn.turnIdx] = turn.actionCode;
turnMap.set(turn.generalId, list);
}
const nationMap = new Map(nations.map((item) => [item.id, item]));
const officers = await ctx.db.general.findMany({
where: { officerLevel: { in: [2, 3, 4] } },
select: { name: true, officerLevel: true, meta: true },
});
const selectedOfficers = Object.fromEntries(
officers
.filter((item) => officerCity(item.meta) === selected.id)
.map((item) => [item.officerLevel, item.name])
);
const redact = <T>(value: T): T | null => (full ? value : null);
const mappedGenerals = generals.map((general) => {
const ours = admin || (me.nationId > 0 && general.nationId === me.nationId);
return {
id: general.id,
name: general.name,
npcState: general.npcState,
picture: general.picture,
imageServer: general.imageServer,
nationId: general.nationId,
nationName: nationMap.get(general.nationId)?.name ?? '재야',
leadership: general.leadership,
strength: general.strength,
intelligence: general.intel,
injury: general.injury,
officerLevel: general.officerLevel,
defenceTrain: ours ? defenceTrain(general.meta) : null,
crewTypeId: ours ? general.crewTypeId : null,
crew: ours || full ? general.crew : null,
train: ours ? general.train : null,
atmos: ours ? general.atmos : null,
turns: ours && general.npcState <= 1 ? (turnMap.get(general.id) ?? []) : [],
};
});
return {
me: { id: me.id, nationId: me.nationId, officerLevel: me.officerLevel, admin },
options: [...selectable]
.map((id) => cityById.get(id))
.filter((city): city is NonNullable<typeof city> => Boolean(city))
.map((city) => ({ id: city.id, name: city.name, nationId: city.nationId })),
visibility: { full, detailed },
city: {
id: selected.id,
name: selected.name,
nationId: selected.nationId,
level: selected.level,
region: selected.region,
population: redact(selected.population),
populationMax: selected.populationMax,
agriculture: redact(selected.agriculture),
agricultureMax: selected.agricultureMax,
commerce: redact(selected.commerce),
commerceMax: selected.commerceMax,
security: redact(selected.security),
securityMax: selected.securityMax,
trust: redact(selected.trust),
trade: selected.trade,
defence: full || selected.nationId === 0 ? selected.defence : null,
defenceMax: selected.defenceMax,
wall: full || selected.nationId === 0 ? selected.wall : null,
wallMax: selected.wallMax,
officers: {
4: selectedOfficers[4] ?? '-',
3: selectedOfficers[3] ?? '-',
2: selectedOfficers[2] ?? '-',
},
},
generals: mappedGenerals,
lastExecute:
typeof asRecord(world?.meta).turntime === 'string' ? String(asRecord(world?.meta).turntime) : '',
};
}),
getState: procedure.query(async ({ ctx }) => {
const state = await ctx.db.worldState.findFirst();
return state ? toWorldStateSnapshot(state) : null;