Files
Scoreboard/web/src/admin/tests/basedata-import-api.test.ts
T
AskaEth 6841cf49aa fix(p2): 按审查清单修 103 条「建议修」+ 奖牌榜改名 + 两个守卫(dev_0.2.0)
## 奖牌榜改名(主人要求)
「团体奖牌榜」→「单位奖牌榜」,界面 / 大屏渲染页 / 导出件(工作表名与
下载文件名 `单位奖牌明细.xlsx`)/ 用户文档 全部统一;`DISPLAY_PAGES` 是
大屏控制页与大屏页的共同来源,改一处两边同时生效。旧名保留为别名,
老链接与老配置(`display.pages`)照常有效。真 Chromium 验证:14 个管理端
路由 + 7 个基础数据分区 0 报错,大屏页标题已是「单位奖牌榜」。

## P2 清单(123 条,103 条标「建议修」)
按 A/B/C/D 分组、以「文件所有权互斥」分 10 个代理并行推进,另有独立复核
代理逐条核对:61 条声称已修 / 55 条证实 / 4 条部分 / 0 条不成立 / 0 垃圾。

主要交付(按风险从高到低):
- 写入侧校验:update 路径补必填与 TrimSpace、模板 rules 重复 rank、
  「小项不存在」的四种回答、`defaultProfileId` 外键、decodeJSON 的 8MB
  上限与 413(A01–A06、D02、D03 批量上限 500)
- 危险操作:一键恢复加互斥(第二个请求当场 409)、恢复超时不再说
  「未执行」、`ConfirmDialog` pending 时锁死 ESC/遮罩/关闭
- 认证:改密与撤会话进同一事务、滑动续期写库失败不再假装成功、
  CSRF Cookie 丢失自动补发、密码长度按字符(原按字节)、
  反代 403 只在可信代理透传原 Host 时采信 `X-Forwarded-Host`(全等比较)、
  过期会话定期清理、登出补审计、登录限流可配
- 数据可见性:导出「已发布未结算」行改为 `名次 — / 积分 — / 状态未结算`、
  单位积分明细成绩列与其它导出件逐字一致、空单位也打合计行、
  基础数据包命中「已彻底删除的单位」整行跳过并报界面路径、
  报名导入换单位给明确提示、勾选报名有冲突不再假报成功
- 导入/导出:赛事包上限 512MB(**它是唯一带字体/图片的包**,字体上限
  20MB)而 multipart 内存档位独立钉在 16MB、工作簿表名尾随空格、
  导出件路由与文件名契约补全
- 前端:一次写请求只生成一个 requestId(幂等缓存此前从未命中)、
  基础数据包补 `X-Request-Id`、示例数据模式禁写扩到撤销发布/存草稿、
  访客 401 不再是裸错误、模板 `{{else if}}` 不再静默吞内容
- Console:按设计退出(切赛事/恢复)不再判成崩溃、旧数据目录读不出来
  会记日志、渲染层日志按上限截断、`service.js` 补 17 例测试

## 测试
服务端用例 610 → 674(13 包全绿,新增老库跨九条迁移升级、panic 形状、
429 落 interceptions、三态对照、avg_mode 分母、会话失效、请求体上限等)
前端 449 → 531(vue-tsc + build 通过);Console 28 → 54(19 个文件)。
另修复一条会让整包挂死 600s 的用例(测试主协程堵在 client.Do,defer
轮不到执行 → 改为可取消 + 探针超时,改坏也 7.5s 快速失败)。

## 两个新守卫(防止再出现「组件 setup 抛异常」这类盲区)
- `web/scripts/check-declaration-order.mjs` 已进测试命令:沿 watch/
  watchEffect 的 const 依赖链查 TDZ(正是「运动员页整块空白」的根因)
- `web/scripts/smoke-admin.mjs`(`pnpm smoke`):真 Chromium 点遍 14 个
  管理端路由 + 7 个基础数据分区 + 大屏页,任何 console 错误即失败

## 文档
- `docs/升级说明.md` 新增 dev_0.2.0 一节(三件升级必知:改名、审计前缀
  与历史记录、密码口径;现场变化;赛事包上限;反代与 CSRF)
