Add nation general and secret office parity

This commit is contained in:
2026-07-26 05:16:07 +00:00
parent b02ab9fe99
commit 8771840c1c
11 changed files with 1001 additions and 325 deletions
@@ -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,
};
});
+2
View File
@@ -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,
@@ -0,0 +1,142 @@
import { describe, expect, it, vi } from 'vitest';
import type { GameSessionTokenPayload } from '@sammo-ts/common/auth/gameToken';
import type { RedisConnector } from '@sammo-ts/infra';
import { RedisAccessTokenStore } from '../src/auth/accessTokenStore.js';
import { InMemoryFlushStore } from '../src/auth/flushStore.js';
import type { DatabaseClient, GameApiContext, GeneralRow } from '../src/context.js';
import { appRouter } from '../src/router.js';
const now = new Date('2026-01-01T01:02:00Z');
const general = (overrides: Partial<GeneralRow> = {}): GeneralRow => ({
id: 1,
userId: 'u1',
name: '장수',
nationId: 1,
cityId: 1,
troopId: 0,
npcState: 0,
affinity: null,
bornYear: 180,
deadYear: 300,
picture: null,
imageServer: 0,
leadership: 70,
strength: 60,
intel: 50,
injury: 0,
experience: 900,
dedication: 100,
officerLevel: 1,
gold: 1000,
rice: 2000,
crew: 300,
crewTypeId: 1,
train: 90,
atmos: 90,
weaponCode: 'None',
bookCode: 'None',
horseCode: 'None',
itemCode: 'None',
turnTime: now,
recentWarTime: null,
age: 20,
startAge: 20,
personalCode: 'None',
specialCode: 'None',
special2Code: 'None',
lastTurn: {},
meta: { belong: 1, defence_train: 80, killturn: 7 },
penalty: {},
createdAt: now,
updatedAt: now,
...overrides,
});
const token = (userId: string): GameSessionTokenPayload => ({
version: 1,
profile: 'che:default',
issuedAt: now.toISOString(),
expiresAt: new Date(now.getTime() + 86400000).toISOString(),
sessionId: userId,
user: { id: userId, username: userId, displayName: userId, roles: [] },
sanctions: {},
});
const fixture = (generals: GeneralRow[], userId = 'u1') => {
const db = {
general: {
findFirst: vi.fn(async ({ where }: { where: { userId: string } }) =>
generals.find((g) => g.userId === where.userId)
),
findMany: vi.fn(async ({ where }: { where: { nationId: number } }) =>
generals.filter((g) => g.nationId === where.nationId)
),
},
nation: {
findUnique: vi.fn(async () => ({
id: 1,
name: '위',
color: '#080',
level: 3,
typeCode: 'che_중립',
capitalCityId: 1,
meta: { secretlimit: 3 },
})),
},
city: { findMany: vi.fn(async () => [{ id: 1, name: '업' }]) },
troop: { findMany: vi.fn(async () => [{ troopLeaderId: 2, name: '선봉대' }]) },
worldState: { findFirst: vi.fn(async () => null) },
generalTurn: { findMany: vi.fn(async () => [{ generalId: 1, turnIdx: 0, actionCode: '징병' }]) },
generalAccessLog: {
findMany: vi.fn(async () => generals.map((g) => ({ generalId: g.id, refreshScoreTotal: g.id * 10 }))),
},
};
const redis = { get: vi.fn(async () => null), set: vi.fn(async () => null) } as unknown as RedisConnector['client'];
const context: GameApiContext = {
db: db as unknown as DatabaseClient,
redis,
turnDaemon: {} as GameApiContext['turnDaemon'],
battleSim: {} as GameApiContext['battleSim'],
profile: { id: 'che', scenario: 'default', name: 'che:default' },
auth: token(userId),
uploadDir: 'uploads',
uploadPath: '/uploads',
uploadPublicUrl: null,
accessTokenStore: new RedisAccessTokenStore(redis, 'che:default'),
flushStore: new InMemoryFlushStore(),
gameTokenSecret: 'secret',
};
return { caller: appRouter.createCaller(context), db };
};
describe('nation general and secret office permissions', () => {
it('redacts ordinary-member details and denies the secret office', async () => {
const { caller } = fixture([general()]);
const result = await caller.nation.getGeneralList();
expect(result.viewer).toEqual({ generalId: 1, permission: 0 });
expect(result.generals[0]).toMatchObject({
officerLevel: 1,
cityName: null,
troopName: null,
refreshScoreTotal: 10,
});
expect(result.generals[0]).not.toHaveProperty('crew');
await expect(caller.nation.getSecretGeneralList()).rejects.toMatchObject({ code: 'FORBIDDEN' });
});
it('uses the session-owned general and scopes secret rows to that nation', async () => {
const first = general();
const actor = general({ id: 2, userId: 'u2', officerLevel: 5, meta: { belong: 1 } });
const ally = general({ id: 3, userId: 'u3', gold: 3000, crew: 200, train: 80, atmos: 80 });
const foreign = general({ id: 4, userId: 'u4', nationId: 2, gold: 99999 });
const { caller, db } = fixture([first, actor, ally, foreign], 'u2');
const result = await caller.nation.getSecretGeneralList();
expect(result.viewer).toEqual({ generalId: 2, permission: 2 });
expect(result.generals.map((g) => g.id)).toEqual([1, 2, 3]);
expect(result.summary).toMatchObject({ gold: 5000, crew: 800, generalCount: 3 });
expect(db.general.findFirst).toHaveBeenCalledWith({ where: { userId: 'u2' } });
expect(db.general.findMany).toHaveBeenCalledWith(expect.objectContaining({ where: { nationId: 1 } }));
});
it('honors general penalties after a user switch', async () => {
const penalized = general({ officerLevel: 5, penalty: { noChief: true } });
const { caller } = fixture([penalized]);
await expect(caller.nation.getSecretGeneralList()).rejects.toMatchObject({ code: 'FORBIDDEN' });
});
});