Страница импорта и звуковые эффекты из файлов

- метаданные пака (название, id, финал) читаются из самого CSV
- страница /import/<токен>: перетащить таблицу, проверить, сохранить
- пак применяется без перезапуска сервера, если партия не начата
- звуки берутся из content/sfx/, иначе используется синтез
- заголовок таблицы ищется по содержимому, а не по позиции
This commit is contained in:
oskarvitalii committed 2026-11-16 15:19:58 +07:00
1 parent 2f0263e59b
commit ea2d5d905c
21 files changed
+1529 -88

No files matched your search

+16 -19
View File
@@ -15,7 +15,7 @@
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'
import { decodeTable, parseFinal, parsePack, tableToPack } from '../packages/shared/src/index'
const root = fileURLToPath(new URL('../', import.meta.url))
const packsDir = path.join(root, 'content', 'packs')
@@ -88,15 +88,6 @@ function usage(): void {
)
}
/** Русский 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, '')
@@ -122,16 +113,16 @@ if (args.help || !args.input) {
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 берём его из блока метаданных в самой таблице, иначе из имени файла.
const idFromArgs = args.id ?? slug(path.basename(inputPath))
if (args.id && !/^[a-z0-9][a-z0-9-]*$/.test(args.id)) {
fail(`идентификатор «${args.id}» не подходит`, [
'нужны строчные латинские буквы, цифры и дефис',
'задайте его явно: --id=novy-god',
'пример: --id=novy-god',
])
}
const title = args.title ?? id
const decoded = decode(readFileSync(inputPath))
const decoded = decodeTable(readFileSync(inputPath))
console.log(`\nчитаю ${path.relative(root, inputPath)} (${decoded.encoding})`)
@@ -139,14 +130,18 @@ 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)
const parsedFinal = parseFinal(decodeTable(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 } : {}) })
const result = tableToPack(decoded.text, {
id: idFromArgs,
...(args.title ? { title: args.title } : {}),
...(final ? { final } : {}),
})
if (!result.ok) {
fail('в таблице есть ошибки', result.errors.map((error) => `строка ${error.line}: ${error.message}`))
@@ -166,7 +161,9 @@ if (args.check) {
process.exit(0)
}
const outPath = args.out ? path.resolve(args.out) : path.join(packsDir, `${id}.json`)
const outPath = args.out
? path.resolve(args.out)
: path.join(packsDir, `${validated.pack.id}.json`)
writeFileSync(outPath, `${JSON.stringify(validated.pack, null, 2)}\n`, 'utf8')
console.log(`записано: ${path.relative(root, outPath)}`)
+135
View File
@@ -0,0 +1,135 @@
/**
* Проверка страницы импорта в браузере: перетаскивание файла, проверка,
* показ ошибок и сохранение.
*
* Требует запущенного `npm run dev` с известным токеном:
* $env:QUIZ_ROOM='TEST'; $env:QUIZ_HOST_TOKEN='smoke-token'; npm run dev
*
* Запуск: node scripts/smoke-import.mjs
*/
import { mkdirSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import puppeteer from 'puppeteer-core'
const BASE = process.env.QUIZ_URL ?? 'http://127.0.0.1:5173'
const TOKEN = process.env.QUIZ_HOST_TOKEN ?? 'smoke-token'
const OUT = fileURLToPath(new URL('../.screenshots/', import.meta.url))
const ROOT = fileURLToPath(new URL('../', import.meta.url))
const CHROME =
process.env.CHROME_PATH ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe'
mkdirSync(OUT, { recursive: true })
const browser = await puppeteer.launch({
executablePath: CHROME,
headless: 'new',
args: ['--disable-gpu', '--no-first-run', '--no-default-browser-check'],
defaultViewport: { width: 1440, height: 1100 },
})
const problems = []
const page = await browser.newPage()
page.on('pageerror', (error) => problems.push(`pageerror: ${error.message}`))
page.on('console', (message) => {
if (message.type() === 'error') problems.push(`console: ${message.text()}`)
})
async function shot(name) {
await page.screenshot({ path: `${OUT}${name}.png`, fullPage: true })
console.log(` снимок: ${name}.png`)
}
try {
console.log('1. страница импорта')
await page.goto(`${BASE}/import/${TOKEN}`, { waitUntil: 'networkidle0' })
await page.waitForSelector('.drop', { timeout: 15000 })
await shot('20-import-empty')
console.log('2. загрузка таблицы')
const input = await page.$('input[type=file]')
if (!input) throw new Error('нет поля выбора файла')
await input.uploadFile(`${ROOT}examples/questions.csv`)
await page.waitForSelector('.drop.filled', { timeout: 15000 })
console.log('3. проверка без записи')
const [check] = await Promise.all([
page.waitForResponse((response) => response.url().includes('/api/import?')),
page.evaluate(() => {
const button = Array.from(document.querySelectorAll('button')).find(
(node) => node.textContent?.trim() === 'Проверить',
)
button?.click()
}),
])
const checked = await check.json()
console.log(` статус ${check.status()}, клеток ${checked?.stats?.cells}`)
if (!checked?.ok) throw new Error(`проверка не прошла: ${JSON.stringify(checked)}`)
if (checked.written !== false) throw new Error('dry-run записал файл')
await page.waitForSelector('.ok-card', { timeout: 15000 })
const title = await page.$eval('.import-title', (node) => node.textContent?.trim())
console.log(` название из таблицы: ${title}`)
if (title !== 'Новогодний квиз 2027') throw new Error(`не то название: ${title}`)
await shot('21-import-checked')
console.log('4. ошибки в таблице')
// Битый файл создаём на диске, чтобы проверить показ ошибок.
const { writeFileSync } = await import('node:fs')
const broken = `${ROOT}.screenshots/broken.csv`
writeFileSync(broken, 'Тема;Стоимость;Вопрос;Ответ\nСтол;100;Без ответа;\n', 'utf8')
const input2 = await page.$('input[type=file]')
await input2.uploadFile(broken)
await page.waitForSelector('.drop.filled', { timeout: 15000 })
await Promise.all([
page.waitForResponse((response) => response.url().includes('/api/import?')),
page.evaluate(() => {
const button = Array.from(document.querySelectorAll('button')).find(
(node) => node.textContent?.trim() === 'Проверить',
)
button?.click()
}),
])
await page.waitForSelector('.bad-card', { timeout: 15000 })
const errorText = await page.$eval('.error-list', (node) => node.textContent?.replace(/\s+/g, ' '))
console.log(` ошибка: ${errorText?.trim()}`)
if (!errorText?.includes('строка 2')) throw new Error('ошибка без номера строки')
await shot('22-import-errors')
console.log('5. сохранение и применение')
const input3 = await page.$('input[type=file]')
await input3.uploadFile(`${ROOT}examples/questions.csv`)
await page.waitForSelector('.drop.filled', { timeout: 15000 })
const [saved] = await Promise.all([
page.waitForResponse(
(response) => response.url().includes('/api/import?') && !response.url().includes('dry=1'),
),
page.evaluate(() => {
const button = Array.from(document.querySelectorAll('button')).find(
(node) => node.textContent?.trim() === 'Сохранить пак',
)
button?.click()
}),
])
const saveResult = await saved.json()
if (!saveResult?.ok || !saveResult.written) throw new Error('пак не сохранился')
await page.waitForSelector('.ok-card', { timeout: 15000 })
await shot('23-import-saved')
const room = await (await fetch(`${BASE}/api/room`)).json()
console.log(` комната играет пак: ${room.pack}`)
if (room.pack !== 'example') throw new Error(`пак не применился: ${room.pack}`)
if (problems.length > 0) {
console.error('\nОшибки в консоли браузера:')
for (const problem of problems) console.error(` - ${problem}`)
process.exitCode = 1
} else {
console.log('\nOK: импорт работает через интерфейс, ошибки показываются со строками')
}
} finally {
await browser.close()
}