내무부, 금/쌀수입, 감찰부 구현

This commit is contained in:
2026-01-18 16:40:12 +00:00
parent bb618a9ade
commit 5b51aad6d0
15 changed files with 2705 additions and 143 deletions
+844 -142
View File
@@ -2,8 +2,18 @@ import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { asNumber, asRecord } from '@sammo-ts/common';
import { LogCategory, LogScope } from '@sammo-ts/infra';
import {
calcCityGoldIncome,
calcCityRiceIncome,
calcCityWallIncome,
createIncomeActionContext,
DomesticTraitLoader,
getGoldIncome,
getOutcome,
getRiceIncome,
getWallIncome,
getWarGoldIncome,
loadDomesticTraitModules,
isDomesticTraitKey,
loadNationTraitModules,
@@ -15,13 +25,14 @@ import {
loadWarTraitModules,
WarTraitLoader,
isWarTraitKey,
type GeneralActionContext,
type General as LogicGeneral,
type CityIncomeSource,
type Nation as LogicNation,
type NationIncomeContext,
type TriggerNationalIncomeType,
type TriggerValue,
} from '@sammo-ts/logic';
import type { WorldStateRow } from '../../context.js';
import type { GameApiContext, InputJsonValue, WorldStateRow } from '../../context.js';
import { authedProcedure, router } from '../../trpc.js';
import { MAX_NATION_TURNS, listNationTurns } from '../../turns/reservedTurns.js';
import { getMyGeneral } from '../shared/general.js';
@@ -40,12 +51,6 @@ type TraitCache = {
type NationTraitModule = Awaited<ReturnType<typeof loadNationTraitModules>>[number] | null;
type NationIncomeContext = {
trait: NationTraitModule;
context: GeneralActionContext;
rate: number;
};
type NationIncomeRow = {
id: number;
name: string;
@@ -119,6 +124,46 @@ type GeneralOfficerRow = {
meta: unknown;
};
type NationCountRow = {
nationId: number;
count: number;
};
type NationStratRow = {
id: number;
name: string;
color: string;
level: number;
typeCode: string;
capitalCityId: number | null;
gold: number | null;
rice: number | null;
tech: number | null;
meta: unknown;
};
type DiplomacyRow = {
destNationId: number;
stateCode: number;
term: number;
};
type GeneralPowerRow = {
id: number;
nationId: number;
cityId: number;
npcState: number;
officerLevel: number;
leadership: number;
strength: number;
intel: number;
experience: number;
dedication: number;
gold: number;
rice: number;
meta: unknown;
};
const traitCache: TraitCache = {
domestic: new Map(),
war: new Map(),
@@ -127,6 +172,8 @@ const traitCache: TraitCache = {
};
const DEFAULT_CHIEF_STAT_MIN = 65;
const MAX_AVAILABLE_WAR_SETTING_CNT = 10;
const INC_AVAILABLE_WAR_SETTING_CNT = 2;
const normalizeTraitKey = (value: string | null | undefined): string | null => {
if (!value || value === 'None') {
@@ -140,6 +187,26 @@ const readMetaNumber = (meta: Record<string, unknown>, key: string, fallback: nu
return typeof raw === 'number' && Number.isFinite(raw) ? raw : fallback;
};
const readMetaBool = (meta: Record<string, unknown>, key: string, fallback = false): boolean => {
const raw = meta[key];
if (typeof raw === 'boolean') {
return raw;
}
if (typeof raw === 'number') {
return raw !== 0;
}
if (typeof raw === 'string') {
const lowered = raw.toLowerCase();
if (lowered === 'true' || lowered === '1') {
return true;
}
if (lowered === 'false' || lowered === '0') {
return false;
}
}
return fallback;
};
const resolveOfficerCity = (meta: Record<string, unknown>): number => {
const camel = readMetaNumber(meta, 'officerCity', 0);
if (camel > 0) {
@@ -172,6 +239,53 @@ const resolveNationRate = (nation: NationIncomeRow): number => {
return asNumber(meta.rate, 20);
};
const toIncomeCity = (city: CityIncomeRow): CityIncomeSource => ({
id: city.id,
population: city.population,
populationMax: city.populationMax,
agriculture: city.agriculture,
agricultureMax: city.agricultureMax,
commerce: city.commerce,
commerceMax: city.commerceMax,
security: city.security,
securityMax: city.securityMax,
trust: city.trust,
supplyState: city.supplyState,
defence: city.defence,
defenceMax: city.defenceMax,
wall: city.wall,
wallMax: city.wallMax,
meta: asRecord(city.meta),
});
const resolveNationBill = (meta: Record<string, unknown>): number => readMetaNumber(meta, 'bill', 100);
const resolveNationSecretLimit = (meta: Record<string, unknown>): number => {
const legacy = readMetaNumber(meta, 'secretlimit', -1);
if (legacy >= 0) {
return legacy;
}
return readMetaNumber(meta, 'secretLimit', 3);
};
const resolveNationBlockWar = (meta: Record<string, unknown>): boolean =>
readMetaBool(meta, 'war', readMetaBool(meta, 'blockWar', false));
const resolveNationBlockScout = (meta: Record<string, unknown>): boolean =>
readMetaBool(meta, 'scout', readMetaBool(meta, 'blockScout', false));
const resolveNationNotice = (meta: Record<string, unknown>): string =>
typeof meta.notice === 'string' ? meta.notice : '';
const resolveNationScoutMessage = (meta: Record<string, unknown>): string =>
typeof meta.infoText === 'string' ? meta.infoText : '';
const resolveWarSettingRemain = (meta: Record<string, unknown>): number => {
const legacy = readMetaNumber(meta, 'available_war_setting_cnt', -1);
const fallback = legacy >= 0 ? legacy : readMetaNumber(meta, 'availableWarSettingCnt', MAX_AVAILABLE_WAR_SETTING_CNT);
return Math.max(0, Math.min(MAX_AVAILABLE_WAR_SETTING_CNT, fallback));
};
const checkSecretMaxPermission = (penalty: Record<string, unknown>): number => {
if (penalty.noTopSecret) {
return 1;
@@ -234,46 +348,12 @@ const loadTraitNames = async (
return cache;
};
const buildIncomeContext = (nation: NationIncomeRow): GeneralActionContext => {
const buildNationIncomeContext = async (nation: NationIncomeRow): Promise<NationIncomeContext> => {
let trait: NationTraitModule = null;
if (isNationTraitKey(nation.typeCode)) {
[trait] = await loadNationTraitModules([nation.typeCode], new NationTraitLoader());
}
const nationMeta = asRecord(nation.meta) as Record<string, TriggerValue>;
const general: LogicGeneral = {
id: 0,
name: 'SYSTEM',
nationId: nation.id,
cityId: 0,
troopId: 0,
stats: { leadership: 0, strength: 0, intelligence: 0 },
experience: 0,
dedication: 0,
officerLevel: 0,
role: {
personality: null,
specialDomestic: null,
specialWar: null,
items: {
horse: null,
weapon: null,
book: null,
item: null,
},
},
injury: 0,
gold: 0,
rice: 0,
crew: 0,
crewTypeId: 0,
train: 0,
atmos: 0,
age: 0,
npcState: 0,
triggerState: {
flags: {},
counters: {},
modifiers: {},
meta: {},
},
meta: {},
};
const logicNation: LogicNation = {
id: nation.id,
name: nation.name,
@@ -287,105 +367,31 @@ const buildIncomeContext = (nation: NationIncomeRow): GeneralActionContext => {
typeCode: nation.typeCode,
meta: nationMeta,
};
return { general, nation: logicNation };
};
const buildNationIncomeContext = async (nation: NationIncomeRow): Promise<NationIncomeContext> => {
let trait: NationTraitModule = null;
if (isNationTraitKey(nation.typeCode)) {
[trait] = await loadNationTraitModules([nation.typeCode], new NationTraitLoader());
}
const actionContext = createIncomeActionContext(logicNation);
const modifyIncome = trait?.onCalcNationalIncome
? (type: TriggerNationalIncomeType, amount: number) => trait.onCalcNationalIncome!(actionContext, type, amount)
: undefined;
return {
trait,
context: buildIncomeContext(nation),
modifyIncome,
rate: resolveNationRate(nation),
};
};
const applyNationIncome = (
incomeContext: NationIncomeContext,
type: 'gold' | 'rice' | 'pop',
amount: number
): number => {
if (!incomeContext.trait?.onCalcNationalIncome) {
return amount;
const formatDateTime = (value: Date | null): string => {
if (!value) {
return '';
}
return incomeContext.trait.onCalcNationalIncome(incomeContext.context, type, amount);
const year = value.getFullYear();
const month = String(value.getMonth() + 1).padStart(2, '0');
const day = String(value.getDate()).padStart(2, '0');
const hours = String(value.getHours()).padStart(2, '0');
const minutes = String(value.getMinutes()).padStart(2, '0');
const seconds = String(value.getSeconds()).padStart(2, '0');
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
const calcCityGoldIncome = (
incomeContext: NationIncomeContext,
city: CityIncomeRow,
officerCnt: number,
isCapital: boolean,
nationLevel: number
): number => {
if (city.supplyState === 0) {
return 0;
}
const trustRatio = city.trust / 200 + 0.5;
const commMax = Math.max(1, city.commerceMax);
const secuMax = Math.max(1, city.securityMax);
let income = (city.population * city.commerce * trustRatio) / commMax / 30;
income *= 1 + city.security / secuMax / 10;
income *= Math.pow(1.05, officerCnt);
if (isCapital && nationLevel > 0) {
income *= 1 + 1 / (3 * nationLevel);
}
const adjusted = applyNationIncome(incomeContext, 'gold', income);
return Math.round(adjusted * (incomeContext.rate / 20));
};
const calcCityRiceIncome = (
incomeContext: NationIncomeContext,
city: CityIncomeRow,
officerCnt: number,
isCapital: boolean,
nationLevel: number
): number => {
if (city.supplyState === 0) {
return 0;
}
const trustRatio = city.trust / 200 + 0.5;
const agriMax = Math.max(1, city.agricultureMax);
const secuMax = Math.max(1, city.securityMax);
let income = (city.population * city.agriculture * trustRatio) / agriMax / 30;
income *= 1 + city.security / secuMax / 10;
income *= Math.pow(1.05, officerCnt);
if (isCapital && nationLevel > 0) {
income *= 1 + 1 / (3 * nationLevel);
}
const adjusted = applyNationIncome(incomeContext, 'rice', income);
return Math.round(adjusted * (incomeContext.rate / 20));
};
const calcCityWallIncome = (
incomeContext: NationIncomeContext,
city: CityIncomeRow,
officerCnt: number,
isCapital: boolean,
nationLevel: number
): number => {
if (city.supplyState === 0) {
return 0;
}
const wallMax = Math.max(1, city.wallMax);
const secuMax = Math.max(1, city.securityMax);
let income = (city.defence * city.wall) / wallMax / 3;
income *= 1 + city.security / secuMax / 10;
income *= Math.pow(1.05, officerCnt);
if (isCapital && nationLevel > 0) {
income *= 1 + 1 / (3 * nationLevel);
}
const adjusted = applyNationIncome(incomeContext, 'rice', income);
return Math.round(adjusted * (incomeContext.rate / 20));
};
const zGeneralLogType = z.enum(['generalHistory', 'generalAction', 'battleResult', 'battleDetail']);
type GeneralLogType = z.infer<typeof zGeneralLogType>;
const assertNationAccess = (general: { nationId: number; officerLevel: number }) => {
if (general.nationId <= 0 || general.officerLevel <= 0) {
@@ -393,6 +399,58 @@ const assertNationAccess = (general: { nationId: number; officerLevel: number })
}
};
const resolveNationPermission = (
general: { nationId: number; officerLevel: number; meta: unknown; penalty: unknown },
nationMeta: unknown,
checkSecretLimit = true
): number =>
resolveSecretPermission(
{
nationId: general.nationId,
officerLevel: general.officerLevel,
meta: general.meta,
penalty: general.penalty,
},
nationMeta,
checkSecretLimit
);
const assertNationEditable = (
general: { nationId: number; officerLevel: number; meta: unknown; penalty: unknown },
nationMeta: unknown
): void => {
const permission = resolveNationPermission(general, nationMeta, false);
if (permission < 0) {
throw new TRPCError({ code: 'FORBIDDEN', message: '권한이 부족합니다.' });
}
if (general.officerLevel < 5 && permission !== 4) {
throw new TRPCError({ code: 'FORBIDDEN', message: '권한이 부족합니다.' });
}
};
const updateNationMeta = async (
ctx: Pick<GameApiContext, 'db'>,
nationId: number,
updates: Record<string, unknown>
): Promise<InputJsonValue> => {
const nation = await ctx.db.nation.findUnique({
where: { id: nationId },
select: { meta: true },
});
if (!nation) {
throw new TRPCError({ code: 'NOT_FOUND', message: 'Nation not found' });
}
const meta = asRecord(nation.meta);
const nextMeta = { ...meta, ...updates } as InputJsonValue;
await ctx.db.nation.update({
where: { id: nationId },
data: {
meta: nextMeta,
},
});
return nextMeta;
};
const mapGeneralList = async (
generals: GeneralListRow[],
cityNameMap: Map<number, string>,
@@ -632,10 +690,11 @@ export const nationRouter = router({
const officers = officerByCity.get(city.id) ?? {};
const officerCnt = officerCntByCity.get(city.id) ?? 0;
const isCapital = nation.capitalCityId === city.id;
const incomeCity = toIncomeCity(city);
const incomes = {
gold: calcCityGoldIncome(incomeContext, city, officerCnt, isCapital, nation.level),
rice: calcCityRiceIncome(incomeContext, city, officerCnt, isCapital, nation.level),
wall: calcCityWallIncome(incomeContext, city, officerCnt, isCapital, nation.level),
gold: calcCityGoldIncome(incomeContext, incomeCity, officerCnt, isCapital, nation.level),
rice: calcCityRiceIncome(incomeContext, incomeCity, officerCnt, isCapital, nation.level),
wall: calcCityWallIncome(incomeContext, incomeCity, officerCnt, isCapital, nation.level),
};
return {
@@ -871,6 +930,649 @@ export const nationRouter = router({
},
};
}),
getStratFinan: authedProcedure.query(async ({ ctx }) => {
const me = await getMyGeneral(ctx);
assertNationAccess(me);
const [nation, worldState, nationRows, diplomacyRows, generalCounts, cityCounts, cityRows, generalRows] =
(await Promise.all([
ctx.db.nation.findUnique({
where: { id: me.nationId },
select: {
id: true,
name: true,
color: true,
level: true,
typeCode: true,
capitalCityId: true,
gold: true,
rice: true,
tech: true,
meta: true,
},
}),
ctx.db.worldState.findFirst(),
ctx.db.nation.findMany({
select: {
id: true,
name: true,
color: true,
level: true,
typeCode: true,
capitalCityId: true,
gold: true,
rice: true,
tech: true,
meta: true,
},
orderBy: { id: 'asc' },
}),
ctx.db.diplomacy.findMany({
where: { srcNationId: me.nationId },
select: {
destNationId: true,
stateCode: true,
term: true,
},
}),
ctx.db.$queryRaw<NationCountRow[]>`
SELECT nation_id as "nationId", COUNT(*)::int as "count"
FROM general
GROUP BY nation_id
`,
ctx.db.$queryRaw<NationCountRow[]>`
SELECT nation_id as "nationId", COUNT(*)::int as "count"
FROM city
GROUP BY nation_id
`,
ctx.db.city.findMany({
select: {
id: true,
name: true,
level: true,
nationId: true,
region: true,
population: true,
populationMax: true,
agriculture: true,
agricultureMax: true,
commerce: true,
commerceMax: true,
security: true,
securityMax: true,
trust: true,
trade: true,
defence: true,
defenceMax: true,
wall: true,
wallMax: true,
supplyState: true,
frontState: true,
meta: true,
},
}),
ctx.db.general.findMany({
select: {
id: true,
nationId: true,
cityId: true,
npcState: true,
officerLevel: true,
leadership: true,
strength: true,
intel: true,
experience: true,
dedication: true,
gold: true,
rice: true,
meta: true,
},
}),
])) as [
(NationIncomeRow & { tech: number | null }) | null,
WorldStateRow | null,
NationStratRow[],
DiplomacyRow[],
NationCountRow[],
NationCountRow[],
CityIncomeRow[],
GeneralPowerRow[],
];
if (!nation) {
throw new TRPCError({ code: 'NOT_FOUND', message: 'Nation not found' });
}
if (!worldState) {
throw new TRPCError({ code: 'PRECONDITION_FAILED', message: 'World state is not initialized.' });
}
const permissionLevel = resolveNationPermission(me, nation.meta, true);
if (permissionLevel < 1) {
throw new TRPCError({ code: 'FORBIDDEN', message: '권한이 부족합니다.' });
}
const nationMeta = asRecord(nation.meta);
const editable = me.officerLevel >= 5 || permissionLevel === 4;
const generalCountMap = new Map<number, number>();
for (const row of generalCounts) {
generalCountMap.set(row.nationId, row.count);
}
const cityCountMap = new Map<number, number>();
for (const row of cityCounts) {
cityCountMap.set(row.nationId, row.count);
}
const diplomacyMap = new Map<number, { state: number; term: number | null }>();
for (const row of diplomacyRows) {
diplomacyMap.set(row.destNationId, { state: row.stateCode, term: row.term });
}
const cityStatsByNation = new Map<number, { popSum: number; valueSum: number; maxSum: number }>();
for (const city of cityRows) {
const entry = cityStatsByNation.get(city.nationId) ?? { popSum: 0, valueSum: 0, maxSum: 0 };
const valueSum =
city.population +
city.agriculture +
city.commerce +
city.security +
city.wall +
city.defence;
const maxSum =
city.populationMax +
city.agricultureMax +
city.commerceMax +
city.securityMax +
city.wallMax +
city.defenceMax;
entry.popSum += city.population;
entry.valueSum += valueSum;
entry.maxSum += maxSum;
cityStatsByNation.set(city.nationId, entry);
}
const generalStatsByNation = new Map<number, { goldRice: number; statPower: number; expDed: number }>();
for (const general of generalRows) {
const entry = generalStatsByNation.get(general.nationId) ?? { goldRice: 0, statPower: 0, expDed: 0 };
entry.goldRice += general.gold + general.rice;
const leadership = general.leadership;
const strength = general.strength;
const intel = general.intel;
const npcMultiplier = general.npcState < 2 ? 1.2 : 1;
const leaderCore = leadership >= 40 ? leadership : 0;
entry.statPower += npcMultiplier * leaderCore * 2 + (Math.sqrt(intel * strength) * 2 + leadership / 2) / 2;
entry.expDed += general.experience + general.dedication;
generalStatsByNation.set(general.nationId, entry);
}
const powerByNation = new Map<number, number>();
for (const nationItem of nationRows) {
const generalStats = generalStatsByNation.get(nationItem.id) ?? { goldRice: 0, statPower: 0, expDed: 0 };
const cityStats = cityStatsByNation.get(nationItem.id) ?? { popSum: 0, valueSum: 0, maxSum: 0 };
const resource = Math.round(((nationItem.gold ?? 0) + (nationItem.rice ?? 0) + generalStats.goldRice) / 100);
const tech = nationItem.tech ?? 0;
const cityPower =
nationItem.level > 0 && cityStats.maxSum > 0
? Math.round((cityStats.popSum * cityStats.valueSum) / cityStats.maxSum / 100)
: 0;
const expDed = Math.round(generalStats.expDed / 100);
powerByNation.set(
nationItem.id,
Math.round((resource + tech + cityPower + generalStats.statPower + expDed) / 10)
);
}
const nationsList = nationRows.map((nationItem) => {
const diplomacy =
nationItem.id === nation.id
? { state: 7, term: null }
: diplomacyMap.get(nationItem.id) ?? { state: 2, term: 0 };
return {
id: nationItem.id,
name: nationItem.name,
color: nationItem.color,
level: nationItem.level,
power: powerByNation.get(nationItem.id) ?? 0,
generalCount: generalCountMap.get(nationItem.id) ?? 0,
cityCount: cityCountMap.get(nationItem.id) ?? 0,
diplomacy,
};
});
const nationCities = cityRows.filter((city) => city.nationId === nation.id);
const nationGenerals = generalRows.filter((general) => general.nationId === nation.id);
const officerCntByCity = new Map<number, number>();
for (const general of nationGenerals) {
if (general.officerLevel < 2 || general.officerLevel > 4) {
continue;
}
const officerCity = resolveOfficerCity(asRecord(general.meta));
if (!officerCity || general.cityId !== officerCity) {
continue;
}
officerCntByCity.set(officerCity, (officerCntByCity.get(officerCity) ?? 0) + 1);
}
const incomeContext = await buildNationIncomeContext(nation);
const baseIncomeContext: NationIncomeContext = { ...incomeContext, rate: 100 };
const incomeCities = nationCities.map(toIncomeCity);
const goldCityIncome = getGoldIncome(
baseIncomeContext,
incomeCities,
officerCntByCity,
nation.capitalCityId ?? 0,
nation.level
);
const riceCityIncome = getRiceIncome(
baseIncomeContext,
incomeCities,
officerCntByCity,
nation.capitalCityId ?? 0,
nation.level
);
const riceWallIncome = getWallIncome(
baseIncomeContext,
incomeCities,
officerCntByCity,
nation.capitalCityId ?? 0,
nation.level
);
const warGoldIncome = getWarGoldIncome(baseIncomeContext, incomeCities);
const outcome = getOutcome(
100,
nationGenerals.filter((general) => general.npcState !== 5)
);
return {
editable,
nationMsg: resolveNationNotice(nationMeta),
scoutMsg: resolveNationScoutMessage(nationMeta),
nationId: nation.id,
officerLevel: me.officerLevel,
year: worldState.currentYear,
month: worldState.currentMonth,
nationsList,
gold: nation.gold ?? 0,
rice: nation.rice ?? 0,
income: {
gold: {
city: goldCityIncome,
war: warGoldIncome,
},
rice: {
city: riceCityIncome,
wall: riceWallIncome,
},
},
outcome,
policy: {
rate: resolveNationRate(nation),
bill: resolveNationBill(nationMeta),
secretLimit: resolveNationSecretLimit(nationMeta),
blockScout: resolveNationBlockScout(nationMeta),
blockWar: resolveNationBlockWar(nationMeta),
},
warSettingCnt: {
remain: resolveWarSettingRemain(nationMeta),
inc: INC_AVAILABLE_WAR_SETTING_CNT,
max: MAX_AVAILABLE_WAR_SETTING_CNT,
},
};
}),
setNotice: authedProcedure
.input(
z.object({
msg: z.string().max(16384),
})
)
.mutation(async ({ ctx, input }) => {
const me = await getMyGeneral(ctx);
assertNationAccess(me);
const nation = await ctx.db.nation.findUnique({
where: { id: me.nationId },
select: { meta: true },
});
if (!nation) {
throw new TRPCError({ code: 'NOT_FOUND', message: 'Nation not found' });
}
assertNationEditable(me, nation.meta);
await updateNationMeta(ctx, me.nationId, {
notice: input.msg,
});
return { ok: true };
}),
setScoutMsg: authedProcedure
.input(
z.object({
msg: z.string().max(1000),
})
)
.mutation(async ({ ctx, input }) => {
const me = await getMyGeneral(ctx);
assertNationAccess(me);
const nation = await ctx.db.nation.findUnique({
where: { id: me.nationId },
select: { meta: true },
});
if (!nation) {
throw new TRPCError({ code: 'NOT_FOUND', message: 'Nation not found' });
}
assertNationEditable(me, nation.meta);
await updateNationMeta(ctx, me.nationId, {
infoText: input.msg,
});
return { ok: true };
}),
setRate: authedProcedure
.input(
z.object({
amount: z.number().int().min(5).max(30),
})
)
.mutation(async ({ ctx, input }) => {
const me = await getMyGeneral(ctx);
assertNationAccess(me);
const nation = await ctx.db.nation.findUnique({
where: { id: me.nationId },
select: { meta: true },
});
if (!nation) {
throw new TRPCError({ code: 'NOT_FOUND', message: 'Nation not found' });
}
assertNationEditable(me, nation.meta);
await updateNationMeta(ctx, me.nationId, {
rate: input.amount,
});
return { ok: true };
}),
setBill: authedProcedure
.input(
z.object({
amount: z.number().int().min(20).max(200),
})
)
.mutation(async ({ ctx, input }) => {
const me = await getMyGeneral(ctx);
assertNationAccess(me);
const nation = await ctx.db.nation.findUnique({
where: { id: me.nationId },
select: { meta: true },
});
if (!nation) {
throw new TRPCError({ code: 'NOT_FOUND', message: 'Nation not found' });
}
assertNationEditable(me, nation.meta);
await updateNationMeta(ctx, me.nationId, {
bill: input.amount,
});
return { ok: true };
}),
setSecretLimit: authedProcedure
.input(
z.object({
amount: z.number().int().min(1).max(99),
})
)
.mutation(async ({ ctx, input }) => {
const me = await getMyGeneral(ctx);
assertNationAccess(me);
const nation = await ctx.db.nation.findUnique({
where: { id: me.nationId },
select: { meta: true },
});
if (!nation) {
throw new TRPCError({ code: 'NOT_FOUND', message: 'Nation not found' });
}
assertNationEditable(me, nation.meta);
await updateNationMeta(ctx, me.nationId, {
secretlimit: input.amount,
});
return { ok: true };
}),
setBlockWar: authedProcedure
.input(
z.object({
value: z.boolean(),
})
)
.mutation(async ({ ctx, input }) => {
const me = await getMyGeneral(ctx);
assertNationAccess(me);
const nation = await ctx.db.nation.findUnique({
where: { id: me.nationId },
select: { meta: true },
});
if (!nation) {
throw new TRPCError({ code: 'NOT_FOUND', message: 'Nation not found' });
}
assertNationEditable(me, nation.meta);
const meta = asRecord(nation.meta);
const remain = resolveWarSettingRemain(meta);
if (remain <= 0) {
throw new TRPCError({ code: 'BAD_REQUEST', message: '잔여 횟수가 부족합니다.' });
}
const nextRemain = Math.max(0, remain - 1);
await updateNationMeta(ctx, me.nationId, {
war: input.value ? 1 : 0,
available_war_setting_cnt: nextRemain,
});
return { availableCnt: nextRemain };
}),
setBlockScout: authedProcedure
.input(
z.object({
value: z.boolean(),
})
)
.mutation(async ({ ctx, input }) => {
const me = await getMyGeneral(ctx);
assertNationAccess(me);
const nation = await ctx.db.nation.findUnique({
where: { id: me.nationId },
select: { meta: true },
});
if (!nation) {
throw new TRPCError({ code: 'NOT_FOUND', message: 'Nation not found' });
}
assertNationEditable(me, nation.meta);
await updateNationMeta(ctx, me.nationId, {
scout: input.value ? 1 : 0,
});
return { ok: true };
}),
getBattleCenter: authedProcedure.query(async ({ ctx }) => {
const me = await getMyGeneral(ctx);
assertNationAccess(me);
const [nation, worldState, generalRows] = await Promise.all([
ctx.db.nation.findUnique({
where: { id: me.nationId },
select: {
id: true,
name: true,
color: true,
level: true,
meta: true,
},
}),
ctx.db.worldState.findFirst(),
ctx.db.general.findMany({
where: { nationId: me.nationId },
select: {
id: true,
name: true,
npcState: true,
officerLevel: true,
cityId: true,
turnTime: true,
recentWarTime: true,
leadership: true,
strength: true,
intel: true,
experience: true,
dedication: true,
injury: true,
gold: true,
rice: true,
crew: true,
train: true,
atmos: true,
},
orderBy: { id: 'asc' },
}),
]);
if (!nation) {
throw new TRPCError({ code: 'NOT_FOUND', message: 'Nation not found' });
}
if (!worldState) {
throw new TRPCError({ code: 'PRECONDITION_FAILED', message: 'World state is not initialized.' });
}
const permissionLevel = resolveNationPermission(me, nation.meta, true);
if (permissionLevel < 1) {
throw new TRPCError({ code: 'FORBIDDEN', message: '권한이 부족합니다.' });
}
const generalIds = generalRows.map((general) => general.id);
const battleCounts =
generalIds.length > 0
? await ctx.db.logEntry.groupBy({
by: ['generalId'],
where: {
generalId: { in: generalIds },
category: LogCategory.BATTLE_BRIEF,
},
_count: { _all: true },
})
: [];
const battleCountMap = new Map<number, number>();
for (const row of battleCounts) {
if (row.generalId !== null) {
battleCountMap.set(row.generalId, row._count._all);
}
}
const generals = generalRows.map((general) => ({
id: general.id,
name: general.name,
npcState: general.npcState,
officerLevel: general.officerLevel,
cityId: general.cityId,
turnTime: formatDateTime(general.turnTime),
recentWar: formatDateTime(general.recentWarTime),
warnum: battleCountMap.get(general.id) ?? 0,
stats: {
leadership: general.leadership,
strength: general.strength,
intelligence: general.intel,
},
experience: general.experience,
dedication: general.dedication,
injury: general.injury,
gold: general.gold,
rice: general.rice,
crew: general.crew,
train: general.train,
atmos: general.atmos,
}));
return {
me: {
id: me.id,
officerLevel: me.officerLevel,
permissionLevel,
},
nation: {
id: nation.id,
name: nation.name,
color: nation.color,
level: nation.level,
},
currentYear: worldState.currentYear,
currentMonth: worldState.currentMonth,
turnTermMinutes: Math.max(1, Math.round(worldState.tickSeconds / 60)),
generals,
};
}),
getGeneralLog: authedProcedure
.input(
z.object({
generalId: z.number().int().positive(),
type: zGeneralLogType,
})
)
.query(async ({ ctx, input }) => {
const me = await getMyGeneral(ctx);
assertNationAccess(me);
const [nation, target] = await Promise.all([
ctx.db.nation.findUnique({
where: { id: me.nationId },
select: { meta: true },
}),
ctx.db.general.findUnique({
where: { id: input.generalId },
select: { id: true, nationId: true, npcState: true },
}),
]);
if (!nation) {
throw new TRPCError({ code: 'NOT_FOUND', message: 'Nation not found' });
}
if (!target) {
throw new TRPCError({ code: 'NOT_FOUND', message: 'General not found' });
}
const permissionLevel = resolveNationPermission(me, nation.meta, true);
if (permissionLevel < 1) {
throw new TRPCError({ code: 'FORBIDDEN', message: '권한이 부족합니다.' });
}
if (target.nationId !== me.nationId) {
throw new TRPCError({ code: 'FORBIDDEN', message: '같은 나라의 장수가 아닙니다.' });
}
if (
input.type === 'generalAction' &&
target.npcState < 2 &&
target.id !== me.id &&
permissionLevel < 2
) {
throw new TRPCError({
code: 'FORBIDDEN',
message: '권한이 부족합니다. 유저 장수의 개인 기록은 수뇌만 열람 가능합니다.',
});
}
const categoryMap: Record<GeneralLogType, LogCategory> = {
generalHistory: LogCategory.HISTORY,
generalAction: LogCategory.ACTION,
battleResult: LogCategory.BATTLE_BRIEF,
battleDetail: LogCategory.BATTLE_DETAIL,
};
const logs = await ctx.db.logEntry.findMany({
where: {
generalId: target.id,
scope: LogScope.GENERAL,
category: categoryMap[input.type],
},
orderBy: { id: 'desc' },
take: 30,
});
return {
type: input.type,
generalId: target.id,
logs: logs.map((entry) => ({
id: entry.id,
text: entry.text,
})),
};
}),
getChiefCenter: authedProcedure.query(async ({ ctx }) => {
const me = await getMyGeneral(ctx);
assertNationAccess(me);
@@ -0,0 +1,22 @@
import type { TurnCalendarHandler } from './inMemoryWorld.js';
export const composeCalendarHandlers = (
...handlers: Array<TurnCalendarHandler | null | undefined>
): TurnCalendarHandler | null => {
const resolved = handlers.filter(Boolean) as TurnCalendarHandler[];
if (resolved.length === 0) {
return null;
}
return {
onMonthChanged: (context) => {
for (const handler of resolved) {
handler.onMonthChanged?.(context);
}
},
onYearChanged: (context) => {
for (const handler of resolved) {
handler.onYearChanged?.(context);
}
},
};
};
+281
View File
@@ -0,0 +1,281 @@
import { asNumber, asRecord } from '@sammo-ts/common';
import {
ActionLogger,
LogFormat,
createIncomeActionContext,
getBill,
getGoldIncome,
getOutcome,
getRiceIncome,
getWallIncome,
type CityIncomeSource,
type Nation,
type NationIncomeContext,
type NationTraitModule,
type TriggerNationalIncomeType,
} from '@sammo-ts/logic';
import type { ScenarioConfig } from '@sammo-ts/logic';
import type { InMemoryTurnWorld, TurnCalendarHandler, TurnCalendarContext } from './inMemoryWorld.js';
import type { TurnGeneral } from './types.js';
const resolveNumber = (source: Record<string, unknown>, keys: string[], fallback: number): number => {
for (const key of keys) {
const value = source[key];
if (typeof value === 'number' && Number.isFinite(value)) {
return value;
}
}
return fallback;
};
const resolveNationRate = (nation: Nation): number => asNumber(nation.meta.rate, 20);
const resolveNationBill = (nation: Nation): number => asNumber(nation.meta.bill, 100);
const resolveOfficerCity = (meta: Record<string, unknown>): number => {
const camel = asNumber(meta.officerCity, 0);
if (camel > 0) {
return camel;
}
return asNumber(meta.officer_city, 0);
};
const resolveCityTrust = (meta: Record<string, unknown>): number => {
const trust = asNumber(meta.trust, 50);
return trust;
};
const toIncomeCity = (city: ReturnType<InMemoryTurnWorld['listCities']>[number]): CityIncomeSource => ({
id: city.id,
population: city.population,
populationMax: city.populationMax,
agriculture: city.agriculture,
agricultureMax: city.agricultureMax,
commerce: city.commerce,
commerceMax: city.commerceMax,
security: city.security,
securityMax: city.securityMax,
trust: resolveCityTrust(asRecord(city.meta)),
supplyState: city.supplyState,
defence: city.defence,
defenceMax: city.defenceMax,
wall: city.wall,
wallMax: city.wallMax,
meta: asRecord(city.meta),
});
const buildNationIncomeContext = (nation: Nation, trait: NationTraitModule | null): NationIncomeContext => {
const actionContext = createIncomeActionContext(nation);
const modifyIncome = trait?.onCalcNationalIncome
? (type: TriggerNationalIncomeType, amount: number) => trait.onCalcNationalIncome!(actionContext, type, amount)
: undefined;
return {
rate: resolveNationRate(nation),
modifyIncome,
};
};
const buildOfficerCountMap = (generals: TurnGeneral[]): Map<number, number> => {
const officerCntByCity = new Map<number, number>();
for (const general of generals) {
if (general.officerLevel < 2 || general.officerLevel > 4) {
continue;
}
const officerCity = resolveOfficerCity(asRecord(general.meta));
if (!officerCity || general.cityId !== officerCity) {
continue;
}
officerCntByCity.set(officerCity, (officerCntByCity.get(officerCity) ?? 0) + 1);
}
return officerCntByCity;
};
const pushLogs = (world: InMemoryTurnWorld, logs: ReturnType<ActionLogger['flush']>): void => {
for (const log of logs) {
world.pushLog(log);
}
};
const roundResource = (value: number): number => Math.round(value);
const applyIncomeOutcome = (
current: number,
income: number,
outcome: number,
baseResource: number,
originOutcome: number
): { next: number; ratio: number; realOutcome: number } => {
let next = current + income;
let realOutcome = 0;
if (next < baseResource) {
realOutcome = 0;
next = baseResource;
} else if (next - baseResource < outcome) {
realOutcome = next - baseResource;
next = baseResource;
} else {
realOutcome = outcome;
next -= realOutcome;
}
const ratio = originOutcome > 0 ? realOutcome / originOutcome : 0;
return { next: Math.max(next, baseResource), ratio, realOutcome };
};
const processIncomeForNation = (
world: InMemoryTurnWorld,
nation: Nation,
generals: TurnGeneral[],
cities: ReturnType<InMemoryTurnWorld['listCities']>,
officerCounts: Map<number, number>,
traitMap: Map<string, NationTraitModule>,
type: 'gold' | 'rice',
baseResource: number
): void => {
const nationCities = cities.filter((city) => city.nationId === nation.id).map(toIncomeCity);
const nationGenerals = generals.filter((general) => general.nationId === nation.id && general.npcState !== 5);
const trait = traitMap.get(nation.typeCode) ?? null;
const incomeContext = buildNationIncomeContext(nation, trait);
let income = 0;
if (type === 'gold') {
income = getGoldIncome(
incomeContext,
nationCities,
officerCounts,
nation.capitalCityId ?? 0,
nation.level
);
} else {
income =
getRiceIncome(
incomeContext,
nationCities,
officerCounts,
nation.capitalCityId ?? 0,
nation.level
) +
getWallIncome(
incomeContext,
nationCities,
officerCounts,
nation.capitalCityId ?? 0,
nation.level
);
}
const incomeValue = roundResource(income);
const originOutcome = getOutcome(100, nationGenerals);
const bill = resolveNationBill(nation);
const outcome = Math.round((bill / 100) * originOutcome);
const current = type === 'gold' ? nation.gold : nation.rice;
const { next, ratio } = applyIncomeOutcome(current, incomeValue, outcome, baseResource, originOutcome);
const nextMeta = {
...nation.meta,
[`prev_income_${type}`]: incomeValue,
};
if (type === 'gold') {
world.updateNation(nation.id, { gold: next, meta: nextMeta });
} else {
world.updateNation(nation.id, { rice: next, meta: nextMeta });
}
const incomeText = incomeValue.toLocaleString();
const incomeLog = type === 'gold' ? `이번 수입은 금 <C>${incomeText}</>입니다.` : `이번 수입은 쌀 <C>${incomeText}</>입니다.`;
for (const general of nationGenerals) {
const pay = Math.round(getBill(general.dedication) * ratio);
if (type === 'gold') {
world.updateGeneral(general.id, { gold: general.gold + pay });
} else {
world.updateGeneral(general.id, { rice: general.rice + pay });
}
const logger = new ActionLogger({ generalId: general.id, nationId: nation.id });
if (general.officerLevel > 4) {
logger.pushGeneralActionLog(incomeLog, LogFormat.PLAIN);
}
const payText = pay.toLocaleString();
const payLog =
type === 'gold'
? `봉급으로 금 <C>${payText}</>을 받았습니다.`
: `봉급으로 쌀 <C>${payText}</>을 받았습니다.`;
logger.pushGeneralActionLog(payLog, LogFormat.PLAIN);
pushLogs(world, logger.flush());
}
};
export const createIncomeHandler = (options: {
getWorld: () => InMemoryTurnWorld | null;
scenarioConfig: ScenarioConfig;
nationTraits: Map<string, NationTraitModule>;
}): TurnCalendarHandler => {
const constValues = asRecord(options.scenarioConfig.const);
const baseGold = resolveNumber(constValues, ['baseGold', 'basegold'], 0);
const baseRice = resolveNumber(constValues, ['baseRice', 'baserice'], 0);
const handler: TurnCalendarHandler = {
onMonthChanged: (context: TurnCalendarContext) => {
const world = options.getWorld();
if (!world) {
return;
}
const month = context.currentMonth;
if (month !== 1 && month !== 7) {
return;
}
const nations = world.listNations();
const generals = world.listGenerals();
const cities = world.listCities();
const byNation: Map<number, TurnGeneral[]> = new Map();
for (const general of generals) {
const bucket = byNation.get(general.nationId) ?? [];
bucket.push(general);
byNation.set(general.nationId, bucket);
}
for (const nation of nations) {
const nationGenerals = byNation.get(nation.id) ?? [];
const officerCounts = buildOfficerCountMap(nationGenerals);
if (month === 1) {
processIncomeForNation(
world,
nation,
nationGenerals,
cities,
officerCounts,
options.nationTraits,
'gold',
baseGold
);
} else if (month === 7) {
processIncomeForNation(
world,
nation,
nationGenerals,
cities,
officerCounts,
options.nationTraits,
'rice',
baseRice
);
}
}
const logger = new ActionLogger();
if (month === 1) {
logger.pushGlobalHistoryLog('<W><b>【지급】</b></>봄이 되어 봉록에 따라 자금이 지급됩니다.');
} else if (month === 7) {
logger.pushGlobalHistoryLog('<W><b>【지급】</b></>가을이 되어 봉록에 따라 군량이 지급됩니다.');
}
pushLogs(world, logger.flush());
},
};
return handler;
};
+12 -1
View File
@@ -1,6 +1,7 @@
import type { TurnCommandProfile, TurnSchedule } from '@sammo-ts/logic';
import { buildGameEventChannel, type RealtimeEvent } from '@sammo-ts/common';
import { createRedisConnector, resolveRedisConfigFromEnv } from '@sammo-ts/infra';
import { NATION_TRAIT_KEYS, NationTraitLoader, loadNationTraitModules } from '@sammo-ts/logic';
import { SystemClock } from '../lifecycle/clock.js';
import { getNextTickTime } from '../lifecycle/getNextTickTime.js';
@@ -16,6 +17,8 @@ import { InMemoryTurnProcessor } from './inMemoryTurnProcessor.js';
import { InMemoryTurnStateStore } from './inMemoryStateStore.js';
import { createGatewayAdminActionConsumer } from './gatewayAdminActions.js';
import { createGatewayProfileGate } from './gatewayProfileGate.js';
import { composeCalendarHandlers } from './calendarHandlers.js';
import { createIncomeHandler } from './incomeHandler.js';
import { createReservedTurnHandler } from './reservedTurnHandler.js';
import { createReservedTurnStore } from './reservedTurnStore.js';
import { createTurnDaemonCommandHandler } from './worldCommandHandler.js';
@@ -100,6 +103,8 @@ export const createTurnDaemonRuntime = async (options: TurnDaemonRuntimeOptions)
})
: await loadTurnCommandProfile());
let worldRef: InMemoryTurnWorld | null = null;
const nationTraits = await loadNationTraitModules([...NATION_TRAIT_KEYS], new NationTraitLoader());
const nationTraitMap = new Map(nationTraits.map((module) => [module.key, module]));
const unification = options.calendarHandler
? null
: createUnificationHandler({
@@ -107,6 +112,12 @@ export const createTurnDaemonRuntime = async (options: TurnDaemonRuntimeOptions)
profileName: options.profileName ?? options.profile,
getWorld: () => worldRef,
});
const incomeHandler = createIncomeHandler({
getWorld: () => worldRef,
scenarioConfig: snapshot.scenarioConfig,
nationTraits: nationTraitMap,
});
const calendarHandler = composeCalendarHandlers(options.calendarHandler ?? unification?.handler, incomeHandler);
const worldOptions: InMemoryTurnWorldOptions = {
schedule,
generalTurnHandler:
@@ -120,7 +131,7 @@ export const createTurnDaemonRuntime = async (options: TurnDaemonRuntimeOptions)
getWorld: () => worldRef,
commandProfile,
})),
calendarHandler: options.calendarHandler ?? unification?.handler,
calendarHandler: calendarHandler ?? undefined,
};
const world = new InMemoryTurnWorld(resolvedState, snapshot, worldOptions);
worldRef = world;
+20
View File
@@ -7,7 +7,9 @@ import InheritView from '../views/InheritView.vue';
import NationCitiesView from '../views/NationCitiesView.vue';
import NationGeneralsView from '../views/NationGeneralsView.vue';
import NationPersonnelView from '../views/NationPersonnelView.vue';
import NationStratFinanView from '../views/NationStratFinanView.vue';
import ChiefCenterView from '../views/ChiefCenterView.vue';
import BattleCenterView from '../views/BattleCenterView.vue';
import NpcControlView from '../views/NpcControlView.vue';
import NotFoundView from '../views/NotFoundView.vue';
import { useSessionStore } from '../stores/session';
@@ -72,6 +74,15 @@ const routes = [
requiresGeneral: true,
},
},
{
path: '/nation/finance',
name: 'nation-finance',
component: NationStratFinanView,
meta: {
requiresAuth: true,
requiresGeneral: true,
},
},
{
path: '/chief-center',
name: 'chief-center',
@@ -81,6 +92,15 @@ const routes = [
requiresGeneral: true,
},
},
{
path: '/battle-center',
name: 'battle-center',
component: BattleCenterView,
meta: {
requiresAuth: true,
requiresGeneral: true,
},
},
{
path: '/npc-control',
name: 'npc-control',
+17
View File
@@ -0,0 +1,17 @@
export type DiplomacyState = 0 | 1 | 2 | 7;
export type DiplomacyInfo = {
name: string;
color?: string;
};
export const diplomacyStateInfo: Record<DiplomacyState, DiplomacyInfo> = {
0: { name: '교전', color: 'red' },
1: { name: '선포중', color: 'magenta' },
2: { name: '통상' },
7: { name: '불가침', color: 'green' },
};
export const resolveDiplomacyInfo = (state: number): DiplomacyInfo => {
return diplomacyStateInfo[state as DiplomacyState] ?? { name: '알 수 없음' };
};
+58
View File
@@ -0,0 +1,58 @@
const logRegex = /<([RBGMCLSODYW]1?|1|\/)>/g;
const convertMap: Record<string, string> = {
R: 'color: red;',
B: 'color: blue;',
G: 'color: green;',
M: 'color: magenta;',
C: 'color: cyan;',
L: 'color: limegreen;',
S: 'color: skyblue;',
O: 'color: orangered;',
D: 'color: orangered;',
Y: 'color: yellow;',
W: 'color: white;',
1: 'font-size: 0.9em;',
};
const convertMap2: Record<string, string> = {
1: 'font-size: 0.9em;',
};
export const formatLog = (text?: string): string => {
if (!text) {
return '';
}
let match: RegExpExecArray | null = null;
let lastIndex = 0;
const result: string[] = [];
while ((match = logRegex.exec(text)) !== null) {
const partAll = match[0];
const subPart = match[1];
const index = match.index;
if (lastIndex !== index) {
result.push(text.slice(lastIndex, index));
}
if (subPart === '/') {
result.push('</span>');
} else if (subPart.length === 2) {
result.push(
`<span style="${convertMap[subPart[0]] ?? ''}${convertMap2[subPart[1]] ?? ''}">`
);
} else {
result.push(`<span style="${convertMap[subPart] ?? ''}">`);
}
lastIndex = index + partAll.length;
}
if (lastIndex !== text.length) {
result.push(text.slice(lastIndex));
}
return result.join('');
};
@@ -0,0 +1,429 @@
<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import PanelCard from '../components/ui/PanelCard.vue';
import SkeletonLines from '../components/ui/SkeletonLines.vue';
import GeneralBasicCard from '../components/main/GeneralBasicCard.vue';
import { trpc } from '../utils/trpc';
import { getNpcColor } from '../utils/npcColor';
import { formatLog } from '../utils/formatLog';
type BattleCenterResponse = Awaited<ReturnType<typeof trpc.nation.getBattleCenter.query>>;
type GeneralEntry = BattleCenterResponse['generals'][number];
type LogType = 'generalHistory' | 'battleResult' | 'battleDetail' | 'generalAction';
type LogLine = { id: number; html: string };
const logTypes: LogType[] = ['generalHistory', 'battleDetail', 'battleResult', 'generalAction'];
const logLabels: Record<LogType, string> = {
generalHistory: '장수 열전',
battleDetail: '전투 기록',
battleResult: '전투 결과',
generalAction: '개인 기록',
};
const orderOptions = [
{ key: 'recentWar', label: '최근 전투' },
{ key: 'warnum', label: '전투 횟수' },
{ key: 'turnTime', label: '최근 턴' },
{ key: 'name', label: '이름' },
] as const;
type OrderKey = (typeof orderOptions)[number]['key'];
const loading = ref(false);
const logLoading = ref(false);
const error = ref<string | null>(null);
const data = ref<BattleCenterResponse | null>(null);
const orderBy = ref<OrderKey>('turnTime');
const selectedGeneralId = ref<number>(0);
const logs = reactive<Record<LogType, LogLine[]>>({
generalHistory: [],
battleDetail: [],
battleResult: [],
generalAction: [],
});
const resolveErrorMessage = (value: unknown): string => {
if (value instanceof Error) {
return value.message;
}
if (typeof value === 'string') {
return value;
}
return 'unknown_error';
};
const parseGeneralId = (value: unknown): number => {
if (typeof value === 'string') {
const parsed = Number(value);
if (Number.isFinite(parsed)) {
return parsed;
}
}
if (typeof value === 'number' && Number.isFinite(value)) {
return value;
}
return 0;
};
const route = useRoute();
const loadBattleCenter = async () => {
if (loading.value) {
return;
}
loading.value = true;
error.value = null;
try {
data.value = await trpc.nation.getBattleCenter.query();
} catch (err) {
error.value = resolveErrorMessage(err);
} finally {
loading.value = false;
}
};
const orderedGenerals = computed(() => {
const list = data.value?.generals ?? [];
const key = orderBy.value;
const sorted = [...list].sort((lhs, rhs) => {
switch (key) {
case 'recentWar': {
const lhsVal = lhs.recentWar ?? '';
const rhsVal = rhs.recentWar ?? '';
return rhsVal.localeCompare(lhsVal);
}
case 'warnum':
return rhs.warnum - lhs.warnum;
case 'name': {
const lhsVal = `${lhs.npcState}${lhs.name}`;
const rhsVal = `${rhs.npcState}${rhs.name}`;
return lhsVal.localeCompare(rhsVal);
}
case 'turnTime':
default: {
const lhsVal = lhs.turnTime ?? '';
const rhsVal = rhs.turnTime ?? '';
return rhsVal.localeCompare(lhsVal);
}
}
});
return sorted;
});
const selectedGeneral = computed(() => {
const list = data.value?.generals ?? [];
return list.find((general) => general.id === selectedGeneralId.value) ?? null;
});
const statusLine = computed(() => {
if (!data.value) {
return '감찰부 정보를 불러오는 중';
}
return `${data.value.currentYear}${data.value.currentMonth}월 · 턴 ${data.value.turnTermMinutes}`;
});
const formatGeneralLabel = (general: GeneralEntry): string => {
const name = general.officerLevel > 4 ? `*${general.name}*` : general.name;
const time = general.turnTime ? general.turnTime.slice(-5) : '--:--';
if (orderBy.value === 'recentWar') {
return `${name} (${general.recentWar ? general.recentWar.slice(-5) : '--:--'})`;
}
if (orderBy.value === 'warnum') {
return `${name} (${general.warnum}회)`;
}
return `${name} (${time})`;
};
let logRequestId = 0;
const loadLogs = async (generalId: number) => {
if (!generalId) {
return;
}
logLoading.value = true;
const requestId = (logRequestId += 1);
try {
const responses = await Promise.all(
logTypes.map((type) => trpc.nation.getGeneralLog.query({ generalId, type }))
);
if (requestId !== logRequestId || selectedGeneralId.value !== generalId) {
return;
}
for (const response of responses) {
const formatted = response.logs.map((entry) => ({
id: entry.id,
html: formatLog(entry.text),
}));
logs[response.type] = formatted;
}
} catch (err) {
error.value = resolveErrorMessage(err);
} finally {
if (requestId === logRequestId) {
logLoading.value = false;
}
}
};
const changeTargetByOffset = (offset: number) => {
const list = orderedGenerals.value;
if (!list.length || !selectedGeneralId.value) {
return;
}
const index = list.findIndex((general) => general.id === selectedGeneralId.value);
if (index < 0) {
return;
}
let nextIndex = (index + offset) % list.length;
if (nextIndex < 0) {
nextIndex += list.length;
}
selectedGeneralId.value = list[nextIndex].id;
};
watch(
() => orderedGenerals.value,
(list) => {
if (!list.length) {
selectedGeneralId.value = 0;
return;
}
if (!selectedGeneralId.value || !list.some((general) => general.id === selectedGeneralId.value)) {
selectedGeneralId.value = list[0].id;
}
}
);
watch(
() => selectedGeneralId.value,
(generalId) => {
if (generalId) {
void loadLogs(generalId);
}
}
);
watch(
() => route.query,
(query) => {
const queryId = parseGeneralId(query.generalId ?? query.gen);
if (queryId) {
selectedGeneralId.value = queryId;
}
},
{ immediate: true }
);
onMounted(() => {
void loadBattleCenter();
});
</script>
<template>
<main class="battle-page">
<header class="page-header">
<div>
<h1 class="page-title">감찰부</h1>
<p class="page-subtitle">{{ statusLine }}</p>
</div>
<div class="header-actions">
<RouterLink class="ghost" to="/">메인</RouterLink>
<RouterLink class="ghost" to="/nation/finance">내무부</RouterLink>
<button class="ghost" @click="loadBattleCenter">새로고침</button>
</div>
</header>
<div v-if="error" class="error">{{ error }}</div>
<section class="layout-grid">
<div class="stack">
<PanelCard title="대상 선택" subtitle="정렬 기준과 장수를 선택합니다.">
<div class="selector-row">
<button class="ghost" @click="changeTargetByOffset(-1)"> 이전</button>
<select v-model="orderBy" class="select-input">
<option v-for="option in orderOptions" :key="option.key" :value="option.key">
{{ option.label }}
</option>
</select>
<select v-model.number="selectedGeneralId" class="select-input">
<option
v-for="general in orderedGenerals"
:key="general.id"
:value="general.id"
:style="{ color: getNpcColor(general.npcState) ?? undefined }"
>
{{ formatGeneralLabel(general) }}
</option>
</select>
<button class="ghost" @click="changeTargetByOffset(1)">다음 </button>
</div>
</PanelCard>
<PanelCard title="장수 정보">
<GeneralBasicCard :general="selectedGeneral" :loading="loading" />
<div v-if="selectedGeneral" class="general-meta">
<div>최근 : {{ selectedGeneral.turnTime ? selectedGeneral.turnTime.slice(-5) : '-' }}</div>
<div>최근 전투: {{ selectedGeneral.recentWar || '-' }}</div>
<div>전투 횟수: {{ selectedGeneral.warnum }}</div>
</div>
</PanelCard>
</div>
<div class="stack">
<PanelCard title="장수 기록" subtitle="열전과 전투 기록">
<div class="log-grid">
<div v-for="type in logTypes" :key="type" class="log-block">
<div class="log-title">{{ logLabels[type] }}</div>
<SkeletonLines v-if="loading || logLoading" :lines="3" />
<template v-else>
<div v-if="logs[type].length === 0" class="empty">기록이 없습니다.</div>
<div
v-for="entry in logs[type]"
:key="entry.id"
class="log-line"
v-html="entry.html"
/>
</template>
</div>
</div>
</PanelCard>
</div>
</section>
</main>
</template>
<style scoped>
.battle-page {
min-height: 100vh;
padding: 24px;
display: flex;
flex-direction: column;
gap: 24px;
}
.page-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
flex-wrap: wrap;
}
.page-title {
font-size: 1.6rem;
font-weight: 700;
}
.page-subtitle {
color: rgba(232, 221, 196, 0.7);
margin-top: 6px;
}
.header-actions {
display: flex;
flex-wrap: wrap;
gap: 10px;
}
.layout-grid {
display: grid;
grid-template-columns: minmax(0, 320px) minmax(0, 1fr);
gap: 18px;
}
.stack {
display: flex;
flex-direction: column;
gap: 18px;
}
.selector-row {
display: grid;
grid-template-columns: auto minmax(140px, 1fr) minmax(180px, 2fr) auto;
gap: 8px;
align-items: center;
}
.select-input {
min-width: 0;
padding: 6px 8px;
border: 1px solid rgba(201, 164, 90, 0.4);
background: rgba(12, 12, 12, 0.7);
color: inherit;
font-size: 0.85rem;
}
.ghost {
border: 1px solid rgba(201, 164, 90, 0.5);
background: transparent;
color: inherit;
padding: 6px 10px;
font-size: 0.8rem;
cursor: pointer;
}
.general-meta {
margin-top: 10px;
font-size: 0.85rem;
color: rgba(232, 221, 196, 0.75);
display: grid;
gap: 4px;
}
.log-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 12px;
}
.log-block {
border: 1px solid rgba(201, 164, 90, 0.3);
padding: 8px;
background: rgba(12, 12, 12, 0.6);
min-height: 160px;
}
.log-title {
font-weight: 600;
margin-bottom: 6px;
font-size: 0.9rem;
}
.log-line {
padding: 4px 0;
border-bottom: 1px dashed rgba(201, 164, 90, 0.2);
}
.log-line:last-child {
border-bottom: none;
}
.empty {
color: rgba(232, 221, 196, 0.6);
font-size: 0.85rem;
}
.error {
color: #f08a5d;
font-size: 0.9rem;
}
@media (max-width: 1024px) {
.layout-grid {
grid-template-columns: 1fr;
}
.selector-row {
grid-template-columns: 1fr;
}
}
</style>
+2
View File
@@ -94,7 +94,9 @@ watch(
<RouterLink class="ghost" to="/nation/cities">세력 도시</RouterLink>
<RouterLink class="ghost" to="/nation/generals">세력 장수</RouterLink>
<RouterLink class="ghost" to="/nation/personnel">인사부</RouterLink>
<RouterLink class="ghost" to="/nation/finance">내무부</RouterLink>
<RouterLink class="ghost" to="/chief-center">사령부</RouterLink>
<RouterLink class="ghost" to="/battle-center">감찰부</RouterLink>
<RouterLink class="ghost" to="/npc-control">NPC 정책</RouterLink>
<RouterLink class="ghost" to="/inherit">유산 강화</RouterLink>
<button
@@ -0,0 +1,740 @@
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import PanelCard from '../components/ui/PanelCard.vue';
import SkeletonLines from '../components/ui/SkeletonLines.vue';
import { trpc } from '../utils/trpc';
import { resolveDiplomacyInfo } from '../utils/diplomacy';
type StratFinanResponse = Awaited<ReturnType<typeof trpc.nation.getStratFinan.query>>;
type NationEntry = StratFinanResponse['nationsList'][number];
const loading = ref(false);
const error = ref<string | null>(null);
const data = ref<StratFinanResponse | null>(null);
const nationMsg = ref('');
const scoutMsg = ref('');
const nationMsgDraft = ref('');
const scoutMsgDraft = ref('');
const editingNationMsg = ref(false);
const editingScoutMsg = ref(false);
const policy = reactive({
rate: 0,
bill: 0,
secretLimit: 0,
blockScout: false,
blockWar: false,
});
const oldPolicy = reactive({
rate: 0,
bill: 0,
secretLimit: 0,
});
const resolveErrorMessage = (value: unknown): string => {
if (value instanceof Error) {
return value.message;
}
if (typeof value === 'string') {
return value;
}
return 'unknown_error';
};
const loadStratFinan = async () => {
if (loading.value) {
return;
}
loading.value = true;
error.value = null;
try {
const response = await trpc.nation.getStratFinan.query();
data.value = response;
nationMsg.value = response.nationMsg ?? '';
scoutMsg.value = response.scoutMsg ?? '';
nationMsgDraft.value = nationMsg.value;
scoutMsgDraft.value = scoutMsg.value;
Object.assign(policy, response.policy);
Object.assign(oldPolicy, response.policy);
} catch (err) {
error.value = resolveErrorMessage(err);
} finally {
loading.value = false;
}
};
const canEdit = computed(() => data.value?.editable ?? false);
const nationsList = computed(() => data.value?.nationsList ?? []);
const warSettingCnt = computed(() => data.value?.warSettingCnt ?? { remain: 0, inc: 0, max: 0 });
const statusLine = computed(() => {
if (!data.value) {
return '내무부 정보를 불러오는 중';
}
return `${data.value.year}${data.value.month}`;
});
const formatNumber = (value: number): string => new Intl.NumberFormat('ko-KR').format(value);
const incomeGoldCity = computed(() => {
if (!data.value) {
return 0;
}
return (data.value.income.gold.city * policy.rate) / 100;
});
const incomeGold = computed(() => {
if (!data.value) {
return 0;
}
return incomeGoldCity.value + data.value.income.gold.war;
});
const incomeRiceCity = computed(() => {
if (!data.value) {
return 0;
}
return (data.value.income.rice.city * policy.rate) / 100;
});
const incomeRiceWall = computed(() => {
if (!data.value) {
return 0;
}
return (data.value.income.rice.wall * policy.rate) / 100;
});
const incomeRice = computed(() => incomeRiceCity.value + incomeRiceWall.value);
const outcomeByBill = computed(() => {
if (!data.value) {
return 0;
}
return (data.value.outcome * policy.bill) / 100;
});
const joinYearMonth = (year: number, month: number): number => year * 12 + month - 1;
const parseYearMonth = (value: number): [number, number] => {
return [Math.floor(value / 12), (value % 12) + 1];
};
const resolveDiplomacyEnd = (term: number | null): string => {
if (!data.value || !term) {
return '-';
}
const [endYear, endMonth] = parseYearMonth(joinYearMonth(data.value.year, data.value.month) + term);
return `${endYear}${endMonth}`;
};
const enableEditNationMsg = () => {
if (!canEdit.value) {
return;
}
editingNationMsg.value = true;
nationMsgDraft.value = nationMsg.value;
};
const rollbackNationMsg = () => {
editingNationMsg.value = false;
nationMsgDraft.value = nationMsg.value;
};
const saveNationMsg = async () => {
if (!canEdit.value) {
return;
}
try {
await trpc.nation.setNotice.mutate({ msg: nationMsgDraft.value });
nationMsg.value = nationMsgDraft.value;
editingNationMsg.value = false;
} catch (err) {
error.value = resolveErrorMessage(err);
}
};
const enableEditScoutMsg = () => {
if (!canEdit.value) {
return;
}
editingScoutMsg.value = true;
scoutMsgDraft.value = scoutMsg.value;
};
const rollbackScoutMsg = () => {
editingScoutMsg.value = false;
scoutMsgDraft.value = scoutMsg.value;
};
const saveScoutMsg = async () => {
if (!canEdit.value) {
return;
}
try {
await trpc.nation.setScoutMsg.mutate({ msg: scoutMsgDraft.value });
scoutMsg.value = scoutMsgDraft.value;
editingScoutMsg.value = false;
} catch (err) {
error.value = resolveErrorMessage(err);
}
};
const setRate = async () => {
if (!canEdit.value) {
return;
}
try {
await trpc.nation.setRate.mutate({ amount: policy.rate });
oldPolicy.rate = policy.rate;
} catch (err) {
error.value = resolveErrorMessage(err);
policy.rate = oldPolicy.rate;
}
};
const rollbackRate = () => {
policy.rate = oldPolicy.rate;
};
const setBill = async () => {
if (!canEdit.value) {
return;
}
try {
await trpc.nation.setBill.mutate({ amount: policy.bill });
oldPolicy.bill = policy.bill;
} catch (err) {
error.value = resolveErrorMessage(err);
policy.bill = oldPolicy.bill;
}
};
const rollbackBill = () => {
policy.bill = oldPolicy.bill;
};
const setSecretLimit = async () => {
if (!canEdit.value) {
return;
}
try {
await trpc.nation.setSecretLimit.mutate({ amount: policy.secretLimit });
oldPolicy.secretLimit = policy.secretLimit;
} catch (err) {
error.value = resolveErrorMessage(err);
policy.secretLimit = oldPolicy.secretLimit;
}
};
const rollbackSecretLimit = () => {
policy.secretLimit = oldPolicy.secretLimit;
};
const setBlockWar = async () => {
if (!canEdit.value || !data.value) {
return;
}
const nextValue = policy.blockWar;
try {
const result = await trpc.nation.setBlockWar.mutate({ value: nextValue });
data.value.warSettingCnt.remain = result.availableCnt;
} catch (err) {
error.value = resolveErrorMessage(err);
policy.blockWar = !nextValue;
}
};
const setBlockScout = async () => {
if (!canEdit.value) {
return;
}
const nextValue = policy.blockScout;
try {
await trpc.nation.setBlockScout.mutate({ value: nextValue });
} catch (err) {
error.value = resolveErrorMessage(err);
policy.blockScout = !nextValue;
}
};
const formatDiplomacyTerm = (term: number | null): string => {
if (!term) {
return '-';
}
return `${term}개월`;
};
const diplomacyInfo = (nation: NationEntry) => resolveDiplomacyInfo(nation.diplomacy.state);
onMounted(() => {
void loadStratFinan();
});
</script>
<template>
<main class="finance-page">
<header class="page-header">
<div>
<h1 class="page-title">내무부</h1>
<p class="page-subtitle">{{ statusLine }}</p>
</div>
<div class="header-actions">
<RouterLink class="ghost" to="/">메인</RouterLink>
<RouterLink class="ghost" to="/nation/cities">세력 도시</RouterLink>
<RouterLink class="ghost" to="/nation/generals">세력 장수</RouterLink>
<button class="ghost" @click="loadStratFinan">새로고침</button>
</div>
</header>
<div v-if="error" class="error">{{ error }}</div>
<section class="layout-grid">
<div class="stack">
<PanelCard title="외교 관계" subtitle="현 세력 외교 상황">
<SkeletonLines v-if="loading" :lines="4" />
<div v-else class="table-scroll">
<table class="finance-table">
<thead>
<tr>
<th>국가명</th>
<th>국력</th>
<th>장수</th>
<th>속령</th>
<th>상태</th>
<th>기간</th>
<th>종료 시점</th>
</tr>
</thead>
<tbody>
<tr v-for="nation in nationsList" :key="nation.id">
<td>
<span class="nation-swatch" :style="{ backgroundColor: nation.color }" />
{{ nation.name }}
</td>
<td>{{ formatNumber(nation.power) }}</td>
<td>{{ formatNumber(nation.generalCount) }}</td>
<td>{{ formatNumber(nation.cityCount) }}</td>
<template v-if="nation.id === data?.nationId">
<td>-</td>
<td>-</td>
<td>-</td>
</template>
<template v-else>
<td :style="{ color: diplomacyInfo(nation).color ?? undefined }">
{{ diplomacyInfo(nation).name }}
</td>
<td>{{ formatDiplomacyTerm(nation.diplomacy.term) }}</td>
<td>{{ resolveDiplomacyEnd(nation.diplomacy.term) }}</td>
</template>
</tr>
</tbody>
</table>
</div>
</PanelCard>
<PanelCard title="국가 방침">
<template #actions>
<button v-if="canEdit && !editingNationMsg" class="ghost" @click="enableEditNationMsg">
국가방침 수정
</button>
<button v-if="canEdit && editingNationMsg" class="ghost" @click="saveNationMsg">저장</button>
<button v-if="canEdit && editingNationMsg" class="ghost" @click="rollbackNationMsg">취소</button>
</template>
<SkeletonLines v-if="loading" :lines="4" />
<div v-else class="message-block">
<div v-if="!editingNationMsg" class="message-preview" v-html="nationMsg || '내용 없음'" />
<textarea
v-else
v-model="nationMsgDraft"
class="text-area"
rows="6"
maxlength="16384"
/>
</div>
</PanelCard>
<PanelCard title="임관 권유">
<template #actions>
<button v-if="canEdit && !editingScoutMsg" class="ghost" @click="enableEditScoutMsg">
임관 권유문 수정
</button>
<button v-if="canEdit && editingScoutMsg" class="ghost" @click="saveScoutMsg">저장</button>
<button v-if="canEdit && editingScoutMsg" class="ghost" @click="rollbackScoutMsg">취소</button>
</template>
<SkeletonLines v-if="loading" :lines="3" />
<div v-else class="message-block">
<div class="hint">870px x 200px를 넘어서는 내용은 표시되지 않습니다.</div>
<div v-if="!editingScoutMsg" class="message-preview" v-html="scoutMsg || '내용 없음'" />
<textarea
v-else
v-model="scoutMsgDraft"
class="text-area"
rows="4"
maxlength="1000"
/>
</div>
</PanelCard>
</div>
<div class="stack">
<PanelCard title="예산 요약" subtitle="세입/세출 추산">
<SkeletonLines v-if="loading" :lines="5" />
<div v-else class="budget-grid">
<div class="budget-card">
<div class="budget-title">자금 예산</div>
<div class="budget-row">
<span> </span>
<span>{{ formatNumber(Math.floor(data?.gold ?? 0)) }}</span>
</div>
<div class="budget-row">
<span>단기수입</span>
<span>{{ formatNumber(Math.floor(data?.income.gold.war ?? 0)) }}</span>
</div>
<div class="budget-row">
<span> </span>
<span>{{ formatNumber(Math.floor(incomeGoldCity)) }}</span>
</div>
<div class="budget-row">
<span>수입/지출</span>
<span>
+{{ formatNumber(Math.floor(incomeGold)) }} /
{{ formatNumber(Math.floor(-outcomeByBill)) }}
</span>
</div>
<div class="budget-row total">
<span>국고 예산</span>
<span>
{{ formatNumber(Math.floor((data?.gold ?? 0) + incomeGold - outcomeByBill)) }}
({{ incomeGold >= outcomeByBill ? '+' : '' }}{{
formatNumber(Math.floor(incomeGold - outcomeByBill))
}})
</span>
</div>
</div>
<div class="budget-card">
<div class="budget-title">군량 예산</div>
<div class="budget-row">
<span> </span>
<span>{{ formatNumber(Math.floor(data?.rice ?? 0)) }}</span>
</div>
<div class="budget-row">
<span>둔전수입</span>
<span>{{ formatNumber(Math.floor(incomeRiceWall)) }}</span>
</div>
<div class="budget-row">
<span> </span>
<span>{{ formatNumber(Math.floor(incomeRiceCity)) }}</span>
</div>
<div class="budget-row">
<span>수입/지출</span>
<span>
+{{ formatNumber(Math.floor(incomeRice)) }} /
{{ formatNumber(Math.floor(-outcomeByBill)) }}
</span>
</div>
<div class="budget-row total">
<span>국고 예산</span>
<span>
{{ formatNumber(Math.floor((data?.rice ?? 0) + incomeRice - outcomeByBill)) }}
({{ incomeRice >= outcomeByBill ? '+' : '' }}{{
formatNumber(Math.floor(incomeRice - outcomeByBill))
}})
</span>
</div>
</div>
</div>
</PanelCard>
<PanelCard title="정책 설정" subtitle="세율/지급률/기밀 권한">
<div class="policy-grid">
<div class="policy-row">
<div class="policy-label">세율 (5 ~ 30%)</div>
<div class="policy-control">
<input
v-model.number="policy.rate"
class="number-input"
type="number"
min="5"
max="30"
:disabled="!canEdit"
/>
<button class="ghost" :disabled="!canEdit" @click="setRate">변경</button>
<button class="ghost" :disabled="!canEdit" @click="rollbackRate">취소</button>
</div>
</div>
<div class="policy-row">
<div class="policy-label">지급률 (20 ~ 200%)</div>
<div class="policy-control">
<input
v-model.number="policy.bill"
class="number-input"
type="number"
min="20"
max="200"
:disabled="!canEdit"
/>
<button class="ghost" :disabled="!canEdit" @click="setBill">변경</button>
<button class="ghost" :disabled="!canEdit" @click="rollbackBill">취소</button>
</div>
</div>
<div class="policy-row">
<div class="policy-label">기밀 권한 (1 ~ 99)</div>
<div class="policy-control">
<input
v-model.number="policy.secretLimit"
class="number-input"
type="number"
min="1"
max="99"
:disabled="!canEdit"
/>
<button class="ghost" :disabled="!canEdit" @click="setSecretLimit">변경</button>
<button class="ghost" :disabled="!canEdit" @click="rollbackSecretLimit">취소</button>
</div>
</div>
<div class="policy-row">
<div class="policy-label">전쟁 금지 설정</div>
<div class="policy-summary">
{{ warSettingCnt.remain }} ( +{{ warSettingCnt.inc }}, 최대{{ warSettingCnt.max }})
</div>
</div>
<div class="policy-toggles">
<label class="toggle">
<input
v-model="policy.blockWar"
type="checkbox"
:disabled="!canEdit"
@change="setBlockWar"
/>
<span>전쟁 금지</span>
</label>
<label class="toggle">
<input
v-model="policy.blockScout"
type="checkbox"
:disabled="!canEdit"
@change="setBlockScout"
/>
<span>임관 금지</span>
</label>
</div>
</div>
</PanelCard>
</div>
</section>
</main>
</template>
<style scoped>
.finance-page {
min-height: 100vh;
padding: 24px;
display: flex;
flex-direction: column;
gap: 24px;
}
.page-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
flex-wrap: wrap;
}
.page-title {
font-size: 1.6rem;
font-weight: 700;
}
.page-subtitle {
color: rgba(232, 221, 196, 0.7);
margin-top: 6px;
}
.header-actions {
display: flex;
flex-wrap: wrap;
gap: 10px;
}
.layout-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
gap: 18px;
}
.stack {
display: flex;
flex-direction: column;
gap: 18px;
}
.table-scroll {
overflow-x: auto;
}
.finance-table {
width: 100%;
border-collapse: collapse;
font-size: 0.85rem;
}
.finance-table th,
.finance-table td {
padding: 6px 8px;
border-bottom: 1px solid rgba(201, 164, 90, 0.2);
text-align: center;
}
.finance-table th {
text-align: center;
font-weight: 600;
}
.nation-swatch {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 2px;
margin-right: 6px;
}
.message-block {
display: flex;
flex-direction: column;
gap: 8px;
}
.message-preview {
min-height: 80px;
padding: 10px;
border: 1px solid rgba(201, 164, 90, 0.2);
background: rgba(12, 12, 12, 0.5);
}
.text-area {
width: 100%;
border: 1px solid rgba(201, 164, 90, 0.4);
background: rgba(12, 12, 12, 0.7);
color: inherit;
padding: 8px;
font-size: 0.9rem;
}
.hint {
font-size: 0.75rem;
color: rgba(232, 221, 196, 0.6);
}
.budget-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 14px;
}
.budget-card {
border: 1px solid rgba(201, 164, 90, 0.3);
padding: 10px;
background: rgba(12, 12, 12, 0.6);
}
.budget-title {
font-weight: 600;
margin-bottom: 8px;
}
.budget-row {
display: flex;
justify-content: space-between;
margin-bottom: 4px;
font-size: 0.85rem;
}
.budget-row.total {
margin-top: 8px;
padding-top: 8px;
border-top: 1px dashed rgba(201, 164, 90, 0.3);
font-weight: 600;
}
.policy-grid {
display: flex;
flex-direction: column;
gap: 12px;
}
.policy-row {
display: flex;
flex-direction: column;
gap: 6px;
}
.policy-label {
font-size: 0.85rem;
}
.policy-control {
display: flex;
flex-wrap: wrap;
gap: 8px;
align-items: center;
}
.policy-summary {
font-size: 0.85rem;
color: rgba(232, 221, 196, 0.8);
}
.policy-toggles {
display: flex;
flex-wrap: wrap;
gap: 16px;
margin-top: 6px;
}
.toggle {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 0.85rem;
}
.number-input {
width: 80px;
padding: 4px 6px;
border: 1px solid rgba(201, 164, 90, 0.4);
background: rgba(12, 12, 12, 0.7);
color: inherit;
text-align: right;
}
.ghost {
border: 1px solid rgba(201, 164, 90, 0.5);
background: transparent;
color: inherit;
padding: 6px 10px;
font-size: 0.8rem;
cursor: pointer;
}
.ghost:disabled {
opacity: 0.4;
cursor: not-allowed;
}
.error {
color: #f08a5d;
font-size: 0.9rem;
}
@media (max-width: 768px) {
.page-header {
flex-direction: column;
align-items: flex-start;
}
}
</style>
+2
View File
@@ -7,9 +7,11 @@ export interface DatabaseClient {
general: GamePrisma.GeneralDelegate;
city: GamePrisma.CityDelegate;
nation: GamePrisma.NationDelegate;
diplomacy: GamePrisma.DiplomacyDelegate;
generalTurn: GamePrisma.GeneralTurnDelegate;
nationTurn: GamePrisma.NationTurnDelegate;
troop: GamePrisma.TroopDelegate;
logEntry: GamePrisma.LogEntryDelegate;
inheritancePoint: GamePrisma.InheritancePointDelegate;
inheritanceLog: GamePrisma.InheritanceLogDelegate;
inheritanceResult: GamePrisma.InheritanceResultDelegate;
+1
View File
@@ -0,0 +1 @@
export * from './nationIncome.js';
+275
View File
@@ -0,0 +1,275 @@
import type { General, Nation } from '../domain/entities.js';
import type { GeneralActionContext } from '../triggers/general.js';
import type { TriggerNationalIncomeType } from '../triggers/types.js';
export type NationIncomeModifier = (type: TriggerNationalIncomeType, amount: number) => number;
export interface NationIncomeContext {
rate: number;
modifyIncome?: NationIncomeModifier;
}
export interface CityIncomeSource {
id: number;
population: number;
populationMax: number;
agriculture: number;
agricultureMax: number;
commerce: number;
commerceMax: number;
security: number;
securityMax: number;
trust: number;
supplyState: number;
defence: number;
defenceMax: number;
wall: number;
wallMax: number;
meta: Record<string, unknown>;
}
const MAX_DED_LEVEL = 30;
const readMetaNumber = (meta: Record<string, unknown>, key: string, fallback = 0): number => {
const value = meta[key];
if (typeof value === 'number' && Number.isFinite(value)) {
return value;
}
return fallback;
};
const applyNationIncome = (context: NationIncomeContext, type: TriggerNationalIncomeType, amount: number): number => {
if (!context.modifyIncome) {
return amount;
}
return context.modifyIncome(type, amount);
};
export const createIncomeActionContext = (nation: Nation): GeneralActionContext => {
const general: General = {
id: 0,
name: 'SYSTEM',
nationId: nation.id,
cityId: 0,
troopId: 0,
stats: { leadership: 0, strength: 0, intelligence: 0 },
experience: 0,
dedication: 0,
officerLevel: 0,
role: {
personality: null,
specialDomestic: null,
specialWar: null,
items: {
horse: null,
weapon: null,
book: null,
item: null,
},
},
injury: 0,
gold: 0,
rice: 0,
crew: 0,
crewTypeId: 0,
train: 0,
atmos: 0,
age: 0,
npcState: 0,
triggerState: {
flags: {},
counters: {},
modifiers: {},
meta: {},
},
meta: {},
};
return { general, nation };
};
export const calcCityGoldIncomeBase = (
context: NationIncomeContext,
city: CityIncomeSource,
officerCnt: number,
isCapital: boolean,
nationLevel: number
): number => {
if (city.supplyState === 0) {
return 0;
}
const trustRatio = city.trust / 200 + 0.5;
const commMax = Math.max(1, city.commerceMax);
const secuMax = Math.max(1, city.securityMax);
let income = (city.population * city.commerce * trustRatio) / commMax / 30;
income *= 1 + city.security / secuMax / 10;
income *= Math.pow(1.05, officerCnt);
if (isCapital && nationLevel > 0) {
income *= 1 + 1 / (3 * nationLevel);
}
const adjusted = applyNationIncome(context, 'gold', income);
return Math.round(adjusted);
};
export const calcCityRiceIncomeBase = (
context: NationIncomeContext,
city: CityIncomeSource,
officerCnt: number,
isCapital: boolean,
nationLevel: number
): number => {
if (city.supplyState === 0) {
return 0;
}
const trustRatio = city.trust / 200 + 0.5;
const agriMax = Math.max(1, city.agricultureMax);
const secuMax = Math.max(1, city.securityMax);
let income = (city.population * city.agriculture * trustRatio) / agriMax / 30;
income *= 1 + city.security / secuMax / 10;
income *= Math.pow(1.05, officerCnt);
if (isCapital && nationLevel > 0) {
income *= 1 + 1 / (3 * nationLevel);
}
const adjusted = applyNationIncome(context, 'rice', income);
return Math.round(adjusted);
};
export const calcCityWallIncomeBase = (
context: NationIncomeContext,
city: CityIncomeSource,
officerCnt: number,
isCapital: boolean,
nationLevel: number
): number => {
if (city.supplyState === 0) {
return 0;
}
const wallMax = Math.max(1, city.wallMax);
const secuMax = Math.max(1, city.securityMax);
let income = (city.defence * city.wall) / wallMax / 3;
income *= 1 + city.security / secuMax / 10;
income *= Math.pow(1.05, officerCnt);
if (isCapital && nationLevel > 0) {
income *= 1 + 1 / (3 * nationLevel);
}
const adjusted = applyNationIncome(context, 'rice', income);
return Math.round(adjusted);
};
export const calcCityWarGoldIncome = (context: NationIncomeContext, city: CityIncomeSource): number => {
if (city.supplyState === 0) {
return 0;
}
const dead = readMetaNumber(city.meta as Record<string, unknown>, 'dead', 0);
const income = dead / 10;
const adjusted = applyNationIncome(context, 'gold', income);
return Math.round(adjusted);
};
export const calcCityGoldIncome = (
context: NationIncomeContext,
city: CityIncomeSource,
officerCnt: number,
isCapital: boolean,
nationLevel: number
): number => {
const base = calcCityGoldIncomeBase(context, city, officerCnt, isCapital, nationLevel);
return Math.round(base * (context.rate / 20));
};
export const calcCityRiceIncome = (
context: NationIncomeContext,
city: CityIncomeSource,
officerCnt: number,
isCapital: boolean,
nationLevel: number
): number => {
const base = calcCityRiceIncomeBase(context, city, officerCnt, isCapital, nationLevel);
return Math.round(base * (context.rate / 20));
};
export const calcCityWallIncome = (
context: NationIncomeContext,
city: CityIncomeSource,
officerCnt: number,
isCapital: boolean,
nationLevel: number
): number => {
const base = calcCityWallIncomeBase(context, city, officerCnt, isCapital, nationLevel);
return Math.round(base * (context.rate / 20));
};
export const getGoldIncome = (
context: NationIncomeContext,
cities: CityIncomeSource[],
officerCounts: Map<number, number>,
capitalCityId: number | null,
nationLevel: number
): number => {
let total = 0;
for (const city of cities) {
const officerCnt = officerCounts.get(city.id) ?? 0;
total += calcCityGoldIncomeBase(context, city, officerCnt, capitalCityId === city.id, nationLevel);
}
return total * (context.rate / 20);
};
export const getRiceIncome = (
context: NationIncomeContext,
cities: CityIncomeSource[],
officerCounts: Map<number, number>,
capitalCityId: number | null,
nationLevel: number
): number => {
let total = 0;
for (const city of cities) {
const officerCnt = officerCounts.get(city.id) ?? 0;
total += calcCityRiceIncomeBase(context, city, officerCnt, capitalCityId === city.id, nationLevel);
}
return total * (context.rate / 20);
};
export const getWallIncome = (
context: NationIncomeContext,
cities: CityIncomeSource[],
officerCounts: Map<number, number>,
capitalCityId: number | null,
nationLevel: number
): number => {
let total = 0;
for (const city of cities) {
const officerCnt = officerCounts.get(city.id) ?? 0;
total += calcCityWallIncomeBase(context, city, officerCnt, capitalCityId === city.id, nationLevel);
}
return total * (context.rate / 20);
};
export const getWarGoldIncome = (context: NationIncomeContext, cities: CityIncomeSource[]): number => {
let total = 0;
for (const city of cities) {
total += calcCityWarGoldIncome(context, city);
}
return total;
};
export const resolveDedLevel = (dedication: number): number => {
const level = Math.ceil(Math.sqrt(Math.max(0, dedication)) / 10);
return Math.max(0, Math.min(MAX_DED_LEVEL, level));
};
export const getBillByLevel = (dedicationLevel: number): number => dedicationLevel * 200 + 400;
export const getBill = (dedication: number): number => getBillByLevel(resolveDedLevel(dedication));
export const getOutcome = (billRate: number, generals: Array<{ dedication: number }>): number => {
let total = 0;
for (const general of generals) {
total += getBill(general.dedication);
}
return Math.round(total * (billRate / 100));
};
+1
View File
@@ -3,6 +3,7 @@ export type { RandomGenerator } from '@sammo-ts/common';
export * from './actions/index.js';
export * from './constraints/index.js';
export * from './diplomacy/index.js';
export * from './economy/index.js';
export * from './logging/index.js';
export * from './messages/index.js';
export * from './items/index.js';
+1
View File
@@ -1,4 +1,5 @@
export * from './core.js';
export * from './general.js';
export * from './general-action.js';
export * from './types.js';
export * from './special/index.js';