Merge branch 'main' into feature/nation-personnel-finance-parity
# Conflicts: # app/game-frontend/e2e/playwright.config.mjs # app/game-frontend/package.json # docs/frontend-legacy-parity.md
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { loadMapDefinitionByName } from './mapDefinition.js';
|
||||
|
||||
export interface MapLayoutCity {
|
||||
id: number;
|
||||
@@ -30,8 +31,7 @@ const LEGACY_CITY_CONST = path.resolve(process.cwd(), 'legacy/hwe/sammo/CityCons
|
||||
|
||||
const layoutCache = new Map<string, MapLayout>();
|
||||
|
||||
const stripComments = (value: string): string =>
|
||||
value.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, '');
|
||||
const stripComments = (value: string): string => value.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, '');
|
||||
|
||||
const extractPhpArray = (source: string, marker: string): string | null => {
|
||||
const idx = source.indexOf(marker);
|
||||
@@ -196,11 +196,7 @@ const parseCityConstFile = async (filePath: string): Promise<ParsedCityConst> =>
|
||||
|
||||
const resolveScenarioFile = async (scenario: string): Promise<string> => {
|
||||
const normalized = scenario.replace(/\.json$/i, '');
|
||||
const candidates = [
|
||||
`${normalized}.json`,
|
||||
`scenario_${normalized}.json`,
|
||||
'default.json',
|
||||
];
|
||||
const candidates = [`${normalized}.json`, `scenario_${normalized}.json`, 'default.json'];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
const fullPath = path.join(LEGACY_SCENARIO_ROOT, candidate);
|
||||
@@ -272,15 +268,15 @@ const normalizeInitCity = (
|
||||
typeof levelLabel === 'number'
|
||||
? levelLabel
|
||||
: typeof levelLabel === 'string'
|
||||
? levelMap.nameToId[levelLabel] ?? Number(levelLabel)
|
||||
: 0;
|
||||
? (levelMap.nameToId[levelLabel] ?? Number(levelLabel))
|
||||
: 0;
|
||||
|
||||
const regionValue =
|
||||
typeof regionLabel === 'number'
|
||||
? regionLabel
|
||||
: typeof regionLabel === 'string'
|
||||
? regionMap.nameToId[regionLabel] ?? Number(regionLabel)
|
||||
: 0;
|
||||
? (regionMap.nameToId[regionLabel] ?? Number(regionLabel))
|
||||
: 0;
|
||||
|
||||
const pathNames = Array.isArray(path) ? (path as string[]) : [];
|
||||
const pathIds = pathNames
|
||||
@@ -324,7 +320,19 @@ export const loadMapLayout = async (scenario: string): Promise<MapLayout> => {
|
||||
const levelMap = buildLookupMap(levelMapRaw);
|
||||
|
||||
const initCity = map.initCity ?? base.initCity ?? [];
|
||||
const cityList = normalizeInitCity(initCity, levelMap, regionMap);
|
||||
let cityList = normalizeInitCity(initCity, levelMap, regionMap);
|
||||
if (cityList.length === 0) {
|
||||
const resourceMap = await loadMapDefinitionByName(mapName);
|
||||
cityList = resourceMap.cities.map((city) => ({
|
||||
id: city.id,
|
||||
name: city.name,
|
||||
level: city.level,
|
||||
region: city.region,
|
||||
x: city.position.x,
|
||||
y: city.position.y,
|
||||
path: [...city.connections],
|
||||
}));
|
||||
}
|
||||
|
||||
const layout: MapLayout = {
|
||||
mapName,
|
||||
|
||||
@@ -5,31 +5,37 @@ import { promises as fs } from 'fs';
|
||||
import { randomUUID } from 'crypto';
|
||||
import sharp, { type WebpOptions } from 'sharp';
|
||||
|
||||
import { GamePrisma } from '@sammo-ts/infra';
|
||||
|
||||
import { authedProcedure, router } from '../../trpc.js';
|
||||
import { getMyGeneral } from '../shared/general.js';
|
||||
import { resolveSecretPermission } from '../shared/secretPermission.js';
|
||||
|
||||
const MAX_UPLOAD_BYTES = 1024 * 1024;
|
||||
const MAX_LONG_EDGE = 2048;
|
||||
const WEBP_QUALITY = 80;
|
||||
const WEBP_MIN_SAVING_RATIO = 0.97;
|
||||
|
||||
const resolveSecretPermission = (officerLevel: number): number => {
|
||||
if (officerLevel >= 5) return 2;
|
||||
if (officerLevel > 1) return 1;
|
||||
return 0;
|
||||
};
|
||||
|
||||
const assertBoardAccess = (nationId: number, officerLevel: number, isSecret: boolean) => {
|
||||
if (nationId <= 0 || officerLevel <= 0) {
|
||||
const assertBoardAccess = (permission: number, isSecret: boolean) => {
|
||||
if (permission < 0) {
|
||||
throw new TRPCError({ code: 'FORBIDDEN', message: '국가에 소속되어있지 않습니다.' });
|
||||
}
|
||||
if (isSecret && resolveSecretPermission(officerLevel) < 2) {
|
||||
if (isSecret && permission < 2) {
|
||||
throw new TRPCError({ code: 'FORBIDDEN', message: '권한이 부족합니다. 수뇌부가 아닙니다.' });
|
||||
}
|
||||
};
|
||||
|
||||
const getBoardActor = async (ctx: Parameters<typeof getMyGeneral>[0]) => {
|
||||
const general = await getMyGeneral(ctx);
|
||||
const nation =
|
||||
general.nationId > 0
|
||||
? await ctx.db.nation.findUnique({
|
||||
where: { id: general.nationId },
|
||||
select: { meta: true },
|
||||
})
|
||||
: null;
|
||||
const permission = resolveSecretPermission(general, nation?.meta ?? {}, true);
|
||||
return { general, permission };
|
||||
};
|
||||
|
||||
const normalizeUploadPath = (value: string) => {
|
||||
if (!value.startsWith('/')) {
|
||||
return `/${value}`;
|
||||
@@ -92,111 +98,96 @@ const buildAvifBuffer = async (buffer: Buffer, resize: boolean): Promise<Buffer>
|
||||
return pipeline.avif({ quality: 60, effort: 4 }).toBuffer();
|
||||
};
|
||||
|
||||
type BoardPostRow = {
|
||||
id: number;
|
||||
nation_id: number;
|
||||
is_secret: boolean;
|
||||
author_general_id: number;
|
||||
author_name: string;
|
||||
title: string;
|
||||
content_html: string;
|
||||
created_at: Date;
|
||||
};
|
||||
|
||||
type BoardCommentRow = {
|
||||
id: number;
|
||||
post_id: number;
|
||||
author_general_id: number;
|
||||
author_name: string;
|
||||
content_text: string;
|
||||
created_at: Date;
|
||||
};
|
||||
|
||||
export const boardRouter = router({
|
||||
getArticles: authedProcedure
|
||||
.input(z.object({ isSecret: z.boolean() }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
const me = await getMyGeneral(ctx);
|
||||
assertBoardAccess(me.nationId, me.officerLevel, input.isSecret);
|
||||
getAccess: authedProcedure.query(async ({ ctx }) => {
|
||||
const { permission } = await getBoardActor(ctx);
|
||||
return {
|
||||
permission,
|
||||
canMeeting: permission >= 0,
|
||||
canSecret: permission >= 2,
|
||||
};
|
||||
}),
|
||||
getArticles: authedProcedure.input(z.object({ isSecret: z.boolean() })).query(async ({ ctx, input }) => {
|
||||
const { general, permission } = await getBoardActor(ctx);
|
||||
assertBoardAccess(permission, input.isSecret);
|
||||
|
||||
const posts = await ctx.db.$queryRaw<BoardPostRow[]>(GamePrisma.sql`
|
||||
SELECT
|
||||
id,
|
||||
nation_id,
|
||||
is_secret,
|
||||
author_general_id,
|
||||
author_name,
|
||||
title,
|
||||
content_html,
|
||||
created_at
|
||||
FROM board_post
|
||||
WHERE nation_id = ${me.nationId} AND is_secret = ${input.isSecret}
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 100
|
||||
`);
|
||||
const posts = await ctx.db.boardPost.findMany({
|
||||
where: {
|
||||
nationId: general.nationId,
|
||||
isSecret: input.isSecret,
|
||||
},
|
||||
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
||||
take: 100,
|
||||
include: {
|
||||
comments: {
|
||||
orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (posts.length === 0) {
|
||||
return [];
|
||||
}
|
||||
if (posts.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const postIds = posts.map((post) => post.id);
|
||||
const comments = await ctx.db.$queryRaw<BoardCommentRow[]>(GamePrisma.sql`
|
||||
SELECT
|
||||
id,
|
||||
post_id,
|
||||
author_general_id,
|
||||
author_name,
|
||||
content_text,
|
||||
created_at
|
||||
FROM board_comment
|
||||
WHERE post_id IN (${GamePrisma.join(postIds)})
|
||||
ORDER BY created_at ASC
|
||||
`);
|
||||
const authors = await ctx.db.general.findMany({
|
||||
where: {
|
||||
id: {
|
||||
in: [...new Set(posts.map((post) => post.authorGeneralId))],
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
picture: true,
|
||||
imageServer: true,
|
||||
},
|
||||
});
|
||||
const authorMap = new Map(authors.map((author) => [author.id, author]));
|
||||
|
||||
const commentMap = new Map<number, BoardCommentRow[]>();
|
||||
for (const comment of comments) {
|
||||
const list = commentMap.get(comment.post_id) ?? [];
|
||||
list.push(comment);
|
||||
commentMap.set(comment.post_id, list);
|
||||
}
|
||||
|
||||
return posts.map((post) => ({
|
||||
id: post.id,
|
||||
title: post.title,
|
||||
contentHtml: post.content_html,
|
||||
authorName: post.author_name,
|
||||
createdAt: post.created_at.toISOString(),
|
||||
comments: (commentMap.get(post.id) ?? []).map((comment) => ({
|
||||
id: comment.id,
|
||||
authorName: comment.author_name,
|
||||
content: comment.content_text,
|
||||
createdAt: comment.created_at.toISOString(),
|
||||
})),
|
||||
}));
|
||||
}),
|
||||
return posts.map((post) => ({
|
||||
id: post.id,
|
||||
title: post.title,
|
||||
content: post.contentHtml,
|
||||
authorName: post.authorName,
|
||||
authorPicture: authorMap.get(post.authorGeneralId)?.picture ?? null,
|
||||
authorImageServer: authorMap.get(post.authorGeneralId)?.imageServer ?? 0,
|
||||
createdAt: post.createdAt.toISOString(),
|
||||
comments: post.comments.map((comment) => ({
|
||||
id: comment.id,
|
||||
authorName: comment.authorName,
|
||||
content: comment.contentText,
|
||||
createdAt: comment.createdAt.toISOString(),
|
||||
})),
|
||||
}));
|
||||
}),
|
||||
writeArticle: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
isSecret: z.boolean(),
|
||||
title: z.string().trim().max(250),
|
||||
contentHtml: z.string().trim().max(20000),
|
||||
content: z.string().trim().max(20000),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const me = await getMyGeneral(ctx);
|
||||
assertBoardAccess(me.nationId, me.officerLevel, input.isSecret);
|
||||
const { general, permission } = await getBoardActor(ctx);
|
||||
assertBoardAccess(permission, input.isSecret);
|
||||
|
||||
if (!input.title && !input.contentHtml) {
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: '제목 혹은 내용이 필요합니다.' });
|
||||
if (!input.title && !input.content) {
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: '제목과 내용이 둘다 비어있습니다.' });
|
||||
}
|
||||
|
||||
const rows = await ctx.db.$queryRaw<{ id: number }[]>(GamePrisma.sql`
|
||||
INSERT INTO board_post (nation_id, is_secret, author_general_id, author_name, title, content_html)
|
||||
VALUES (${me.nationId}, ${input.isSecret}, ${me.id}, ${me.name}, ${input.title}, ${input.contentHtml})
|
||||
RETURNING id
|
||||
`);
|
||||
const post = await ctx.db.boardPost.create({
|
||||
data: {
|
||||
nationId: general.nationId,
|
||||
isSecret: input.isSecret,
|
||||
authorGeneralId: general.id,
|
||||
authorName: general.name,
|
||||
title: input.title,
|
||||
contentHtml: input.content,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
return { id: rows[0]?.id ?? null };
|
||||
return { id: post.id };
|
||||
}),
|
||||
writeComment: authedProcedure
|
||||
.input(
|
||||
@@ -206,101 +197,99 @@ export const boardRouter = router({
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const me = await getMyGeneral(ctx);
|
||||
const { general, permission } = await getBoardActor(ctx);
|
||||
if (!input.content) {
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: '내용이 필요합니다.' });
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: '내용이 비어있습니다.' });
|
||||
}
|
||||
|
||||
const posts = await ctx.db.$queryRaw<{ id: number; nation_id: number; is_secret: boolean }[]>(
|
||||
GamePrisma.sql`
|
||||
SELECT id, nation_id, is_secret
|
||||
FROM board_post
|
||||
WHERE id = ${input.postId}
|
||||
LIMIT 1
|
||||
`
|
||||
);
|
||||
|
||||
const post = posts[0];
|
||||
const post = await ctx.db.boardPost.findFirst({
|
||||
where: {
|
||||
id: input.postId,
|
||||
nationId: general.nationId,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
isSecret: true,
|
||||
},
|
||||
});
|
||||
if (!post) {
|
||||
throw new TRPCError({ code: 'NOT_FOUND', message: '게시물을 찾을 수 없습니다.' });
|
||||
throw new TRPCError({ code: 'NOT_FOUND', message: '게시물이 없습니다.' });
|
||||
}
|
||||
|
||||
assertBoardAccess(me.nationId, me.officerLevel, post.is_secret);
|
||||
assertBoardAccess(permission, post.isSecret);
|
||||
|
||||
if (post.nation_id !== me.nationId) {
|
||||
throw new TRPCError({ code: 'FORBIDDEN', message: '권한이 부족합니다.' });
|
||||
}
|
||||
const comment = await ctx.db.boardComment.create({
|
||||
data: {
|
||||
postId: post.id,
|
||||
nationId: general.nationId,
|
||||
isSecret: post.isSecret,
|
||||
authorGeneralId: general.id,
|
||||
authorName: general.name,
|
||||
contentText: input.content,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
const rows = await ctx.db.$queryRaw<{ id: number }[]>(GamePrisma.sql`
|
||||
INSERT INTO board_comment (post_id, nation_id, is_secret, author_general_id, author_name, content_text)
|
||||
VALUES (${post.id}, ${me.nationId}, ${post.is_secret}, ${me.id}, ${me.name}, ${input.content})
|
||||
RETURNING id
|
||||
`);
|
||||
|
||||
return { id: rows[0]?.id ?? null };
|
||||
return { id: comment.id };
|
||||
}),
|
||||
uploadImage: authedProcedure
|
||||
.input(z.object({ dataUrl: z.string().min(1) }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const me = await getMyGeneral(ctx);
|
||||
if (me.nationId <= 0 || me.officerLevel <= 0) {
|
||||
throw new TRPCError({ code: 'FORBIDDEN', message: '국가에 소속되어있지 않습니다.' });
|
||||
uploadImage: authedProcedure.input(z.object({ dataUrl: z.string().min(1) })).mutation(async ({ ctx, input }) => {
|
||||
const { permission } = await getBoardActor(ctx);
|
||||
assertBoardAccess(permission, false);
|
||||
|
||||
const buffer = parseDataUrl(input.dataUrl);
|
||||
if (buffer.length > MAX_UPLOAD_BYTES) {
|
||||
throw new TRPCError({ code: 'PAYLOAD_TOO_LARGE', message: '이미지 용량 제한(1MB)을 초과했습니다.' });
|
||||
}
|
||||
|
||||
const metadata = await sharp(buffer, { animated: true }).metadata();
|
||||
if (!metadata.format || !metadata.width || !metadata.height) {
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: '이미지 정보를 확인할 수 없습니다.' });
|
||||
}
|
||||
|
||||
const format = metadata.format;
|
||||
const isAnimated = (metadata.pages ?? 1) > 1;
|
||||
const needsResize = Math.max(metadata.width, metadata.height) > MAX_LONG_EDGE;
|
||||
|
||||
const allowed = new Set(['png', 'jpeg', 'jpg', 'gif', 'webp', 'avif', 'heif', 'tiff', 'bmp']);
|
||||
if (!allowed.has(format)) {
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: '지원하지 않는 이미지 형식입니다.' });
|
||||
}
|
||||
|
||||
let outputBuffer = buffer;
|
||||
let outputFormat = format === 'avif' ? 'avif' : 'webp';
|
||||
|
||||
if (format === 'avif') {
|
||||
if (needsResize) {
|
||||
outputBuffer = await buildAvifBuffer(buffer, true);
|
||||
}
|
||||
|
||||
const buffer = parseDataUrl(input.dataUrl);
|
||||
if (buffer.length > MAX_UPLOAD_BYTES) {
|
||||
throw new TRPCError({ code: 'PAYLOAD_TOO_LARGE', message: '이미지 용량 제한(1MB)을 초과했습니다.' });
|
||||
}
|
||||
|
||||
const metadata = await sharp(buffer, { animated: true }).metadata();
|
||||
if (!metadata.format || !metadata.width || !metadata.height) {
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: '이미지 정보를 확인할 수 없습니다.' });
|
||||
}
|
||||
|
||||
const format = metadata.format;
|
||||
const isAnimated = (metadata.pages ?? 1) > 1;
|
||||
const needsResize = Math.max(metadata.width, metadata.height) > MAX_LONG_EDGE;
|
||||
|
||||
const allowed = new Set(['png', 'jpeg', 'jpg', 'gif', 'webp', 'avif', 'heif', 'tiff', 'bmp']);
|
||||
if (!allowed.has(format)) {
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: '지원하지 않는 이미지 형식입니다.' });
|
||||
}
|
||||
|
||||
let outputBuffer = buffer;
|
||||
let outputFormat = format === 'avif' ? 'avif' : 'webp';
|
||||
|
||||
if (format === 'avif') {
|
||||
if (needsResize) {
|
||||
outputBuffer = await buildAvifBuffer(buffer, true);
|
||||
}
|
||||
} else {
|
||||
const webpBuffer = await buildWebpBuffer(buffer, {
|
||||
animated: isAnimated || format === 'gif',
|
||||
resize: needsResize,
|
||||
});
|
||||
if (format === 'webp' && !needsResize && webpBuffer.length >= buffer.length * WEBP_MIN_SAVING_RATIO) {
|
||||
outputBuffer = buffer;
|
||||
outputFormat = 'webp';
|
||||
} else {
|
||||
const webpBuffer = await buildWebpBuffer(buffer, {
|
||||
animated: isAnimated || format === 'gif',
|
||||
resize: needsResize,
|
||||
});
|
||||
if (format === 'webp' && !needsResize && webpBuffer.length >= buffer.length * WEBP_MIN_SAVING_RATIO) {
|
||||
outputBuffer = buffer;
|
||||
outputFormat = 'webp';
|
||||
} else {
|
||||
outputBuffer = webpBuffer;
|
||||
outputFormat = 'webp';
|
||||
}
|
||||
outputBuffer = webpBuffer;
|
||||
outputFormat = 'webp';
|
||||
}
|
||||
}
|
||||
|
||||
await fs.mkdir(ctx.uploadDir, { recursive: true });
|
||||
const filename = `${randomUUID()}.${outputFormat}`;
|
||||
await fs.writeFile(path.join(ctx.uploadDir, filename), outputBuffer);
|
||||
await fs.mkdir(ctx.uploadDir, { recursive: true });
|
||||
const filename = `${randomUUID()}.${outputFormat}`;
|
||||
await fs.writeFile(path.join(ctx.uploadDir, filename), outputBuffer);
|
||||
|
||||
const outputMeta = await sharp(outputBuffer, { animated: true }).metadata();
|
||||
const url = buildPublicImageUrl(ctx.uploadPublicUrl, ctx.uploadPath, filename);
|
||||
const outputMeta = await sharp(outputBuffer, { animated: true }).metadata();
|
||||
const url = buildPublicImageUrl(ctx.uploadPublicUrl, ctx.uploadPath, filename);
|
||||
|
||||
return {
|
||||
url,
|
||||
width: outputMeta.width ?? metadata.width,
|
||||
height: outputMeta.height ?? metadata.height,
|
||||
format: outputFormat,
|
||||
animated: isAnimated,
|
||||
size: outputBuffer.length,
|
||||
};
|
||||
}),
|
||||
});
|
||||
return {
|
||||
url,
|
||||
width: outputMeta.width ?? metadata.width,
|
||||
height: outputMeta.height ?? metadata.height,
|
||||
format: outputFormat,
|
||||
animated: isAnimated,
|
||||
size: outputBuffer.length,
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
import { TRPCError } from '@trpc/server';
|
||||
|
||||
import { asRecord } from '@sammo-ts/common';
|
||||
import { LogCategory, LogScope } from '@sammo-ts/infra';
|
||||
import { getGoldIncome, getOutcome, getRiceIncome, getWallIncome, getWarGoldIncome } from '@sammo-ts/logic';
|
||||
|
||||
import { authedProcedure } from '../../../trpc.js';
|
||||
import { getMyGeneral } from '../../shared/general.js';
|
||||
import {
|
||||
assertNationAccess,
|
||||
buildNationIncomeContext,
|
||||
resolveNationBill,
|
||||
resolveNationRate,
|
||||
resolveOfficerCity,
|
||||
toIncomeCity,
|
||||
} from '../shared.js';
|
||||
|
||||
export const getNationInfo = authedProcedure.query(async ({ ctx }) => {
|
||||
const me = await getMyGeneral(ctx);
|
||||
assertNationAccess(me);
|
||||
|
||||
const [nation, cities, generals, history] = await Promise.all([
|
||||
ctx.db.nation.findUnique({ where: { id: me.nationId } }),
|
||||
ctx.db.city.findMany({ where: { nationId: me.nationId }, orderBy: { id: 'asc' } }),
|
||||
ctx.db.general.findMany({ where: { nationId: me.nationId } }),
|
||||
ctx.db.logEntry.findMany({
|
||||
where: {
|
||||
scope: LogScope.NATION,
|
||||
category: LogCategory.HISTORY,
|
||||
nationId: me.nationId,
|
||||
},
|
||||
select: { id: true, year: true, month: true, text: true },
|
||||
orderBy: { id: 'asc' },
|
||||
}),
|
||||
]);
|
||||
if (!nation) {
|
||||
throw new TRPCError({ code: 'NOT_FOUND', message: 'Nation not found' });
|
||||
}
|
||||
|
||||
const officerCntByCity = new Map<number, number>();
|
||||
for (const general of generals) {
|
||||
const officerCity = resolveOfficerCity(asRecord(general.meta));
|
||||
if (
|
||||
general.officerLevel >= 2 &&
|
||||
general.officerLevel <= 4 &&
|
||||
officerCity > 0 &&
|
||||
general.cityId === officerCity
|
||||
) {
|
||||
officerCntByCity.set(officerCity, (officerCntByCity.get(officerCity) ?? 0) + 1);
|
||||
}
|
||||
}
|
||||
|
||||
const incomeContext = await buildNationIncomeContext(nation);
|
||||
const incomeCities = cities.map(toIncomeCity);
|
||||
const rate = resolveNationRate(nation);
|
||||
const bill = resolveNationBill(asRecord(nation.meta));
|
||||
const goldCity = getGoldIncome(
|
||||
incomeContext,
|
||||
incomeCities,
|
||||
officerCntByCity,
|
||||
nation.capitalCityId ?? 0,
|
||||
nation.level
|
||||
);
|
||||
const goldWar = getWarGoldIncome(incomeContext, incomeCities);
|
||||
const riceCity = getRiceIncome(
|
||||
incomeContext,
|
||||
incomeCities,
|
||||
officerCntByCity,
|
||||
nation.capitalCityId ?? 0,
|
||||
nation.level
|
||||
);
|
||||
const riceWall = getWallIncome(
|
||||
incomeContext,
|
||||
incomeCities,
|
||||
officerCntByCity,
|
||||
nation.capitalCityId ?? 0,
|
||||
nation.level
|
||||
);
|
||||
const outcome = getOutcome(
|
||||
bill,
|
||||
generals.filter((general) => general.npcState !== 5)
|
||||
);
|
||||
const population = cities.reduce((sum, city) => sum + city.population, 0);
|
||||
const populationMax = cities.reduce((sum, city) => sum + city.populationMax, 0);
|
||||
const crewGenerals = generals.filter((general) => general.npcState !== 5);
|
||||
const crew = crewGenerals.reduce((sum, general) => sum + general.crew, 0);
|
||||
const crewMax = crewGenerals.reduce((sum, general) => sum + general.leadership * 100, 0);
|
||||
const meta = asRecord(nation.meta);
|
||||
|
||||
return {
|
||||
nation: {
|
||||
id: nation.id,
|
||||
name: nation.name,
|
||||
color: nation.color,
|
||||
level: nation.level,
|
||||
power: typeof meta.power === 'number' ? meta.power : 0,
|
||||
gold: nation.gold,
|
||||
rice: nation.rice,
|
||||
tech: Math.floor(nation.tech),
|
||||
rate,
|
||||
bill,
|
||||
capitalCityId: nation.capitalCityId ?? 0,
|
||||
generalCount: generals.length,
|
||||
},
|
||||
population: { current: population, max: populationMax },
|
||||
crew: { current: crew, max: crewMax },
|
||||
income: {
|
||||
goldCity,
|
||||
goldWar,
|
||||
goldTotal: goldCity + goldWar,
|
||||
riceCity,
|
||||
riceWall,
|
||||
riceTotal: riceCity + riceWall,
|
||||
outcome,
|
||||
},
|
||||
budget: {
|
||||
gold: nation.gold + goldCity + goldWar - outcome,
|
||||
rice: nation.rice + riceCity + riceWall - outcome,
|
||||
},
|
||||
cities: cities.map((city) => ({
|
||||
id: city.id,
|
||||
name: city.name,
|
||||
capital: city.id === nation.capitalCityId,
|
||||
})),
|
||||
history,
|
||||
};
|
||||
});
|
||||
@@ -6,6 +6,7 @@ import { getChiefCenter } from './endpoints/getChiefCenter.js';
|
||||
import { getCityOverview } from './endpoints/getCityOverview.js';
|
||||
import { getGeneralList } from './endpoints/getGeneralList.js';
|
||||
import { getGeneralLog } from './endpoints/getGeneralLog.js';
|
||||
import { getNationInfo } from './endpoints/getNationInfo.js';
|
||||
import { getPersonnelInfo } from './endpoints/getPersonnelInfo.js';
|
||||
import { getStratFinan } from './endpoints/getStratFinan.js';
|
||||
import { kick } from './endpoints/kick.js';
|
||||
@@ -18,6 +19,7 @@ import { setScoutMsg } from './endpoints/setScoutMsg.js';
|
||||
import { setSecretLimit } from './endpoints/setSecretLimit.js';
|
||||
|
||||
export const nationRouter = router({
|
||||
getNationInfo,
|
||||
getGeneralList,
|
||||
getCityOverview,
|
||||
getPersonnelInfo,
|
||||
@@ -36,4 +38,3 @@ export const nationRouter = router({
|
||||
kick,
|
||||
appoint,
|
||||
});
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import { asRecord, LiteHashDRBG, RandUtil } from '@sammo-ts/common';
|
||||
import { GamePrisma } from '@sammo-ts/infra';
|
||||
import {
|
||||
ITEM_KEYS,
|
||||
addOccupiedUniqueItemKeys,
|
||||
buildVoteUniqueSeed,
|
||||
countOccupiedUniqueItems,
|
||||
createItemModuleRegistry,
|
||||
@@ -22,7 +23,12 @@ const hasAdminRole = (roles: string[], profileName: string): boolean => {
|
||||
if (roles.includes('superuser') || roles.includes('admin') || roles.includes('admin.superuser')) {
|
||||
return true;
|
||||
}
|
||||
return roles.some((role) => role === 'admin.survey' || role === `admin.survey:${profileName}`);
|
||||
return roles.some(
|
||||
(role) =>
|
||||
role === 'admin.survey.open' ||
|
||||
role === 'admin.survey.open:*' ||
|
||||
role === `admin.survey.open:${profileName}`
|
||||
);
|
||||
};
|
||||
|
||||
const adminProcedure = authedProcedure.use(({ ctx, next }) => {
|
||||
@@ -66,9 +72,7 @@ const normalizeCode = (value: string | null | undefined): string | null => {
|
||||
};
|
||||
|
||||
const normalizeOptions = (options: string[]): string[] =>
|
||||
options
|
||||
.map((option) => option.trim())
|
||||
.filter((option) => option.length > 0);
|
||||
options.map((option) => option.trim()).filter((option) => option.length > 0);
|
||||
|
||||
const readMetaNumber = (meta: Record<string, unknown>, key: string, fallback: number): number => {
|
||||
const value = meta[key];
|
||||
@@ -225,9 +229,7 @@ export const voteRouter = router({
|
||||
const pollEnded = Boolean(row.closed_at) || (row.end_at ? row.end_at <= new Date() : false);
|
||||
|
||||
const userId = ctx.auth?.user.id;
|
||||
const general = userId
|
||||
? await ctx.db.general.findFirst({ where: { userId }, select: { id: true } })
|
||||
: null;
|
||||
const general = userId ? await ctx.db.general.findFirst({ where: { userId }, select: { id: true } }) : null;
|
||||
|
||||
const [comments, userCnt, myVoteRow] = await Promise.all([
|
||||
ctx.db.$queryRaw<VoteCommentRow[]>(GamePrisma.sql`
|
||||
@@ -257,9 +259,8 @@ export const voteRouter = router({
|
||||
|
||||
const myVote = myVoteRow[0]?.selection ? parseSelection(myVoteRow[0].selection) : null;
|
||||
|
||||
const canReveal = row.reveal_mode === 'after_vote'
|
||||
? Boolean(myVote) || pollEnded
|
||||
: pollEnded;
|
||||
// 레거시는 투표 전에도 현재 집계를 보여준다. after_end만 명시적으로 숨긴다.
|
||||
const canReveal = row.reveal_mode === 'after_end' ? pollEnded : true;
|
||||
|
||||
const voteResults = canReveal
|
||||
? await ctx.db.$queryRaw<VoteResultRow[]>(GamePrisma.sql`
|
||||
@@ -355,6 +356,9 @@ export const voteRouter = router({
|
||||
}
|
||||
|
||||
const sortedSelection = [...selection].sort((a, b) => a - b);
|
||||
if (new Set(sortedSelection).size !== sortedSelection.length) {
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: '선택한 항목이 올바르지 않습니다.' });
|
||||
}
|
||||
const general = await getMyGeneral(ctx);
|
||||
|
||||
const rows = await ctx.db.$queryRaw<Array<{ id: number }>>(GamePrisma.sql`
|
||||
@@ -394,14 +398,24 @@ export const voteRouter = router({
|
||||
const itemRegistry = await getItemRegistry();
|
||||
const uniqueConfig = resolveUniqueConfig(constValues);
|
||||
|
||||
const generalRows = await ctx.db.general.findMany({
|
||||
select: {
|
||||
horseCode: true,
|
||||
weaponCode: true,
|
||||
bookCode: true,
|
||||
itemCode: true,
|
||||
},
|
||||
});
|
||||
const [generalRows, reservedUniqueRows] = await Promise.all([
|
||||
ctx.db.general.findMany({
|
||||
select: {
|
||||
horseCode: true,
|
||||
weaponCode: true,
|
||||
bookCode: true,
|
||||
itemCode: true,
|
||||
},
|
||||
}),
|
||||
ctx.db.auction.findMany({
|
||||
where: {
|
||||
type: 'UNIQUE_ITEM',
|
||||
status: { in: ['OPEN', 'FINALIZING'] },
|
||||
targetCode: { not: null },
|
||||
},
|
||||
select: { targetCode: true },
|
||||
}),
|
||||
]);
|
||||
const generalItems: GeneralItemSlots[] = generalRows.map((row) => ({
|
||||
horse: normalizeCode(row.horseCode),
|
||||
weapon: normalizeCode(row.weaponCode),
|
||||
@@ -410,6 +424,11 @@ export const voteRouter = router({
|
||||
}));
|
||||
|
||||
const occupiedUniqueCounts = countOccupiedUniqueItems(generalItems, itemRegistry);
|
||||
addOccupiedUniqueItemKeys(
|
||||
occupiedUniqueCounts,
|
||||
reservedUniqueRows.map((row) => row.targetCode),
|
||||
itemRegistry
|
||||
);
|
||||
const userCount = await ctx.db.general.count({ where: { npcState: { lt: 2 } } });
|
||||
|
||||
const rngSeed = buildVoteUniqueSeed(
|
||||
|
||||
@@ -1,15 +1,37 @@
|
||||
import { TRPCError } from '@trpc/server';
|
||||
import { z } from 'zod';
|
||||
|
||||
import {
|
||||
type WorldStateRow,
|
||||
zWorldStateConfig,
|
||||
zWorldStateMeta,
|
||||
} from '../../context.js';
|
||||
import { type WorldStateRow, zWorldStateConfig, zWorldStateMeta } from '../../context.js';
|
||||
import { procedure, router } from '../../trpc.js';
|
||||
import { authedProcedure } from '../../trpc.js';
|
||||
import { asRecord, isRecord } from '@sammo-ts/common';
|
||||
import { loadWorldMap } from '../../maps/worldMap.js';
|
||||
import { loadMapLayout } from '../../maps/mapLayout.js';
|
||||
import { getOwnedGeneral } from '../shared/general.js';
|
||||
import { getMyGeneral, getOwnedGeneral } from '../shared/general.js';
|
||||
|
||||
const isWorldAdmin = (roles: readonly string[]): boolean =>
|
||||
roles.some((role) => role === 'superuser' || role === 'admin' || role === 'admin.superuser');
|
||||
|
||||
const numberRecord = (value: unknown): Record<number, number> => {
|
||||
if (!isRecord(value)) return {};
|
||||
return Object.fromEntries(
|
||||
Object.entries(value)
|
||||
.map(([key, item]) => [Number(key), typeof item === 'number' ? item : Number.NaN] as const)
|
||||
.filter(([key, item]) => Number.isFinite(key) && Number.isFinite(item))
|
||||
);
|
||||
};
|
||||
|
||||
const officerCity = (meta: unknown): number => {
|
||||
const value = asRecord(meta);
|
||||
const raw = value.officerCity ?? value.officer_city;
|
||||
return typeof raw === 'number' && Number.isFinite(raw) ? raw : 0;
|
||||
};
|
||||
|
||||
const defenceTrain = (meta: unknown): number => {
|
||||
const value = asRecord(meta);
|
||||
const raw = value.defenceTrain ?? value.defence_train;
|
||||
return typeof raw === 'number' && Number.isFinite(raw) ? raw : 0;
|
||||
};
|
||||
|
||||
const toWorldStateSnapshot = (row: WorldStateRow) => ({
|
||||
scenarioCode: row.scenarioCode,
|
||||
@@ -22,6 +44,183 @@ const toWorldStateSnapshot = (row: WorldStateRow) => ({
|
||||
});
|
||||
|
||||
export const worldRouter = router({
|
||||
getGlobalInfo: authedProcedure.query(async ({ ctx }) => {
|
||||
const me = await getMyGeneral(ctx);
|
||||
const [nations, cities, diplomacy, map] = await Promise.all([
|
||||
ctx.db.nation.findMany({ where: { level: { gt: 0 } } }),
|
||||
ctx.db.city.findMany({ orderBy: { id: 'asc' } }),
|
||||
ctx.db.diplomacy.findMany({ where: { isDead: false, isShowing: true } }),
|
||||
loadWorldMap(ctx, { generalId: me.id, neutralView: false, showMe: true }),
|
||||
]);
|
||||
if (!map) {
|
||||
throw new TRPCError({ code: 'PRECONDITION_FAILED', message: 'World state is not initialized.' });
|
||||
}
|
||||
const nationRows = nations
|
||||
.map((nation) => ({
|
||||
id: nation.id,
|
||||
name: nation.name,
|
||||
color: nation.color,
|
||||
capitalCityId: nation.capitalCityId ?? 0,
|
||||
level: nation.level,
|
||||
power: typeof asRecord(nation.meta).power === 'number' ? Number(asRecord(nation.meta).power) : 0,
|
||||
cities: cities.filter((city) => city.nationId === nation.id).map((city) => city.name),
|
||||
}))
|
||||
.sort((left, right) => right.power - left.power || left.id - right.id);
|
||||
const matrix: Record<number, Record<number, number>> = {};
|
||||
for (const nation of nationRows) {
|
||||
matrix[nation.id] = {};
|
||||
for (const other of nationRows) matrix[nation.id]![other.id] = 2;
|
||||
}
|
||||
for (const relation of diplomacy) {
|
||||
if (!matrix[relation.srcNationId]) continue;
|
||||
const related = relation.srcNationId === me.nationId || relation.destNationId === me.nationId;
|
||||
matrix[relation.srcNationId]![relation.destNationId] = related
|
||||
? relation.stateCode
|
||||
: [3, 4, 5, 6, 7].includes(relation.stateCode)
|
||||
? 2
|
||||
: relation.stateCode;
|
||||
}
|
||||
const conflict = cities.flatMap((city) => {
|
||||
const raw = numberRecord(city.conflict);
|
||||
const entries = Object.entries(raw);
|
||||
if (entries.length < 2) return [];
|
||||
const sum = entries.reduce((total, [, value]) => total + value, 0);
|
||||
if (sum <= 0) return [];
|
||||
return [
|
||||
{
|
||||
cityId: city.id,
|
||||
cityName: city.name,
|
||||
nations: Object.fromEntries(
|
||||
entries.map(([id, value]) => [id, Math.round((value * 1000) / sum) / 10])
|
||||
),
|
||||
},
|
||||
];
|
||||
});
|
||||
return { myNationId: me.nationId, nations: nationRows, diplomacy: matrix, conflict, map };
|
||||
}),
|
||||
getCurrentCity: authedProcedure
|
||||
.input(z.object({ cityId: z.number().int().positive().optional() }).optional())
|
||||
.query(async ({ ctx, input }) => {
|
||||
const me = await getMyGeneral(ctx);
|
||||
const admin = isWorldAdmin(ctx.auth?.user.roles ?? []);
|
||||
const [cities, nation, nationGenerals, nations, world, layout] = await Promise.all([
|
||||
ctx.db.city.findMany({ orderBy: { id: 'asc' } }),
|
||||
me.nationId > 0 ? ctx.db.nation.findUnique({ where: { id: me.nationId } }) : null,
|
||||
me.nationId > 0
|
||||
? ctx.db.general.findMany({ where: { nationId: me.nationId }, select: { cityId: true } })
|
||||
: [],
|
||||
ctx.db.nation.findMany(),
|
||||
ctx.db.worldState.findFirst(),
|
||||
loadMapLayout(ctx.profile.scenario),
|
||||
]);
|
||||
const cityById = new Map(cities.map((city) => [city.id, city]));
|
||||
const requested = input?.cityId && cityById.has(input.cityId) ? input.cityId : me.cityId;
|
||||
const selected = cityById.get(requested);
|
||||
if (!selected) throw new TRPCError({ code: 'NOT_FOUND', message: 'City not found' });
|
||||
const spy = numberRecord(asRecord(nation?.meta).spyList ?? asRecord(nation?.meta).spy);
|
||||
const selectable = new Set<number>([me.cityId]);
|
||||
if (me.officerLevel > 0 && me.nationId > 0) {
|
||||
cities.filter((city) => city.nationId === me.nationId).forEach((city) => selectable.add(city.id));
|
||||
nationGenerals.forEach((general) => selectable.add(general.cityId));
|
||||
Object.keys(spy).forEach((id) => selectable.add(Number(id)));
|
||||
}
|
||||
if (admin) cities.forEach((city) => selectable.add(city.id));
|
||||
const full = admin || selectable.has(selected.id);
|
||||
const ownCities = new Set(
|
||||
cities.filter((city) => city.nationId === me.nationId && me.nationId > 0).map((city) => city.id)
|
||||
);
|
||||
const layoutCity = layout.cityList.find((city) => city.id === selected.id);
|
||||
const detailed = full || Boolean(layoutCity?.path.some((id) => ownCities.has(id)));
|
||||
const generals = detailed
|
||||
? await ctx.db.general.findMany({ where: { cityId: selected.id }, orderBy: { turnTime: 'asc' } })
|
||||
: [];
|
||||
const generalIds = generals
|
||||
.filter((general) => general.nationId === me.nationId && general.npcState <= 1)
|
||||
.map((general) => general.id);
|
||||
const turns = generalIds.length
|
||||
? await ctx.db.generalTurn.findMany({
|
||||
where: { generalId: { in: generalIds }, turnIdx: { lt: 5 } },
|
||||
orderBy: [{ generalId: 'asc' }, { turnIdx: 'asc' }],
|
||||
})
|
||||
: [];
|
||||
const turnMap = new Map<number, string[]>();
|
||||
for (const turn of turns) {
|
||||
const list = turnMap.get(turn.generalId) ?? [];
|
||||
list[turn.turnIdx] = turn.actionCode;
|
||||
turnMap.set(turn.generalId, list);
|
||||
}
|
||||
const nationMap = new Map(nations.map((item) => [item.id, item]));
|
||||
const officers = await ctx.db.general.findMany({
|
||||
where: { officerLevel: { in: [2, 3, 4] } },
|
||||
select: { name: true, officerLevel: true, meta: true },
|
||||
});
|
||||
const selectedOfficers = Object.fromEntries(
|
||||
officers
|
||||
.filter((item) => officerCity(item.meta) === selected.id)
|
||||
.map((item) => [item.officerLevel, item.name])
|
||||
);
|
||||
const redact = <T>(value: T): T | null => (full ? value : null);
|
||||
const mappedGenerals = generals.map((general) => {
|
||||
const ours = admin || (me.nationId > 0 && general.nationId === me.nationId);
|
||||
return {
|
||||
id: general.id,
|
||||
name: general.name,
|
||||
npcState: general.npcState,
|
||||
picture: general.picture,
|
||||
imageServer: general.imageServer,
|
||||
nationId: general.nationId,
|
||||
nationName: nationMap.get(general.nationId)?.name ?? '재야',
|
||||
leadership: general.leadership,
|
||||
strength: general.strength,
|
||||
intelligence: general.intel,
|
||||
injury: general.injury,
|
||||
officerLevel: general.officerLevel,
|
||||
defenceTrain: ours ? defenceTrain(general.meta) : null,
|
||||
crewTypeId: ours ? general.crewTypeId : null,
|
||||
crew: ours || full ? general.crew : null,
|
||||
train: ours ? general.train : null,
|
||||
atmos: ours ? general.atmos : null,
|
||||
turns: ours && general.npcState <= 1 ? (turnMap.get(general.id) ?? []) : [],
|
||||
};
|
||||
});
|
||||
return {
|
||||
me: { id: me.id, nationId: me.nationId, officerLevel: me.officerLevel, admin },
|
||||
options: [...selectable]
|
||||
.map((id) => cityById.get(id))
|
||||
.filter((city): city is NonNullable<typeof city> => Boolean(city))
|
||||
.map((city) => ({ id: city.id, name: city.name, nationId: city.nationId })),
|
||||
visibility: { full, detailed },
|
||||
city: {
|
||||
id: selected.id,
|
||||
name: selected.name,
|
||||
nationId: selected.nationId,
|
||||
level: selected.level,
|
||||
region: selected.region,
|
||||
population: redact(selected.population),
|
||||
populationMax: selected.populationMax,
|
||||
agriculture: redact(selected.agriculture),
|
||||
agricultureMax: selected.agricultureMax,
|
||||
commerce: redact(selected.commerce),
|
||||
commerceMax: selected.commerceMax,
|
||||
security: redact(selected.security),
|
||||
securityMax: selected.securityMax,
|
||||
trust: redact(selected.trust),
|
||||
trade: selected.trade,
|
||||
defence: full || selected.nationId === 0 ? selected.defence : null,
|
||||
defenceMax: selected.defenceMax,
|
||||
wall: full || selected.nationId === 0 ? selected.wall : null,
|
||||
wallMax: selected.wallMax,
|
||||
officers: {
|
||||
4: selectedOfficers[4] ?? '-',
|
||||
3: selectedOfficers[3] ?? '-',
|
||||
2: selectedOfficers[2] ?? '-',
|
||||
},
|
||||
},
|
||||
generals: mappedGenerals,
|
||||
lastExecute:
|
||||
typeof asRecord(world?.meta).turntime === 'string' ? String(asRecord(world?.meta).turntime) : '',
|
||||
};
|
||||
}),
|
||||
getState: procedure.query(async ({ ctx }) => {
|
||||
const state = await ctx.db.worldState.findFirst();
|
||||
return state ? toWorldStateSnapshot(state) : null;
|
||||
|
||||
@@ -0,0 +1,301 @@
|
||||
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 buildGeneral = (overrides: Partial<GeneralRow> = {}): GeneralRow => ({
|
||||
id: 1,
|
||||
userId: 'user-1',
|
||||
name: '테스트장수',
|
||||
nationId: 1,
|
||||
cityId: 1,
|
||||
troopId: 0,
|
||||
npcState: 0,
|
||||
affinity: null,
|
||||
bornYear: 180,
|
||||
deadYear: 300,
|
||||
picture: '22.jpg',
|
||||
imageServer: 0,
|
||||
leadership: 50,
|
||||
strength: 50,
|
||||
intel: 50,
|
||||
injury: 0,
|
||||
experience: 0,
|
||||
dedication: 0,
|
||||
officerLevel: 1,
|
||||
gold: 1000,
|
||||
rice: 1000,
|
||||
crew: 0,
|
||||
crewTypeId: 0,
|
||||
train: 0,
|
||||
atmos: 0,
|
||||
weaponCode: 'None',
|
||||
bookCode: 'None',
|
||||
horseCode: 'None',
|
||||
itemCode: 'None',
|
||||
turnTime: new Date('2026-01-01T00:00:00Z'),
|
||||
recentWarTime: null,
|
||||
age: 20,
|
||||
startAge: 20,
|
||||
personalCode: 'None',
|
||||
specialCode: 'None',
|
||||
special2Code: 'None',
|
||||
lastTurn: {},
|
||||
meta: {},
|
||||
penalty: {},
|
||||
createdAt: new Date('2026-01-01T00:00:00Z'),
|
||||
updatedAt: new Date('2026-01-01T00:00:00Z'),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const auth: GameSessionTokenPayload = {
|
||||
version: 1,
|
||||
profile: 'che:default',
|
||||
issuedAt: '2026-01-01T00:00:00.000Z',
|
||||
expiresAt: '2026-01-02T00:00:00.000Z',
|
||||
sessionId: 'session-1',
|
||||
user: {
|
||||
id: 'user-1',
|
||||
username: 'tester',
|
||||
displayName: 'Tester',
|
||||
roles: [],
|
||||
},
|
||||
sanctions: {},
|
||||
};
|
||||
|
||||
const buildContext = (options: {
|
||||
me?: GeneralRow;
|
||||
nationMeta?: Record<string, unknown>;
|
||||
auth?: GameSessionTokenPayload | null;
|
||||
posts?: Array<{
|
||||
id: number;
|
||||
nationId: number;
|
||||
isSecret: boolean;
|
||||
authorGeneralId: number;
|
||||
authorName: string;
|
||||
title: string;
|
||||
contentHtml: string;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
comments: Array<{
|
||||
id: number;
|
||||
postId: number;
|
||||
nationId: number;
|
||||
isSecret: boolean;
|
||||
authorGeneralId: number;
|
||||
authorName: string;
|
||||
contentText: string;
|
||||
createdAt: Date;
|
||||
}>;
|
||||
}>;
|
||||
targetPost?: { id: number; isSecret: boolean } | null;
|
||||
}) => {
|
||||
const me = options.me ?? buildGeneral();
|
||||
const boardPostFindMany = vi.fn(async () => options.posts ?? []);
|
||||
const boardPostFindFirst = vi.fn(async () => options.targetPost ?? null);
|
||||
const boardPostCreate = vi.fn(async () => ({ id: 31 }));
|
||||
const boardCommentCreate = vi.fn(async () => ({ id: 41 }));
|
||||
const db = {
|
||||
general: {
|
||||
findFirst: vi.fn(async ({ where }: { where: { userId: string } }) =>
|
||||
me.userId === where.userId ? me : null
|
||||
),
|
||||
findMany: vi.fn(async () => [{ id: me.id, picture: me.picture, imageServer: me.imageServer }]),
|
||||
},
|
||||
nation: {
|
||||
findUnique: vi.fn(async ({ where }: { where: { id: number } }) =>
|
||||
where.id === me.nationId ? { meta: options.nationMeta ?? {} } : null
|
||||
),
|
||||
},
|
||||
boardPost: {
|
||||
findMany: boardPostFindMany,
|
||||
findFirst: boardPostFindFirst,
|
||||
create: boardPostCreate,
|
||||
},
|
||||
boardComment: {
|
||||
create: boardCommentCreate,
|
||||
},
|
||||
};
|
||||
const accessTokenStore = new RedisAccessTokenStore(
|
||||
{
|
||||
get: async () => null,
|
||||
set: async () => null,
|
||||
},
|
||||
'che:default'
|
||||
);
|
||||
const context: GameApiContext = {
|
||||
db: db as unknown as DatabaseClient,
|
||||
redis: {} as RedisConnector['client'],
|
||||
turnDaemon: {} as GameApiContext['turnDaemon'],
|
||||
battleSim: {} as GameApiContext['battleSim'],
|
||||
profile: { id: 'che', scenario: 'default', name: 'che:default' },
|
||||
auth: options.auth === undefined ? auth : options.auth,
|
||||
uploadDir: 'uploads',
|
||||
uploadPath: '/uploads',
|
||||
uploadPublicUrl: null,
|
||||
accessTokenStore,
|
||||
flushStore: new InMemoryFlushStore(),
|
||||
gameTokenSecret: 'test-secret',
|
||||
};
|
||||
return {
|
||||
context,
|
||||
boardPostFindMany,
|
||||
boardPostFindFirst,
|
||||
boardPostCreate,
|
||||
boardCommentCreate,
|
||||
};
|
||||
};
|
||||
|
||||
describe('board router actor, nation, and secret permissions', () => {
|
||||
it.each([
|
||||
{
|
||||
label: 'ordinary member',
|
||||
me: buildGeneral({ officerLevel: 1 }),
|
||||
nationMeta: {},
|
||||
expected: { permission: 0, canMeeting: true, canSecret: false },
|
||||
},
|
||||
{
|
||||
label: 'chief',
|
||||
me: buildGeneral({ officerLevel: 5 }),
|
||||
nationMeta: {},
|
||||
expected: { permission: 2, canMeeting: true, canSecret: true },
|
||||
},
|
||||
{
|
||||
label: 'low-rank ambassador',
|
||||
me: buildGeneral({ officerLevel: 1, meta: { permission: 'ambassador' } }),
|
||||
nationMeta: {},
|
||||
expected: { permission: 4, canMeeting: true, canSecret: true },
|
||||
},
|
||||
{
|
||||
label: 'auditor',
|
||||
me: buildGeneral({ officerLevel: 1, meta: { permission: 'auditor' } }),
|
||||
nationMeta: {},
|
||||
expected: { permission: 3, canMeeting: true, canSecret: true },
|
||||
},
|
||||
{
|
||||
label: 'penalized chief',
|
||||
me: buildGeneral({ officerLevel: 5, penalty: { noChief: true } }),
|
||||
nationMeta: {},
|
||||
expected: { permission: 0, canMeeting: true, canSecret: false },
|
||||
},
|
||||
{
|
||||
label: 'unaffiliated general',
|
||||
me: buildGeneral({ nationId: 0, officerLevel: 0 }),
|
||||
nationMeta: {},
|
||||
expected: { permission: -1, canMeeting: false, canSecret: false },
|
||||
},
|
||||
])('reports legacy-compatible access for $label', async ({ me, nationMeta, expected }) => {
|
||||
const fixture = buildContext({ me, nationMeta });
|
||||
await expect(appRouter.createCaller(fixture.context).board.getAccess()).resolves.toEqual(expected);
|
||||
});
|
||||
|
||||
it('derives the article actor from the authenticated user and scopes the list to their nation', async () => {
|
||||
const createdAt = new Date('2026-07-26T10:20:00Z');
|
||||
const fixture = buildContext({
|
||||
me: buildGeneral({ id: 7, userId: 'user-1', nationId: 3, officerLevel: 5 }),
|
||||
posts: [
|
||||
{
|
||||
id: 11,
|
||||
nationId: 3,
|
||||
isSecret: true,
|
||||
authorGeneralId: 7,
|
||||
authorName: '작성자',
|
||||
title: '작전',
|
||||
contentHtml: '내용',
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
comments: [],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await expect(
|
||||
appRouter.createCaller(fixture.context).board.getArticles({ isSecret: true })
|
||||
).resolves.toMatchObject([
|
||||
{
|
||||
id: 11,
|
||||
title: '작전',
|
||||
content: '내용',
|
||||
authorName: '작성자',
|
||||
authorPicture: '22.jpg',
|
||||
authorImageServer: 0,
|
||||
},
|
||||
]);
|
||||
expect(fixture.boardPostFindMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: { nationId: 3, isSecret: true },
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('uses the session actor for writes and keeps empty-input wording compatible', async () => {
|
||||
const fixture = buildContext({
|
||||
me: buildGeneral({ id: 7, userId: 'user-1', nationId: 3, officerLevel: 1 }),
|
||||
});
|
||||
const caller = appRouter.createCaller(fixture.context);
|
||||
|
||||
await expect(caller.board.writeArticle({ isSecret: false, title: '', content: '' })).rejects.toMatchObject({
|
||||
code: 'BAD_REQUEST',
|
||||
message: '제목과 내용이 둘다 비어있습니다.',
|
||||
});
|
||||
|
||||
await expect(caller.board.writeArticle({ isSecret: false, title: '알림', content: '내용' })).resolves.toEqual({
|
||||
id: 31,
|
||||
});
|
||||
expect(fixture.boardPostCreate).toHaveBeenCalledWith({
|
||||
data: {
|
||||
nationId: 3,
|
||||
isSecret: false,
|
||||
authorGeneralId: 7,
|
||||
authorName: '테스트장수',
|
||||
title: '알림',
|
||||
contentHtml: '내용',
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
});
|
||||
|
||||
it('does not reveal whether another nation owns a requested comment target', async () => {
|
||||
const fixture = buildContext({
|
||||
me: buildGeneral({ nationId: 3, officerLevel: 5 }),
|
||||
targetPost: null,
|
||||
});
|
||||
await expect(
|
||||
appRouter.createCaller(fixture.context).board.writeComment({ postId: 99, content: '답변' })
|
||||
).rejects.toMatchObject({
|
||||
code: 'NOT_FOUND',
|
||||
message: '게시물이 없습니다.',
|
||||
});
|
||||
expect(fixture.boardPostFindFirst).toHaveBeenCalledWith({
|
||||
where: { id: 99, nationId: 3 },
|
||||
select: { id: true, isSecret: true },
|
||||
});
|
||||
expect(fixture.boardCommentCreate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('checks secret permission again when adding a comment', async () => {
|
||||
const fixture = buildContext({
|
||||
me: buildGeneral({ officerLevel: 2 }),
|
||||
targetPost: { id: 5, isSecret: true },
|
||||
});
|
||||
await expect(
|
||||
appRouter.createCaller(fixture.context).board.writeComment({ postId: 5, content: '답변' })
|
||||
).rejects.toMatchObject({
|
||||
code: 'FORBIDDEN',
|
||||
message: '권한이 부족합니다. 수뇌부가 아닙니다.',
|
||||
});
|
||||
expect(fixture.boardCommentCreate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects unauthenticated board access', async () => {
|
||||
const fixture = buildContext({ auth: null });
|
||||
await expect(appRouter.createCaller(fixture.context).board.getAccess()).rejects.toMatchObject({
|
||||
code: 'UNAUTHORIZED',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,185 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import type { GameSessionTokenPayload } from '@sammo-ts/common/auth/gameToken';
|
||||
import type { RedisConnector } from '@sammo-ts/infra';
|
||||
|
||||
import { InMemoryFlushStore } from '../src/auth/flushStore.js';
|
||||
import { RedisAccessTokenStore } from '../src/auth/accessTokenStore.js';
|
||||
import type { DatabaseClient, GameApiContext, GeneralRow } from '../src/context.js';
|
||||
import { appRouter } from '../src/router.js';
|
||||
|
||||
const now = new Date('2026-01-01T00:00:00Z');
|
||||
const general = (overrides: Partial<GeneralRow> = {}): GeneralRow => ({
|
||||
id: 1,
|
||||
userId: 'user-1',
|
||||
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: 0,
|
||||
dedication: 0,
|
||||
officerLevel: 1,
|
||||
gold: 1000,
|
||||
rice: 1000,
|
||||
crew: 500,
|
||||
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: { defence_train: 80 },
|
||||
penalty: {},
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
...overrides,
|
||||
});
|
||||
const auth = (roles: string[] = []): GameSessionTokenPayload => ({
|
||||
version: 1,
|
||||
profile: 'che:default',
|
||||
issuedAt: now.toISOString(),
|
||||
expiresAt: new Date(now.getTime() + 86400000).toISOString(),
|
||||
sessionId: 'session',
|
||||
user: { id: 'user-1', username: 'tester', displayName: 'Tester', roles },
|
||||
sanctions: {},
|
||||
});
|
||||
const city = (id: number, nationId: number) => ({
|
||||
id,
|
||||
name: `도시${id}`,
|
||||
level: 6,
|
||||
nationId,
|
||||
supplyState: 1,
|
||||
frontState: 0,
|
||||
population: 1000,
|
||||
populationMax: 2000,
|
||||
agriculture: 10,
|
||||
agricultureMax: 20,
|
||||
commerce: 11,
|
||||
commerceMax: 21,
|
||||
security: 12,
|
||||
securityMax: 22,
|
||||
trust: 50,
|
||||
trade: 100,
|
||||
defence: 13,
|
||||
defenceMax: 23,
|
||||
wall: 14,
|
||||
wallMax: 24,
|
||||
region: 2,
|
||||
conflict: {},
|
||||
meta: {},
|
||||
});
|
||||
|
||||
const context = (options: { me?: GeneralRow; roles?: string[]; nationMeta?: Record<string, unknown> } = {}) => {
|
||||
const me = options.me ?? general();
|
||||
const cities = [city(1, 1), city(2, 2), city(3, 2), city(80, 1)];
|
||||
const foreign = general({ id: 2, userId: 'user-2', name: '적군', nationId: 2, cityId: 2, crew: 777 });
|
||||
const db = {
|
||||
general: {
|
||||
findFirst: vi.fn(async () => me),
|
||||
findMany: vi.fn(async (args: { where?: Record<string, unknown>; select?: Record<string, boolean> }) => {
|
||||
if (args.where?.nationId === 1 && args.select?.cityId) return [{ cityId: me.cityId }];
|
||||
if (args.where?.cityId === 2) return [foreign];
|
||||
if (args.where?.cityId === 3) return [foreign];
|
||||
if (args.where?.officerLevel) return [];
|
||||
return [];
|
||||
}),
|
||||
},
|
||||
nation: {
|
||||
findUnique: vi.fn(async () => ({
|
||||
id: 1,
|
||||
name: '아국',
|
||||
color: '#008000',
|
||||
level: 1,
|
||||
capitalCityId: 1,
|
||||
meta: options.nationMeta ?? {},
|
||||
})),
|
||||
findMany: vi.fn(async () => [
|
||||
{ id: 1, name: '아국', color: '#008000', level: 1, capitalCityId: 1, meta: { power: 100 } },
|
||||
{ id: 2, name: '적국', color: '#800000', level: 1, capitalCityId: 2, meta: { power: 90 } },
|
||||
]),
|
||||
},
|
||||
city: { findMany: vi.fn(async () => cities) },
|
||||
worldState: { findFirst: vi.fn(async () => ({ meta: { turntime: '2026-01-01' } })) },
|
||||
generalTurn: { findMany: vi.fn(async () => []) },
|
||||
diplomacy: { findMany: vi.fn(async () => []) },
|
||||
};
|
||||
const redis = { get: vi.fn(async () => null), set: vi.fn(async () => null) } as unknown as RedisConnector['client'];
|
||||
const accessTokenStore = new RedisAccessTokenStore(redis, 'che:default');
|
||||
return {
|
||||
db: db as unknown as DatabaseClient,
|
||||
redis,
|
||||
turnDaemon: {} as GameApiContext['turnDaemon'],
|
||||
battleSim: {} as GameApiContext['battleSim'],
|
||||
profile: { id: 'che', scenario: 'default', name: 'che:default' },
|
||||
auth: auth(options.roles),
|
||||
uploadDir: 'uploads',
|
||||
uploadPath: '/uploads',
|
||||
uploadPublicUrl: null,
|
||||
accessTokenStore,
|
||||
flushStore: new InMemoryFlushStore(),
|
||||
gameTokenSecret: 'secret',
|
||||
} satisfies GameApiContext;
|
||||
};
|
||||
|
||||
describe('in-game information permissions', () => {
|
||||
it('does not expose nation-only pages to a wandering general', async () => {
|
||||
const caller = appRouter.createCaller(context({ me: general({ nationId: 0, officerLevel: 0 }) }));
|
||||
await expect(caller.nation.getNationInfo()).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
|
||||
await expect(caller.nation.getCityOverview()).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
|
||||
});
|
||||
|
||||
it('lets a wandering general select only the current city', async () => {
|
||||
const caller = appRouter.createCaller(context({ me: general({ nationId: 0, officerLevel: 0 }) }));
|
||||
const result = await caller.world.getCurrentCity({ cityId: 2 });
|
||||
expect(result.city.id).toBe(2);
|
||||
expect(result.options.map((entry) => entry.id)).toEqual([1]);
|
||||
expect(result.visibility.full).toBe(false);
|
||||
expect(result.city.population).toBeNull();
|
||||
expect(result.generals).toEqual([]);
|
||||
});
|
||||
|
||||
it('keeps adjacent foreign detail redacted and never reveals military fields', async () => {
|
||||
const result = await appRouter
|
||||
.createCaller(context({ me: general({ cityId: 80 }) }))
|
||||
.world.getCurrentCity({ cityId: 2 });
|
||||
expect(result.visibility).toEqual({ full: false, detailed: true });
|
||||
expect(result.city.agriculture).toBeNull();
|
||||
expect(result.city.defence).toBeNull();
|
||||
expect(result.generals[0]).toMatchObject({ crew: null, train: null, atmos: null, crewTypeId: null });
|
||||
});
|
||||
|
||||
it('allows a spied city in full but still redacts foreign-general private details', async () => {
|
||||
const result = await appRouter
|
||||
.createCaller(context({ nationMeta: { spy: { 2: 2 } } }))
|
||||
.world.getCurrentCity({ cityId: 2 });
|
||||
expect(result.visibility.full).toBe(true);
|
||||
expect(result.city.population).toBe(1000);
|
||||
expect(result.generals[0]).toMatchObject({ crew: 777, train: null, atmos: null, crewTypeId: null });
|
||||
});
|
||||
|
||||
it('allows administrative roles to inspect all city and general fields', async () => {
|
||||
const result = await appRouter.createCaller(context({ roles: ['admin'] })).world.getCurrentCity({ cityId: 3 });
|
||||
expect(result.options).toHaveLength(4);
|
||||
expect(result.visibility.full).toBe(true);
|
||||
expect(result.generals[0]).toMatchObject({ crew: 777, train: 90, atmos: 90, crewTypeId: 1 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,292 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import type { GameSessionTokenPayload } from '@sammo-ts/common/auth/gameToken';
|
||||
import type { GamePrisma, 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 type { TurnDaemonTransport } from '../src/daemon/transport.js';
|
||||
import { appRouter } from '../src/router.js';
|
||||
|
||||
const poll = {
|
||||
id: 1,
|
||||
title: '선호하는 병종',
|
||||
body: '',
|
||||
options: ['보병', '기병'],
|
||||
multiple_options: 1,
|
||||
reveal_mode: 'after_vote',
|
||||
opener_general_id: 1,
|
||||
opener_name: '관리자',
|
||||
start_at: new Date('2026-07-26T00:00:00Z'),
|
||||
end_at: null,
|
||||
closed_at: null,
|
||||
};
|
||||
|
||||
const buildGeneral = (overrides: Partial<GeneralRow> = {}): GeneralRow => ({
|
||||
id: 7,
|
||||
userId: 'user-1',
|
||||
name: '유비',
|
||||
nationId: 1,
|
||||
cityId: 1,
|
||||
troopId: 0,
|
||||
npcState: 0,
|
||||
affinity: null,
|
||||
bornYear: 180,
|
||||
deadYear: 300,
|
||||
picture: null,
|
||||
imageServer: 0,
|
||||
leadership: 50,
|
||||
strength: 50,
|
||||
intel: 50,
|
||||
injury: 0,
|
||||
experience: 0,
|
||||
dedication: 0,
|
||||
officerLevel: 1,
|
||||
gold: 1000,
|
||||
rice: 1000,
|
||||
crew: 0,
|
||||
crewTypeId: 0,
|
||||
train: 0,
|
||||
atmos: 0,
|
||||
weaponCode: 'None',
|
||||
bookCode: 'None',
|
||||
horseCode: 'None',
|
||||
itemCode: 'None',
|
||||
turnTime: new Date('2026-07-26T00:00:00Z'),
|
||||
recentWarTime: null,
|
||||
age: 20,
|
||||
startAge: 20,
|
||||
personalCode: 'None',
|
||||
specialCode: 'None',
|
||||
special2Code: 'None',
|
||||
lastTurn: {},
|
||||
meta: {},
|
||||
penalty: {},
|
||||
createdAt: new Date('2026-07-26T00:00:00Z'),
|
||||
updatedAt: new Date('2026-07-26T00:00:00Z'),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const buildAuth = (roles: string[] = [], userId = 'user-1'): GameSessionTokenPayload => ({
|
||||
version: 1,
|
||||
profile: 'che:default',
|
||||
issuedAt: '2026-07-26T00:00:00.000Z',
|
||||
expiresAt: '2026-07-27T00:00:00.000Z',
|
||||
sessionId: `session-${userId}`,
|
||||
user: {
|
||||
id: userId,
|
||||
username: userId,
|
||||
displayName: userId,
|
||||
roles,
|
||||
},
|
||||
sanctions: {},
|
||||
});
|
||||
|
||||
const sqlText = (query: GamePrisma.Sql): string => query.strings.join(' ');
|
||||
|
||||
const buildContext = (options: {
|
||||
auth?: GameSessionTokenPayload | null;
|
||||
general?: GeneralRow | null;
|
||||
myVote?: number[] | null;
|
||||
voteRows?: Array<{ selection: number[]; cnt: number }>;
|
||||
pollRow?: typeof poll;
|
||||
configConst?: Record<string, unknown>;
|
||||
auctionTargets?: string[];
|
||||
}) => {
|
||||
const auth = options.auth === undefined ? buildAuth() : options.auth;
|
||||
const general = options.general === undefined ? buildGeneral() : options.general;
|
||||
const requestCommand = vi.fn(async () => ({
|
||||
type: 'voteReward' as const,
|
||||
ok: true as const,
|
||||
voteId: 1,
|
||||
generalId: general?.id ?? 0,
|
||||
awardedUnique: false,
|
||||
}));
|
||||
const queryRaw = vi.fn(async (query: GamePrisma.Sql) => {
|
||||
const text = sqlText(query);
|
||||
if (text.includes('FROM vote_poll') && text.includes('LIMIT 1')) {
|
||||
return [options.pollRow ?? poll];
|
||||
}
|
||||
if (text.includes('INSERT INTO vote (')) {
|
||||
return [{ id: 11 }];
|
||||
}
|
||||
if (text.includes('FROM vote_comment')) {
|
||||
return [];
|
||||
}
|
||||
if (text.includes('SELECT selection') && text.includes('general_id')) {
|
||||
return options.myVote ? [{ selection: options.myVote }] : [];
|
||||
}
|
||||
if (text.includes('GROUP BY selection')) {
|
||||
return options.voteRows ?? [{ selection: [0], cnt: 2 }];
|
||||
}
|
||||
if (text.includes('INSERT INTO vote_comment')) {
|
||||
return [];
|
||||
}
|
||||
return [];
|
||||
});
|
||||
const db = {
|
||||
$queryRaw: queryRaw,
|
||||
worldState: {
|
||||
findFirst: vi.fn(async () => ({
|
||||
id: 1,
|
||||
scenarioCode: 'default',
|
||||
currentYear: 200,
|
||||
currentMonth: 1,
|
||||
tickSeconds: 3600,
|
||||
config: { const: { develCost: 18, allItems: {}, ...(options.configConst ?? {}) } },
|
||||
meta: {
|
||||
hiddenSeed: 'seed',
|
||||
scenarioId: 200,
|
||||
initYear: 180,
|
||||
initMonth: 1,
|
||||
scenarioMeta: { startYear: 180 },
|
||||
},
|
||||
updatedAt: new Date(),
|
||||
})),
|
||||
},
|
||||
general: {
|
||||
findFirst: vi.fn(async ({ where }: { where: { userId: string } }) =>
|
||||
general?.userId === where.userId ? general : null
|
||||
),
|
||||
findMany: vi.fn(async () => [
|
||||
{
|
||||
horseCode: general?.horseCode ?? 'None',
|
||||
weaponCode: general?.weaponCode ?? 'None',
|
||||
bookCode: general?.bookCode ?? 'None',
|
||||
itemCode: general?.itemCode ?? 'None',
|
||||
},
|
||||
]),
|
||||
count: vi.fn(async () => 2),
|
||||
},
|
||||
nation: {
|
||||
findFirst: vi.fn(async () => ({ name: '촉' })),
|
||||
},
|
||||
auction: {
|
||||
findMany: vi.fn(async () => (options.auctionTargets ?? []).map((targetCode) => ({ targetCode }))),
|
||||
},
|
||||
};
|
||||
const accessTokenStore = new RedisAccessTokenStore(
|
||||
{
|
||||
get: async () => null,
|
||||
set: async () => null,
|
||||
},
|
||||
'che:default'
|
||||
);
|
||||
const context: GameApiContext = {
|
||||
db: db as unknown as DatabaseClient,
|
||||
redis: {} as RedisConnector['client'],
|
||||
turnDaemon: { requestCommand } as unknown as TurnDaemonTransport,
|
||||
battleSim: {} as GameApiContext['battleSim'],
|
||||
profile: { id: 'che', scenario: 'default', name: 'che:default' },
|
||||
auth,
|
||||
uploadDir: 'uploads',
|
||||
uploadPath: '/uploads',
|
||||
uploadPublicUrl: null,
|
||||
accessTokenStore,
|
||||
flushStore: new InMemoryFlushStore(),
|
||||
gameTokenSecret: 'test-secret',
|
||||
};
|
||||
return { context, requestCommand, queryRaw, db };
|
||||
};
|
||||
|
||||
describe('vote router actor and permission boundaries', () => {
|
||||
it('rejects unauthenticated survey access', async () => {
|
||||
const fixture = buildContext({ auth: null });
|
||||
|
||||
await expect(appRouter.createCaller(fixture.context).vote.getVoteList()).rejects.toMatchObject({
|
||||
code: 'UNAUTHORIZED',
|
||||
});
|
||||
});
|
||||
|
||||
it('uses only the general owned by the authenticated user for voting and reward dispatch', async () => {
|
||||
const owned = buildGeneral({ id: 7, userId: 'user-1', name: '유비' });
|
||||
const fixture = buildContext({ general: owned });
|
||||
|
||||
await expect(
|
||||
appRouter.createCaller(fixture.context).vote.submitVote({ voteId: 1, selection: [0] })
|
||||
).resolves.toEqual({ ok: true, wonLottery: false });
|
||||
expect(fixture.requestCommand).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: 'voteReward',
|
||||
voteId: 1,
|
||||
generalId: 7,
|
||||
goldReward: 90,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('includes active unique auctions in the API-side reward expectation', async () => {
|
||||
const fixture = buildContext({
|
||||
configConst: {
|
||||
allItems: { weapon: { che_무기_12_칠성검: 1 } },
|
||||
maxUniqueItemLimit: [[-1, 1]],
|
||||
uniqueTrialCoef: 10,
|
||||
maxUniqueTrialProb: 10,
|
||||
minMonthToAllowInheritItem: 0,
|
||||
},
|
||||
auctionTargets: ['che_무기_12_칠성검'],
|
||||
});
|
||||
|
||||
await appRouter.createCaller(fixture.context).vote.submitVote({ voteId: 1, selection: [0] });
|
||||
|
||||
expect(fixture.requestCommand).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
unique: { expected: false, itemKey: null },
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects voting and comments when the authenticated user owns no general', async () => {
|
||||
const fixture = buildContext({ auth: buildAuth([], 'user-2'), general: buildGeneral({ userId: 'user-1' }) });
|
||||
const caller = appRouter.createCaller(fixture.context);
|
||||
|
||||
await expect(caller.vote.submitVote({ voteId: 1, selection: [0] })).rejects.toMatchObject({
|
||||
code: 'NOT_FOUND',
|
||||
message: 'General not found',
|
||||
});
|
||||
await expect(caller.vote.addComment({ voteId: 1, text: '댓글' })).rejects.toMatchObject({
|
||||
code: 'NOT_FOUND',
|
||||
message: 'General not found',
|
||||
});
|
||||
expect(fixture.requestCommand).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects duplicate selections before persisting a vote', async () => {
|
||||
const fixture = buildContext({ pollRow: { ...poll, multiple_options: 2 } });
|
||||
|
||||
await expect(
|
||||
appRouter.createCaller(fixture.context).vote.submitVote({ voteId: 1, selection: [0, 0] })
|
||||
).rejects.toMatchObject({
|
||||
code: 'BAD_REQUEST',
|
||||
message: '선택한 항목이 올바르지 않습니다.',
|
||||
});
|
||||
expect(fixture.requestCommand).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('shows legacy-compatible aggregate results before the current general votes', async () => {
|
||||
const fixture = buildContext({ myVote: null, voteRows: [{ selection: [0], cnt: 2 }] });
|
||||
|
||||
const result = await appRouter.createCaller(fixture.context).vote.getVoteDetail({ voteId: 1 });
|
||||
|
||||
expect(result.myVote).toBeNull();
|
||||
expect(result.votes).toEqual([{ selection: [0], count: 2 }]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['global survey permission', ['admin.survey.open'], true],
|
||||
['wildcard survey permission', ['admin.survey.open:*'], true],
|
||||
['matching profile permission', ['admin.survey.open:che:default'], true],
|
||||
['different profile permission', ['admin.survey.open:hwe:default'], false],
|
||||
['ordinary user', ['user'], false],
|
||||
])('%s controls the administrator panel', async (_label, roles, allowed) => {
|
||||
const fixture = buildContext({ auth: buildAuth(roles) });
|
||||
const request = appRouter.createCaller(fixture.context).vote.getAdminStatus();
|
||||
|
||||
if (allowed) {
|
||||
await expect(request).resolves.toEqual({ ok: true });
|
||||
} else {
|
||||
await expect(request).rejects.toMatchObject({ code: 'FORBIDDEN' });
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user