Скачиваемый шаблон таблицы на странице импорта

- examples/template.csv: 2 раунда, все типы клеток, медиа, финал
- эндпоинт /api/import/template отдаёт файл с BOM для Excel
- ссылка ⇩ Скачать пример CSV в разделе загрузки
- тесты: BOM на месте, скачанный шаблон сам проходит импорт
This commit is contained in:
oskarvitalii committed 2026-11-16 15:46:48 +07:00
1 parent 05ef0213ae
commit 1924f5498a
6 files changed
+98 -3

No files matched your search

+25 -1
View File
@@ -7,7 +7,7 @@
*/
import { randomBytes } from 'node:crypto'
import { existsSync, readdirSync } from 'node:fs'
import { existsSync, readFileSync, readdirSync } from 'node:fs'
import path from 'node:path'
import fastifyStatic from '@fastify/static'
import Fastify, { type FastifyInstance } from 'fastify'
@@ -29,6 +29,8 @@ export interface AppOptions {
contentDir?: string
/** Перечитать паки с диска: нужен после импорта, без перезапуска сервера. */
reloadPacks?: () => Pack[]
/** Пример таблицы, который можно скачать со страницы импорта. */
templatePath?: string
tickMs?: number
logger?: boolean
}
@@ -204,6 +206,28 @@ export async function buildApp(options: AppOptions): Promise<BuiltApp> {
}
})
/**
* Пример таблицы для скачивания.
*
* Отдаём с BOM: без него Excel открывает UTF-8 как ANSI и показывает
* кракозябры вместо русского текста. Наш разборщик BOM снимает.
*/
app.get('/api/import/template', async (_request, reply) => {
const file = options.templatePath
if (!file || !existsSync(file)) {
return reply.code(404).send({ ok: false, error: 'шаблон не найден на сервере' })
}
const body = Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), readFileSync(file)])
return reply
.header('Content-Type', 'text/csv; charset=utf-8')
.header(
'Content-Disposition',
`attachment; filename="quiz-template.csv"; filename*=UTF-8''${encodeURIComponent('шаблон-квиза.csv')}`,
)
.send(body)
})
app.post('/api/import', async (request, reply) => {
const query = request.query as { token?: string; dry?: string }
if (query.token !== hostToken) {
+1
View File
@@ -41,6 +41,7 @@ const built = await buildApp({
contentDir,
// Импорт из браузера не должен требовать перезапуска сервера.
reloadPacks: () => loadPacks(contentDir).packs.map((entry) => entry.pack),
templatePath: path.join(repoRoot, 'examples/template.csv'),
})
try {
+35
View File
@@ -9,6 +9,7 @@
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import type { Pack } from '@quiz/shared'
import { buildApp, type BuiltApp } from '../src/app'
@@ -68,6 +69,7 @@ beforeEach(async () => {
hostToken: TOKEN,
contentDir,
reloadPacks: () => loadPacks(contentDir).packs.map((entry) => entry.pack),
templatePath: fileURLToPath(new URL('../../../examples/template.csv', import.meta.url)),
})
await built.app.listen({ port: 0, host: '127.0.0.1' })
const address = built.app.server.address()
@@ -227,6 +229,39 @@ describe('применение пака без перезапуска', () => {
})
})
describe('пример таблицы для скачивания', () => {
it('отдаётся файлом с BOM, чтобы Excel не портил кириллицу', async () => {
const response = await fetch(`${origin}/api/import/template`)
expect(response.status).toBe(200)
expect(response.headers.get('content-type')).toContain('text/csv')
expect(response.headers.get('content-disposition')).toContain('attachment')
const bytes = new Uint8Array(await response.arrayBuffer())
expect([bytes[0], bytes[1], bytes[2]]).toEqual([0xef, 0xbb, 0xbf])
})
it('скачанный пример сам проходит импорт', async () => {
const response = await fetch(`${origin}/api/import/template`)
const bytes = new Uint8Array(await response.arrayBuffer())
const uploaded = await fetch(`${origin}/api/import?token=${TOKEN}&dry=1`, {
method: 'POST',
headers: { 'Content-Type': 'application/octet-stream' },
body: bytes,
})
const data = (await uploaded.json()) as {
ok: boolean
stats: { rounds: number; cells: number }
errors?: Array<{ line: number; message: string }>
}
if (!data.ok) throw new Error(JSON.stringify(data.errors))
expect(data.stats.rounds).toBe(2)
expect(data.stats.cells).toBe(15)
})
})
describe('список для страницы импорта', () => {
it('отдаёт паки с диска, папки медиа и найденные звуки', async () => {
await postCsv(CSV, `token=${TOKEN}`)
+6
View File
@@ -220,7 +220,13 @@ async function send(dry: boolean): Promise<void> {
строками выше заголовка: <code>Название;Новогодний квиз 2027</code>.
</p>
<p class="note">
Не знаете, как заполнять? Скачайте готовый пример: в нём есть название игры,
финальный вопрос, два раунда, все типы клеток и строка с медиа.
</p>
<div class="chips">
<a class="ghost accent" href="/api/import/template" download>⇩ Скачать пример CSV</a>
<button class="ghost" :disabled="!hasFile || busy" @click="send(true)">
Проверить
</button>