Files
oskarvitalii ea2d5d905c Страница импорта и звуковые эффекты из файлов
- метаданные пака (название, id, финал) читаются из самого CSV
- страница /import/<токен>: перетащить таблицу, проверить, сохранить
- пак применяется без перезапуска сервера, если партия не начата
- звуки берутся из content/sfx/, иначе используется синтез
- заголовок таблицы ищется по содержимому, а не по позиции
2026-11-16 15:19:58 +07:00

136 lines
5.7 KiB
JavaScript

/**
* Проверка страницы импорта в браузере: перетаскивание файла, проверка,
* показ ошибок и сохранение.
*
* Требует запущенного `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()
}