Merge branch 'main' into feature/best-general-hall-of-fame-parity
# Conflicts: # docs/frontend-legacy-parity.md
This commit is contained in:
@@ -30,6 +30,9 @@ export * from './auction/types.js';
|
||||
export * from './auction/keys.js';
|
||||
export * from './auction/scheduler.js';
|
||||
export * from './auction/worker.js';
|
||||
export * from './tournament/keys.js';
|
||||
export * from './tournament/store.js';
|
||||
export * from './tournament/types.js';
|
||||
export * from './tournament/worker.js';
|
||||
|
||||
// Types for TRPC consumer
|
||||
|
||||
@@ -3,7 +3,14 @@ import { z } from 'zod';
|
||||
|
||||
import { authedProcedure, router } from '../../trpc.js';
|
||||
import { asNumber, asRecord, parseJson, LiteHashDRBG } from '@sammo-ts/common';
|
||||
import { loadWarTraitModules, WarTraitLoader, WAR_TRAIT_KEYS, isWarTraitKey } from '@sammo-ts/logic';
|
||||
import {
|
||||
ItemLoader,
|
||||
isItemKey,
|
||||
loadWarTraitModules,
|
||||
WarTraitLoader,
|
||||
WAR_TRAIT_KEYS,
|
||||
isWarTraitKey,
|
||||
} from '@sammo-ts/logic';
|
||||
import type { InheritBuffType } from '@sammo-ts/logic';
|
||||
import {
|
||||
appendInheritanceLog,
|
||||
@@ -23,8 +30,8 @@ const BUFF_KEYS: InheritBuffType[] = [
|
||||
'warAvoidRatio',
|
||||
'warCriticalRatio',
|
||||
'warMagicTrialProb',
|
||||
'success',
|
||||
'fail',
|
||||
'domesticSuccessProb',
|
||||
'domesticFailProb',
|
||||
'warAvoidRatioOppose',
|
||||
'warCriticalRatioOppose',
|
||||
'warMagicTrialProbOppose',
|
||||
@@ -34,8 +41,8 @@ const BUFF_LABELS: Record<InheritBuffType, string> = {
|
||||
warAvoidRatio: '회피 확률 증가',
|
||||
warCriticalRatio: '필살 확률 증가',
|
||||
warMagicTrialProb: '전투계략 시도 확률 증가',
|
||||
success: '내정 성공률 증가',
|
||||
fail: '내정 실패율 감소',
|
||||
domesticSuccessProb: '내정 성공률 증가',
|
||||
domesticFailProb: '내정 실패율 감소',
|
||||
warAvoidRatioOppose: '상대 회피 확률 감소',
|
||||
warCriticalRatioOppose: '상대 필살 확률 감소',
|
||||
warMagicTrialProbOppose: '상대 전투계략 시도 확률 감소',
|
||||
@@ -58,6 +65,37 @@ const parseBuffRecord = (raw: unknown): Record<string, number> => {
|
||||
|
||||
const serializeBuffRecord = (buff: Record<string, number>): string => JSON.stringify(buff);
|
||||
|
||||
const readBuffLevel = (buff: Record<string, number>, key: InheritBuffType): number => {
|
||||
const compatibilityKey = key === 'domesticSuccessProb' ? 'success' : key === 'domesticFailProb' ? 'fail' : null;
|
||||
return Math.max(0, Math.min(5, Math.floor(buff[key] ?? (compatibilityKey ? buff[compatibilityKey] : 0) ?? 0)));
|
||||
};
|
||||
|
||||
const loadAvailableUniqueItems = async (worldState: WorldStateRow) => {
|
||||
const configuredItems = asRecord(asRecord(worldState.config).const).allItems;
|
||||
const enabledKeys: Array<Parameters<ItemLoader['load']>[0]> = [];
|
||||
for (const entries of Object.values(asRecord(configuredItems))) {
|
||||
for (const [key, amount] of Object.entries(asRecord(entries))) {
|
||||
if (asNumber(amount, 0) !== 0 && isItemKey(key)) {
|
||||
enabledKeys.push(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const loader = new ItemLoader();
|
||||
const items = await Promise.all(
|
||||
[...new Set(enabledKeys)].map(async (key) => {
|
||||
const item = await loader.load(key);
|
||||
return {
|
||||
key,
|
||||
name: item.name,
|
||||
rawName: item.rawName,
|
||||
info: item.info ?? '',
|
||||
};
|
||||
})
|
||||
);
|
||||
return items.sort((left, right) => left.name.localeCompare(right.name, 'ko'));
|
||||
};
|
||||
|
||||
const resolveWorld = async (ctx: { db: { worldState: { findFirst: () => Promise<unknown> } } }) => {
|
||||
const worldState = await ctx.db.worldState.findFirst();
|
||||
if (!worldState || typeof worldState !== 'object') {
|
||||
@@ -199,6 +237,9 @@ export const inheritRouter = router({
|
||||
special2Code: true,
|
||||
meta: true,
|
||||
turnTime: true,
|
||||
leadership: true,
|
||||
strength: true,
|
||||
intel: true,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -219,7 +260,7 @@ export const inheritRouter = router({
|
||||
const inheritConst = resolveInheritConstants(worldState);
|
||||
const buffState = parseBuffRecord(asRecord(general.meta).inheritBuff);
|
||||
const buffLevels = BUFF_KEYS.reduce<Record<string, number>>((acc, key) => {
|
||||
acc[key] = Math.max(0, Math.min(5, Math.floor(buffState[key] ?? 0)));
|
||||
acc[key] = readBuffLevel(buffState, key);
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
@@ -240,11 +281,14 @@ export const inheritRouter = router({
|
||||
info: trait.info ?? '',
|
||||
}));
|
||||
|
||||
const others = await ctx.db.general.findMany({
|
||||
where: { id: { not: general.id }, userId: { not: null } },
|
||||
select: { id: true, name: true },
|
||||
orderBy: { id: 'asc' },
|
||||
});
|
||||
const [others, availableUnique] = await Promise.all([
|
||||
ctx.db.general.findMany({
|
||||
where: { id: { not: general.id }, npcState: { lt: 2 }, userId: { not: null } },
|
||||
select: { id: true, name: true },
|
||||
orderBy: { id: 'asc' },
|
||||
}),
|
||||
loadAvailableUniqueItems(worldState),
|
||||
]);
|
||||
|
||||
return {
|
||||
items,
|
||||
@@ -260,10 +304,16 @@ export const inheritRouter = router({
|
||||
resetTurnTime: resetTurnLevel,
|
||||
},
|
||||
availableSpecialWar: warSpecials,
|
||||
availableUnique,
|
||||
availableTargetGenerals: others,
|
||||
turnTimeZones: buildTurnTimeZoneList(Math.max(1, Math.round(worldState.tickSeconds / 60))),
|
||||
isUnited,
|
||||
currentSpecialWar: general.special2Code ?? 'None',
|
||||
currentStat: {
|
||||
leadership: general.leadership,
|
||||
strength: general.strength,
|
||||
intel: general.intel,
|
||||
},
|
||||
};
|
||||
}),
|
||||
getLogs: authedProcedure
|
||||
@@ -285,7 +335,7 @@ export const inheritRouter = router({
|
||||
},
|
||||
orderBy: { id: 'desc' },
|
||||
take: 30,
|
||||
select: { id: true, year: true, month: true, text: true },
|
||||
select: { id: true, year: true, month: true, text: true, createdAt: true },
|
||||
});
|
||||
return logs;
|
||||
}),
|
||||
@@ -318,7 +368,7 @@ export const inheritRouter = router({
|
||||
}
|
||||
|
||||
const buff = parseBuffRecord(asRecord(general.meta).inheritBuff);
|
||||
const prevLevel = Math.max(0, Math.min(5, Math.floor(buff[input.type] ?? 0)));
|
||||
const prevLevel = readBuffLevel(buff, input.type);
|
||||
if (input.level === prevLevel) {
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: '이미 구입했습니다.' });
|
||||
}
|
||||
@@ -417,7 +467,12 @@ export const inheritRouter = router({
|
||||
},
|
||||
});
|
||||
|
||||
await setInheritancePoint(ctx.db, userId, 'previous', currentPoint - inheritConst.inheritSpecificSpecialPoint);
|
||||
await setInheritancePoint(
|
||||
ctx.db,
|
||||
userId,
|
||||
'previous',
|
||||
currentPoint - inheritConst.inheritSpecificSpecialPoint
|
||||
);
|
||||
await appendInheritanceLog(
|
||||
ctx.db,
|
||||
userId,
|
||||
@@ -460,7 +515,8 @@ export const inheritRouter = router({
|
||||
}
|
||||
|
||||
const meta = asRecord(general.meta);
|
||||
const prevList = parseJson<string[]>(typeof meta.prev_types_special2 === 'string' ? meta.prev_types_special2 : null) ?? [];
|
||||
const prevList =
|
||||
parseJson<string[]>(typeof meta.prev_types_special2 === 'string' ? meta.prev_types_special2 : null) ?? [];
|
||||
prevList.push(general.special2Code);
|
||||
|
||||
await patchGeneral(ctx, general.id, {
|
||||
@@ -473,7 +529,13 @@ export const inheritRouter = router({
|
||||
});
|
||||
|
||||
await setInheritancePoint(ctx.db, userId, 'previous', currentPoint - cost);
|
||||
await appendInheritanceLog(ctx.db, userId, worldState.currentYear, worldState.currentMonth, `${cost} 포인트로 전투 특기 초기화`);
|
||||
await appendInheritanceLog(
|
||||
ctx.db,
|
||||
userId,
|
||||
worldState.currentYear,
|
||||
worldState.currentMonth,
|
||||
`${cost} 포인트로 전투 특기 초기화`
|
||||
);
|
||||
return { ok: true };
|
||||
}),
|
||||
resetTurnTime: authedProcedure.mutation(async ({ ctx }) => {
|
||||
@@ -624,9 +686,7 @@ export const inheritRouter = router({
|
||||
const finalBonus =
|
||||
bonusSum === 0
|
||||
? buildRandomBonus(
|
||||
new LiteHashDRBG(
|
||||
`${asRecord(worldState.meta).hiddenSeed ?? 'inherit'}:ResetStat:${userId}`
|
||||
),
|
||||
new LiteHashDRBG(`${asRecord(worldState.meta).hiddenSeed ?? 'inherit'}:ResetStat:${userId}`),
|
||||
[input.leadership, input.strength, input.intel]
|
||||
)
|
||||
: (bonus as [number, number, number]);
|
||||
@@ -674,9 +734,7 @@ export const inheritRouter = router({
|
||||
if (seasonValue !== null) {
|
||||
const userState = await readUserStateMeta(ctx.db, userId);
|
||||
const resetSeasons = readResetSeasons(userState);
|
||||
const nextSeasons = resetSeasons.includes(seasonValue)
|
||||
? resetSeasons
|
||||
: [...resetSeasons, seasonValue];
|
||||
const nextSeasons = resetSeasons.includes(seasonValue) ? resetSeasons : [...resetSeasons, seasonValue];
|
||||
await writeUserStateMeta(ctx.db, userId, {
|
||||
...userState,
|
||||
last_stat_reset: nextSeasons,
|
||||
@@ -709,7 +767,10 @@ export const inheritRouter = router({
|
||||
}
|
||||
const meta = asRecord(general.meta);
|
||||
if (meta.inheritRandomUnique !== undefined && meta.inheritRandomUnique !== null) {
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: '이미 구입 명령을 내렸습니다. 다음 턴까지 기다려주세요.' });
|
||||
throw new TRPCError({
|
||||
code: 'BAD_REQUEST',
|
||||
message: '이미 구입 명령을 내렸습니다. 다음 턴까지 기다려주세요.',
|
||||
});
|
||||
}
|
||||
|
||||
await patchGeneral(ctx, general.id, {
|
||||
@@ -803,7 +864,9 @@ export const inheritRouter = router({
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: '자신의 정보는 확인할 수 없습니다.' });
|
||||
}
|
||||
|
||||
const ownerName = typeof asRecord(target.meta).ownerName === 'string' ? (asRecord(target.meta).ownerName as string) : target.userId;
|
||||
const rawOwnerName = asRecord(target.meta).ownerName;
|
||||
const ownerName =
|
||||
typeof rawOwnerName === 'string' && rawOwnerName.trim().length > 0 ? rawOwnerName : '알수없음';
|
||||
|
||||
await setInheritancePoint(ctx.db, userId, 'previous', currentPoint - inheritConst.inheritCheckOwnerPoint);
|
||||
await appendInheritanceLog(
|
||||
|
||||
@@ -2,7 +2,21 @@ import { TRPCError } from '@trpc/server';
|
||||
|
||||
import { authedProcedure } from '../../../trpc.js';
|
||||
import { getMyGeneral } from '../../shared/general.js';
|
||||
import { assertNationAccess, loadTraitNames, mapGeneralList, resolveChiefStatMin } from '../shared.js';
|
||||
import {
|
||||
assertNationAccess,
|
||||
loadTraitNames,
|
||||
mapGeneralList,
|
||||
resolveChiefStatMin,
|
||||
resolveNationPermission,
|
||||
} from '../shared.js';
|
||||
|
||||
const experienceLevel = (experience: number): number =>
|
||||
Math.max(
|
||||
0,
|
||||
Math.min(100, experience < 1000 ? Math.floor(experience / 100) : Math.floor(Math.sqrt(experience / 10)))
|
||||
);
|
||||
const dedicationLevel = (dedication: number): number =>
|
||||
Math.max(0, Math.min(10, Math.ceil(Math.sqrt(dedication) / 10)));
|
||||
|
||||
export const getGeneralList = authedProcedure.query(async ({ ctx }) => {
|
||||
const general = await getMyGeneral(ctx);
|
||||
@@ -62,7 +76,38 @@ export const getGeneralList = authedProcedure.query(async ({ ctx }) => {
|
||||
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 accessRows = generalRows.length
|
||||
? await ctx.db.generalAccessLog.findMany({
|
||||
where: { generalId: { in: generalRows.map((entry) => entry.id) } },
|
||||
select: { generalId: true, refreshScoreTotal: true },
|
||||
})
|
||||
: [];
|
||||
const accessByGeneral = new Map(accessRows.map((entry) => [entry.generalId, entry.refreshScoreTotal]));
|
||||
const nationTrait = (await loadTraitNames([nation.typeCode], 'nation')).get(nation.typeCode);
|
||||
const permission = resolveNationPermission(general, nation.meta, true);
|
||||
const visibleList = list.map((entry) => {
|
||||
const { permission: _targetPermission, ...safeEntry } = entry;
|
||||
if (permission >= 1) {
|
||||
return {
|
||||
...safeEntry,
|
||||
refreshScoreTotal: accessByGeneral.get(entry.id) ?? 0,
|
||||
experienceLevel: experienceLevel(entry.experience),
|
||||
dedicationLevel: dedicationLevel(entry.dedication),
|
||||
};
|
||||
}
|
||||
const { crew: _crew, experience: _experience, dedication: _dedication, ...visible } = safeEntry;
|
||||
return {
|
||||
...visible,
|
||||
refreshScoreTotal: accessByGeneral.get(entry.id) ?? 0,
|
||||
officerLevel: entry.officerLevel >= 5 ? entry.officerLevel : Math.min(1, entry.officerLevel),
|
||||
cityName: null,
|
||||
troopName: null,
|
||||
officerCity: 0,
|
||||
officerCityName: null,
|
||||
experienceLevel: experienceLevel(entry.experience),
|
||||
dedicationLevel: dedicationLevel(entry.dedication),
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
nation: {
|
||||
@@ -79,6 +124,7 @@ export const getGeneralList = authedProcedure.query(async ({ ctx }) => {
|
||||
capitalCityId: nation.capitalCityId ?? 0,
|
||||
},
|
||||
chiefStatMin: resolveChiefStatMin(worldState),
|
||||
generals: list,
|
||||
viewer: { generalId: general.id, permission },
|
||||
generals: visibleList,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
import { TRPCError } from '@trpc/server';
|
||||
|
||||
import { asRecord } from '@sammo-ts/common';
|
||||
|
||||
import { authedProcedure } from '../../../trpc.js';
|
||||
import { getMyGeneral } from '../../shared/general.js';
|
||||
import { assertNationAccess, resolveNationPermission } from '../shared.js';
|
||||
|
||||
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 woundedStat = (value: number, injury: number): number =>
|
||||
injury > 0 ? Math.floor((value * (100 - injury)) / 100) : value;
|
||||
const experienceLevel = (experience: number): number =>
|
||||
Math.max(
|
||||
0,
|
||||
Math.min(100, experience < 1000 ? Math.floor(experience / 100) : Math.floor(Math.sqrt(experience / 10)))
|
||||
);
|
||||
const leadershipBonus = (officerLevel: number, nationLevel: number): number =>
|
||||
officerLevel === 12 ? nationLevel * 2 : officerLevel >= 5 ? nationLevel : 0;
|
||||
const defenceTrainText = (value: number): string =>
|
||||
value === 999 ? '×' : value >= 90 ? '☆' : value >= 80 ? '◎' : value >= 60 ? '○' : '△';
|
||||
|
||||
export const getSecretGeneralList = authedProcedure.query(async ({ ctx }) => {
|
||||
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, meta: true },
|
||||
});
|
||||
if (!nation) throw new TRPCError({ code: 'NOT_FOUND', message: 'Nation not found' });
|
||||
const permission = resolveNationPermission(me, nation.meta, true);
|
||||
if (permission < 1) {
|
||||
throw new TRPCError({
|
||||
code: 'FORBIDDEN',
|
||||
message: '권한이 부족합니다. 수뇌부가 아니거나 사관년도가 부족합니다.',
|
||||
});
|
||||
}
|
||||
|
||||
const [cities, troops, 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 turns = generalIds.length
|
||||
? await ctx.db.generalTurn.findMany({
|
||||
where: { generalId: { in: generalIds }, turnIdx: { lt: 5 } },
|
||||
select: { generalId: true, turnIdx: true, actionCode: true },
|
||||
orderBy: [{ generalId: 'asc' }, { turnIdx: 'asc' }],
|
||||
})
|
||||
: [];
|
||||
const cityNames = new Map(cities.map((city) => [city.id, city.name]));
|
||||
const troopNames = new Map(troops.map((troop) => [troop.troopLeaderId, troop.name]));
|
||||
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 generals = generalRows.map((general) => {
|
||||
const meta = asRecord(general.meta);
|
||||
const defenceTrain = readNumber(meta, ['defenceTrain', 'defence_train'], 80);
|
||||
return {
|
||||
id: general.id,
|
||||
name: general.name,
|
||||
npcState: general.npcState,
|
||||
injury: general.injury,
|
||||
stats: {
|
||||
leadership: woundedStat(general.leadership, general.injury),
|
||||
strength: woundedStat(general.strength, general.injury),
|
||||
intelligence: woundedStat(general.intel, general.injury),
|
||||
},
|
||||
leadershipBonus: leadershipBonus(general.officerLevel, nation.level),
|
||||
experienceLevel: experienceLevel(general.experience),
|
||||
troopId: general.troopId,
|
||||
troopName: troopNames.get(general.troopId) ?? null,
|
||||
gold: general.gold,
|
||||
rice: general.rice,
|
||||
cityId: general.cityId,
|
||||
cityName: cityNames.get(general.cityId) ?? null,
|
||||
defenceTrain,
|
||||
defenceTrainText: defenceTrainText(defenceTrain),
|
||||
crewTypeId: general.crewTypeId,
|
||||
crew: general.crew,
|
||||
train: general.train,
|
||||
atmos: general.atmos,
|
||||
killTurn: readNumber(meta, ['killturn', 'killTurn']),
|
||||
turnTime: general.turnTime.toISOString(),
|
||||
reservedCommands: general.npcState < 2 ? (turnMap.get(general.id) ?? []) : [],
|
||||
};
|
||||
});
|
||||
const counted = generals.filter((general) => general.npcState !== 5);
|
||||
const summary = counted.reduce(
|
||||
(result, general) => {
|
||||
result.gold += general.gold;
|
||||
result.rice += general.rice;
|
||||
result.crew += general.crew;
|
||||
if (general.crew > 0) {
|
||||
for (const threshold of [90, 80, 60] as const) {
|
||||
if (general.train >= threshold && general.atmos >= threshold) {
|
||||
result.readiness[threshold].crew += general.crew;
|
||||
result.readiness[threshold].generals += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
},
|
||||
{
|
||||
gold: 0,
|
||||
rice: 0,
|
||||
crew: 0,
|
||||
readiness: {
|
||||
90: { crew: 0, generals: 0 },
|
||||
80: { crew: 0, generals: 0 },
|
||||
60: { crew: 0, generals: 0 },
|
||||
},
|
||||
}
|
||||
);
|
||||
return {
|
||||
nation: { id: nation.id, name: nation.name, color: nation.color, level: nation.level },
|
||||
viewer: { generalId: me.id, permission },
|
||||
summary: {
|
||||
...summary,
|
||||
generalCount: counted.length,
|
||||
averageGold: counted.length ? summary.gold / counted.length : 0,
|
||||
averageRice: counted.length ? summary.rice / counted.length : 0,
|
||||
},
|
||||
generals,
|
||||
};
|
||||
});
|
||||
@@ -5,6 +5,7 @@ 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 { getSecretGeneralList } from './endpoints/getSecretGeneralList.js';
|
||||
import { getGeneralLog } from './endpoints/getGeneralLog.js';
|
||||
import { getNationInfo } from './endpoints/getNationInfo.js';
|
||||
import { getPersonnelInfo } from './endpoints/getPersonnelInfo.js';
|
||||
@@ -21,6 +22,7 @@ import { setSecretLimit } from './endpoints/setSecretLimit.js';
|
||||
export const nationRouter = router({
|
||||
getNationInfo,
|
||||
getGeneralList,
|
||||
getSecretGeneralList,
|
||||
getCityOverview,
|
||||
getPersonnelInfo,
|
||||
getStratFinan,
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import path from 'node:path';
|
||||
|
||||
import { TRPCError } from '@trpc/server';
|
||||
import { z } from 'zod';
|
||||
|
||||
@@ -165,8 +163,6 @@ const FLOAT_POLICY_KEYS = ['safeRecruitCityPopulationRatio'] as const;
|
||||
type NumericPolicyKey = (typeof INTEGER_POLICY_KEYS)[number];
|
||||
type FloatPolicyKey = (typeof FLOAT_POLICY_KEYS)[number];
|
||||
|
||||
const UNIT_SET_ROOT = path.resolve(process.cwd(), 'resources', 'unitset');
|
||||
|
||||
const readNumber = (value: unknown, fallback = 0): number => {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||
return value;
|
||||
@@ -353,8 +349,8 @@ const buildZeroPolicy = async (
|
||||
}
|
||||
): Promise<NationPolicy> => {
|
||||
const { statMax, statNpcMax, nationTech, develCost, defaultCrewTypeId, unitSetName } = options;
|
||||
const unitSet = await loadUnitSetDefinitionByName(unitSetName, { unitSetRoot: UNIT_SET_ROOT });
|
||||
const crewType = findCrewTypeById(unitSet, defaultCrewTypeId);
|
||||
const unitSet = await loadUnitSetDefinitionByName(unitSetName);
|
||||
const crewType = findCrewTypeById(unitSet, defaultCrewTypeId || unitSet.defaultCrewTypeId || 0);
|
||||
const techCost = getTechCost(nationTech);
|
||||
const next = clonePolicy(policy);
|
||||
|
||||
@@ -364,7 +360,7 @@ const buildZeroPolicy = async (
|
||||
|
||||
if (next.reqNPCWarGold === 0 || next.reqNPCWarRice === 0) {
|
||||
const baseGold = crewType ? crewType.cost * techCost * statNpcMax : 0;
|
||||
const baseRice = statNpcMax;
|
||||
const baseRice = crewType ? crewType.rice * techCost * statNpcMax : 0;
|
||||
if (next.reqNPCWarGold === 0) {
|
||||
next.reqNPCWarGold = roundTo(baseGold * 4, -2);
|
||||
}
|
||||
@@ -375,7 +371,7 @@ const buildZeroPolicy = async (
|
||||
|
||||
if (next.reqHumanWarUrgentGold === 0 || next.reqHumanWarUrgentRice === 0) {
|
||||
const baseGold = crewType ? crewType.cost * techCost * statMax : 0;
|
||||
const baseRice = statMax;
|
||||
const baseRice = crewType ? crewType.rice * techCost * statMax : 0;
|
||||
if (next.reqHumanWarUrgentGold === 0) {
|
||||
next.reqHumanWarUrgentGold = roundTo(baseGold * 6, -2);
|
||||
}
|
||||
@@ -415,8 +411,6 @@ const resolveSetterInfo = (policy: Record<string, unknown>, kind: 'value' | 'pri
|
||||
};
|
||||
};
|
||||
|
||||
const ensureUniquePriority = (priority: string[]): string[] => Array.from(new Set(priority));
|
||||
|
||||
const validateGeneralPriority = (priority: string[]): string | null => {
|
||||
const orderRequired: Array<[string, string]> = [['출병', '일반내정']];
|
||||
const mustHave = new Set(['출병', '일반내정']);
|
||||
@@ -461,6 +455,7 @@ export const npcRouter = router({
|
||||
id: true,
|
||||
name: true,
|
||||
level: true,
|
||||
tech: true,
|
||||
meta: true,
|
||||
},
|
||||
}),
|
||||
@@ -508,9 +503,9 @@ export const npcRouter = router({
|
||||
const stat = resolveScenarioStat(config);
|
||||
const env = resolveCommandEnv(config);
|
||||
const unitSetName = resolveUnitSetName(config, 'che');
|
||||
const nationTech = readNumber(asRecord(nationMeta).tech, 0);
|
||||
const nationTech = readNumber(nation.tech, 0);
|
||||
|
||||
const zeroPolicy = await buildZeroPolicy(defaultNationPolicy, {
|
||||
const zeroPolicy = await buildZeroPolicy(DEFAULT_NATION_POLICY, {
|
||||
statMax: stat.max,
|
||||
statNpcMax: stat.npcMax,
|
||||
nationTech,
|
||||
@@ -542,277 +537,272 @@ export const npcRouter = router({
|
||||
permissionLevel,
|
||||
};
|
||||
}),
|
||||
setNationPolicy: authedProcedure
|
||||
.input(z.record(z.string(), z.unknown()))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const general = await getMyGeneral(ctx);
|
||||
if (general.nationId <= 0) {
|
||||
throw new TRPCError({ code: 'PRECONDITION_FAILED', message: 'Nation membership required.' });
|
||||
}
|
||||
setNationPolicy: authedProcedure.input(z.record(z.string(), z.unknown())).mutation(async ({ ctx, input }) => {
|
||||
const general = await getMyGeneral(ctx);
|
||||
if (general.nationId <= 0) {
|
||||
throw new TRPCError({ code: 'PRECONDITION_FAILED', message: 'Nation membership required.' });
|
||||
}
|
||||
|
||||
const nation = await ctx.db.nation.findUnique({
|
||||
where: { id: general.nationId },
|
||||
select: { id: true, meta: true },
|
||||
});
|
||||
if (!nation) {
|
||||
throw new TRPCError({ code: 'NOT_FOUND', message: 'Nation not found' });
|
||||
}
|
||||
const nation = await ctx.db.nation.findUnique({
|
||||
where: { id: general.nationId },
|
||||
select: { id: true, meta: true },
|
||||
});
|
||||
if (!nation) {
|
||||
throw new TRPCError({ code: 'NOT_FOUND', message: 'Nation not found' });
|
||||
}
|
||||
|
||||
const permissionLevel = resolveSecretPermission(
|
||||
{
|
||||
nationId: general.nationId,
|
||||
officerLevel: general.officerLevel,
|
||||
meta: general.meta,
|
||||
penalty: general.penalty,
|
||||
},
|
||||
nation.meta
|
||||
);
|
||||
if (permissionLevel < 3) {
|
||||
throw new TRPCError({ code: 'FORBIDDEN', message: '권한이 부족합니다.' });
|
||||
}
|
||||
const permissionLevel = resolveSecretPermission(
|
||||
{
|
||||
nationId: general.nationId,
|
||||
officerLevel: general.officerLevel,
|
||||
meta: general.meta,
|
||||
penalty: general.penalty,
|
||||
},
|
||||
nation.meta
|
||||
);
|
||||
if (permissionLevel < 3) {
|
||||
throw new TRPCError({ code: 'FORBIDDEN', message: '권한이 부족합니다.' });
|
||||
}
|
||||
|
||||
const keys = Object.keys(input);
|
||||
for (const key of keys) {
|
||||
if (!NATION_POLICY_KEYS.has(key as keyof NationPolicy)) {
|
||||
const keys = Object.keys(input);
|
||||
for (const key of keys) {
|
||||
if (!NATION_POLICY_KEYS.has(key as keyof NationPolicy)) {
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: `${key}는 올바른 정책값이 아닙니다.` });
|
||||
}
|
||||
}
|
||||
|
||||
const troopRows = await ctx.db.troop.findMany({
|
||||
where: { nationId: general.nationId },
|
||||
select: { troopLeaderId: true },
|
||||
});
|
||||
const cityRows = await ctx.db.city.findMany({ select: { id: true } });
|
||||
|
||||
const troopSet = new Set(troopRows.map((row) => row.troopLeaderId));
|
||||
const citySet = new Set(cityRows.map((row) => row.id));
|
||||
const assigned = new Set<number>();
|
||||
|
||||
const nationMeta = asRecord(nation.meta);
|
||||
const policyRoot = asRecord(nationMeta.npc_nation_policy);
|
||||
const nextValues = applyPolicyValues(DEFAULT_NATION_POLICY, asRecord(policyRoot.values));
|
||||
|
||||
for (const key of INTEGER_POLICY_KEYS) {
|
||||
if (!(key in input)) {
|
||||
continue;
|
||||
}
|
||||
const value = input[key];
|
||||
if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isInteger(value)) {
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: `${key}는 올바른 값이 아닙니다.` });
|
||||
}
|
||||
nextValues[key] = Math.max(0, value);
|
||||
}
|
||||
|
||||
for (const key of FLOAT_POLICY_KEYS) {
|
||||
if (!(key in input)) {
|
||||
continue;
|
||||
}
|
||||
const value = input[key];
|
||||
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: `${key}는 올바른 값이 아닙니다.` });
|
||||
}
|
||||
nextValues[key] = value;
|
||||
}
|
||||
|
||||
if ('CombatForce' in input) {
|
||||
const rawCombat = input.CombatForce;
|
||||
if (!isRecord(rawCombat)) {
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: 'CombatForce는 올바른 정책값이 아닙니다.' });
|
||||
}
|
||||
const combatForce: Record<number, [number, number]> = {};
|
||||
for (const [rawKey, rawValue] of Object.entries(rawCombat)) {
|
||||
const leaderId = Number(rawKey);
|
||||
if (!Number.isFinite(leaderId)) {
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: `${rawKey}는 올바른 부대가 아닙니다.` });
|
||||
}
|
||||
if (!troopSet.has(leaderId)) {
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: `${leaderId}는 국가의 부대가 아닙니다.` });
|
||||
}
|
||||
if (assigned.has(leaderId)) {
|
||||
throw new TRPCError({
|
||||
code: 'BAD_REQUEST',
|
||||
message: `부대(${leaderId})는 하나의 역할만 지정할 수 있습니다.`,
|
||||
});
|
||||
}
|
||||
if (!Array.isArray(rawValue) || rawValue.length < 2) {
|
||||
throw new TRPCError({
|
||||
code: 'BAD_REQUEST',
|
||||
message: `${leaderId}의 입력양식이 올바르지 않습니다.`,
|
||||
});
|
||||
}
|
||||
const fromCity = Number(rawValue[0]);
|
||||
const toCity = Number(rawValue[1]);
|
||||
if (!citySet.has(fromCity) || !citySet.has(toCity)) {
|
||||
throw new TRPCError({
|
||||
code: 'BAD_REQUEST',
|
||||
message: `${leaderId}의 도시 ${fromCity}, ${toCity}가 올바른 도시 번호가 아닙니다.`,
|
||||
});
|
||||
}
|
||||
combatForce[leaderId] = [fromCity, toCity];
|
||||
assigned.add(leaderId);
|
||||
}
|
||||
nextValues.CombatForce = combatForce;
|
||||
}
|
||||
|
||||
for (const key of ['SupportForce', 'DevelopForce'] as const) {
|
||||
if (!(key in input)) {
|
||||
continue;
|
||||
}
|
||||
const rawList = input[key];
|
||||
if (!Array.isArray(rawList)) {
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: `${key}는 올바른 정책값이 아닙니다.` });
|
||||
}
|
||||
const list: number[] = [];
|
||||
for (const rawValue of rawList) {
|
||||
if (typeof rawValue !== 'number' || !Number.isFinite(rawValue)) {
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: `${key}는 올바른 정책값이 아닙니다.` });
|
||||
}
|
||||
}
|
||||
|
||||
const troopRows = await ctx.db.troop.findMany({
|
||||
where: { nationId: general.nationId },
|
||||
select: { troopLeaderId: true },
|
||||
});
|
||||
const cityRows = await ctx.db.city.findMany({ select: { id: true } });
|
||||
|
||||
const troopSet = new Set(troopRows.map((row) => row.troopLeaderId));
|
||||
const citySet = new Set(cityRows.map((row) => row.id));
|
||||
const assigned = new Set<number>();
|
||||
|
||||
const nationMeta = asRecord(nation.meta);
|
||||
const policyRoot = asRecord(nationMeta.npc_nation_policy);
|
||||
const nextValues = applyPolicyValues(DEFAULT_NATION_POLICY, asRecord(policyRoot.values));
|
||||
|
||||
for (const key of INTEGER_POLICY_KEYS) {
|
||||
if (!(key in input)) {
|
||||
continue;
|
||||
if (!troopSet.has(rawValue)) {
|
||||
throw new TRPCError({
|
||||
code: 'BAD_REQUEST',
|
||||
message: `${rawValue}는 국가의 부대가 아닙니다.`,
|
||||
});
|
||||
}
|
||||
const value = input[key];
|
||||
if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isInteger(value)) {
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: `${key}는 올바른 값이 아닙니다.` });
|
||||
if (assigned.has(rawValue)) {
|
||||
throw new TRPCError({
|
||||
code: 'BAD_REQUEST',
|
||||
message: `부대(${rawValue})는 하나의 역할만 지정할 수 있습니다.`,
|
||||
});
|
||||
}
|
||||
nextValues[key] = Math.max(0, value);
|
||||
assigned.add(rawValue);
|
||||
list.push(rawValue);
|
||||
}
|
||||
|
||||
for (const key of FLOAT_POLICY_KEYS) {
|
||||
if (!(key in input)) {
|
||||
continue;
|
||||
}
|
||||
const value = input[key];
|
||||
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: `${key}는 올바른 값이 아닙니다.` });
|
||||
}
|
||||
nextValues[key] = Math.max(0, value);
|
||||
if (key === 'SupportForce') {
|
||||
nextValues.SupportForce = list;
|
||||
} else {
|
||||
nextValues.DevelopForce = list;
|
||||
}
|
||||
}
|
||||
|
||||
if ('CombatForce' in input) {
|
||||
const rawCombat = input.CombatForce;
|
||||
if (!isRecord(rawCombat)) {
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: 'CombatForce는 올바른 정책값이 아닙니다.' });
|
||||
}
|
||||
const combatForce: Record<number, [number, number]> = {};
|
||||
for (const [rawKey, rawValue] of Object.entries(rawCombat)) {
|
||||
const leaderId = Number(rawKey);
|
||||
if (!Number.isFinite(leaderId)) {
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: `${rawKey}는 올바른 부대가 아닙니다.` });
|
||||
}
|
||||
if (!troopSet.has(leaderId)) {
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: `${leaderId}는 국가의 부대가 아닙니다.` });
|
||||
}
|
||||
if (assigned.has(leaderId)) {
|
||||
throw new TRPCError({
|
||||
code: 'BAD_REQUEST',
|
||||
message: `부대(${leaderId})는 하나의 역할만 지정할 수 있습니다.`,
|
||||
});
|
||||
}
|
||||
if (!Array.isArray(rawValue) || rawValue.length < 2) {
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: `${leaderId}의 입력양식이 올바르지 않습니다.` });
|
||||
}
|
||||
const fromCity = Number(rawValue[0]);
|
||||
const toCity = Number(rawValue[1]);
|
||||
if (!citySet.has(fromCity) || !citySet.has(toCity)) {
|
||||
throw new TRPCError({
|
||||
code: 'BAD_REQUEST',
|
||||
message: `${leaderId}의 도시 ${fromCity}, ${toCity}가 올바른 도시 번호가 아닙니다.`,
|
||||
});
|
||||
}
|
||||
combatForce[leaderId] = [fromCity, toCity];
|
||||
assigned.add(leaderId);
|
||||
}
|
||||
nextValues.CombatForce = combatForce;
|
||||
const nextPolicyRoot = {
|
||||
...policyRoot,
|
||||
values: nextValues,
|
||||
valueSetter: general.name,
|
||||
valueSetTime: new Date().toISOString(),
|
||||
};
|
||||
|
||||
await updateNationMeta(
|
||||
ctx,
|
||||
nation.id,
|
||||
{
|
||||
npc_nation_policy: nextPolicyRoot,
|
||||
},
|
||||
nationMeta
|
||||
);
|
||||
|
||||
return { ok: true };
|
||||
}),
|
||||
setNationPriority: authedProcedure.input(z.array(z.string())).mutation(async ({ ctx, input }) => {
|
||||
const general = await getMyGeneral(ctx);
|
||||
if (general.nationId <= 0) {
|
||||
throw new TRPCError({ code: 'PRECONDITION_FAILED', message: 'Nation membership required.' });
|
||||
}
|
||||
|
||||
const nation = await ctx.db.nation.findUnique({
|
||||
where: { id: general.nationId },
|
||||
select: { id: true, meta: true },
|
||||
});
|
||||
if (!nation) {
|
||||
throw new TRPCError({ code: 'NOT_FOUND', message: 'Nation not found' });
|
||||
}
|
||||
|
||||
const permissionLevel = resolveSecretPermission(
|
||||
{
|
||||
nationId: general.nationId,
|
||||
officerLevel: general.officerLevel,
|
||||
meta: general.meta,
|
||||
penalty: general.penalty,
|
||||
},
|
||||
nation.meta
|
||||
);
|
||||
if (permissionLevel < 3) {
|
||||
throw new TRPCError({ code: 'FORBIDDEN', message: '권한이 부족합니다.' });
|
||||
}
|
||||
|
||||
for (const item of input) {
|
||||
if (!DEFAULT_NATION_PRIORITY.includes(item as (typeof DEFAULT_NATION_PRIORITY)[number])) {
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: `${item}은 올바른 명령이 아닙니다.` });
|
||||
}
|
||||
}
|
||||
|
||||
for (const key of ['SupportForce', 'DevelopForce'] as const) {
|
||||
if (!(key in input)) {
|
||||
continue;
|
||||
}
|
||||
const rawList = input[key];
|
||||
if (!Array.isArray(rawList)) {
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: `${key}는 올바른 정책값이 아닙니다.` });
|
||||
}
|
||||
const list: number[] = [];
|
||||
for (const rawValue of rawList) {
|
||||
if (typeof rawValue !== 'number' || !Number.isFinite(rawValue)) {
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: `${key}는 올바른 정책값이 아닙니다.` });
|
||||
}
|
||||
if (!troopSet.has(rawValue)) {
|
||||
throw new TRPCError({
|
||||
code: 'BAD_REQUEST',
|
||||
message: `${rawValue}는 국가의 부대가 아닙니다.`,
|
||||
});
|
||||
}
|
||||
if (assigned.has(rawValue)) {
|
||||
throw new TRPCError({
|
||||
code: 'BAD_REQUEST',
|
||||
message: `부대(${rawValue})는 하나의 역할만 지정할 수 있습니다.`,
|
||||
});
|
||||
}
|
||||
assigned.add(rawValue);
|
||||
list.push(rawValue);
|
||||
}
|
||||
if (key === 'SupportForce') {
|
||||
nextValues.SupportForce = list;
|
||||
} else {
|
||||
nextValues.DevelopForce = list;
|
||||
}
|
||||
}
|
||||
const nationMeta = asRecord(nation.meta);
|
||||
const policyRoot = asRecord(nationMeta.npc_nation_policy);
|
||||
const nextPolicyRoot = {
|
||||
...policyRoot,
|
||||
priority: input,
|
||||
prioritySetter: general.name,
|
||||
prioritySetTime: new Date().toISOString(),
|
||||
};
|
||||
|
||||
const nextPolicyRoot = {
|
||||
...policyRoot,
|
||||
values: nextValues,
|
||||
valueSetter: general.name,
|
||||
valueSetTime: new Date().toISOString(),
|
||||
};
|
||||
await updateNationMeta(
|
||||
ctx,
|
||||
nation.id,
|
||||
{
|
||||
npc_nation_policy: nextPolicyRoot,
|
||||
},
|
||||
nationMeta
|
||||
);
|
||||
|
||||
await updateNationMeta(
|
||||
ctx,
|
||||
nation.id,
|
||||
{
|
||||
npc_nation_policy: nextPolicyRoot,
|
||||
},
|
||||
nationMeta
|
||||
);
|
||||
return { ok: true };
|
||||
}),
|
||||
setGeneralPriority: authedProcedure.input(z.array(z.string())).mutation(async ({ ctx, input }) => {
|
||||
const general = await getMyGeneral(ctx);
|
||||
if (general.nationId <= 0) {
|
||||
throw new TRPCError({ code: 'PRECONDITION_FAILED', message: 'Nation membership required.' });
|
||||
}
|
||||
|
||||
return { ok: true };
|
||||
}),
|
||||
setNationPriority: authedProcedure
|
||||
.input(z.array(z.string()))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const general = await getMyGeneral(ctx);
|
||||
if (general.nationId <= 0) {
|
||||
throw new TRPCError({ code: 'PRECONDITION_FAILED', message: 'Nation membership required.' });
|
||||
}
|
||||
const nation = await ctx.db.nation.findUnique({
|
||||
where: { id: general.nationId },
|
||||
select: { id: true, meta: true },
|
||||
});
|
||||
if (!nation) {
|
||||
throw new TRPCError({ code: 'NOT_FOUND', message: 'Nation not found' });
|
||||
}
|
||||
|
||||
const nation = await ctx.db.nation.findUnique({
|
||||
where: { id: general.nationId },
|
||||
select: { id: true, meta: true },
|
||||
});
|
||||
if (!nation) {
|
||||
throw new TRPCError({ code: 'NOT_FOUND', message: 'Nation not found' });
|
||||
}
|
||||
const permissionLevel = resolveSecretPermission(
|
||||
{
|
||||
nationId: general.nationId,
|
||||
officerLevel: general.officerLevel,
|
||||
meta: general.meta,
|
||||
penalty: general.penalty,
|
||||
},
|
||||
nation.meta
|
||||
);
|
||||
if (permissionLevel < 3) {
|
||||
throw new TRPCError({ code: 'FORBIDDEN', message: '권한이 부족합니다.' });
|
||||
}
|
||||
|
||||
const permissionLevel = resolveSecretPermission(
|
||||
{
|
||||
nationId: general.nationId,
|
||||
officerLevel: general.officerLevel,
|
||||
meta: general.meta,
|
||||
penalty: general.penalty,
|
||||
},
|
||||
nation.meta
|
||||
);
|
||||
if (permissionLevel < 3) {
|
||||
throw new TRPCError({ code: 'FORBIDDEN', message: '권한이 부족합니다.' });
|
||||
}
|
||||
const validationError = validateGeneralPriority(input);
|
||||
if (validationError) {
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: validationError });
|
||||
}
|
||||
|
||||
const unique = ensureUniquePriority(input);
|
||||
for (const item of unique) {
|
||||
if (!DEFAULT_NATION_PRIORITY.includes(item as (typeof DEFAULT_NATION_PRIORITY)[number])) {
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: `${item}은 올바른 명령이 아닙니다.` });
|
||||
}
|
||||
}
|
||||
const nationMeta = asRecord(nation.meta);
|
||||
const policyRoot = asRecord(nationMeta.npc_general_policy);
|
||||
const nextPolicyRoot = {
|
||||
...policyRoot,
|
||||
priority: input,
|
||||
prioritySetter: general.name,
|
||||
prioritySetTime: new Date().toISOString(),
|
||||
};
|
||||
|
||||
const nationMeta = asRecord(nation.meta);
|
||||
const policyRoot = asRecord(nationMeta.npc_nation_policy);
|
||||
const nextPolicyRoot = {
|
||||
...policyRoot,
|
||||
priority: unique,
|
||||
prioritySetter: general.name,
|
||||
prioritySetTime: new Date().toISOString(),
|
||||
};
|
||||
await updateNationMeta(
|
||||
ctx,
|
||||
nation.id,
|
||||
{
|
||||
npc_general_policy: nextPolicyRoot,
|
||||
},
|
||||
nationMeta
|
||||
);
|
||||
|
||||
await updateNationMeta(
|
||||
ctx,
|
||||
nation.id,
|
||||
{
|
||||
npc_nation_policy: nextPolicyRoot,
|
||||
},
|
||||
nationMeta
|
||||
);
|
||||
|
||||
return { ok: true };
|
||||
}),
|
||||
setGeneralPriority: authedProcedure
|
||||
.input(z.array(z.string()))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const general = await getMyGeneral(ctx);
|
||||
if (general.nationId <= 0) {
|
||||
throw new TRPCError({ code: 'PRECONDITION_FAILED', message: 'Nation membership required.' });
|
||||
}
|
||||
|
||||
const nation = await ctx.db.nation.findUnique({
|
||||
where: { id: general.nationId },
|
||||
select: { id: true, meta: true },
|
||||
});
|
||||
if (!nation) {
|
||||
throw new TRPCError({ code: 'NOT_FOUND', message: 'Nation not found' });
|
||||
}
|
||||
|
||||
const permissionLevel = resolveSecretPermission(
|
||||
{
|
||||
nationId: general.nationId,
|
||||
officerLevel: general.officerLevel,
|
||||
meta: general.meta,
|
||||
penalty: general.penalty,
|
||||
},
|
||||
nation.meta
|
||||
);
|
||||
if (permissionLevel < 3) {
|
||||
throw new TRPCError({ code: 'FORBIDDEN', message: '권한이 부족합니다.' });
|
||||
}
|
||||
|
||||
const unique = ensureUniquePriority(input);
|
||||
const validationError = validateGeneralPriority(unique);
|
||||
if (validationError) {
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: validationError });
|
||||
}
|
||||
|
||||
const nationMeta = asRecord(nation.meta);
|
||||
const policyRoot = asRecord(nationMeta.npc_general_policy);
|
||||
const nextPolicyRoot = {
|
||||
...policyRoot,
|
||||
priority: unique,
|
||||
prioritySetter: general.name,
|
||||
prioritySetTime: new Date().toISOString(),
|
||||
};
|
||||
|
||||
await updateNationMeta(
|
||||
ctx,
|
||||
nation.id,
|
||||
{
|
||||
npc_general_policy: nextPolicyRoot,
|
||||
},
|
||||
nationMeta
|
||||
);
|
||||
|
||||
return { ok: true };
|
||||
}),
|
||||
return { ok: true };
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -7,6 +7,7 @@ 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 { loadUnitSetDefinitionByName } from '../../battleSim/unitSetLoader.js';
|
||||
import { getMyGeneral, getOwnedGeneral } from '../shared/general.js';
|
||||
|
||||
const isWorldAdmin = (roles: readonly string[]): boolean =>
|
||||
@@ -33,6 +34,29 @@ const defenceTrain = (meta: unknown): number => {
|
||||
return typeof raw === 'number' && Number.isFinite(raw) ? raw : 0;
|
||||
};
|
||||
|
||||
const unitSetName = (world: WorldStateRow | null, fallback: string): string => {
|
||||
const config = asRecord(world?.config);
|
||||
const environment = asRecord(config.environment ?? config.map);
|
||||
return typeof environment.unitSet === 'string' && environment.unitSet.trim() ? environment.unitSet : fallback;
|
||||
};
|
||||
|
||||
const crewTypeNameCache = new Map<string, Promise<Map<number, string>>>();
|
||||
const loadCrewTypeNames = (name: string): Promise<Map<number, string>> => {
|
||||
const cached = crewTypeNameCache.get(name);
|
||||
if (cached) return cached;
|
||||
const pending = loadUnitSetDefinitionByName(name)
|
||||
.then((definition) => new Map((definition.crewTypes ?? []).map((crewType) => [crewType.id, crewType.name])))
|
||||
.catch(() => new Map<number, string>());
|
||||
crewTypeNameCache.set(name, pending);
|
||||
return pending;
|
||||
};
|
||||
|
||||
const leadershipBonus = (officerLevel: number, nationLevel: number): number => {
|
||||
if (officerLevel === 12) return nationLevel * 2;
|
||||
if (officerLevel >= 5) return nationLevel;
|
||||
return 0;
|
||||
};
|
||||
|
||||
const toWorldStateSnapshot = (row: WorldStateRow) => ({
|
||||
scenarioCode: row.scenarioCode,
|
||||
currentYear: row.currentYear,
|
||||
@@ -122,6 +146,8 @@ export const worldRouter = router({
|
||||
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));
|
||||
}
|
||||
if ((nation?.level ?? 0) > 0) {
|
||||
Object.keys(spy).forEach((id) => selectable.add(Number(id)));
|
||||
}
|
||||
if (admin) cities.forEach((city) => selectable.add(city.id));
|
||||
@@ -150,6 +176,8 @@ export const worldRouter = router({
|
||||
turnMap.set(turn.generalId, list);
|
||||
}
|
||||
const nationMap = new Map(nations.map((item) => [item.id, item]));
|
||||
const selectedNation = nationMap.get(selected.nationId);
|
||||
const crewTypeNames = await loadCrewTypeNames(unitSetName(world, ctx.profile.id));
|
||||
const officers = await ctx.db.general.findMany({
|
||||
where: { officerLevel: { in: [2, 3, 4] } },
|
||||
select: { name: true, officerLevel: true, meta: true },
|
||||
@@ -175,14 +203,59 @@ export const worldRouter = router({
|
||||
intelligence: general.intel,
|
||||
injury: general.injury,
|
||||
officerLevel: general.officerLevel,
|
||||
leadershipBonus: leadershipBonus(general.officerLevel, nationMap.get(general.nationId)?.level ?? 0),
|
||||
defenceTrain: ours ? defenceTrain(general.meta) : null,
|
||||
crewTypeId: ours ? general.crewTypeId : null,
|
||||
crewTypeName: ours ? (crewTypeNames.get(general.crewTypeId) ?? null) : 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) ?? []) : [],
|
||||
};
|
||||
});
|
||||
const forceSummary = mappedGenerals.reduce(
|
||||
(summary, general) => {
|
||||
if (general.nationId > 0 && me.nationId > 0 && general.nationId !== me.nationId) {
|
||||
summary.enemyGenerals += 1;
|
||||
if (general.crew !== null && general.crew >= 0) summary.enemyCrew += general.crew;
|
||||
if (general.crew !== null && general.crew > 0) summary.enemyArmedGenerals += 1;
|
||||
return summary;
|
||||
}
|
||||
if (me.nationId <= 0 || general.nationId !== me.nationId) return summary;
|
||||
summary.ownGenerals += 1;
|
||||
summary.ownCrew += general.crew ?? 0;
|
||||
if ((general.crew ?? 0) <= 0) return summary;
|
||||
summary.ownArmedGenerals += 1;
|
||||
const readiness = Math.min(general.train ?? -1, general.atmos ?? -1);
|
||||
if (readiness >= 90) {
|
||||
summary.ready90Crew += general.crew ?? 0;
|
||||
summary.ready90Generals += 1;
|
||||
}
|
||||
if (readiness >= 60) {
|
||||
summary.ready60Crew += general.crew ?? 0;
|
||||
summary.ready60Generals += 1;
|
||||
}
|
||||
if (general.defenceTrain !== null && readiness >= general.defenceTrain) {
|
||||
summary.defenceReadyCrew += general.crew ?? 0;
|
||||
summary.defenceReadyGenerals += 1;
|
||||
}
|
||||
return summary;
|
||||
},
|
||||
{
|
||||
enemyCrew: 0,
|
||||
enemyArmedGenerals: 0,
|
||||
enemyGenerals: 0,
|
||||
ownCrew: 0,
|
||||
ownArmedGenerals: 0,
|
||||
ownGenerals: 0,
|
||||
ready90Crew: 0,
|
||||
ready90Generals: 0,
|
||||
ready60Crew: 0,
|
||||
ready60Generals: 0,
|
||||
defenceReadyCrew: 0,
|
||||
defenceReadyGenerals: 0,
|
||||
}
|
||||
);
|
||||
return {
|
||||
me: { id: me.id, nationId: me.nationId, officerLevel: me.officerLevel, admin },
|
||||
options: [...selectable]
|
||||
@@ -194,6 +267,7 @@ export const worldRouter = router({
|
||||
id: selected.id,
|
||||
name: selected.name,
|
||||
nationId: selected.nationId,
|
||||
nationColor: selectedNation?.color ?? '#000000',
|
||||
level: selected.level,
|
||||
region: selected.region,
|
||||
population: redact(selected.population),
|
||||
@@ -217,8 +291,11 @@ export const worldRouter = router({
|
||||
},
|
||||
},
|
||||
generals: mappedGenerals,
|
||||
forceSummary,
|
||||
lastExecute:
|
||||
typeof asRecord(world?.meta).turntime === 'string' ? String(asRecord(world?.meta).turntime) : '',
|
||||
typeof asRecord(world?.meta).turntime === 'string'
|
||||
? String(asRecord(world?.meta).turntime).slice(5, 19)
|
||||
: '',
|
||||
};
|
||||
}),
|
||||
getState: procedure.query(async ({ ctx }) => {
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import { createTournamentRng } from '@sammo-ts/common';
|
||||
import { createTournamentRng, type TurnDaemonCommandResult } from '@sammo-ts/common';
|
||||
import { resolveTournamentBattle } from '@sammo-ts/logic';
|
||||
import {
|
||||
createGamePostgresConnector,
|
||||
createRedisConnector,
|
||||
resolvePostgresConfigFromEnv,
|
||||
resolveRedisConfigFromEnv,
|
||||
type GamePrismaClient,
|
||||
} from '@sammo-ts/infra';
|
||||
|
||||
import { resolveGameApiConfigFromEnv } from '../config.js';
|
||||
import { RedisTurnDaemonTransport } from '../daemon/redisTransport.js';
|
||||
import { buildTurnDaemonStreamKeys } from '../daemon/streamKeys.js';
|
||||
import { DatabaseTurnDaemonTransport } from '../daemon/databaseTransport.js';
|
||||
import type { TurnDaemonTransport } from '../daemon/transport.js';
|
||||
import { buildTournamentKeys } from './keys.js';
|
||||
import { TournamentStore } from './store.js';
|
||||
@@ -462,13 +462,30 @@ export const settleTournamentOutcome = async (options: {
|
||||
return null;
|
||||
}
|
||||
|
||||
let settledState: TournamentState | null = null;
|
||||
let settledState = state;
|
||||
let changed = false;
|
||||
|
||||
if (!state.rewardSettled) {
|
||||
const requireSuccessfulResult = (
|
||||
result: TurnDaemonCommandResult | null,
|
||||
expectedType: TurnDaemonCommandResult['type']
|
||||
): void => {
|
||||
if (!result) {
|
||||
throw new Error(`${expectedType} 명령 응답 시간이 초과되었습니다.`);
|
||||
}
|
||||
if (result.type !== expectedType) {
|
||||
throw new Error(`${expectedType} 명령에 잘못된 응답(${result.type})을 받았습니다.`);
|
||||
}
|
||||
if (!result.ok) {
|
||||
throw new Error(`${expectedType} 명령이 실패했습니다: ${result.reason}`);
|
||||
}
|
||||
};
|
||||
|
||||
if (!settledState.rewardSettled) {
|
||||
const matches = await store.getMatches();
|
||||
const rewardPayload = buildTournamentRewardPayload(matches);
|
||||
await daemonTransport.sendCommand({
|
||||
const result = await daemonTransport.requestCommand({
|
||||
type: 'tournamentReward',
|
||||
requestId: `tournament:${state.bettingId ?? `${state.openYear}:${state.openMonth}:${state.type}`}:reward`,
|
||||
tournamentType: state.type,
|
||||
winnerId: rewardPayload.winnerId,
|
||||
runnerUpId: rewardPayload.runnerUpId,
|
||||
@@ -476,46 +493,100 @@ export const settleTournamentOutcome = async (options: {
|
||||
top8: rewardPayload.top8,
|
||||
top4: rewardPayload.top4,
|
||||
});
|
||||
requireSuccessfulResult(result, 'tournamentReward');
|
||||
settledState = {
|
||||
...(settledState ?? state),
|
||||
...settledState,
|
||||
rewardSettled: true,
|
||||
};
|
||||
changed = true;
|
||||
await store.setState(settledState);
|
||||
}
|
||||
|
||||
if (state.bettingId && !state.bettingSettled) {
|
||||
if (settledState.bettingId && !settledState.bettingSettled) {
|
||||
const bettingEntries = await store.getBettingEntries();
|
||||
if (bettingEntries.length > 0) {
|
||||
const payoutInfo = buildBettingPayouts(state.winnerId, bettingEntries);
|
||||
const payoutInfo = buildBettingPayouts(settledState.winnerId!, bettingEntries);
|
||||
if (payoutInfo.payouts.length > 0) {
|
||||
if (payoutInfo.refundAll) {
|
||||
await daemonTransport.sendCommand({
|
||||
const result = await daemonTransport.requestCommand({
|
||||
type: 'tournamentRefund',
|
||||
bettingId: state.bettingId,
|
||||
requestId: `tournament:${settledState.bettingId}:betting-refund`,
|
||||
bettingId: settledState.bettingId,
|
||||
refunds: payoutInfo.payouts,
|
||||
reason: 'no_winner',
|
||||
});
|
||||
requireSuccessfulResult(result, 'tournamentRefund');
|
||||
} else {
|
||||
await daemonTransport.sendCommand({
|
||||
const result = await daemonTransport.requestCommand({
|
||||
type: 'tournamentBettingPayout',
|
||||
bettingId: state.bettingId,
|
||||
requestId: `tournament:${settledState.bettingId}:betting-payout`,
|
||||
bettingId: settledState.bettingId,
|
||||
payouts: payoutInfo.payouts,
|
||||
reason: 'winner_payout',
|
||||
});
|
||||
requireSuccessfulResult(result, 'tournamentBettingPayout');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
settledState = {
|
||||
...(settledState ?? state),
|
||||
...settledState,
|
||||
bettingSettled: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (settledState) {
|
||||
changed = true;
|
||||
await store.setState(settledState);
|
||||
}
|
||||
|
||||
return settledState;
|
||||
return changed ? settledState : null;
|
||||
};
|
||||
|
||||
const needsSettlement = (state: TournamentState): boolean =>
|
||||
state.stage === 0 &&
|
||||
Boolean(state.winnerId) &&
|
||||
(!state.rewardSettled || (Boolean(state.bettingId) && !state.bettingSettled));
|
||||
|
||||
export const processTournamentTick = async (options: {
|
||||
store: TournamentStore;
|
||||
prisma: GamePrismaClient;
|
||||
daemonTransport: TurnDaemonTransport;
|
||||
now?: () => number;
|
||||
}): Promise<TournamentState | null> => {
|
||||
const { store, prisma, daemonTransport } = options;
|
||||
const now = options.now ?? Date.now;
|
||||
let processedState: TournamentState | null = null;
|
||||
|
||||
await store.withMutationLock(async () => {
|
||||
const state = await store.getState();
|
||||
if (!state || (!state.auto && !needsSettlement(state))) {
|
||||
return;
|
||||
}
|
||||
const nextAt = new Date(state.nextAt).getTime();
|
||||
if (state.auto && Number.isFinite(nextAt) && nextAt > now()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (needsSettlement(state)) {
|
||||
processedState = (await settleTournamentOutcome({ store, daemonTransport, state })) ?? state;
|
||||
return;
|
||||
}
|
||||
|
||||
const worldState = await prisma.worldState.findFirst();
|
||||
const baseSeed = (worldState?.meta as Record<string, unknown> | null)?.hiddenSeed ?? 'tournament';
|
||||
let nextState = state;
|
||||
if (isBattleStage(state.stage)) {
|
||||
nextState = await applyBattle(store, state, String(baseSeed), daemonTransport);
|
||||
} else if (isPreBattleStage(state.stage)) {
|
||||
nextState = await applyPreBattleStage(store, prisma, state, String(baseSeed), daemonTransport);
|
||||
}
|
||||
processedState =
|
||||
(await settleTournamentOutcome({
|
||||
store,
|
||||
daemonTransport,
|
||||
state: nextState,
|
||||
})) ?? nextState;
|
||||
});
|
||||
|
||||
return processedState;
|
||||
};
|
||||
|
||||
export const runTournamentWorker = async (): Promise<void> => {
|
||||
@@ -527,10 +598,7 @@ export const runTournamentWorker = async (): Promise<void> => {
|
||||
await redis.connect();
|
||||
|
||||
const store = new TournamentStore(redis.client, buildTournamentKeys(config.profileName));
|
||||
const daemonTransport = new RedisTurnDaemonTransport(redis.client, {
|
||||
keys: buildTurnDaemonStreamKeys(config.profileName),
|
||||
requestTimeoutMs: config.daemonRequestTimeoutMs,
|
||||
});
|
||||
const daemonTransport = new DatabaseTurnDaemonTransport(postgres.prisma, config.daemonRequestTimeoutMs);
|
||||
|
||||
const handleExit = async () => {
|
||||
await redis.disconnect();
|
||||
@@ -541,49 +609,23 @@ export const runTournamentWorker = async (): Promise<void> => {
|
||||
|
||||
while (true) {
|
||||
const state = await store.getState();
|
||||
if (!state || !state.auto) {
|
||||
if (!state || (!state.auto && !needsSettlement(state))) {
|
||||
await sleepMs(config.tournamentPollMs);
|
||||
continue;
|
||||
}
|
||||
|
||||
const nextAt = new Date(state.nextAt).getTime();
|
||||
const now = Date.now();
|
||||
if (Number.isFinite(nextAt) && nextAt > now) {
|
||||
if (state.auto && Number.isFinite(nextAt) && nextAt > now) {
|
||||
await sleepMs(Math.min(config.tournamentPollMs, nextAt - now));
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
await store.withMutationLock(async () => {
|
||||
const lockedState = await store.getState();
|
||||
if (!lockedState || !lockedState.auto) {
|
||||
return;
|
||||
}
|
||||
const lockedNextAt = new Date(lockedState.nextAt).getTime();
|
||||
if (Number.isFinite(lockedNextAt) && lockedNextAt > Date.now()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const worldState = await postgres.prisma.worldState.findFirst();
|
||||
const baseSeed = (worldState?.meta as Record<string, unknown> | null)?.hiddenSeed ?? 'tournament';
|
||||
let nextState = lockedState;
|
||||
if (isBattleStage(lockedState.stage)) {
|
||||
nextState = await applyBattle(store, lockedState, String(baseSeed), daemonTransport);
|
||||
} else if (isPreBattleStage(lockedState.stage)) {
|
||||
nextState = await applyPreBattleStage(
|
||||
store,
|
||||
postgres.prisma,
|
||||
lockedState,
|
||||
String(baseSeed),
|
||||
daemonTransport
|
||||
);
|
||||
}
|
||||
|
||||
await settleTournamentOutcome({
|
||||
store,
|
||||
daemonTransport,
|
||||
state: nextState,
|
||||
});
|
||||
await processTournamentTick({
|
||||
store,
|
||||
prisma: postgres.prisma,
|
||||
daemonTransport,
|
||||
});
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error';
|
||||
@@ -603,9 +645,9 @@ export const runTournamentWorker = async (): Promise<void> => {
|
||||
},
|
||||
},
|
||||
});
|
||||
const currentState = (await store.getState()) ?? state;
|
||||
const nextState: TournamentState = {
|
||||
...state,
|
||||
auto: false,
|
||||
...currentState,
|
||||
lastError: message,
|
||||
lastErrorAt: now,
|
||||
};
|
||||
|
||||
@@ -520,8 +520,9 @@ export const buildBettingPayouts = (
|
||||
const winners = entries.filter((entry) => entry.targetId === winnerId);
|
||||
const winnersTotal = winners.reduce((sum, entry) => sum + entry.amount, 0);
|
||||
if (winnersTotal <= 0) {
|
||||
const refunds = entries.map((entry) => ({ generalId: entry.generalId, amount: entry.amount }));
|
||||
return { payouts: refunds, total, refundAll: true };
|
||||
// Legacy Betting::_calcRewardExclusive() builds a refund candidate list
|
||||
// but returns no rewards when nobody selected the winner.
|
||||
return { payouts: [], total, refundAll: false };
|
||||
}
|
||||
const ratio = total / winnersTotal;
|
||||
const payouts = winners.map((entry) => ({
|
||||
|
||||
Reference in New Issue
Block a user