Импорт вопросов из таблицы CSV/Excel
- разбор таблицы: разделитель и кодировка определяются сами - ошибки с номерами строк вместо путей в JSON - пути к медиа дописываются, тип угадывается по расширению - CLI-скрипт с --check и отдельным файлом финала - пример таблицы в examples/ и тест, что он импортируется
This commit is contained in:
1 parent
89eeea4855
commit
2f0263e59b
10 files changed
+1011
-8
No files matched your search
@@ -0,0 +1,487 @@
|
||||
/**
|
||||
* Импорт пака из таблицы (CSV/TSV).
|
||||
*
|
||||
* Люди пишут вопросы в Excel и Google Sheets, а не в JSON с кавычками. Поэтому
|
||||
* здесь живёт разбор таблицы: он прощает формат (разделитель, кавычки, переводы
|
||||
* строк внутри клетки) и ругается номерами строк, а не путями в JSON.
|
||||
*
|
||||
* Модуль чистый: текст на входе, пак или список ошибок на выходе.
|
||||
*/
|
||||
|
||||
import type {
|
||||
Cell,
|
||||
CellKind,
|
||||
MediaKind,
|
||||
Pack,
|
||||
PackSettings,
|
||||
Question,
|
||||
Round,
|
||||
Theme,
|
||||
} from './types'
|
||||
import { DEFAULT_SETTINGS } from './pack'
|
||||
|
||||
export interface ImportError {
|
||||
/** Номер строки в файле; 0 — ошибка уровня всего пака. */
|
||||
line: number
|
||||
message: string
|
||||
}
|
||||
|
||||
export interface ImportOptions {
|
||||
id: string
|
||||
title: string
|
||||
settings?: Partial<PackSettings>
|
||||
final?: { question: string; answer: string; comment?: string }
|
||||
}
|
||||
|
||||
export type ImportResult =
|
||||
| { ok: true; pack: Pack; stats: { rounds: number; themes: number; cells: number } }
|
||||
| { ok: false; errors: ImportError[] }
|
||||
|
||||
// ─── Разбор таблицы ────────────────────────────────────────────────────────
|
||||
|
||||
export interface TableRow {
|
||||
cells: string[]
|
||||
/** Физическая строка файла — по ней и ругаемся. */
|
||||
line: number
|
||||
}
|
||||
|
||||
export interface Table {
|
||||
header: string[]
|
||||
rows: TableRow[]
|
||||
}
|
||||
|
||||
const DELIMITERS = [',', ';', '\t'] as const
|
||||
|
||||
function firstLine(text: string): string {
|
||||
let inQuotes = false
|
||||
for (let index = 0; index < text.length; index += 1) {
|
||||
const char = text[index]
|
||||
if (char === '"') inQuotes = !inQuotes
|
||||
else if (!inQuotes && (char === '\n' || char === '\r')) return text.slice(0, index)
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
/**
|
||||
* Русский Excel сохраняет CSV через «;», английский — через «,».
|
||||
* Считаем разделители в первой строке вне кавычек и берём самый частый.
|
||||
*/
|
||||
export function detectDelimiter(text: string): string {
|
||||
const line = firstLine(text.replace(/^\uFEFF/, ''))
|
||||
let best = ','
|
||||
let bestCount = 0
|
||||
|
||||
for (const delimiter of DELIMITERS) {
|
||||
let count = 0
|
||||
let inQuotes = false
|
||||
for (let index = 0; index < line.length; index += 1) {
|
||||
const char = line[index]
|
||||
if (char === '"') inQuotes = !inQuotes
|
||||
else if (!inQuotes && char === delimiter) count += 1
|
||||
}
|
||||
if (count > bestCount) {
|
||||
best = delimiter
|
||||
bestCount = count
|
||||
}
|
||||
}
|
||||
|
||||
return best
|
||||
}
|
||||
|
||||
export function parseTable(text: string): Table {
|
||||
const source = text.replace(/^\uFEFF/, '')
|
||||
const delimiter = detectDelimiter(source)
|
||||
const rows: TableRow[] = []
|
||||
|
||||
let record: string[] = []
|
||||
let field = ''
|
||||
let line = 1
|
||||
let recordLine = 1
|
||||
let inQuotes = false
|
||||
let touched = false
|
||||
|
||||
const pushField = (): void => {
|
||||
record.push(field)
|
||||
field = ''
|
||||
touched = true
|
||||
}
|
||||
|
||||
const pushRecord = (): void => {
|
||||
pushField()
|
||||
if (!record.every((cell) => cell.trim() === '')) {
|
||||
rows.push({ cells: record, line: recordLine })
|
||||
}
|
||||
record = []
|
||||
touched = false
|
||||
}
|
||||
|
||||
for (let index = 0; index < source.length; index += 1) {
|
||||
const char = source[index]
|
||||
|
||||
if (inQuotes) {
|
||||
if (char === '"') {
|
||||
if (source[index + 1] === '"') {
|
||||
field += '"'
|
||||
index += 1
|
||||
} else {
|
||||
inQuotes = false
|
||||
}
|
||||
} else {
|
||||
if (char === '\n') line += 1
|
||||
field += char
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if (char === '"') {
|
||||
inQuotes = true
|
||||
touched = true
|
||||
continue
|
||||
}
|
||||
if (char === delimiter) {
|
||||
pushField()
|
||||
continue
|
||||
}
|
||||
if (char === '\r') continue
|
||||
if (char === '\n') {
|
||||
pushRecord()
|
||||
line += 1
|
||||
recordLine = line
|
||||
continue
|
||||
}
|
||||
|
||||
field += char
|
||||
touched = true
|
||||
}
|
||||
|
||||
if (touched || field.length > 0 || record.length > 0) pushRecord()
|
||||
|
||||
const header = rows.shift()
|
||||
return { header: header?.cells ?? [], rows }
|
||||
}
|
||||
|
||||
// ─── Заголовки ─────────────────────────────────────────────────────────────
|
||||
|
||||
type Column = 'round' | 'theme' | 'value' | 'question' | 'answer' | 'comment' | 'kind' | 'media'
|
||||
|
||||
const HEADER_ALIASES: Record<string, Column> = {
|
||||
раунд: 'round',
|
||||
round: 'round',
|
||||
тема: 'theme',
|
||||
theme: 'theme',
|
||||
стоимость: 'value',
|
||||
номинал: 'value',
|
||||
очки: 'value',
|
||||
value: 'value',
|
||||
вопрос: 'question',
|
||||
question: 'question',
|
||||
ответ: 'answer',
|
||||
answer: 'answer',
|
||||
комментарий: 'comment',
|
||||
примечание: 'comment',
|
||||
comment: 'comment',
|
||||
тип: 'kind',
|
||||
kind: 'kind',
|
||||
медиа: 'media',
|
||||
файл: 'media',
|
||||
media: 'media',
|
||||
}
|
||||
|
||||
function normalizeHeader(raw: string): string {
|
||||
return raw
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[«»"'`]/g, '')
|
||||
.replace(/\s+/g, ' ')
|
||||
}
|
||||
|
||||
const REQUIRED_COLUMNS: Column[] = ['theme', 'value', 'question', 'answer']
|
||||
|
||||
// ─── Значения ──────────────────────────────────────────────────────────────
|
||||
|
||||
const KIND_ALIASES: Record<string, CellKind> = {
|
||||
'': 'normal',
|
||||
normal: 'normal',
|
||||
обычный: 'normal',
|
||||
обычная: 'normal',
|
||||
кот: 'cat_in_bag',
|
||||
'кот в мешке': 'cat_in_bag',
|
||||
cat: 'cat_in_bag',
|
||||
cat_in_bag: 'cat_in_bag',
|
||||
аукцион: 'auction',
|
||||
auction: 'auction',
|
||||
супер: 'super',
|
||||
'супер-вопрос': 'super',
|
||||
super: 'super',
|
||||
}
|
||||
|
||||
const MEDIA_BY_EXTENSION: Array<[MediaKind, string[]]> = [
|
||||
['audio', ['.mp3', '.wav', '.ogg', '.m4a', '.aac']],
|
||||
['image', ['.jpg', '.jpeg', '.png', '.webp', '.gif']],
|
||||
['video', ['.mp4', '.webm', '.mov']],
|
||||
]
|
||||
|
||||
function mediaKindOf(source: string): MediaKind | null {
|
||||
const lower = source.toLowerCase()
|
||||
for (const [kind, extensions] of MEDIA_BY_EXTENSION) {
|
||||
if (extensions.some((extension) => lower.endsWith(extension))) return kind
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** «song.mp3» → «/media/<id-пака>/song.mp3»; полный путь оставляем как есть. */
|
||||
function normalizeMediaSource(raw: string, packId: string): string {
|
||||
const value = raw.trim().replace(/\\/g, '/')
|
||||
if (value.startsWith('/media/')) return value
|
||||
return `/media/${packId}/${value.replace(/^\.?\//, '')}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Финальный вопрос — отдельный маленький файл: одна строка, три колонки.
|
||||
* Заголовок необязателен: если его нет, первая строка считается данными.
|
||||
*/
|
||||
export function parseFinal(
|
||||
text: string,
|
||||
):
|
||||
| { ok: true; final: { question: string; answer: string; comment?: string } }
|
||||
| { ok: false; errors: ImportError[] } {
|
||||
const table = parseTable(text)
|
||||
if (table.rows.length === 0 && table.header.length === 0) {
|
||||
return { ok: false, errors: [{ line: 1, message: 'файл финала пуст' }] }
|
||||
}
|
||||
|
||||
const columns = new Map<Column, number>()
|
||||
table.header.forEach((raw, index) => {
|
||||
const column = HEADER_ALIASES[normalizeHeader(raw)]
|
||||
if (column && !columns.has(column)) columns.set(column, index)
|
||||
})
|
||||
|
||||
const hasHeader = columns.has('question') || columns.has('answer')
|
||||
const rows = hasHeader ? table.rows : [{ cells: table.header, line: 1 }, ...table.rows]
|
||||
const row = rows[0]
|
||||
if (!row) return { ok: false, errors: [{ line: 1, message: 'в файле финала нет вопроса' }] }
|
||||
|
||||
const take = (column: Column, fallback: number): string => {
|
||||
const index = columns.get(column) ?? fallback
|
||||
return (row.cells[index] ?? '').trim()
|
||||
}
|
||||
|
||||
const question = take('question', 0)
|
||||
const answer = take('answer', 1)
|
||||
const comment = take('comment', 2)
|
||||
|
||||
if (!question) return { ok: false, errors: [{ line: row.line, message: 'не указан вопрос' }] }
|
||||
if (!answer) return { ok: false, errors: [{ line: row.line, message: 'не указан ответ' }] }
|
||||
|
||||
return { ok: true, final: { question, answer, ...(comment ? { comment } : {}) } }
|
||||
}
|
||||
|
||||
interface Entry { line: number
|
||||
round: string
|
||||
theme: string
|
||||
value: number
|
||||
question: string
|
||||
answer: string
|
||||
comment?: string
|
||||
kind: CellKind
|
||||
media?: string
|
||||
}
|
||||
|
||||
// ─── Сборка пака ───────────────────────────────────────────────────────────
|
||||
|
||||
export function tableToPack(text: string, options: ImportOptions): ImportResult {
|
||||
const table = parseTable(text)
|
||||
const errors: ImportError[] = []
|
||||
|
||||
const columns = new Map<Column, number>()
|
||||
table.header.forEach((raw, index) => {
|
||||
const column = HEADER_ALIASES[normalizeHeader(raw)]
|
||||
if (column && !columns.has(column)) columns.set(column, index)
|
||||
})
|
||||
|
||||
const missing = REQUIRED_COLUMNS.filter((column) => !columns.has(column))
|
||||
if (missing.length > 0) {
|
||||
const names: Record<string, string> = {
|
||||
theme: 'Тема',
|
||||
value: 'Стоимость',
|
||||
question: 'Вопрос',
|
||||
answer: 'Ответ',
|
||||
}
|
||||
return {
|
||||
ok: false,
|
||||
errors: [
|
||||
{
|
||||
line: 1,
|
||||
message: `в заголовке нет колонок: ${missing.map((column) => names[column]).join(', ')}`,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
const cell = (row: TableRow, column: Column): string => {
|
||||
const index = columns.get(column)
|
||||
if (index === undefined) return ''
|
||||
return (row.cells[index] ?? '').trim()
|
||||
}
|
||||
|
||||
const entries: Entry[] = []
|
||||
|
||||
for (const row of table.rows) {
|
||||
const theme = cell(row, 'theme')
|
||||
const valueRaw = cell(row, 'value')
|
||||
const question = cell(row, 'question')
|
||||
const answer = cell(row, 'answer')
|
||||
const comment = cell(row, 'comment')
|
||||
const kindRaw = cell(row, 'kind')
|
||||
const mediaRaw = cell(row, 'media')
|
||||
|
||||
if (!theme && !question && !answer) continue
|
||||
|
||||
if (!theme) {
|
||||
errors.push({ line: row.line, message: 'не указана тема' })
|
||||
continue
|
||||
}
|
||||
const value = Number(valueRaw.replace(',', '.'))
|
||||
if (!Number.isInteger(value) || value <= 0) {
|
||||
errors.push({ line: row.line, message: `номинал должен быть целым числом: «${valueRaw}»` })
|
||||
continue
|
||||
}
|
||||
if (!answer) {
|
||||
errors.push({ line: row.line, message: 'не указан ответ' })
|
||||
continue
|
||||
}
|
||||
const kind = KIND_ALIASES[normalizeHeader(kindRaw)]
|
||||
if (!kind) {
|
||||
errors.push({ line: row.line, message: `неизвестный тип клетки: «${kindRaw}»` })
|
||||
continue
|
||||
}
|
||||
|
||||
let media: string | undefined
|
||||
if (mediaRaw) {
|
||||
media = normalizeMediaSource(mediaRaw, options.id)
|
||||
if (!mediaKindOf(media)) {
|
||||
errors.push({
|
||||
line: row.line,
|
||||
message: `не понять, что за медиа: «${mediaRaw}» (ожидаются mp3, wav, png, jpg, mp4)`,
|
||||
})
|
||||
continue
|
||||
}
|
||||
}
|
||||
if (!question && !media) {
|
||||
errors.push({ line: row.line, message: 'нужен вопрос или медиа' })
|
||||
continue
|
||||
}
|
||||
|
||||
entries.push({
|
||||
line: row.line,
|
||||
round: cell(row, 'round') || 'Раунд 1',
|
||||
theme,
|
||||
value,
|
||||
question,
|
||||
answer,
|
||||
comment: comment || undefined,
|
||||
kind,
|
||||
media,
|
||||
})
|
||||
}
|
||||
|
||||
if (entries.length === 0) {
|
||||
return {
|
||||
ok: false,
|
||||
errors: errors.length > 0 ? errors : [{ line: 0, message: 'в таблице нет ни одной клетки' }],
|
||||
}
|
||||
}
|
||||
|
||||
// Раунды и темы — в порядке появления в таблице, клетки — по возрастанию номинала.
|
||||
const roundOrder: string[] = []
|
||||
const themeOrder = new Map<string, string[]>()
|
||||
const cells = new Map<string, Entry[]>()
|
||||
|
||||
for (const entry of entries) {
|
||||
if (!roundOrder.includes(entry.round)) {
|
||||
roundOrder.push(entry.round)
|
||||
themeOrder.set(entry.round, [])
|
||||
}
|
||||
const themes = themeOrder.get(entry.round)
|
||||
if (themes && !themes.includes(entry.theme)) themes.push(entry.theme)
|
||||
|
||||
const key = `${entry.round}\u0000${entry.theme}`
|
||||
const list = cells.get(key) ?? []
|
||||
list.push(entry)
|
||||
cells.set(key, list)
|
||||
}
|
||||
|
||||
for (const roundTitle of roundOrder) {
|
||||
const themes = themeOrder.get(roundTitle) ?? []
|
||||
if (themes.length === 0) continue
|
||||
|
||||
const sizes = new Set(
|
||||
themes.map((theme) => (cells.get(`${roundTitle}\u0000${theme}`) ?? []).length),
|
||||
)
|
||||
if (sizes.size > 1) {
|
||||
const detail = themes
|
||||
.map((theme) => `${theme} — ${(cells.get(`${roundTitle}\u0000${theme}`) ?? []).length}`)
|
||||
.join(', ')
|
||||
errors.push({
|
||||
line: 0,
|
||||
message: `в раунде «${roundTitle}» у тем разное число клеток: ${detail}. Табло — прямоугольник, выровняйте.`,
|
||||
})
|
||||
}
|
||||
|
||||
for (const theme of themes) {
|
||||
const list = cells.get(`${roundTitle}\u0000${theme}`) ?? []
|
||||
const seen = new Set<number>()
|
||||
for (const entry of list) {
|
||||
if (seen.has(entry.value)) {
|
||||
errors.push({
|
||||
line: entry.line,
|
||||
message: `в теме «${theme}» повторяется номинал ${entry.value}`,
|
||||
})
|
||||
}
|
||||
seen.add(entry.value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (errors.length > 0) return { ok: false, errors }
|
||||
|
||||
const rounds: Round[] = roundOrder.map((roundTitle, roundIndex) => {
|
||||
const themes = (themeOrder.get(roundTitle) ?? []).map((themeTitle, themeIndex) => {
|
||||
const list = (cells.get(`${roundTitle}\u0000${themeTitle}`) ?? []).sort(
|
||||
(left, right) => left.value - right.value,
|
||||
)
|
||||
const builtCells: Cell[] = list.map((entry) => {
|
||||
const question: Question = { answer: entry.answer }
|
||||
if (entry.question) question.text = entry.question
|
||||
if (entry.media) question.media = { kind: mediaKindOf(entry.media) ?? 'audio', src: entry.media }
|
||||
if (entry.comment) question.comment = entry.comment
|
||||
return { value: entry.value, kind: entry.kind, question }
|
||||
})
|
||||
|
||||
return { id: `t${themeIndex + 1}`, title: themeTitle, cells: builtCells } satisfies Theme
|
||||
})
|
||||
|
||||
return { id: `r${roundIndex + 1}`, title: roundTitle, themes }
|
||||
})
|
||||
|
||||
const pack: Pack = {
|
||||
id: options.id,
|
||||
title: options.title,
|
||||
settings: { ...DEFAULT_SETTINGS, ...options.settings },
|
||||
rounds,
|
||||
}
|
||||
if (options.final) {
|
||||
// В паке финал — это Question, а не строка: у него есть text и answer.
|
||||
const question: Question = { text: options.final.question, answer: options.final.answer }
|
||||
if (options.final.comment) question.comment = options.final.comment
|
||||
pack.final = { question }
|
||||
}
|
||||
|
||||
const stats = {
|
||||
rounds: rounds.length,
|
||||
themes: rounds.reduce((sum, round) => sum + round.themes.length, 0),
|
||||
cells: entries.length,
|
||||
}
|
||||
|
||||
return { ok: true, pack, stats }
|
||||
}
|
||||
@@ -9,9 +9,19 @@ export {
|
||||
roundCellKeys,
|
||||
isRoundComplete,
|
||||
effectiveValue,
|
||||
DEFAULT_SETTINGS,
|
||||
} from './pack'
|
||||
export type { CellKeyParts, FoundCell, ParsePackResult, ParsedPack } from './pack'
|
||||
|
||||
export { detectDelimiter, parseTable, tableToPack, parseFinal } from './importer'
|
||||
export type {
|
||||
ImportError,
|
||||
ImportOptions,
|
||||
ImportResult,
|
||||
Table,
|
||||
TableRow,
|
||||
} from './importer'
|
||||
|
||||
export { applyCommand, initialState } from './game'
|
||||
export { GameEngine } from './engine'
|
||||
export type { EngineOptions } from './engine'
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
*/
|
||||
|
||||
import { z } from 'zod'
|
||||
import type { Cell, Pack, Round } from './types'
|
||||
import type { Cell, Pack, PackSettings, Round } from './types'
|
||||
|
||||
const idSchema = z
|
||||
.string()
|
||||
@@ -88,15 +88,29 @@ const roundSchema = z
|
||||
}
|
||||
})
|
||||
|
||||
/**
|
||||
* Значения по умолчанию — в одном месте: и схема, и импортёр из таблицы
|
||||
* берут их отсюда, чтобы пак из Excel ничем не отличался от написанного руками.
|
||||
*/
|
||||
export const DEFAULT_SETTINGS: PackSettings = {
|
||||
wrongPenalty: 'value',
|
||||
buzzers: true,
|
||||
finalEnabled: true,
|
||||
defaultTimeLimit: 30,
|
||||
answerTimeLimit: 20,
|
||||
auctionTimeLimit: 30,
|
||||
betTimeLimit: 20,
|
||||
}
|
||||
|
||||
const settingsSchema = z
|
||||
.object({
|
||||
wrongPenalty: z.enum(['none', 'value']).default('value'),
|
||||
buzzers: z.boolean().default(true),
|
||||
finalEnabled: z.boolean().default(true),
|
||||
defaultTimeLimit: z.number().int().positive().max(600).default(30),
|
||||
answerTimeLimit: z.number().int().positive().max(600).default(20),
|
||||
auctionTimeLimit: z.number().int().positive().max(600).default(30),
|
||||
betTimeLimit: z.number().int().positive().max(600).default(20),
|
||||
wrongPenalty: z.enum(['none', 'value']).default(DEFAULT_SETTINGS.wrongPenalty),
|
||||
buzzers: z.boolean().default(DEFAULT_SETTINGS.buzzers),
|
||||
finalEnabled: z.boolean().default(DEFAULT_SETTINGS.finalEnabled),
|
||||
defaultTimeLimit: z.number().int().positive().max(600).default(DEFAULT_SETTINGS.defaultTimeLimit),
|
||||
answerTimeLimit: z.number().int().positive().max(600).default(DEFAULT_SETTINGS.answerTimeLimit),
|
||||
auctionTimeLimit: z.number().int().positive().max(600).default(DEFAULT_SETTINGS.auctionTimeLimit),
|
||||
betTimeLimit: z.number().int().positive().max(600).default(DEFAULT_SETTINGS.betTimeLimit),
|
||||
})
|
||||
.default({})
|
||||
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
/**
|
||||
* Импортёр таблиц.
|
||||
*
|
||||
* Проверяем не только «счастливый путь», но и то, на чём люди спотыкаются:
|
||||
* запятые внутри вопроса, перевод строки внутри клетки, русский Excel с «;»,
|
||||
* опечатки в номиналах и темах.
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { detectDelimiter, parseTable, tableToPack } from '../src/index'
|
||||
import type { ImportResult } from '../src/index'
|
||||
|
||||
const OPTIONS = { id: 'test', title: 'Тест' }
|
||||
|
||||
function errorsOf(result: ImportResult): string[] {
|
||||
if (result.ok) throw new Error('ожидалась ошибка, а пак собрался')
|
||||
return result.errors.map((error) => `строка ${error.line}: ${error.message}`)
|
||||
}
|
||||
|
||||
describe('разбор таблицы', () => {
|
||||
it('понимает запятую, точку с запятой и табуляцию', () => {
|
||||
expect(detectDelimiter('a,b,c\n1,2,3')).toBe(',')
|
||||
expect(detectDelimiter('a;b;c\n1;2;3')).toBe(';')
|
||||
expect(detectDelimiter('a\tb\tc')).toBe('\t')
|
||||
})
|
||||
|
||||
it('не спотыкается о запятые и кавычки внутри вопроса', () => {
|
||||
const text = 'Тема,Вопрос\nСтол,"Кто сказал ""привет"", тот и прав, да?"\nЁлка,Просто вопрос'
|
||||
const table = parseTable(text)
|
||||
expect(table.rows[0]?.cells).toEqual(['Стол', 'Кто сказал "привет", тот и прав, да?'])
|
||||
expect(table.rows[1]?.cells).toEqual(['Ёлка', 'Просто вопрос'])
|
||||
})
|
||||
|
||||
it('держит перевод строки внутри клетки и считает строки файла', () => {
|
||||
const text = 'Тема,Вопрос\nСтол,"Первая строка\nвторая строка"\nЁлка,После многострочной'
|
||||
const table = parseTable(text)
|
||||
expect(table.rows[0]?.cells[1]).toBe('Первая строка\nвторая строка')
|
||||
// Многострочная клетка занимает две физические строки — следующая запись на 4-й.
|
||||
expect(table.rows[1]?.line).toBe(4)
|
||||
})
|
||||
|
||||
it('снимает BOM и пропускает пустые строки', () => {
|
||||
const text = '\uFEFFТема,Вопрос\n\nСтол,Вопрос\n'
|
||||
const table = parseTable(text)
|
||||
expect(table.header).toEqual(['Тема', 'Вопрос'])
|
||||
expect(table.rows).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('сборка пака', () => {
|
||||
const csv = [
|
||||
'Раунд,Тема,Стоимость,Вопрос,Ответ,Комментарий,Тип,Медиа',
|
||||
'Раунд 1,Стол,300,Вопрос три,Ответ три,,,',
|
||||
'Раунд 1,Стол,100,Вопрос один,Ответ один,Ремарка,,',
|
||||
'Раунд 1,Ёлка,100,Вопрос ёлки,Ответ ёлки,,кот в мешке,',
|
||||
'Раунд 1,Ёлка,300,Вопрос ёлки три,Ответ ёлки три,,,',
|
||||
'Раунд 1,Стол,200,Вопрос два,Ответ два,,,',
|
||||
'Раунд 1,Ёлка,200,Вопрос ёлки два,Ответ ёлки два,,аукцион,',
|
||||
].join('\n')
|
||||
|
||||
it('строит раунды, темы и сортирует клетки по номиналу', () => {
|
||||
const result = tableToPack(csv, OPTIONS)
|
||||
if (!result.ok) throw new Error(result.errors.map((e) => e.message).join(', '))
|
||||
|
||||
expect(result.stats).toEqual({ rounds: 1, themes: 2, cells: 6 })
|
||||
const round = result.pack.rounds[0]
|
||||
expect(round?.title).toBe('Раунд 1')
|
||||
expect(round?.themes.map((theme) => theme.title)).toEqual(['Стол', 'Ёлка'])
|
||||
expect(round?.themes[0]?.cells.map((cell) => cell.value)).toEqual([100, 200, 300])
|
||||
expect(round?.themes[0]?.cells[1]?.question.text).toBe('Вопрос два')
|
||||
expect(round?.themes[0]?.cells[0]?.question.comment).toBe('Ремарка')
|
||||
})
|
||||
|
||||
it('понимает русские названия типов клеток', () => {
|
||||
const result = tableToPack(csv, OPTIONS)
|
||||
if (!result.ok) throw new Error('пак не собрался')
|
||||
const tree = result.pack.rounds[0]?.themes[1]
|
||||
expect(tree?.cells[0]?.kind).toBe('cat_in_bag')
|
||||
expect(tree?.cells[1]?.kind).toBe('auction')
|
||||
expect(tree?.cells[2]?.kind).toBe('normal')
|
||||
})
|
||||
|
||||
it('дописывает путь к медиа и угадывает его тип', () => {
|
||||
const text = [
|
||||
'Тема,Стоимость,Вопрос,Ответ,Медиа',
|
||||
'Музыка,100,Что звучит?,Мелодия,song.mp3',
|
||||
'Музыка,200,Что на картинке?,Ёлка,tree.PNG',
|
||||
].join('\n')
|
||||
const result = tableToPack(text, OPTIONS)
|
||||
if (!result.ok) throw new Error(result.errors.map((e) => e.message).join(', '))
|
||||
|
||||
const cells = result.pack.rounds[0]?.themes[0]?.cells ?? []
|
||||
expect(cells[0]?.question.media).toEqual({ kind: 'audio', src: '/media/test/song.mp3' })
|
||||
expect(cells[1]?.question.media).toEqual({ kind: 'image', src: '/media/test/tree.PNG' })
|
||||
})
|
||||
|
||||
it('оставляет полный путь к медиа как есть', () => {
|
||||
const text = ['Тема,Стоимость,Вопрос,Ответ,Медиа', 'Музыка,100,?,Ответ,/media/other/a.wav'].join(
|
||||
'\n',
|
||||
)
|
||||
const result = tableToPack(text, OPTIONS)
|
||||
if (!result.ok) throw new Error('пак не собрался')
|
||||
expect(result.pack.rounds[0]?.themes[0]?.cells[0]?.question.media?.src).toBe(
|
||||
'/media/other/a.wav',
|
||||
)
|
||||
})
|
||||
|
||||
it('добавляет финальный вопрос', () => {
|
||||
const result = tableToPack(csv, {
|
||||
...OPTIONS,
|
||||
final: { question: 'Финальный вопрос', answer: 'Финальный ответ' },
|
||||
})
|
||||
if (!result.ok) throw new Error('пак не собрался')
|
||||
expect(result.pack.final?.question.text).toBe('Финальный вопрос')
|
||||
expect(result.pack.final?.question.answer).toBe('Финальный ответ')
|
||||
})
|
||||
|
||||
it('пак с финалом проходит схему', async () => {
|
||||
const { parsePack } = await import('../src/index')
|
||||
const result = tableToPack(csv, {
|
||||
...OPTIONS,
|
||||
final: { question: 'Финальный вопрос', answer: 'Ответ', comment: 'Ремарка' },
|
||||
})
|
||||
if (!result.ok) throw new Error('пак не собрался')
|
||||
|
||||
const validated = parsePack(result.pack)
|
||||
if (!validated.ok) throw new Error(validated.errors.join(', '))
|
||||
expect(validated.pack.final?.question.comment).toBe('Ремарка')
|
||||
})
|
||||
|
||||
it('собранный пак проходит схему', async () => {
|
||||
const { parsePack } = await import('../src/index')
|
||||
const result = tableToPack(csv, OPTIONS)
|
||||
if (!result.ok) throw new Error('пак не собрался')
|
||||
const validated = parsePack(result.pack)
|
||||
if (!validated.ok) throw new Error(validated.errors.join(', '))
|
||||
expect(validated.pack.settings.defaultTimeLimit).toBe(30)
|
||||
})
|
||||
})
|
||||
|
||||
describe('пример из examples/', () => {
|
||||
it('импортируется без ошибок и проходит схему', async () => {
|
||||
// Пример лежит в репозитории рядом с README: если он сломается,
|
||||
// инструкция начнёт врать, а поймать это иначе нечем.
|
||||
const { readFileSync } = await import('node:fs')
|
||||
const { fileURLToPath } = await import('node:url')
|
||||
const { parsePack, parseFinal } = await import('../src/index')
|
||||
|
||||
const examplesDir = fileURLToPath(new URL('../../../examples/', import.meta.url))
|
||||
const questions = readFileSync(`${examplesDir}questions.csv`, 'utf8')
|
||||
const finalText = readFileSync(`${examplesDir}final.csv`, 'utf8')
|
||||
|
||||
const parsedFinal = parseFinal(finalText)
|
||||
if (!parsedFinal.ok) throw new Error(parsedFinal.errors.map((e) => e.message).join(', '))
|
||||
|
||||
const result = tableToPack(questions, {
|
||||
id: 'example',
|
||||
title: 'Пример из таблицы',
|
||||
final: parsedFinal.final,
|
||||
})
|
||||
if (!result.ok) throw new Error(result.errors.map((e) => `${e.line}: ${e.message}`).join(', '))
|
||||
|
||||
const validated = parsePack(result.pack)
|
||||
if (!validated.ok) throw new Error(validated.errors.join(', '))
|
||||
|
||||
const pack = validated.pack
|
||||
expect(pack.rounds[0]?.themes.map((theme) => theme.title)).toEqual([
|
||||
'Новогодний стол',
|
||||
'Ёлка',
|
||||
'Музыка',
|
||||
])
|
||||
expect(pack.rounds[0]?.themes[1]?.cells[2]?.kind).toBe('cat_in_bag')
|
||||
expect(pack.rounds[0]?.themes[2]?.cells[0]?.question.media?.kind).toBe('audio')
|
||||
expect(pack.final?.question.answer).toContain('пепел')
|
||||
})
|
||||
})
|
||||
|
||||
describe('финальный вопрос отдельным файлом', () => {
|
||||
it('читает с заголовком и без него', async () => {
|
||||
const { parseFinal } = await import('../src/index')
|
||||
|
||||
const withHeader = parseFinal('Вопрос;Ответ;Комментарий\nЧто?;Это;Ремарка')
|
||||
if (!withHeader.ok) throw new Error('не разобрался')
|
||||
expect(withHeader.final).toEqual({ question: 'Что?', answer: 'Это', comment: 'Ремарка' })
|
||||
|
||||
const withoutHeader = parseFinal('Что?;Это')
|
||||
if (!withoutHeader.ok) throw new Error('не разобрался')
|
||||
expect(withoutHeader.final).toEqual({ question: 'Что?', answer: 'Это' })
|
||||
})
|
||||
|
||||
it('требует и вопрос, и ответ', async () => {
|
||||
const { parseFinal } = await import('../src/index')
|
||||
const result = parseFinal('Вопрос;Ответ\nЧто?;')
|
||||
if (result.ok) throw new Error('ожидалась ошибка')
|
||||
expect(result.errors[0]?.message).toMatch(/не указан ответ/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('ошибки автора таблицы', () => {
|
||||
it('ругается номером строки, а не путём в JSON', () => {
|
||||
const text = ['Тема,Стоимость,Вопрос,Ответ', 'Стол,100,Вопрос,', 'Ёлка,100,Вопрос,Ответ'].join(
|
||||
'\n',
|
||||
)
|
||||
const errors = errorsOf(tableToPack(text, OPTIONS))
|
||||
expect(errors).toEqual(['строка 2: не указан ответ'])
|
||||
})
|
||||
|
||||
it('ловит повторяющийся номинал', () => {
|
||||
const text = [
|
||||
'Тема,Стоимость,Вопрос,Ответ',
|
||||
'Стол,100,Первый,Ответ',
|
||||
'Стол,100,Второй,Ответ',
|
||||
].join('\n')
|
||||
expect(errorsOf(tableToPack(text, OPTIONS)).join(' ')).toMatch(/повторяется номинал 100/)
|
||||
})
|
||||
|
||||
it('требует, чтобы у тем раунда было одинаковое число клеток', () => {
|
||||
const text = [
|
||||
'Тема,Стоимость,Вопрос,Ответ',
|
||||
'Стол,100,Вопрос,Ответ',
|
||||
'Ёлка,100,Вопрос,Ответ',
|
||||
'Ёлка,200,Вопрос,Ответ',
|
||||
].join('\n')
|
||||
expect(errorsOf(tableToPack(text, OPTIONS)).join(' ')).toMatch(/разное число клеток/)
|
||||
})
|
||||
|
||||
it('не понимает неизвестный тип клетки', () => {
|
||||
const text = ['Тема,Стоимость,Вопрос,Ответ,Тип', 'Стол,100,Вопрос,Ответ,бонус'].join('\n')
|
||||
expect(errorsOf(tableToPack(text, OPTIONS)).join(' ')).toMatch(/неизвестный тип/)
|
||||
})
|
||||
|
||||
it('не принимает номинал текстом', () => {
|
||||
const text = ['Тема,Стоимость,Вопрос,Ответ', 'Стол,сто,Вопрос,Ответ'].join('\n')
|
||||
expect(errorsOf(tableToPack(text, OPTIONS)).join(' ')).toMatch(/номинал должен быть целым/)
|
||||
})
|
||||
|
||||
it('сообщает, если в заголовке нет обязательных колонок', () => {
|
||||
const text = ['Тема,Вопрос', 'Стол,Вопрос'].join('\n')
|
||||
expect(errorsOf(tableToPack(text, OPTIONS)).join(' ')).toMatch(/нет колонок: Стоимость, Ответ/)
|
||||
})
|
||||
|
||||
it('не падает на пустой таблице', () => {
|
||||
expect(errorsOf(tableToPack('', OPTIONS)).join(' ')).toMatch(/нет ни одной клетки|нет колонок/)
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user