- 使用手册 / 常见问题 / 部署指南 / 上线检查清单按实现同步
2026-09-11 23:46:59 +08:00

241 lines
7.9 KiB
TypeScript

import { test } from 'node:test'
import assert from 'node:assert/strict'
import { ApiError } from '@/shared'
import {
downloadBaseDataXLSX,
downloadEntriesXLSX,
entriesExportPath,
importBaseDataXLSX,
} from '@/shared/basedata'
/**
* 报名名单导出与基础数据包导入的前端契约:路径、筛选参数、dryRun 标志、解析出的差异。
*
* 路径或参数写错时现场拿到的是 404 或「筛了却导出全量」;dryRun 标志丢了则会
* 让「预览差异」直接写库。这里用 stub fetch 钉住真正发出去的请求。
*/
interface Captured {
url?: string
method?: string
body?: unknown
headers?: Record<string, string>
}
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
})
}
function xlsxResponse(): Response {
return new Response(new Blob([new Uint8Array([0x50, 0x4b, 0x03, 0x04])]), {
status: 200,
headers: { 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' },
})
}
let reply: () => Response = () => xlsxResponse()
let lastRequest: Captured = {}
globalThis.fetch = (async (input: unknown, init?: RequestInit) => {
lastRequest = {
url: String(input),
method: init?.method ?? 'GET',
body: init?.body,
headers: (init?.headers ?? {}) as Record<string, string>,
}
return reply()
}) as typeof fetch
function respondWith(next: () => Response): void {
lastRequest = {}
reply = next
}
function formValue(body: unknown, key: string): FormDataEntryValue | null {
assert.ok(body instanceof FormData, '上传必须是 multipart FormData')
return body.get(key)
}
test('报名名单导出路径按筛选条件拼 query,留空的维度不出现', () => {
assert.equal(entriesExportPath(), '/export/entries.xlsx')
assert.equal(entriesExportPath({ eventId: 3 }), '/export/entries.xlsx?eventId=3')
assert.equal(
entriesExportPath({ eventId: 3, categoryId: 9, teamId: 1, heat: 2 }),
'/export/entries.xlsx?eventId=3&categoryId=9&teamId=1&heat=2',
)
})
test('导出报名名单走 GET /api/export/entries.xlsx,文件名是「报名名单.xlsx」', async () => {
respondWith(() => xlsxResponse())
const result = await downloadEntriesXLSX({ eventId: 3, heat: 2 })
assert.equal(lastRequest.url, '/api/export/entries.xlsx?eventId=3&heat=2')
assert.equal(lastRequest.method, 'GET')
assert.equal(result.filename, '报名名单.xlsx')
assert.equal(result.blob.size, 4)
})
test('导出基础数据包走 GET /api/export/basedata.xlsx,文件名是「基础数据包.xlsx」', async () => {
respondWith(() => xlsxResponse())
const result = await downloadBaseDataXLSX()
assert.equal(lastRequest.url, '/api/export/basedata.xlsx')
assert.equal(result.filename, '基础数据包.xlsx')
})
test('预览差异带 dryRun=1,结果里的三类计数与逐行差异都解析出来', async () => {
respondWith(() => jsonResponse({
ok: true,
data: {
dryRun: true,
added: 1,
updated: 2,
unchanged: 5,
errorCount: 1,
errors: ['单位 第 3 行:单位编码必填'],
changes: [
{
sheet: '单位',
line: 2,
action: 'updated',
key: 'T1',
fields: [{ field: '单位名称', from: '第一分公司', to: '第一分公司(改)' }],
},
],
},
}))
const file = new File(['x'], 'basedata.xlsx')
const result = await importBaseDataXLSX(file, { dryRun: true })
assert.equal(lastRequest.url, '/api/export/basedata/import')
assert.equal(lastRequest.method, 'POST')
assert.equal(formValue(lastRequest.body, 'dryRun'), '1')
assert.equal(formValue(lastRequest.body, 'file'), file)
assert.equal(result.dryRun, true)
assert.equal(result.added, 1)
assert.equal(result.updated, 2)
assert.equal(result.unchanged, 5)
assert.equal(result.errorCount, 1)
assert.deepEqual(result.errors, ['单位 第 3 行:单位编码必填'])
assert.equal(result.changes.length, 1)
assert.equal(result.changes[0].sheet, '单位')
assert.equal(result.changes[0].line, 2)
assert.equal(result.changes[0].fields[0].field, '单位名称')
assert.equal(result.changes[0].fields[0].from, '第一分公司')
assert.equal(result.changes[0].fields[0].to, '第一分公司(改)')
})
test('确认写入不带 dryRun,避免预览之后又走一次只读分支', async () => {
respondWith(() => jsonResponse({
ok: true,
data: { dryRun: false, added: 3, updated: 0, unchanged: 0, errorCount: 0, errors: [], changes: [] },
}))
const result = await importBaseDataXLSX(new File(['x'], 'basedata.xlsx'), { dryRun: false })
assert.equal(formValue(lastRequest.body, 'dryRun'), null)
assert.equal(result.dryRun, false)
assert.equal(result.added, 3)
})
// 基础数据包导入是唯一一条不带 JSON 体的写请求(multipart),但服务端对这条路由
// 挂了基于 X-Request-Id 的幂等缓存:不带这个 header,cached 层直接放行,
// 现场超时重发就会把整包数据(单位 / 大项 / 小项 / 组别)再写一遍。
test('导入基础数据包带 X-Request-Id(服务端按它做幂等与审计)', async () => {
respondWith(() => jsonResponse({
ok: true,
data: { dryRun: false, added: 0, updated: 0, unchanged: 0, errorCount: 0, errors: [], changes: [] },
}))
await importBaseDataXLSX(new File(['x'], 'basedata.xlsx'))
assert.equal(typeof lastRequest.headers?.['X-Request-Id'], 'string')
assert.notEqual(lastRequest.headers?.['X-Request-Id'], '')
})
test('两次导入各自生成一个幂等键(不会复用上一次的)', async () => {
respondWith(() => jsonResponse({
ok: true,
data: { dryRun: true, added: 0, updated: 0, unchanged: 0, errorCount: 0, errors: [], changes: [] },
}))
const file = new File(['x'], 'basedata.xlsx')
await importBaseDataXLSX(file, { dryRun: true })
const first = lastRequest.headers?.['X-Request-Id']
await importBaseDataXLSX(file, { dryRun: true })
const second = lastRequest.headers?.['X-Request-Id']
assert.equal(typeof first, 'string')
assert.equal(typeof second, 'string')
assert.notEqual(first, second)
})
test('服务端 400 的行级错误原样抛出,页面能拿到那句中文', async () => {
respondWith(() => jsonResponse({
ok: false,
error: { code: 'VALIDATION_FAILED', message: '导出链接参数不对' },
}, 400))
await assert.rejects(
() => downloadEntriesXLSX({ heat: 0 }),
(error: unknown) => {
assert.ok(error instanceof ApiError)
assert.equal(error.status, 400)
assert.equal(error.code, 'VALIDATION_FAILED')
assert.equal(error.message, '导出链接参数不对')
return true
},
)
})
test('导入 403 / 500 原样抛出,不降级成示例数据', async () => {
respondWith(() => jsonResponse({
ok: false,
error: { code: 'FORBIDDEN', message: '只有管理员可以导入基础数据' },
}, 403))
await assert.rejects(
() => importBaseDataXLSX(new File(['x'], 'basedata.xlsx')),
(error: unknown) => {
assert.ok(error instanceof ApiError)
assert.equal(error.code, 'FORBIDDEN')
assert.equal(error.message, '只有管理员可以导入基础数据')
return true
},
)
})
test('响应不是 {ok,data} 结构时报解析错误,而不是假装导入成功', async () => {
respondWith(() => jsonResponse({ hello: 'world' }))
await assert.rejects(
() => importBaseDataXLSX(new File(['x'], 'basedata.xlsx')),
(error: unknown) => {
assert.ok(error instanceof ApiError)
assert.equal(error.code, 'INTERNAL')
return true
},
)
})
test('连不上服务端时报 NETWORK,页面据此区分「后端未就绪」', async () => {
respondWith(() => {
throw new TypeError('fetch failed')
})
await assert.rejects(
() => downloadEntriesXLSX(),
(error: unknown) => {
assert.ok(error instanceof ApiError)
assert.equal(error.code, 'NETWORK')
return true
},
)
})