feat: add board functionality with articles and comments
- Implemented BoardView for creating and displaying articles with comments. - Added NationAffairsView for managing national policies and financial settings. - Created ScoutMessageView for editing recruitment messages. - Introduced database migrations for board_post and board_comment tables.
This commit is contained in:
@@ -32,6 +32,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@fastify/cors": "^11.2.0",
|
||||
"@fastify/static": "^9.0.0",
|
||||
"@sammo-ts/common": "workspace:*",
|
||||
"@sammo-ts/infra": "workspace:*",
|
||||
"@sammo-ts/logic": "workspace:*",
|
||||
@@ -40,6 +41,7 @@
|
||||
"es-toolkit": "^1.43.0",
|
||||
"fastify": "^5.6.2",
|
||||
"redis": "^5.10.0",
|
||||
"sharp": "^0.34.4",
|
||||
"zod": "^4.3.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,9 @@ export interface GameApiConfig {
|
||||
port: number;
|
||||
trpcPath: string;
|
||||
eventsPath: string;
|
||||
uploadPath: string;
|
||||
uploadDir: string;
|
||||
uploadPublicUrl: string | null;
|
||||
profile: string;
|
||||
scenario: string;
|
||||
profileName: string;
|
||||
@@ -34,6 +37,9 @@ export const resolveGameApiConfigFromEnv = (env: NodeJS.ProcessEnv = process.env
|
||||
port: parseNumberWithFallback(env.GAME_API_PORT, 14000, 'GAME_API_PORT'),
|
||||
trpcPath: env.GAME_TRPC_PATH ?? env.TRPC_PATH ?? '/trpc',
|
||||
eventsPath: env.GAME_API_EVENTS_PATH ?? '/events',
|
||||
uploadPath: env.GAME_UPLOAD_PATH ?? '/uploads',
|
||||
uploadDir: env.GAME_UPLOAD_DIR ?? 'uploads',
|
||||
uploadPublicUrl: env.GAME_UPLOAD_PUBLIC_URL ?? null,
|
||||
profile,
|
||||
scenario,
|
||||
profileName,
|
||||
|
||||
@@ -66,6 +66,9 @@ export interface GameApiContext {
|
||||
turnDaemon: TurnDaemonTransport;
|
||||
battleSim: BattleSimTransport;
|
||||
profile: GameProfile;
|
||||
uploadDir: string;
|
||||
uploadPath: string;
|
||||
uploadPublicUrl: string | null;
|
||||
auth: GameSessionTokenPayload | null;
|
||||
accessTokenStore: RedisAccessTokenStore;
|
||||
flushStore: FlushStore;
|
||||
@@ -78,6 +81,9 @@ export const createGameApiContext = (options: {
|
||||
turnDaemon: TurnDaemonTransport;
|
||||
battleSim: BattleSimTransport;
|
||||
profile: GameProfile;
|
||||
uploadDir: string;
|
||||
uploadPath: string;
|
||||
uploadPublicUrl: string | null;
|
||||
auth: GameSessionTokenPayload | null;
|
||||
accessTokenStore: RedisAccessTokenStore;
|
||||
flushStore: FlushStore;
|
||||
@@ -89,6 +95,9 @@ export const createGameApiContext = (options: {
|
||||
turnDaemon: options.turnDaemon,
|
||||
battleSim: options.battleSim,
|
||||
profile: options.profile,
|
||||
uploadDir: options.uploadDir,
|
||||
uploadPath: options.uploadPath,
|
||||
uploadPublicUrl: options.uploadPublicUrl,
|
||||
auth: options.auth,
|
||||
accessTokenStore: options.accessTokenStore,
|
||||
flushStore: options.flushStore,
|
||||
|
||||
@@ -17,6 +17,7 @@ import { turnsRouter } from './router/turns/index.js';
|
||||
import { worldRouter } from './router/world/index.js';
|
||||
import { auctionRouter } from './router/auction/index.js';
|
||||
import { tournamentRouter } from './router/tournament/index.js';
|
||||
import { boardRouter } from './router/board/index.js';
|
||||
|
||||
export const appRouter = router({
|
||||
health: healthRouter,
|
||||
@@ -36,6 +37,7 @@ export const appRouter = router({
|
||||
turnDaemon: turnDaemonRouter,
|
||||
auction: auctionRouter,
|
||||
tournament: tournamentRouter,
|
||||
board: boardRouter,
|
||||
});
|
||||
|
||||
export type AppRouter = typeof appRouter;
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
import { TRPCError } from '@trpc/server';
|
||||
import { z } from 'zod';
|
||||
import path from 'path';
|
||||
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';
|
||||
|
||||
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) {
|
||||
throw new TRPCError({ code: 'FORBIDDEN', message: '국가에 소속되어있지 않습니다.' });
|
||||
}
|
||||
if (isSecret && resolveSecretPermission(officerLevel) < 2) {
|
||||
throw new TRPCError({ code: 'FORBIDDEN', message: '권한이 부족합니다. 수뇌부가 아닙니다.' });
|
||||
}
|
||||
};
|
||||
|
||||
const normalizeUploadPath = (value: string) => {
|
||||
if (!value.startsWith('/')) {
|
||||
return `/${value}`;
|
||||
}
|
||||
return value.replace(/\/$/, '');
|
||||
};
|
||||
|
||||
const buildPublicImageUrl = (uploadPublicUrl: string | null, uploadPath: string, filename: string) => {
|
||||
if (uploadPublicUrl) {
|
||||
return `${uploadPublicUrl.replace(/\/$/, '')}/${filename}`;
|
||||
}
|
||||
const normalizedPath = normalizeUploadPath(uploadPath);
|
||||
return `${normalizedPath}/${filename}`;
|
||||
};
|
||||
|
||||
const parseDataUrl = (dataUrl: string): Buffer => {
|
||||
const match = dataUrl.match(/^data:([^;]+);base64,(.+)$/);
|
||||
if (match) {
|
||||
return Buffer.from(match[2], 'base64');
|
||||
}
|
||||
return Buffer.from(dataUrl, 'base64');
|
||||
};
|
||||
|
||||
type WebpOptionsWithAnimation = WebpOptions & { animated?: boolean };
|
||||
|
||||
const buildWebpBuffer = async (
|
||||
buffer: Buffer,
|
||||
{ animated, resize }: { animated: boolean; resize: boolean }
|
||||
): Promise<Buffer> => {
|
||||
let pipeline = sharp(buffer, { animated: true });
|
||||
if (resize) {
|
||||
pipeline = pipeline.resize({
|
||||
width: MAX_LONG_EDGE,
|
||||
height: MAX_LONG_EDGE,
|
||||
fit: 'inside',
|
||||
withoutEnlargement: true,
|
||||
});
|
||||
}
|
||||
const webpOptions: WebpOptionsWithAnimation = {
|
||||
quality: WEBP_QUALITY,
|
||||
effort: 4,
|
||||
alphaQuality: WEBP_QUALITY,
|
||||
loop: 0,
|
||||
...(animated ? { animated: true } : {}),
|
||||
};
|
||||
|
||||
return pipeline.webp(webpOptions).toBuffer();
|
||||
};
|
||||
|
||||
const buildAvifBuffer = async (buffer: Buffer, resize: boolean): Promise<Buffer> => {
|
||||
let pipeline = sharp(buffer, { animated: true });
|
||||
if (resize) {
|
||||
pipeline = pipeline.resize({
|
||||
width: MAX_LONG_EDGE,
|
||||
height: MAX_LONG_EDGE,
|
||||
fit: 'inside',
|
||||
withoutEnlargement: true,
|
||||
});
|
||||
}
|
||||
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);
|
||||
|
||||
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
|
||||
`);
|
||||
|
||||
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 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(),
|
||||
})),
|
||||
}));
|
||||
}),
|
||||
writeArticle: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
isSecret: z.boolean(),
|
||||
title: z.string().trim().max(250),
|
||||
contentHtml: z.string().trim().max(20000),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const me = await getMyGeneral(ctx);
|
||||
assertBoardAccess(me.nationId, me.officerLevel, input.isSecret);
|
||||
|
||||
if (!input.title && !input.contentHtml) {
|
||||
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
|
||||
`);
|
||||
|
||||
return { id: rows[0]?.id ?? null };
|
||||
}),
|
||||
writeComment: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
postId: z.number().int().positive(),
|
||||
content: z.string().trim().max(2000),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const me = await getMyGeneral(ctx);
|
||||
if (!input.content) {
|
||||
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];
|
||||
if (!post) {
|
||||
throw new TRPCError({ code: 'NOT_FOUND', message: '게시물을 찾을 수 없습니다.' });
|
||||
}
|
||||
|
||||
assertBoardAccess(me.nationId, me.officerLevel, post.is_secret);
|
||||
|
||||
if (post.nation_id !== me.nationId) {
|
||||
throw new TRPCError({ code: 'FORBIDDEN', message: '권한이 부족합니다.' });
|
||||
}
|
||||
|
||||
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 };
|
||||
}),
|
||||
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: '국가에 소속되어있지 않습니다.' });
|
||||
}
|
||||
|
||||
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 {
|
||||
outputBuffer = webpBuffer;
|
||||
outputFormat = 'webp';
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
return {
|
||||
url,
|
||||
width: outputMeta.width ?? metadata.width,
|
||||
height: outputMeta.height ?? metadata.height,
|
||||
format: outputFormat,
|
||||
animated: isAnimated,
|
||||
size: outputBuffer.length,
|
||||
};
|
||||
}),
|
||||
});
|
||||
@@ -1,5 +1,7 @@
|
||||
import fastify, { type FastifyRequest } from 'fastify';
|
||||
import cors from '@fastify/cors';
|
||||
import fastifyStatic from '@fastify/static';
|
||||
import path from 'path';
|
||||
import { fastifyTRPCPlugin } from '@trpc/server/adapters/fastify';
|
||||
import { buildGameEventChannel } from '@sammo-ts/common';
|
||||
import type { GameSessionTokenPayload } from '@sammo-ts/common/auth/gameToken';
|
||||
@@ -96,6 +98,11 @@ export const createGameApiServer = async () => {
|
||||
credentials: true,
|
||||
});
|
||||
|
||||
await app.register(fastifyStatic, {
|
||||
root: path.resolve(process.cwd(), config.uploadDir),
|
||||
prefix: config.uploadPath.endsWith('/') ? config.uploadPath : `${config.uploadPath}/`,
|
||||
});
|
||||
|
||||
await app.register(fastifyTRPCPlugin, {
|
||||
prefix: config.trpcPath,
|
||||
trpcOptions: {
|
||||
@@ -113,6 +120,9 @@ export const createGameApiServer = async () => {
|
||||
scenario: config.scenario,
|
||||
name: config.profileName,
|
||||
},
|
||||
uploadDir: path.resolve(process.cwd(), config.uploadDir),
|
||||
uploadPath: config.uploadPath,
|
||||
uploadPublicUrl: config.uploadPublicUrl,
|
||||
auth,
|
||||
accessTokenStore,
|
||||
flushStore,
|
||||
|
||||
@@ -227,6 +227,9 @@ const buildContext = (options: { state: WorldStateRow; battleSim: BattleSimTrans
|
||||
battleSim: options.battleSim,
|
||||
profile,
|
||||
auth,
|
||||
uploadDir: 'uploads',
|
||||
uploadPath: '/uploads',
|
||||
uploadPublicUrl: null,
|
||||
redis: {} as unknown as RedisConnector['client'],
|
||||
accessTokenStore,
|
||||
flushStore: new InMemoryFlushStore(),
|
||||
|
||||
@@ -143,6 +143,9 @@ const buildContext = (options?: {
|
||||
battleSim,
|
||||
profile,
|
||||
auth,
|
||||
uploadDir: 'uploads',
|
||||
uploadPath: '/uploads',
|
||||
uploadPublicUrl: null,
|
||||
redis: {} as unknown as RedisConnector['client'],
|
||||
accessTokenStore,
|
||||
flushStore: new InMemoryFlushStore(),
|
||||
|
||||
@@ -17,6 +17,12 @@
|
||||
"@sammo-ts/game-api": "workspace:*",
|
||||
"@sammo-ts/gateway-api": "workspace:*",
|
||||
"@sammo-ts/logic": "workspace:*",
|
||||
"@tiptap/extension-image": "^3.5.0",
|
||||
"@tiptap/extension-link": "^3.5.0",
|
||||
"@tiptap/extension-placeholder": "^3.5.0",
|
||||
"@tiptap/extension-underline": "^3.5.0",
|
||||
"@tiptap/starter-kit": "^3.5.0",
|
||||
"@tiptap/vue-3": "^3.5.0",
|
||||
"@trpc/client": "^11.8.1",
|
||||
"@trpc/server": "^11.8.1",
|
||||
"@vueuse/core": "^14.1.0",
|
||||
|
||||
@@ -16,6 +16,9 @@ import NotFoundView from '../views/NotFoundView.vue';
|
||||
import TournamentView from '../views/TournamentView.vue';
|
||||
import MyPageView from '../views/MyPageView.vue';
|
||||
import MySettingsView from '../views/MySettingsView.vue';
|
||||
import BoardView from '../views/BoardView.vue';
|
||||
import NationAffairsView from '../views/NationAffairsView.vue';
|
||||
import ScoutMessageView from '../views/ScoutMessageView.vue';
|
||||
import { useSessionStore } from '../stores/session';
|
||||
|
||||
const routes = [
|
||||
@@ -60,6 +63,24 @@ const routes = [
|
||||
requiresGeneral: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
path: '/nation/affairs',
|
||||
name: 'nation-affairs',
|
||||
component: NationAffairsView,
|
||||
meta: {
|
||||
requiresAuth: true,
|
||||
requiresGeneral: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
path: '/nation/recruit-message',
|
||||
name: 'nation-recruit-message',
|
||||
component: ScoutMessageView,
|
||||
meta: {
|
||||
requiresAuth: true,
|
||||
requiresGeneral: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
path: '/nation/generals',
|
||||
name: 'nation-generals',
|
||||
@@ -114,6 +135,24 @@ const routes = [
|
||||
requiresGeneral: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
path: '/board',
|
||||
name: 'board',
|
||||
component: BoardView,
|
||||
meta: {
|
||||
requiresAuth: true,
|
||||
requiresGeneral: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
path: '/board/secret',
|
||||
name: 'board-secret',
|
||||
component: BoardView,
|
||||
meta: {
|
||||
requiresAuth: true,
|
||||
requiresGeneral: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
path: '/my-page',
|
||||
name: 'my-page',
|
||||
|
||||
@@ -0,0 +1,473 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue';
|
||||
import { useRoute } from 'vue-router';
|
||||
import { EditorContent, useEditor } from '@tiptap/vue-3';
|
||||
import StarterKit from '@tiptap/starter-kit';
|
||||
import Image from '@tiptap/extension-image';
|
||||
import Link from '@tiptap/extension-link';
|
||||
import Placeholder from '@tiptap/extension-placeholder';
|
||||
import Underline from '@tiptap/extension-underline';
|
||||
|
||||
import { trpc } from '../utils/trpc';
|
||||
|
||||
type BoardComment = {
|
||||
id: number;
|
||||
authorName: string;
|
||||
content: string;
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
type BoardArticle = {
|
||||
id: number;
|
||||
title: string;
|
||||
contentHtml: string;
|
||||
authorName: string;
|
||||
createdAt: string;
|
||||
comments: BoardComment[];
|
||||
};
|
||||
|
||||
const route = useRoute();
|
||||
const isSecretBoard = computed(() => route.name === 'board-secret');
|
||||
const title = computed(() => (isSecretBoard.value ? '기밀실' : '회의실'));
|
||||
const toggleBoardLabel = computed(() => (isSecretBoard.value ? '회의실로' : '기밀실로'));
|
||||
const toggleBoardPath = computed(() => (isSecretBoard.value ? '/board' : '/board/secret'));
|
||||
|
||||
const loading = ref(false);
|
||||
const errorMessage = ref<string | null>(null);
|
||||
const articles = ref<BoardArticle[]>([]);
|
||||
|
||||
const draftTitle = ref('');
|
||||
const commentDrafts = reactive<Record<number, string>>({});
|
||||
|
||||
const editor = useEditor({
|
||||
extensions: [
|
||||
StarterKit,
|
||||
Underline,
|
||||
Link.configure({ openOnClick: false }),
|
||||
Image.configure({ inline: false }),
|
||||
Placeholder.configure({ placeholder: '내용을 입력하세요.' }),
|
||||
],
|
||||
content: '',
|
||||
editorProps: {
|
||||
attributes: {
|
||||
class: 'board-editor',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const refreshArticles = async () => {
|
||||
if (loading.value) return;
|
||||
loading.value = true;
|
||||
errorMessage.value = null;
|
||||
try {
|
||||
const result = await trpc.board.getArticles.query({ isSecret: isSecretBoard.value });
|
||||
articles.value = result;
|
||||
} catch (err) {
|
||||
errorMessage.value = err instanceof Error ? err.message : '게시판을 불러오지 못했습니다.';
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const submitArticle = async () => {
|
||||
const contentHtml = editor.value?.getHTML().trim() ?? '';
|
||||
const titleValue = draftTitle.value.trim();
|
||||
if (!titleValue && !contentHtml) return;
|
||||
errorMessage.value = null;
|
||||
try {
|
||||
await trpc.board.writeArticle.mutate({
|
||||
isSecret: isSecretBoard.value,
|
||||
title: titleValue,
|
||||
contentHtml,
|
||||
});
|
||||
draftTitle.value = '';
|
||||
editor.value?.commands.setContent('');
|
||||
await refreshArticles();
|
||||
} catch (err) {
|
||||
errorMessage.value = err instanceof Error ? err.message : '게시물 등록에 실패했습니다.';
|
||||
}
|
||||
};
|
||||
|
||||
const submitComment = async (postId: number) => {
|
||||
const content = (commentDrafts[postId] ?? '').trim();
|
||||
if (!content) return;
|
||||
errorMessage.value = null;
|
||||
try {
|
||||
await trpc.board.writeComment.mutate({ postId, content });
|
||||
commentDrafts[postId] = '';
|
||||
await refreshArticles();
|
||||
} catch (err) {
|
||||
errorMessage.value = err instanceof Error ? err.message : '댓글 등록에 실패했습니다.';
|
||||
}
|
||||
};
|
||||
|
||||
const fileInputRef = ref<HTMLInputElement | null>(null);
|
||||
const uploadBusy = ref(false);
|
||||
|
||||
const addLink = () => {
|
||||
const url = window.prompt('링크 주소를 입력하세요');
|
||||
if (!url) return;
|
||||
editor.value?.chain().focus().extendMarkRange('link').setLink({ href: url }).run();
|
||||
};
|
||||
|
||||
const readFileAsDataUrl = (file: File) =>
|
||||
new Promise<string>((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
if (typeof reader.result === 'string') {
|
||||
resolve(reader.result);
|
||||
} else {
|
||||
reject(new Error('이미지를 읽을 수 없습니다.'));
|
||||
}
|
||||
};
|
||||
reader.onerror = () => reject(new Error('이미지를 읽는 중 오류가 발생했습니다.'));
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
|
||||
const onSelectImage = async (event: Event) => {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const file = input.files?.[0];
|
||||
if (!file || uploadBusy.value) return;
|
||||
uploadBusy.value = true;
|
||||
errorMessage.value = null;
|
||||
try {
|
||||
const dataUrl = await readFileAsDataUrl(file);
|
||||
const result = await trpc.board.uploadImage.mutate({ dataUrl });
|
||||
editor.value?.chain().focus().setImage({ src: result.url, alt: file.name }).run();
|
||||
} catch (err) {
|
||||
errorMessage.value = err instanceof Error ? err.message : '이미지 업로드에 실패했습니다.';
|
||||
} finally {
|
||||
uploadBusy.value = false;
|
||||
if (input) {
|
||||
input.value = '';
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const formatDate = (value: string) => new Date(value).toLocaleString('ko-KR');
|
||||
|
||||
watch(isSecretBoard, () => {
|
||||
refreshArticles();
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
refreshArticles();
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
editor.value?.destroy();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="board-view">
|
||||
<header class="board-header">
|
||||
<div>
|
||||
<h1>{{ title }}</h1>
|
||||
<span class="board-subtitle">새 게시물 작성</span>
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<RouterLink class="ghost" to="/">메인으로</RouterLink>
|
||||
<RouterLink class="ghost" :to="toggleBoardPath">{{ toggleBoardLabel }}</RouterLink>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section class="board-editor-card">
|
||||
<div class="field-row">
|
||||
<label class="field-label">제목</label>
|
||||
<input v-model="draftTitle" class="field-input" type="text" maxlength="250" placeholder="제목" />
|
||||
</div>
|
||||
|
||||
<div class="editor-toolbar">
|
||||
<button type="button" @click="editor?.chain().focus().toggleBold().run()" :class="{ active: editor?.isActive('bold') }">
|
||||
굵게
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
@click="editor?.chain().focus().toggleItalic().run()"
|
||||
:class="{ active: editor?.isActive('italic') }"
|
||||
>
|
||||
기울임
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
@click="editor?.chain().focus().toggleUnderline().run()"
|
||||
:class="{ active: editor?.isActive('underline') }"
|
||||
>
|
||||
밑줄
|
||||
</button>
|
||||
<button type="button" @click="addLink">링크</button>
|
||||
<button type="button" @click="editor?.chain().focus().toggleBulletList().run()">
|
||||
목록
|
||||
</button>
|
||||
<button type="button" @click="editor?.chain().focus().toggleOrderedList().run()">
|
||||
번호 목록
|
||||
</button>
|
||||
<button type="button" @click="fileInputRef?.click()" :disabled="uploadBusy">
|
||||
이미지 업로드
|
||||
</button>
|
||||
<input ref="fileInputRef" type="file" accept="image/*" class="hidden" @change="onSelectImage" />
|
||||
</div>
|
||||
|
||||
<EditorContent v-if="editor" :editor="editor" />
|
||||
|
||||
<div class="submit-row">
|
||||
<button type="button" class="primary" @click="submitArticle">등록</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<p v-if="errorMessage" class="error-text">{{ errorMessage }}</p>
|
||||
|
||||
<section class="board-list">
|
||||
<div v-if="loading" class="empty-text">불러오는 중...</div>
|
||||
<div v-else-if="!articles.length" class="empty-text">게시물이 없습니다.</div>
|
||||
<article v-else v-for="article in articles" :key="article.id" class="board-article">
|
||||
<header class="article-header">
|
||||
<h2>{{ article.title || '제목 없음' }}</h2>
|
||||
<div class="article-meta">
|
||||
<span>{{ article.authorName }}</span>
|
||||
<span>{{ formatDate(article.createdAt) }}</span>
|
||||
</div>
|
||||
</header>
|
||||
<div class="article-content" v-html="article.contentHtml" />
|
||||
|
||||
<section class="comment-list">
|
||||
<div v-if="!article.comments.length" class="comment-empty">댓글이 없습니다.</div>
|
||||
<div v-for="comment in article.comments" :key="comment.id" class="comment-item">
|
||||
<div class="comment-meta">
|
||||
<span>{{ comment.authorName }}</span>
|
||||
<span>{{ formatDate(comment.createdAt) }}</span>
|
||||
</div>
|
||||
<p class="comment-content">{{ comment.content }}</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div class="comment-form">
|
||||
<textarea
|
||||
v-model="commentDrafts[article.id]"
|
||||
rows="3"
|
||||
placeholder="댓글을 입력하세요."
|
||||
/>
|
||||
<button type="button" @click="submitComment(article.id)">댓글 등록</button>
|
||||
</div>
|
||||
</article>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.board-view {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 24px;
|
||||
padding: 24px;
|
||||
color: #e6e8ef;
|
||||
background: #0f1118;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.board-header h1 {
|
||||
font-size: 28px;
|
||||
margin: 0 0 6px;
|
||||
}
|
||||
|
||||
.header-actions {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.header-actions .ghost {
|
||||
padding: 6px 12px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #2b2f3f;
|
||||
color: #c7d0e0;
|
||||
text-decoration: none;
|
||||
background: #141826;
|
||||
}
|
||||
|
||||
.header-actions .ghost:hover {
|
||||
background: #1b2233;
|
||||
}
|
||||
|
||||
.board-subtitle {
|
||||
font-size: 14px;
|
||||
color: #a8afc5;
|
||||
}
|
||||
|
||||
.board-editor-card {
|
||||
background: #181b26;
|
||||
padding: 20px;
|
||||
border-radius: 12px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
box-shadow: 0 12px 24px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.field-row {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.field-label {
|
||||
min-width: 52px;
|
||||
font-weight: 600;
|
||||
color: #c9d0e5;
|
||||
}
|
||||
|
||||
.field-input {
|
||||
flex: 1;
|
||||
padding: 10px 12px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #2b2f3f;
|
||||
background: #11131a;
|
||||
color: #f2f4f8;
|
||||
}
|
||||
|
||||
.editor-toolbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.editor-toolbar button {
|
||||
padding: 6px 10px;
|
||||
border-radius: 6px;
|
||||
border: 1px solid #2b2f3f;
|
||||
background: #1e2232;
|
||||
color: #d8dff0;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.editor-toolbar button.active {
|
||||
background: #3b425c;
|
||||
}
|
||||
|
||||
.editor-toolbar button:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.board-editor {
|
||||
min-height: 220px;
|
||||
padding: 12px;
|
||||
border-radius: 10px;
|
||||
border: 1px solid #2b2f3f;
|
||||
background: #0f1118;
|
||||
color: #f5f6fa;
|
||||
}
|
||||
|
||||
.board-editor :deep(img) {
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.submit-row {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.submit-row .primary {
|
||||
padding: 10px 20px;
|
||||
border-radius: 8px;
|
||||
border: none;
|
||||
background: #3b82f6;
|
||||
color: #fff;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.error-text {
|
||||
color: #f87171;
|
||||
}
|
||||
|
||||
.board-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.board-article {
|
||||
background: #161a24;
|
||||
border-radius: 12px;
|
||||
padding: 18px;
|
||||
border: 1px solid #202638;
|
||||
}
|
||||
|
||||
.article-header h2 {
|
||||
margin: 0 0 6px;
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
.article-meta {
|
||||
font-size: 12px;
|
||||
color: #9aa3b8;
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.article-content {
|
||||
margin-top: 12px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.comment-list {
|
||||
margin-top: 16px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.comment-item {
|
||||
background: #11131a;
|
||||
border-radius: 8px;
|
||||
padding: 10px 12px;
|
||||
}
|
||||
|
||||
.comment-meta {
|
||||
font-size: 11px;
|
||||
color: #8e96aa;
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.comment-content {
|
||||
margin: 0;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.comment-form {
|
||||
margin-top: 12px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.comment-form textarea {
|
||||
background: #0f1118;
|
||||
border: 1px solid #2b2f3f;
|
||||
border-radius: 8px;
|
||||
padding: 8px 10px;
|
||||
color: #e6e8ef;
|
||||
}
|
||||
|
||||
.comment-form button {
|
||||
align-self: flex-end;
|
||||
padding: 6px 14px;
|
||||
border-radius: 6px;
|
||||
border: none;
|
||||
background: #334155;
|
||||
color: #fff;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.empty-text {
|
||||
color: #9aa3b8;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,577 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
import { EditorContent, useEditor } from '@tiptap/vue-3';
|
||||
import StarterKit from '@tiptap/starter-kit';
|
||||
import Image from '@tiptap/extension-image';
|
||||
import Link from '@tiptap/extension-link';
|
||||
import Placeholder from '@tiptap/extension-placeholder';
|
||||
import Underline from '@tiptap/extension-underline';
|
||||
import { trpc } from '../utils/trpc';
|
||||
|
||||
type StratFinanResult = Awaited<ReturnType<typeof trpc.nation.getStratFinan.query>>;
|
||||
|
||||
type TabKey = 'policy' | 'finance';
|
||||
|
||||
const activeTab = ref<TabKey>('policy');
|
||||
const loading = ref(false);
|
||||
const errorMessage = ref<string | null>(null);
|
||||
const data = ref<StratFinanResult | null>(null);
|
||||
|
||||
const editable = computed(() => data.value?.editable ?? false);
|
||||
|
||||
const nationMsg = ref('');
|
||||
const originalNationMsg = ref('');
|
||||
const editingNationMsg = ref(false);
|
||||
|
||||
const policyDraft = ref({
|
||||
rate: 0,
|
||||
bill: 0,
|
||||
secretLimit: 0,
|
||||
blockWar: false,
|
||||
blockScout: false,
|
||||
});
|
||||
|
||||
const updateFromData = (payload: StratFinanResult) => {
|
||||
nationMsg.value = payload.nationMsg ?? '';
|
||||
originalNationMsg.value = payload.nationMsg ?? '';
|
||||
policyDraft.value = {
|
||||
rate: payload.policy.rate,
|
||||
bill: payload.policy.bill,
|
||||
secretLimit: payload.policy.secretLimit,
|
||||
blockWar: payload.policy.blockWar,
|
||||
blockScout: payload.policy.blockScout,
|
||||
};
|
||||
if (!editingNationMsg.value) {
|
||||
editor.value?.commands.setContent(nationMsg.value || '');
|
||||
}
|
||||
};
|
||||
|
||||
const loadData = async () => {
|
||||
if (loading.value) return;
|
||||
loading.value = true;
|
||||
errorMessage.value = null;
|
||||
try {
|
||||
const result = await trpc.nation.getStratFinan.query();
|
||||
data.value = result;
|
||||
updateFromData(result);
|
||||
} catch (err) {
|
||||
errorMessage.value = err instanceof Error ? err.message : '내무부 정보를 불러오지 못했습니다.';
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const editor = useEditor({
|
||||
extensions: [
|
||||
StarterKit,
|
||||
Underline,
|
||||
Link.configure({ openOnClick: false }),
|
||||
Image.configure({ inline: false }),
|
||||
Placeholder.configure({ placeholder: '국가 방침을 입력하세요.' }),
|
||||
],
|
||||
editable: false,
|
||||
content: nationMsg.value,
|
||||
editorProps: {
|
||||
attributes: {
|
||||
class: 'policy-editor',
|
||||
},
|
||||
},
|
||||
onUpdate({ editor }) {
|
||||
nationMsg.value = editor.getHTML();
|
||||
},
|
||||
});
|
||||
|
||||
const fileInputRef = ref<HTMLInputElement | null>(null);
|
||||
const uploadBusy = ref(false);
|
||||
|
||||
const readFileAsDataUrl = (file: File) =>
|
||||
new Promise<string>((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
if (typeof reader.result === 'string') {
|
||||
resolve(reader.result);
|
||||
} else {
|
||||
reject(new Error('이미지를 읽을 수 없습니다.'));
|
||||
}
|
||||
};
|
||||
reader.onerror = () => reject(new Error('이미지를 읽는 중 오류가 발생했습니다.'));
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
|
||||
const onSelectImage = async (event: Event) => {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const file = input.files?.[0];
|
||||
if (!file || uploadBusy.value) return;
|
||||
uploadBusy.value = true;
|
||||
errorMessage.value = null;
|
||||
try {
|
||||
const dataUrl = await readFileAsDataUrl(file);
|
||||
const result = await trpc.board.uploadImage.mutate({ dataUrl });
|
||||
editor.value?.chain().focus().setImage({ src: result.url, alt: file.name }).run();
|
||||
} catch (err) {
|
||||
errorMessage.value = err instanceof Error ? err.message : '이미지 업로드에 실패했습니다.';
|
||||
} finally {
|
||||
uploadBusy.value = false;
|
||||
if (input) {
|
||||
input.value = '';
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const addLink = () => {
|
||||
const url = window.prompt('링크 주소를 입력하세요');
|
||||
if (!url) return;
|
||||
editor.value?.chain().focus().extendMarkRange('link').setLink({ href: url }).run();
|
||||
};
|
||||
|
||||
const startEditNationMsg = () => {
|
||||
if (!editable.value) return;
|
||||
editingNationMsg.value = true;
|
||||
editor.value?.setEditable(true);
|
||||
};
|
||||
|
||||
const cancelEditNationMsg = () => {
|
||||
editingNationMsg.value = false;
|
||||
nationMsg.value = originalNationMsg.value;
|
||||
editor.value?.commands.setContent(originalNationMsg.value || '');
|
||||
editor.value?.setEditable(false);
|
||||
};
|
||||
|
||||
const saveNationMsg = async () => {
|
||||
if (!editable.value) return;
|
||||
errorMessage.value = null;
|
||||
try {
|
||||
await trpc.nation.setNotice.mutate({ msg: nationMsg.value });
|
||||
originalNationMsg.value = nationMsg.value;
|
||||
editingNationMsg.value = false;
|
||||
editor.value?.setEditable(false);
|
||||
} catch (err) {
|
||||
errorMessage.value = err instanceof Error ? err.message : '국가 방침 저장에 실패했습니다.';
|
||||
}
|
||||
};
|
||||
|
||||
const setRate = async () => {
|
||||
if (!editable.value) return;
|
||||
errorMessage.value = null;
|
||||
try {
|
||||
await trpc.nation.setRate.mutate({ amount: policyDraft.value.rate });
|
||||
await loadData();
|
||||
} catch (err) {
|
||||
errorMessage.value = err instanceof Error ? err.message : '세율 변경에 실패했습니다.';
|
||||
}
|
||||
};
|
||||
|
||||
const setBill = async () => {
|
||||
if (!editable.value) return;
|
||||
errorMessage.value = null;
|
||||
try {
|
||||
await trpc.nation.setBill.mutate({ amount: policyDraft.value.bill });
|
||||
await loadData();
|
||||
} catch (err) {
|
||||
errorMessage.value = err instanceof Error ? err.message : '지급률 변경에 실패했습니다.';
|
||||
}
|
||||
};
|
||||
|
||||
const setSecretLimit = async () => {
|
||||
if (!editable.value) return;
|
||||
errorMessage.value = null;
|
||||
try {
|
||||
await trpc.nation.setSecretLimit.mutate({ amount: policyDraft.value.secretLimit });
|
||||
await loadData();
|
||||
} catch (err) {
|
||||
errorMessage.value = err instanceof Error ? err.message : '기밀 권한 변경에 실패했습니다.';
|
||||
}
|
||||
};
|
||||
|
||||
const setBlockWar = async () => {
|
||||
if (!editable.value) return;
|
||||
errorMessage.value = null;
|
||||
try {
|
||||
await trpc.nation.setBlockWar.mutate({ value: policyDraft.value.blockWar });
|
||||
await loadData();
|
||||
} catch (err) {
|
||||
errorMessage.value = err instanceof Error ? err.message : '전쟁 금지 설정에 실패했습니다.';
|
||||
policyDraft.value.blockWar = !policyDraft.value.blockWar;
|
||||
}
|
||||
};
|
||||
|
||||
const setBlockScout = async () => {
|
||||
if (!editable.value) return;
|
||||
errorMessage.value = null;
|
||||
try {
|
||||
await trpc.nation.setBlockScout.mutate({ value: policyDraft.value.blockScout });
|
||||
await loadData();
|
||||
} catch (err) {
|
||||
errorMessage.value = err instanceof Error ? err.message : '임관 권유 설정에 실패했습니다.';
|
||||
policyDraft.value.blockScout = !policyDraft.value.blockScout;
|
||||
}
|
||||
};
|
||||
|
||||
const incomeGoldCity = computed(() => {
|
||||
if (!data.value) return 0;
|
||||
return (data.value.income.gold.city * policyDraft.value.rate) / 100;
|
||||
});
|
||||
|
||||
const incomeGold = computed(() => {
|
||||
if (!data.value) return 0;
|
||||
return incomeGoldCity.value + data.value.income.gold.war;
|
||||
});
|
||||
|
||||
const incomeRiceCity = computed(() => {
|
||||
if (!data.value) return 0;
|
||||
return (data.value.income.rice.city * policyDraft.value.rate) / 100;
|
||||
});
|
||||
|
||||
const incomeRiceWall = computed(() => {
|
||||
if (!data.value) return 0;
|
||||
return (data.value.income.rice.wall * policyDraft.value.rate) / 100;
|
||||
});
|
||||
|
||||
const incomeRice = computed(() => incomeRiceCity.value + incomeRiceWall.value);
|
||||
|
||||
const outcomeByBill = computed(() => {
|
||||
if (!data.value) return 0;
|
||||
return (data.value.outcome * policyDraft.value.bill) / 100;
|
||||
});
|
||||
|
||||
watch(
|
||||
() => editingNationMsg.value,
|
||||
(value) => {
|
||||
editor.value?.setEditable(value);
|
||||
}
|
||||
);
|
||||
|
||||
onMounted(() => {
|
||||
loadData();
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
editor.value?.destroy();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="affairs-view">
|
||||
<header class="page-header">
|
||||
<div>
|
||||
<h1>내무부</h1>
|
||||
<p class="subtitle">국가 방침 및 정책 조정</p>
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<button type="button" class="ghost" @click="loadData">수동 갱신</button>
|
||||
<RouterLink class="ghost" to="/nation/recruit-message">임관 권유 편집</RouterLink>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<nav class="tab-bar">
|
||||
<button type="button" :class="{ active: activeTab === 'policy' }" @click="activeTab = 'policy'">
|
||||
국가 방침
|
||||
</button>
|
||||
<button type="button" :class="{ active: activeTab === 'finance' }" @click="activeTab = 'finance'">
|
||||
세율 · 재정 · 전쟁
|
||||
</button>
|
||||
</nav>
|
||||
|
||||
<p v-if="errorMessage" class="error-text">{{ errorMessage }}</p>
|
||||
|
||||
<section v-if="activeTab === 'policy'" class="panel">
|
||||
<div class="panel-header">
|
||||
<h2>국가 방침</h2>
|
||||
<div class="panel-actions">
|
||||
<button v-if="editable && !editingNationMsg" type="button" @click="startEditNationMsg">
|
||||
수정
|
||||
</button>
|
||||
<button v-if="editable && editingNationMsg" type="button" @click="saveNationMsg">
|
||||
저장
|
||||
</button>
|
||||
<button v-if="editable && editingNationMsg" type="button" @click="cancelEditNationMsg">
|
||||
취소
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="editingNationMsg" class="editor-toolbar">
|
||||
<button type="button" @click="editor?.chain().focus().toggleBold().run()" :class="{ active: editor?.isActive('bold') }">
|
||||
굵게
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
@click="editor?.chain().focus().toggleItalic().run()"
|
||||
:class="{ active: editor?.isActive('italic') }"
|
||||
>
|
||||
기울임
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
@click="editor?.chain().focus().toggleUnderline().run()"
|
||||
:class="{ active: editor?.isActive('underline') }"
|
||||
>
|
||||
밑줄
|
||||
</button>
|
||||
<button type="button" @click="addLink">링크</button>
|
||||
<button type="button" @click="editor?.chain().focus().toggleBulletList().run()">목록</button>
|
||||
<button type="button" @click="editor?.chain().focus().toggleOrderedList().run()">번호 목록</button>
|
||||
<button type="button" @click="fileInputRef?.click()" :disabled="uploadBusy">이미지 업로드</button>
|
||||
<input ref="fileInputRef" type="file" accept="image/*" class="hidden" @change="onSelectImage" />
|
||||
</div>
|
||||
<div class="policy-editor-frame">
|
||||
<EditorContent v-if="editor" :editor="editor" />
|
||||
</div>
|
||||
<p v-if="!editable" class="hint">편집 권한은 군주/수뇌에게만 제공됩니다.</p>
|
||||
</section>
|
||||
|
||||
<section v-if="activeTab === 'finance' && data" class="panel grid">
|
||||
<div class="panel-card">
|
||||
<h3>자금 예산</h3>
|
||||
<dl>
|
||||
<div><dt>현재</dt><dd>{{ data.gold.toLocaleString() }}</dd></div>
|
||||
<div><dt>단기 수입</dt><dd>{{ data.income.gold.war.toLocaleString() }}</dd></div>
|
||||
<div><dt>세금</dt><dd>{{ Math.floor(incomeGoldCity).toLocaleString() }}</dd></div>
|
||||
<div><dt>수입/지출</dt><dd>+{{ Math.floor(incomeGold).toLocaleString() }} / {{ Math.floor(-outcomeByBill).toLocaleString() }}</dd></div>
|
||||
<div><dt>국고 예산</dt><dd>{{ Math.floor(data.gold + incomeGold - outcomeByBill).toLocaleString() }}</dd></div>
|
||||
</dl>
|
||||
</div>
|
||||
<div class="panel-card">
|
||||
<h3>군량 예산</h3>
|
||||
<dl>
|
||||
<div><dt>현재</dt><dd>{{ data.rice.toLocaleString() }}</dd></div>
|
||||
<div><dt>둔전 수입</dt><dd>{{ Math.floor(incomeRiceWall).toLocaleString() }}</dd></div>
|
||||
<div><dt>세금</dt><dd>{{ Math.floor(incomeRiceCity).toLocaleString() }}</dd></div>
|
||||
<div><dt>수입/지출</dt><dd>+{{ Math.floor(incomeRice).toLocaleString() }} / {{ Math.floor(-outcomeByBill).toLocaleString() }}</dd></div>
|
||||
<div><dt>국고 예산</dt><dd>{{ Math.floor(data.rice + incomeRice - outcomeByBill).toLocaleString() }}</dd></div>
|
||||
</dl>
|
||||
</div>
|
||||
<div class="panel-card">
|
||||
<h3>세율</h3>
|
||||
<div class="input-row">
|
||||
<input v-model.number="policyDraft.rate" type="number" min="5" max="30" :disabled="!editable" />
|
||||
<span>%</span>
|
||||
<button type="button" @click="setRate" :disabled="!editable">변경</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="panel-card">
|
||||
<h3>지급률</h3>
|
||||
<div class="input-row">
|
||||
<input v-model.number="policyDraft.bill" type="number" min="20" max="200" :disabled="!editable" />
|
||||
<span>%</span>
|
||||
<button type="button" @click="setBill" :disabled="!editable">변경</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="panel-card">
|
||||
<h3>기밀 권한</h3>
|
||||
<div class="input-row">
|
||||
<input v-model.number="policyDraft.secretLimit" type="number" min="1" max="99" :disabled="!editable" />
|
||||
<span>년</span>
|
||||
<button type="button" @click="setSecretLimit" :disabled="!editable">변경</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="panel-card">
|
||||
<h3>전쟁 금지 설정</h3>
|
||||
<div class="toggle-row">
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
v-model="policyDraft.blockWar"
|
||||
:disabled="!editable"
|
||||
@change="setBlockWar"
|
||||
/>
|
||||
전쟁 금지
|
||||
</label>
|
||||
<span class="hint">잔여 {{ data.warSettingCnt.remain }}회 (월 +{{ data.warSettingCnt.inc }}회)</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="panel-card">
|
||||
<h3>임관 권유 설정</h3>
|
||||
<div class="toggle-row">
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
v-model="policyDraft.blockScout"
|
||||
:disabled="!editable"
|
||||
@change="setBlockScout"
|
||||
/>
|
||||
임관 권유 허용
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div v-if="loading" class="loading">불러오는 중...</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.affairs-view {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
padding: 24px;
|
||||
background: #0f1118;
|
||||
color: #e6e8ef;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.page-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
color: #9aa3b8;
|
||||
margin: 4px 0 0;
|
||||
}
|
||||
|
||||
.header-actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.ghost {
|
||||
padding: 6px 12px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #2b2f3f;
|
||||
background: #141826;
|
||||
color: #c7d0e0;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.tab-bar {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.tab-bar button {
|
||||
border: 1px solid #2b2f3f;
|
||||
background: #141826;
|
||||
color: #c7d0e0;
|
||||
padding: 8px 14px;
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.tab-bar button.active {
|
||||
background: #2b3348;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.panel {
|
||||
background: #181b26;
|
||||
border-radius: 12px;
|
||||
padding: 16px;
|
||||
border: 1px solid #23283a;
|
||||
}
|
||||
|
||||
.panel-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.panel-actions button {
|
||||
margin-left: 8px;
|
||||
}
|
||||
|
||||
.policy-editor {
|
||||
min-height: 220px;
|
||||
padding: 12px;
|
||||
border-radius: 10px;
|
||||
border: 1px solid #2b2f3f;
|
||||
background: #0f1118;
|
||||
color: #f5f6fa;
|
||||
}
|
||||
|
||||
.policy-editor-frame {
|
||||
max-width: 1000px;
|
||||
}
|
||||
|
||||
.editor-toolbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.editor-toolbar button {
|
||||
padding: 6px 10px;
|
||||
border-radius: 6px;
|
||||
border: 1px solid #2b2f3f;
|
||||
background: #1e2232;
|
||||
color: #d8dff0;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.editor-toolbar button.active {
|
||||
background: #3b425c;
|
||||
}
|
||||
|
||||
.hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.panel.grid {
|
||||
display: grid;
|
||||
gap: 16px;
|
||||
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
|
||||
}
|
||||
|
||||
.panel-card {
|
||||
background: #131722;
|
||||
padding: 12px;
|
||||
border-radius: 10px;
|
||||
border: 1px solid #23283a;
|
||||
}
|
||||
|
||||
.panel-card h3 {
|
||||
margin: 0 0 8px;
|
||||
}
|
||||
|
||||
.panel-card dl {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.panel-card dl div {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.input-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.input-row input {
|
||||
width: 90px;
|
||||
padding: 4px 8px;
|
||||
border-radius: 6px;
|
||||
border: 1px solid #2b2f3f;
|
||||
background: #0f1118;
|
||||
color: #f5f6fa;
|
||||
}
|
||||
|
||||
.toggle-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 8px 0;
|
||||
}
|
||||
|
||||
.hint {
|
||||
color: #9aa3b8;
|
||||
}
|
||||
|
||||
.error-text {
|
||||
color: #f87171;
|
||||
}
|
||||
|
||||
.loading {
|
||||
color: #9aa3b8;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,308 @@
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
import { EditorContent, useEditor } from '@tiptap/vue-3';
|
||||
import StarterKit from '@tiptap/starter-kit';
|
||||
import Image from '@tiptap/extension-image';
|
||||
import Link from '@tiptap/extension-link';
|
||||
import Placeholder from '@tiptap/extension-placeholder';
|
||||
import Underline from '@tiptap/extension-underline';
|
||||
import { trpc } from '../utils/trpc';
|
||||
|
||||
type StratFinanResult = Awaited<ReturnType<typeof trpc.nation.getStratFinan.query>>;
|
||||
|
||||
const loading = ref(false);
|
||||
const errorMessage = ref<string | null>(null);
|
||||
const editable = ref(false);
|
||||
|
||||
const scoutMsg = ref('');
|
||||
const originalScoutMsg = ref('');
|
||||
const editing = ref(false);
|
||||
|
||||
const editor = useEditor({
|
||||
extensions: [
|
||||
StarterKit,
|
||||
Underline,
|
||||
Link.configure({ openOnClick: false }),
|
||||
Image.configure({ inline: false }),
|
||||
Placeholder.configure({ placeholder: '임관 권유 메시지를 입력하세요.' }),
|
||||
],
|
||||
editable: false,
|
||||
content: scoutMsg.value,
|
||||
editorProps: {
|
||||
attributes: {
|
||||
class: 'scout-editor',
|
||||
},
|
||||
},
|
||||
onUpdate({ editor }) {
|
||||
scoutMsg.value = editor.getHTML();
|
||||
},
|
||||
});
|
||||
|
||||
const fileInputRef = ref<HTMLInputElement | null>(null);
|
||||
const uploadBusy = ref(false);
|
||||
|
||||
const readFileAsDataUrl = (file: File) =>
|
||||
new Promise<string>((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
if (typeof reader.result === 'string') {
|
||||
resolve(reader.result);
|
||||
} else {
|
||||
reject(new Error('이미지를 읽을 수 없습니다.'));
|
||||
}
|
||||
};
|
||||
reader.onerror = () => reject(new Error('이미지를 읽는 중 오류가 발생했습니다.'));
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
|
||||
const onSelectImage = async (event: Event) => {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const file = input.files?.[0];
|
||||
if (!file || uploadBusy.value) return;
|
||||
uploadBusy.value = true;
|
||||
errorMessage.value = null;
|
||||
try {
|
||||
const dataUrl = await readFileAsDataUrl(file);
|
||||
const result = await trpc.board.uploadImage.mutate({ dataUrl });
|
||||
editor.value?.chain().focus().setImage({ src: result.url, alt: file.name }).run();
|
||||
} catch (err) {
|
||||
errorMessage.value = err instanceof Error ? err.message : '이미지 업로드에 실패했습니다.';
|
||||
} finally {
|
||||
uploadBusy.value = false;
|
||||
if (input) {
|
||||
input.value = '';
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const addLink = () => {
|
||||
const url = window.prompt('링크 주소를 입력하세요');
|
||||
if (!url) return;
|
||||
editor.value?.chain().focus().extendMarkRange('link').setLink({ href: url }).run();
|
||||
};
|
||||
|
||||
const loadData = async () => {
|
||||
if (loading.value) return;
|
||||
loading.value = true;
|
||||
errorMessage.value = null;
|
||||
try {
|
||||
const result: StratFinanResult = await trpc.nation.getStratFinan.query();
|
||||
editable.value = result.editable;
|
||||
scoutMsg.value = result.scoutMsg ?? '';
|
||||
originalScoutMsg.value = result.scoutMsg ?? '';
|
||||
if (!editing.value) {
|
||||
editor.value?.commands.setContent(scoutMsg.value || '');
|
||||
}
|
||||
} catch (err) {
|
||||
errorMessage.value = err instanceof Error ? err.message : '임관 권유 정보를 불러오지 못했습니다.';
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const startEdit = () => {
|
||||
if (!editable.value) return;
|
||||
editing.value = true;
|
||||
editor.value?.setEditable(true);
|
||||
};
|
||||
|
||||
const cancelEdit = () => {
|
||||
editing.value = false;
|
||||
scoutMsg.value = originalScoutMsg.value;
|
||||
editor.value?.commands.setContent(originalScoutMsg.value || '');
|
||||
editor.value?.setEditable(false);
|
||||
};
|
||||
|
||||
const saveScoutMsg = async () => {
|
||||
if (!editable.value) return;
|
||||
errorMessage.value = null;
|
||||
try {
|
||||
await trpc.nation.setScoutMsg.mutate({ msg: scoutMsg.value });
|
||||
originalScoutMsg.value = scoutMsg.value;
|
||||
editing.value = false;
|
||||
editor.value?.setEditable(false);
|
||||
} catch (err) {
|
||||
errorMessage.value = err instanceof Error ? err.message : '임관 권유 저장에 실패했습니다.';
|
||||
}
|
||||
};
|
||||
|
||||
watch(
|
||||
() => editing.value,
|
||||
(value) => {
|
||||
editor.value?.setEditable(value);
|
||||
}
|
||||
);
|
||||
|
||||
onMounted(() => {
|
||||
loadData();
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
editor.value?.destroy();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="scout-view">
|
||||
<header class="page-header">
|
||||
<div>
|
||||
<h1>임관 권유</h1>
|
||||
<p class="subtitle">장수 모집 화면에 표시되는 메시지입니다.</p>
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<button type="button" class="ghost" @click="loadData">수동 갱신</button>
|
||||
<RouterLink class="ghost" to="/nation/affairs">내무부로</RouterLink>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<p v-if="errorMessage" class="error-text">{{ errorMessage }}</p>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-header">
|
||||
<h2>임관 권유문</h2>
|
||||
<div class="panel-actions">
|
||||
<button v-if="editable && !editing" type="button" @click="startEdit">수정</button>
|
||||
<button v-if="editable && editing" type="button" @click="saveScoutMsg">저장</button>
|
||||
<button v-if="editable && editing" type="button" @click="cancelEdit">취소</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="editing" class="editor-toolbar">
|
||||
<button type="button" @click="editor?.chain().focus().toggleBold().run()" :class="{ active: editor?.isActive('bold') }">
|
||||
굵게
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
@click="editor?.chain().focus().toggleItalic().run()"
|
||||
:class="{ active: editor?.isActive('italic') }"
|
||||
>
|
||||
기울임
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
@click="editor?.chain().focus().toggleUnderline().run()"
|
||||
:class="{ active: editor?.isActive('underline') }"
|
||||
>
|
||||
밑줄
|
||||
</button>
|
||||
<button type="button" @click="addLink">링크</button>
|
||||
<button type="button" @click="editor?.chain().focus().toggleBulletList().run()">목록</button>
|
||||
<button type="button" @click="editor?.chain().focus().toggleOrderedList().run()">번호 목록</button>
|
||||
<button type="button" @click="fileInputRef?.click()" :disabled="uploadBusy">이미지 업로드</button>
|
||||
<input ref="fileInputRef" type="file" accept="image/*" class="hidden" @change="onSelectImage" />
|
||||
</div>
|
||||
|
||||
<div class="scout-editor-frame">
|
||||
<EditorContent v-if="editor" :editor="editor" />
|
||||
</div>
|
||||
<p v-if="!editable" class="hint">편집 권한은 군주/수뇌에게만 제공됩니다.</p>
|
||||
</section>
|
||||
|
||||
<div v-if="loading" class="loading">불러오는 중...</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.scout-view {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
padding: 24px;
|
||||
background: #0f1118;
|
||||
color: #e6e8ef;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.page-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
color: #9aa3b8;
|
||||
margin: 4px 0 0;
|
||||
}
|
||||
|
||||
.header-actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.ghost {
|
||||
padding: 6px 12px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #2b2f3f;
|
||||
background: #141826;
|
||||
color: #c7d0e0;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.panel {
|
||||
background: #181b26;
|
||||
border-radius: 12px;
|
||||
padding: 16px;
|
||||
border: 1px solid #23283a;
|
||||
}
|
||||
|
||||
.panel-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.scout-editor {
|
||||
min-height: 200px;
|
||||
padding: 12px;
|
||||
border-radius: 10px;
|
||||
border: 1px solid #2b2f3f;
|
||||
background: #0f1118;
|
||||
color: #f5f6fa;
|
||||
}
|
||||
|
||||
.scout-editor-frame {
|
||||
max-width: 870px;
|
||||
max-height: 200px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.editor-toolbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.editor-toolbar button {
|
||||
padding: 6px 10px;
|
||||
border-radius: 6px;
|
||||
border: 1px solid #2b2f3f;
|
||||
background: #1e2232;
|
||||
color: #d8dff0;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.editor-toolbar button.active {
|
||||
background: #3b425c;
|
||||
}
|
||||
|
||||
.hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.hint {
|
||||
color: #9aa3b8;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.error-text {
|
||||
color: #f87171;
|
||||
}
|
||||
|
||||
.loading {
|
||||
color: #9aa3b8;
|
||||
}
|
||||
</style>
|
||||
Reference in New Issue
Block a user