제작된 퀴즈 6단계: 플레이 통계 상세(문제마다 힌트 시간/투표, 정답이 아닌 입력 수·사람 수, 다시듣기, 제작된 퀴즈·곡; DB에 없는 퀴즈 곡도 기록 — song_plays.song_id nullable로 다시 만듦). 관리자 통계 곡별·퀴즈별(퀴즈 → 곡별 어려운 순) 탭. 난이도 제안이 힌트도 보고, 검토 대기 → 난이도 조정에 근거(출제·정답·힌트·오답·다시듣기)와 함께 승인/반영 안 함(5번 더 나온 뒤 다시). 메뉴 개수에 포함

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-22 13:15:08 +09:00
parent b999310eb9
commit a0907b551b
12 changed files with 424 additions and 25 deletions

View File

@@ -162,6 +162,12 @@ describe('admin artists, genres, stats, rooms, collect, room defaults', () => {
expect((await call('/stats')).body.rows.find((r: any) => r.id === easy)).toMatchObject({ level: 4 });
expect(suggestLevel(1, 10, 10, 1000)).toBeNull();
expect(suggestLevel(5, 4, 4, 1000)).toBeNull(); // too few plays
expect(suggestLevel(5, 10, 9, 3000, 5)).toBeNull(); // guessed fast, but only with hints: not easier
expect(suggestLevel(5, 10, 5, 9000, 7)).toBe(6); // half guessed with hints most of the time: harder
const lv = (await call('/level-reviews')).body.rows;
expect(lv.find((r: any) => r.id === hard).evidence[1]).toContain('정답 나온 문제 1번');
await call(`/level-reviews/${hard}/dismiss`, { method: 'POST' });
expect((await call('/level-reviews')).body.rows.find((r: any) => r.id === hard)).toBeUndefined();
});
test('rooms: the admin sees private rooms too and can close one; players are told', async () => {

View File

@@ -172,8 +172,16 @@ test('a quiz game plays every song in order from its own 처음 position and acc
expect(g1.game!.total).toBe(3); // every song, whatever 문제 수 says
const play = (await cl.waitFor((m) => m.t === 'play' && m.n === 1)) as Msg<'play'>;
await sleep(Math.max(0, play.startAt - Date.now()) + 15);
cl.send({ t: 'chat', text: '모르겠다' });
cl.send({ t: 'chat', text: 'First' });
await cl.waitFor((m) => m.t === 'answer');
// 통계: the question's row knows the quiz, the item and the wrong try (the song is not in the DB)
const row = s.db.query<{ song_id: number | null; quiz_id: number; wrong: number; wrong_players: number; hint: string | null; how: string }, []>(
'SELECT song_id, quiz_id, wrong, wrong_players, hint, how FROM song_plays ORDER BY id DESC LIMIT 1',
).get();
expect(row).toEqual({ song_id: null, quiz_id: q.id, wrong: 1, wrong_players: 1, hint: null, how: 'correct' });
const qs = (await api(s.base, '/api/admin/stats/quizzes', { cookie: sa })).body.quizzes;
expect(qs[0]).toMatchObject({ id: q.id, questions: 1, correct: 1, wrong: 1 });
// 2nd: the DB song, 자동 → starts at 0 ("처음부터")
const p2 = (await cl.waitFor((m) => m.t === 'prepare' && m.n === 2)) as Msg<'prepare'>;
expect(p2).toMatchObject({ videoId: 'goodday0001', startSec: 0 });

View File

@@ -0,0 +1,33 @@
-- 통계 more detail: hints, wrong tries, replays, and which 제작된 퀴즈 the question came from.
-- song_id becomes nullable: a quiz song that is not in the server DB still counts for its quiz.
CREATE TABLE song_plays_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
song_id INTEGER REFERENCES songs(id) ON DELETE CASCADE,
game_id TEXT NOT NULL,
played_at INTEGER NOT NULL,
players INTEGER NOT NULL,
winner_id TEXT,
ms INTEGER,
how TEXT NOT NULL, -- correct | skip | timeout
hint TEXT, -- NULL no hint | auto (time) | vote (직접선택)
wrong INTEGER NOT NULL DEFAULT 0, -- chat lines during the question that were not the answer
wrong_players INTEGER NOT NULL DEFAULT 0, -- players who sent at least one of those
replays INTEGER NOT NULL DEFAULT 0, -- 다시듣기 passed
quiz_id INTEGER, -- custom_quizzes.id
quiz_item_id INTEGER -- custom_quiz_items.id
);
INSERT INTO song_plays_new (id, song_id, game_id, played_at, players, winner_id, ms, how)
SELECT id, song_id, game_id, played_at, players, winner_id, ms, how FROM song_plays;
DROP TABLE song_plays;
ALTER TABLE song_plays_new RENAME TO song_plays;
CREATE INDEX song_plays_song ON song_plays(song_id);
CREATE INDEX song_plays_at ON song_plays(played_at);
CREATE INDEX song_plays_quiz ON song_plays(quiz_id, quiz_item_id);
-- 검토 대기 → 난이도 조정 "반영 안 함": hidden until the song has been played this many times.
CREATE TABLE level_dismissals (
song_id INTEGER PRIMARY KEY REFERENCES songs(id) ON DELETE CASCADE,
until_plays INTEGER NOT NULL,
by_user TEXT,
at INTEGER NOT NULL
);

View File

@@ -90,6 +90,8 @@ export class Game {
private runningSince: number | null = null;
private limitMs: number | null = null;
hint: string | null = null;
/** 통계: how the hint came (null = none), chat lines that were not the answer and who sent them, replays. */
private stat = { hint: null as 'auto' | 'vote' | null, wrong: 0, wrongBy: new Set<string>(), replays: 0 };
private lyrics: string[] | null = null;
votes = { skip: new Set<string>(), hint: new Set<string>(), replay: new Set<string>(), next: new Set<string>() };
history: GameHistoryItem[] = [];
@@ -194,6 +196,7 @@ export class Game {
this.elapsedMs = 0;
this.runningSince = null;
this.hint = null;
this.stat = { hint: null, wrong: 0, wrongBy: new Set(), replays: 0 };
this.revealUntil = null;
for (const v of Object.values(this.votes)) v.clear();
if (this.listening) {
@@ -285,8 +288,9 @@ export class Game {
this.broadcast();
}
private showHint(): void {
private showHint(how: 'auto' | 'vote' = 'auto'): void {
if (this.hint || !this.song) return;
this.stat.hint = how;
this.hint = hintText(this.song, this.room.config.answer);
if (this.lyrics && this.song.lyrics) this.lyrics = lyricsCard(this.song.lyrics, this.song.title, 1);
this.votes.hint.clear();
@@ -296,6 +300,7 @@ export class Game {
private replay(): void {
if (!this.listening || !this.song) return;
this.stat.replays++;
for (const v of Object.values(this.votes)) v.clear();
this.clipDone.clear();
this.clipOver = false;
@@ -341,10 +346,28 @@ export class Game {
this.asked.push(s.id);
try {
// 통계 (admin): never let a stats write break the game.
if (s.dbSongId !== null)
const quizId = this.room.config.quizId;
if (s.dbSongId !== null || quizId)
this.room.deps.db
.query('INSERT INTO song_plays (song_id, game_id, played_at, players, winner_id, ms, how) VALUES (?, ?, ?, ?, ?, ?, ?)')
.run(s.dbSongId, this.gameId, now, Math.max(1, this.active().length), winner, ms, how === 'end' ? 'timeout' : how);
.query(
`INSERT INTO song_plays (song_id, game_id, played_at, players, winner_id, ms, how, hint, wrong, wrong_players, replays, quiz_id, quiz_item_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(
s.dbSongId,
this.gameId,
now,
Math.max(1, this.active().length),
winner,
ms,
how === 'end' ? 'timeout' : how,
this.stat.hint,
this.stat.wrong,
this.stat.wrongBy.size,
this.stat.replays,
quizId,
quizId ? s.id : null,
);
} catch {
/* stats only */
}
@@ -455,7 +478,11 @@ export class Game {
judge(userId: string, text: string, n?: string): boolean {
if (this.phase !== 'play' || !this.song || this.firstStartAt === null || this.now() < this.firstStartAt) return false;
if (!this.participants.has(userId) || this.excluded.has(userId)) return false;
if (!isCorrect(text, this.song, this.room.config.answer, this.room.config.strict)) return false;
if (!isCorrect(text, this.song, this.room.config.answer, this.room.config.strict)) {
this.stat.wrong++;
this.stat.wrongBy.add(userId);
return false;
}
this.endQuestion(userId, 'correct', { text, n });
return true;
}
@@ -504,7 +531,7 @@ export class Game {
return need !== null && this.votes[k].size >= need;
};
if (pass('skip')) return this.endQuestion(null, 'skip');
if (pass('hint') && this.phase === 'play') this.showHint();
if (pass('hint') && this.phase === 'play') this.showHint('vote');
if (pass('replay') && this.phase === 'play' && this.firstStartAt !== null) this.replay();
}

View File

@@ -17,6 +17,10 @@ import {
mergeSongs,
parseCsv,
playStats,
quizStats,
quizItemStats,
levelReviews,
dismissLevel,
restoreSongs,
toCsv,
trashSongs,
@@ -268,6 +272,18 @@ export function mountCatalogAdmin(
return c.json({ ok: true });
});
// 통계 → 퀴즈별
app.get('/stats/quizzes', (c) => c.json({ quizzes: quizStats(d.db) }));
app.get('/stats/quizzes/:id', (c) => c.json({ items: quizItemStats(d.db, Number(c.req.param('id'))) }));
// 검토 대기 → 난이도 조정 (승인은 /stats/apply)
app.get('/level-reviews', (c) => c.json({ rows: levelReviews(d.db) }));
app.post('/level-reviews/:songId/dismiss', (c) => {
const id = Number(c.req.param('songId'));
dismissLevel(d.db, id, h.actor(c));
d.audit.log(h.actor(c), 'song.level.dismiss', String(id), null, null);
return c.json({ ok: true });
});
// ------------------------------------------------------------ rooms (진행 중 방, 강제 종료)
app.get('/rooms', (c) => c.json({ rooms: d.rooms?.adminList() ?? [] }));
app.post('/rooms/:code/close', (c) => {

View File

@@ -10,6 +10,7 @@ import { CustomQuizzes, type QuizLimits } from '../quizzes/store';
import type { YtmSong } from '../collector/ytmusic';
import { pickSearcher } from '../collector/ytmusic';
import { listSongs } from '../songs/store';
import { playStats } from '../songs/admin-ops';
import { audioFile, type AudioLinks } from '../songs/audio';
import { getImportJob, startImport, type Lavalink } from '../quizzes/playlist';
import { applyReview, listReviews, pendingCount, rejectReview, syncReviews } from '../quizzes/review';
@@ -63,7 +64,11 @@ export function mountQuizAdmin(app: Hono<Env>, d: QuizAdminDeps, h: { actor: (c:
});
// ---------------------------------------------------------------- 검토 대기 (전체공개 퀴즈 → 서버 노래 DB)
app.get('/reviews/count', (c) => c.json({ pending: pendingCount(d.db) }));
app.get('/reviews/count', (c) => {
const levels = playStats(d.db, { sort: 'suggest', size: 1 }).suggestions;
const songs = pendingCount(d.db);
return c.json({ pending: songs + levels, songs, levels });
});
app.get('/reviews', (c) => c.json({ reviews: listReviews(d.db, c.req.query('status') === 'done' ? 'done' : 'pending'), pending: pendingCount(d.db) }));
app.post('/reviews/:id/apply', async (c) => {
const id = Number(c.req.param('id'));

View File

@@ -273,33 +273,114 @@ export const MIN_PLAYS_FOR_SUGGESTION = 5;
/**
* Level suggestion from how people did (docs/02 통계 → 난이도 조정 제안).
* Levels go 1 (everyone knows) → 10 (nobody): mostly guessed and fast → one easier, rarely guessed → one harder.
* Levels go 1 (everyone knows) → 10 (nobody): mostly guessed, fast and without hints → one easier;
* rarely guessed, or guessed only half the time with hints most of the time → one harder.
*/
export function suggestLevel(level: number | null, plays: number, correct: number, avgMs: number | null): number | null {
export function suggestLevel(level: number | null, plays: number, correct: number, avgMs: number | null, hints = 0): number | null {
if (!level || plays < MIN_PLAYS_FOR_SUGGESTION) return null;
const rate = correct / plays;
if (rate >= 0.8 && avgMs !== null && avgMs <= 8000 && level > 1) return level - 1;
if (rate <= 0.3 && level < 10) return level + 1;
const hintRate = hints / plays;
if (rate >= 0.8 && avgMs !== null && avgMs <= 8000 && hintRate < 0.3 && level > 1) return level - 1;
if ((rate <= 0.3 || (rate <= 0.5 && hintRate >= 0.6)) && level < 10) return level + 1;
return null;
}
export function playStats(db: Database, opts: { sort?: 'plays' | 'correct' | 'fast' | 'suggest'; page?: number } = {}) {
const size = 50;
export interface StatRow {
id: number;
title: string;
artist: string;
level: number | null;
plays: number;
correct: number;
avg_ms: number | null;
rate: number;
last_at: number;
hints: number;
wrong: number;
wrong_players: number;
replays: number;
players: number;
suggest: number | null;
}
/** The numbers behind a suggestion, in plain words for 검토 대기 → 난이도 조정. */
export function evidence(r: Pick<StatRow, 'plays' | 'correct' | 'avg_ms' | 'hints' | 'wrong' | 'wrong_players' | 'replays' | 'players'>): string[] {
const pct = (a: number, b: number) => `${Math.round((a / Math.max(1, b)) * 100)}%`;
return [
`${r.plays}번 출제, 문제마다 평균 ${(r.players / Math.max(1, r.plays)).toFixed(1)}명 참가`,
`정답 나온 문제 ${r.correct}번(${pct(r.correct, r.plays)}), 못 맞힌 문제 ${r.plays - r.correct}번`,
r.avg_ms !== null ? `맞힌 때 평균 ${(r.avg_ms / 1000).toFixed(1)}초` : '맞힌 기록 없음',
`힌트 공개 ${r.hints}번(${pct(r.hints, r.plays)})`,
`정답이 아닌 입력 ${r.wrong}번(문제당 ${(r.wrong / Math.max(1, r.plays)).toFixed(1)}번, 연인원 ${r.wrong_players}명)`,
`다시듣기 ${r.replays}번`,
];
}
export function playStats(db: Database, opts: { sort?: 'plays' | 'correct' | 'fast' | 'suggest'; page?: number; size?: number } = {}) {
const size = opts.size ?? 50;
const page = Math.max(0, opts.page ?? 0);
const order = { plays: 'plays DESC', correct: 'rate DESC', fast: 'avg_ms IS NULL, avg_ms', suggest: 'plays DESC' }[opts.sort ?? 'plays'];
// "반영 안 함" hides a suggestion until the song has been played 5 more times
const dismissed = new Map(db.query<{ song_id: number; until_plays: number }, []>('SELECT song_id, until_plays FROM level_dismissals').all().map((r) => [r.song_id, r.until_plays]));
const all = db
.query<{ id: number; title: string; artist: string; level: number | null; plays: number; correct: number; avg_ms: number | null; rate: number; last_at: number }, []>(
.query<Omit<StatRow, 'suggest'>, []>(
`SELECT s.id, s.title, s.artist, lv.level, COUNT(*) plays, SUM(p.winner_id IS NOT NULL) correct, AVG(p.ms) avg_ms,
1.0 * SUM(p.winner_id IS NOT NULL) / COUNT(*) rate, MAX(p.played_at) last_at
1.0 * SUM(p.winner_id IS NOT NULL) / COUNT(*) rate, MAX(p.played_at) last_at, SUM(p.hint IS NOT NULL) hints, SUM(p.wrong) wrong,
SUM(p.wrong_players) wrong_players, SUM(p.replays) replays, SUM(p.players) players
FROM song_plays p JOIN songs s ON s.id = p.song_id AND s.deleted_at IS NULL
LEFT JOIN song_levels lv ON lv.song_id = s.id AND lv.scope = 'all'
GROUP BY s.id ORDER BY ${order}, s.id`,
)
.all()
.map((r) => ({ ...r, avg_ms: r.avg_ms === null ? null : Math.round(r.avg_ms), suggest: suggestLevel(r.level, r.plays, r.correct, r.avg_ms) }));
.map((r): StatRow => {
const suggest = suggestLevel(r.level, r.plays, r.correct, r.avg_ms, r.hints);
return { ...r, avg_ms: r.avg_ms === null ? null : Math.round(r.avg_ms), suggest: suggest !== null && (dismissed.get(r.id) ?? 0) > r.plays ? null : suggest };
});
const list = opts.sort === 'suggest' ? all.filter((r) => r.suggest !== null) : all;
const day = 86400_000;
const since = Date.now() - day;
const today = db.query<{ plays: number; games: number }, [number]>('SELECT COUNT(*) plays, COUNT(DISTINCT game_id) games FROM song_plays WHERE played_at >= ?').get(since)!;
return { total: list.length, rows: list.slice(page * size, page * size + size), pageSize: size, today, suggestions: all.filter((r) => r.suggest !== null).length };
}
/** 검토 대기 → 난이도 조정: every suggestion with its evidence. */
export function levelReviews(db: Database) {
return playStats(db, { sort: 'suggest', size: 500 }).rows.map((r) => ({ ...r, evidence: evidence(r) }));
}
export function dismissLevel(db: Database, songId: number, by: string, now = Date.now()): void {
const plays = db.query<{ n: number }, [number]>('SELECT COUNT(*) n FROM song_plays WHERE song_id = ?').get(songId)!.n;
db.query('INSERT INTO level_dismissals (song_id, until_plays, by_user, at) VALUES (?, ?, ?, ?) ON CONFLICT(song_id) DO UPDATE SET until_plays = excluded.until_plays, by_user = excluded.by_user, at = excluded.at').run(
songId,
plays + MIN_PLAYS_FOR_SUGGESTION,
by,
now,
);
}
/** 통계 → 퀴즈별: games, questions, how people did, per 제작된 퀴즈. */
export function quizStats(db: Database) {
return db
.query<{ id: number; name: string; visibility: string; owner: string | null; songs: number; plays: number; games: number; questions: number; correct: number; avg_ms: number | null; hints: number; wrong: number; replays: number; last_at: number | null }, []>(
`SELECT q.id, q.name, q.visibility, u.nickname owner, (SELECT COUNT(*) FROM custom_quiz_items i WHERE i.quiz_id = q.id) songs, q.plays,
COUNT(DISTINCT p.game_id) games, COUNT(p.id) questions, COALESCE(SUM(p.winner_id IS NOT NULL), 0) correct, AVG(p.ms) avg_ms,
COALESCE(SUM(p.hint IS NOT NULL), 0) hints, COALESCE(SUM(p.wrong), 0) wrong, COALESCE(SUM(p.replays), 0) replays, MAX(p.played_at) last_at
FROM custom_quizzes q LEFT JOIN users u ON u.id = q.owner_id LEFT JOIN song_plays p ON p.quiz_id = q.id
WHERE q.deleted_at IS NULL GROUP BY q.id ORDER BY questions DESC, q.updated_at DESC`,
)
.all()
.map((r) => ({ ...r, avg_ms: r.avg_ms === null ? null : Math.round(r.avg_ms) }));
}
/** One quiz's songs: how each did (hardest first). */
export function quizItemStats(db: Database, quizId: number) {
return db
.query<{ id: number; pos: number; title: string; artist: string; song_id: number | null; plays: number; correct: number; avg_ms: number | null; hints: number; wrong: number; replays: number }, [number]>(
`SELECT i.id, i.pos, i.title, i.artist, i.song_id, COUNT(p.id) plays, COALESCE(SUM(p.winner_id IS NOT NULL), 0) correct, AVG(p.ms) avg_ms,
COALESCE(SUM(p.hint IS NOT NULL), 0) hints, COALESCE(SUM(p.wrong), 0) wrong, COALESCE(SUM(p.replays), 0) replays
FROM custom_quiz_items i LEFT JOIN song_plays p ON p.quiz_item_id = i.id
WHERE i.quiz_id = ? GROUP BY i.id ORDER BY plays = 0, 1.0 * correct / MAX(plays, 1), i.pos`,
)
.all(quizId)
.map((r) => ({ ...r, avg_ms: r.avg_ms === null ? null : Math.round(r.avg_ms) }));
}