feat: add survey view with voting functionality and admin panel
- Implemented SurveyView.vue for displaying and managing polls, including voting, comments, and results. - Added new database tables for vote polls, votes, and comments in migration script. - Created unique lottery logic for handling unique item rewards based on voting. - Developed unit tests for unique lottery functionality to ensure deterministic behavior and correct counting of occupied unique items.
This commit is contained in:
@@ -22,6 +22,7 @@ import { diplomacyRouter } from './router/diplomacy/index.js';
|
|||||||
import { yearbookRouter } from './router/yearbook/index.js';
|
import { yearbookRouter } from './router/yearbook/index.js';
|
||||||
import { rankingRouter } from './router/ranking/index.js';
|
import { rankingRouter } from './router/ranking/index.js';
|
||||||
import { dynastyRouter } from './router/dynasty/index.js';
|
import { dynastyRouter } from './router/dynasty/index.js';
|
||||||
|
import { voteRouter } from './router/vote/index.js';
|
||||||
|
|
||||||
export const appRouter = router({
|
export const appRouter = router({
|
||||||
health: healthRouter,
|
health: healthRouter,
|
||||||
@@ -46,6 +47,7 @@ export const appRouter = router({
|
|||||||
yearbook: yearbookRouter,
|
yearbook: yearbookRouter,
|
||||||
ranking: rankingRouter,
|
ranking: rankingRouter,
|
||||||
dynasty: dynastyRouter,
|
dynasty: dynastyRouter,
|
||||||
|
vote: voteRouter,
|
||||||
});
|
});
|
||||||
|
|
||||||
export type AppRouter = typeof appRouter;
|
export type AppRouter = typeof appRouter;
|
||||||
|
|||||||
@@ -0,0 +1,675 @@
|
|||||||
|
import { TRPCError } from '@trpc/server';
|
||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
import { asRecord, LiteHashDRBG, RandUtil } from '@sammo-ts/common';
|
||||||
|
import { GamePrisma } from '@sammo-ts/infra';
|
||||||
|
import {
|
||||||
|
ITEM_KEYS,
|
||||||
|
buildVoteUniqueSeed,
|
||||||
|
countOccupiedUniqueItems,
|
||||||
|
createItemModuleRegistry,
|
||||||
|
loadItemModules,
|
||||||
|
resolveUniqueConfig,
|
||||||
|
rollUniqueLottery,
|
||||||
|
type GeneralItemSlots,
|
||||||
|
type ItemModule,
|
||||||
|
} from '@sammo-ts/logic';
|
||||||
|
|
||||||
|
import { authedProcedure, router } from '../../trpc.js';
|
||||||
|
import { getMyGeneral } from '../shared/general.js';
|
||||||
|
|
||||||
|
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}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const adminProcedure = authedProcedure.use(({ ctx, next }) => {
|
||||||
|
const roles = ctx.auth?.user.roles ?? [];
|
||||||
|
if (!hasAdminRole(roles, ctx.profile.name)) {
|
||||||
|
throw new TRPCError({ code: 'FORBIDDEN', message: 'Admin permission is required.' });
|
||||||
|
}
|
||||||
|
return next();
|
||||||
|
});
|
||||||
|
|
||||||
|
let itemRegistryPromise: Promise<Map<string, ItemModule>> | null = null;
|
||||||
|
|
||||||
|
const getItemRegistry = async (): Promise<Map<string, ItemModule>> => {
|
||||||
|
if (!itemRegistryPromise) {
|
||||||
|
itemRegistryPromise = loadItemModules([...ITEM_KEYS]).then((modules) => createItemModuleRegistry(modules));
|
||||||
|
}
|
||||||
|
return itemRegistryPromise;
|
||||||
|
};
|
||||||
|
|
||||||
|
const resolveNumber = (source: Record<string, unknown>, keys: string[], fallback: number): number => {
|
||||||
|
for (const key of keys) {
|
||||||
|
const value = source[key];
|
||||||
|
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
if (typeof value === 'string') {
|
||||||
|
const parsed = Number(value);
|
||||||
|
if (Number.isFinite(parsed)) {
|
||||||
|
return parsed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fallback;
|
||||||
|
};
|
||||||
|
|
||||||
|
const normalizeCode = (value: string | null | undefined): string | null => {
|
||||||
|
if (!value || value === 'None') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
};
|
||||||
|
|
||||||
|
const normalizeOptions = (options: string[]): string[] =>
|
||||||
|
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];
|
||||||
|
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||||
|
return Math.floor(value);
|
||||||
|
}
|
||||||
|
if (typeof value === 'string') {
|
||||||
|
const parsed = Number(value);
|
||||||
|
if (Number.isFinite(parsed)) {
|
||||||
|
return Math.floor(parsed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fallback;
|
||||||
|
};
|
||||||
|
|
||||||
|
const parseOptions = (value: unknown): string[] => {
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
return value.filter((entry): entry is string => typeof entry === 'string');
|
||||||
|
}
|
||||||
|
if (typeof value === 'string') {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(value);
|
||||||
|
if (Array.isArray(parsed)) {
|
||||||
|
return parsed.filter((entry): entry is string => typeof entry === 'string');
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [];
|
||||||
|
};
|
||||||
|
|
||||||
|
const parseSelection = (value: unknown): number[] => {
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
return value.map((entry) => Number(entry)).filter((entry) => Number.isFinite(entry));
|
||||||
|
}
|
||||||
|
if (typeof value === 'string') {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(value);
|
||||||
|
if (Array.isArray(parsed)) {
|
||||||
|
return parsed.map((entry) => Number(entry)).filter((entry) => Number.isFinite(entry));
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [];
|
||||||
|
};
|
||||||
|
|
||||||
|
type VotePollRow = {
|
||||||
|
id: number;
|
||||||
|
title: string;
|
||||||
|
body: string;
|
||||||
|
options: unknown;
|
||||||
|
multiple_options: number;
|
||||||
|
reveal_mode: string;
|
||||||
|
opener_general_id: number;
|
||||||
|
opener_name: string;
|
||||||
|
start_at: Date;
|
||||||
|
end_at: Date | null;
|
||||||
|
closed_at: Date | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
type VoteListRow = {
|
||||||
|
id: number;
|
||||||
|
title: string;
|
||||||
|
start_at: Date;
|
||||||
|
end_at: Date | null;
|
||||||
|
closed_at: Date | null;
|
||||||
|
reveal_mode: string;
|
||||||
|
multiple_options: number;
|
||||||
|
options_count: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
type VoteCommentRow = {
|
||||||
|
id: number;
|
||||||
|
vote_id: number;
|
||||||
|
general_id: number;
|
||||||
|
nation_id: number;
|
||||||
|
general_name: string;
|
||||||
|
nation_name: string;
|
||||||
|
text: string;
|
||||||
|
created_at: Date;
|
||||||
|
};
|
||||||
|
|
||||||
|
type VoteResultRow = {
|
||||||
|
selection: unknown;
|
||||||
|
cnt: number | bigint;
|
||||||
|
};
|
||||||
|
|
||||||
|
const zRevealMode = z.enum(['after_vote', 'after_end']);
|
||||||
|
|
||||||
|
export const voteRouter = router({
|
||||||
|
getVoteList: authedProcedure.query(async ({ ctx }) => {
|
||||||
|
const worldState = await ctx.db.worldState.findFirst();
|
||||||
|
const config = asRecord(worldState?.config ?? {});
|
||||||
|
const constValues = asRecord(config.const);
|
||||||
|
const develCost = resolveNumber(constValues, ['develCost', 'develcost', 'develrate'], 0);
|
||||||
|
const voteReward = develCost * 5;
|
||||||
|
|
||||||
|
const rows = await ctx.db.$queryRaw<VoteListRow[]>(GamePrisma.sql`
|
||||||
|
SELECT
|
||||||
|
id,
|
||||||
|
title,
|
||||||
|
start_at,
|
||||||
|
end_at,
|
||||||
|
closed_at,
|
||||||
|
reveal_mode,
|
||||||
|
multiple_options,
|
||||||
|
jsonb_array_length(options) AS options_count
|
||||||
|
FROM vote_poll
|
||||||
|
ORDER BY id DESC
|
||||||
|
`);
|
||||||
|
|
||||||
|
const polls = rows.map((row) => ({
|
||||||
|
id: row.id,
|
||||||
|
title: row.title,
|
||||||
|
startAt: row.start_at.toISOString(),
|
||||||
|
endAt: row.end_at ? row.end_at.toISOString() : null,
|
||||||
|
closedAt: row.closed_at ? row.closed_at.toISOString() : null,
|
||||||
|
revealMode: row.reveal_mode as 'after_vote' | 'after_end',
|
||||||
|
optionsCount: Number(row.options_count ?? 0),
|
||||||
|
multipleOptions: row.multiple_options,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return { polls, voteReward };
|
||||||
|
}),
|
||||||
|
getVoteDetail: authedProcedure
|
||||||
|
.input(z.object({ voteId: z.number().int().positive() }))
|
||||||
|
.query(async ({ ctx, input }) => {
|
||||||
|
const rows = await ctx.db.$queryRaw<VotePollRow[]>(GamePrisma.sql`
|
||||||
|
SELECT
|
||||||
|
id,
|
||||||
|
title,
|
||||||
|
body,
|
||||||
|
options,
|
||||||
|
multiple_options,
|
||||||
|
reveal_mode,
|
||||||
|
opener_general_id,
|
||||||
|
opener_name,
|
||||||
|
start_at,
|
||||||
|
end_at,
|
||||||
|
closed_at
|
||||||
|
FROM vote_poll
|
||||||
|
WHERE id = ${input.voteId}
|
||||||
|
LIMIT 1
|
||||||
|
`);
|
||||||
|
const row = rows[0];
|
||||||
|
if (!row) {
|
||||||
|
throw new TRPCError({ code: 'NOT_FOUND', message: '설문조사가 없습니다.' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const options = parseOptions(row.options);
|
||||||
|
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 [comments, userCnt, myVoteRow] = await Promise.all([
|
||||||
|
ctx.db.$queryRaw<VoteCommentRow[]>(GamePrisma.sql`
|
||||||
|
SELECT
|
||||||
|
id,
|
||||||
|
vote_id,
|
||||||
|
general_id,
|
||||||
|
nation_id,
|
||||||
|
general_name,
|
||||||
|
nation_name,
|
||||||
|
text,
|
||||||
|
created_at
|
||||||
|
FROM vote_comment
|
||||||
|
WHERE vote_id = ${input.voteId}
|
||||||
|
ORDER BY created_at ASC
|
||||||
|
`),
|
||||||
|
ctx.db.general.count({ where: { npcState: { lt: 2 } } }),
|
||||||
|
general
|
||||||
|
? ctx.db.$queryRaw<Array<{ selection: unknown }>>(GamePrisma.sql`
|
||||||
|
SELECT selection
|
||||||
|
FROM vote
|
||||||
|
WHERE vote_id = ${input.voteId} AND general_id = ${general.id}
|
||||||
|
LIMIT 1
|
||||||
|
`)
|
||||||
|
: Promise.resolve([]),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const myVote = myVoteRow[0]?.selection ? parseSelection(myVoteRow[0].selection) : null;
|
||||||
|
|
||||||
|
const canReveal = row.reveal_mode === 'after_vote'
|
||||||
|
? Boolean(myVote) || pollEnded
|
||||||
|
: pollEnded;
|
||||||
|
|
||||||
|
const voteResults = canReveal
|
||||||
|
? await ctx.db.$queryRaw<VoteResultRow[]>(GamePrisma.sql`
|
||||||
|
SELECT selection, count(*) as cnt
|
||||||
|
FROM vote
|
||||||
|
WHERE vote_id = ${input.voteId}
|
||||||
|
GROUP BY selection
|
||||||
|
`)
|
||||||
|
: [];
|
||||||
|
|
||||||
|
const votes = voteResults.map((entry) => ({
|
||||||
|
selection: parseSelection(entry.selection),
|
||||||
|
count: Number(entry.cnt),
|
||||||
|
}));
|
||||||
|
|
||||||
|
return {
|
||||||
|
voteInfo: {
|
||||||
|
id: row.id,
|
||||||
|
title: row.title,
|
||||||
|
body: row.body,
|
||||||
|
options,
|
||||||
|
multipleOptions: row.multiple_options,
|
||||||
|
revealMode: row.reveal_mode as 'after_vote' | 'after_end',
|
||||||
|
openerGeneralId: row.opener_general_id,
|
||||||
|
openerName: row.opener_name,
|
||||||
|
startAt: row.start_at.toISOString(),
|
||||||
|
endAt: row.end_at ? row.end_at.toISOString() : null,
|
||||||
|
closedAt: row.closed_at ? row.closed_at.toISOString() : null,
|
||||||
|
},
|
||||||
|
votes,
|
||||||
|
comments: comments.map((comment) => ({
|
||||||
|
id: comment.id,
|
||||||
|
voteId: comment.vote_id,
|
||||||
|
generalId: comment.general_id,
|
||||||
|
nationId: comment.nation_id,
|
||||||
|
generalName: comment.general_name,
|
||||||
|
nationName: comment.nation_name,
|
||||||
|
text: comment.text,
|
||||||
|
createdAt: comment.created_at.toISOString(),
|
||||||
|
})),
|
||||||
|
myVote,
|
||||||
|
userCnt,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
submitVote: authedProcedure
|
||||||
|
.input(
|
||||||
|
z.object({
|
||||||
|
voteId: z.number().int().positive(),
|
||||||
|
selection: z.array(z.number().int()),
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.mutation(async ({ ctx, input }) => {
|
||||||
|
const selection = input.selection;
|
||||||
|
if (!selection || selection.length === 0) {
|
||||||
|
throw new TRPCError({ code: 'BAD_REQUEST', message: '선택한 항목이 없습니다.' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const pollRows = await ctx.db.$queryRaw<VotePollRow[]>(GamePrisma.sql`
|
||||||
|
SELECT
|
||||||
|
id,
|
||||||
|
title,
|
||||||
|
body,
|
||||||
|
options,
|
||||||
|
multiple_options,
|
||||||
|
reveal_mode,
|
||||||
|
opener_general_id,
|
||||||
|
opener_name,
|
||||||
|
start_at,
|
||||||
|
end_at,
|
||||||
|
closed_at
|
||||||
|
FROM vote_poll
|
||||||
|
WHERE id = ${input.voteId}
|
||||||
|
LIMIT 1
|
||||||
|
`);
|
||||||
|
const poll = pollRows[0];
|
||||||
|
if (!poll) {
|
||||||
|
throw new TRPCError({ code: 'NOT_FOUND', message: '설문조사가 없습니다.' });
|
||||||
|
}
|
||||||
|
if (poll.closed_at || (poll.end_at && poll.end_at < new Date())) {
|
||||||
|
throw new TRPCError({ code: 'BAD_REQUEST', message: '설문조사가 종료되었습니다.' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const options = parseOptions(poll.options);
|
||||||
|
if (poll.multiple_options >= 1 && selection.length > poll.multiple_options) {
|
||||||
|
throw new TRPCError({ code: 'BAD_REQUEST', message: '선택한 항목이 너무 많습니다.' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const optionCount = options.length;
|
||||||
|
for (const value of selection) {
|
||||||
|
if (!Number.isFinite(value) || value < 0 || value >= optionCount) {
|
||||||
|
throw new TRPCError({ code: 'BAD_REQUEST', message: '선택한 항목이 없습니다.' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const sortedSelection = [...selection].sort((a, b) => a - b);
|
||||||
|
const general = await getMyGeneral(ctx);
|
||||||
|
|
||||||
|
const rows = await ctx.db.$queryRaw<Array<{ id: number }>>(GamePrisma.sql`
|
||||||
|
INSERT INTO vote (vote_id, general_id, nation_id, selection)
|
||||||
|
VALUES (
|
||||||
|
${input.voteId},
|
||||||
|
${general.id},
|
||||||
|
${general.nationId},
|
||||||
|
CAST(${JSON.stringify(sortedSelection)} AS jsonb)
|
||||||
|
)
|
||||||
|
ON CONFLICT (vote_id, general_id) DO NOTHING
|
||||||
|
RETURNING id
|
||||||
|
`);
|
||||||
|
|
||||||
|
if (!rows[0]?.id) {
|
||||||
|
throw new TRPCError({ code: 'BAD_REQUEST', message: '이미 설문조사를 완료하였습니다.' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const worldState = await ctx.db.worldState.findFirst();
|
||||||
|
if (!worldState) {
|
||||||
|
throw new TRPCError({ code: 'PRECONDITION_FAILED', message: 'World state is not initialized.' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const config = asRecord(worldState.config);
|
||||||
|
const constValues = asRecord(config.const);
|
||||||
|
const develCost = resolveNumber(constValues, ['develCost', 'develcost', 'develrate'], 0);
|
||||||
|
const voteReward = develCost * 5;
|
||||||
|
|
||||||
|
const worldMeta = asRecord(worldState.meta);
|
||||||
|
const scenarioMeta = asRecord(worldMeta.scenarioMeta);
|
||||||
|
const startYear = readMetaNumber(scenarioMeta, 'startYear', worldState.currentYear);
|
||||||
|
const initYear = readMetaNumber(worldMeta, 'initYear', startYear);
|
||||||
|
const initMonth = readMetaNumber(worldMeta, 'initMonth', 1);
|
||||||
|
const scenarioId = readMetaNumber(worldMeta, 'scenarioId', 0);
|
||||||
|
const hiddenSeed = worldMeta.hiddenSeed ?? worldMeta.seed ?? worldState.id;
|
||||||
|
|
||||||
|
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 generalItems: GeneralItemSlots[] = generalRows.map((row) => ({
|
||||||
|
horse: normalizeCode(row.horseCode),
|
||||||
|
weapon: normalizeCode(row.weaponCode),
|
||||||
|
book: normalizeCode(row.bookCode),
|
||||||
|
item: normalizeCode(row.itemCode),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const occupiedUniqueCounts = countOccupiedUniqueItems(generalItems, itemRegistry);
|
||||||
|
const userCount = await ctx.db.general.count({ where: { npcState: { lt: 2 } } });
|
||||||
|
|
||||||
|
const rngSeed = buildVoteUniqueSeed(
|
||||||
|
typeof hiddenSeed === 'string' || typeof hiddenSeed === 'number' ? hiddenSeed : String(hiddenSeed),
|
||||||
|
input.voteId,
|
||||||
|
general.id
|
||||||
|
);
|
||||||
|
const rng = new RandUtil(LiteHashDRBG.build(rngSeed));
|
||||||
|
const itemKey = rollUniqueLottery({
|
||||||
|
rng,
|
||||||
|
config: uniqueConfig,
|
||||||
|
itemRegistry,
|
||||||
|
generalItems: {
|
||||||
|
horse: normalizeCode(general.horseCode),
|
||||||
|
weapon: normalizeCode(general.weaponCode),
|
||||||
|
book: normalizeCode(general.bookCode),
|
||||||
|
item: normalizeCode(general.itemCode),
|
||||||
|
},
|
||||||
|
occupiedUniqueCounts,
|
||||||
|
scenarioId,
|
||||||
|
userCount,
|
||||||
|
currentYear: worldState.currentYear,
|
||||||
|
currentMonth: worldState.currentMonth,
|
||||||
|
startYear,
|
||||||
|
initYear,
|
||||||
|
initMonth,
|
||||||
|
acquireType: '설문조사',
|
||||||
|
});
|
||||||
|
|
||||||
|
const rewardResult = await ctx.turnDaemon.requestCommand({
|
||||||
|
type: 'voteReward',
|
||||||
|
voteId: input.voteId,
|
||||||
|
generalId: general.id,
|
||||||
|
goldReward: voteReward,
|
||||||
|
unique: {
|
||||||
|
expected: Boolean(itemKey),
|
||||||
|
itemKey: itemKey ?? null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!rewardResult || rewardResult.type !== 'voteReward') {
|
||||||
|
throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR', message: 'Unexpected response' });
|
||||||
|
}
|
||||||
|
if (!rewardResult.ok) {
|
||||||
|
throw new TRPCError({ code: 'BAD_REQUEST', message: rewardResult.reason });
|
||||||
|
}
|
||||||
|
|
||||||
|
return { ok: true, wonLottery: rewardResult.awardedUnique };
|
||||||
|
}),
|
||||||
|
addComment: authedProcedure
|
||||||
|
.input(
|
||||||
|
z.object({
|
||||||
|
voteId: z.number().int().positive(),
|
||||||
|
text: z.string().trim().max(200),
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.mutation(async ({ ctx, input }) => {
|
||||||
|
if (!input.text) {
|
||||||
|
throw new TRPCError({ code: 'BAD_REQUEST', message: '내용이 필요합니다.' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const pollRows = await ctx.db.$queryRaw<Array<{ id: number }>>(GamePrisma.sql`
|
||||||
|
SELECT id
|
||||||
|
FROM vote_poll
|
||||||
|
WHERE id = ${input.voteId}
|
||||||
|
LIMIT 1
|
||||||
|
`);
|
||||||
|
if (!pollRows[0]?.id) {
|
||||||
|
throw new TRPCError({ code: 'NOT_FOUND', message: '설문조사가 없습니다.' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const general = await getMyGeneral(ctx);
|
||||||
|
const nation = general.nationId
|
||||||
|
? await ctx.db.nation.findFirst({ where: { id: general.nationId }, select: { name: true } })
|
||||||
|
: null;
|
||||||
|
const nationName = nation?.name ?? '재야';
|
||||||
|
|
||||||
|
await ctx.db.$queryRaw(GamePrisma.sql`
|
||||||
|
INSERT INTO vote_comment (vote_id, general_id, nation_id, general_name, nation_name, text)
|
||||||
|
VALUES (${input.voteId}, ${general.id}, ${general.nationId}, ${general.name}, ${nationName}, ${input.text})
|
||||||
|
`);
|
||||||
|
|
||||||
|
return { ok: true };
|
||||||
|
}),
|
||||||
|
createPoll: adminProcedure
|
||||||
|
.input(
|
||||||
|
z.object({
|
||||||
|
title: z.string().trim().min(1).max(200),
|
||||||
|
body: z.string().trim().max(5000).optional().default(''),
|
||||||
|
options: z.array(z.string()).default([]),
|
||||||
|
multipleOptions: z.number().int().optional().default(1),
|
||||||
|
endAt: z.string().optional(),
|
||||||
|
revealMode: zRevealMode,
|
||||||
|
closePrevious: z.boolean().optional().default(true),
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.mutation(async ({ ctx, input }) => {
|
||||||
|
const general = await getMyGeneral(ctx);
|
||||||
|
const options = normalizeOptions(input.options);
|
||||||
|
if (options.length === 0) {
|
||||||
|
throw new TRPCError({ code: 'BAD_REQUEST', message: '항목이 없습니다.' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const endAt = input.endAt ? new Date(input.endAt) : null;
|
||||||
|
if (endAt && Number.isNaN(endAt.getTime())) {
|
||||||
|
throw new TRPCError({ code: 'BAD_REQUEST', message: '종료일이 잘못되었습니다.' });
|
||||||
|
}
|
||||||
|
if (endAt && endAt < new Date()) {
|
||||||
|
throw new TRPCError({ code: 'BAD_REQUEST', message: '종료일이 이미 지났습니다.' });
|
||||||
|
}
|
||||||
|
|
||||||
|
let multipleOptions = input.multipleOptions;
|
||||||
|
if (multipleOptions < 0) {
|
||||||
|
multipleOptions = 0;
|
||||||
|
}
|
||||||
|
if (multipleOptions > options.length) {
|
||||||
|
multipleOptions = options.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.closePrevious) {
|
||||||
|
await ctx.db.$queryRaw(GamePrisma.sql`
|
||||||
|
UPDATE vote_poll
|
||||||
|
SET closed_at = NOW(), updated_at = NOW()
|
||||||
|
WHERE closed_at IS NULL
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
|
||||||
|
await ctx.db.$queryRaw(GamePrisma.sql`
|
||||||
|
INSERT INTO vote_poll (
|
||||||
|
title,
|
||||||
|
body,
|
||||||
|
options,
|
||||||
|
multiple_options,
|
||||||
|
reveal_mode,
|
||||||
|
opener_general_id,
|
||||||
|
opener_name,
|
||||||
|
start_at,
|
||||||
|
end_at
|
||||||
|
)
|
||||||
|
VALUES (
|
||||||
|
${input.title},
|
||||||
|
${input.body ?? ''},
|
||||||
|
CAST(${JSON.stringify(options)} AS jsonb),
|
||||||
|
${multipleOptions},
|
||||||
|
${input.revealMode},
|
||||||
|
${general.id},
|
||||||
|
${general.name},
|
||||||
|
NOW(),
|
||||||
|
${endAt}
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
return { ok: true };
|
||||||
|
}),
|
||||||
|
updatePoll: adminProcedure
|
||||||
|
.input(
|
||||||
|
z.object({
|
||||||
|
voteId: z.number().int().positive(),
|
||||||
|
title: z.string().trim().min(1).max(200).optional(),
|
||||||
|
body: z.string().trim().max(5000).optional(),
|
||||||
|
appendOptions: z.array(z.string()).optional(),
|
||||||
|
multipleOptions: z.number().int().optional(),
|
||||||
|
endAt: z.string().optional(),
|
||||||
|
revealMode: zRevealMode.optional(),
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.mutation(async ({ ctx, input }) => {
|
||||||
|
const pollRows = await ctx.db.$queryRaw<VotePollRow[]>(GamePrisma.sql`
|
||||||
|
SELECT
|
||||||
|
id,
|
||||||
|
title,
|
||||||
|
body,
|
||||||
|
options,
|
||||||
|
multiple_options,
|
||||||
|
reveal_mode,
|
||||||
|
opener_general_id,
|
||||||
|
opener_name,
|
||||||
|
start_at,
|
||||||
|
end_at,
|
||||||
|
closed_at
|
||||||
|
FROM vote_poll
|
||||||
|
WHERE id = ${input.voteId}
|
||||||
|
LIMIT 1
|
||||||
|
`);
|
||||||
|
const poll = pollRows[0];
|
||||||
|
if (!poll) {
|
||||||
|
throw new TRPCError({ code: 'NOT_FOUND', message: '설문조사가 없습니다.' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const voteCountRow = await ctx.db.$queryRaw<Array<{ cnt: number }>>(GamePrisma.sql`
|
||||||
|
SELECT count(*) as cnt
|
||||||
|
FROM vote
|
||||||
|
WHERE vote_id = ${input.voteId}
|
||||||
|
`);
|
||||||
|
const voteCount = Number(voteCountRow[0]?.cnt ?? 0);
|
||||||
|
if (voteCount > 0) {
|
||||||
|
throw new TRPCError({ code: 'BAD_REQUEST', message: '이미 설문조사가 진행중입니다.' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const existingOptions = parseOptions(poll.options);
|
||||||
|
const appendedOptions = normalizeOptions(input.appendOptions ?? []);
|
||||||
|
const nextOptions = appendedOptions.length > 0 ? [...existingOptions, ...appendedOptions] : existingOptions;
|
||||||
|
|
||||||
|
let nextMultipleOptions = input.multipleOptions;
|
||||||
|
if (nextMultipleOptions !== undefined) {
|
||||||
|
if (nextMultipleOptions < 0) {
|
||||||
|
nextMultipleOptions = 0;
|
||||||
|
}
|
||||||
|
if (nextMultipleOptions > nextOptions.length) {
|
||||||
|
nextMultipleOptions = nextOptions.length;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const endAt = input.endAt ? new Date(input.endAt) : undefined;
|
||||||
|
if (endAt && Number.isNaN(endAt.getTime())) {
|
||||||
|
throw new TRPCError({ code: 'BAD_REQUEST', message: '종료일이 잘못되었습니다.' });
|
||||||
|
}
|
||||||
|
if (endAt && endAt < new Date()) {
|
||||||
|
throw new TRPCError({ code: 'BAD_REQUEST', message: '종료일이 이미 지났습니다.' });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
input.title === undefined &&
|
||||||
|
input.body === undefined &&
|
||||||
|
appendedOptions.length === 0 &&
|
||||||
|
nextMultipleOptions === undefined &&
|
||||||
|
endAt === undefined &&
|
||||||
|
input.revealMode === undefined
|
||||||
|
) {
|
||||||
|
throw new TRPCError({ code: 'BAD_REQUEST', message: '변경할 항목이 없습니다.' });
|
||||||
|
}
|
||||||
|
|
||||||
|
await ctx.db.$queryRaw(GamePrisma.sql`
|
||||||
|
UPDATE vote_poll
|
||||||
|
SET
|
||||||
|
title = COALESCE(${input.title}, title),
|
||||||
|
body = COALESCE(${input.body}, body),
|
||||||
|
options = ${appendedOptions.length > 0 ? GamePrisma.sql`CAST(${JSON.stringify(nextOptions)} AS jsonb)` : GamePrisma.sql`options`},
|
||||||
|
multiple_options = COALESCE(${nextMultipleOptions}, multiple_options),
|
||||||
|
reveal_mode = COALESCE(${input.revealMode}, reveal_mode),
|
||||||
|
end_at = ${endAt ?? poll.end_at},
|
||||||
|
updated_at = NOW()
|
||||||
|
WHERE id = ${input.voteId}
|
||||||
|
`);
|
||||||
|
|
||||||
|
return { ok: true };
|
||||||
|
}),
|
||||||
|
closePoll: adminProcedure
|
||||||
|
.input(z.object({ voteId: z.number().int().positive() }))
|
||||||
|
.mutation(async ({ ctx, input }) => {
|
||||||
|
const rows = await ctx.db.$queryRaw<Array<{ id: number }>>(GamePrisma.sql`
|
||||||
|
UPDATE vote_poll
|
||||||
|
SET closed_at = NOW(), updated_at = NOW()
|
||||||
|
WHERE id = ${input.voteId}
|
||||||
|
RETURNING id
|
||||||
|
`);
|
||||||
|
if (!rows[0]?.id) {
|
||||||
|
throw new TRPCError({ code: 'NOT_FOUND', message: '설문조사가 없습니다.' });
|
||||||
|
}
|
||||||
|
return { ok: true };
|
||||||
|
}),
|
||||||
|
getAdminStatus: adminProcedure.query(async () => ({ ok: true })),
|
||||||
|
});
|
||||||
@@ -141,6 +141,19 @@ const zTournamentReward = z.object({
|
|||||||
top4: z.array(zFiniteNumber),
|
top4: z.array(zFiniteNumber),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const zVoteReward = z.object({
|
||||||
|
type: z.literal('voteReward'),
|
||||||
|
voteId: zFiniteNumber,
|
||||||
|
generalId: zFiniteNumber,
|
||||||
|
goldReward: zFiniteNumber,
|
||||||
|
unique: z
|
||||||
|
.object({
|
||||||
|
expected: z.boolean(),
|
||||||
|
itemKey: z.string().nullable().optional(),
|
||||||
|
})
|
||||||
|
.optional(),
|
||||||
|
});
|
||||||
|
|
||||||
const zSetNationMeta = z.object({
|
const zSetNationMeta = z.object({
|
||||||
type: z.literal('setNationMeta'),
|
type: z.literal('setNationMeta'),
|
||||||
nationId: zFiniteNumber,
|
nationId: zFiniteNumber,
|
||||||
@@ -358,6 +371,14 @@ const normalizeTournamentReward: CommandNormalizer<'tournamentReward'> = (envelo
|
|||||||
return { ...command, requestId: envelope.requestId };
|
return { ...command, requestId: envelope.requestId };
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const normalizeVoteReward: CommandNormalizer<'voteReward'> = (envelope) => {
|
||||||
|
const command = parseWith(zVoteReward, envelope.command);
|
||||||
|
if (!command) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return { ...command, requestId: envelope.requestId };
|
||||||
|
};
|
||||||
|
|
||||||
const normalizeSetNationMeta: CommandNormalizer<'setNationMeta'> = (envelope) => {
|
const normalizeSetNationMeta: CommandNormalizer<'setNationMeta'> = (envelope) => {
|
||||||
const command = parseWith(zSetNationMeta, envelope.command);
|
const command = parseWith(zSetNationMeta, envelope.command);
|
||||||
if (!command) {
|
if (!command) {
|
||||||
@@ -431,6 +452,7 @@ const normalizers: CommandNormalizerMap = {
|
|||||||
tournamentRefund: normalizeTournamentRefund,
|
tournamentRefund: normalizeTournamentRefund,
|
||||||
tournamentBettingPayout: normalizeTournamentBettingPayout,
|
tournamentBettingPayout: normalizeTournamentBettingPayout,
|
||||||
tournamentReward: normalizeTournamentReward,
|
tournamentReward: normalizeTournamentReward,
|
||||||
|
voteReward: normalizeVoteReward,
|
||||||
setNationMeta: normalizeSetNationMeta,
|
setNationMeta: normalizeSetNationMeta,
|
||||||
adjustGeneralResources: normalizeAdjustGeneralResources,
|
adjustGeneralResources: normalizeAdjustGeneralResources,
|
||||||
adjustGeneralMeta: normalizeAdjustGeneralMeta,
|
adjustGeneralMeta: normalizeAdjustGeneralMeta,
|
||||||
|
|||||||
@@ -5,6 +5,21 @@ import type {
|
|||||||
TurnDaemonCommandResult,
|
TurnDaemonCommandResult,
|
||||||
TurnRunResult,
|
TurnRunResult,
|
||||||
} from '../lifecycle/types.js';
|
} from '../lifecycle/types.js';
|
||||||
|
import { asRecord, JosaUtil, LiteHashDRBG, RandUtil } from '@sammo-ts/common';
|
||||||
|
import {
|
||||||
|
LogCategory,
|
||||||
|
LogFormat,
|
||||||
|
LogScope,
|
||||||
|
ITEM_KEYS,
|
||||||
|
buildVoteUniqueSeed,
|
||||||
|
countOccupiedUniqueItems,
|
||||||
|
createItemModuleRegistry,
|
||||||
|
loadItemModules,
|
||||||
|
resolveUniqueConfig,
|
||||||
|
rollUniqueLottery,
|
||||||
|
type ItemModule,
|
||||||
|
type TriggerValue,
|
||||||
|
} from '@sammo-ts/logic';
|
||||||
import type { InMemoryTurnWorld } from './inMemoryWorld.js';
|
import type { InMemoryTurnWorld } from './inMemoryWorld.js';
|
||||||
import type { TurnGeneral } from './types.js';
|
import type { TurnGeneral } from './types.js';
|
||||||
|
|
||||||
@@ -27,6 +42,29 @@ const flushWorld = async (world: InMemoryTurnWorld, hooks?: TurnDaemonHooks): Pr
|
|||||||
await hooks.flushChanges(buildFlushResult(world));
|
await hooks.flushChanges(buildFlushResult(world));
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let itemRegistryPromise: Promise<Map<string, ItemModule>> | null = null;
|
||||||
|
|
||||||
|
const getItemRegistry = async (): Promise<Map<string, ItemModule>> => {
|
||||||
|
if (!itemRegistryPromise) {
|
||||||
|
itemRegistryPromise = loadItemModules([...ITEM_KEYS]).then((modules) => createItemModuleRegistry(modules));
|
||||||
|
}
|
||||||
|
return itemRegistryPromise;
|
||||||
|
};
|
||||||
|
|
||||||
|
const readMetaNumber = (meta: Record<string, unknown>, key: string, fallback: number): number => {
|
||||||
|
const value = meta[key];
|
||||||
|
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||||
|
return Math.floor(value);
|
||||||
|
}
|
||||||
|
if (typeof value === 'string') {
|
||||||
|
const parsed = Number(value);
|
||||||
|
if (Number.isFinite(parsed)) {
|
||||||
|
return Math.floor(parsed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fallback;
|
||||||
|
};
|
||||||
|
|
||||||
interface CommandHandlerContext {
|
interface CommandHandlerContext {
|
||||||
world: InMemoryTurnWorld;
|
world: InMemoryTurnWorld;
|
||||||
hooks?: TurnDaemonHooks;
|
hooks?: TurnDaemonHooks;
|
||||||
@@ -925,6 +963,207 @@ async function handleTournamentReward(
|
|||||||
return ctx.tournamentRewardFinalizer.finalize(command);
|
return ctx.tournamentRewardFinalizer.finalize(command);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 설문 보상은 API에서 전달된 RNG 결과를 재검증한 뒤 월드에 반영한다.
|
||||||
|
async function handleVoteReward(
|
||||||
|
ctx: CommandHandlerContext,
|
||||||
|
command: Extract<TurnDaemonCommand, { type: 'voteReward' }>
|
||||||
|
): Promise<TurnDaemonCommandResult> {
|
||||||
|
const { world, hooks } = ctx;
|
||||||
|
const general = world.getGeneralById(command.generalId);
|
||||||
|
if (!general) {
|
||||||
|
return {
|
||||||
|
type: 'voteReward',
|
||||||
|
ok: false,
|
||||||
|
voteId: command.voteId,
|
||||||
|
generalId: command.generalId,
|
||||||
|
reason: '장수 정보를 찾을 수 없습니다.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const baseMeta = general.meta;
|
||||||
|
const metaRecord = asRecord(baseMeta);
|
||||||
|
const existingRewards = asRecord(metaRecord.voteRewards);
|
||||||
|
const rewardKey = String(command.voteId);
|
||||||
|
if (Object.prototype.hasOwnProperty.call(existingRewards, rewardKey)) {
|
||||||
|
const existingValue = existingRewards[rewardKey];
|
||||||
|
const existingEntry = asRecord(existingValue);
|
||||||
|
const existingItemKey = typeof existingEntry.itemKey === 'string' ? existingEntry.itemKey : null;
|
||||||
|
const awarded = existingEntry.awarded === true || Boolean(existingItemKey);
|
||||||
|
return {
|
||||||
|
type: 'voteReward',
|
||||||
|
ok: true,
|
||||||
|
voteId: command.voteId,
|
||||||
|
generalId: command.generalId,
|
||||||
|
awardedUnique: awarded,
|
||||||
|
itemKey: existingItemKey ?? null,
|
||||||
|
alreadyApplied: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const worldState = world.getState();
|
||||||
|
const worldMeta = asRecord(worldState.meta);
|
||||||
|
const scenarioMeta = asRecord(worldMeta.scenarioMeta);
|
||||||
|
const startYear = readMetaNumber(scenarioMeta, 'startYear', worldState.currentYear);
|
||||||
|
const initYear = readMetaNumber(worldMeta, 'initYear', startYear);
|
||||||
|
const initMonth = readMetaNumber(worldMeta, 'initMonth', 1);
|
||||||
|
const scenarioId = readMetaNumber(worldMeta, 'scenarioId', 0);
|
||||||
|
const hiddenSeed = worldMeta.hiddenSeed ?? worldMeta.seed ?? worldState.id;
|
||||||
|
|
||||||
|
const itemRegistry = await getItemRegistry();
|
||||||
|
const configConst = asRecord(world.getScenarioConfig().const);
|
||||||
|
const uniqueConfig = resolveUniqueConfig(configConst);
|
||||||
|
const generals = world.listGenerals();
|
||||||
|
const occupiedUniqueCounts = countOccupiedUniqueItems(
|
||||||
|
generals.map((entry) => entry.role.items),
|
||||||
|
itemRegistry
|
||||||
|
);
|
||||||
|
const userCount = generals.filter((entry) => entry.npcState < 2).length;
|
||||||
|
const rngSeed = buildVoteUniqueSeed(
|
||||||
|
typeof hiddenSeed === 'string' || typeof hiddenSeed === 'number' ? hiddenSeed : String(hiddenSeed),
|
||||||
|
command.voteId,
|
||||||
|
command.generalId
|
||||||
|
);
|
||||||
|
const rng = new RandUtil(LiteHashDRBG.build(rngSeed));
|
||||||
|
const itemKey = rollUniqueLottery({
|
||||||
|
rng,
|
||||||
|
config: uniqueConfig,
|
||||||
|
itemRegistry,
|
||||||
|
generalItems: general.role.items,
|
||||||
|
occupiedUniqueCounts,
|
||||||
|
scenarioId,
|
||||||
|
userCount,
|
||||||
|
currentYear: worldState.currentYear,
|
||||||
|
currentMonth: worldState.currentMonth,
|
||||||
|
startYear,
|
||||||
|
initYear,
|
||||||
|
initMonth,
|
||||||
|
acquireType: '설문조사',
|
||||||
|
});
|
||||||
|
|
||||||
|
const expectedUnique = command.unique?.expected ?? false;
|
||||||
|
const expectedItemKey = command.unique?.itemKey ?? null;
|
||||||
|
if (expectedUnique !== Boolean(itemKey)) {
|
||||||
|
return {
|
||||||
|
type: 'voteReward',
|
||||||
|
ok: false,
|
||||||
|
voteId: command.voteId,
|
||||||
|
generalId: command.generalId,
|
||||||
|
reason: '유니크 판정이 일치하지 않습니다.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (expectedUnique) {
|
||||||
|
if (!expectedItemKey || !itemKey || expectedItemKey !== itemKey) {
|
||||||
|
return {
|
||||||
|
type: 'voteReward',
|
||||||
|
ok: false,
|
||||||
|
voteId: command.voteId,
|
||||||
|
generalId: command.generalId,
|
||||||
|
reason: '유니크 판정이 일치하지 않습니다.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} else if (itemKey) {
|
||||||
|
return {
|
||||||
|
type: 'voteReward',
|
||||||
|
ok: false,
|
||||||
|
voteId: command.voteId,
|
||||||
|
generalId: command.generalId,
|
||||||
|
reason: '유니크 판정이 일치하지 않습니다.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const rewardEntry: Record<string, TriggerValue> = {
|
||||||
|
awarded: Boolean(itemKey),
|
||||||
|
at: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
if (itemKey) {
|
||||||
|
rewardEntry.itemKey = itemKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
const nextVoteRewards: Record<string, TriggerValue> = {
|
||||||
|
...(existingRewards as Record<string, TriggerValue>),
|
||||||
|
[rewardKey]: rewardEntry,
|
||||||
|
};
|
||||||
|
|
||||||
|
const nextMeta: TurnGeneral['meta'] = {
|
||||||
|
...baseMeta,
|
||||||
|
voteRewards: nextVoteRewards,
|
||||||
|
};
|
||||||
|
|
||||||
|
const patch: Partial<TurnGeneral> = {
|
||||||
|
gold: general.gold + command.goldReward,
|
||||||
|
meta: nextMeta,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (itemKey) {
|
||||||
|
const itemModule = itemRegistry.get(itemKey);
|
||||||
|
if (!itemModule) {
|
||||||
|
return {
|
||||||
|
type: 'voteReward',
|
||||||
|
ok: false,
|
||||||
|
voteId: command.voteId,
|
||||||
|
generalId: command.generalId,
|
||||||
|
reason: '유니크 아이템을 찾을 수 없습니다.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
patch.role = {
|
||||||
|
...general.role,
|
||||||
|
items: {
|
||||||
|
...general.role.items,
|
||||||
|
[itemModule.slot]: itemKey,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const nationName = world.getNationById(general.nationId)?.name ?? '재야';
|
||||||
|
const generalName = general.name;
|
||||||
|
const itemName = itemModule.name;
|
||||||
|
const itemRawName = itemModule.rawName;
|
||||||
|
const josaYi = JosaUtil.pick(generalName, '이');
|
||||||
|
const josaUl = JosaUtil.pick(itemRawName, '을');
|
||||||
|
|
||||||
|
world.pushLog({
|
||||||
|
scope: LogScope.GENERAL,
|
||||||
|
category: LogCategory.ACTION,
|
||||||
|
format: LogFormat.MONTH,
|
||||||
|
text: `<C>${itemName}</>${josaUl} 습득했습니다!`,
|
||||||
|
generalId: general.id,
|
||||||
|
meta: {},
|
||||||
|
});
|
||||||
|
world.pushLog({
|
||||||
|
scope: LogScope.GENERAL,
|
||||||
|
category: LogCategory.HISTORY,
|
||||||
|
format: LogFormat.YEAR_MONTH,
|
||||||
|
text: `<C>${itemName}</>${josaUl} 습득`,
|
||||||
|
generalId: general.id,
|
||||||
|
meta: {},
|
||||||
|
});
|
||||||
|
world.pushLog({
|
||||||
|
scope: LogScope.SYSTEM,
|
||||||
|
category: LogCategory.SUMMARY,
|
||||||
|
format: LogFormat.MONTH,
|
||||||
|
text: `<Y>${generalName}</>${josaYi} <C>${itemName}</>${josaUl} 습득했습니다!`,
|
||||||
|
meta: {},
|
||||||
|
});
|
||||||
|
world.pushLog({
|
||||||
|
scope: LogScope.SYSTEM,
|
||||||
|
category: LogCategory.HISTORY,
|
||||||
|
format: LogFormat.YEAR_MONTH,
|
||||||
|
text: `<C><b>【설문조사】</b></><D><b>${nationName}</b></>의 <Y>${generalName}</>${josaYi} <C>${itemName}</>${josaUl} 습득했습니다!`,
|
||||||
|
meta: {},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
world.updateGeneral(command.generalId, patch);
|
||||||
|
await flushWorld(world, hooks);
|
||||||
|
return {
|
||||||
|
type: 'voteReward',
|
||||||
|
ok: true,
|
||||||
|
voteId: command.voteId,
|
||||||
|
generalId: command.generalId,
|
||||||
|
awardedUnique: Boolean(itemKey),
|
||||||
|
...(itemKey ? { itemKey } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export const createTurnDaemonCommandHandler = (options: {
|
export const createTurnDaemonCommandHandler = (options: {
|
||||||
world: InMemoryTurnWorld;
|
world: InMemoryTurnWorld;
|
||||||
hooks?: TurnDaemonHooks;
|
hooks?: TurnDaemonHooks;
|
||||||
@@ -959,6 +1198,7 @@ export const createTurnDaemonCommandHandler = (options: {
|
|||||||
tournamentRefund: (command) => handleTournamentRefund(ctx, command as Extract<TurnDaemonCommand, { type: 'tournamentRefund' }>),
|
tournamentRefund: (command) => handleTournamentRefund(ctx, command as Extract<TurnDaemonCommand, { type: 'tournamentRefund' }>),
|
||||||
tournamentBettingPayout: (command) => handleTournamentBettingPayout(ctx, command as Extract<TurnDaemonCommand, { type: 'tournamentBettingPayout' }>),
|
tournamentBettingPayout: (command) => handleTournamentBettingPayout(ctx, command as Extract<TurnDaemonCommand, { type: 'tournamentBettingPayout' }>),
|
||||||
tournamentReward: (command) => handleTournamentReward(ctx, command as Extract<TurnDaemonCommand, { type: 'tournamentReward' }>),
|
tournamentReward: (command) => handleTournamentReward(ctx, command as Extract<TurnDaemonCommand, { type: 'tournamentReward' }>),
|
||||||
|
voteReward: (command) => handleVoteReward(ctx, command as Extract<TurnDaemonCommand, { type: 'voteReward' }>),
|
||||||
setNationMeta: (command) => handleSetNationMeta(ctx, command as Extract<TurnDaemonCommand, { type: 'setNationMeta' }>),
|
setNationMeta: (command) => handleSetNationMeta(ctx, command as Extract<TurnDaemonCommand, { type: 'setNationMeta' }>),
|
||||||
adjustGeneralResources: (command) => handleAdjustGeneralResources(ctx, command as Extract<TurnDaemonCommand, { type: 'adjustGeneralResources' }>),
|
adjustGeneralResources: (command) => handleAdjustGeneralResources(ctx, command as Extract<TurnDaemonCommand, { type: 'adjustGeneralResources' }>),
|
||||||
adjustGeneralMeta: (command) => handleAdjustGeneralMeta(ctx, command as Extract<TurnDaemonCommand, { type: 'adjustGeneralMeta' }>),
|
adjustGeneralMeta: (command) => handleAdjustGeneralMeta(ctx, command as Extract<TurnDaemonCommand, { type: 'adjustGeneralMeta' }>),
|
||||||
|
|||||||
@@ -0,0 +1,217 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
|
||||||
|
import { LiteHashDRBG, RandUtil } from '@sammo-ts/common';
|
||||||
|
import {
|
||||||
|
ITEM_KEYS,
|
||||||
|
buildVoteUniqueSeed,
|
||||||
|
countOccupiedUniqueItems,
|
||||||
|
createItemModuleRegistry,
|
||||||
|
loadItemModules,
|
||||||
|
resolveUniqueConfig,
|
||||||
|
rollUniqueLottery,
|
||||||
|
} from '@sammo-ts/logic';
|
||||||
|
|
||||||
|
import { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js';
|
||||||
|
import type { TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js';
|
||||||
|
import { createTurnDaemonCommandHandler } from '../src/turn/worldCommandHandler.js';
|
||||||
|
|
||||||
|
const buildGeneral = (id: number): TurnGeneral => ({
|
||||||
|
id,
|
||||||
|
name: `General_${id}`,
|
||||||
|
nationId: 1,
|
||||||
|
cityId: 1,
|
||||||
|
troopId: 0,
|
||||||
|
stats: { leadership: 50, strength: 50, intelligence: 50 },
|
||||||
|
turnTime: new Date('0180-01-01T00:00:00Z'),
|
||||||
|
role: {
|
||||||
|
items: { horse: null, weapon: null, book: null, item: null },
|
||||||
|
personality: null,
|
||||||
|
specialDomestic: null,
|
||||||
|
specialWar: null,
|
||||||
|
},
|
||||||
|
triggerState: { flags: {}, counters: {}, modifiers: {}, meta: {} },
|
||||||
|
meta: { killturn: 24 },
|
||||||
|
officerLevel: 1,
|
||||||
|
experience: 0,
|
||||||
|
dedication: 0,
|
||||||
|
injury: 0,
|
||||||
|
gold: 1000,
|
||||||
|
rice: 1000,
|
||||||
|
crew: 0,
|
||||||
|
crewTypeId: 0,
|
||||||
|
train: 0,
|
||||||
|
atmos: 0,
|
||||||
|
age: 30,
|
||||||
|
npcState: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('voteReward command', () => {
|
||||||
|
it('applies gold, unique item, logs, and idempotency', async () => {
|
||||||
|
const generals = [buildGeneral(1)];
|
||||||
|
const snapshot: TurnWorldSnapshot = {
|
||||||
|
generals: generals as any,
|
||||||
|
cities: [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
name: 'City_1',
|
||||||
|
nationId: 1,
|
||||||
|
viewName: 'City_1',
|
||||||
|
agriculture: 100,
|
||||||
|
agricultureMax: 2000,
|
||||||
|
commerce: 100,
|
||||||
|
commerceMax: 2000,
|
||||||
|
security: 100,
|
||||||
|
securityMax: 100,
|
||||||
|
def: 100,
|
||||||
|
defMax: 100,
|
||||||
|
wall: 100,
|
||||||
|
wallMax: 100,
|
||||||
|
pop: 10000,
|
||||||
|
popMax: 50000,
|
||||||
|
trust: 50,
|
||||||
|
supplyState: 1,
|
||||||
|
frontState: 0,
|
||||||
|
tradepoint: 0,
|
||||||
|
level: 1,
|
||||||
|
meta: {},
|
||||||
|
},
|
||||||
|
] as any,
|
||||||
|
nations: [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
name: 'TestNation',
|
||||||
|
color: '#FF0000',
|
||||||
|
capitalCityId: 1,
|
||||||
|
chiefGeneralId: 1,
|
||||||
|
gold: 10000,
|
||||||
|
rice: 10000,
|
||||||
|
power: 0,
|
||||||
|
level: 1,
|
||||||
|
typeCode: 'che_def',
|
||||||
|
meta: {},
|
||||||
|
},
|
||||||
|
] as any,
|
||||||
|
troops: [],
|
||||||
|
diplomacy: [],
|
||||||
|
events: [],
|
||||||
|
initialEvents: [],
|
||||||
|
map: {
|
||||||
|
id: 'test_map',
|
||||||
|
name: 'TestMap',
|
||||||
|
cities: [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
name: 'City_1',
|
||||||
|
level: 1,
|
||||||
|
region: 1,
|
||||||
|
position: { x: 0, y: 0 },
|
||||||
|
connections: [],
|
||||||
|
max: {} as any,
|
||||||
|
initial: {} as any,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
defaults: { trust: 50, trade: 100, supplyState: 1, frontState: 0 },
|
||||||
|
} as any,
|
||||||
|
scenarioConfig: {
|
||||||
|
stat: { total: 300, min: 10, max: 100, npcTotal: 150, npcMax: 50, npcMin: 10, chiefMin: 70 },
|
||||||
|
iconPath: '',
|
||||||
|
map: {},
|
||||||
|
const: {
|
||||||
|
allItems: {
|
||||||
|
weapon: {
|
||||||
|
che_무기_12_칠성검: 1,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
maxUniqueItemLimit: [[-1, 1]],
|
||||||
|
uniqueTrialCoef: 10,
|
||||||
|
maxUniqueTrialProb: 10,
|
||||||
|
minMonthToAllowInheritItem: 0,
|
||||||
|
},
|
||||||
|
environment: { mapName: 'test_map', unitSet: 'default' },
|
||||||
|
},
|
||||||
|
scenarioMeta: {
|
||||||
|
startYear: 180,
|
||||||
|
} as any,
|
||||||
|
unitSet: {} as any,
|
||||||
|
};
|
||||||
|
|
||||||
|
const state: TurnWorldState = {
|
||||||
|
id: 1,
|
||||||
|
currentYear: 180,
|
||||||
|
currentMonth: 1,
|
||||||
|
tickSeconds: 3600,
|
||||||
|
lastTurnTime: new Date('0180-01-01T00:00:00Z'),
|
||||||
|
meta: {
|
||||||
|
hiddenSeed: 'seed',
|
||||||
|
scenarioId: 200,
|
||||||
|
initYear: 180,
|
||||||
|
initMonth: 1,
|
||||||
|
scenarioMeta: { startYear: 180 },
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const world = new InMemoryTurnWorld(state, snapshot, {
|
||||||
|
schedule: { entries: [{ startMinute: 0, tickMinutes: 10 }] },
|
||||||
|
});
|
||||||
|
|
||||||
|
const itemRegistry = createItemModuleRegistry(await loadItemModules([...ITEM_KEYS]));
|
||||||
|
const config = resolveUniqueConfig(snapshot.scenarioConfig.const as Record<string, unknown>);
|
||||||
|
const occupied = countOccupiedUniqueItems(generals.map((general) => general.role.items), itemRegistry);
|
||||||
|
const rng = new RandUtil(LiteHashDRBG.build(buildVoteUniqueSeed('seed', 1, 1)));
|
||||||
|
const itemKey = rollUniqueLottery({
|
||||||
|
rng,
|
||||||
|
config,
|
||||||
|
itemRegistry,
|
||||||
|
generalItems: generals[0]!.role.items,
|
||||||
|
occupiedUniqueCounts: occupied,
|
||||||
|
scenarioId: 200,
|
||||||
|
userCount: 1,
|
||||||
|
currentYear: 180,
|
||||||
|
currentMonth: 1,
|
||||||
|
startYear: 180,
|
||||||
|
initYear: 180,
|
||||||
|
initMonth: 1,
|
||||||
|
acquireType: '설문조사',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(itemKey).toBe('che_무기_12_칠성검');
|
||||||
|
|
||||||
|
const handler = createTurnDaemonCommandHandler({ world });
|
||||||
|
const command = {
|
||||||
|
type: 'voteReward' as const,
|
||||||
|
voteId: 1,
|
||||||
|
generalId: 1,
|
||||||
|
goldReward: 500,
|
||||||
|
unique: {
|
||||||
|
expected: true,
|
||||||
|
itemKey,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = await handler.handle(command);
|
||||||
|
expect(result && result.type).toBe('voteReward');
|
||||||
|
if (!result || result.type !== 'voteReward' || !result.ok) {
|
||||||
|
throw new Error('voteReward result missing');
|
||||||
|
}
|
||||||
|
expect(result.awardedUnique).toBe(true);
|
||||||
|
|
||||||
|
const updated = world.getGeneralById(1);
|
||||||
|
expect(updated?.gold).toBe(1500);
|
||||||
|
expect(updated?.role.items.weapon).toBe('che_무기_12_칠성검');
|
||||||
|
const meta = updated?.meta as Record<string, unknown>;
|
||||||
|
expect(meta?.voteRewards).toBeTruthy();
|
||||||
|
|
||||||
|
const diff = world.consumeDirtyState();
|
||||||
|
const logTexts = diff.logs.map((entry) => entry.text);
|
||||||
|
expect(logTexts.some((text) => text.includes('【설문조사】'))).toBe(true);
|
||||||
|
|
||||||
|
const second = await handler.handle(command);
|
||||||
|
expect(second && second.type).toBe('voteReward');
|
||||||
|
if (!second || second.type !== 'voteReward' || !second.ok) {
|
||||||
|
throw new Error('voteReward second result missing');
|
||||||
|
}
|
||||||
|
expect(second.alreadyApplied).toBe(true);
|
||||||
|
const afterSecond = world.getGeneralById(1);
|
||||||
|
expect(afterSecond?.gold).toBe(1500);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -24,6 +24,7 @@ import BestGeneralView from '../views/BestGeneralView.vue';
|
|||||||
import HallOfFameView from '../views/HallOfFameView.vue';
|
import HallOfFameView from '../views/HallOfFameView.vue';
|
||||||
import DynastyListView from '../views/DynastyListView.vue';
|
import DynastyListView from '../views/DynastyListView.vue';
|
||||||
import DynastyDetailView from '../views/DynastyDetailView.vue';
|
import DynastyDetailView from '../views/DynastyDetailView.vue';
|
||||||
|
import SurveyView from '../views/SurveyView.vue';
|
||||||
import { useSessionStore } from '../stores/session';
|
import { useSessionStore } from '../stores/session';
|
||||||
|
|
||||||
const routes = [
|
const routes = [
|
||||||
@@ -199,6 +200,15 @@ const routes = [
|
|||||||
requiresGeneral: true,
|
requiresGeneral: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: '/survey',
|
||||||
|
name: 'survey',
|
||||||
|
component: SurveyView,
|
||||||
|
meta: {
|
||||||
|
requiresAuth: true,
|
||||||
|
requiresGeneral: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
path: '/my-settings',
|
path: '/my-settings',
|
||||||
name: 'my-settings',
|
name: 'my-settings',
|
||||||
|
|||||||
@@ -105,6 +105,7 @@ watch(
|
|||||||
<RouterLink class="ghost" to="/battle-simulator">전투 시뮬레이터</RouterLink>
|
<RouterLink class="ghost" to="/battle-simulator">전투 시뮬레이터</RouterLink>
|
||||||
<RouterLink class="ghost" to="/my-page">내 정보</RouterLink>
|
<RouterLink class="ghost" to="/my-page">내 정보</RouterLink>
|
||||||
<RouterLink class="ghost" to="/tournament">토너먼트</RouterLink>
|
<RouterLink class="ghost" to="/tournament">토너먼트</RouterLink>
|
||||||
|
<RouterLink class="ghost" to="/survey">설문조사</RouterLink>
|
||||||
<RouterLink class="ghost" to="/npc-control">NPC 정책</RouterLink>
|
<RouterLink class="ghost" to="/npc-control">NPC 정책</RouterLink>
|
||||||
<RouterLink class="ghost" to="/inherit">유산 강화</RouterLink>
|
<RouterLink class="ghost" to="/inherit">유산 강화</RouterLink>
|
||||||
<button
|
<button
|
||||||
|
|||||||
@@ -0,0 +1,865 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onMounted, ref, watch } from 'vue';
|
||||||
|
import PanelCard from '../components/ui/PanelCard.vue';
|
||||||
|
import SkeletonLines from '../components/ui/SkeletonLines.vue';
|
||||||
|
import { trpc } from '../utils/trpc';
|
||||||
|
|
||||||
|
type VoteListResponse = Awaited<ReturnType<typeof trpc.vote.getVoteList.query>>;
|
||||||
|
type VoteDetailResponse = Awaited<ReturnType<typeof trpc.vote.getVoteDetail.query>>;
|
||||||
|
|
||||||
|
type RevealMode = 'after_vote' | 'after_end';
|
||||||
|
|
||||||
|
type PollSummary = VoteListResponse['polls'][number];
|
||||||
|
|
||||||
|
type VoteDetail = VoteDetailResponse;
|
||||||
|
|
||||||
|
type VoteResultEntry = VoteDetail['votes'][number];
|
||||||
|
|
||||||
|
const loading = ref(false);
|
||||||
|
const detailLoading = ref(false);
|
||||||
|
const error = ref<string | null>(null);
|
||||||
|
const polls = ref<PollSummary[]>([]);
|
||||||
|
const voteReward = ref(0);
|
||||||
|
const activeVoteId = ref<number | null>(null);
|
||||||
|
const voteDetail = ref<VoteDetail | null>(null);
|
||||||
|
const adminEnabled = ref(false);
|
||||||
|
|
||||||
|
const selectionSingle = ref<number | null>(null);
|
||||||
|
const selectionMulti = ref<number[]>([]);
|
||||||
|
const commentDraft = ref('');
|
||||||
|
const actionMessage = ref<string | null>(null);
|
||||||
|
|
||||||
|
const newPollTitle = ref('');
|
||||||
|
const newPollBody = ref('');
|
||||||
|
const newPollOptionsText = ref('');
|
||||||
|
const newPollMultipleOptions = ref(1);
|
||||||
|
const newPollEndAt = ref('');
|
||||||
|
const newPollRevealMode = ref<RevealMode>('after_vote');
|
||||||
|
const newPollClosePrevious = ref(true);
|
||||||
|
|
||||||
|
const updateTitle = ref('');
|
||||||
|
const updateBody = ref('');
|
||||||
|
const updateOptionsText = ref('');
|
||||||
|
const updateMultipleOptions = ref<number | null>(null);
|
||||||
|
const updateEndAt = ref('');
|
||||||
|
const updateRevealMode = ref<RevealMode>('after_vote');
|
||||||
|
|
||||||
|
const resolveErrorMessage = (value: unknown): string => {
|
||||||
|
if (value instanceof Error) {
|
||||||
|
return value.message;
|
||||||
|
}
|
||||||
|
if (typeof value === 'string') {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
return 'unknown_error';
|
||||||
|
};
|
||||||
|
|
||||||
|
const formatDate = (value: string | null): string => {
|
||||||
|
if (!value) {
|
||||||
|
return '-';
|
||||||
|
}
|
||||||
|
const date = new Date(value);
|
||||||
|
if (Number.isNaN(date.getTime())) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
return date.toLocaleString('ko-KR');
|
||||||
|
};
|
||||||
|
|
||||||
|
const parseOptionsText = (text: string): string[] =>
|
||||||
|
text
|
||||||
|
.split('\n')
|
||||||
|
.map((line) => line.trim())
|
||||||
|
.filter((line) => line.length > 0);
|
||||||
|
|
||||||
|
const resolveDateInput = (value: string): string | undefined => {
|
||||||
|
if (!value) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
const parsed = new Date(value);
|
||||||
|
if (Number.isNaN(parsed.getTime())) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
return parsed.toISOString();
|
||||||
|
};
|
||||||
|
|
||||||
|
const isPollEnded = (poll: { endAt: string | null; closedAt: string | null }): boolean => {
|
||||||
|
if (poll.closedAt) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (!poll.endAt) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const endDate = new Date(poll.endAt);
|
||||||
|
if (Number.isNaN(endDate.getTime())) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return endDate <= new Date();
|
||||||
|
};
|
||||||
|
|
||||||
|
const currentPoll = computed(() => {
|
||||||
|
if (!polls.value.length) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const selected = polls.value.find((poll) => poll.id === activeVoteId.value);
|
||||||
|
return selected ?? polls.value[0] ?? null;
|
||||||
|
});
|
||||||
|
|
||||||
|
const revealLabel = computed(() => {
|
||||||
|
if (!voteDetail.value) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
return voteDetail.value.voteInfo.revealMode === 'after_vote' ? '투표 후 공개' : '종료 후 공개';
|
||||||
|
});
|
||||||
|
|
||||||
|
const pollEnded = computed(() => {
|
||||||
|
if (!voteDetail.value) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return isPollEnded({
|
||||||
|
endAt: voteDetail.value.voteInfo.endAt,
|
||||||
|
closedAt: voteDetail.value.voteInfo.closedAt,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const canVote = computed(() => {
|
||||||
|
if (!voteDetail.value) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (voteDetail.value.myVote) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return !pollEnded.value;
|
||||||
|
});
|
||||||
|
|
||||||
|
const canReveal = computed(() => {
|
||||||
|
if (!voteDetail.value) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (voteDetail.value.voteInfo.revealMode === 'after_vote') {
|
||||||
|
return Boolean(voteDetail.value.myVote) || pollEnded.value;
|
||||||
|
}
|
||||||
|
return pollEnded.value;
|
||||||
|
});
|
||||||
|
|
||||||
|
const isSingleChoice = computed(() => voteDetail.value?.voteInfo.multipleOptions === 1);
|
||||||
|
|
||||||
|
const voteDistribution = computed(() => {
|
||||||
|
if (!voteDetail.value) {
|
||||||
|
return [] as number[];
|
||||||
|
}
|
||||||
|
const optionCount = voteDetail.value.voteInfo.options.length;
|
||||||
|
const counts = Array.from({ length: optionCount }, () => 0);
|
||||||
|
for (const entry of voteDetail.value.votes as VoteResultEntry[]) {
|
||||||
|
for (const index of entry.selection) {
|
||||||
|
if (index >= 0 && index < counts.length) {
|
||||||
|
counts[index] += entry.count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return counts;
|
||||||
|
});
|
||||||
|
|
||||||
|
const voteTotal = computed(() =>
|
||||||
|
(voteDetail.value?.votes ?? []).reduce((sum, entry) => sum + entry.count, 0)
|
||||||
|
);
|
||||||
|
|
||||||
|
const selectPoll = (pollId: number) => {
|
||||||
|
if (activeVoteId.value === pollId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
activeVoteId.value = pollId;
|
||||||
|
};
|
||||||
|
|
||||||
|
const loadVoteList = async () => {
|
||||||
|
if (loading.value) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
loading.value = true;
|
||||||
|
error.value = null;
|
||||||
|
try {
|
||||||
|
const result = await trpc.vote.getVoteList.query();
|
||||||
|
polls.value = result.polls;
|
||||||
|
voteReward.value = result.voteReward ?? 0;
|
||||||
|
if (!activeVoteId.value || !result.polls.some((poll) => poll.id === activeVoteId.value)) {
|
||||||
|
const openPoll = result.polls.find((poll) => !isPollEnded(poll));
|
||||||
|
activeVoteId.value = openPoll?.id ?? result.polls[0]?.id ?? null;
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
error.value = resolveErrorMessage(err);
|
||||||
|
} finally {
|
||||||
|
loading.value = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const loadVoteDetail = async (voteId: number) => {
|
||||||
|
if (detailLoading.value) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
detailLoading.value = true;
|
||||||
|
error.value = null;
|
||||||
|
actionMessage.value = null;
|
||||||
|
try {
|
||||||
|
const result = await trpc.vote.getVoteDetail.query({ voteId });
|
||||||
|
voteDetail.value = result;
|
||||||
|
if (result.myVote && result.myVote.length > 0) {
|
||||||
|
if (result.voteInfo.multipleOptions === 1) {
|
||||||
|
selectionSingle.value = result.myVote[0] ?? null;
|
||||||
|
selectionMulti.value = [...result.myVote];
|
||||||
|
} else {
|
||||||
|
selectionSingle.value = null;
|
||||||
|
selectionMulti.value = [...result.myVote];
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
selectionSingle.value = null;
|
||||||
|
selectionMulti.value = [];
|
||||||
|
}
|
||||||
|
commentDraft.value = '';
|
||||||
|
updateTitle.value = result.voteInfo.title;
|
||||||
|
updateBody.value = result.voteInfo.body;
|
||||||
|
updateMultipleOptions.value = result.voteInfo.multipleOptions;
|
||||||
|
updateRevealMode.value = result.voteInfo.revealMode;
|
||||||
|
updateEndAt.value = result.voteInfo.endAt ? result.voteInfo.endAt.slice(0, 16) : '';
|
||||||
|
} catch (err) {
|
||||||
|
error.value = resolveErrorMessage(err);
|
||||||
|
} finally {
|
||||||
|
detailLoading.value = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const refreshAll = async () => {
|
||||||
|
await loadVoteList();
|
||||||
|
if (activeVoteId.value) {
|
||||||
|
await loadVoteDetail(activeVoteId.value);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const submitVote = async () => {
|
||||||
|
if (!voteDetail.value) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const optionLimit = voteDetail.value.voteInfo.multipleOptions;
|
||||||
|
const selected = isSingleChoice.value
|
||||||
|
? selectionSingle.value !== null
|
||||||
|
? [selectionSingle.value]
|
||||||
|
: []
|
||||||
|
: [...selectionMulti.value];
|
||||||
|
|
||||||
|
if (selected.length === 0) {
|
||||||
|
actionMessage.value = '선택한 항목이 없습니다.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (optionLimit >= 1 && selected.length > optionLimit) {
|
||||||
|
actionMessage.value = '선택한 항목이 너무 많습니다.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
actionMessage.value = null;
|
||||||
|
try {
|
||||||
|
const result = await trpc.vote.submitVote.mutate({
|
||||||
|
voteId: voteDetail.value.voteInfo.id,
|
||||||
|
selection: selected,
|
||||||
|
});
|
||||||
|
actionMessage.value = result.wonLottery
|
||||||
|
? '투표 완료! 유니크 추첨에 당첨되었습니다.'
|
||||||
|
: '투표가 완료되었습니다.';
|
||||||
|
await refreshAll();
|
||||||
|
} catch (err) {
|
||||||
|
actionMessage.value = resolveErrorMessage(err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const submitComment = async () => {
|
||||||
|
if (!voteDetail.value) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const text = commentDraft.value.trim();
|
||||||
|
if (!text) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
actionMessage.value = null;
|
||||||
|
try {
|
||||||
|
await trpc.vote.addComment.mutate({
|
||||||
|
voteId: voteDetail.value.voteInfo.id,
|
||||||
|
text,
|
||||||
|
});
|
||||||
|
commentDraft.value = '';
|
||||||
|
await loadVoteDetail(voteDetail.value.voteInfo.id);
|
||||||
|
} catch (err) {
|
||||||
|
actionMessage.value = resolveErrorMessage(err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const createPoll = async () => {
|
||||||
|
const options = parseOptionsText(newPollOptionsText.value);
|
||||||
|
const endAt = resolveDateInput(newPollEndAt.value);
|
||||||
|
actionMessage.value = null;
|
||||||
|
try {
|
||||||
|
await trpc.vote.createPoll.mutate({
|
||||||
|
title: newPollTitle.value.trim(),
|
||||||
|
body: newPollBody.value.trim(),
|
||||||
|
options,
|
||||||
|
multipleOptions: newPollMultipleOptions.value,
|
||||||
|
endAt,
|
||||||
|
revealMode: newPollRevealMode.value,
|
||||||
|
closePrevious: newPollClosePrevious.value,
|
||||||
|
});
|
||||||
|
newPollTitle.value = '';
|
||||||
|
newPollBody.value = '';
|
||||||
|
newPollOptionsText.value = '';
|
||||||
|
newPollMultipleOptions.value = 1;
|
||||||
|
newPollEndAt.value = '';
|
||||||
|
newPollRevealMode.value = 'after_vote';
|
||||||
|
newPollClosePrevious.value = true;
|
||||||
|
await refreshAll();
|
||||||
|
} catch (err) {
|
||||||
|
actionMessage.value = resolveErrorMessage(err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const updatePoll = async () => {
|
||||||
|
if (!voteDetail.value) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const appendOptions = parseOptionsText(updateOptionsText.value);
|
||||||
|
const endAt = resolveDateInput(updateEndAt.value);
|
||||||
|
actionMessage.value = null;
|
||||||
|
try {
|
||||||
|
await trpc.vote.updatePoll.mutate({
|
||||||
|
voteId: voteDetail.value.voteInfo.id,
|
||||||
|
title: updateTitle.value.trim() || undefined,
|
||||||
|
body: updateBody.value.trim() || undefined,
|
||||||
|
appendOptions: appendOptions.length > 0 ? appendOptions : undefined,
|
||||||
|
multipleOptions: updateMultipleOptions.value ?? undefined,
|
||||||
|
endAt,
|
||||||
|
revealMode: updateRevealMode.value,
|
||||||
|
});
|
||||||
|
updateOptionsText.value = '';
|
||||||
|
await refreshAll();
|
||||||
|
} catch (err) {
|
||||||
|
actionMessage.value = resolveErrorMessage(err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const closePoll = async () => {
|
||||||
|
if (!voteDetail.value) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
actionMessage.value = null;
|
||||||
|
try {
|
||||||
|
await trpc.vote.closePoll.mutate({ voteId: voteDetail.value.voteInfo.id });
|
||||||
|
await refreshAll();
|
||||||
|
} catch (err) {
|
||||||
|
actionMessage.value = resolveErrorMessage(err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
void refreshAll();
|
||||||
|
void trpc.vote.getAdminStatus.query().then((result) => {
|
||||||
|
adminEnabled.value = Boolean(result?.ok);
|
||||||
|
}).catch(() => {
|
||||||
|
adminEnabled.value = false;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
watch(activeVoteId, (voteId) => {
|
||||||
|
if (voteId) {
|
||||||
|
void loadVoteDetail(voteId);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<main class="survey-view">
|
||||||
|
<header class="page-header">
|
||||||
|
<div>
|
||||||
|
<h1 class="page-title">설문조사</h1>
|
||||||
|
<p class="page-subtitle">투표 참여 보상과 유니크 추첨이 함께 진행됩니다.</p>
|
||||||
|
</div>
|
||||||
|
<div class="header-actions">
|
||||||
|
<RouterLink class="ghost" to="/">메인으로</RouterLink>
|
||||||
|
<button class="ghost" @click="refreshAll" :disabled="loading">새로고침</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div v-if="error" class="error">{{ error }}</div>
|
||||||
|
<div v-if="actionMessage" class="notice">{{ actionMessage }}</div>
|
||||||
|
|
||||||
|
<section class="survey-grid">
|
||||||
|
<div class="survey-main">
|
||||||
|
<PanelCard title="보상 안내">
|
||||||
|
<div class="reward-block">
|
||||||
|
<div>투표 참여 보상: <strong>{{ voteReward }}</strong> 금</div>
|
||||||
|
<div>추첨 보상: 유니크 장비 1종</div>
|
||||||
|
</div>
|
||||||
|
</PanelCard>
|
||||||
|
|
||||||
|
<PanelCard title="현재 설문" :subtitle="currentPoll?.title ?? '설문 정보 없음'">
|
||||||
|
<SkeletonLines v-if="loading || detailLoading" :lines="6" />
|
||||||
|
<div v-else-if="!voteDetail" class="placeholder">설문 정보가 없습니다.</div>
|
||||||
|
<div v-else class="poll-detail">
|
||||||
|
<div class="poll-meta">
|
||||||
|
<div><strong>제목</strong> {{ voteDetail.voteInfo.title }}</div>
|
||||||
|
<div v-if="voteDetail.voteInfo.body"><strong>본문</strong> {{ voteDetail.voteInfo.body }}</div>
|
||||||
|
<div><strong>작성자</strong> {{ voteDetail.voteInfo.openerName }}</div>
|
||||||
|
<div>
|
||||||
|
<strong>선택 제한</strong>
|
||||||
|
{{
|
||||||
|
voteDetail.voteInfo.multipleOptions === 0
|
||||||
|
? '제한 없음'
|
||||||
|
: voteDetail.voteInfo.multipleOptions === 1
|
||||||
|
? '1개 선택'
|
||||||
|
: `${voteDetail.voteInfo.multipleOptions}개 선택`
|
||||||
|
}}
|
||||||
|
</div>
|
||||||
|
<div><strong>공개 정책</strong> {{ revealLabel }}</div>
|
||||||
|
<div><strong>시작</strong> {{ formatDate(voteDetail.voteInfo.startAt) }}</div>
|
||||||
|
<div><strong>종료</strong> {{ formatDate(voteDetail.voteInfo.endAt) }}</div>
|
||||||
|
<div><strong>닫힘</strong> {{ formatDate(voteDetail.voteInfo.closedAt) }}</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="poll-options">
|
||||||
|
<div
|
||||||
|
v-for="(option, idx) in voteDetail.voteInfo.options"
|
||||||
|
:key="`${voteDetail.voteInfo.id}-${idx}`"
|
||||||
|
class="poll-option"
|
||||||
|
>
|
||||||
|
<label>
|
||||||
|
<input
|
||||||
|
v-if="isSingleChoice"
|
||||||
|
type="radio"
|
||||||
|
:value="idx"
|
||||||
|
v-model="selectionSingle"
|
||||||
|
:disabled="!canVote"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
v-else
|
||||||
|
type="checkbox"
|
||||||
|
:value="idx"
|
||||||
|
v-model="selectionMulti"
|
||||||
|
:disabled="!canVote"
|
||||||
|
/>
|
||||||
|
<span>{{ option }}</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="poll-actions">
|
||||||
|
<button class="ghost" @click="submitVote" :disabled="!canVote">투표하기</button>
|
||||||
|
<span v-if="voteDetail.myVote" class="muted">이미 투표했습니다.</span>
|
||||||
|
<span v-else-if="pollEnded" class="muted">설문이 종료되었습니다.</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</PanelCard>
|
||||||
|
|
||||||
|
<PanelCard title="결과">
|
||||||
|
<SkeletonLines v-if="detailLoading" :lines="4" />
|
||||||
|
<div v-else-if="!voteDetail" class="placeholder">설문 결과가 없습니다.</div>
|
||||||
|
<div v-else-if="!canReveal" class="placeholder">
|
||||||
|
결과는 {{ revealLabel }}됩니다.
|
||||||
|
</div>
|
||||||
|
<div v-else class="poll-results">
|
||||||
|
<div class="result-summary">
|
||||||
|
참여 인원 {{ voteTotal }} / {{ voteDetail.userCnt }}
|
||||||
|
</div>
|
||||||
|
<div v-for="(option, idx) in voteDetail.voteInfo.options" :key="`result-${idx}`" class="result-row">
|
||||||
|
<div class="result-option">{{ option }}</div>
|
||||||
|
<div class="result-count">{{ voteDistribution[idx] ?? 0 }}명</div>
|
||||||
|
<div class="result-percent">
|
||||||
|
{{
|
||||||
|
voteTotal > 0
|
||||||
|
? ((voteDistribution[idx] ?? 0) / voteTotal * 100).toFixed(1)
|
||||||
|
: '0.0'
|
||||||
|
}}%
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</PanelCard>
|
||||||
|
|
||||||
|
<PanelCard title="댓글">
|
||||||
|
<SkeletonLines v-if="detailLoading" :lines="4" />
|
||||||
|
<div v-else-if="!voteDetail" class="placeholder">댓글을 불러오는 중입니다.</div>
|
||||||
|
<div v-else>
|
||||||
|
<div v-if="voteDetail.comments.length === 0" class="placeholder">아직 댓글이 없습니다.</div>
|
||||||
|
<div v-else class="comment-list">
|
||||||
|
<div v-for="comment in voteDetail.comments" :key="comment.id" class="comment-item">
|
||||||
|
<div class="comment-header">
|
||||||
|
<span>{{ comment.nationName }}</span>
|
||||||
|
<span>{{ comment.generalName }}</span>
|
||||||
|
<span class="comment-date">{{ formatDate(comment.createdAt) }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="comment-text">{{ comment.text }}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="comment-form">
|
||||||
|
<input
|
||||||
|
v-model="commentDraft"
|
||||||
|
type="text"
|
||||||
|
maxlength="200"
|
||||||
|
placeholder="댓글을 입력하세요"
|
||||||
|
/>
|
||||||
|
<button class="ghost" @click="submitComment">댓글 등록</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</PanelCard>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="survey-side">
|
||||||
|
<PanelCard title="설문 목록">
|
||||||
|
<SkeletonLines v-if="loading" :lines="4" />
|
||||||
|
<div v-else class="poll-list">
|
||||||
|
<div v-if="polls.length === 0" class="placeholder">등록된 설문이 없습니다.</div>
|
||||||
|
<button
|
||||||
|
v-for="poll in polls"
|
||||||
|
:key="poll.id"
|
||||||
|
class="poll-list-item"
|
||||||
|
:class="{ active: poll.id === currentPoll?.id }"
|
||||||
|
@click="selectPoll(poll.id)"
|
||||||
|
>
|
||||||
|
<div class="poll-title">{{ poll.title }}</div>
|
||||||
|
<div class="poll-meta-row">
|
||||||
|
<span>{{ formatDate(poll.startAt) }}</span>
|
||||||
|
<span>{{ isPollEnded(poll) ? '종료됨' : '진행중' }}</span>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</PanelCard>
|
||||||
|
|
||||||
|
<PanelCard v-if="adminEnabled" title="관리자 패널">
|
||||||
|
<div class="admin-section">
|
||||||
|
<h3>새 설문 생성</h3>
|
||||||
|
<label>
|
||||||
|
제목
|
||||||
|
<input v-model="newPollTitle" type="text" />
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
본문
|
||||||
|
<textarea v-model="newPollBody" rows="3" />
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
항목 (줄바꿈 구분)
|
||||||
|
<textarea v-model="newPollOptionsText" rows="4" />
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
동시 응답 수 (0=제한 없음)
|
||||||
|
<input v-model.number="newPollMultipleOptions" type="number" min="0" />
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
종료 시각
|
||||||
|
<input v-model="newPollEndAt" type="datetime-local" />
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
공개 정책
|
||||||
|
<select v-model="newPollRevealMode">
|
||||||
|
<option value="after_vote">투표 후 공개</option>
|
||||||
|
<option value="after_end">종료 후 공개</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label class="checkbox">
|
||||||
|
<input v-model="newPollClosePrevious" type="checkbox" />
|
||||||
|
기존 설문 종료
|
||||||
|
</label>
|
||||||
|
<button class="ghost" @click="createPoll">설문 생성</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="admin-section" v-if="voteDetail">
|
||||||
|
<h3>설문 수정</h3>
|
||||||
|
<p class="muted">응답 0건일 때만 수정 가능합니다.</p>
|
||||||
|
<label>
|
||||||
|
제목
|
||||||
|
<input v-model="updateTitle" type="text" />
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
본문
|
||||||
|
<textarea v-model="updateBody" rows="3" />
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
항목 추가 (줄바꿈 구분)
|
||||||
|
<textarea v-model="updateOptionsText" rows="3" />
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
동시 응답 수
|
||||||
|
<input v-model.number="updateMultipleOptions" type="number" min="0" />
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
종료 시각
|
||||||
|
<input v-model="updateEndAt" type="datetime-local" />
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
공개 정책
|
||||||
|
<select v-model="updateRevealMode">
|
||||||
|
<option value="after_vote">투표 후 공개</option>
|
||||||
|
<option value="after_end">종료 후 공개</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<div class="admin-actions">
|
||||||
|
<button class="ghost" @click="updatePoll">수정 적용</button>
|
||||||
|
<button class="ghost" @click="closePoll">설문 종료</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</PanelCard>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.survey-view {
|
||||||
|
min-height: 100vh;
|
||||||
|
padding: 24px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.page-header {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
border-bottom: 1px solid rgba(201, 164, 90, 0.4);
|
||||||
|
padding-bottom: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.page-title {
|
||||||
|
font-size: 1.6rem;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.page-subtitle {
|
||||||
|
font-size: 0.85rem;
|
||||||
|
color: rgba(232, 221, 196, 0.7);
|
||||||
|
}
|
||||||
|
|
||||||
|
.header-actions {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ghost {
|
||||||
|
border: 1px solid rgba(201, 164, 90, 0.4);
|
||||||
|
padding: 6px 12px;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
cursor: pointer;
|
||||||
|
background: rgba(16, 16, 16, 0.6);
|
||||||
|
color: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ghost:disabled {
|
||||||
|
opacity: 0.6;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error {
|
||||||
|
color: #ff8080;
|
||||||
|
}
|
||||||
|
|
||||||
|
.notice {
|
||||||
|
color: rgba(232, 221, 196, 0.8);
|
||||||
|
}
|
||||||
|
|
||||||
|
.survey-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(0, 1fr) 320px;
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.survey-main,
|
||||||
|
.survey-side {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.reward-block {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.poll-detail {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.poll-meta {
|
||||||
|
display: grid;
|
||||||
|
gap: 6px;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.poll-options {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.poll-option {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.poll-actions {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.poll-results {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.result-summary {
|
||||||
|
font-size: 0.9rem;
|
||||||
|
color: rgba(232, 221, 196, 0.8);
|
||||||
|
}
|
||||||
|
|
||||||
|
.result-row {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 1fr auto auto;
|
||||||
|
gap: 12px;
|
||||||
|
align-items: center;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.result-count,
|
||||||
|
.result-percent {
|
||||||
|
text-align: right;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.comment-list {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.comment-item {
|
||||||
|
padding: 10px 12px;
|
||||||
|
border: 1px solid rgba(201, 164, 90, 0.3);
|
||||||
|
border-radius: 8px;
|
||||||
|
background: rgba(16, 16, 16, 0.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
.comment-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
color: rgba(232, 221, 196, 0.8);
|
||||||
|
}
|
||||||
|
|
||||||
|
.comment-date {
|
||||||
|
opacity: 0.7;
|
||||||
|
}
|
||||||
|
|
||||||
|
.comment-text {
|
||||||
|
margin-top: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.comment-form {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
margin-top: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.comment-form input {
|
||||||
|
flex: 1;
|
||||||
|
padding: 6px 8px;
|
||||||
|
background: rgba(16, 16, 16, 0.6);
|
||||||
|
border: 1px solid rgba(201, 164, 90, 0.4);
|
||||||
|
color: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
|
.poll-list {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.poll-list-item {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 4px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
border: 1px solid rgba(201, 164, 90, 0.3);
|
||||||
|
background: rgba(16, 16, 16, 0.5);
|
||||||
|
text-align: left;
|
||||||
|
cursor: pointer;
|
||||||
|
color: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
|
.poll-list-item.active {
|
||||||
|
border-color: rgba(255, 214, 140, 0.8);
|
||||||
|
background: rgba(32, 24, 12, 0.8);
|
||||||
|
}
|
||||||
|
|
||||||
|
.poll-meta-row {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
color: rgba(232, 221, 196, 0.7);
|
||||||
|
}
|
||||||
|
|
||||||
|
.placeholder {
|
||||||
|
color: rgba(232, 221, 196, 0.7);
|
||||||
|
}
|
||||||
|
|
||||||
|
.muted {
|
||||||
|
color: rgba(232, 221, 196, 0.6);
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-section {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-section h3 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-section label {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 4px;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-section input,
|
||||||
|
.admin-section textarea,
|
||||||
|
.admin-section select {
|
||||||
|
padding: 6px 8px;
|
||||||
|
background: rgba(16, 16, 16, 0.6);
|
||||||
|
border: 1px solid rgba(201, 164, 90, 0.4);
|
||||||
|
color: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-section .checkbox {
|
||||||
|
flex-direction: row;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-actions {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 1024px) {
|
||||||
|
.survey-grid {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
|
||||||
|
.comment-form {
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -60,6 +60,7 @@ Move items into the main docs once they are finalized.
|
|||||||
- [AI suggestion] Replace smoke/placeholder tests with concrete assertions for success/failure outcomes (e.g., 등용, NPC능동 invalid args, 출병 troop creation).
|
- [AI suggestion] Replace smoke/placeholder tests with concrete assertions for success/failure outcomes (e.g., 등용, NPC능동 invalid args, 출병 troop creation).
|
||||||
- [AI suggestion] Document che*출병 parity gaps vs legacy (city state/term=43, fallback to che*이동 when friendly, nation.war/AllowWar check, post-war static events/unique-item lottery, missing route data when map/diplomacy not provided).
|
- [AI suggestion] Document che*출병 parity gaps vs legacy (city state/term=43, fallback to che*이동 when friendly, nation.war/AllowWar check, post-war static events/unique-item lottery, missing route data when map/diplomacy not provided).
|
||||||
- [AI suggestion] Verify that "이호경식" followed by "출병" is correctly blocked with the new reserved-turn overlay (diplomacy state sync).
|
- [AI suggestion] Verify that "이호경식" followed by "출병" is correctly blocked with the new reserved-turn overlay (diplomacy state sync).
|
||||||
|
- [AI suggestion] Survey/unique lottery should account for auction/storage-held unique items once the inventory and auction models are finalized.
|
||||||
|
|
||||||
## Trigger System
|
## Trigger System
|
||||||
|
|
||||||
|
|||||||
@@ -115,14 +115,25 @@ export type TurnDaemonCommand =
|
|||||||
top16: number[];
|
top16: number[];
|
||||||
top8: number[];
|
top8: number[];
|
||||||
top4: number[];
|
top4: number[];
|
||||||
}
|
}
|
||||||
| {
|
| {
|
||||||
type: 'setNationMeta';
|
type: 'voteReward';
|
||||||
requestId?: string;
|
requestId?: string;
|
||||||
nationId: number;
|
voteId: number;
|
||||||
updates: Record<string, unknown>;
|
generalId: number;
|
||||||
expectedUpdatedAt?: string;
|
goldReward: number;
|
||||||
}
|
unique?: {
|
||||||
|
expected: boolean;
|
||||||
|
itemKey?: string | null;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
type: 'setNationMeta';
|
||||||
|
requestId?: string;
|
||||||
|
nationId: number;
|
||||||
|
updates: Record<string, unknown>;
|
||||||
|
expectedUpdatedAt?: string;
|
||||||
|
}
|
||||||
| {
|
| {
|
||||||
type: 'adjustGeneralResources';
|
type: 'adjustGeneralResources';
|
||||||
requestId?: string;
|
requestId?: string;
|
||||||
@@ -264,20 +275,36 @@ export type TurnDaemonCommandResult =
|
|||||||
winnerId: number;
|
winnerId: number;
|
||||||
runnerUpId: number;
|
runnerUpId: number;
|
||||||
reason: string;
|
reason: string;
|
||||||
}
|
}
|
||||||
| {
|
| {
|
||||||
type: 'setNationMeta';
|
type: 'voteReward';
|
||||||
ok: true;
|
ok: true;
|
||||||
nationId: number;
|
voteId: number;
|
||||||
updatedAt: string;
|
generalId: number;
|
||||||
}
|
awardedUnique: boolean;
|
||||||
| {
|
itemKey?: string | null;
|
||||||
type: 'setNationMeta';
|
alreadyApplied?: boolean;
|
||||||
ok: false;
|
}
|
||||||
nationId: number;
|
| {
|
||||||
reason: string;
|
type: 'voteReward';
|
||||||
currentUpdatedAt?: string;
|
ok: false;
|
||||||
}
|
voteId: number;
|
||||||
|
generalId: number;
|
||||||
|
reason: string;
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
type: 'setNationMeta';
|
||||||
|
ok: true;
|
||||||
|
nationId: number;
|
||||||
|
updatedAt: string;
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
type: 'setNationMeta';
|
||||||
|
ok: false;
|
||||||
|
nationId: number;
|
||||||
|
reason: string;
|
||||||
|
currentUpdatedAt?: string;
|
||||||
|
}
|
||||||
| {
|
| {
|
||||||
type: 'adjustGeneralResources';
|
type: 'adjustGeneralResources';
|
||||||
ok: true;
|
ok: true;
|
||||||
|
|||||||
@@ -514,3 +514,55 @@ model BoardComment {
|
|||||||
@@index([postId, createdAt])
|
@@index([postId, createdAt])
|
||||||
@@map("board_comment")
|
@@map("board_comment")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
model VotePoll {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
title String
|
||||||
|
body String @default("")
|
||||||
|
options Json
|
||||||
|
multipleOptions Int @default(1) @map("multiple_options")
|
||||||
|
revealMode String @map("reveal_mode")
|
||||||
|
openerGeneralId Int @map("opener_general_id")
|
||||||
|
openerName String @map("opener_name")
|
||||||
|
startAt DateTime @default(now()) @map("start_at")
|
||||||
|
endAt DateTime? @map("end_at")
|
||||||
|
closedAt DateTime? @map("closed_at")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
votes Vote[]
|
||||||
|
comments VoteComment[]
|
||||||
|
|
||||||
|
@@map("vote_poll")
|
||||||
|
}
|
||||||
|
|
||||||
|
model Vote {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
voteId Int @map("vote_id")
|
||||||
|
generalId Int @map("general_id")
|
||||||
|
nationId Int @map("nation_id")
|
||||||
|
selection Json
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
|
||||||
|
poll VotePoll @relation(fields: [voteId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@unique([voteId, generalId])
|
||||||
|
@@index([voteId])
|
||||||
|
@@map("vote")
|
||||||
|
}
|
||||||
|
|
||||||
|
model VoteComment {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
voteId Int @map("vote_id")
|
||||||
|
generalId Int @map("general_id")
|
||||||
|
nationId Int @map("nation_id")
|
||||||
|
generalName String @map("general_name")
|
||||||
|
nationName String @map("nation_name")
|
||||||
|
text String
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
|
||||||
|
poll VotePoll @relation(fields: [voteId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@index([voteId, createdAt])
|
||||||
|
@@map("vote_comment")
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
CREATE TABLE "vote_poll" (
|
||||||
|
"id" SERIAL PRIMARY KEY,
|
||||||
|
"title" TEXT NOT NULL,
|
||||||
|
"body" TEXT NOT NULL DEFAULT '',
|
||||||
|
"options" JSONB NOT NULL,
|
||||||
|
"multiple_options" INTEGER NOT NULL DEFAULT 1,
|
||||||
|
"reveal_mode" TEXT NOT NULL,
|
||||||
|
"opener_general_id" INTEGER NOT NULL,
|
||||||
|
"opener_name" TEXT NOT NULL,
|
||||||
|
"start_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"end_at" TIMESTAMP(3) NULL,
|
||||||
|
"closed_at" TIMESTAMP(3) NULL,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE "vote" (
|
||||||
|
"id" SERIAL PRIMARY KEY,
|
||||||
|
"vote_id" INTEGER NOT NULL REFERENCES "vote_poll"("id") ON DELETE CASCADE,
|
||||||
|
"general_id" INTEGER NOT NULL,
|
||||||
|
"nation_id" INTEGER NOT NULL,
|
||||||
|
"selection" JSONB NOT NULL,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX "vote_vote_general_uidx" ON "vote"("vote_id", "general_id");
|
||||||
|
CREATE INDEX "vote_vote_idx" ON "vote"("vote_id");
|
||||||
|
|
||||||
|
CREATE TABLE "vote_comment" (
|
||||||
|
"id" SERIAL PRIMARY KEY,
|
||||||
|
"vote_id" INTEGER NOT NULL REFERENCES "vote_poll"("id") ON DELETE CASCADE,
|
||||||
|
"general_id" INTEGER NOT NULL,
|
||||||
|
"nation_id" INTEGER NOT NULL,
|
||||||
|
"general_name" TEXT NOT NULL,
|
||||||
|
"nation_name" TEXT NOT NULL,
|
||||||
|
"text" TEXT NOT NULL,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX "vote_comment_vote_created_idx" ON "vote_comment"("vote_id", "created_at");
|
||||||
@@ -8,6 +8,7 @@ export * from './logging/index.js';
|
|||||||
export * from './messages/index.js';
|
export * from './messages/index.js';
|
||||||
export * from './items/index.js';
|
export * from './items/index.js';
|
||||||
export { ITEM_KEYS, createItemActionModules, createItemModuleRegistry, loadItemModules } from './items/index.js';
|
export { ITEM_KEYS, createItemActionModules, createItemModuleRegistry, loadItemModules } from './items/index.js';
|
||||||
|
export * from './rewards/uniqueLottery.js';
|
||||||
export * from './inheritance/inheritBuff.js';
|
export * from './inheritance/inheritBuff.js';
|
||||||
export * from './resources/index.js';
|
export * from './resources/index.js';
|
||||||
export * from './ports/world.js';
|
export * from './ports/world.js';
|
||||||
|
|||||||
@@ -0,0 +1,278 @@
|
|||||||
|
import { asRecord, parseJson, type RandUtil } from '@sammo-ts/common';
|
||||||
|
import type { GeneralItemSlots } from '../domain/entities.js';
|
||||||
|
import type { ItemModule } from '../items/types.js';
|
||||||
|
|
||||||
|
export type UniqueItemPool = Record<string, Record<string, number>>;
|
||||||
|
|
||||||
|
export type UniqueLotteryConfig = {
|
||||||
|
allItems: UniqueItemPool;
|
||||||
|
maxUniqueItemLimit: Array<[number, number]>;
|
||||||
|
uniqueTrialCoef: number;
|
||||||
|
maxUniqueTrialProb: number;
|
||||||
|
minMonthToAllowInheritItem: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type UniqueLotteryInput = {
|
||||||
|
rng: RandUtil;
|
||||||
|
config: UniqueLotteryConfig;
|
||||||
|
itemRegistry: Map<string, ItemModule>;
|
||||||
|
generalItems: GeneralItemSlots;
|
||||||
|
occupiedUniqueCounts: Map<string, number>;
|
||||||
|
scenarioId: number;
|
||||||
|
userCount: number;
|
||||||
|
currentYear: number;
|
||||||
|
currentMonth: number;
|
||||||
|
startYear: number;
|
||||||
|
initYear: number;
|
||||||
|
initMonth: number;
|
||||||
|
acquireType?: string;
|
||||||
|
inheritRandomUnique?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
const DEFAULT_MAX_UNIQUE_ITEM_LIMIT: Array<[number, number]> = [
|
||||||
|
[-1, 1],
|
||||||
|
[3, 2],
|
||||||
|
[10, 3],
|
||||||
|
[20, 4],
|
||||||
|
];
|
||||||
|
|
||||||
|
const DEFAULT_UNIQUE_TRIAL_COEF = 1;
|
||||||
|
const DEFAULT_MAX_UNIQUE_TRIAL_PROB = 0.25;
|
||||||
|
const DEFAULT_MIN_MONTH_TO_ALLOW_INHERIT_ITEM = 4;
|
||||||
|
|
||||||
|
const readNumber = (value: unknown, fallback: number): number => {
|
||||||
|
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
if (typeof value === 'string') {
|
||||||
|
const parsed = Number(value);
|
||||||
|
if (Number.isFinite(parsed)) {
|
||||||
|
return parsed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fallback;
|
||||||
|
};
|
||||||
|
|
||||||
|
const normalizeItemPool = (value: unknown): UniqueItemPool => {
|
||||||
|
if (typeof value === 'string') {
|
||||||
|
const parsed = parseJson<UniqueItemPool>(value);
|
||||||
|
return normalizeItemPool(parsed);
|
||||||
|
}
|
||||||
|
const record = asRecord(value);
|
||||||
|
const result: UniqueItemPool = {};
|
||||||
|
for (const [itemType, rawItems] of Object.entries(record)) {
|
||||||
|
const rawEntries = asRecord(rawItems);
|
||||||
|
const entries: Record<string, number> = {};
|
||||||
|
for (const [itemKey, rawCount] of Object.entries(rawEntries)) {
|
||||||
|
const count = readNumber(rawCount, Number.NaN);
|
||||||
|
if (!Number.isFinite(count)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
entries[itemKey] = Math.floor(count);
|
||||||
|
}
|
||||||
|
result[itemType] = entries;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
|
||||||
|
const normalizeLimitTable = (value: unknown): Array<[number, number]> => {
|
||||||
|
if (!Array.isArray(value)) {
|
||||||
|
return [...DEFAULT_MAX_UNIQUE_ITEM_LIMIT];
|
||||||
|
}
|
||||||
|
const result: Array<[number, number]> = [];
|
||||||
|
for (const entry of value) {
|
||||||
|
if (!Array.isArray(entry) || entry.length < 2) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const year = readNumber(entry[0], Number.NaN);
|
||||||
|
const limit = readNumber(entry[1], Number.NaN);
|
||||||
|
if (!Number.isFinite(year) || !Number.isFinite(limit)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
result.push([Math.floor(year), Math.floor(limit)]);
|
||||||
|
}
|
||||||
|
return result.length > 0 ? result : [...DEFAULT_MAX_UNIQUE_ITEM_LIMIT];
|
||||||
|
};
|
||||||
|
|
||||||
|
export const resolveUniqueConfig = (configConst: Record<string, unknown>): UniqueLotteryConfig => {
|
||||||
|
const allItems = normalizeItemPool(configConst.allItems);
|
||||||
|
return {
|
||||||
|
allItems,
|
||||||
|
maxUniqueItemLimit: normalizeLimitTable(configConst.maxUniqueItemLimit),
|
||||||
|
uniqueTrialCoef: readNumber(configConst.uniqueTrialCoef, DEFAULT_UNIQUE_TRIAL_COEF),
|
||||||
|
maxUniqueTrialProb: readNumber(configConst.maxUniqueTrialProb, DEFAULT_MAX_UNIQUE_TRIAL_PROB),
|
||||||
|
minMonthToAllowInheritItem: Math.max(
|
||||||
|
0,
|
||||||
|
Math.floor(readNumber(configConst.minMonthToAllowInheritItem, DEFAULT_MIN_MONTH_TO_ALLOW_INHERIT_ITEM))
|
||||||
|
),
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export const countOccupiedUniqueItems = (
|
||||||
|
generals: GeneralItemSlots[],
|
||||||
|
itemRegistry: Map<string, ItemModule>
|
||||||
|
): Map<string, number> => {
|
||||||
|
const counts = new Map<string, number>();
|
||||||
|
for (const items of generals) {
|
||||||
|
const values = [items.horse, items.weapon, items.book, items.item];
|
||||||
|
for (const itemKey of values) {
|
||||||
|
if (!itemKey) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const module = itemRegistry.get(itemKey);
|
||||||
|
if (!module || module.buyable) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
counts.set(itemKey, (counts.get(itemKey) ?? 0) + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return counts;
|
||||||
|
};
|
||||||
|
|
||||||
|
const joinYearMonth = (year: number, month: number): number => year * 12 + month - 1;
|
||||||
|
|
||||||
|
const serializeSeed = (...values: Array<string | number>): string =>
|
||||||
|
values
|
||||||
|
.map((value) => (typeof value === 'string' ? `str(${value.length},${value})` : `int(${Math.floor(value)})`))
|
||||||
|
.join('|');
|
||||||
|
|
||||||
|
export const buildVoteUniqueSeed = (hiddenSeed: string | number, voteId: number, generalId: number): string =>
|
||||||
|
serializeSeed(hiddenSeed, 'voteUnique', voteId, generalId);
|
||||||
|
|
||||||
|
export const rollUniqueLottery = (input: UniqueLotteryInput): string | null => {
|
||||||
|
const {
|
||||||
|
rng,
|
||||||
|
config,
|
||||||
|
itemRegistry,
|
||||||
|
generalItems,
|
||||||
|
occupiedUniqueCounts,
|
||||||
|
scenarioId,
|
||||||
|
userCount,
|
||||||
|
currentYear,
|
||||||
|
currentMonth,
|
||||||
|
startYear,
|
||||||
|
initYear,
|
||||||
|
initMonth,
|
||||||
|
acquireType,
|
||||||
|
inheritRandomUnique,
|
||||||
|
} = input;
|
||||||
|
|
||||||
|
if (userCount <= 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const itemTypes = Object.keys(config.allItems);
|
||||||
|
const itemTypeCnt = itemTypes.length;
|
||||||
|
if (itemTypeCnt <= 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const relYear = currentYear - startYear;
|
||||||
|
let maxTrialCountByYear = 1;
|
||||||
|
for (const [targetYear, targetTrialCnt] of config.maxUniqueItemLimit) {
|
||||||
|
if (relYear < targetYear) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
maxTrialCountByYear = targetTrialCnt;
|
||||||
|
}
|
||||||
|
|
||||||
|
let trialCnt = Math.min(itemTypeCnt, maxTrialCountByYear);
|
||||||
|
let maxCnt = itemTypeCnt;
|
||||||
|
|
||||||
|
const invalidItemTypes = new Set<string>();
|
||||||
|
const equippedItems: Array<[string, string | null]> = [
|
||||||
|
['horse', generalItems.horse],
|
||||||
|
['weapon', generalItems.weapon],
|
||||||
|
['book', generalItems.book],
|
||||||
|
['item', generalItems.item],
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const [slot, itemKey] of equippedItems) {
|
||||||
|
if (!itemKey) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const module = itemRegistry.get(itemKey);
|
||||||
|
if (!module || module.buyable) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
invalidItemTypes.add(slot);
|
||||||
|
trialCnt -= 1;
|
||||||
|
maxCnt -= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (trialCnt <= 0 || maxCnt <= 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const relMonthByInit =
|
||||||
|
joinYearMonth(currentYear, currentMonth) - joinYearMonth(initYear, initMonth);
|
||||||
|
const availableBuyUnique = relMonthByInit >= config.minMonthToAllowInheritItem;
|
||||||
|
|
||||||
|
let prob: number;
|
||||||
|
if (scenarioId < 100) {
|
||||||
|
prob = 1 / (userCount * 3 * itemTypeCnt);
|
||||||
|
} else {
|
||||||
|
prob = 1 / (userCount * itemTypeCnt);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (acquireType === '설문조사') {
|
||||||
|
prob = 1 / (userCount * itemTypeCnt * 0.7 / 3);
|
||||||
|
} else if (acquireType === '랜덤 임관') {
|
||||||
|
prob = 1 / (userCount * itemTypeCnt / 10 / 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
prob *= config.uniqueTrialCoef;
|
||||||
|
if (prob > config.maxUniqueTrialProb) {
|
||||||
|
prob = config.maxUniqueTrialProb;
|
||||||
|
}
|
||||||
|
|
||||||
|
prob /= Math.sqrt(7);
|
||||||
|
const moreProb = Math.pow(10, 1 / 4);
|
||||||
|
|
||||||
|
if (inheritRandomUnique && availableBuyUnique) {
|
||||||
|
prob = 1;
|
||||||
|
} else if (acquireType === '건국') {
|
||||||
|
prob = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
let success = false;
|
||||||
|
for (let i = 0; i < maxCnt; i += 1) {
|
||||||
|
if (rng.nextBool(prob)) {
|
||||||
|
success = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
prob *= moreProb;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!success) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const availableUnique: Array<[string, number]> = [];
|
||||||
|
for (const itemType of itemTypes) {
|
||||||
|
if (invalidItemTypes.has(itemType)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const itemEntries = config.allItems[itemType] ?? {};
|
||||||
|
for (const [itemKey, rawCount] of Object.entries(itemEntries)) {
|
||||||
|
const count = readNumber(rawCount, 0);
|
||||||
|
if (count <= 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const module = itemRegistry.get(itemKey);
|
||||||
|
if (!module || module.buyable) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const remain = count - (occupiedUniqueCounts.get(itemKey) ?? 0);
|
||||||
|
if (remain > 0) {
|
||||||
|
availableUnique.push([itemKey, remain]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (availableUnique.length === 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return rng.choiceUsingWeightPair(availableUnique);
|
||||||
|
};
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
|
||||||
|
import { LiteHashDRBG, RandUtil } from '@sammo-ts/common';
|
||||||
|
import type { GeneralItemSlots } from '../src/domain/entities.js';
|
||||||
|
import type { ItemModule } from '../src/items/types.js';
|
||||||
|
import {
|
||||||
|
buildVoteUniqueSeed,
|
||||||
|
countOccupiedUniqueItems,
|
||||||
|
resolveUniqueConfig,
|
||||||
|
rollUniqueLottery,
|
||||||
|
} from '../src/rewards/uniqueLottery.js';
|
||||||
|
|
||||||
|
const buildItem = (key: string, slot: ItemModule['slot'], buyable = false): ItemModule => ({
|
||||||
|
key,
|
||||||
|
rawName: key,
|
||||||
|
name: key,
|
||||||
|
info: key,
|
||||||
|
slot,
|
||||||
|
cost: null,
|
||||||
|
buyable,
|
||||||
|
consumable: false,
|
||||||
|
reqSecu: 0,
|
||||||
|
unique: !buyable,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('unique lottery', () => {
|
||||||
|
it('returns deterministic item for fixed seed', () => {
|
||||||
|
const itemRegistry = new Map<string, ItemModule>([
|
||||||
|
['itemB', buildItem('itemB', 'weapon', false)],
|
||||||
|
]);
|
||||||
|
const config = resolveUniqueConfig({
|
||||||
|
allItems: {
|
||||||
|
weapon: {
|
||||||
|
itemB: 1,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
maxUniqueItemLimit: [[-1, 1]],
|
||||||
|
uniqueTrialCoef: 10,
|
||||||
|
maxUniqueTrialProb: 10,
|
||||||
|
minMonthToAllowInheritItem: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
const rngSeed = buildVoteUniqueSeed('seed', 1, 1);
|
||||||
|
const rng = new RandUtil(LiteHashDRBG.build(rngSeed));
|
||||||
|
const result = rollUniqueLottery({
|
||||||
|
rng,
|
||||||
|
config,
|
||||||
|
itemRegistry,
|
||||||
|
generalItems: { horse: null, weapon: null, book: null, item: null },
|
||||||
|
occupiedUniqueCounts: new Map(),
|
||||||
|
scenarioId: 200,
|
||||||
|
userCount: 1,
|
||||||
|
currentYear: 200,
|
||||||
|
currentMonth: 1,
|
||||||
|
startYear: 180,
|
||||||
|
initYear: 180,
|
||||||
|
initMonth: 1,
|
||||||
|
acquireType: '설문조사',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result).toBe('itemB');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('counts only non-buyable equipped items', () => {
|
||||||
|
const itemRegistry = new Map<string, ItemModule>([
|
||||||
|
['uniqueItem', buildItem('uniqueItem', 'weapon', false)],
|
||||||
|
['buyableItem', buildItem('buyableItem', 'book', true)],
|
||||||
|
]);
|
||||||
|
const generals: GeneralItemSlots[] = [
|
||||||
|
{ horse: null, weapon: 'uniqueItem', book: null, item: null },
|
||||||
|
{ horse: null, weapon: null, book: 'buyableItem', item: null },
|
||||||
|
];
|
||||||
|
|
||||||
|
const counts = countOccupiedUniqueItems(generals, itemRegistry);
|
||||||
|
expect(counts.get('uniqueItem')).toBe(1);
|
||||||
|
expect(counts.get('buyableItem')).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user