Импорт вопросов из таблицы CSV/Excel

- разбор таблицы: разделитель и кодировка определяются сами
- ошибки с номерами строк вместо путей в JSON
- пути к медиа дописываются, тип угадывается по расширению
- CLI-скрипт с --check и отдельным файлом финала
- пример таблицы в examples/ и тест, что он импортируется
This commit is contained in:
oskarvitalii committed 2026-11-16 14:57:20 +07:00
1 parent 89eeea4855
commit 2f0263e59b
10 files changed
+1011 -8

No files matched your search

+173
View File
@@ -0,0 +1,173 @@
/**
* Сборка пака из таблицы Excel / Google Sheets.
*
* npx tsx scripts/import-pack.ts вопросы.csv --id novy-god --title "Квиз"
* npx tsx scripts/import-pack.ts вопросы.csv --final финал.csv
* npx tsx scripts/import-pack.ts вопросы.csv --check # только проверить
*
* В PowerShell npm съедает «--» вместе с флагами, поэтому там нужен npx tsx.
* В cmd.exe и bash работает и короткая форма: npm run import -- файл.csv
*
* CSV может быть в UTF-8 или Windows-1251 (так сохраняет русский Excel),
* с запятыми, точками с запятой или табуляцией — разделитель определяется сам.
*/
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { parseFinal, parsePack, tableToPack } from '../packages/shared/src/index'
const root = fileURLToPath(new URL('../', import.meta.url))
const packsDir = path.join(root, 'content', 'packs')
interface Args {
input?: string
id?: string
title?: string
final?: string
out?: string
check: boolean
help: boolean
}
function parseArgs(argv: string[]): Args {
const args: Args = { check: false, help: false }
const positional: string[] = []
for (let index = 0; index < argv.length; index += 1) {
const current = argv[index]
if (!current) continue
if (current === '--check') {
args.check = true
continue
}
if (current === '--help' || current === '-h') {
args.help = true
continue
}
if (current.startsWith('--')) {
const [rawName, inline] = current.slice(2).split('=')
const name = rawName as keyof Args
const value = inline ?? argv[index + 1]
if (inline === undefined) index += 1
if (typeof value === 'string') {
if (name === 'id' || name === 'title' || name === 'final' || name === 'out') args[name] = value
}
continue
}
positional.push(current)
}
args.input = positional[0]
return args
}
function usage(): void {
console.log(
[
'',
'Сборка пака из таблицы',
'',
' npx tsx scripts/import-pack.ts <файл.csv> [ключи]',
' npm run import -- <файл.csv> [ключи] (cmd.exe и bash)',
'',
'В PowerShell используйте npx: он съедает «--», и флаги до скрипта не доходят.',
'',
' --id=<идентификатор> латиницей, по умолчанию из имени файла',
' --title="Название" заголовок пака, по умолчанию равен id',
' --final=<файл.csv> финальный вопрос: вопрос, ответ, комментарий',
' --out=<путь> куда положить пак, по умолчанию content/packs/<id>.json',
' --check только проверить таблицу, ничего не писать',
'',
'Колонки: Раунд, Тема, Стоимость, Вопрос, Ответ, Комментарий, Тип, Медиа.',
'Обязательны Тема, Стоимость, Вопрос, Ответ (или Медиа вместо Вопроса).',
'',
].join('\n'),
)
}
/** Русский Excel сохраняет CSV в Windows-1251, а не в UTF-8. */
function decode(buffer: Buffer): { text: string; encoding: string } {
try {
return { text: new TextDecoder('utf-8', { fatal: true }).decode(buffer), encoding: 'utf-8' }
} catch {
return { text: new TextDecoder('windows-1251').decode(buffer), encoding: 'windows-1251' }
}
}
function slug(input: string): string {
return input
.replace(/\.(csv|tsv|txt)$/i, '')
.toLowerCase()
.replace(/[^a-z0-9-]+/g, '-')
.replace(/^-+|-+$/g, '')
}
function fail(message: string, details: string[] = []): never {
console.error(`\n✖ ${message}`)
for (const detail of details) console.error(` ${detail}`)
console.error('')
process.exit(1)
}
const args = parseArgs(process.argv.slice(2))
if (args.help || !args.input) {
usage()
process.exit(args.help ? 0 : 1)
}
const inputPath = path.resolve(args.input)
if (!existsSync(inputPath)) fail(`файл не найден: ${inputPath}`)
const id = args.id ?? slug(path.basename(inputPath)) ?? 'quiz'
if (!/^[a-z0-9][a-z0-9-]*$/.test(id)) {
fail(`идентификатор «${id}» не подходит`, [
'нужны строчные латинские буквы, цифры и дефис',
'задайте его явно: --id=novy-god',
])
}
const title = args.title ?? id
const decoded = decode(readFileSync(inputPath))
console.log(`\nчитаю ${path.relative(root, inputPath)} (${decoded.encoding})`)
let final: { question: string; answer: string; comment?: string } | undefined
if (args.final) {
const finalPath = path.resolve(args.final)
if (!existsSync(finalPath)) fail(`файл финала не найден: ${finalPath}`)
const parsedFinal = parseFinal(decode(readFileSync(finalPath)).text)
if (!parsedFinal.ok) {
fail('финальный вопрос не разобрался', parsedFinal.errors.map((e) => `строка ${e.line}: ${e.message}`))
}
final = parsedFinal.final
}
const result = tableToPack(decoded.text, { id, title, ...(final ? { final } : {}) })
if (!result.ok) {
fail('в таблице есть ошибки', result.errors.map((error) => `строка ${error.line}: ${error.message}`))
}
// Импортёр старается, но последнее слово — за схемой, с которой живёт игра.
const validated = parsePack(result.pack)
if (!validated.ok) {
fail('пак не прошёл схему (это баг импортёра, напишите о нём)', validated.errors)
}
const { stats } = result
console.log(`раундов: ${stats.rounds}, тем: ${stats.themes}, клеток: ${stats.cells}`)
if (args.check) {
console.log('проверка пройдена, файл не записан (--check)\n')
process.exit(0)
}
const outPath = args.out ? path.resolve(args.out) : path.join(packsDir, `${id}.json`)
writeFileSync(outPath, `${JSON.stringify(validated.pack, null, 2)}\n`, 'utf8')
console.log(`записано: ${path.relative(root, outPath)}`)
console.log('сервер подхватит пак при следующем запуске\n')